text
stringlengths 9
39.2M
| dir
stringlengths 26
295
| lang
stringclasses 185
values | created_date
timestamp[us] | updated_date
timestamp[us] | repo_name
stringlengths 1
97
| repo_full_name
stringlengths 7
106
| star
int64 1k
183k
| len_tokens
int64 1
13.8M
|
|---|---|---|---|---|---|---|---|---|
```c++
/*
LodePNG Utils
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_util.h"
#include <iostream>
namespace lodepng
{
LodePNGInfo getPNGHeaderInfo(const std::vector<unsigned char>& png)
{
unsigned w, h;
lodepng::State state;
lodepng_inspect(&w, &h, &state, &png[0], png.size());
return state.info_png;
}
unsigned getChunkInfo(std::vector<std::string>& names, std::vector<size_t>& sizes,
const std::vector<unsigned char>& 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)
{
char type[5];
lodepng_chunk_type(type, chunk);
if(std::string(type).size() != 4) return 1;
unsigned length = lodepng_chunk_length(chunk);
if(chunk + length + 12 > end) return 1;
names.push_back(type);
sizes.push_back(length);
next = lodepng_chunk_next_const(chunk);
if (next <= chunk) return 1; // integer overflow
chunk = next;
}
return 0;
}
unsigned getChunks(std::vector<std::string> names[3],
std::vector<std::vector<unsigned char> > chunks[3],
const std::vector<unsigned char>& 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)
{
char type[5];
lodepng_chunk_type(type, chunk);
std::string name(type);
if(name.size() != 4) return 1;
next = lodepng_chunk_next_const(chunk);
if (next <= chunk) return 1; // integer overflow
if(name == "IHDR")
{
location = 0;
}
else if(name == "PLTE")
{
location = 1;
}
else if(name == "IDAT")
{
location = 2;
}
else if(name == "IEND")
{
break; // anything after IEND is not part of the PNG or the 3 groups here.
}
else
{
if(next > end) return 1; // invalid chunk, content too far
names[location].push_back(name);
chunks[location].push_back(std::vector<unsigned char>(chunk, next));
}
chunk = next;
}
return 0;
}
unsigned insertChunks(std::vector<unsigned char>& png,
const std::vector<std::vector<unsigned char> > chunks[3])
{
const unsigned char *chunk, *next, *begin, *end;
end = &png.back() + 1;
begin = chunk = &png.front() + 8;
long l0 = 0; //location 0: IHDR-l0-PLTE (or IHDR-l0-l1-IDAT)
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)
{
char type[5];
lodepng_chunk_type(type, chunk);
std::string name(type);
if(name.size() != 4) return 1;
next = lodepng_chunk_next_const(chunk);
if (next <= chunk) return 1; // integer overflow
if(name == "PLTE")
{
if(l0 == 0) l0 = chunk - begin + 8;
}
else if(name == "IDAT")
{
if(l0 == 0) l0 = chunk - begin + 8;
if(l1 == 0) l1 = chunk - begin + 8;
}
else if(name == "IEND")
{
if(l2 == 0) l2 = chunk - begin + 8;
}
chunk = next;
}
std::vector<unsigned char> result;
result.insert(result.end(), png.begin(), png.begin() + l0);
for(size_t i = 0; i < chunks[0].size(); i++) result.insert(result.end(), chunks[0][i].begin(), chunks[0][i].end());
result.insert(result.end(), png.begin() + l0, png.begin() + l1);
for(size_t i = 0; i < chunks[1].size(); i++) result.insert(result.end(), chunks[1][i].begin(), chunks[1][i].end());
result.insert(result.end(), png.begin() + l1, png.begin() + l2);
for(size_t i = 0; i < chunks[2].size(); i++) result.insert(result.end(), chunks[2][i].begin(), chunks[2][i].end());
result.insert(result.end(), png.begin() + l2, png.end());
png = result;
return 0;
}
unsigned getFilterTypesInterlaced(std::vector<std::vector<unsigned char> >& filterTypes,
const std::vector<unsigned char>& png)
{
//Get color type and interlace type
lodepng::State state;
unsigned w, h;
unsigned error;
error = lodepng_inspect(&w, &h, &state, &png[0], png.size());
if(error) return 1;
//Read literal data from all IDAT chunks
const unsigned char *chunk, *begin, *end, *next;
end = &png.back() + 1;
begin = chunk = &png.front() + 8;
std::vector<unsigned char> zdata;
while(chunk + 8 < end && chunk >= begin)
{
char type[5];
lodepng_chunk_type(type, chunk);
if(std::string(type).size() != 4) return 1; //Probably not a PNG file
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) {
// corrupt chunk length
return 1;
}
for(unsigned i = 0; i < clength; i++)
{
zdata.push_back(cdata[i]);
}
}
next = lodepng_chunk_next_const(chunk);
if (next <= chunk) return 1; // integer overflow
chunk = next;
}
//Decompress all IDAT data
std::vector<unsigned char> data;
error = lodepng::decompress(data, &zdata[0], zdata.size());
if(error) return 1;
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)
{
filterTypes[0].push_back(data[i]);
}
}
else
{
//Interlaced
filterTypes.resize(7);
static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
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++)
{
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++)
{
filterTypes[j].push_back(data[pos]);
pos += linebytes;
}
}
}
return 0; /* OK */
}
unsigned getFilterTypes(std::vector<unsigned char>& filterTypes, const std::vector<unsigned char>& png)
{
std::vector<std::vector<unsigned char> > passes;
unsigned error = getFilterTypesInterlaced(passes, png);
if(error) return error;
if(passes.size() == 1)
{
filterTypes.swap(passes[0]);
}
else
{
lodepng::State state;
unsigned w, h;
lodepng_inspect(&w, &h, &state, &png[0], png.size());
/*
Interlaced. Simplify it: put pass 6 and 7 alternating in the one vector so
that one filter per scanline of the uninterlaced image is given, with that
filter corresponding the closest to what it would be for non-interlaced
image.
*/
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)
{
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;
else if(bits == 1) return (data[i / 8] >> (i % 8)) & 1;
else return 0;
}
//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
{
std::vector<ZlibBlockInfo>* zlibinfo;
ExtractZlib(std::vector<ZlibBlockInfo>* info) : zlibinfo(info) {};
int error;
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 result = 0;
for(size_t i = 0; i < nbits; i++) result += (readBitFromStream(bitp, bits)) << i;
return result;
}
struct HuffmanTree
{
int makeFromLengths(const std::vector<unsigned long>& bitlen, unsigned long maxbitlen)
{ //make tree given the lengths
unsigned long numcodes = (unsigned long)(bitlen.size()), treepos = 0, nodefilled = 0;
std::vector<unsigned long> 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++)
{
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
{
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])
{
//last bit
tree2d[2 * treepos + bit] = n;
treepos = 0;
}
else
{
//addresses are encoded as values > numcodes
tree2d[2 * treepos + bit] = ++nodefilled + numcodes;
treepos = nodefilled;
}
}
else treepos = tree2d[2 * treepos + bit] - numcodes; //subtract numcodes from address to get address value
}
return 0;
}
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];
decoded = (result < numcodes);
treepos = decoded ? 0 : result - numcodes;
return 0;
}
//2D representation of a huffman tree: one dimension is "0" or "1", the other contains all nodes and leaves.
std::vector<unsigned long> tree2d;
};
void inflate(std::vector<unsigned char>& out, const std::vector<unsigned char>& 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)
{
size_t uncomprblockstart = pos;
size_t bpstart = bp;
if(bp >> 3 >= in.size()) { error = 52; return; } //error, bit pointer will jump past memory
BFINAL = readBitFromStream(bp, &in[inpos]);
unsigned long BTYPE = readBitFromStream(bp, &in[inpos]); BTYPE += 2 * readBitFromStream(bp, &in[inpos]);
zlibinfo->resize(zlibinfo->size() + 1);
zlibinfo->back().btype = BTYPE;
if(BTYPE == 3) { error = 20; return; } //error: invalid BTYPE
else if(BTYPE == 0) inflateNoCompression(out, &in[inpos], bp, pos, in.size());
else inflateHuffmanBlock(out, &in[inpos], bp, pos, in.size(), BTYPE);
size_t uncomprblocksize = pos - uncomprblockstart;
zlibinfo->back().compressedbits = bp - bpstart;
zlibinfo->back().uncompressedbytes = uncomprblocksize;
}
}
void generateFixedTrees(HuffmanTree& tree, HuffmanTree& treeD) //get the tree of a deflated block with fixed tree
{
std::vector<unsigned long> 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;
tree.makeFromLengths(bitlen, 15);
treeD.makeFromLengths(bitlenD, 15);
}
//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)
{
//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;;)
{
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
if(decoded) return ct;
}
}
void getTreeInflateDynamic(HuffmanTree& tree, HuffmanTree& treeD,
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<unsigned long> bitlen(288, 0), bitlenD(32, 0);
if(bp >> 3 >= inlength - 2) { error = 49; return; } //the bit pointer is or will go past the memory
size_t HLIT = readBitsFromStream(bp, in, 5) + 257; //number of literal/length codes + 257
size_t HDIST = readBitsFromStream(bp, in, 5) + 1; //number of dist codes + 1
size_t HCLEN = readBitsFromStream(bp, in, 4) + 4; //number of code length codes + 4
zlibinfo->back().hlit = HLIT - 257;
zlibinfo->back().hdist = HDIST - 1;
zlibinfo->back().hclen = HCLEN - 4;
std::vector<unsigned long> codelengthcode(19); //lengths of tree to decode the lengths of the dynamic tree
for(size_t i = 0; i < 19; i++) codelengthcode[CLCL[i]] = (i < HCLEN) ? readBitsFromStream(bp, in, 3) : 0;
//code length code lengths
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)
{
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
{
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
{
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
{
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
{
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
{
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
{
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;
}
}
else { error = 16; return; } //error: somehow an unexisting code appeared. This can never happen.
}
if(bitlen[256] == 0) { error = 64; return; } //the length of the end code 256 must be larger than 0
error = tree.makeFromLengths(bitlen, 15);
if(error) return; //now we've finally got HLIT and HDIST, so generate the code trees, and the function is done
error = treeD.makeFromLengths(bitlenD, 15);
if(error) return;
zlibinfo->back().treebits = bp - bpstart;
//lit/len/end symbol lengths
for(size_t j = 0; j < bitlen.size(); j++) zlibinfo->back().litlenlengths.push_back(bitlen[j]);
//dist lengths
for(size_t j = 0; j < bitlenD.size(); j++) zlibinfo->back().distlengths.push_back(bitlenD[j]);
}
void inflateHuffmanBlock(std::vector<unsigned char>& out,
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(;;)
{
unsigned long code = huffmanDecodeSymbol(in, bp, codetree, inlength); if(error) return;
numcodes++;
zlibinfo->back().lz77_lcode.push_back(code); //output code
zlibinfo->back().lz77_dcode.push_back(0);
zlibinfo->back().lz77_lbits.push_back(0);
zlibinfo->back().lz77_dbits.push_back(0);
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
{
out.push_back((unsigned char)(code));
pos++;
numlit++;
}
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);
unsigned long codeD = huffmanDecodeSymbol(in, bp, codetreeD, inlength); if(error) return;
if(codeD > 29) { error = 18; return; } //error: invalid dist code (30-31 are never used)
unsigned long dist = DISTBASE[codeD], numextrabitsD = DISTEXTRA[codeD];
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++)
{
out.push_back(out[back++]);
pos++;
if(back >= start) back = start - dist;
}
numlen++;
zlibinfo->back().lz77_dcode.back() = codeD; //output distance code
zlibinfo->back().lz77_lbits.back() = numextrabits; //output length extra bits
zlibinfo->back().lz77_dbits.back() = numextrabitsD; //output dist extra bits
zlibinfo->back().lz77_lvalue.back() = length; //output length
zlibinfo->back().lz77_dvalue.back() = dist; //output dist
}
}
zlibinfo->back().numlit = numlit; //output number of literal symbols
zlibinfo->back().numlen = numlen; //output number of length symbols
}
void inflateNoCompression(std::vector<unsigned char>& out,
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++)
{
out.push_back(in[p++]); //read LEN bytes of literal data
pos++;
}
bp = p * 8;
}
int decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& 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; }
unsigned long CM = in[0] & 15, CINFO = (in[0] >> 4) & 15, FDICT = (in[1] >> 5) & 1;
//error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec
if(CM != 8 || CINFO > 7) { return 25; }
//error: the PNG spec says about the zlib stream: "The additional flags shall not specify a preset dictionary."
if(FDICT != 0) { return 26; }
inflate(out, in, 2);
return error; //note: adler32 checksum was skipped and ignored
}
};
struct ExtractPNG //PNG decoding and information extraction
{
std::vector<ZlibBlockInfo>* zlibinfo;
ExtractPNG(std::vector<ZlibBlockInfo>* info) : zlibinfo(info) {};
int error;
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;
size_t pos = 33; //first byte of the first chunk after the header
std::vector<unsigned char> idat; //the data from idat chunks
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)
{
//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;
if(chunkLength > 2147483647) { error = 63; return; }
//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')
{
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')
{
pos += 4;
IEND = true;
}
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)
}
std::vector<unsigned char> out; //now the out buffer will be filled
ExtractZlib zlib(zlibinfo); //decompress with the Zlib decompressor
error = zlib.decompress(out, idat);
if(error) return; //stop if the zlib decompressor returned an error
}
//read the information from the header and store it in the Info
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
//error: it doesn't start with a IHDR chunk!
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 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 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)
{
bits[bitp >> 3] |= (bit << (7 - (bitp & 0x7))); bitp++;
}
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<ZlibBlockInfo>& zlibinfo, const std::vector<unsigned char>& in)
{
ExtractPNG decoder(&zlibinfo);
decoder.decode(&in[0], in.size());
if(decoder.error) std::cout << "extract error: " << decoder.error << std::endl;
}
} // namespace lodepng
```
|
/content/code_sandbox/library/JQLibrary/src/JQZopfli/zopflipng/lodepng/lodepng_util.cpp
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 8,306
|
```c++
#include "JQGuetzli.h"
// Qt lib import
#include <QDebug>
#include <QFileInfo>
#include <QTime>
#include <QElapsedTimer>
// guetzli lib import
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <memory>
#include <string>
#include <string.h>
#include "gflags/gflags.h"
#include "png/png.h"
#include "guetzli/processor.h"
#include "guetzli/quality.h"
#include "guetzli/stats.h"
// Workaround for differences between versions of gflags.
namespace gflags {
}
using namespace gflags;
namespace google {
}
using namespace google;
DEFINE_bool(verbose, false,
"Print a verbose trace of all attempts to standard output.");
DEFINE_double(quality, 95,
"Visual quality to aim for, expressed as a JPEG quality value.");
inline uint8_t JQGuetzli_BlendOnBlack(const uint8_t val, const uint8_t alpha) {
return (static_cast<int>(val) * static_cast<int>(alpha) + 128) / 255;
}
bool JQGuetzli_ReadPNG(FILE* f, int* xsize, int* ysize,
std::vector<uint8_t>* rgb) {
png_structp png_ptr =
png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!png_ptr) {
return false;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, nullptr, nullptr);
return false;
}
if (setjmp(png_jmpbuf(png_ptr)) != 0) {
// Ok we are here because of the setjmp.
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return false;
}
rewind(f);
png_init_io(png_ptr, f);
// The png_transforms flags are as follows:
// packing == convert 1,2,4 bit images,
// strip == 16 -> 8 bits / channel,
// shift == use sBIT dynamics, and
// expand == palettes -> rgb, grayscale -> 8 bit images, tRNS -> alpha.
const unsigned int png_transforms =
PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_STRIP_16;
png_read_png(png_ptr, info_ptr, png_transforms, nullptr);
png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);
*xsize = png_get_image_width(png_ptr, info_ptr);
*ysize = png_get_image_height(png_ptr, info_ptr);
rgb->resize(3 * (*xsize) * (*ysize));
const int components = png_get_channels(png_ptr, info_ptr);
switch (components) {
case 1: {
// GRAYSCALE
for (int y = 0; y < *ysize; ++y) {
const uint8_t* row_in = row_pointers[y];
uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];
for (int x = 0; x < *xsize; ++x) {
const uint8_t gray = row_in[x];
row_out[3 * x + 0] = gray;
row_out[3 * x + 1] = gray;
row_out[3 * x + 2] = gray;
}
}
break;
}
case 2: {
// GRAYSCALE + ALPHA
for (int y = 0; y < *ysize; ++y) {
const uint8_t* row_in = row_pointers[y];
uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];
for (int x = 0; x < *xsize; ++x) {
const uint8_t gray = JQGuetzli_BlendOnBlack(row_in[2 * x], row_in[2 * x + 1]);
row_out[3 * x + 0] = gray;
row_out[3 * x + 1] = gray;
row_out[3 * x + 2] = gray;
}
}
break;
}
case 3: {
// RGB
for (int y = 0; y < *ysize; ++y) {
const uint8_t* row_in = row_pointers[y];
uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];
memcpy(row_out, row_in, 3 * (*xsize));
}
break;
}
case 4: {
// RGBA
for (int y = 0; y < *ysize; ++y) {
const uint8_t* row_in = row_pointers[y];
uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];
for (int x = 0; x < *xsize; ++x) {
const uint8_t alpha = row_in[4 * x + 3];
row_out[3 * x + 0] = JQGuetzli_BlendOnBlack(row_in[4 * x + 0], alpha);
row_out[3 * x + 1] = JQGuetzli_BlendOnBlack(row_in[4 * x + 1], alpha);
row_out[3 * x + 2] = JQGuetzli_BlendOnBlack(row_in[4 * x + 2], alpha);
}
}
break;
}
default:
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return false;
}
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return true;
}
std::string JQGuetzli_ReadFile(FILE* f) {
if (fseek(f, 0, SEEK_END) != 0) {
perror("fseek");
return { };
}
off_t size = ftell(f);
if (size < 0) {
perror("ftell");
return { };
}
if (fseek(f, 0, SEEK_SET) != 0) {
perror("fseek");
return { };
}
std::unique_ptr<char[]> buf(new char[size]);
if (fread(buf.get(), 1, size, f) != (size_t)size) {
perror("fread");
return { };
}
std::string result(buf.get(), size);
return result;
}
bool JQGuetzli_WriteFile(FILE* f, const std::string& contents) {
if (fwrite(contents.data(), 1, contents.size(), f) != contents.size()) {
perror("fwrite");
return false;
}
if (fclose(f) < 0) {
perror("fclose");
return false;
}
return true;
}
JQGuetzli::ProcessResult JQGuetzli::process(const QString &inputImageFilePath, const QString &outputImageFilePath)
{
QElapsedTimer timer;
timer.start();
ProcessResult result;
result.originalSize = QFileInfo( inputImageFilePath ).size();
FILE* fin = fopen(inputImageFilePath.toLocal8Bit().data(), "rb");
if (!fin) {
fprintf(stderr, "Can't open input file\n");
return result;
}
std::string in_data = JQGuetzli_ReadFile(fin);
std::string out_data;
if ( in_data.empty() )
{
return result;
}
guetzli::Params params;
params.butteraugli_target =
guetzli::ButteraugliScoreForQuality(FLAGS_quality);
guetzli::ProcessStats stats;
if (FLAGS_verbose) {
stats.debug_output_file = stdout;
}
static const unsigned char kPNGMagicBytes[] = {
0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n',
};
if (in_data.size() >= 8 &&
memcmp(in_data.data(), kPNGMagicBytes, sizeof(kPNGMagicBytes)) == 0) {
int xsize, ysize;
std::vector<uint8_t> rgb;
if (!JQGuetzli_ReadPNG(fin, &xsize, &ysize, &rgb)) {
fprintf(stderr, "Error reading PNG data from input file\n");
return result;
}
if (!guetzli::Process(params, &stats, rgb, xsize, ysize, &out_data)) {
fprintf(stderr, "Guetzli processing failed\n");
return result;
}
} else {
if (!guetzli::Process(params, &stats, in_data, &out_data)) {
fprintf(stderr, "Guetzli processing failed\n");
return result;
}
}
fclose(fin);
FILE* fout = fopen(outputImageFilePath.toLocal8Bit().data(), "wb");
if (!fout) {
fprintf(stderr, "Can't open output file for writing\n");
return result;
}
if ( !JQGuetzli_WriteFile(fout, out_data) )
{
return result;
}
result.processSucceed = true;
result.resultSize = QFileInfo( outputImageFilePath ).size();
result.compressionRatio = (double)result.resultSize / (double)result.originalSize;
result.timeConsuming = timer.elapsed();
return result;
}
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/JQGuetzli.cpp
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 2,060
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/jpeg_data.h"
#include <assert.h>
#include <string.h>
namespace guetzli {
bool JPEGData::Is420() const {
return (components.size() == 3 &&
max_h_samp_factor == 2 &&
max_v_samp_factor == 2 &&
components[0].h_samp_factor == 2 &&
components[0].v_samp_factor == 2 &&
components[1].h_samp_factor == 1 &&
components[1].v_samp_factor == 1 &&
components[2].h_samp_factor == 1 &&
components[2].v_samp_factor == 1);
}
bool JPEGData::Is444() const {
return (components.size() == 3 &&
max_h_samp_factor == 1 &&
max_v_samp_factor == 1 &&
components[0].h_samp_factor == 1 &&
components[0].v_samp_factor == 1 &&
components[1].h_samp_factor == 1 &&
components[1].v_samp_factor == 1 &&
components[2].h_samp_factor == 1 &&
components[2].v_samp_factor == 1);
}
void InitJPEGDataForYUV444(int w, int h, JPEGData* jpg) {
jpg->width = w;
jpg->height = h;
jpg->max_h_samp_factor = 1;
jpg->max_v_samp_factor = 1;
jpg->MCU_rows = (h + 7) >> 3;
jpg->MCU_cols = (w + 7) >> 3;
jpg->quant.resize(3);
jpg->components.resize(3);
for (int i = 0; i < 3; ++i) {
JPEGComponent* c = &jpg->components[i];
c->id = i;
c->h_samp_factor = 1;
c->v_samp_factor = 1;
c->quant_idx = i;
c->width_in_blocks = jpg->MCU_cols;
c->height_in_blocks = jpg->MCU_rows;
c->num_blocks = c->width_in_blocks * c->height_in_blocks;
c->coeffs.resize(c->num_blocks * kDCTBlockSize);
}
}
void SaveQuantTables(const int q[3][kDCTBlockSize], JPEGData* jpg) {
const size_t kTableSize = kDCTBlockSize * sizeof(q[0][0]);
jpg->quant.clear();
int num_tables = 0;
for (int i = 0; i < (int)jpg->components.size(); ++i) {
JPEGComponent* comp = &jpg->components[i];
// Check if we have this quant table already.
bool found = false;
for (int j = 0; j < num_tables; ++j) {
if (memcmp(&q[i][0], &jpg->quant[j].values[0], kTableSize) == 0) {
comp->quant_idx = j;
found = true;
break;
}
}
if (!found) {
JPEGQuantTable table;
memcpy(&table.values[0], &q[i][0], kTableSize);
table.precision = 0;
for (int k = 0; k < kDCTBlockSize; ++k) {
assert(table.values[k] >= 0);
assert(table.values[k] < (1 << 16));
if (table.values[k] > 0xff) {
table.precision = 1;
}
}
table.index = num_tables;
comp->quant_idx = num_tables;
jpg->quant.push_back(table);
++num_tables;
}
}
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/jpeg_data.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 857
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/debug_print.h"
namespace guetzli {
void PrintDebug(ProcessStats* stats, std::string s) {
if (stats->debug_output) {
stats->debug_output->append(s);
}
if (stats->debug_output_file) {
fprintf(stats->debug_output_file, "%s", s.c_str());
}
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/debug_print.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 123
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/jpeg_huffman_decode.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "guetzli/jpeg_data.h"
namespace guetzli {
// Returns the table width of the next 2nd level table, count is the histogram
// of bit lengths for the remaining symbols, len is the code length of the next
// processed symbol.
static inline int NextTableBitSize(const int* count, int len) {
int left = 1 << (len - kJpegHuffmanRootTableBits);
while (len < kJpegHuffmanMaxBitLength) {
left -= count[len];
if (left <= 0) break;
++len;
left <<= 1;
}
return len - kJpegHuffmanRootTableBits;
}
int BuildJpegHuffmanTable(const int* count_in, const int* symbols,
HuffmanTableEntry* lut) {
HuffmanTableEntry code; // current table entry
HuffmanTableEntry* table; // next available space in table
int len; // current code length
int idx; // symbol index
int key; // prefix code
int reps; // number of replicate key values in current table
int low; // low bits for current root entry
int table_bits; // key length of current table
int table_size; // size of current table
int total_size; // sum of root table size and 2nd level table sizes
// Make a local copy of the input bit length histogram.
int count[kJpegHuffmanMaxBitLength + 1] = { 0 };
int total_count = 0;
for (len = 1; len <= kJpegHuffmanMaxBitLength; ++len) {
count[len] = count_in[len];
total_count += count[len];
}
table = lut;
table_bits = kJpegHuffmanRootTableBits;
table_size = 1 << table_bits;
total_size = table_size;
// Special case code with only one value.
if (total_count == 1) {
code.bits = 0;
code.value = symbols[0];
for (key = 0; key < total_size; ++key) {
table[key] = code;
}
return total_size;
}
// Fill in root table.
key = 0;
idx = 0;
for (len = 1; len <= kJpegHuffmanRootTableBits; ++len) {
for (; count[len] > 0; --count[len]) {
code.bits = len;
code.value = symbols[idx++];
reps = 1 << (kJpegHuffmanRootTableBits - len);
while (reps--) {
table[key++] = code;
}
}
}
// Fill in 2nd level tables and add pointers to root table.
table += table_size;
table_size = 0;
low = 0;
for (len = kJpegHuffmanRootTableBits + 1;
len <= kJpegHuffmanMaxBitLength; ++len) {
for (; count[len] > 0; --count[len]) {
// Start a new sub-table if the previous one is full.
if (low >= table_size) {
table += table_size;
table_bits = NextTableBitSize(count, len);
table_size = 1 << table_bits;
total_size += table_size;
low = 0;
lut[key].bits = table_bits + kJpegHuffmanRootTableBits;
lut[key].value = (table - lut) - key;
++key;
}
code.bits = len - kJpegHuffmanRootTableBits;
code.value = symbols[idx++];
reps = 1 << (table_bits - code.bits);
while (reps--) {
table[low++] = code;
}
}
}
return total_size;
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/jpeg_huffman_decode.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 918
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/score.h"
#include <cmath>
namespace guetzli {
double ScoreJPEG(double butteraugli_distance, int size,
double butteraugli_target) {
constexpr double kScale = 50;
constexpr double kMaxExponent = 10;
constexpr double kLargeSize = 1e30;
// TODO(user): The score should also depend on distance below target (and be
// smooth).
double diff = butteraugli_distance - butteraugli_target;
if (diff <= 0.0) {
return size;
} else {
double exponent = kScale * diff;
if (exponent > kMaxExponent) {
return kLargeSize * std::exp(kMaxExponent) * diff + size;
} else {
return std::exp(exponent) * size;
}
}
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/score.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 232
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/gamma_correct.h"
#include <cmath>
namespace guetzli {
const double* NewSrgb8ToLinearTable() {
double* table = new double[256];
int i = 0;
for (; i < 11; ++i) {
table[i] = i / 12.92;
}
for (; i < 256; ++i) {
table[i] = 255.0 * std::pow(((i / 255.0) + 0.055) / 1.055, 2.4);
}
return table;
}
const double* Srgb8ToLinearTable() {
static const double* const kSrgb8ToLinearTable = NewSrgb8ToLinearTable();
return kSrgb8ToLinearTable;
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/gamma_correct.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 222
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/dct_double.h"
#include <algorithm>
#include <cmath>
namespace guetzli {
namespace {
// kDCTMatrix[8*u+x] = 0.5*alpha(u)*cos((2*x+1)*u*M_PI/16),
// where alpha(0) = 1/sqrt(2) and alpha(u) = 1 for u > 0.
static const double kDCTMatrix[64] = {
0.3535533906, 0.3535533906, 0.3535533906, 0.3535533906,
0.3535533906, 0.3535533906, 0.3535533906, 0.3535533906,
0.4903926402, 0.4157348062, 0.2777851165, 0.0975451610,
-0.0975451610, -0.2777851165, -0.4157348062, -0.4903926402,
0.4619397663, 0.1913417162, -0.1913417162, -0.4619397663,
-0.4619397663, -0.1913417162, 0.1913417162, 0.4619397663,
0.4157348062, -0.0975451610, -0.4903926402, -0.2777851165,
0.2777851165, 0.4903926402, 0.0975451610, -0.4157348062,
0.3535533906, -0.3535533906, -0.3535533906, 0.3535533906,
0.3535533906, -0.3535533906, -0.3535533906, 0.3535533906,
0.2777851165, -0.4903926402, 0.0975451610, 0.4157348062,
-0.4157348062, -0.0975451610, 0.4903926402, -0.2777851165,
0.1913417162, -0.4619397663, 0.4619397663, -0.1913417162,
-0.1913417162, 0.4619397663, -0.4619397663, 0.1913417162,
0.0975451610, -0.2777851165, 0.4157348062, -0.4903926402,
0.4903926402, -0.4157348062, 0.2777851165, -0.0975451610,
};
void DCT1d(const double* in, int stride, double* out) {
for (int x = 0; x < 8; ++x) {
out[x * stride] = 0.0;
for (int u = 0; u < 8; ++u) {
out[x * stride] += kDCTMatrix[8 * x + u] * in[u * stride];
}
}
}
void IDCT1d(const double* in, int stride, double* out) {
for (int x = 0; x < 8; ++x) {
out[x * stride] = 0.0;
for (int u = 0; u < 8; ++u) {
out[x * stride] += kDCTMatrix[8 * u + x] * in[u * stride];
}
}
}
typedef void (*Transform1d)(const double* in, int stride, double* out);
void TransformBlock(double block[64], Transform1d f) {
double tmp[64];
for (int x = 0; x < 8; ++x) {
f(&block[x], 8, &tmp[x]);
}
for (int y = 0; y < 8; ++y) {
f(&tmp[8 * y], 1, &block[8 * y]);
}
}
} // namespace
void ComputeBlockDCTDouble(double block[64]) {
TransformBlock(block, DCT1d);
}
void ComputeBlockIDCTDouble(double block[64]) {
TransformBlock(block, IDCT1d);
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/dct_double.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,045
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/butteraugli_comparator.h"
#include <algorithm>
#include "guetzli/debug_print.h"
#include "guetzli/gamma_correct.h"
#include "guetzli/score.h"
namespace guetzli {
namespace {
using ::butteraugli::ConstRestrict;
using ::butteraugli::ImageF;
using ::butteraugli::CreatePlanes;
using ::butteraugli::PlanesFromPacked;
using ::butteraugli::PackedFromPlanes;
std::vector<ImageF> LinearRgb(const size_t xsize, const size_t ysize,
const std::vector<uint8_t>& rgb) {
const double* lut = Srgb8ToLinearTable();
std::vector<ImageF> planes = CreatePlanes<float>(xsize, ysize, 3);
for (int c = 0; c < 3; ++c) {
for (size_t y = 0; y < ysize; ++y) {
ConstRestrict<const uint8_t*> row_in = &rgb[3 * xsize * y];
ConstRestrict<float*> row_out = planes[c].Row(y);
for (size_t x = 0; x < xsize; ++x) {
row_out[x] = lut[row_in[3 * x + c]];
}
}
}
return planes;
}
} // namespace
ButteraugliComparator::ButteraugliComparator(const int width, const int height,
const std::vector<uint8_t>& rgb,
const float target_distance,
ProcessStats* stats)
: width_(width),
height_(height),
target_distance_(target_distance),
comparator_(width_, height_, kButteraugliStep),
distance_(0.0),
distmap_(width_, height_),
stats_(stats) {
rgb_linear_pregamma_ = LinearRgb(width, height, rgb);
const int block_w = (width_ + 7) / 8;
const int block_h = (height_ + 7) / 8;
const int nblocks = block_w * block_h;
per_block_pregamma_.resize(nblocks);
for (int block_y = 0, bx = 0; block_y < block_h; ++block_y) {
for (int block_x = 0; block_x < block_w; ++block_x, ++bx) {
per_block_pregamma_[bx].resize(3, std::vector<float>(kDCTBlockSize));
for (int iy = 0, i = 0; iy < 8; ++iy) {
for (int ix = 0; ix < 8; ++ix, ++i) {
int x = std::min(8 * block_x + ix, width_ - 1);
int y = std::min(8 * block_y + iy, height_ - 1);
for (int c = 0; c < 3; ++c) {
ConstRestrict<const float*> row_linear =
rgb_linear_pregamma_[c].Row(y);
per_block_pregamma_[bx][c][i] = row_linear[x];
}
}
}
::butteraugli::OpsinDynamicsImage(8, 8, per_block_pregamma_[bx]);
}
}
std::vector<std::vector<float>> pregamma =
PackedFromPlanes(rgb_linear_pregamma_);
::butteraugli::OpsinDynamicsImage(width_, height_, pregamma);
rgb_linear_pregamma_ = PlanesFromPacked(width_, height_, pregamma);
std::vector<std::vector<float> > dummy(3);
::butteraugli::Mask(pregamma, pregamma, width_, height_,
&mask_xyz_, &dummy);
}
void ButteraugliComparator::Compare(const OutputImage& img) {
std::vector<std::vector<float> > rgb(3, std::vector<float>(width_ * height_));
img.ToLinearRGB(&rgb);
::butteraugli::OpsinDynamicsImage(width_, height_, rgb);
ImageF distmap;
const std::vector<ImageF> rgb_planes = PlanesFromPacked(width_, height_, rgb);
comparator_.DiffmapOpsinDynamicsImage(rgb_linear_pregamma_,
rgb_planes, distmap);
distmap_.resize(width_ * height_);
CopyToPacked(distmap, &distmap_);
distance_ = ::butteraugli::ButteraugliScoreFromDiffmap(distmap);
GUETZLI_LOG(stats_, " BA[100.00%%] D[%6.4f]", distance_);
}
double ButteraugliComparator::CompareBlock(
const OutputImage& img, int block_x, int block_y) const {
int xmin = 8 * block_x;
int ymin = 8 * block_y;
int block_ix = block_y * ((width_ + 7) / 8) + block_x;
const std::vector<std::vector<float> >& rgb0_c =
per_block_pregamma_[block_ix];
std::vector<std::vector<float> > rgb1_c(3, std::vector<float>(kDCTBlockSize));
img.ToLinearRGB(xmin, ymin, 8, 8, &rgb1_c);
::butteraugli::OpsinDynamicsImage(8, 8, rgb1_c);
std::vector<std::vector<float> > rgb0 = rgb0_c;
std::vector<std::vector<float> > rgb1 = rgb1_c;
::butteraugli::MaskHighIntensityChange(8, 8, rgb0_c, rgb1_c, rgb0, rgb1);
double b0[3 * kDCTBlockSize];
double b1[3 * kDCTBlockSize];
for (int c = 0; c < 3; ++c) {
for (int ix = 0; ix < kDCTBlockSize; ++ix) {
b0[c * kDCTBlockSize + ix] = rgb0[c][ix];
b1[c * kDCTBlockSize + ix] = rgb1[c][ix];
}
}
double diff_xyz_dc[3] = { 0.0 };
double diff_xyz_ac[3] = { 0.0 };
double diff_xyz_edge_dc[3] = { 0.0 };
::butteraugli::ButteraugliBlockDiff(
b0, b1, diff_xyz_dc, diff_xyz_ac, diff_xyz_edge_dc);
double scale[3];
for (int c = 0; c < 3; ++c) {
scale[c] = mask_xyz_[c][ymin * width_ + xmin];
}
static const double kEdgeWeight = 0.05;
double diff = 0.0;
double diff_edge = 0.0;
for (int c = 0; c < 3; ++c) {
diff += diff_xyz_dc[c] * scale[c];
diff += diff_xyz_ac[c] * scale[c];
diff_edge += diff_xyz_edge_dc[c] * scale[c];
}
return sqrt((1 - kEdgeWeight) * diff + kEdgeWeight * diff_edge);
}
float ButteraugliComparator::BlockErrorLimit() const {
return target_distance_;
}
void ButteraugliComparator::ComputeBlockErrorAdjustmentWeights(
int direction,
int max_block_dist,
double target_mul,
int factor_x, int factor_y,
const std::vector<float>& distmap,
std::vector<float>* block_weight) {
const double target_distance = target_distance_ * target_mul;
const int sizex = 8 * factor_x;
const int sizey = 8 * factor_y;
const int block_width = (width_ + sizex - 1) / sizex;
const int block_height = (height_ + sizey - 1) / sizey;
std::vector<float> max_dist_per_block(block_width * block_height);
for (int block_y = 0; block_y < block_height; ++block_y) {
for (int block_x = 0; block_x < block_width; ++block_x) {
int block_ix = block_y * block_width + block_x;
int x_max = std::min(width_, sizex * (block_x + 1));
int y_max = std::min(height_, sizey * (block_y + 1));
float max_dist = 0.0;
for (int y = sizey * block_y; y < y_max; ++y) {
for (int x = sizex * block_x; x < x_max; ++x) {
max_dist = std::max(max_dist, distmap[y * width_ + x]);
}
}
max_dist_per_block[block_ix] = max_dist;
}
}
for (int block_y = 0; block_y < block_height; ++block_y) {
for (int block_x = 0; block_x < block_width; ++block_x) {
int block_ix = block_y * block_width + block_x;
float max_local_dist = target_distance;
int x_min = std::max(0, block_x - max_block_dist);
int y_min = std::max(0, block_y - max_block_dist);
int x_max = std::min(block_width, block_x + 1 + max_block_dist);
int y_max = std::min(block_height, block_y + 1 + max_block_dist);
for (int y = y_min; y < y_max; ++y) {
for (int x = x_min; x < x_max; ++x) {
max_local_dist =
std::max(max_local_dist, max_dist_per_block[y * block_width + x]);
}
}
if (direction > 0) {
if (max_dist_per_block[block_ix] <= target_distance &&
max_local_dist <= 1.1 * target_distance) {
(*block_weight)[block_ix] = 1.0;
}
} else {
constexpr double kLocalMaxWeight = 0.5;
if (max_dist_per_block[block_ix] <=
(1 - kLocalMaxWeight) * target_distance +
kLocalMaxWeight * max_local_dist) {
continue;
}
for (int y = y_min; y < y_max; ++y) {
for (int x = x_min; x < x_max; ++x) {
int d = std::max(std::abs(y - block_y), std::abs(x - block_x));
int ix = y * block_width + x;
(*block_weight)[ix] = std::max<float>(
(*block_weight)[ix], 1.0 / (d + 1.0));
}
}
}
}
}
}
double ButteraugliComparator::ScoreOutputSize(int size) const {
return ScoreJPEG(distance_, size, target_distance_);
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/butteraugli_comparator.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 2,440
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/processor.h"
#include <algorithm>
#include <set>
#include <string.h>
#include <vector>
#include "guetzli/butteraugli_comparator.h"
#include "guetzli/comparator.h"
#include "guetzli/debug_print.h"
#include "guetzli/fast_log.h"
#include "guetzli/jpeg_data_decoder.h"
#include "guetzli/jpeg_data_encoder.h"
#include "guetzli/jpeg_data_reader.h"
#include "guetzli/jpeg_data_writer.h"
#include "guetzli/output_image.h"
#include "guetzli/quantize.h"
namespace guetzli {
namespace {
static const size_t kBlockSize = 3 * kDCTBlockSize;
struct CoeffData {
int idx;
float block_err;
};
struct QuantData {
int q[3][kDCTBlockSize];
bool dist_ok;
GuetzliOutput out;
};
class Processor {
public:
bool ProcessJpegData(const Params& params, const JPEGData& jpg_in,
Comparator* comparator, GuetzliOutput* out,
ProcessStats* stats);
private:
void SelectFrequencyMasking(const JPEGData& jpg, OutputImage* img,
const uint8_t comp_mask, const double target_mul,
bool stop_early);
void ComputeBlockZeroingOrder(
const coeff_t block[kBlockSize], const coeff_t orig_block[kBlockSize],
const int block_x, const int block_y, const int factor_x,
const int factor_y, const uint8_t comp_mask, OutputImage* img,
std::vector<CoeffData>* output_order);
bool SelectQuantMatrix(const JPEGData& jpg_in, const bool downsample,
int best_q[3][kDCTBlockSize],
GuetzliOutput* quantized_out);
QuantData TryQuantMatrix(const JPEGData& jpg_in,
const float target_mul,
int q[3][kDCTBlockSize]);
void MaybeOutput(const std::string& encoded_jpg);
void DownsampleImage(OutputImage* img);
void OutputJpeg(const JPEGData& in, std::string* out);
Params params_;
Comparator* comparator_;
GuetzliOutput* final_output_;
ProcessStats* stats_;
};
void RemoveOriginalQuantization(JPEGData* jpg, int q_in[3][kDCTBlockSize]) {
for (int i = 0; i < 3; ++i) {
JPEGComponent& c = jpg->components[i];
const int* q = &jpg->quant[c.quant_idx].values[0];
memcpy(&q_in[i][0], q, kDCTBlockSize * sizeof(q[0]));
for (int j = 0; j < (int)c.coeffs.size(); ++j) {
c.coeffs[j] *= q[j % kDCTBlockSize];
}
}
int q[3][kDCTBlockSize];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < kDCTBlockSize; ++j) q[i][j] = 1;
SaveQuantTables(q, jpg);
}
void Processor::DownsampleImage(OutputImage* img) {
if (img->component(1).factor_x() > 1 || img->component(1).factor_y() > 1) {
return;
}
OutputImage::DownsampleConfig cfg;
cfg.use_silver_screen = params_.use_silver_screen;
img->Downsample(cfg);
}
} // namespace
int GuetzliStringOut(void* data, const uint8_t* buf, size_t count) {
std::string* sink =
reinterpret_cast<std::string*>(data);
sink->append(reinterpret_cast<const char*>(buf), count);
return count;
}
void Processor::OutputJpeg(const JPEGData& jpg,
std::string* out) {
out->clear();
JPEGOutput output(GuetzliStringOut, out);
if (!WriteJpeg(jpg, params_.clear_metadata, output)) {
assert(0);
}
}
void Processor::MaybeOutput(const std::string& encoded_jpg) {
double score = comparator_->ScoreOutputSize(encoded_jpg.size());
GUETZLI_LOG(stats_, " Score[%.4f]", score);
if (score < final_output_->score || final_output_->score < 0) {
final_output_->jpeg_data = encoded_jpg;
final_output_->distmap = comparator_->distmap();
final_output_->distmap_aggregate = comparator_->distmap_aggregate();
final_output_->score = score;
GUETZLI_LOG(stats_, " (*)");
}
GUETZLI_LOG(stats_, "\n");
}
bool CompareQuantData(const QuantData& a, const QuantData& b) {
if (a.dist_ok && !b.dist_ok) return true;
if (!a.dist_ok && b.dist_ok) return false;
return a.out.jpeg_data.size() < b.out.jpeg_data.size();
}
// Compares a[0..kBlockSize) and b[0..kBlockSize) vectors, and returns
// 0 : if they are equal
// -1 : if a is everywhere <= than b and in at least one coordinate <
// 1 : if a is everywhere >= than b and in at least one coordinate >
// 2 : if a and b are uncomparable (some coordinate smaller and some greater)
int CompareQuantMatrices(const int* a, const int* b) {
int i = 0;
while (i < (int)kBlockSize && a[i] == b[i]) ++i;
if (i == kBlockSize) {
return 0;
}
if (a[i] < b[i]) {
for (++i; i < (int)kBlockSize; ++i) {
if (a[i] > b[i]) return 2;
}
return -1;
} else {
for (++i; i < (int)kBlockSize; ++i) {
if (a[i] < b[i]) return 2;
}
return 1;
}
}
double ContrastSensitivity(int k) {
return 1.0 / (1.0 + kJPEGZigZagOrder[k] / 2.0);
}
double QuantMatrixHeuristicScore(const int q[3][kDCTBlockSize]) {
double score = 0.0;
for (int c = 0; c < 3; ++c) {
for (int k = 0; k < kDCTBlockSize; ++k) {
score += 0.5 * (q[c][k] - 1.0) * ContrastSensitivity(k);
}
}
return score;
}
class QuantMatrixGenerator {
public:
QuantMatrixGenerator(bool downsample, ProcessStats* stats)
: downsample_(downsample), hscore_a_(-1.0), hscore_b_(-1.0),
total_csf_(0.0), stats_(stats) {
for (int k = 0; k < kDCTBlockSize; ++k) {
total_csf_ += 3.0 * ContrastSensitivity(k);
}
}
bool GetNext(int q[3][kDCTBlockSize]) {
// This loop should terminate by return. This 1000 iteration limit is just a
// precaution.
for (int iter = 0; iter < 1000; iter++) {
double hscore;
if (hscore_b_ == -1.0) {
if (hscore_a_ == -1.0) {
hscore = downsample_ ? 0.0 : total_csf_;
} else {
hscore = hscore_a_ + total_csf_;
}
if (hscore > 100 * total_csf_) {
// We could not find a quantization matrix that creates enough
// butteraugli error. This can happen if all dct coefficients are
// close to zero in the original image.
return false;
}
} else if (hscore_b_ == 0.0) {
return false;
} else if (hscore_a_ == -1.0) {
hscore = 0.0;
} else {
int lower_q[3][kDCTBlockSize];
int upper_q[3][kDCTBlockSize];
constexpr double kEps = 0.05;
GetQuantMatrixWithHeuristicScore(
(1 - kEps) * hscore_a_ + kEps * 0.5 * (hscore_a_ + hscore_b_),
lower_q);
GetQuantMatrixWithHeuristicScore(
(1 - kEps) * hscore_b_ + kEps * 0.5 * (hscore_a_ + hscore_b_),
upper_q);
if (CompareQuantMatrices(&lower_q[0][0], &upper_q[0][0]) == 0)
return false;
hscore = (hscore_a_ + hscore_b_) * 0.5;
}
GetQuantMatrixWithHeuristicScore(hscore, q);
bool retry = false;
for (int i = 0; i < (int)quants_.size(); ++i) {
if (CompareQuantMatrices(&q[0][0], &quants_[i].q[0][0]) == 0) {
if (quants_[i].dist_ok) {
hscore_a_ = hscore;
} else {
hscore_b_ = hscore;
}
retry = true;
break;
}
}
if (!retry) return true;
}
return false;
}
void Add(const QuantData& data) {
quants_.push_back(data);
double hscore = QuantMatrixHeuristicScore(data.q);
if (data.dist_ok) {
hscore_a_ = std::max(hscore_a_, hscore);
} else {
hscore_b_ = hscore_b_ == -1.0 ? hscore : std::min(hscore_b_, hscore);
}
}
private:
void GetQuantMatrixWithHeuristicScore(double score,
int q[3][kDCTBlockSize]) const {
int level = static_cast<int>(score / total_csf_);
score -= level * total_csf_;
for (int k = kDCTBlockSize - 1; k >= 0; --k) {
for (int c = 0; c < 3; ++c) {
q[c][kJPEGNaturalOrder[k]] = 2 * level + (score > 0.0 ? 3 : 1);
}
score -= 3.0 * ContrastSensitivity(kJPEGNaturalOrder[k]);
}
}
const bool downsample_;
// Lower bound for quant matrix heuristic score used in binary search.
double hscore_a_;
// Upper bound for quant matrix heuristic score used in binary search, or 0.0
// if no upper bound is found yet.
double hscore_b_;
// Cached value of the sum of all ContrastSensitivity() values over all
// quant matrix elements.
double total_csf_;
std::vector<QuantData> quants_;
ProcessStats* stats_;
ProcessStats *removeWarning(){ return stats_; }
};
QuantData Processor::TryQuantMatrix(const JPEGData& jpg_in,
const float target_mul,
int q[3][kDCTBlockSize]) {
QuantData data;
memcpy(data.q, q, sizeof(data.q));
OutputImage img(jpg_in.width, jpg_in.height);
img.CopyFromJpegData(jpg_in);
img.ApplyGlobalQuantization(data.q);
JPEGData jpg_out = jpg_in;
img.SaveToJpegData(&jpg_out);
std::string encoded_jpg;
OutputJpeg(jpg_out, &encoded_jpg);
GUETZLI_LOG(stats_, "Iter %2d: %s quantization matrix:\n",
stats_->counters[kNumItersCnt] + 1,
img.FrameTypeStr().c_str());
GUETZLI_LOG_QUANT(stats_, q);
GUETZLI_LOG(stats_, "Iter %2d: %s GQ[%5.2f] Out[%7zd]",
stats_->counters[kNumItersCnt] + 1,
img.FrameTypeStr().c_str(),
QuantMatrixHeuristicScore(q), encoded_jpg.size());
++stats_->counters[kNumItersCnt];
comparator_->Compare(img);
data.dist_ok = comparator_->DistanceOK(target_mul);
data.out.jpeg_data = encoded_jpg;
data.out.distmap = comparator_->distmap();
data.out.distmap_aggregate = comparator_->distmap_aggregate();
data.out.score = comparator_->ScoreOutputSize(encoded_jpg.size());
MaybeOutput(encoded_jpg);
return data;
}
bool Processor::SelectQuantMatrix(const JPEGData& jpg_in, const bool downsample,
int best_q[3][kDCTBlockSize],
GuetzliOutput* quantized_out) {
QuantMatrixGenerator qgen(downsample, stats_);
// Don't try to go up to exactly the target distance when selecting a
// quantization matrix, since we will need some slack to do the frequency
// masking later.
const float target_mul_high = 0.97;
const float target_mul_low = 0.95;
QuantData best = TryQuantMatrix(jpg_in, target_mul_high, best_q);
for (;;) {
int q_next[3][kDCTBlockSize];
if (!qgen.GetNext(q_next)) {
break;
}
QuantData data =
TryQuantMatrix(jpg_in, target_mul_high, q_next);
qgen.Add(data);
if (CompareQuantData(data, best)) {
best = data;
if (data.dist_ok && !comparator_->DistanceOK(target_mul_low)) {
break;
}
}
}
memcpy(&best_q[0][0], &best.q[0][0], kBlockSize * sizeof(best_q[0][0]));
*quantized_out = best.out;
GUETZLI_LOG(stats_, "\n%s selected quantization matrix:\n",
downsample ? "YUV420" : "YUV444");
GUETZLI_LOG_QUANT(stats_, best_q);
return best.dist_ok;
}
// REQUIRES: block[c*64...(c*64+63)] is all zero if (comp_mask & (1<<c)) == 0.
void Processor::ComputeBlockZeroingOrder(
const coeff_t block[kBlockSize], const coeff_t orig_block[kBlockSize],
const int block_x, const int block_y, const int factor_x,
const int factor_y, const uint8_t comp_mask, OutputImage* img,
std::vector<CoeffData>* output_order) {
static const uint8_t oldCsf[kDCTBlockSize] = {
10, 10, 20, 40, 60, 70, 80, 90,
10, 20, 30, 60, 70, 80, 90, 90,
20, 30, 60, 70, 80, 90, 90, 90,
40, 60, 70, 80, 90, 90, 90, 90,
60, 70, 80, 90, 90, 90, 90, 90,
70, 80, 90, 90, 90, 90, 90, 90,
80, 90, 90, 90, 90, 90, 90, 90,
90, 90, 90, 90, 90, 90, 90, 90,
};
static const double kWeight[3] = { 1.0, 0.22, 0.20 };
#include "guetzli/order.inc"
std::vector<std::pair<int, float> > input_order;
for (int c = 0; c < 3; ++c) {
if (!(comp_mask & (1 << c))) continue;
for (int k = 1; k < kDCTBlockSize; ++k) {
int idx = c * kDCTBlockSize + k;
if (block[idx] != 0) {
float score;
if (params_.new_zeroing_model) {
score = std::abs(orig_block[idx]) * csf[idx] + bias[idx];
} else {
score = (std::abs(orig_block[idx]) - kJPEGZigZagOrder[k] / 64.0) *
kWeight[c] / oldCsf[k];
}
input_order.push_back(std::make_pair(idx, score));
}
}
}
std::sort(input_order.begin(), input_order.end(),
[](const std::pair<int, float>& a, const std::pair<int, float>& b) {
return a.second < b.second; });
coeff_t processed_block[kBlockSize];
memcpy(processed_block, block, sizeof(processed_block));
while (!input_order.empty()) {
float best_err = 1e17;
int best_i = 0;
for (int i = 0; i < (int)std::min<size_t>((size_t)params_.zeroing_greedy_lookahead,
input_order.size());
++i) {
coeff_t candidate_block[kBlockSize];
memcpy(candidate_block, processed_block, sizeof(candidate_block));
const int idx = input_order[i].first;
candidate_block[idx] = 0;
for (int c = 0; c < 3; ++c) {
if (comp_mask & (1 << c)) {
img->component(c).SetCoeffBlock(
block_x, block_y, &candidate_block[c * kDCTBlockSize]);
}
}
float max_err = 0;
for (int iy = 0; iy < factor_y; ++iy) {
for (int ix = 0; ix < factor_x; ++ix) {
int block_xx = block_x * factor_x + ix;
int block_yy = block_y * factor_y + iy;
if (8 * block_xx < img->width() && 8 * block_yy < img->height()) {
float err = comparator_->CompareBlock(*img, block_xx, block_yy);
max_err = std::max(max_err, err);
}
}
}
if (max_err < best_err) {
best_err = max_err;
best_i = i;
}
}
int idx = input_order[best_i].first;
processed_block[idx] = 0;
input_order.erase(input_order.begin() + best_i);
output_order->push_back({idx, best_err});
for (int c = 0; c < 3; ++c) {
if (comp_mask & (1 << c)) {
img->component(c).SetCoeffBlock(
block_x, block_y, &processed_block[c * kDCTBlockSize]);
}
}
}
// Make the block error values monotonic.
float min_err = 1e10;
for (int i = output_order->size() - 1; i >= 0; --i) {
min_err = std::min(min_err, (*output_order)[i].block_err);
(*output_order)[i].block_err = min_err;
}
// Cut off at the block error limit.
int num = 0;
while (num < (int)output_order->size() &&
(*output_order)[num].block_err <= comparator_->BlockErrorLimit()) {
++num;
}
output_order->resize(num);
// Restore *img to the same state as it was at the start of this function.
for (int c = 0; c < 3; ++c) {
if (comp_mask & (1 << c)) {
img->component(c).SetCoeffBlock(
block_x, block_y, &block[c * kDCTBlockSize]);
}
}
}
namespace {
void UpdateACHistogram(const int weight,
const coeff_t* coeffs,
const int* q,
JpegHistogram* ac_histogram) {
int r = 0;
for (int k = 1; k < 64; ++k) {
const int k_nat = kJPEGNaturalOrder[k];
coeff_t coeff = coeffs[k_nat];
if (coeff == 0) {
r++;
continue;
}
while (r > 15) {
ac_histogram->Add(0xf0, weight);
r -= 16;
}
int nbits = Log2FloorNonZero(std::abs(coeff / q[k_nat])) + 1;
int symbol = (r << 4) + nbits;
ac_histogram->Add(symbol, weight);
r = 0;
}
if (r > 0) {
ac_histogram->Add(0, weight);
}
}
size_t ComputeEntropyCodes(const std::vector<JpegHistogram>& histograms,
std::vector<uint8_t>* depths) {
std::vector<JpegHistogram> clustered = histograms;
size_t num = histograms.size();
std::vector<int> indexes(histograms.size());
std::vector<uint8_t> clustered_depths(
histograms.size() * JpegHistogram::kSize);
ClusterHistograms(&clustered[0], &num, &indexes[0], &clustered_depths[0]);
depths->resize(clustered_depths.size());
for (int i = 0; i < (int)histograms.size(); ++i) {
memcpy(&(*depths)[i * JpegHistogram::kSize],
&clustered_depths[indexes[i] * JpegHistogram::kSize],
JpegHistogram::kSize);
}
size_t histogram_size = 0;
for (int i = 0; i < (int)num; ++i) {
histogram_size += HistogramHeaderCost(clustered[i]) / 8;
}
return histogram_size;
}
size_t EntropyCodedDataSize(const std::vector<JpegHistogram>& histograms,
const std::vector<uint8_t>& depths) {
size_t numbits = 0;
for (int i = 0; i < (int)histograms.size(); ++i) {
numbits += HistogramEntropyCost(
histograms[i], &depths[i * JpegHistogram::kSize]);
}
return (numbits + 7) / 8;
}
size_t EstimateDCSize(const JPEGData& jpg) {
std::vector<JpegHistogram> histograms(jpg.components.size());
BuildDCHistograms(jpg, &histograms[0]);
size_t num = histograms.size();
std::vector<int> indexes(num);
std::vector<uint8_t> depths(num * JpegHistogram::kSize);
return ClusterHistograms(&histograms[0], &num, &indexes[0], &depths[0]);
}
} // namespace
void Processor::SelectFrequencyMasking(const JPEGData& jpg, OutputImage* img,
const uint8_t comp_mask,
const double target_mul,
bool stop_early) {
const int width = img->width();
const int height = img->height();
const int last_c = Log2FloorNonZero(comp_mask);
if (last_c >= (int)jpg.components.size()) return;
const int factor_x = img->component(last_c).factor_x();
const int factor_y = img->component(last_c).factor_y();
const int block_width = (width + 8 * factor_x - 1) / (8 * factor_x);
const int block_height = (height + 8 * factor_y - 1) / (8 * factor_y);
const int num_blocks = block_width * block_height;
std::vector<std::vector<CoeffData> > orders(num_blocks);
for (int block_y = 0, block_ix = 0; block_y < block_height; ++block_y) {
for (int block_x = 0; block_x < block_width; ++block_x, ++block_ix) {
coeff_t block[kBlockSize] = { 0 };
coeff_t orig_block[kBlockSize] = { 0 };
for (int c = 0; c < 3; ++c) {
if (comp_mask & (1 << c)) {
assert(img->component(c).factor_x() == factor_x);
assert(img->component(c).factor_y() == factor_y);
img->component(c).GetCoeffBlock(block_x, block_y,
&block[c * kDCTBlockSize]);
const JPEGComponent& comp = jpg.components[c];
int jpg_block_ix = block_y * comp.width_in_blocks + block_x;
memcpy(&orig_block[c * kDCTBlockSize],
&comp.coeffs[jpg_block_ix * kDCTBlockSize],
kDCTBlockSize * sizeof(orig_block[0]));
}
}
ComputeBlockZeroingOrder(block, orig_block, block_x, block_y, factor_x,
factor_y, comp_mask, img,
&orders[block_ix]);
}
}
JPEGData jpg_out = jpg;
img->SaveToJpegData(&jpg_out);
const int jpg_header_size = JpegHeaderSize(jpg_out, params_.clear_metadata);
const int dc_size = EstimateDCSize(jpg_out);
std::vector<JpegHistogram> ac_histograms(jpg_out.components.size());
BuildACHistograms(jpg_out, &ac_histograms[0]);
std::vector<uint8_t> ac_depths;
int ac_histogram_size = ComputeEntropyCodes(ac_histograms, &ac_depths);
int base_size = jpg_header_size + dc_size + ac_histogram_size +
EntropyCodedDataSize(ac_histograms, ac_depths);
int prev_size = base_size;
std::vector<float> max_block_error(num_blocks);
std::vector<int> last_indexes(num_blocks);
std::vector<float> distmap(width * height);
bool first_up_iter = true;
for (int direction : {1, -1}) {
for (;;) {
if (stop_early && direction == -1) {
if (prev_size > 1.01 * final_output_->jpeg_data.size()) {
// If we are down-adjusting the error, the output size will only keep
// increasing.
// TODO(user): Do this check always by comparing only the size
// of the currently processed components.
break;
}
}
std::vector<std::pair<int, float> > global_order;
int blocks_to_change;
std::vector<float> block_weight;
for (int rblock = 1; rblock <= 4; ++rblock) {
block_weight = std::vector<float>(num_blocks);
comparator_->ComputeBlockErrorAdjustmentWeights(
direction, rblock, target_mul, factor_x, factor_y, distmap,
&block_weight);
global_order.clear();
blocks_to_change = 0;
for (int block_y = 0, block_ix = 0; block_y < block_height; ++block_y) {
for (int block_x = 0; block_x < block_width; ++block_x, ++block_ix) {
const int last_index = last_indexes[block_ix];
const std::vector<CoeffData>& order = orders[block_ix];
const float max_err = max_block_error[block_ix];
if (block_weight[block_ix] == 0) {
continue;
}
if (direction > 0) {
for (int i = last_index; i < (int)order.size(); ++i) {
float val = ((order[i].block_err - max_err) /
block_weight[block_ix]);
global_order.push_back(std::make_pair(block_ix, val));
}
blocks_to_change += (last_index < (int)order.size() ? 1 : 0);
} else {
for (int i = last_index - 1; i >= 0; --i) {
float val = ((max_err - order[i].block_err) /
block_weight[block_ix]);
global_order.push_back(std::make_pair(block_ix, val));
}
blocks_to_change += (last_index > 0 ? 1 : 0);
}
}
}
if (!global_order.empty()) {
// If we found something to adjust with the current block adjustment
// radius, we can stop and adjust the blocks we have.
break;
}
}
if (global_order.empty()) {
break;
}
std::sort(global_order.begin(), global_order.end(),
[](const std::pair<int, float>& a,
const std::pair<int, float>& b) {
return a.second < b.second; });
double rel_size_delta = direction > 0 ? 0.01 : 0.0005;
if (direction > 0 && comparator_->DistanceOK(1.0)) {
rel_size_delta = 0.05;
}
size_t min_size_delta = base_size * rel_size_delta;
float coeffs_to_change_per_block =
direction > 0 ? 2.0 : factor_x * factor_y * 0.2;
int min_coeffs_to_change = coeffs_to_change_per_block * blocks_to_change;
if (first_up_iter) {
const float limit = 0.75 * comparator_->BlockErrorLimit();
auto it = std::partition_point(global_order.begin(), global_order.end(),
[=](const std::pair<int, float>& a) {
return a.second < limit; });
min_coeffs_to_change = std::max<int>(min_coeffs_to_change,
it - global_order.begin());
first_up_iter = false;
}
std::set<int> changed_blocks;
float val_threshold = 0.0;
int changed_coeffs = 0;
int est_jpg_size = prev_size;
for (int i = 0; i < (int)global_order.size(); ++i) {
const int block_ix = global_order[i].first;
const int block_x = block_ix % block_width;
const int block_y = block_ix / block_width;
const int last_idx = last_indexes[block_ix];
const std::vector<CoeffData>& order = orders[block_ix];
const int idx = order[last_idx + std::min(direction, 0)].idx;
const int c = idx / kDCTBlockSize;
const int k = idx % kDCTBlockSize;
const int* quant = img->component(c).quant();
const JPEGComponent& comp = jpg.components[c];
const int jpg_block_ix = block_y * comp.width_in_blocks + block_x;
const int newval = direction > 0 ? 0 : Quantize(
comp.coeffs[jpg_block_ix * kDCTBlockSize + k], quant[k]);
coeff_t block[kDCTBlockSize] = { 0 };
img->component(c).GetCoeffBlock(block_x, block_y, block);
UpdateACHistogram(-1, block, quant, &ac_histograms[c]);
block[k] = newval;
UpdateACHistogram(1, block, quant, &ac_histograms[c]);
img->component(c).SetCoeffBlock(block_x, block_y, block);
last_indexes[block_ix] += direction;
changed_blocks.insert(block_ix);
val_threshold = global_order[i].second;
++changed_coeffs;
static const int kEntropyCodeUpdateFreq = 10;
if (i % kEntropyCodeUpdateFreq == 0) {
ac_histogram_size = ComputeEntropyCodes(ac_histograms, &ac_depths);
}
est_jpg_size = jpg_header_size + dc_size + ac_histogram_size +
EntropyCodedDataSize(ac_histograms, ac_depths);
if (changed_coeffs > min_coeffs_to_change &&
std::abs(est_jpg_size - prev_size) > (int)min_size_delta) {
break;
}
}
for (int i = 0; i < num_blocks; ++i) {
max_block_error[i] += block_weight[i] * val_threshold * direction;
}
++stats_->counters[kNumItersCnt];
++stats_->counters[direction > 0 ? kNumItersUpCnt : kNumItersDownCnt];
JPEGData jpg_out = jpg;
img->SaveToJpegData(&jpg_out);
std::string encoded_jpg;
OutputJpeg(jpg_out, &encoded_jpg);
GUETZLI_LOG(stats_,
"Iter %2d: %s(%d) %s Coeffs[%d/%zd] "
"Blocks[%zd/%d/%d] ValThres[%.4f] Out[%7zd] EstErr[%.2f%%]",
stats_->counters[kNumItersCnt], img->FrameTypeStr().c_str(),
comp_mask, direction > 0 ? "up" : "down", changed_coeffs,
global_order.size(), changed_blocks.size(),
blocks_to_change, num_blocks, val_threshold,
encoded_jpg.size(),
100.0 - (100.0 * est_jpg_size) / encoded_jpg.size());
comparator_->Compare(*img);
MaybeOutput(encoded_jpg);
distmap = comparator_->distmap();
prev_size = est_jpg_size;
}
}
}
bool IsGrayscale(const JPEGData& jpg) {
for (int c = 1; c < 3; ++c) {
const JPEGComponent& comp = jpg.components[c];
for (size_t i = 0; i < comp.coeffs.size(); ++i) {
if (comp.coeffs[i] != 0) return false;
}
}
return true;
}
bool Processor::ProcessJpegData(const Params& params, const JPEGData& jpg_in,
Comparator* comparator, GuetzliOutput* out,
ProcessStats* stats) {
params_ = params;
comparator_ = comparator;
final_output_ = out;
stats_ = stats;
if (params.butteraugli_target > 2.0f) {
fprintf(stderr,
"Guetzli should be called with quality >= 84, otherwise the\n"
"output will have noticeable artifacts. If you want to\n"
"proceed anyway, please edit the source code.\n");
return false;
}
if (jpg_in.components.size() != 3 || !HasYCbCrColorSpace(jpg_in)) {
fprintf(stderr, "Only YUV color space input jpeg is supported\n");
return false;
}
bool input_is_420;
if (jpg_in.Is444()) {
input_is_420 = false;
} else if (jpg_in.Is420()) {
input_is_420 = true;
} else {
fprintf(stderr, "Unsupported sampling factors:");
for (int i = 0; i < (int)jpg_in.components.size(); ++i) {
fprintf(stderr, " %dx%d", jpg_in.components[i].h_samp_factor,
jpg_in.components[i].v_samp_factor);
}
fprintf(stderr, "\n");
return false;
}
JPEGData jpg = jpg_in;
int q_in[3][kDCTBlockSize];
// Output the original image, in case we do not manage to create anything
// with a good enough quality.
std::string encoded_jpg;
OutputJpeg(jpg, &encoded_jpg);
final_output_->score = -1;
GUETZLI_LOG(stats, "Original Out[%7zd]", encoded_jpg.size());
if (comparator_ == nullptr) {
GUETZLI_LOG(stats, " <image too small for Butteraugli>\n");
final_output_->jpeg_data = encoded_jpg;
final_output_->distmap = std::vector<float>(jpg.width * jpg.height, 0.0);
final_output_->distmap_aggregate = 0;
final_output_->score = encoded_jpg.size();
// Butteraugli doesn't work with images this small.
return true;
}
RemoveOriginalQuantization(&jpg, q_in);
OutputImage img(jpg.width, jpg.height);
img.CopyFromJpegData(jpg);
comparator_->Compare(img);
MaybeOutput(encoded_jpg);
int try_420 = (input_is_420 || params_.force_420 ||
(params_.try_420 && !IsGrayscale(jpg))) ? 1 : 0;
int force_420 = (input_is_420 || params_.force_420) ? 1 : 0;
for (int downsample = force_420; downsample <= try_420; ++downsample) {
OutputImage img(jpg.width, jpg.height);
img.CopyFromJpegData(jpg);
JPEGData tmp_jpg;
if (downsample) {
DownsampleImage(&img);
img.SaveToJpegData(&tmp_jpg);
} else {
tmp_jpg = jpg;
}
int best_q[3][kDCTBlockSize];
memcpy(best_q, q_in, sizeof(best_q));
GuetzliOutput quantized_out;
if (!SelectQuantMatrix(tmp_jpg, downsample, best_q, &quantized_out)) {
for (int c = 0; c < 3; ++c) {
for (int i = 0; i < kDCTBlockSize; ++i) {
best_q[c][i] = 1;
}
}
}
img.ApplyGlobalQuantization(best_q);
if (!downsample) {
SelectFrequencyMasking(tmp_jpg, &img, 7, 1.0, false);
} else {
const float ymul = tmp_jpg.components.size() == 1 ? 1.0 : 0.97;
SelectFrequencyMasking(tmp_jpg, &img, 1, ymul, false);
SelectFrequencyMasking(tmp_jpg, &img, 6, 1.0, true);
}
}
return true;
}
bool ProcessJpegData(const Params& params, const JPEGData& jpg_in,
Comparator* comparator, GuetzliOutput* out,
ProcessStats* stats) {
Processor processor;
return processor.ProcessJpegData(params, jpg_in, comparator, out, stats);
}
bool Process(const Params& params, ProcessStats* stats,
const std::string& data,
std::string* jpg_out) {
JPEGData jpg;
if (!ReadJpeg(data, JPEG_READ_ALL, &jpg)) {
fprintf(stderr, "Can't read jpg data from input file\n");
return false;
}
std::vector<uint8_t> rgb = DecodeJpegToRGB(jpg);
if (rgb.empty()) {
fprintf(stderr, "Invalid input JPEG file\n");
return false;
}
GuetzliOutput out;
ProcessStats dummy_stats;
if (stats == nullptr) {
stats = &dummy_stats;
}
std::unique_ptr<ButteraugliComparator> comparator;
if (jpg.width >= 32 && jpg.height >= 32) {
comparator.reset(
new ButteraugliComparator(jpg.width, jpg.height, rgb,
params.butteraugli_target, stats));
}
bool ok = ProcessJpegData(params, jpg, comparator.get(), &out, stats);
*jpg_out = out.jpeg_data;
return ok;
}
bool Process(const Params& params, ProcessStats* stats,
const std::vector<uint8_t>& rgb, int w, int h,
std::string* jpg_out) {
JPEGData jpg;
if (!EncodeRGBToJpeg(rgb, w, h, &jpg)) {
fprintf(stderr, "Could not create jpg data from rgb pixels\n");
return false;
}
GuetzliOutput out;
ProcessStats dummy_stats;
if (stats == nullptr) {
stats = &dummy_stats;
}
std::unique_ptr<ButteraugliComparator> comparator;
if (jpg.width >= 32 && jpg.height >= 32) {
comparator.reset(
new ButteraugliComparator(jpg.width, jpg.height, rgb,
params.butteraugli_target, stats));
}
bool ok = ProcessJpegData(params, jpg, comparator.get(), &out, stats);
*jpg_out = out.jpeg_data;
return ok;
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/processor.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 8,853
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Integer implementation of the Inverse Discrete Cosine Transform (IDCT).
#include "guetzli/idct.h"
#include <algorithm>
#include <math.h>
namespace guetzli {
// kIDCTMatrix[8*x+u] = alpha(u)*cos((2*x+1)*u*M_PI/16)*sqrt(2), with fixed 13
// bit precision, where alpha(0) = 1/sqrt(2) and alpha(u) = 1 for u > 0.
// Some coefficients are off by +-1 to mimick libjpeg's behaviour.
static const int kIDCTMatrix[kDCTBlockSize] = {
8192, 11363, 10703, 9633, 8192, 6437, 4433, 2260,
8192, 9633, 4433, -2259, -8192, -11362, -10704, -6436,
8192, 6437, -4433, -11362, -8192, 2261, 10704, 9633,
8192, 2260, -10703, -6436, 8192, 9633, -4433, -11363,
8192, -2260, -10703, 6436, 8192, -9633, -4433, 11363,
8192, -6437, -4433, 11362, -8192, -2261, 10704, -9633,
8192, -9633, 4433, 2259, -8192, 11362, -10704, 6436,
8192, -11363, 10703, -9633, 8192, -6437, 4433, -2260,
};
// Computes out[x] = sum{kIDCTMatrix[8*x+u]*in[u*stride]; for u in [0..7]}
inline void Compute1dIDCT(const coeff_t* in, const int stride, int out[8]) {
int tmp0, tmp1, tmp2, tmp3, tmp4;
tmp1 = kIDCTMatrix[0] * in[0];
out[0] = out[1] = out[2] = out[3] = out[4] = out[5] = out[6] = out[7] = tmp1;
tmp0 = in[stride];
tmp1 = kIDCTMatrix[ 1] * tmp0;
tmp2 = kIDCTMatrix[ 9] * tmp0;
tmp3 = kIDCTMatrix[17] * tmp0;
tmp4 = kIDCTMatrix[25] * tmp0;
out[0] += tmp1;
out[1] += tmp2;
out[2] += tmp3;
out[3] += tmp4;
out[4] -= tmp4;
out[5] -= tmp3;
out[6] -= tmp2;
out[7] -= tmp1;
tmp0 = in[2 * stride];
tmp1 = kIDCTMatrix[ 2] * tmp0;
tmp2 = kIDCTMatrix[10] * tmp0;
out[0] += tmp1;
out[1] += tmp2;
out[2] -= tmp2;
out[3] -= tmp1;
out[4] -= tmp1;
out[5] -= tmp2;
out[6] += tmp2;
out[7] += tmp1;
tmp0 = in[3 * stride];
tmp1 = kIDCTMatrix[ 3] * tmp0;
tmp2 = kIDCTMatrix[11] * tmp0;
tmp3 = kIDCTMatrix[19] * tmp0;
tmp4 = kIDCTMatrix[27] * tmp0;
out[0] += tmp1;
out[1] += tmp2;
out[2] += tmp3;
out[3] += tmp4;
out[4] -= tmp4;
out[5] -= tmp3;
out[6] -= tmp2;
out[7] -= tmp1;
tmp0 = in[4 * stride];
tmp1 = kIDCTMatrix[ 4] * tmp0;
out[0] += tmp1;
out[1] -= tmp1;
out[2] -= tmp1;
out[3] += tmp1;
out[4] += tmp1;
out[5] -= tmp1;
out[6] -= tmp1;
out[7] += tmp1;
tmp0 = in[5 * stride];
tmp1 = kIDCTMatrix[ 5] * tmp0;
tmp2 = kIDCTMatrix[13] * tmp0;
tmp3 = kIDCTMatrix[21] * tmp0;
tmp4 = kIDCTMatrix[29] * tmp0;
out[0] += tmp1;
out[1] += tmp2;
out[2] += tmp3;
out[3] += tmp4;
out[4] -= tmp4;
out[5] -= tmp3;
out[6] -= tmp2;
out[7] -= tmp1;
tmp0 = in[6 * stride];
tmp1 = kIDCTMatrix[ 6] * tmp0;
tmp2 = kIDCTMatrix[14] * tmp0;
out[0] += tmp1;
out[1] += tmp2;
out[2] -= tmp2;
out[3] -= tmp1;
out[4] -= tmp1;
out[5] -= tmp2;
out[6] += tmp2;
out[7] += tmp1;
tmp0 = in[7 * stride];
tmp1 = kIDCTMatrix[ 7] * tmp0;
tmp2 = kIDCTMatrix[15] * tmp0;
tmp3 = kIDCTMatrix[23] * tmp0;
tmp4 = kIDCTMatrix[31] * tmp0;
out[0] += tmp1;
out[1] += tmp2;
out[2] += tmp3;
out[3] += tmp4;
out[4] -= tmp4;
out[5] -= tmp3;
out[6] -= tmp2;
out[7] -= tmp1;
}
void ComputeBlockIDCT(const coeff_t* block, uint8_t* out) {
coeff_t colidcts[kDCTBlockSize];
const int kColScale = 11;
const int kColRound = 1 << (kColScale - 1);
for (int x = 0; x < 8; ++x) {
int colbuf[8] = { 0 };
Compute1dIDCT(&block[x], 8, colbuf);
for (int y = 0; y < 8; ++y) {
colidcts[8 * y + x] = (colbuf[y] + kColRound) >> kColScale;
}
}
const int kRowScale = 18;
const int kRowRound = 257 << (kRowScale - 1); // includes offset by 128
for (int y = 0; y < 8; ++y) {
const int rowidx = 8 * y;
int rowbuf[8] = { 0 };
Compute1dIDCT(&colidcts[rowidx], 1, rowbuf);
for (int x = 0; x < 8; ++x) {
out[rowidx + x] =
std::max(0, std::min(255, (rowbuf[x] + kRowRound) >> kRowScale));
}
}
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/idct.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,829
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/output_image.h"
#include <algorithm>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <cstdlib>
#include "guetzli/idct.h"
#include "guetzli/color_transform.h"
#include "guetzli/dct_double.h"
#include "guetzli/gamma_correct.h"
#include "guetzli/preprocess_downsample.h"
#include "guetzli/quantize.h"
namespace guetzli {
OutputImageComponent::OutputImageComponent(int w, int h)
: width_(w), height_(h) {
Reset(1, 1);
}
void OutputImageComponent::Reset(int factor_x, int factor_y) {
factor_x_ = factor_x;
factor_y_ = factor_y;
width_in_blocks_ = (width_ + 8 * factor_x_ - 1) / (8 * factor_x_);
height_in_blocks_ = (height_ + 8 * factor_y_ - 1) / (8 * factor_y_);
num_blocks_ = width_in_blocks_ * height_in_blocks_;
coeffs_ = std::vector<coeff_t>(num_blocks_ * kDCTBlockSize);
pixels_ = std::vector<uint16_t>(width_ * height_, 128 << 4);
for (int i = 0; i < kDCTBlockSize; ++i) quant_[i] = 1;
}
bool OutputImageComponent::IsAllZero() const {
int numcoeffs = num_blocks_ * kDCTBlockSize;
for (int i = 0; i < numcoeffs; ++i) {
if (coeffs_[i] != 0) return false;
}
return true;
}
void OutputImageComponent::GetCoeffBlock(int block_x, int block_y,
coeff_t block[kDCTBlockSize]) const {
assert(block_x < width_in_blocks_);
assert(block_y < height_in_blocks_);
int offset = (block_y * width_in_blocks_ + block_x) * kDCTBlockSize;
memcpy(block, &coeffs_[offset], kDCTBlockSize * sizeof(coeffs_[0]));
}
void OutputImageComponent::ToPixels(int xmin, int ymin, int xsize, int ysize,
uint8_t* out, int stride) const {
assert(xmin >= 0);
assert(ymin >= 0);
assert(xmin < width_);
assert(ymin < height_);
const int yend1 = ymin + ysize;
const int yend0 = std::min(yend1, height_);
int y = ymin;
for (; y < yend0; ++y) {
const int xend1 = xmin + xsize;
const int xend0 = std::min(xend1, width_);
int x = xmin;
int px = y * width_ + xmin;
for (; x < xend0; ++x, ++px, out += stride) {
*out = static_cast<uint8_t>((pixels_[px] + 8 - (x & 1)) >> 4);
}
const int offset = -stride;
for (; x < xend1; ++x) {
*out = out[offset];
out += stride;
}
}
for (; y < yend1; ++y) {
const int offset = -stride * xsize;
for (int x = 0; x < xsize; ++x) {
*out = out[offset];
out += stride;
}
}
}
void OutputImageComponent::ToFloatPixels(float* out, int stride) const {
assert(factor_x_ == 1);
assert(factor_y_ == 1);
for (int block_y = 0; block_y < height_in_blocks_; ++block_y) {
for (int block_x = 0; block_x < width_in_blocks_; ++block_x) {
coeff_t block[kDCTBlockSize];
GetCoeffBlock(block_x, block_y, block);
double blockd[kDCTBlockSize];
for (int k = 0; k < kDCTBlockSize; ++k) {
blockd[k] = block[k];
}
ComputeBlockIDCTDouble(blockd);
for (int iy = 0; iy < 8; ++iy) {
for (int ix = 0; ix < 8; ++ix) {
int y = block_y * 8 + iy;
int x = block_x * 8 + ix;
if (y >= height_ || x >= width_) continue;
out[(y * width_ + x) * stride] = blockd[8 * iy + ix] + 128.0;
}
}
}
}
}
void OutputImageComponent::SetCoeffBlock(int block_x, int block_y,
const coeff_t block[kDCTBlockSize]) {
assert(block_x < width_in_blocks_);
assert(block_y < height_in_blocks_);
int offset = (block_y * width_in_blocks_ + block_x) * kDCTBlockSize;
memcpy(&coeffs_[offset], block, kDCTBlockSize * sizeof(coeffs_[0]));
uint8_t idct[kDCTBlockSize];
ComputeBlockIDCT(&coeffs_[offset], idct);
UpdatePixelsForBlock(block_x, block_y, idct);
}
void OutputImageComponent::UpdatePixelsForBlock(
int block_x, int block_y, const uint8_t idct[kDCTBlockSize]) {
if (factor_x_ == 1 && factor_y_ == 1) {
for (int iy = 0; iy < 8; ++iy) {
for (int ix = 0; ix < 8; ++ix) {
int x = 8 * block_x + ix;
int y = 8 * block_y + iy;
if (x >= width_ || y >= height_) continue;
int p = y * width_ + x;
pixels_[p] = idct[8 * iy + ix] << 4;
}
}
} else if (factor_x_ == 2 && factor_y_ == 2) {
// Fill in the 10x10 pixel area in the subsampled image that will be the
// basis of the upsampling. This area is enough to hold the 3x3 kernel of
// the fancy upsampler around each pixel.
static const int kSubsampledEdgeSize = 10;
uint16_t subsampled[kSubsampledEdgeSize * kSubsampledEdgeSize];
for (int j = 0; j < kSubsampledEdgeSize; ++j) {
// The order we fill in the rows is:
// 8 rows intersecting the block, row below, row above
const int y0 = block_y * 16 + (j < 9 ? j * 2 : -2);
for (int i = 0; i < kSubsampledEdgeSize; ++i) {
// The order we fill in each row is:
// 8 pixels within the block, left edge, right edge
const int ix = ((j < 9 ? (j + 1) * kSubsampledEdgeSize : 0) +
(i < 9 ? i + 1 : 0));
const int x0 = block_x * 16 + (i < 9 ? i * 2 : -2);
if (x0 < 0) {
subsampled[ix] = subsampled[ix + 1];
} else if (y0 < 0) {
subsampled[ix] = subsampled[ix + kSubsampledEdgeSize];
} else if (x0 >= width_) {
subsampled[ix] = subsampled[ix - 1];
} else if (y0 >= height_) {
subsampled[ix] = subsampled[ix - kSubsampledEdgeSize];
} else if (i < 8 && j < 8) {
subsampled[ix] = idct[j * 8 + i] << 4;
} else {
// Reconstruct the subsampled pixels around the edge of the current
// block by computing the inverse of the fancy upsampler.
const int y1 = std::max(y0 - 1, 0);
const int x1 = std::max(x0 - 1, 0);
subsampled[ix] = (pixels_[y0 * width_ + x0] * 9 +
pixels_[y1 * width_ + x1] +
pixels_[y0 * width_ + x1] * -3 +
pixels_[y1 * width_ + x0] * -3) >> 2;
}
}
}
// Determine area to update.
int xmin = std::max(block_x * 16 - 1, 0);
int xmax = std::min(block_x * 16 + 16, width_ - 1);
int ymin = std::max(block_y * 16 - 1, 0);
int ymax = std::min(block_y * 16 + 16, height_ - 1);
// Apply the fancy upsampler on the subsampled block.
for (int y = ymin; y <= ymax; ++y) {
const int y0 = ((y & ~1) / 2 - block_y * 8 + 1) * kSubsampledEdgeSize;
const int dy = ((y & 1) * 2 - 1) * kSubsampledEdgeSize;
uint16_t* rowptr = &pixels_[y * width_];
for (int x = xmin; x <= xmax; ++x) {
const int x0 = (x & ~1) / 2 - block_x * 8 + 1;
const int dx = (x & 1) * 2 - 1;
const int ix = x0 + y0;
rowptr[x] = (subsampled[ix] * 9 + subsampled[ix + dy] * 3 +
subsampled[ix + dx] * 3 + subsampled[ix + dx + dy]) >> 4;
}
}
} else {
printf("Sampling ratio not supported: factor_x = %d factor_y = %d\n",
factor_x_, factor_y_);
exit(1);
}
}
void OutputImageComponent::CopyFromJpegComponent(const JPEGComponent& comp,
int factor_x, int factor_y,
const int* quant) {
Reset(factor_x, factor_y);
assert(width_in_blocks_ <= comp.width_in_blocks);
assert(height_in_blocks_ <= comp.height_in_blocks);
const size_t src_row_size = comp.width_in_blocks * kDCTBlockSize;
for (int block_y = 0; block_y < height_in_blocks_; ++block_y) {
const coeff_t* src_coeffs = &comp.coeffs[block_y * src_row_size];
for (int block_x = 0; block_x < width_in_blocks_; ++block_x) {
coeff_t block[kDCTBlockSize];
for (int i = 0; i < kDCTBlockSize; ++i) {
block[i] = src_coeffs[i] * quant[i];
}
SetCoeffBlock(block_x, block_y, block);
src_coeffs += kDCTBlockSize;
}
}
memcpy(quant_, quant, sizeof(quant_));
}
void OutputImageComponent::ApplyGlobalQuantization(const int q[kDCTBlockSize]) {
for (int block_y = 0; block_y < height_in_blocks_; ++block_y) {
for (int block_x = 0; block_x < width_in_blocks_; ++block_x) {
coeff_t block[kDCTBlockSize];
GetCoeffBlock(block_x, block_y, block);
if (QuantizeBlock(block, q)) {
SetCoeffBlock(block_x, block_y, block);
}
}
}
memcpy(quant_, q, sizeof(quant_));
}
OutputImage::OutputImage(int w, int h)
: width_(w),
height_(h),
components_(3, OutputImageComponent(w, h)) {}
void OutputImage::CopyFromJpegData(const JPEGData& jpg) {
for (int i = 0; i < (int)jpg.components.size(); ++i) {
const JPEGComponent& comp = jpg.components[i];
assert(jpg.max_h_samp_factor % comp.h_samp_factor == 0);
assert(jpg.max_v_samp_factor % comp.v_samp_factor == 0);
int factor_x = jpg.max_h_samp_factor / comp.h_samp_factor;
int factor_y = jpg.max_v_samp_factor / comp.v_samp_factor;
assert(comp.quant_idx < (int)jpg.quant.size());
components_[i].CopyFromJpegComponent(comp, factor_x, factor_y,
&jpg.quant[comp.quant_idx].values[0]);
}
}
namespace {
void SetDownsampledCoefficients(const std::vector<float>& pixels,
int factor_x, int factor_y,
OutputImageComponent* comp) {
assert((int)pixels.size() == comp->width() * comp->height());
comp->Reset(factor_x, factor_y);
for (int block_y = 0; block_y < comp->height_in_blocks(); ++block_y) {
for (int block_x = 0; block_x < comp->width_in_blocks(); ++block_x) {
double blockd[kDCTBlockSize];
int x0 = 8 * block_x * factor_x;
int y0 = 8 * block_y * factor_y;
assert(x0 < comp->width());
assert(y0 < comp->height());
for (int iy = 0; iy < 8; ++iy) {
for (int ix = 0; ix < 8; ++ix) {
float avg = 0.0;
for (int j = 0; j < factor_y; ++j) {
for (int i = 0; i < factor_x; ++i) {
int x = std::min(x0 + ix * factor_x + i, comp->width() - 1);
int y = std::min(y0 + iy * factor_y + j, comp->height() - 1);
avg += pixels[y * comp->width() + x];
}
}
avg /= factor_x * factor_y;
blockd[iy * 8 + ix] = avg;
}
}
ComputeBlockDCTDouble(blockd);
blockd[0] -= 1024.0;
coeff_t block[kDCTBlockSize];
for (int k = 0; k < kDCTBlockSize; ++k) {
block[k] = static_cast<coeff_t>(std::round(blockd[k]));
}
comp->SetCoeffBlock(block_x, block_y, block);
}
}
}
} // namespace
void OutputImage::Downsample(const DownsampleConfig& cfg) {
if (components_[1].IsAllZero() && components_[2].IsAllZero()) {
// If the image is already grayscale, nothing to do.
return;
}
if (cfg.use_silver_screen &&
cfg.u_factor_x == 2 && cfg.u_factor_y == 2 &&
cfg.v_factor_x == 2 && cfg.v_factor_y == 2) {
std::vector<uint8_t> rgb = ToSRGB();
std::vector<std::vector<float> > yuv = RGBToYUV420(rgb, width_, height_);
SetDownsampledCoefficients(yuv[0], 1, 1, &components_[0]);
SetDownsampledCoefficients(yuv[1], 2, 2, &components_[1]);
SetDownsampledCoefficients(yuv[2], 2, 2, &components_[2]);
return;
}
// Get the floating-point precision YUV array represented by the set of
// DCT coefficients.
std::vector<std::vector<float> > yuv(3, std::vector<float>(width_ * height_));
for (int c = 0; c < 3; ++c) {
components_[c].ToFloatPixels(&yuv[c][0], 1);
}
yuv = PreProcessChannel(width_, height_, 2, 1.3, 0.5,
cfg.u_sharpen, cfg.u_blur, yuv);
yuv = PreProcessChannel(width_, height_, 1, 1.3, 0.5,
cfg.v_sharpen, cfg.v_blur, yuv);
// Do the actual downsampling (averaging) and forward-DCT.
if (cfg.u_factor_x != 1 || cfg.u_factor_y != 1) {
SetDownsampledCoefficients(yuv[1], cfg.u_factor_x, cfg.u_factor_y,
&components_[1]);
}
if (cfg.v_factor_x != 1 || cfg.v_factor_y != 1) {
SetDownsampledCoefficients(yuv[2], cfg.v_factor_x, cfg.v_factor_y,
&components_[2]);
}
}
void OutputImage::ApplyGlobalQuantization(const int q[3][kDCTBlockSize]) {
for (int c = 0; c < 3; ++c) {
components_[c].ApplyGlobalQuantization(&q[c][0]);
}
}
void OutputImage::SaveToJpegData(JPEGData* jpg) const {
assert(components_[0].factor_x() == 1);
assert(components_[0].factor_y() == 1);
jpg->width = width_;
jpg->height = height_;
jpg->max_h_samp_factor = 1;
jpg->max_v_samp_factor = 1;
jpg->MCU_cols = components_[0].width_in_blocks();
jpg->MCU_rows = components_[0].height_in_blocks();
int ncomp = components_[1].IsAllZero() && components_[2].IsAllZero() ? 1 : 3;
for (int i = 1; i < ncomp; ++i) {
jpg->max_h_samp_factor = std::max(jpg->max_h_samp_factor,
components_[i].factor_x());
jpg->max_v_samp_factor = std::max(jpg->max_h_samp_factor,
components_[i].factor_y());
jpg->MCU_cols = std::min(jpg->MCU_cols, components_[i].width_in_blocks());
jpg->MCU_rows = std::min(jpg->MCU_rows, components_[i].height_in_blocks());
}
jpg->components.resize(ncomp);
int q[3][kDCTBlockSize];
for (int c = 0; c < 3; ++c) {
memcpy(&q[c][0], components_[c].quant(), kDCTBlockSize * sizeof(q[0][0]));
}
for (int c = 0; c < ncomp; ++c) {
JPEGComponent* comp = &jpg->components[c];
assert(jpg->max_h_samp_factor % components_[c].factor_x() == 0);
assert(jpg->max_v_samp_factor % components_[c].factor_y() == 0);
comp->id = c;
comp->h_samp_factor = jpg->max_h_samp_factor / components_[c].factor_x();
comp->v_samp_factor = jpg->max_v_samp_factor / components_[c].factor_y();
comp->width_in_blocks = jpg->MCU_cols * comp->h_samp_factor;
comp->height_in_blocks = jpg->MCU_rows * comp->v_samp_factor;
comp->num_blocks = comp->width_in_blocks * comp->height_in_blocks;
comp->coeffs.resize(kDCTBlockSize * comp->num_blocks);
int last_dc = 0;
const coeff_t* src_coeffs = components_[c].coeffs();
coeff_t* dest_coeffs = &comp->coeffs[0];
for (int block_y = 0; block_y < comp->height_in_blocks; ++block_y) {
for (int block_x = 0; block_x < comp->width_in_blocks; ++block_x) {
if (block_y >= components_[c].height_in_blocks() ||
block_x >= components_[c].width_in_blocks()) {
dest_coeffs[0] = last_dc;
for (int k = 1; k < kDCTBlockSize; ++k) {
dest_coeffs[k] = 0;
}
} else {
for (int k = 0; k < kDCTBlockSize; ++k) {
const int quant = q[c][k];
int coeff = src_coeffs[k];
assert(coeff % quant == 0);
dest_coeffs[k] = coeff / quant;
}
src_coeffs += kDCTBlockSize;
}
last_dc = dest_coeffs[0];
dest_coeffs += kDCTBlockSize;
}
}
}
SaveQuantTables(q, jpg);
}
std::vector<uint8_t> OutputImage::ToSRGB(int xmin, int ymin,
int xsize, int ysize) const {
std::vector<uint8_t> rgb(xsize * ysize * 3);
for (int c = 0; c < 3; ++c) {
components_[c].ToPixels(xmin, ymin, xsize, ysize, &rgb[c], 3);
}
for (int p = 0; p < (int)rgb.size(); p += 3) {
ColorTransformYCbCrToRGB(&rgb[p]);
}
return rgb;
}
std::vector<uint8_t> OutputImage::ToSRGB() const {
return ToSRGB(0, 0, width_, height_);
}
void OutputImage::ToLinearRGB(int xmin, int ymin, int xsize, int ysize,
std::vector<std::vector<float> >* rgb) const {
const double* lut = Srgb8ToLinearTable();
std::vector<uint8_t> rgb_pixels = ToSRGB(xmin, ymin, xsize, ysize);
for (int p = 0; p < xsize * ysize; ++p) {
for (int i = 0; i < 3; ++i) {
(*rgb)[i][p] = lut[rgb_pixels[3 * p + i]];
}
}
}
void OutputImage::ToLinearRGB(std::vector<std::vector<float> >* rgb) const {
ToLinearRGB(0, 0, width_, height_, rgb);
}
std::string OutputImage::FrameTypeStr() const {
char buf[128];
int len = snprintf(buf, sizeof(buf), "f%d%d%d%d%d%d",
component(0).factor_x(), component(0).factor_y(),
component(1).factor_x(), component(1).factor_y(),
component(2).factor_x(), component(2).factor_y());
return std::string(buf, len);
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/output_image.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 5,057
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Entropy encoding (Huffman) utilities.
#include "guetzli/entropy_encode.h"
#include <assert.h>
#include <algorithm>
namespace guetzli {
bool SetDepth(int p0, HuffmanTree *pool, uint8_t *depth, int max_depth) {
int stack[17];
int level = 0;
int p = p0;
assert(max_depth <= 16);
stack[0] = -1;
while (true) {
if (pool[p].index_left_ >= 0) {
level++;
if (level > max_depth) return false;
stack[level] = pool[p].index_right_or_value_;
p = pool[p].index_left_;
continue;
} else {
depth[pool[p].index_right_or_value_] = static_cast<uint8_t>(level);
}
while (level >= 0 && stack[level] == -1) level--;
if (level < 0) return true;
p = stack[level];
stack[level] = -1;
}
}
// Sort the root nodes, least popular first.
static inline bool SortHuffmanTree(const HuffmanTree& v0,
const HuffmanTree& v1) {
if (v0.total_count_ != v1.total_count_) {
return v0.total_count_ < v1.total_count_;
}
return v0.index_right_or_value_ > v1.index_right_or_value_;
}
// This function will create a Huffman tree.
//
// The catch here is that the tree cannot be arbitrarily deep.
// Brotli specifies a maximum depth of 15 bits for "code trees"
// and 7 bits for "code length code trees."
//
// count_limit is the value that is to be faked as the minimum value
// and this minimum value is raised until the tree matches the
// maximum length requirement.
//
// This algorithm is not of excellent performance for very long data blocks,
// especially when population counts are longer than 2**tree_limit, but
// we are not planning to use this with extremely long blocks.
//
// See path_to_url
void CreateHuffmanTree(const uint32_t *data,
const size_t length,
const int tree_limit,
HuffmanTree* tree,
uint8_t *depth) {
// For block sizes below 64 kB, we never need to do a second iteration
// of this loop. Probably all of our block sizes will be smaller than
// that, so this loop is mostly of academic interest. If we actually
// would need this, we would be better off with the Katajainen algorithm.
for (uint32_t count_limit = 1; ; count_limit *= 2) {
size_t n = 0;
for (size_t i = length; i != 0;) {
--i;
if (data[i]) {
const uint32_t count = std::max<uint32_t>(data[i], count_limit);
tree[n++] = HuffmanTree(count, -1, static_cast<int16_t>(i));
}
}
if (n == 1) {
depth[tree[0].index_right_or_value_] = 1; // Only one element.
break;
}
std::sort(tree, tree + n, SortHuffmanTree);
// The nodes are:
// [0, n): the sorted leaf nodes that we start with.
// [n]: we add a sentinel here.
// [n + 1, 2n): new parent nodes are added here, starting from
// (n+1). These are naturally in ascending order.
// [2n]: we add a sentinel at the end as well.
// There will be (2n+1) elements at the end.
const HuffmanTree sentinel(~static_cast<uint32_t>(0), -1, -1);
tree[n] = sentinel;
tree[n + 1] = sentinel;
size_t i = 0; // Points to the next leaf node.
size_t j = n + 1; // Points to the next non-leaf node.
for (size_t k = n - 1; k != 0; --k) {
size_t left, right;
if (tree[i].total_count_ <= tree[j].total_count_) {
left = i;
++i;
} else {
left = j;
++j;
}
if (tree[i].total_count_ <= tree[j].total_count_) {
right = i;
++i;
} else {
right = j;
++j;
}
// The sentinel node becomes the parent node.
size_t j_end = 2 * n - k;
tree[j_end].total_count_ =
tree[left].total_count_ + tree[right].total_count_;
tree[j_end].index_left_ = static_cast<int16_t>(left);
tree[j_end].index_right_or_value_ = static_cast<int16_t>(right);
// Add back the last sentinel node.
tree[j_end + 1] = sentinel;
}
if (SetDepth(static_cast<int>(2 * n - 1), &tree[0], depth, tree_limit)) {
/* We need to pack the Huffman tree in tree_limit bits. If this was not
successful, add fake entities to the lowest values and retry. */
break;
}
}
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/entropy_encode.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,208
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/quality.h"
namespace guetzli {
namespace {
constexpr int kLowestQuality = 70;
constexpr int kHighestQuality = 110;
// Butteraugli scores that correspond to JPEG quality levels, starting at
// kLowestQuality. They were computed by taking median BA scores of JPEGs
// generated using libjpeg-turbo at given quality from a set of PNGs.
// The scores above quality level 100 are just linearly decreased so that score
// for 110 is 90% of the score for 100.
const double kScoreForQuality[] = {
2.810761, // 70
2.729300,
2.689687,
2.636811,
2.547863,
2.525400,
2.473416,
2.366133,
2.338078,
2.318654,
2.201674, // 80
2.145517,
2.087322,
2.009328,
1.945456,
1.900112,
1.805701,
1.750194,
1.644175,
1.562165,
1.473608, // 90
1.382021,
1.294298,
1.185402,
1.066781,
0.971769, // 95
0.852901,
0.724544,
0.611302,
0.443185,
0.211578, // 100
0.209462,
0.207346,
0.205230,
0.203114,
0.200999, // 105
0.198883,
0.196767,
0.194651,
0.192535,
0.190420, // 110
0.190420,
};
} // namespace
double ButteraugliScoreForQuality(double quality) {
if (quality < kLowestQuality) quality = kLowestQuality;
if (quality > kHighestQuality) quality = kHighestQuality;
int index = static_cast<int>(quality);
double mix = quality - index;
return kScoreForQuality[index - kLowestQuality] * (1 - mix) +
kScoreForQuality[index - kLowestQuality + 1] * mix;
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/quality.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 609
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/quantize.h"
namespace guetzli {
bool QuantizeBlock(coeff_t block[kDCTBlockSize],
const int q[kDCTBlockSize]) {
bool changed = false;
for (int k = 0; k < kDCTBlockSize; ++k) {
coeff_t coeff = Quantize(block[k], q[k]);
changed = changed || (coeff != block[k]);
block[k] = coeff;
}
return changed;
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/quantize.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 148
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Integer implementation of the Discrete Cosine Transform (DCT)
//
// Note! DCT output is kept scaled by 16, to retain maximum 16bit precision
#include "guetzli/fdct.h"
namespace guetzli {
namespace {
///////////////////////////////////////////////////////////////////////////////
// Cosine table: C(k) = cos(k.pi/16)/sqrt(2), k = 1..7 using 15 bits signed
const coeff_t kTable04[7] = { 22725, 21407, 19266, 16384, 12873, 8867, 4520 };
// rows #1 and #7 are pre-multiplied by 2.C(1) before the 2nd pass.
// This multiply is merged in the table of constants used during 1st pass:
const coeff_t kTable17[7] = { 31521, 29692, 26722, 22725, 17855, 12299, 6270 };
// rows #2 and #6 are pre-multiplied by 2.C(2):
const coeff_t kTable26[7] = { 29692, 27969, 25172, 21407, 16819, 11585, 5906 };
// rows #3 and #5 are pre-multiplied by 2.C(3):
const coeff_t kTable35[7] = { 26722, 25172, 22654, 19266, 15137, 10426, 5315 };
///////////////////////////////////////////////////////////////////////////////
// Constants (15bit precision) and C macros for IDCT vertical pass
#define kTan1 (13036) // = tan(pi/16)
#define kTan2 (27146) // = tan(2.pi/16) = sqrt(2) - 1.
#define kTan3m1 (-21746) // = tan(3.pi/16) - 1
#define k2Sqrt2 (23170) // = 1 / 2.sqrt(2)
// performs: {a,b} <- {a-b, a+b}, without saturation
#define BUTTERFLY(a, b) do { \
SUB((a), (b)); \
ADD((b), (b)); \
ADD((b), (a)); \
} while (0)
///////////////////////////////////////////////////////////////////////////////
// Constants for DCT horizontal pass
// Note about the CORRECT_LSB macro:
// using 16bit fixed-point constants, we often compute products like:
// p = (A*x + B*y + 32768) >> 16 by adding two sub-terms q = (A*x) >> 16
// and r = (B*y) >> 16 together. Statistically, we have p = q + r + 1
// in 3/4 of the cases. This can be easily seen from the relation:
// (a + b + 1) >> 1 = (a >> 1) + (b >> 1) + ((a|b)&1)
// The approximation we are doing is replacing ((a|b)&1) by 1.
// In practice, this is a slightly more involved because the constants A and B
// have also been rounded compared to their exact floating point value.
// However, all in all the correction is quite small, and CORRECT_LSB can
// be defined empty if needed.
#define COLUMN_DCT8(in) do { \
LOAD(m0, (in)[0 * 8]); \
LOAD(m2, (in)[2 * 8]); \
LOAD(m7, (in)[7 * 8]); \
LOAD(m5, (in)[5 * 8]); \
\
BUTTERFLY(m0, m7); \
BUTTERFLY(m2, m5); \
\
LOAD(m3, (in)[3 * 8]); \
LOAD(m4, (in)[4 * 8]); \
BUTTERFLY(m3, m4); \
\
LOAD(m6, (in)[6 * 8]); \
LOAD(m1, (in)[1 * 8]); \
BUTTERFLY(m1, m6); \
BUTTERFLY(m7, m4); \
BUTTERFLY(m6, m5); \
\
/* RowIdct() needs 15bits fixed-point input, when the output from */ \
/* ColumnIdct() would be 12bits. We are better doing the shift by 3 */ \
/* now instead of in RowIdct(), because we have some multiplies to */ \
/* perform, that can take advantage of the extra 3bits precision. */ \
LSHIFT(m4, 3); \
LSHIFT(m5, 3); \
BUTTERFLY(m4, m5); \
STORE16((in)[0 * 8], m5); \
STORE16((in)[4 * 8], m4); \
\
LSHIFT(m7, 3); \
LSHIFT(m6, 3); \
LSHIFT(m3, 3); \
LSHIFT(m0, 3); \
\
LOAD_CST(m4, kTan2); \
m5 = m4; \
MULT(m4, m7); \
MULT(m5, m6); \
SUB(m4, m6); \
ADD(m5, m7); \
STORE16((in)[2 * 8], m5); \
STORE16((in)[6 * 8], m4); \
\
/* We should be multiplying m6 by C4 = 1/sqrt(2) here, but we only have */ \
/* the k2Sqrt2 = 1/(2.sqrt(2)) constant that fits into 15bits. So we */ \
/* shift by 4 instead of 3 to compensate for the additional 1/2 factor. */ \
LOAD_CST(m6, k2Sqrt2); \
LSHIFT(m2, 3 + 1); \
LSHIFT(m1, 3 + 1); \
BUTTERFLY(m1, m2); \
MULT(m2, m6); \
MULT(m1, m6); \
BUTTERFLY(m3, m1); \
BUTTERFLY(m0, m2); \
\
LOAD_CST(m4, kTan3m1); \
LOAD_CST(m5, kTan1); \
m7 = m3; \
m6 = m1; \
MULT(m3, m4); \
MULT(m1, m5); \
\
ADD(m3, m7); \
ADD(m1, m2); \
CORRECT_LSB(m1); \
CORRECT_LSB(m3); \
MULT(m4, m0); \
MULT(m5, m2); \
ADD(m4, m0); \
SUB(m0, m3); \
ADD(m7, m4); \
SUB(m5, m6); \
\
STORE16((in)[1 * 8], m1); \
STORE16((in)[3 * 8], m0); \
STORE16((in)[5 * 8], m7); \
STORE16((in)[7 * 8], m5); \
} while (0)
// these are the macro required by COLUMN_*
#define LOAD_CST(dst, src) (dst) = (src)
#define LOAD(dst, src) (dst) = (src)
#define MULT(a, b) (a) = (((a) * (b)) >> 16)
#define ADD(a, b) (a) = (a) + (b)
#define SUB(a, b) (a) = (a) - (b)
#define LSHIFT(a, n) (a) = ((a) << (n))
#define STORE16(a, b) (a) = (b)
#define CORRECT_LSB(a) (a) += 1
// DCT vertical pass
inline void ColumnDct(coeff_t* in) {
for (int i = 0; i < 8; ++i) {
int m0, m1, m2, m3, m4, m5, m6, m7;
COLUMN_DCT8(in + i);
}
}
// DCT horizontal pass
// We don't really need to round before descaling, since we
// still have 4 bits of precision left as final scaled output.
#define DESCALE(a) static_cast<coeff_t>((a) >> 16)
void RowDct(coeff_t* in, const coeff_t* table) {
// The Fourier transform is an unitary operator, so we're basically
// doing the transpose of RowIdct()
const int a0 = in[0] + in[7];
const int b0 = in[0] - in[7];
const int a1 = in[1] + in[6];
const int b1 = in[1] - in[6];
const int a2 = in[2] + in[5];
const int b2 = in[2] - in[5];
const int a3 = in[3] + in[4];
const int b3 = in[3] - in[4];
// even part
const int C2 = table[1];
const int C4 = table[3];
const int C6 = table[5];
const int c0 = a0 + a3;
const int c1 = a0 - a3;
const int c2 = a1 + a2;
const int c3 = a1 - a2;
in[0] = DESCALE(C4 * (c0 + c2));
in[4] = DESCALE(C4 * (c0 - c2));
in[2] = DESCALE(C2 * c1 + C6 * c3);
in[6] = DESCALE(C6 * c1 - C2 * c3);
// odd part
const int C1 = table[0];
const int C3 = table[2];
const int C5 = table[4];
const int C7 = table[6];
in[1] = DESCALE(C1 * b0 + C3 * b1 + C5 * b2 + C7 * b3);
in[3] = DESCALE(C3 * b0 - C7 * b1 - C1 * b2 - C5 * b3);
in[5] = DESCALE(C5 * b0 - C1 * b1 + C7 * b2 + C3 * b3);
in[7] = DESCALE(C7 * b0 - C5 * b1 + C3 * b2 - C1 * b3);
}
#undef DESCALE
#undef LOAD_CST
#undef LOAD
#undef MULT
#undef ADD
#undef SUB
#undef LSHIFT
#undef STORE16
#undef CORRECT_LSB
#undef kTan1
#undef kTan2
#undef kTan3m1
#undef k2Sqrt2
#undef BUTTERFLY
#undef COLUMN_DCT8
} // namespace
///////////////////////////////////////////////////////////////////////////////
// visible FDCT callable functions
void ComputeBlockDCT(coeff_t* coeffs) {
ColumnDct(coeffs);
RowDct(coeffs + 0 * 8, kTable04);
RowDct(coeffs + 1 * 8, kTable17);
RowDct(coeffs + 2 * 8, kTable26);
RowDct(coeffs + 3 * 8, kTable35);
RowDct(coeffs + 4 * 8, kTable04);
RowDct(coeffs + 5 * 8, kTable35);
RowDct(coeffs + 6 * 8, kTable26);
RowDct(coeffs + 7 * 8, kTable17);
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/fdct.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 2,685
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/jpeg_data_decoder.h"
#include "guetzli/output_image.h"
namespace guetzli {
// Mimic libjpeg's heuristics to guess jpeg color space.
// Requires that the jpg has 3 components.
bool HasYCbCrColorSpace(const JPEGData& jpg) {
bool has_Adobe_marker = false;
uint8_t Adobe_transform = 0;
for (const std::string& app : jpg.app_data) {
if (static_cast<uint8_t>(app[0]) == 0xe0) {
return true;
} else if (static_cast<uint8_t>(app[0]) == 0xee && app.size() >= 15) {
has_Adobe_marker = true;
Adobe_transform = app[14];
}
}
if (has_Adobe_marker) {
return (Adobe_transform != 0);
}
const int cid0 = jpg.components[0].id;
const int cid1 = jpg.components[1].id;
const int cid2 = jpg.components[2].id;
return (cid0 != 'R' || cid1 != 'G' || cid2 != 'B');
}
std::vector<uint8_t> DecodeJpegToRGB(const JPEGData& jpg) {
if (jpg.components.size() == 1 ||
(jpg.components.size() == 3 &&
HasYCbCrColorSpace(jpg) && (jpg.Is420() || jpg.Is444()))) {
OutputImage img(jpg.width, jpg.height);
img.CopyFromJpegData(jpg);
return img.ToSRGB();
}
return std::vector<uint8_t>();
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/jpeg_data_decoder.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 401
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/jpeg_data_reader.h"
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include "guetzli/jpeg_huffman_decode.h"
namespace guetzli {
namespace {
// Macros for commonly used error conditions.
#define VERIFY_LEN(n) \
if (*pos + (n) > len) { \
fprintf(stderr, "Unexpected end of input: pos=%d need=%d len=%d\n", \
static_cast<int>(*pos), static_cast<int>(n), \
static_cast<int>(len)); \
jpg->error = JPEG_UNEXPECTED_EOF; \
return false; \
}
#define VERIFY_INPUT(var, low, high, code) \
if (var < low || var > high) { \
fprintf(stderr, "Invalid %s: %d\n", #var, static_cast<int>(var)); \
jpg->error = JPEG_INVALID_ ## code; \
return false; \
}
#define VERIFY_MARKER_END() \
if (start_pos + marker_len != *pos) { \
fprintf(stderr, "Invalid marker length: declared=%d actual=%d\n", \
static_cast<int>(marker_len), \
static_cast<int>(*pos - start_pos)); \
jpg->error = JPEG_WRONG_MARKER_SIZE; \
return false; \
}
#define EXPECT_MARKER() \
if (pos + 2 > len || data[pos] != 0xff) { \
fprintf(stderr, "Marker byte (0xff) expected, found: %d " \
"pos=%d len=%d\n", \
(pos < len ? data[pos] : 0), static_cast<int>(pos), \
static_cast<int>(len)); \
jpg->error = JPEG_MARKER_BYTE_NOT_FOUND; \
return false; \
}
// Returns ceil(a/b).
inline int DivCeil(int a, int b) {
return (a + b - 1) / b;
}
inline int ReadUint8(const uint8_t* data, size_t* pos) {
return data[(*pos)++];
}
inline int ReadUint16(const uint8_t* data, size_t* pos) {
int v = (data[*pos] << 8) + data[*pos + 1];
*pos += 2;
return v;
}
// Reads the Start of Frame (SOF) marker segment and fills in *jpg with the
// parsed data.
bool ProcessSOF(const uint8_t* data, const size_t len,
JpegReadMode mode, size_t* pos, JPEGData* jpg) {
if (jpg->width != 0) {
fprintf(stderr, "Duplicate SOF marker.\n");
jpg->error = JPEG_DUPLICATE_SOF;
return false;
}
const size_t start_pos = *pos;
VERIFY_LEN(8);
size_t marker_len = ReadUint16(data, pos);
int precision = ReadUint8(data, pos);
int height = ReadUint16(data, pos);
int width = ReadUint16(data, pos);
int num_components = ReadUint8(data, pos);
VERIFY_INPUT(precision, 8, 8, PRECISION);
VERIFY_INPUT(height, 1, 65535, HEIGHT);
VERIFY_INPUT(width, 1, 65535, WIDTH);
VERIFY_INPUT(num_components, 1, kMaxComponents, NUMCOMP);
VERIFY_LEN(3 * num_components);
jpg->height = height;
jpg->width = width;
jpg->components.resize(num_components);
// Read sampling factors and quant table index for each component.
std::vector<bool> ids_seen(256, false);
for (int i = 0; i < (int)jpg->components.size(); ++i) {
const int id = ReadUint8(data, pos);
if (ids_seen[id]) { // (cf. section B.2.2, syntax of Ci)
fprintf(stderr, "Duplicate ID %d in SOF.\n", id);
jpg->error = JPEG_DUPLICATE_COMPONENT_ID;
return false;
}
ids_seen[id] = true;
jpg->components[i].id = id;
int factor = ReadUint8(data, pos);
int h_samp_factor = factor >> 4;
int v_samp_factor = factor & 0xf;
VERIFY_INPUT(h_samp_factor, 1, 15, SAMP_FACTOR);
VERIFY_INPUT(v_samp_factor, 1, 15, SAMP_FACTOR);
jpg->components[i].h_samp_factor = h_samp_factor;
jpg->components[i].v_samp_factor = v_samp_factor;
jpg->components[i].quant_idx = ReadUint8(data, pos);
jpg->max_h_samp_factor = std::max(jpg->max_h_samp_factor, h_samp_factor);
jpg->max_v_samp_factor = std::max(jpg->max_v_samp_factor, v_samp_factor);
}
// We have checked above that none of the sampling factors are 0, so the max
// sampling factors can not be 0.
jpg->MCU_rows = DivCeil(jpg->height, jpg->max_v_samp_factor * 8);
jpg->MCU_cols = DivCeil(jpg->width, jpg->max_h_samp_factor * 8);
// Compute the block dimensions for each component.
if (mode == JPEG_READ_ALL) {
for (int i = 0; i < (int)jpg->components.size(); ++i) {
JPEGComponent* c = &jpg->components[i];
if (jpg->max_h_samp_factor % c->h_samp_factor != 0 ||
jpg->max_v_samp_factor % c->v_samp_factor != 0) {
fprintf(stderr, "Non-integral subsampling ratios.\n");
jpg->error = JPEG_INVALID_SAMPLING_FACTORS;
return false;
}
c->width_in_blocks = jpg->MCU_cols * c->h_samp_factor;
c->height_in_blocks = jpg->MCU_rows * c->v_samp_factor;
const uint64_t num_blocks =
static_cast<uint64_t>(c->width_in_blocks) * c->height_in_blocks;
if (num_blocks > (1ull << 21)) {
// Refuse to allocate more than 1 GB of memory for the coefficients,
// that is 2M blocks x 64 coeffs x 2 bytes per coeff x max 4 components.
// TODO(user) Add this limit to a GuetzliParams struct.
fprintf(stderr, "Image too large.\n");
jpg->error = JPEG_IMAGE_TOO_LARGE;
return false;
}
c->num_blocks = static_cast<int>(num_blocks);
c->coeffs.resize(c->num_blocks * kDCTBlockSize);
}
}
VERIFY_MARKER_END();
return true;
}
// Reads the Start of Scan (SOS) marker segment and fills in *scan_info with the
// parsed data.
bool ProcessSOS(const uint8_t* data, const size_t len, size_t* pos,
JPEGData* jpg) {
const size_t start_pos = *pos;
VERIFY_LEN(3);
size_t marker_len = ReadUint16(data, pos);
int comps_in_scan = ReadUint8(data, pos);
VERIFY_INPUT(comps_in_scan, 1, (int)jpg->components.size(), COMPS_IN_SCAN);
JPEGScanInfo scan_info;
scan_info.components.resize(comps_in_scan);
VERIFY_LEN(2 * comps_in_scan);
std::vector<bool> ids_seen(256, false);
for (int i = 0; i < comps_in_scan; ++i) {
int id = ReadUint8(data, pos);
if (ids_seen[id]) { // (cf. section B.2.3, regarding CSj)
fprintf(stderr, "Duplicate ID %d in SOS.\n", id);
jpg->error = JPEG_DUPLICATE_COMPONENT_ID;
return false;
}
ids_seen[id] = true;
bool found_index = false;
for (int j = 0; j < (int)jpg->components.size(); ++j) {
if (jpg->components[j].id == id) {
scan_info.components[i].comp_idx = j;
found_index = true;
}
}
if (!found_index) {
fprintf(stderr, "SOS marker: Could not find component with id %d\n", id);
jpg->error = JPEG_COMPONENT_NOT_FOUND;
return false;
}
int c = ReadUint8(data, pos);
int dc_tbl_idx = c >> 4;
int ac_tbl_idx = c & 0xf;
VERIFY_INPUT(dc_tbl_idx, 0, 3, HUFFMAN_INDEX);
VERIFY_INPUT(ac_tbl_idx, 0, 3, HUFFMAN_INDEX);
scan_info.components[i].dc_tbl_idx = dc_tbl_idx;
scan_info.components[i].ac_tbl_idx = ac_tbl_idx;
}
VERIFY_LEN(3);
scan_info.Ss = ReadUint8(data, pos);
scan_info.Se = ReadUint8(data, pos);
VERIFY_INPUT(scan_info.Ss, 0, 63, START_OF_SCAN);
VERIFY_INPUT(scan_info.Se, scan_info.Ss, 63, END_OF_SCAN);
int c = ReadUint8(data, pos);
scan_info.Ah = c >> 4;
scan_info.Al = c & 0xf;
// Check that all the Huffman tables needed for this scan are defined.
for (int i = 0; i < comps_in_scan; ++i) {
bool found_dc_table = false;
bool found_ac_table = false;
for (int j = 0; j < (int)jpg->huffman_code.size(); ++j) {
int slot_id = jpg->huffman_code[j].slot_id;
if (slot_id == scan_info.components[i].dc_tbl_idx) {
found_dc_table = true;
} else if (slot_id == scan_info.components[i].ac_tbl_idx + 16) {
found_ac_table = true;
}
}
if (scan_info.Ss == 0 && !found_dc_table) {
fprintf(stderr, "SOS marker: Could not find DC Huffman table with index "
"%d\n", scan_info.components[i].dc_tbl_idx);
jpg->error = JPEG_HUFFMAN_TABLE_NOT_FOUND;
return false;
}
if (scan_info.Se > 0 && !found_ac_table) {
fprintf(stderr, "SOS marker: Could not find AC Huffman table with index "
"%d\n", scan_info.components[i].ac_tbl_idx);
jpg->error = JPEG_HUFFMAN_TABLE_NOT_FOUND;
return false;
}
}
jpg->scan_info.push_back(scan_info);
VERIFY_MARKER_END();
return true;
}
// Reads the Define Huffman Table (DHT) marker segment and fills in *jpg with
// the parsed data. Builds the Huffman decoding table in either dc_huff_lut or
// ac_huff_lut, depending on the type and solt_id of Huffman code being read.
bool ProcessDHT(const uint8_t* data, const size_t len,
JpegReadMode mode,
std::vector<HuffmanTableEntry>* dc_huff_lut,
std::vector<HuffmanTableEntry>* ac_huff_lut,
size_t* pos,
JPEGData* jpg) {
const size_t start_pos = *pos;
VERIFY_LEN(2);
size_t marker_len = ReadUint16(data, pos);
if (marker_len == 2) {
fprintf(stderr, "DHT marker: no Huffman table found\n");
jpg->error = JPEG_EMPTY_DHT;
return false;
}
while (*pos < start_pos + marker_len) {
VERIFY_LEN(1 + kJpegHuffmanMaxBitLength);
JPEGHuffmanCode huff;
huff.slot_id = ReadUint8(data, pos);
int huffman_index = huff.slot_id;
int is_ac_table = (huff.slot_id & 0x10) != 0;
HuffmanTableEntry* huff_lut;
if (is_ac_table) {
huffman_index -= 0x10;
VERIFY_INPUT(huffman_index, 0, 3, HUFFMAN_INDEX);
huff_lut = &(*ac_huff_lut)[huffman_index * kJpegHuffmanLutSize];
} else {
VERIFY_INPUT(huffman_index, 0, 3, HUFFMAN_INDEX);
huff_lut = &(*dc_huff_lut)[huffman_index * kJpegHuffmanLutSize];
}
huff.counts[0] = 0;
int total_count = 0;
int space = 1 << kJpegHuffmanMaxBitLength;
int max_depth = 1;
for (int i = 1; i <= kJpegHuffmanMaxBitLength; ++i) {
int count = ReadUint8(data, pos);
if (count != 0) {
max_depth = i;
}
huff.counts[i] = count;
total_count += count;
space -= count * (1 << (kJpegHuffmanMaxBitLength - i));
}
if (is_ac_table) {
VERIFY_INPUT(total_count, 0, kJpegHuffmanAlphabetSize, HUFFMAN_CODE);
} else {
VERIFY_INPUT(total_count, 0, kJpegDCAlphabetSize, HUFFMAN_CODE);
}
VERIFY_LEN(total_count);
std::vector<bool> values_seen(256, false);
for (int i = 0; i < total_count; ++i) {
uint8_t value = ReadUint8(data, pos);
if (!is_ac_table) {
VERIFY_INPUT(value, 0, kJpegDCAlphabetSize - 1, HUFFMAN_CODE);
}
if (values_seen[value]) {
fprintf(stderr, "Duplicate Huffman code value %d\n", value);
jpg->error = JPEG_INVALID_HUFFMAN_CODE;
return false;
}
values_seen[value] = true;
huff.values[i] = value;
}
// Add an invalid symbol that will have the all 1 code.
++huff.counts[max_depth];
huff.values[total_count] = kJpegHuffmanAlphabetSize;
space -= (1 << (kJpegHuffmanMaxBitLength - max_depth));
if (space < 0) {
fprintf(stderr, "Invalid Huffman code lengths.\n");
jpg->error = JPEG_INVALID_HUFFMAN_CODE;
return false;
} else if (space > 0 && huff_lut[0].value != 0xffff) {
// Re-initialize the values to an invalid symbol so that we can recognize
// it when reading the bit stream using a Huffman code with space > 0.
for (int i = 0; i < kJpegHuffmanLutSize; ++i) {
huff_lut[i].bits = 0;
huff_lut[i].value = 0xffff;
}
}
huff.is_last = (*pos == start_pos + marker_len);
if (mode == JPEG_READ_ALL &&
!BuildJpegHuffmanTable(&huff.counts[0], &huff.values[0], huff_lut)) {
fprintf(stderr, "Failed to build Huffman table.\n");
jpg->error = JPEG_INVALID_HUFFMAN_CODE;
return false;
}
jpg->huffman_code.push_back(huff);
}
VERIFY_MARKER_END();
return true;
}
// Reads the Define Quantization Table (DQT) marker segment and fills in *jpg
// with the parsed data.
bool ProcessDQT(const uint8_t* data, const size_t len, size_t* pos,
JPEGData* jpg) {
const size_t start_pos = *pos;
VERIFY_LEN(2);
size_t marker_len = ReadUint16(data, pos);
if (marker_len == 2) {
fprintf(stderr, "DQT marker: no quantization table found\n");
jpg->error = JPEG_EMPTY_DQT;
return false;
}
while (*pos < start_pos + marker_len && jpg->quant.size() < kMaxQuantTables) {
VERIFY_LEN(1);
int quant_table_index = ReadUint8(data, pos);
int quant_table_precision = quant_table_index >> 4;
quant_table_index &= 0xf;
VERIFY_INPUT(quant_table_index, 0, 3, QUANT_TBL_INDEX);
VERIFY_LEN((quant_table_precision ? 2 : 1) * kDCTBlockSize);
JPEGQuantTable table;
table.index = quant_table_index;
table.precision = quant_table_precision;
for (int i = 0; i < kDCTBlockSize; ++i) {
int quant_val = quant_table_precision ?
ReadUint16(data, pos) :
ReadUint8(data, pos);
VERIFY_INPUT(quant_val, 1, 65535, QUANT_VAL);
table.values[kJPEGNaturalOrder[i]] = quant_val;
}
table.is_last = (*pos == start_pos + marker_len);
jpg->quant.push_back(table);
}
VERIFY_MARKER_END();
return true;
}
// Reads the DRI marker and saved the restart interval into *jpg.
bool ProcessDRI(const uint8_t* data, const size_t len, size_t* pos,
JPEGData* jpg) {
if (jpg->restart_interval > 0) {
fprintf(stderr, "Duplicate DRI marker.\n");
jpg->error = JPEG_DUPLICATE_DRI;
return false;
}
const size_t start_pos = *pos;
VERIFY_LEN(4);
size_t marker_len = ReadUint16(data, pos);
int restart_interval = ReadUint16(data, pos);
jpg->restart_interval = restart_interval;
VERIFY_MARKER_END();
return true;
}
// Saves the APP marker segment as a string to *jpg.
bool ProcessAPP(const uint8_t* data, const size_t len, size_t* pos,
JPEGData* jpg) {
VERIFY_LEN(2);
size_t marker_len = ReadUint16(data, pos);
VERIFY_INPUT(marker_len, 2, 65535, MARKER_LEN);
VERIFY_LEN(marker_len - 2);
// Save the marker type together with the app data.
std::string app_str(reinterpret_cast<const char*>(
&data[*pos - 3]), marker_len + 1);
*pos += marker_len - 2;
jpg->app_data.push_back(app_str);
return true;
}
// Saves the COM marker segment as a string to *jpg.
bool ProcessCOM(const uint8_t* data, const size_t len, size_t* pos,
JPEGData* jpg) {
VERIFY_LEN(2);
size_t marker_len = ReadUint16(data, pos);
VERIFY_INPUT(marker_len, 2, 65535, MARKER_LEN);
VERIFY_LEN(marker_len - 2);
std::string com_str(reinterpret_cast<const char*>(
&data[*pos - 2]), marker_len);
*pos += marker_len - 2;
jpg->com_data.push_back(com_str);
return true;
}
// Helper structure to read bits from the entropy coded data segment.
struct BitReaderState {
BitReaderState(const uint8_t* data, const size_t len, size_t pos)
: data_(data), len_(len) {
Reset(pos);
}
void Reset(size_t pos) {
pos_ = pos;
val_ = 0;
bits_left_ = 0;
next_marker_pos_ = len_ - 2;
FillBitWindow();
}
// Returns the next byte and skips the 0xff/0x00 escape sequences.
uint8_t GetNextByte() {
if (pos_ >= next_marker_pos_) {
++pos_;
return 0;
}
uint8_t c = data_[pos_++];
if (c == 0xff) {
uint8_t escape = data_[pos_];
if (escape == 0) {
++pos_;
} else {
// 0xff was followed by a non-zero byte, which means that we found the
// start of the next marker segment.
next_marker_pos_ = pos_ - 1;
}
}
return c;
}
void FillBitWindow() {
if (bits_left_ <= 16) {
while (bits_left_ <= 56) {
val_ <<= 8;
val_ |= (uint64_t)GetNextByte();
bits_left_ += 8;
}
}
}
int ReadBits(int nbits) {
FillBitWindow();
uint64_t val = (val_ >> (bits_left_ - nbits)) & ((1ULL << nbits) - 1);
bits_left_ -= nbits;
return val;
}
// Sets *pos to the next stream position where parsing should continue.
// Returns false if the stream ended too early.
bool FinishStream(size_t* pos) {
// Give back some bytes that we did not use.
int unused_bytes_left = bits_left_ >> 3;
while (unused_bytes_left-- > 0) {
--pos_;
// If we give back a 0 byte, we need to check if it was a 0xff/0x00 escape
// sequence, and if yes, we need to give back one more byte.
if (pos_ < next_marker_pos_ &&
data_[pos_] == 0 && data_[pos_ - 1] == 0xff) {
--pos_;
}
}
if (pos_ > next_marker_pos_) {
// Data ran out before the scan was complete.
fprintf(stderr, "Unexpected end of scan.\n");
return false;
}
*pos = pos_;
return true;
}
const uint8_t* data_;
const size_t len_;
size_t pos_;
uint64_t val_;
int bits_left_;
size_t next_marker_pos_;
};
// Returns the next Huffman-coded symbol.
int ReadSymbol(const HuffmanTableEntry* table, BitReaderState* br) {
int nbits;
br->FillBitWindow();
int val = (br->val_ >> (br->bits_left_ - 8)) & 0xff;
table += val;
nbits = table->bits - 8;
if (nbits > 0) {
br->bits_left_ -= 8;
table += table->value;
val = (br->val_ >> (br->bits_left_ - nbits)) & ((1 << nbits) - 1);
table += val;
}
br->bits_left_ -= table->bits;
return table->value;
}
// Returns the DC diff or AC value for extra bits value x and prefix code s.
// See Tables F.1 and F.2 of the spec.
int HuffExtend(int x, int s) {
return (x < (1 << (s - 1)) ? x + ((-1) << s ) + 1 : x);
}
// Decodes one 8x8 block of DCT coefficients from the bit stream.
bool DecodeDCTBlock(const HuffmanTableEntry* dc_huff,
const HuffmanTableEntry* ac_huff,
int Ss, int Se, int Al,
int* eobrun,
BitReaderState* br,
JPEGData* jpg,
coeff_t* last_dc_coeff,
coeff_t* coeffs) {
int s;
int r;
bool eobrun_allowed = Ss > 0;
if (Ss == 0) {
s = ReadSymbol(dc_huff, br);
if (s >= kJpegDCAlphabetSize) {
fprintf(stderr, "Invalid Huffman symbol %d for DC coefficient.\n", s);
jpg->error = JPEG_INVALID_SYMBOL;
return false;
}
if (s > 0) {
r = br->ReadBits(s);
s = HuffExtend(r, s);
}
s += *last_dc_coeff;
const int dc_coeff = s << Al;
coeffs[0] = dc_coeff;
if (dc_coeff != coeffs[0]) {
fprintf(stderr, "Invalid DC coefficient %d\n", dc_coeff);
jpg->error = JPEG_NON_REPRESENTABLE_DC_COEFF;
return false;
}
*last_dc_coeff = s;
++Ss;
}
if (Ss > Se) {
return true;
}
if (*eobrun > 0) {
--(*eobrun);
return true;
}
for (int k = Ss; k <= Se; k++) {
s = ReadSymbol(ac_huff, br);
if (s >= kJpegHuffmanAlphabetSize) {
fprintf(stderr, "Invalid Huffman symbol %d for AC coefficient %d\n",
s, k);
jpg->error = JPEG_INVALID_SYMBOL;
return false;
}
r = s >> 4;
s &= 15;
if (s > 0) {
k += r;
if (k > Se) {
fprintf(stderr, "Out-of-band coefficient %d band was %d-%d\n",
k, Ss, Se);
jpg->error = JPEG_OUT_OF_BAND_COEFF;
return false;
}
if (s + Al >= kJpegDCAlphabetSize) {
fprintf(stderr, "Out of range AC coefficient value: s=%d Al=%d k=%d\n",
s, Al, k);
jpg->error = JPEG_NON_REPRESENTABLE_AC_COEFF;
return false;
}
r = br->ReadBits(s);
s = HuffExtend(r, s);
coeffs[kJPEGNaturalOrder[k]] = s << Al;
} else if (r == 15) {
k += 15;
} else {
*eobrun = 1 << r;
if (r > 0) {
if (!eobrun_allowed) {
fprintf(stderr, "End-of-block run crossing DC coeff.\n");
jpg->error = JPEG_EOB_RUN_TOO_LONG;
return false;
}
*eobrun += br->ReadBits(r);
}
break;
}
}
--(*eobrun);
return true;
}
bool RefineDCTBlock(const HuffmanTableEntry* ac_huff,
int Ss, int Se, int Al,
int* eobrun,
BitReaderState* br,
JPEGData* jpg,
coeff_t* coeffs) {
bool eobrun_allowed = Ss > 0;
if (Ss == 0) {
int s = br->ReadBits(1);
coeff_t dc_coeff = coeffs[0];
dc_coeff |= s << Al;
coeffs[0] = dc_coeff;
++Ss;
}
if (Ss > Se) {
return true;
}
int p1 = 1 << Al;
int m1 = (-1) << Al;
int k = Ss;
int r;
int s;
bool in_zero_run = false;
if (*eobrun <= 0) {
for (; k <= Se; k++) {
s = ReadSymbol(ac_huff, br);
if (s >= kJpegHuffmanAlphabetSize) {
fprintf(stderr, "Invalid Huffman symbol %d for AC coefficient %d\n",
s, k);
jpg->error = JPEG_INVALID_SYMBOL;
return false;
}
r = s >> 4;
s &= 15;
if (s) {
if (s != 1) {
fprintf(stderr, "Invalid Huffman symbol %d for AC coefficient %d\n",
s, k);
jpg->error = JPEG_INVALID_SYMBOL;
return false;
}
s = br->ReadBits(1) ? p1 : m1;
in_zero_run = false;
} else {
if (r != 15) {
*eobrun = 1 << r;
if (r > 0) {
if (!eobrun_allowed) {
fprintf(stderr, "End-of-block run crossing DC coeff.\n");
jpg->error = JPEG_EOB_RUN_TOO_LONG;
return false;
}
*eobrun += br->ReadBits(r);
}
break;
}
in_zero_run = true;
}
do {
coeff_t thiscoef = coeffs[kJPEGNaturalOrder[k]];
if (thiscoef != 0) {
if (br->ReadBits(1)) {
if ((thiscoef & p1) == 0) {
if (thiscoef >= 0) {
thiscoef += p1;
} else {
thiscoef += m1;
}
}
}
coeffs[kJPEGNaturalOrder[k]] = thiscoef;
} else {
if (--r < 0) {
break;
}
}
k++;
} while (k <= Se);
if (s) {
if (k > Se) {
fprintf(stderr, "Out-of-band coefficient %d band was %d-%d\n",
k, Ss, Se);
jpg->error = JPEG_OUT_OF_BAND_COEFF;
return false;
}
coeffs[kJPEGNaturalOrder[k]] = s;
}
}
}
if (in_zero_run) {
fprintf(stderr, "Extra zero run before end-of-block.\n");
jpg->error = JPEG_EXTRA_ZERO_RUN;
return false;
}
if (*eobrun > 0) {
for (; k <= Se; k++) {
coeff_t thiscoef = coeffs[kJPEGNaturalOrder[k]];
if (thiscoef != 0) {
if (br->ReadBits(1)) {
if ((thiscoef & p1) == 0) {
if (thiscoef >= 0) {
thiscoef += p1;
} else {
thiscoef += m1;
}
}
}
coeffs[kJPEGNaturalOrder[k]] = thiscoef;
}
}
}
--(*eobrun);
return true;
}
bool ProcessRestart(const uint8_t* data, const size_t len,
int* next_restart_marker, BitReaderState* br,
JPEGData* jpg) {
size_t pos = 0;
if (!br->FinishStream(&pos)) {
jpg->error = JPEG_INVALID_SCAN;
return false;
}
int expected_marker = 0xd0 + *next_restart_marker;
EXPECT_MARKER();
int marker = data[pos + 1];
if (marker != expected_marker) {
fprintf(stderr, "Did not find expected restart marker %d actual=%d\n",
expected_marker, marker);
jpg->error = JPEG_WRONG_RESTART_MARKER;
return false;
}
br->Reset(pos + 2);
*next_restart_marker += 1;
*next_restart_marker &= 0x7;
return true;
}
bool ProcessScan(const uint8_t* data, const size_t len,
const std::vector<HuffmanTableEntry>& dc_huff_lut,
const std::vector<HuffmanTableEntry>& ac_huff_lut,
uint16_t scan_progression[kMaxComponents][kDCTBlockSize],
bool is_progressive,
size_t* pos,
JPEGData* jpg) {
if (!ProcessSOS(data, len, pos, jpg)) {
return false;
}
JPEGScanInfo* scan_info = &jpg->scan_info.back();
bool is_interleaved = (scan_info->components.size() > 1);
int MCUs_per_row;
int MCU_rows;
if (is_interleaved) {
MCUs_per_row = jpg->MCU_cols;
MCU_rows = jpg->MCU_rows;
} else {
const JPEGComponent& c = jpg->components[scan_info->components[0].comp_idx];
MCUs_per_row =
DivCeil(jpg->width * c.h_samp_factor, 8 * jpg->max_h_samp_factor);
MCU_rows =
DivCeil(jpg->height * c.v_samp_factor, 8 * jpg->max_v_samp_factor);
}
coeff_t last_dc_coeff[kMaxComponents] = {0};
BitReaderState br(data, len, *pos);
int restarts_to_go = jpg->restart_interval;
int next_restart_marker = 0;
int eobrun = -1;
int block_scan_index = 0;
const int Al = is_progressive ? scan_info->Al : 0;
const int Ah = is_progressive ? scan_info->Ah : 0;
const int Ss = is_progressive ? scan_info->Ss : 0;
const int Se = is_progressive ? scan_info->Se : 63;
const uint16_t scan_bitmask = Ah == 0 ? (0xffff << Al) : (1u << Al);
const uint16_t refinement_bitmask = (1 << Al) - 1;
for (int i = 0; i < (int)scan_info->components.size(); ++i) {
int comp_idx = scan_info->components[i].comp_idx;
for (int k = Ss; k <= Se; ++k) {
if (scan_progression[comp_idx][k] & scan_bitmask) {
fprintf(stderr, "Overlapping scans: component=%d k=%d prev_mask=%d "
"cur_mask=%d\n", comp_idx, k, scan_progression[i][k],
scan_bitmask);
jpg->error = JPEG_OVERLAPPING_SCANS;
return false;
}
if (scan_progression[comp_idx][k] & refinement_bitmask) {
fprintf(stderr, "Invalid scan order, a more refined scan was already "
"done: component=%d k=%d prev_mask=%d cur_mask=%d\n", comp_idx,
k, scan_progression[i][k], scan_bitmask);
jpg->error = JPEG_INVALID_SCAN_ORDER;
return false;
}
scan_progression[comp_idx][k] |= scan_bitmask;
}
}
if (Al > 10) {
fprintf(stderr, "Scan parameter Al=%d is not supported in guetzli.\n", Al);
jpg->error = JPEG_NON_REPRESENTABLE_AC_COEFF;
return false;
}
for (int mcu_y = 0; mcu_y < MCU_rows; ++mcu_y) {
for (int mcu_x = 0; mcu_x < MCUs_per_row; ++mcu_x) {
// Handle the restart intervals.
if (jpg->restart_interval > 0) {
if (restarts_to_go == 0) {
if (ProcessRestart(data, len,
&next_restart_marker, &br, jpg)) {
restarts_to_go = jpg->restart_interval;
memset(last_dc_coeff, 0, sizeof(last_dc_coeff));
if (eobrun > 0) {
fprintf(stderr, "End-of-block run too long.\n");
jpg->error = JPEG_EOB_RUN_TOO_LONG;
return false;
}
eobrun = -1; // fresh start
} else {
return false;
}
}
--restarts_to_go;
}
// Decode one MCU.
for (int i = 0; i < (int)scan_info->components.size(); ++i) {
JPEGComponentScanInfo* si = &scan_info->components[i];
JPEGComponent* c = &jpg->components[si->comp_idx];
const HuffmanTableEntry* dc_lut =
&dc_huff_lut[si->dc_tbl_idx * kJpegHuffmanLutSize];
const HuffmanTableEntry* ac_lut =
&ac_huff_lut[si->ac_tbl_idx * kJpegHuffmanLutSize];
int nblocks_y = is_interleaved ? c->v_samp_factor : 1;
int nblocks_x = is_interleaved ? c->h_samp_factor : 1;
for (int iy = 0; iy < nblocks_y; ++iy) {
for (int ix = 0; ix < nblocks_x; ++ix) {
int block_y = mcu_y * nblocks_y + iy;
int block_x = mcu_x * nblocks_x + ix;
int block_idx = block_y * c->width_in_blocks + block_x;
coeff_t* coeffs = &c->coeffs[block_idx * kDCTBlockSize];
if (Ah == 0) {
if (!DecodeDCTBlock(dc_lut, ac_lut, Ss, Se, Al, &eobrun, &br, jpg,
&last_dc_coeff[si->comp_idx], coeffs)) {
return false;
}
} else {
if (!RefineDCTBlock(ac_lut, Ss, Se, Al,
&eobrun, &br, jpg, coeffs)) {
return false;
}
}
++block_scan_index;
}
}
}
}
}
if (eobrun > 0) {
fprintf(stderr, "End-of-block run too long.\n");
jpg->error = JPEG_EOB_RUN_TOO_LONG;
return false;
}
if (!br.FinishStream(pos)) {
jpg->error = JPEG_INVALID_SCAN;
return false;
}
if (*pos > len) {
fprintf(stderr, "Unexpected end of file during scan. pos=%d len=%d\n",
static_cast<int>(*pos), static_cast<int>(len));
jpg->error = JPEG_UNEXPECTED_EOF;
return false;
}
return true;
}
// Changes the quant_idx field of the components to refer to the index of the
// quant table in the jpg->quant array.
bool FixupIndexes(JPEGData* jpg) {
for (int i = 0; i < (int)jpg->components.size(); ++i) {
JPEGComponent* c = &jpg->components[i];
bool found_index = false;
for (int j = 0; j < (int)jpg->quant.size(); ++j) {
if (jpg->quant[j].index == c->quant_idx) {
c->quant_idx = j;
found_index = true;
break;
}
}
if (!found_index) {
fprintf(stderr, "Quantization table with index %d not found\n",
c->quant_idx);
jpg->error = JPEG_QUANT_TABLE_NOT_FOUND;
return false;
}
}
return true;
}
size_t FindNextMarker(const uint8_t* data, const size_t len, size_t pos) {
// kIsValidMarker[i] == 1 means (0xc0 + i) is a valid marker.
static const uint8_t kIsValidMarker[] = {
1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
};
size_t num_skipped = 0;
while (pos + 1 < len &&
(data[pos] != 0xff || data[pos + 1] < 0xc0 ||
!kIsValidMarker[data[pos + 1] - 0xc0])) {
++pos;
++num_skipped;
}
return num_skipped;
}
} // namespace
bool ReadJpeg(const uint8_t* data, const size_t len, JpegReadMode mode,
JPEGData* jpg) {
size_t pos = 0;
// Check SOI marker.
EXPECT_MARKER();
int marker = data[pos + 1];
pos += 2;
if (marker != 0xd8) {
fprintf(stderr, "Did not find expected SOI marker, actual=%d\n", marker);
jpg->error = JPEG_SOI_NOT_FOUND;
return false;
}
int lut_size = kMaxHuffmanTables * kJpegHuffmanLutSize;
std::vector<HuffmanTableEntry> dc_huff_lut(lut_size);
std::vector<HuffmanTableEntry> ac_huff_lut(lut_size);
bool found_sof = false;
uint16_t scan_progression[kMaxComponents][kDCTBlockSize] = { { 0 } };
bool is_progressive = false; // default
do {
// Read next marker.
size_t num_skipped = FindNextMarker(data, len, pos);
if (num_skipped > 0) {
// Add a fake marker to indicate arbitrary in-between-markers data.
jpg->marker_order.push_back(0xff);
jpg->inter_marker_data.push_back(
std::string(reinterpret_cast<const char*>(&data[pos]),
num_skipped));
pos += num_skipped;
}
EXPECT_MARKER();
marker = data[pos + 1];
pos += 2;
bool ok = true;
switch (marker) {
case 0xc0:
case 0xc1:
case 0xc2:
is_progressive = (marker == 0xc2);
ok = ProcessSOF(data, len, mode, &pos, jpg);
found_sof = true;
break;
case 0xc4:
ok = ProcessDHT(data, len, mode, &dc_huff_lut, &ac_huff_lut, &pos, jpg);
break;
case 0xd0:
case 0xd1:
case 0xd2:
case 0xd3:
case 0xd4:
case 0xd5:
case 0xd6:
case 0xd7:
// RST markers do not have any data.
break;
case 0xd9:
// Found end marker.
break;
case 0xda:
if (mode == JPEG_READ_ALL) {
ok = ProcessScan(data, len, dc_huff_lut, ac_huff_lut,
scan_progression, is_progressive, &pos, jpg);
}
break;
case 0xdb:
ok = ProcessDQT(data, len, &pos, jpg);
break;
case 0xdd:
ok = ProcessDRI(data, len, &pos, jpg);
break;
case 0xe0:
case 0xe1:
case 0xe2:
case 0xe3:
case 0xe4:
case 0xe5:
case 0xe6:
case 0xe7:
case 0xe8:
case 0xe9:
case 0xea:
case 0xeb:
case 0xec:
case 0xed:
case 0xee:
case 0xef:
if (mode != JPEG_READ_TABLES) {
ok = ProcessAPP(data, len, &pos, jpg);
}
break;
case 0xfe:
if (mode != JPEG_READ_TABLES) {
ok = ProcessCOM(data, len, &pos, jpg);
}
break;
default:
fprintf(stderr, "Unsupported marker: %d pos=%d len=%d\n",
marker, static_cast<int>(pos), static_cast<int>(len));
jpg->error = JPEG_UNSUPPORTED_MARKER;
ok = false;
break;
}
if (!ok) {
return false;
}
jpg->marker_order.push_back(marker);
if (mode == JPEG_READ_HEADER && found_sof) {
break;
}
} while (marker != 0xd9);
if (!found_sof) {
fprintf(stderr, "Missing SOF marker.\n");
jpg->error = JPEG_SOF_NOT_FOUND;
return false;
}
// Supplemental checks.
if (mode == JPEG_READ_ALL) {
if (pos < len) {
jpg->tail_data.assign(reinterpret_cast<const char*>(&data[pos]),
len - pos);
}
if (!FixupIndexes(jpg)) {
return false;
}
if (jpg->huffman_code.size() == 0) {
// Section B.2.4.2: "If a table has never been defined for a particular
// destination, then when this destination is specified in a scan header,
// the results are unpredictable."
fprintf(stderr, "Need at least one Huffman code table.\n");
jpg->error = JPEG_HUFFMAN_TABLE_ERROR;
return false;
}
if (jpg->huffman_code.size() >= kMaxDHTMarkers) {
fprintf(stderr, "Too many Huffman tables.\n");
jpg->error = JPEG_HUFFMAN_TABLE_ERROR;
return false;
}
}
return true;
}
bool ReadJpeg(const std::string& data, JpegReadMode mode,
JPEGData* jpg) {
return ReadJpeg(reinterpret_cast<const uint8_t*>(data.data()),
static_cast<const size_t>(data.size()),
mode, jpg);
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/jpeg_data_reader.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 10,050
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/preprocess_downsample.h"
#include <algorithm>
#include <assert.h>
#include <string.h>
#include <cmath>
using std::size_t;
namespace {
// convolve with size*size kernel
std::vector<float> Convolve2D(const std::vector<float>& image, int w, int h,
const double* kernel, int size) {
auto result = image;
int size2 = size / 2;
for (int i = 0; i < (int)image.size(); i++) {
int x = i % w;
int y = i / w;
// Avoid non-normalized results at boundary by skipping edges.
if (x < size2 || x + size - size2 - 1 >= w
|| y < size2 || y + size - size2 - 1 >= h) {
continue;
}
float v = 0;
for (int j = 0; j < size * size; j++) {
int x2 = x + j % size - size2;
int y2 = y + j / size - size2;
v += kernel[j] * image[y2 * w + x2];
}
result[i] = v;
}
return result;
}
// convolve horizontally and vertically with 1D kernel
std::vector<float> Convolve2X(const std::vector<float>& image, int w, int h,
const double* kernel, int size, double mul) {
auto temp = image;
int size2 = size / 2;
for (int i = 0; i < (int)image.size(); i++) {
int x = i % w;
int y = i / w;
// Avoid non-normalized results at boundary by skipping edges.
if (x < size2 || x + size - size2 - 1 >= w) continue;
float v = 0;
for (int j = 0; j < size; j++) {
int x2 = x + j - size2;
v += kernel[j] * image[y * w + x2];
}
temp[i] = v * mul;
}
auto result = temp;
for (int i = 0; i < (int)temp.size(); i++) {
int x = i % w;
int y = i / w;
// Avoid non-normalized results at boundary by skipping edges.
if (y < size2 || y + size - size2 - 1 >= h) continue;
float v = 0;
for (int j = 0; j < size; j++) {
int y2 = y + j - size2;
v += kernel[j] * temp[y2 * w + x];
}
result[i] = v * mul;
}
return result;
}
double Normal(double x, double sigma) {
static const double kInvSqrt2Pi = 0.3989422804014327;
return std::exp(-x * x / (2 * sigma * sigma)) * kInvSqrt2Pi / sigma;
}
std::vector<float> Sharpen(const std::vector<float>& image, int w, int h,
float sigma, float amount) {
// This is only made for small sigma, e.g. 1.3.
std::vector<double> kernel(5);
for (int i = 0; i < (int)kernel.size(); i++) {
kernel[i] = Normal(1.0 * i - kernel.size() / 2, sigma);
}
double sum = 0;
for (int i = 0; i < (int)kernel.size(); i++) sum += kernel[i];
const double mul = 1.0 / sum;
std::vector<float> result =
Convolve2X(image, w, h, kernel.data(), kernel.size(), mul);
for (size_t i = 0; i < image.size(); i++) {
result[i] = image[i] + (image[i] - result[i]) * amount;
}
return result;
}
void Erode(int w, int h, std::vector<bool>* image) {
std::vector<bool> temp = *image;
for (int y = 1; y + 1 < h; y++) {
for (int x = 1; x + 1 < w; x++) {
size_t index = y * w + x;
if (!(temp[index] && temp[index - 1] && temp[index + 1]
&& temp[index - w] && temp[index + w])) {
(*image)[index] = 0;
}
}
}
}
void Dilate(int w, int h, std::vector<bool>* image) {
std::vector<bool> temp = *image;
for (int y = 1; y + 1 < h; y++) {
for (int x = 1; x + 1 < w; x++) {
size_t index = y * w + x;
if (temp[index] || temp[index - 1] || temp[index + 1]
|| temp[index - w] || temp[index + w]) {
(*image)[index] = 1;
}
}
}
}
std::vector<float> Blur(const std::vector<float>& image, int w, int h) {
// This is only made for small sigma, e.g. 1.3.
static const double kSigma = 1.3;
std::vector<double> kernel(5);
for (int i = 0; i < (int)kernel.size(); i++) {
kernel[i] = Normal(1.0 * i - kernel.size() / 2, kSigma);
}
double sum = 0;
for (int i = 0; i < (int)kernel.size(); i++) sum += kernel[i];
const double mul = 1.0 / sum;
return Convolve2X(image, w, h, kernel.data(), kernel.size(), mul);
}
} // namespace
namespace guetzli {
// Do the sharpening to the v channel, but only in areas where it will help
// channel should be 2 for v sharpening, or 1 for less effective u sharpening
std::vector<std::vector<float>> PreProcessChannel(
int w, int h, int channel, float sigma, float amount, bool blur,
bool sharpen, const std::vector<std::vector<float>>& image) {
if (!blur && !sharpen) return image;
// Bring in range 0.0-1.0 for Y, -0.5 - 0.5 for U and V
auto yuv = image;
for (int i = 0; i < (int)yuv[0].size(); i++) {
yuv[0][i] /= 255.0;
yuv[1][i] = yuv[1][i] / 255.0 - 0.5;
yuv[2][i] = yuv[2][i] / 255.0 - 0.5;
}
// Map of areas where the image is not too bright to apply the effect.
std::vector<bool> darkmap(image[0].size(), false);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
size_t index = y * w + x;
float y = yuv[0][index];
float u = yuv[1][index];
float v = yuv[2][index];
float r = y + 1.402 * v;
float g = y - 0.34414 * u - 0.71414 * v;
float b = y + 1.772 * u;
// Parameters tuned to avoid sharpening in too bright areas, where the
// effect makes it worse instead of better.
if (channel == 2 && g < 0.85 && b < 0.85 && r < 0.9) {
darkmap[index] = true;
}
if (channel == 1 && r < 0.85 && g < 0.85 && b < 0.9) {
darkmap[index] = true;
}
}
}
Erode(w, h, &darkmap);
Erode(w, h, &darkmap);
Erode(w, h, &darkmap);
// Map of areas where the image is red enough (blue in case of u channel).
std::vector<bool> redmap(image[0].size(), false);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
size_t index = y * w + x;
float u = yuv[1][index];
float v = yuv[2][index];
// Parameters tuned to allow only colors on which sharpening is useful.
if (channel == 2 && 2.116 * v > -0.34414 * u + 0.2
&& 1.402 * v > 1.772 * u + 0.2) {
redmap[index] = true;
}
if (channel == 1 && v < 1.263 * u - 0.1 && u > -0.33741 * v) {
redmap[index] = true;
}
}
}
Dilate(w, h, &redmap);
Dilate(w, h, &redmap);
Dilate(w, h, &redmap);
// Map of areas where to allow sharpening by combining red and dark areas
std::vector<bool> sharpenmap(image[0].size(), 0);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
size_t index = y * w + x;
sharpenmap[index] = redmap[index] && darkmap[index];
}
}
// Threshold for where considered an edge.
const double threshold = (channel == 2 ? 0.02 : 1.0) * 127.5;
static const double kEdgeMatrix[9] = {
0, -1, 0,
-1, 4, -1,
0, -1, 0
};
// Map of areas where to allow blurring, only where it is not too sharp
std::vector<bool> blurmap(image[0].size(), false);
std::vector<float> edge = Convolve2D(yuv[channel], w, h, kEdgeMatrix, 3);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
size_t index = y * w + x;
float u = yuv[1][index];
float v = yuv[2][index];
if (sharpenmap[index]) continue;
if (!darkmap[index]) continue;
if (fabs(edge[index]) < threshold && v < -0.162 * u) {
blurmap[index] = true;
}
}
}
Erode(w, h, &blurmap);
Erode(w, h, &blurmap);
// Choose sharpened, blurred or original per pixel
std::vector<float> sharpened = Sharpen(yuv[channel], w, h, sigma, amount);
std::vector<float> blurred = Blur(yuv[channel], w, h);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
size_t index = y * w + x;
if (sharpenmap[index] > 0) {
if (sharpen) yuv[channel][index] = sharpened[index];
} else if (blurmap[index] > 0) {
if (blur) yuv[channel][index] = blurred[index];
}
}
}
// Bring back to range 0-255
for (int i = 0; i < (int)yuv[0].size(); i++) {
yuv[0][i] *= 255.0;
yuv[1][i] = (yuv[1][i] + 0.5) * 255.0;
yuv[2][i] = (yuv[2][i] + 0.5) * 255.0;
}
return yuv;
}
namespace {
inline float Clip(float val) {
return std::max(0.0f, std::min(255.0f, val));
}
inline float RGBToY(float r, float g, float b) {
return 0.299f * r + 0.587f * g + 0.114f * b;
}
inline float RGBToU(float r, float g, float b) {
return -0.16874f * r - 0.33126f * g + 0.5f * b + 128.0;
}
inline float RGBToV(float r, float g, float b) {
return 0.5f * r - 0.41869f * g - 0.08131f * b + 128.0;
}
inline float YUVToR(float y, float , float v) {
return y + 1.402 * (v - 128.0);
}
inline float YUVToG(float y, float u, float v) {
return y - 0.344136 * (u - 128.0) - 0.714136 * (v - 128.0);
}
inline float YUVToB(float y, float u, float ) {
return y + 1.772 * (u - 128.0);
}
// TODO(user) Use SRGB->linear conversion and a lookup-table.
inline float GammaToLinear(float x) {
return std::pow(x / 255.0, 2.2);
}
// TODO(user) Use linear->SRGB conversion and a lookup-table.
inline float LinearToGamma(float x) {
return 255.0 * std::pow(x, 1.0 / 2.2);
}
std::vector<float> LinearlyAveragedLuma(const std::vector<float>& rgb) {
assert(rgb.size() % 3 == 0);
std::vector<float> y(rgb.size() / 3);
for (int i = 0, p = 0; p < (int)rgb.size(); ++i, p += 3) {
y[i] = LinearToGamma(RGBToY(GammaToLinear(rgb[p + 0]),
GammaToLinear(rgb[p + 1]),
GammaToLinear(rgb[p + 2])));
}
return y;
}
std::vector<float> LinearlyDownsample2x2(const std::vector<float>& rgb_in,
const int width, const int height) {
assert((int)rgb_in.size() == 3 * width * height);
int w = (width + 1) / 2;
int h = (height + 1) / 2;
std::vector<float> rgb_out(3 * w * h);
for (int y = 0, p = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
for (int i = 0; i < 3; ++i, ++p) {
rgb_out[p] = 0.0;
for (int iy = 0; iy < 2; ++iy) {
for (int ix = 0; ix < 2; ++ix) {
int yy = std::min(height - 1, 2 * y + iy);
int xx = std::min(width - 1, 2 * x + ix);
rgb_out[p] += GammaToLinear(rgb_in[3 * (yy * width + xx) + i]);
}
}
rgb_out[p] = LinearToGamma(0.25 * rgb_out[p]);
}
}
}
return rgb_out;
}
std::vector<std::vector<float> > RGBToYUV(const std::vector<float>& rgb) {
std::vector<std::vector<float> > yuv(3, std::vector<float>(rgb.size() / 3));
for (int i = 0, p = 0; p < (int)rgb.size(); ++i, p += 3) {
const float r = rgb[p + 0];
const float g = rgb[p + 1];
const float b = rgb[p + 2];
yuv[0][i] = RGBToY(r, g, b);
yuv[1][i] = RGBToU(r, g, b);
yuv[2][i] = RGBToV(r, g, b);
}
return yuv;
}
std::vector<float> YUVToRGB(const std::vector<std::vector<float> >& yuv) {
std::vector<float> rgb(3 * yuv[0].size());
for (int i = 0, p = 0; p < (int)rgb.size(); ++i, p += 3) {
const float y = yuv[0][i];
const float u = yuv[1][i];
const float v = yuv[2][i];
rgb[p + 0] = Clip(YUVToR(y, u, v));
rgb[p + 1] = Clip(YUVToG(y, u, v));
rgb[p + 2] = Clip(YUVToB(y, u, v));
}
return rgb;
}
// Upsamples img_in with a box-filter, and returns an image with output
// dimensions width x height.
std::vector<float> Upsample2x2(const std::vector<float>& img_in,
const int width, const int height) {
int w = (width + 1) / 2;
int h = (height + 1) / 2;
assert((int)img_in.size() == w * h);
std::vector<float> img_out(width * height);
for (int y = 0, p = 0; y < h; ++y) {
for (int x = 0; x < w; ++x, ++p) {
for (int iy = 0; iy < 2; ++iy) {
for (int ix = 0; ix < 2; ++ix) {
int yy = std::min(height - 1, 2 * y + iy);
int xx = std::min(width - 1, 2 * x + ix);
img_out[yy * width + xx] = img_in[p];
}
}
}
}
return img_out;
}
// Apply the "fancy upsample" filter used by libjpeg.
std::vector<float> Blur(const std::vector<float>& img,
const int width, const int height) {
std::vector<float> img_out(width * height);
for (int y0 = 0; y0 < height; y0 += 2) {
for (int x0 = 0; x0 < width; x0 += 2) {
for (int iy = 0; iy < 2 && y0 + iy < height; ++iy) {
for (int ix = 0; ix < 2 && x0 + ix < width; ++ix) {
int dy = 4 * iy - 2;
int dx = 4 * ix - 2;
int x1 = std::min(width - 1, std::max(0, x0 + dx));
int y1 = std::min(height - 1, std::max(0, y0 + dy));
img_out[(y0 + iy) * width + x0 + ix] =
(9.0 * img[y0 * width + x0] +
3.0 * img[y0 * width + x1] +
3.0 * img[y1 * width + x0] +
1.0 * img[y1 * width + x1]) / 16.0;
}
}
}
}
return img_out;
}
std::vector<float> YUV420ToRGB(const std::vector<std::vector<float> >& yuv420,
const int width, const int height) {
std::vector<std::vector<float> > yuv;
yuv.push_back(yuv420[0]);
std::vector<float> u = Upsample2x2(yuv420[1], width, height);
std::vector<float> v = Upsample2x2(yuv420[2], width, height);
yuv.push_back(Blur(u, width, height));
yuv.push_back(Blur(v, width, height));
return YUVToRGB(yuv);
}
void UpdateGuess(const std::vector<float>& target,
const std::vector<float>& reconstructed,
std::vector<float>* guess) {
assert(reconstructed.size() == guess->size());
assert(target.size() == guess->size());
for (int i = 0; i < (int)guess->size(); ++i) {
// TODO(user): Evaluate using a decaying constant here.
(*guess)[i] = Clip((*guess)[i] - (reconstructed[i] - target[i]));
}
}
} // namespace
std::vector<std::vector<float> > RGBToYUV420(
const std::vector<uint8_t>& rgb_in, const int width, const int height) {
std::vector<float> rgbf(rgb_in.size());
for (int i = 0; i < (int)rgb_in.size(); ++i) {
rgbf[i] = static_cast<float>(rgb_in[i]);
}
std::vector<float> y_target = LinearlyAveragedLuma(rgbf);
std::vector<std::vector<float> > yuv_target =
RGBToYUV(LinearlyDownsample2x2(rgbf, width, height));
std::vector<std::vector<float> > yuv_guess = yuv_target;
yuv_guess[0] = Upsample2x2(yuv_guess[0], width, height);
// TODO(user): Stop early if the error is small enough.
for (int iter = 0; iter < 20; ++iter) {
std::vector<float> rgb_rec = YUV420ToRGB(yuv_guess, width, height);
std::vector<float> y_rec = LinearlyAveragedLuma(rgb_rec);
std::vector<std::vector<float> > yuv_rec =
RGBToYUV(LinearlyDownsample2x2(rgb_rec, width, height));
UpdateGuess(y_target, y_rec, &yuv_guess[0]);
UpdateGuess(yuv_target[1], yuv_rec[1], &yuv_guess[1]);
UpdateGuess(yuv_target[2], yuv_rec[2], &yuv_guess[2]);
}
yuv_guess[1] = Upsample2x2(yuv_guess[1], width, height);
yuv_guess[2] = Upsample2x2(yuv_guess[2], width, height);
return yuv_guess;
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/preprocess_downsample.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 5,192
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/jpeg_data_encoder.h"
#include <algorithm>
#include <string.h>
#include "guetzli/fdct.h"
namespace guetzli {
namespace {
static const int kIQuantBits = 16;
// Output of the DCT is upscaled by 16.
static const int kDCTBits = kIQuantBits + 4;
static const int kBias = 0x80 << (kDCTBits - 8);
void Quantize(coeff_t* v, int iquant) {
*v = (*v * iquant + kBias) >> kDCTBits;
}
// Single pixel rgb to 16-bit yuv conversion.
// The returned yuv values are signed integers in the
// range [-128, 127] inclusive.
inline static void RGBToYUV16(const uint8_t* const rgb,
coeff_t *out) {
enum { FRAC = 16, HALF = 1 << (FRAC - 1) };
const int r = rgb[0];
const int g = rgb[1];
const int b = rgb[2];
out[0] = (19595 * r + 38469 * g + 7471 * b - (128 << 16) + HALF) >> FRAC;
out[64] = (-11059 * r - 21709 * g + 32768 * b + HALF - 1) >> FRAC;
out[128] = (32768 * r - 27439 * g - 5329 * b + HALF - 1) >> FRAC;
}
} // namespace
void AddApp0Data(JPEGData* jpg) {
const unsigned char kApp0Data[] = {
0xe0, 0x00, 0x10, // APP0
0x4a, 0x46, 0x49, 0x46, 0x00, // 'JFIF'
0x01, 0x01, // v1.01
0x00, 0x00, 0x01, 0x00, 0x01, // aspect ratio = 1:1
0x00, 0x00 // thumbnail width/height
};
jpg->app_data.push_back(
std::string(reinterpret_cast<const char*>(kApp0Data),
sizeof(kApp0Data)));
}
bool EncodeRGBToJpeg(const std::vector<uint8_t>& rgb, int w, int h,
const int* quant, JPEGData* jpg) {
if (w < 0 || w >= 1 << 16 || h < 0 || h >= 1 << 16 ||
(int)rgb.size() != 3 * w * h) {
return false;
}
InitJPEGDataForYUV444(w, h, jpg);
AddApp0Data(jpg);
int iquant[3 * kDCTBlockSize];
int idx = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < kDCTBlockSize; ++j) {
int v = quant[idx];
jpg->quant[i].values[j] = v;
iquant[idx++] = ((1 << kIQuantBits) + 1) / v;
}
}
// Compute YUV444 DCT coefficients.
int block_ix = 0;
for (int block_y = 0; block_y < jpg->MCU_rows; ++block_y) {
for (int block_x = 0; block_x < jpg->MCU_cols; ++block_x) {
coeff_t block[3 * kDCTBlockSize];
// RGB->YUV transform.
for (int iy = 0; iy < 8; ++iy) {
for (int ix = 0; ix < 8; ++ix) {
int y = std::min(h - 1, 8 * block_y + iy);
int x = std::min(w - 1, 8 * block_x + ix);
int p = y * w + x;
RGBToYUV16(&rgb[3 * p], &block[8 * iy + ix]);
}
}
// DCT
for (int i = 0; i < 3; ++i) {
ComputeBlockDCT(&block[i * kDCTBlockSize]);
}
// Quantization
for (int i = 0; i < 3 * 64; ++i) {
Quantize(&block[i], iquant[i]);
}
// Copy the resulting coefficients to *jpg.
for (int i = 0; i < 3; ++i) {
memcpy(&jpg->components[i].coeffs[block_ix * kDCTBlockSize],
&block[i * kDCTBlockSize], kDCTBlockSize * sizeof(block[0]));
}
++block_ix;
}
}
return true;
}
bool EncodeRGBToJpeg(const std::vector<uint8_t>& rgb, int w, int h,
JPEGData* jpg) {
static const int quant[3 * kDCTBlockSize] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
};
return EncodeRGBToJpeg(rgb, w, h, quant, jpg);
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/jpeg_data_encoder.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,794
|
```c++
/*
LodePNG version 20160409
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.
*/
/*
The manual and changelog are in the header file "lodepng.h"
Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.
*/
#include "lodepng.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
#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 = "20160409";
/*
This source file is built up in the following large parts. The code sections
with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
-Tools for C and common code for PNG and Zlib
-C Code for Zlib (huffman, deflate, ...)
-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
-The C++ wrapper around all of the above
*/
/*The malloc, realloc and free functions defined here with "lodepng_" in front
of the name, so that you can easily change them to others related to your
platform if needed. Everything else in the code calls these. Pass
-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
define them in your own project's source files without needing to change
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)
{
return malloc(size);
}
static void* lodepng_realloc(void* ptr, size_t new_size)
{
return realloc(ptr, new_size);
}
static void lodepng_free(void* ptr)
{
free(ptr);
}
#else /*LODEPNG_COMPILE_ALLOCATORS*/
void* lodepng_malloc(size_t size);
void* lodepng_realloc(void* ptr, size_t new_size);
void lodepng_free(void* ptr);
#endif /*LODEPNG_COMPILE_ALLOCATORS*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // Tools for C, and common code for PNG and Zlib. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/*
Often in case of an error a value is assigned to a variable and then it breaks
out of a loop (to go to the cleanup phase of a function). This macro does that.
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)\
{\
errorvar = code;\
break;\
}
/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
#define ERROR_BREAK(code) CERROR_BREAK(error, code)
/*Set error var to the error code, and return it.*/
#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)\
{\
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)\
{\
errorvar = code;\
return;\
}
/*
About uivector, ucvector and string:
-All of them wrap dynamic arrays or text strings in a similar way.
-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
-They're not used in the interface, only internally in this file as static functions.
-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
*/
#ifdef LODEPNG_COMPILE_ZLIB
/*dynamic vector of unsigned ints*/
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)
{
((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)
{
size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
void* data = lodepng_realloc(p->data, newsize);
if(data)
{
p->allocsize = newsize;
p->data = (unsigned*)data;
}
else return 0; /*error: not enough memory*/
}
return 1;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
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)
{
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)
{
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)
{
if(!uivector_resize(p, p->size + 1)) return 0;
p->data[p->size - 1] = c;
return 1;
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
/* /////////////////////////////////////////////////////////////////////////// */
/*dynamic vector of unsigned chars*/
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)
{
size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
void* data = lodepng_realloc(p->data, newsize);
if(data)
{
p->allocsize = newsize;
p->data = (unsigned char*)data;
}
else return 0; /*error: not enough memory*/
}
return 1;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
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*/
}
#ifdef LODEPNG_COMPILE_PNG
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)
{
p->data = NULL;
p->size = p->allocsize = 0;
}
#endif /*LODEPNG_COMPILE_PNG*/
#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)
{
p->data = buffer;
p->allocsize = p->size = size;
}
#endif /*LODEPNG_COMPILE_ZLIB*/
#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)
{
if(!ucvector_resize(p, p->size + 1)) return 0;
p->data[p->size - 1] = c;
return 1;
}
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_PNG
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned string_resize(char** out, size_t size)
{
char* data = (char*)lodepng_realloc(*out, size + 1);
if(data)
{
data[size] = 0; /*null termination char*/
*out = data;
}
return data != 0;
}
/*init a {char*, size_t} pair for use as string*/
static void string_init(char** out)
{
*out = NULL;
string_resize(out, 0);
}
/*free the above pair again*/
static void string_cleanup(char** out)
{
lodepng_free(*out);
*out = NULL;
}
static void string_set(char** out, const char* in)
{
size_t insize = strlen(in), i;
if(string_resize(out, insize))
{
for(i = 0; i != insize; ++i)
{
(*out)[i] = in[i];
}
}
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
#endif /*LODEPNG_COMPILE_PNG*/
/* ////////////////////////////////////////////////////////////////////////// */
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)
{
buffer[0] = (unsigned char)((value >> 24) & 0xff);
buffer[1] = (unsigned char)((value >> 16) & 0xff);
buffer[2] = (unsigned char)((value >> 8) & 0xff);
buffer[3] = (unsigned char)((value ) & 0xff);
}
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
#ifdef LODEPNG_COMPILE_ENCODER
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);
}
#endif /*LODEPNG_COMPILE_ENCODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / File IO / */
/* ////////////////////////////////////////////////////////////////////////// */
#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)
{
FILE* file;
long size;
file = fopen(filename, "rb");
if(!file) return -1;
if(fseek(file, 0, SEEK_END) != 0)
{
fclose(file);
return -1;
}
size = ftell(file);
/* It may give LONG_MAX as directory size, this is invalid for us. */
if(size == LONG_MAX) size = -1;
fclose(file);
return size;
}
/* 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)
{
FILE* file;
size_t readsize;
file = fopen(filename, "rb");
if(!file) return 78;
readsize = fread(out, 1, size, file);
fclose(file);
if (readsize != size) return 78;
return 0;
}
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;
*out = (unsigned char*)lodepng_malloc((size_t)size);
if(!(*out) && size > 0) return 83; /*the above malloc failed*/
return lodepng_buffer_file(*out, (size_t)size, filename);
}
/*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)
{
FILE* file;
file = fopen(filename, "wb" );
if(!file) return 79;
fwrite((char*)buffer , 1 , buffersize, file);
fclose(file);
return 0;
}
#endif /*LODEPNG_COMPILE_DISK*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // End of common code and tools. Begin of Zlib related code. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#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)\
{\
/*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*/\
(bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\
++(*bitpointer);\
}
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)
{
size_t i;
for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1));
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DECODER
#define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
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)
{
unsigned result = 0, i;
for(i = 0; i != nbits; ++i)
{
result += ((unsigned)READBIT(*bitpointer, bitstream)) << i;
++(*bitpointer);
}
return result;
}
#endif /*LODEPNG_COMPILE_DECODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / Deflate - Huffman / */
/* ////////////////////////////////////////////////////////////////////////// */
#define FIRST_LENGTH_CODE_INDEX 257
#define LAST_LENGTH_CODE_INDEX 285
/*256 literals, the end code, some length codes, and 2 unused codes*/
#define NUM_DEFLATE_CODE_SYMBOLS 288
/*the distance codes have their own symbols, 30 used, 2 unused*/
#define NUM_DISTANCE_SYMBOLS 32
/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
#define NUM_CODE_LENGTH_CODES 19
/*the base lengths represented by codes 257-285*/
static const unsigned LENGTHBASE[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};
/*the extra bits used by codes 257-285 (added to base length)*/
static const unsigned LENGTHEXTRA[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};
/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
static const unsigned DISTANCEBASE[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};
/*the extra bits of backwards distances (added to base)*/
static const unsigned DISTANCEEXTRA[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};
/*the order in which "code length alphabet code lengths" are stored, out of this
the huffman tree of the dynamic huffman tree lengths is generated*/
static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
= {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
/* ////////////////////////////////////////////////////////////////////////// */
/*
Huffman tree struct, containing multiple representations of the tree
*/
typedef struct HuffmanTree
{
unsigned* tree2d;
unsigned* tree1d;
unsigned* lengths; /*the lengths of the codes of the 1d-tree*/
unsigned maxbitlen; /*maximum number of bits a single code can get*/
unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
} HuffmanTree;
/*function used for debug purposes to draw the tree in ascii art with C++*/
/*
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)
{
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)
{
tree->tree2d = 0;
tree->tree1d = 0;
tree->lengths = 0;
}
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)
{
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;
tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned));
if(!tree->tree2d) return 83; /*alloc fail*/
/*
convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
uninited, a value >= numcodes is an address to another bit, a value < numcodes
is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
many columns as codes - 1.
A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
Here, the internal nodes are stored (what their 0 and 1 option point to).
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)
{
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*/
{
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*/
{
tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/
treepos = 0;
}
else
{
/*put address of the next step in here, first that address has to be found of course
(it's just nodefilled + 1)...*/
++nodefilled;
/*addresses encoded with numcodes added to it*/
tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes;
treepos = nodefilled;
}
}
else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
}
}
for(n = 0; n < tree->numcodes * 2; ++n)
{
if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/
}
return 0;
}
/*
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)
{
uivector blcount;
uivector nextcode;
unsigned error = 0;
unsigned bits, n;
uivector_init(&blcount);
uivector_init(&nextcode);
tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));
if(!tree->tree1d) error = 83; /*alloc fail*/
if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0)
|| !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0))
error = 83; /*alloc fail*/
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)
{
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)
{
if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++;
}
}
uivector_cleanup(&blcount);
uivector_cleanup(&nextcode);
if(!error) return HuffmanTree_make2DTree(tree);
else return error;
}
/*
given the code lengths (as stored in the PNG file), generate the tree as defined
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)
{
unsigned i;
tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->maxbitlen = maxbitlen;
return HuffmanTree_makeFromLengths2(tree);
}
#ifdef LODEPNG_COMPILE_ENCODER
/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
/*chain node for boundary package merge*/
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)*/
int in_use;
} BPMNode;
/*lists of chains*/
typedef struct BPMLists
{
/*memory pool*/
unsigned memsize;
BPMNode* memory;
unsigned numfree;
unsigned nextfree;
BPMNode** freelist;
/*two heads of lookahead chains per list*/
unsigned listsize;
BPMNode** chains0;
BPMNode** chains1;
} 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)
{
unsigned i;
BPMNode* result;
/*memory full, so garbage collect*/
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)
{
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)
{
if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
}
lists->nextfree = 0;
}
result = lists->freelist[lists->nextfree++];
result->weight = weight;
result->index = index;
result->tail = tail;
return result;
}
static int bpmnode_compare(const void* a, const void* b)
{
int wa = ((const BPMNode*)a)->weight;
int wb = ((const BPMNode*)b)->weight;
if(wa < wb) return -1;
if(wa > wb) return 1;
/*make the qsort a stable sort*/
return ((const BPMNode*)a)->index < ((const BPMNode*)b)->index ? 1 : -1;
}
/*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)
{
unsigned lastindex = lists->chains1[c]->index;
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
{
/*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)
{
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))
{
boundaryPM(lists, leaves, numpresent, c - 1, num);
boundaryPM(lists, leaves, numpresent, c - 1, num);
}
}
}
unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
size_t numcodes, unsigned maxbitlen)
{
unsigned error = 0;
unsigned i;
size_t numpresent = 0; /*number of symbols with non-zero frequency*/
BPMNode* leaves; /*the symbols, only those with > 0 frequency*/
if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
if((1u << maxbitlen) < numcodes) return 80; /*error: represent all symbols*/
leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));
if(!leaves) return 83; /*alloc fail*/
for(i = 0; i != numcodes; ++i)
{
if(frequencies[i] > 0)
{
leaves[numpresent].weight = (int)frequencies[i];
leaves[numpresent].index = i;
++numpresent;
}
}
for(i = 0; i != numcodes; ++i) lengths[i] = 0;
/*ensure at least two present symbols. There should be at least one symbol
according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
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)
{
lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
}
else if(numpresent == 1)
{
lengths[leaves[0].index] = 1;
lengths[leaves[0].index == 0 ? 1 : 0] = 1;
}
else
{
BPMLists lists;
BPMNode* node;
qsort(leaves, numpresent, sizeof(BPMNode), bpmnode_compare);
lists.listsize = maxbitlen;
lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
lists.nextfree = 0;
lists.numfree = lists.memsize;
lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));
lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
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)
{
lists.chains0[i] = &lists.memory[0];
lists.chains1[i] = &lists.memory[1];
}
/*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(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
}
}
lodepng_free(lists.memory);
lodepng_free(lists.freelist);
lodepng_free(lists.chains0);
lodepng_free(lists.chains1);
}
lodepng_free(leaves);
return error;
}
/*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)
{
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
}
static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index)
{
return tree->tree1d[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)
{
unsigned i, error = 0;
unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
if(!bitlen) return 83; /*alloc fail*/
/*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
for(i = 0; i <= 143; ++i) bitlen[i] = 8;
for(i = 144; i <= 255; ++i) bitlen[i] = 9;
for(i = 256; i <= 279; ++i) bitlen[i] = 7;
for(i = 280; i <= 287; ++i) bitlen[i] = 8;
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
lodepng_free(bitlen);
return error;
}
/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
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*/
/*there are 32 distance codes, but 30-31 are unused*/
for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
lodepng_free(bitlen);
return error;
}
#ifdef LODEPNG_COMPILE_DECODER
/*
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)
{
unsigned treepos = 0, ct;
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
the expression below because this is the biggest bottleneck while decoding
*/
ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)];
++(*bp);
if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/
else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/
if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_DECODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / Inflator (Decompressor) / */
/* ////////////////////////////////////////////////////////////////////////// */
/*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)
{
/*TODO: check for out of memory errors*/
generateFixedLitLenTree(tree_ll);
generateFixedDistanceTree(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)
{
/*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;
size_t inbitlength = inlength * 8;
/*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
unsigned* bitlen_ll = 0; /*lit,len code lengths*/
unsigned* bitlen_d = 0; /*dist code lengths*/
/*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
unsigned* bitlen_cl = 0;
HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/
/*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
HLIT = readBitsFromStream(bp, in, 5) + 257;
/*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
HDIST = readBitsFromStream(bp, in, 5) + 1;
/*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
HCLEN = readBitsFromStream(bp, in, 4) + 4;
if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/
HuffmanTree_init(&tree_cl);
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)
{
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*/
}
error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
if(error) break;
/*now we can use this tree to read the lengths for the tree that this function will return*/
bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0;
for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0;
/*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)
{
unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength);
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*/
{
unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
unsigned value; /*set value to the previous code*/
if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
replength += readBitsFromStream(bp, in, 2);
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)
{
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*/
{
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)
{
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*/
{
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)
{
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))
{
/*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;
}
else error = 16; /*unexisting code, this can never happen*/
break;
}
}
if(error) break;
if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
/*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
if(error) break;
error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
break; /*end of error-while*/
}
lodepng_free(bitlen_cl);
lodepng_free(bitlen_ll);
lodepng_free(bitlen_d);
HuffmanTree_cleanup(&tree_cl);
return error;
}
/*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)
{
unsigned error = 0;
HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
HuffmanTree tree_d; /*the huffman tree for distance codes*/
size_t inbitlength = inlength * 8;
HuffmanTree_init(&tree_ll);
HuffmanTree_init(&tree_d);
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*/
{
/*code_ll is literal, length or end code*/
unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength);
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*/
{
unsigned code_d, distance;
unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
size_t start, forward, backward, length;
/*part 1: get length base*/
length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
/*part 2: get extra bits and add the value of that to length*/
numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
length += readBitsFromStream(bp, in, numextrabits_l);
/*part 3: get distance code*/
code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength);
if(code_d > 29)
{
if(code_ll == (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;
}
else error = 18; /*error: invalid distance code (30-31 are never used)*/
break;
}
distance = DISTANCEBASE[code_d];
/*part 4: get extra bits from distance*/
numextrabits_d = DISTANCEEXTRA[code_d];
if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
distance += readBitsFromStream(bp, in, numextrabits_d);
/*part 5: fill in all the out[n] values based on the length and dist*/
start = (*pos);
if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
backward = start - distance;
if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/);
if (distance < length) {
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)
{
break; /*end code, break the loop*/
}
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;
break;
}
}
HuffmanTree_cleanup(&tree_ll);
HuffmanTree_cleanup(&tree_d);
return error;
}
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;
/*go to first boundary of byte*/
while(((*bp) & 0x7) != 0) ++(*bp);
p = (*bp) / 8; /*byte position*/
/*read LEN (2 bytes) and NLEN (2 bytes)*/
if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/
LEN = in[p] + 256u * in[p + 1]; p += 2;
NLEN = in[p] + 256u * in[p + 1]; p += 2;
/*check if 16-bit NLEN is really the one's complement of LEN*/
if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/
if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/
/*read the literal data: LEN bytes are now stored in the out buffer*/
if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/
for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++];
(*bp) = p * 8;
return error;
}
static unsigned lodepng_inflatev(ucvector* out,
const unsigned char* in, size_t insize,
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;
size_t pos = 0; /*byte position in the out buffer*/
unsigned error = 0;
(void)settings;
while(!BFINAL)
{
unsigned BTYPE;
if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/
BFINAL = readBitFromStream(&bp, in);
BTYPE = 1u * readBitFromStream(&bp, in);
BTYPE += 2u * readBitFromStream(&bp, in);
if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/
else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/
if(error) return error;
}
return error;
}
unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGDecompressSettings* settings)
{
unsigned error;
ucvector v;
ucvector_init_buffer(&v, *out, *outsize);
error = lodepng_inflatev(&v, in, insize, settings);
*out = v.data;
*outsize = v.size;
return error;
}
static unsigned inflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGDecompressSettings* settings)
{
if(settings->custom_inflate)
{
return settings->custom_inflate(out, outsize, in, insize, settings);
}
else
{
return lodepng_inflate(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / Deflator (Compressor) / */
/* ////////////////////////////////////////////////////////////////////////// */
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)
{
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)
{
/*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;
while(left <= right) {
size_t mid = (left + right) >> 1;
if (array[mid] >= value) right = mid - 1;
else left = mid + 1;
}
if(left >= array_size || array[left] > value) left--;
return left;
}
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
257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
286-287: invalid*/
unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX);
uivector_push_back(values, extra_length);
uivector_push_back(values, dist_code);
uivector_push_back(values, extra_distance);
}
/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3
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
{
int* head; /*hash value to head circular pos - can be outdated if went around window*/
/*circular pos to prev circular pos*/
unsigned short* chain;
int* val; /*circular pos to hash value*/
/*TODO: do this not only for zeros but for any repeated byte. However for PNG
it's always going to be the zeros that dominate, so not important for PNG*/
int* headz; /*similar to head, but for chainz*/
unsigned short* chainz; /*those with same amount of zeros*/
unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/
} Hash;
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);
hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * 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)
{
return 83; /*alloc fail*/
}
/*initialize hash table*/
for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;
for(i = 0; i != windowsize; ++i) hash->val[i] = -1;
for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/
for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;
for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/
return 0;
}
static void hash_cleanup(Hash* hash)
{
lodepng_free(hash->head);
lodepng_free(hash->val);
lodepng_free(hash->chain);
lodepng_free(hash->zeros);
lodepng_free(hash->headz);
lodepng_free(hash->chainz);
}
static unsigned getHash(const unsigned char* data, size_t size, size_t pos)
{
unsigned result = 0;
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
calculating the hash.*/
result ^= (unsigned)(data[pos + 0] << 0u);
result ^= (unsigned)(data[pos + 1] << 4u);
result ^= (unsigned)(data[pos + 2] << 8u);
} else {
size_t amount, i;
if(pos >= size) return 0;
amount = size - pos;
for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u));
}
return result & HASH_BIT_MASK;
}
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;
data = start;
while(data != end && *data == 0) ++data;
/*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
return (unsigned)(data - start);
}
/*wpos = pos & (windowsize - 1)*/
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] = wpos;
hash->zeros[wpos] = numzeros;
if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];
hash->headz[numzeros] = wpos;
}
/*
LZ77-encode the data. Return value is error code. The input are raw bytes, the output
is in the form of unsigned integers with codes representing for example literal bytes, or
length/distance pairs.
It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
sliding window (of windowsize) is used, and all past bytes in that window can be used as
the "dictionary". A brute force search through all possible distances would be slow, and
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)
{
size_t pos;
unsigned i, error = 0;
/*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8;
unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/
unsigned numzeros = 0;
unsigned offset; /*the offset represents the distance in LZ77 terminology*/
unsigned length;
unsigned lazy = 0;
unsigned lazylength = 0, lazyoffset = 0;
unsigned hashval;
unsigned current_offset, current_length;
unsigned prev_offset;
const unsigned char *lastptr, *foreptr, *backptr;
unsigned hashpos;
if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/
if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/
if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;
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(numzeros == 0) numzeros = countZeros(in, insize, pos);
else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
}
else
{
numzeros = 0;
}
updateHashChain(hash, wpos, hashval, numzeros);
/*the length and offset found for the current position*/
length = 0;
offset = 0;
hashpos = hash->chain[wpos];
lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
/*search for the longest string*/
prev_offset = 0;
for(;;)
{
if(chainlength++ >= maxchainlength) break;
current_offset = 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)
{
/*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)
{
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*/
{
++backptr;
++foreptr;
}
current_length = (unsigned)(foreptr - &in[pos]);
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
out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/
if(current_length >= nicematch) break;
}
}
if(hashpos == hash->chain[hashpos]) break;
if(numzeros >= 3 && length > numzeros)
{
hashpos = hash->chainz[hashpos];
if(hash->zeros[hashpos] != numzeros) break;
}
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)
{
lazy = 1;
lazylength = length;
lazyoffset = offset;
continue; /*try the next byte*/
}
if(lazy)
{
lazy = 0;
if(pos == 0) ERROR_BREAK(81);
if(length > lazylength + 1)
{
/*push the previous character as literal*/
if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
}
else
{
length = lazylength;
offset = lazyoffset;
hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
hash->headz[numzeros] = -1; /*idem*/
--pos;
}
}
}
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(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
}
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
{
addLengthDistance(out, length, offset);
for(i = 1; i < length; ++i)
{
++pos;
wpos = pos & (windowsize - 1);
hashval = getHash(in, insize, pos);
if(usezeros && hashval == 0)
{
if(numzeros == 0) numzeros = countZeros(in, insize, pos);
else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
}
else
{
numzeros = 0;
}
updateHashChain(hash, wpos, hashval, numzeros);
}
}
} /*end of the loop through each character of input*/
return error;
}
/* /////////////////////////////////////////////////////////////////////////// */
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)
{
unsigned BFINAL, BTYPE, LEN, NLEN;
unsigned char firstbyte;
BFINAL = (i == numdeflateblocks - 1);
BTYPE = 0;
firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1));
ucvector_push_back(out, firstbyte);
LEN = 65535;
if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos;
NLEN = 65535 - LEN;
ucvector_push_back(out, (unsigned char)(LEN & 255));
ucvector_push_back(out, (unsigned char)(LEN >> 8));
ucvector_push_back(out, (unsigned char)(NLEN & 255));
ucvector_push_back(out, (unsigned char)(NLEN >> 8));
/*Decompressed data*/
for(j = 0; j < 65535 && datapos < datasize; ++j)
{
ucvector_push_back(out, data[datapos++]);
}
}
return 0;
}
/*
write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
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)
{
size_t i = 0;
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*/
{
unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
unsigned length_extra_bits = lz77_encoded->data[++i];
unsigned distance_code = lz77_encoded->data[++i];
unsigned distance_index = distance_code;
unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
unsigned distance_extra_bits = lz77_encoded->data[++i];
addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits);
addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code),
HuffmanTree_getLength(tree_d, distance_code));
addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits);
}
}
}
/*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)
{
unsigned error = 0;
/*
A block is compressed as follows: The PNG data is lz77 encoded, resulting in
literal bytes and length/distance pairs. This is then huffman compressed with
two huffman trees. One huffman tree is used for the lit and len values ("ll"),
another huffman tree is used for the dist values ("d"). These two trees are
stored using their code lengths, and to compress even more these code lengths
are also run-length encoded and huffman compressed. This gives a huffman tree
of code lengths "cl". The code lenghts used to describe this third tree are
the code length code lengths ("clcl").
*/
/*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
uivector lz77_encoded;
HuffmanTree tree_ll; /*tree for lit,len values*/
HuffmanTree tree_d; /*tree for distance codes*/
HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
uivector frequencies_ll; /*frequency of lit,len codes*/
uivector frequencies_d; /*frequency of dist codes*/
uivector frequencies_cl; /*frequency of code length codes*/
uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/
uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/
/*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
(these are written as is in the file, it would be crazy to compress these using yet another huffman
tree that needs to be represented by yet another set of code lengths)*/
uivector bitlen_cl;
size_t datasize = dataend - datapos;
/*
Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies:
bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
*/
unsigned BFINAL = final;
size_t numcodes_ll, numcodes_d, i;
unsigned HLIT, HDIST, HCLEN;
uivector_init(&lz77_encoded);
HuffmanTree_init(&tree_ll);
HuffmanTree_init(&tree_d);
HuffmanTree_init(&tree_cl);
uivector_init(&frequencies_ll);
uivector_init(&frequencies_d);
uivector_init(&frequencies_cl);
uivector_init(&bitlen_lld);
uivector_init(&bitlen_lld_e);
uivector_init(&bitlen_cl);
/*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)
{
error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
settings->minmatch, settings->nicematch, settings->lazymatching);
if(error) break;
}
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*/
}
if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
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)
{
unsigned symbol = lz77_encoded.data[i];
++frequencies_ll.data[symbol];
if(symbol > 256)
{
unsigned dist = lz77_encoded.data[i + 2];
++frequencies_d.data[dist];
i += 3;
}
}
frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
/*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15);
if(error) break;
/*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15);
if(error) break;
numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286;
numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30;
/*store the code lengths of both generated trees in bitlen_lld*/
for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i));
for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i));
/*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)
{
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*/
{
++j; /*include the first zero*/
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*/
{
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*/
{
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)
{
uivector_push_back(&bitlen_lld_e, 16);
uivector_push_back(&bitlen_lld_e, 6 - 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*/
{
uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
}
}
/*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)
{
++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*/
if(bitlen_lld_e.data[i] >= 16) ++i;
}
error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data,
frequencies_cl.size, frequencies_cl.size, 7);
if(error) break;
if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/);
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)
{
/*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*/);
}
if(error) break;
/*
Write everything into the output
After the BFINAL and BTYPE, the dynamic block consists out of the following:
- 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
- (HCLEN+4)*3 bits code lengths of code length alphabet
- HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length
alphabet, + possible repetition codes 16, 17, 18)
- HDIST + 1 code lengths of distance alphabet (encoded using the code length
alphabet, + possible repetition codes 16, 17, 18)
- compressed data
- 256 (end code)
*/
/*Write block type*/
addBitToStream(bp, out, BFINAL);
addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/
addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/
/*write the HLIT, HDIST and HCLEN values*/
HLIT = (unsigned)(numcodes_ll - 257);
HDIST = (unsigned)(numcodes_d - 1);
HCLEN = (unsigned)bitlen_cl.size - 4;
/*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN;
addBitsToStream(bp, out, HLIT, 5);
addBitsToStream(bp, out, HDIST, 5);
addBitsToStream(bp, out, HCLEN, 4);
/*write the code lenghts of the code length alphabet*/
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)
{
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*/
if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2);
else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3);
else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7);
}
/*write the compressed data symbols*/
writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
/*error: the length of the end code 256 must be larger than 0*/
if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64);
/*write the end code*/
addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
break; /*end of error-while*/
}
/*cleanup*/
uivector_cleanup(&lz77_encoded);
HuffmanTree_cleanup(&tree_ll);
HuffmanTree_cleanup(&tree_d);
HuffmanTree_cleanup(&tree_cl);
uivector_cleanup(&frequencies_ll);
uivector_cleanup(&frequencies_d);
uivector_cleanup(&frequencies_cl);
uivector_cleanup(&bitlen_lld_e);
uivector_cleanup(&bitlen_lld);
uivector_cleanup(&bitlen_cl);
return error;
}
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)
{
HuffmanTree tree_ll; /*tree for literal values and length codes*/
HuffmanTree tree_d; /*tree for distance codes*/
unsigned BFINAL = final;
unsigned error = 0;
size_t i;
HuffmanTree_init(&tree_ll);
HuffmanTree_init(&tree_d);
generateFixedLitLenTree(&tree_ll);
generateFixedDistanceTree(&tree_d);
addBitToStream(bp, out, BFINAL);
addBitToStream(bp, out, 1); /*first bit of BTYPE*/
addBitToStream(bp, out, 0); /*second bit of BTYPE*/
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)
{
addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i]));
}
}
/*add END code*/
if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
/*cleanup*/
HuffmanTree_cleanup(&tree_ll);
HuffmanTree_cleanup(&tree_d);
return error;
}
static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings)
{
unsigned error = 0;
size_t i, blocksize, numdeflateblocks;
size_t bp = 0; /*the bit pointer*/
Hash hash;
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)*/
{
/*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/
blocksize = insize / 8 + 8;
if(blocksize < 65536) blocksize = 65536;
if(blocksize > 262144) blocksize = 262144;
}
numdeflateblocks = (insize + blocksize - 1) / blocksize;
if(numdeflateblocks == 0) numdeflateblocks = 1;
error = hash_init(&hash, settings->windowsize);
if(error) return error;
for(i = 0; i != numdeflateblocks && !error; ++i)
{
unsigned final = (i == numdeflateblocks - 1);
size_t start = i * blocksize;
size_t end = start + blocksize;
if(end > insize) end = insize;
if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final);
else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final);
}
hash_cleanup(&hash);
return error;
}
unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings)
{
unsigned error;
ucvector v;
ucvector_init_buffer(&v, *out, *outsize);
error = lodepng_deflatev(&v, in, insize, settings);
*out = v.data;
*outsize = v.size;
return error;
}
static unsigned deflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings)
{
if(settings->custom_deflate)
{
return settings->custom_deflate(out, outsize, in, insize, settings);
}
else
{
return lodepng_deflate(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / Adler32 */
/* ////////////////////////////////////////////////////////////////////////// */
static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len)
{
unsigned s1 = adler & 0xffff;
unsigned s2 = (adler >> 16) & 0xffff;
while(len > 0)
{
/*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/
unsigned amount = len > 5550 ? 5550 : len;
len -= amount;
while(amount > 0)
{
s1 += (*data++);
s2 += s1;
--amount;
}
s1 %= 65521;
s2 %= 65521;
}
return (s2 << 16) | s1;
}
/*Return the adler32 of the bytes data[0..len-1]*/
static unsigned adler32(const unsigned char* data, unsigned len)
{
return update_adler32(1L, data, len);
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / Zlib / */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_DECODER
unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
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)
{
/*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
return 24;
}
CM = in[0] & 15;
CINFO = (in[0] >> 4) & 15;
/*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
FDICT = (in[1] >> 5) & 1;
/*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
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)
{
/*error: the specification of PNG says about the zlib stream:
"The additional flags shall not specify a preset dictionary."*/
return 26;
}
error = inflate(out, outsize, in + 2, insize - 2, settings);
if(error) return error;
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*/
}
return 0; /*no error*/
}
static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
size_t insize, const LodePNGDecompressSettings* settings)
{
if(settings->custom_zlib)
{
return settings->custom_zlib(out, outsize, in, insize, settings);
}
else
{
return lodepng_zlib_decompress(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
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;
size_t i;
unsigned error;
unsigned char* deflatedata = 0;
size_t deflatesize = 0;
/*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
unsigned FLEVEL = 0;
unsigned FDICT = 0;
unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
unsigned FCHECK = 31 - CMFFLG % 31;
CMFFLG += FCHECK;
/*ucvector-controlled version of the output buffer, for dynamic array*/
ucvector_init_buffer(&outv, *out, *outsize);
ucvector_push_back(&outv, (unsigned char)(CMFFLG >> 8));
ucvector_push_back(&outv, (unsigned char)(CMFFLG & 255));
error = deflate(&deflatedata, &deflatesize, in, insize, settings);
if(!error)
{
unsigned ADLER32 = adler32(in, (unsigned)insize);
for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]);
lodepng_free(deflatedata);
lodepng_add32bitInt(&outv, ADLER32);
}
*out = outv.data;
*outsize = outv.size;
return error;
}
/* 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)
{
return settings->custom_zlib(out, outsize, in, insize, settings);
}
else
{
return lodepng_zlib_compress(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#else /*no LODEPNG_COMPILE_ZLIB*/
#ifdef LODEPNG_COMPILE_DECODER
static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
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)
{
if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
return settings->custom_zlib(out, outsize, in, insize, settings);
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_ENCODER
/*this is a good tradeoff between speed and compression ratio*/
#define DEFAULT_WINDOWSIZE 2048
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;
settings->windowsize = DEFAULT_WINDOWSIZE;
settings->minmatch = 3;
settings->nicematch = 128;
settings->lazymatching = 1;
settings->custom_zlib = 0;
settings->custom_deflate = 0;
settings->custom_context = 0;
}
const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DECODER
void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings)
{
settings->ignore_adler32 = 0;
settings->custom_zlib = 0;
settings->custom_inflate = 0;
settings->custom_context = 0;
}
const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0};
#endif /*LODEPNG_COMPILE_DECODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // End of Zlib related code. Begin of PNG related code. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_PNG
/* ////////////////////////////////////////////////////////////////////////// */
/* / CRC32 / */
/* ////////////////////////////////////////////////////////////////////////// */
#ifndef LODEPNG_NO_COMPILE_CRC
/* CRC polynomial: 0xedb88320 */
static unsigned lodepng_crc32_table[256] = {
0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u,
249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u,
498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u,
325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u,
997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u,
651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u,
671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u,
1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u,
2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u,
1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u,
1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u,
1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u,
1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u,
1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u,
3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u,
3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u,
4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u,
4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u,
3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u,
3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u,
3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u,
2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u,
2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u,
2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u,
2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u,
2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u,
3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u,
3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u
};
/*Return the CRC of the bytes buf[0..len-1].*/
unsigned lodepng_crc32(const unsigned char* data, size_t length)
{
unsigned r = 0xffffffffu;
size_t i;
for(i = 0; i < length; ++i)
{
r = lodepng_crc32_table[(r ^ data[i]) & 0xff] ^ (r >> 8);
}
return r ^ 0xffffffffu;
}
#else /* !LODEPNG_NO_COMPILE_CRC */
unsigned lodepng_crc32(const unsigned char* data, size_t length);
#endif /* !LODEPNG_NO_COMPILE_CRC */
/* ////////////////////////////////////////////////////////////////////////// */
/* / Reading and writing single bits and bytes from/to stream for LodePNG / */
/* ////////////////////////////////////////////////////////////////////////// */
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)
{
unsigned result = 0;
size_t i;
for(i = nbits - 1; i < nbits; --i)
{
result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i;
}
return result;
}
#ifdef LODEPNG_COMPILE_DECODER
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)
{
/*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7)));
}
++(*bitpointer);
}
#endif /*LODEPNG_COMPILE_DECODER*/
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)));
++(*bitpointer);
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / PNG chunks / */
/* ////////////////////////////////////////////////////////////////////////// */
unsigned lodepng_chunk_length(const unsigned char* chunk)
{
return lodepng_read32bitInt(&chunk[0]);
}
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)
{
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)
{
return((chunk[4] & 32) != 0);
}
unsigned char lodepng_chunk_private(const unsigned char* chunk)
{
return((chunk[6] & 32) != 0);
}
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk)
{
return((chunk[7] & 32) != 0);
}
unsigned char* lodepng_chunk_data(unsigned char* chunk)
{
return &chunk[8];
}
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk)
{
return &chunk[8];
}
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*/
unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
if(CRC != checksum) return 1;
else return 0;
}
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 total_chunk_length = lodepng_chunk_length(chunk) + 12;
return &chunk[total_chunk_length];
}
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk)
{
unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
return &chunk[total_chunk_length];
}
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;
size_t new_length = (*outlength) + total_chunk_length;
if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
if(!new_buffer) return 83; /*alloc fail*/
(*out) = new_buffer;
(*outlength) = new_length;
chunk_start = &(*out)[new_length - total_chunk_length];
for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
return 0;
}
unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
const char* type, const unsigned char* data)
{
unsigned i;
unsigned char *chunk, *new_buffer;
size_t new_length = (*outlength) + length + 12;
if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
if(!new_buffer) return 83; /*alloc fail*/
(*out) = new_buffer;
(*outlength) = new_length;
chunk = &(*out)[(*outlength) - length - 12];
/*1: length*/
lodepng_set32bitInt(chunk, (unsigned)length);
/*2: chunk name (4 letters)*/
chunk[4] = (unsigned char)type[0];
chunk[5] = (unsigned char)type[1];
chunk[6] = (unsigned char)type[2];
chunk[7] = (unsigned char)type[3];
/*3: the data*/
for(i = 0; i != length; ++i) chunk[8 + i] = data[i];
/*4: CRC (of the chunkname characters and the data)*/
lodepng_chunk_generate_crc(chunk);
return 0;
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / Color types and such / */
/* ////////////////////////////////////////////////////////////////////////// */
/*return type is a LodePNG error code*/
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*/
case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/
case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/
default: return 31;
}
return 0; /*allowed color type / bits combination*/
}
static unsigned getNumColorChannels(LodePNGColorType colortype)
{
switch(colortype)
{
case 0: return 1; /*grey*/
case 2: return 3; /*RGB*/
case 3: return 1; /*palette*/
case 4: return 2; /*grey + alpha*/
case 6: return 4; /*RGBA*/
}
return 0; /*unexisting color type*/
}
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)
{
info->key_defined = 0;
info->key_r = info->key_g = info->key_b = 0;
info->colortype = LCT_RGBA;
info->bitdepth = 8;
info->palette = 0;
info->palettesize = 0;
}
void lodepng_color_mode_cleanup(LodePNGColorMode* info)
{
lodepng_palette_clear(info);
}
unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source)
{
size_t i;
lodepng_color_mode_cleanup(dest);
*dest = *source;
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];
}
return 0;
}
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_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 one of the palette sizes is 0, then we consider it to be the same as the
other: it means that e.g. the palette was not given by the user and should be
considered the same as the palette inside the PNG.*/
if(1/*a->palettesize != 0 && b->palettesize != 0*/) {
if(a->palettesize != b->palettesize) return 0;
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)
{
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* 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*/
{
/*room for 256 colors with 4 bytes each*/
data = (unsigned char*)lodepng_realloc(info->palette, 1024);
if(!data) return 83; /*alloc fail*/
else info->palette = data;
}
info->palette[4 * info->palettesize + 0] = r;
info->palette[4 * info->palettesize + 1] = g;
info->palette[4 * info->palettesize + 2] = b;
info->palette[4 * info->palettesize + 3] = a;
++info->palettesize;
return 0;
}
unsigned lodepng_get_bpp(const LodePNGColorMode* info)
{
/*calculate bits per pixel out of colortype and bitdepth*/
return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
}
unsigned lodepng_get_channels(const LodePNGColorMode* info)
{
return getNumColorChannels(info->colortype);
}
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)
{
return (info->colortype & 4) != 0; /*4 or 6*/
}
unsigned lodepng_is_palette_type(const LodePNGColorMode* info)
{
return info->colortype == LCT_PALETTE;
}
unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info)
{
size_t 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)
{
return info->key_defined
|| lodepng_is_alpha_type(info)
|| lodepng_has_palette_alpha(info);
}
size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color)
{
/*will not overflow for any color type if roughly w * h < 268435455*/
size_t bpp = lodepng_get_bpp(color);
size_t n = w * h;
return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8;
}
size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
{
/*will not overflow for any color type if roughly w * h < 268435455*/
size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth);
size_t n = w * h;
return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8;
}
#ifdef LODEPNG_COMPILE_PNG
#ifdef LODEPNG_COMPILE_DECODER
/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/
static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color)
{
/*will not overflow for any color type if roughly w * h < 268435455*/
size_t bpp = lodepng_get_bpp(color);
size_t line = ((w / 8) * bpp) + ((w & 7) * bpp + 7) / 8;
return h * line;
}
#endif /*LODEPNG_COMPILE_DECODER*/
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
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)
{
unsigned i;
for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
}
static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src)
{
unsigned i;
LodePNGUnknownChunks_cleanup(dest);
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)
{
dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
}
}
return 0;
}
/******************************************************************************/
static void LodePNGText_init(LodePNGInfo* info)
{
info->text_num = 0;
info->text_keys = NULL;
info->text_strings = NULL;
}
static void LodePNGText_cleanup(LodePNGInfo* info)
{
size_t i;
for(i = 0; i != info->text_num; ++i)
{
string_cleanup(&info->text_keys[i]);
string_cleanup(&info->text_strings[i]);
}
lodepng_free(info->text_keys);
lodepng_free(info->text_strings);
}
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)
{
CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
}
return 0;
}
void lodepng_clear_text(LodePNGInfo* info)
{
LodePNGText_cleanup(info);
}
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)
{
lodepng_free(new_keys);
lodepng_free(new_strings);
return 83; /*alloc fail*/
}
++info->text_num;
info->text_keys = new_keys;
info->text_strings = new_strings;
string_init(&info->text_keys[info->text_num - 1]);
string_set(&info->text_keys[info->text_num - 1], key);
string_init(&info->text_strings[info->text_num - 1]);
string_set(&info->text_strings[info->text_num - 1], str);
return 0;
}
/******************************************************************************/
static void LodePNGIText_init(LodePNGInfo* info)
{
info->itext_num = 0;
info->itext_keys = NULL;
info->itext_langtags = NULL;
info->itext_transkeys = NULL;
info->itext_strings = NULL;
}
static void LodePNGIText_cleanup(LodePNGInfo* info)
{
size_t 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]);
string_cleanup(&info->itext_strings[i]);
}
lodepng_free(info->itext_keys);
lodepng_free(info->itext_langtags);
lodepng_free(info->itext_transkeys);
lodepng_free(info->itext_strings);
}
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)
{
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)
{
LodePNGIText_cleanup(info);
}
unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
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)
{
lodepng_free(new_keys);
lodepng_free(new_langtags);
lodepng_free(new_transkeys);
lodepng_free(new_strings);
return 83; /*alloc fail*/
}
++info->itext_num;
info->itext_keys = new_keys;
info->itext_langtags = new_langtags;
info->itext_transkeys = new_transkeys;
info->itext_strings = new_strings;
string_init(&info->itext_keys[info->itext_num - 1]);
string_set(&info->itext_keys[info->itext_num - 1], key);
string_init(&info->itext_langtags[info->itext_num - 1]);
string_set(&info->itext_langtags[info->itext_num - 1], langtag);
string_init(&info->itext_transkeys[info->itext_num - 1]);
string_set(&info->itext_transkeys[info->itext_num - 1], transkey);
string_init(&info->itext_strings[info->itext_num - 1]);
string_set(&info->itext_strings[info->itext_num - 1], str);
return 0;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
void lodepng_info_init(LodePNGInfo* info)
{
lodepng_color_mode_init(&info->color);
info->interlace_method = 0;
info->compression_method = 0;
info->filter_method = 0;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
info->background_defined = 0;
info->background_r = info->background_g = info->background_b = 0;
LodePNGText_init(info);
LodePNGIText_init(info);
info->time_defined = 0;
info->phys_defined = 0;
LodePNGUnknownChunks_init(info);
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
void lodepng_info_cleanup(LodePNGInfo* info)
{
lodepng_color_mode_cleanup(&info->color);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
LodePNGText_cleanup(info);
LodePNGIText_cleanup(info);
LodePNGUnknownChunks_cleanup(info);
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source)
{
lodepng_info_cleanup(dest);
*dest = *source;
lodepng_color_mode_init(&dest->color);
CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
LodePNGUnknownChunks_init(dest);
CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
return 0;
}
void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b)
{
LodePNGInfo temp = *a;
*a = *b;
*b = temp;
}
/* ////////////////////////////////////////////////////////////////////////// */
/*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)
{
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;
in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
in = in << (bits * (m - p));
if(p == 0) out[index * bits / 8] = in;
else out[index * bits / 8] |= in;
}
typedef struct ColorTree ColorTree;
/*
One node of a color tree
This is the data structure used to count the number of unique colors and to get a palette
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
{
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)
{
int i;
for(i = 0; i != 16; ++i) tree->children[i] = 0;
tree->index = -1;
}
static void color_tree_cleanup(ColorTree* tree)
{
int i;
for(i = 0; i != 16; ++i)
{
if(tree->children[i])
{
color_tree_cleanup(tree->children[i]);
lodepng_free(tree->children[i]);
}
}
}
/*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)
{
int bit = 0;
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];
}
return tree ? tree->index : -1;
}
#ifdef LODEPNG_COMPILE_ENCODER
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*/
/*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)
{
int 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])
{
tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));
color_tree_init(tree->children[i]);
}
tree = tree->children[i];
}
tree->index = (int)index;
}
/*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*/;
if(mode->bitdepth == 8) out[i] = grey;
else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey;
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)
{
out[i * 3 + 0] = r;
out[i * 3 + 1] = g;
out[i * 3 + 2] = b;
}
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)
{
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)
{
out[i * 2 + 0] = grey;
out[i * 2 + 1] = a;
}
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)
{
out[i * 4 + 0] = r;
out[i * 4 + 1] = g;
out[i * 4 + 2] = b;
out[i * 4 + 3] = a;
}
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;
out[i * 8 + 6] = out[i * 8 + 7] = a;
}
}
return 0; /*no error*/
}
/*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*/;
out[i * 2 + 0] = (grey >> 8) & 255;
out[i * 2 + 1] = grey & 255;
}
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*/;
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)
{
out[i * 8 + 0] = (r >> 8) & 255;
out[i * 8 + 1] = r & 255;
out[i * 8 + 2] = (g >> 8) & 255;
out[i * 8 + 3] = g & 255;
out[i * 8 + 4] = (b >> 8) & 255;
out[i * 8 + 5] = b & 255;
out[i * 8 + 6] = (a >> 8) & 255;
out[i * 8 + 7] = a & 255;
}
}
/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
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)
{
*r = *g = *b = in[i];
if(mode->key_defined && *r == mode->key_r) *a = 0;
else *a = 255;
}
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
{
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);
*r = *g = *b = (value * 255) / highest;
if(mode->key_defined && value == mode->key_r) *a = 0;
else *a = 255;
}
}
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
{
*r = in[i * 6 + 0];
*g = in[i * 6 + 2];
*b = in[i * 6 + 4];
if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
&& 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 = 255;
}
}
else if(mode->colortype == LCT_PALETTE)
{
unsigned index;
if(mode->bitdepth == 8) index = in[i];
else
{
size_t j = i * mode->bitdepth;
index = readBitsFromReversedStream(&j, in, mode->bitdepth);
}
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
{
*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)
{
*r = *g = *b = in[i * 2 + 0];
*a = in[i * 2 + 1];
}
else
{
*r = *g = *b = in[i * 4 + 0];
*a = in[i * 4 + 2];
}
}
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
{
*r = in[i * 8 + 0];
*g = in[i * 8 + 2];
*b = in[i * 8 + 4];
*a = in[i * 8 + 6];
}
}
}
/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
mode test cases, optimized to convert the colors much faster, when converting
to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with
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)
{
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)
{
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)
{
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
{
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)
{
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)
{
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)
{
buffer[0] = in[i * 6 + 0];
buffer[1] = in[i * 6 + 2];
buffer[2] = in[i * 6 + 4];
if(has_alpha) buffer[3] = mode->key_defined
&& 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
}
}
}
else if(mode->colortype == LCT_PALETTE)
{
unsigned index;
size_t j = 0;
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)
{
/*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
{
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)
{
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)
{
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)
{
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)
{
buffer[0] = in[i * 8 + 0];
buffer[1] = in[i * 8 + 2];
buffer[2] = in[i * 8 + 4];
if(has_alpha) buffer[3] = in[i * 8 + 6];
}
}
}
}
/*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)
{
*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)
{
*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];
if(mode->key_defined
&& 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
&& 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)
{
*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)
{
*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];
*a = 256u * in[i * 8 + 6] + in[i * 8 + 7];
}
}
unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
unsigned w, unsigned h)
{
size_t i;
ColorTree tree;
size_t numpixels = w * h;
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)
{
size_t palettesize = mode_out->palettesize;
const unsigned char* palette = mode_out->palette;
size_t palsize = 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)
{
palettesize = mode_in->palettesize;
palette = mode_in->palette;
}
if(palettesize < palsize) palsize = palettesize;
color_tree_init(&tree);
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], 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)
{
getPixelColorsRGBA8(out, numpixels, 1, in, mode_in);
}
else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB)
{
getPixelColorsRGBA8(out, numpixels, 0, in, mode_in);
}
else
{
unsigned char r = 0, g = 0, b = 0, a = 0;
for(i = 0; i != numpixels; ++i)
{
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
CERROR_TRY_RETURN(rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a));
}
}
if(mode_out->colortype == LCT_PALETTE)
{
color_tree_cleanup(&tree);
}
return 0; /*no error*/
}
#ifdef LODEPNG_COMPILE_ENCODER
void lodepng_color_profile_init(LodePNGColorProfile* profile)
{
profile->colored = 0;
profile->key = 0;
profile->alpha = 0;
profile->key_r = profile->key_g = profile->key_b = 0;
profile->numcolors = 0;
profile->bits = 1;
}
/*function used for debug purposes with C++*/
/*void printColorProfile(LodePNGColorProfile* p)
{
std::cout << "colored: " << (int)p->colored << ", ";
std::cout << "key: " << (int)p->key << ", ";
std::cout << "key_r: " << (int)p->key_r << ", ";
std::cout << "key_g: " << (int)p->key_g << ", ";
std::cout << "key_b: " << (int)p->key_b << ", ";
std::cout << "alpha: " << (int)p->alpha << ", ";
std::cout << "numcolors: " << (int)p->numcolors << ", ";
std::cout << "bits: " << (int)p->bits << std::endl;
}*/
/*Returns how many bits needed to represent given value (max 8 bit)*/
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;
return 8;
}
/*profile must already have been inited with mode.
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)
{
unsigned error = 0;
size_t i;
ColorTree tree;
size_t numpixels = w * h;
unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0;
unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1;
unsigned numcolors_done = 0;
unsigned bpp = lodepng_get_bpp(mode);
unsigned bits_done = bpp == 1 ? 1 : 0;
unsigned maxnumcolors = 257;
unsigned sixteen = 0;
if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256));
color_tree_init(&tree);
/*Check if the 16-bit input is truly 16-bit*/
if(mode->bitdepth == 16)
{
unsigned short r, g, b, a;
for(i = 0; i != numpixels; ++i)
{
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
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*/
{
sixteen = 1;
break;
}
}
}
if(sixteen)
{
unsigned short r = 0, g = 0, b = 0, a = 0;
profile->bits = 16;
bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
for(i = 0; i != numpixels; ++i)
{
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
if(!colored_done && (r != g || r != b))
{
profile->colored = 1;
colored_done = 1;
}
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)))
{
profile->alpha = 1;
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)
{
profile->key = 1;
profile->key_r = r;
profile->key_g = g;
profile->key_b = b;
}
else if(a == 65535 && profile->key && matchkey)
{
/* Color key cannot be used if an opaque pixel also has that RGB color. */
profile->alpha = 1;
alpha_done = 1;
}
}
if(alpha_done && numcolors_done && colored_done && bits_done) break;
}
if(profile->key && !profile->alpha)
{
for(i = 0; i != numpixels; ++i)
{
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
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;
alpha_done = 1;
}
}
}
}
else /* < 16-bit */
{
unsigned char r = 0, g = 0, b = 0, a = 0;
for(i = 0; i != numpixels; ++i)
{
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode);
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))
{
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)
{
unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
if(a != 255 && (a != 0 || (profile->key && !matchkey)))
{
profile->alpha = 1;
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)
{
profile->key = 1;
profile->key_r = r;
profile->key_g = g;
profile->key_b = b;
}
else if(a == 255 && profile->key && matchkey)
{
/* Color key cannot be used if an opaque pixel also has that RGB color. */
profile->alpha = 1;
alpha_done = 1;
if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
}
}
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)
{
unsigned char* p = profile->palette;
unsigned n = profile->numcolors;
p[n * 4 + 0] = r;
p[n * 4 + 1] = g;
p[n * 4 + 2] = b;
p[n * 4 + 3] = a;
}
++profile->numcolors;
numcolors_done = profile->numcolors >= maxnumcolors;
}
}
if(alpha_done && numcolors_done && colored_done && bits_done) break;
}
if(profile->key && !profile->alpha)
{
for(i = 0; i != numpixels; ++i)
{
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode);
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;
alpha_done = 1;
}
}
}
/*make the profile's key always 16-bit for consistency - repeat each byte twice*/
profile->key_r += (profile->key_r << 8);
profile->key_g += (profile->key_g << 8);
profile->key_b += (profile->key_b << 8);
}
color_tree_cleanup(&tree);
return error;
}
/*Automatically chooses color type that gives smallest amount of bits in the
output image, e.g. grey if there are only greyscale pixels, palette if there
are less than 256 colors, ...
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)
{
LodePNGColorProfile prof;
unsigned error = 0;
unsigned i, n, palettebits, grey_ok, palette_ok;
lodepng_color_profile_init(&prof);
error = lodepng_get_color_profile(&prof, image, w, h, mode_in);
if(error) return error;
mode_out->key_defined = 0;
if(prof.key && w * h <= 16)
{
prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
}
grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/
n = prof.numcolors;
palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8;
if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/
if(palette_ok)
{
unsigned char* p = prof.palette;
lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
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;
}
mode_out->colortype = LCT_PALETTE;
mode_out->bitdepth = palettebits;
if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
&& 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*/
{
mode_out->bitdepth = prof.bits;
mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA)
: (prof.colored ? LCT_RGB : LCT_GREY);
if(prof.key && !prof.alpha)
{
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;
mode_out->key_b = prof.key_b & mask;
mode_out->key_defined = 1;
}
}
return error;
}
#endif /* #ifdef LODEPNG_COMPILE_ENCODER */
/*
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)
{
short pa = abs(b - c);
short pb = abs(a - c);
short pc = abs(a + b - c - c);
if(pc < pa && pc < pb) return (unsigned char)c;
else if(pb < pa) return (unsigned char)b;
else return (unsigned char)a;
}
/*shared values used by multiple Adam7 related functions*/
static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
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*/
/*
Outputs various dimensions and positions in the image related to the Adam7 reduced images.
passw: output containing the width of the 7 passes
passh: output containing the height of the 7 passes
filter_passstart: output containing the index of the start and end of each
reduced image with filter bytes
padded_passstart output containing the index of the start and end of each
reduced image when without filter bytes but with padded scanlines
passstart: output containing the index of the start and end of each reduced
image without padding between scanlines, but still padding between the images
w, h: width and height of non-interlaced image
bpp: bits per pixel
"padded" is only relevant if bpp is less than 8 and a scanline or image does not
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)
{
/*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)
{
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;
if(passh[i] == 0) passw[i] = 0;
}
filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
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);
/*bits padded if needed to fill full byte at end of each scanline*/
padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8);
/*only padded at end of reduced image*/
passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8;
}
}
#ifdef LODEPNG_COMPILE_DECODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / PNG Decoder / */
/* ////////////////////////////////////////////////////////////////////////// */
/*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)
{
LodePNGInfo* info = &state->info_png;
if(insize == 0 || in == 0)
{
CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
}
if(insize < 33)
{
CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
}
/*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
lodepng_info_cleanup(info);
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)
{
CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
}
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"))
{
CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
}
/*read the values given in the header*/
*w = lodepng_read32bitInt(&in[16]);
*h = lodepng_read32bitInt(&in[20]);
info->color.bitdepth = in[24];
info->color.colortype = (LodePNGColorType)in[25];
info->compression_method = in[26];
info->filter_method = in[27];
info->interlace_method = in[28];
if(*w == 0 || *h == 0)
{
CERROR_RETURN_ERROR(state->error, 93);
}
if(!state->decoder.ignore_crc)
{
unsigned CRC = lodepng_read32bitInt(&in[29]);
unsigned checksum = lodepng_crc32(&in[12], 17);
if(CRC != checksum)
{
CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
}
}
/*error: only compression method 0 is allowed in the specification*/
if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
/*error: only filter method 0 is allowed in the specification*/
if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
/*error: only interlace methods 0 and 1 exist in the specification*/
if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
return state->error;
}
static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
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,
the filter works byte per byte (bytewidth = 1)
precon is the previous unfiltered scanline, recon the result, scanline the current one
the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
recon and scanline MAY be the same memory address! precon must be disjoint.
*/
size_t i;
switch(filterType)
{
case 0:
for(i = 0; i != length; ++i) recon[i] = scanline[i];
break;
case 1:
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
break;
case 2:
if(precon)
{
for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
}
else
{
for(i = 0; i != length; ++i) recon[i] = scanline[i];
}
break;
case 3:
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
{
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)
{
recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[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)
{
recon[i] = scanline[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]);
}
}
break;
default: return 36; /*error: unexisting filter type given*/
}
return 0;
}
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)
out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
*/
unsigned y;
unsigned char* prevline = 0;
/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
size_t bytewidth = (bpp + 7) / 8;
size_t linebytes = (w * bpp + 7) / 8;
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];
CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
prevline = &out[outindex];
}
return 0;
}
/*
in: Adam7 interlaced image, with no padding bits between scanlines, but between
reduced images so that each reduced image starts at a byte.
out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
bpp: bits per pixel
out has the following size in bits: w * h * bpp.
in is possibly bigger due to padding bits between reduced images.
out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
(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)
{
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)
{
unsigned x, y, b;
size_t bytewidth = bpp / 8;
for(y = 0; y < passh[i]; ++y)
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)
{
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)
{
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)
{
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)
{
unsigned char bit = readBitFromReversedStream(&ibp, in);
/*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
setBitOfReversedStream0(&obp, out, bit);
}
}
}
}
}
static void removePaddingBits(unsigned char* out, const unsigned char* in,
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
for the Adam7 code, the color convert code and the output to the user.
in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
only useful if (ilinebits - olinebits) is a value in the range 1..7
*/
unsigned y;
size_t diff = ilinebits - olinebits;
size_t ibp = 0, obp = 0; /*input and output bit pointers*/
for(y = 0; y < h; ++y)
{
size_t x;
for(x = 0; x < olinebits; ++x)
{
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
ibp += diff;
}
}
/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
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)
{
/*
This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
Steps:
*) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
*) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
NOTE: the in buffer will be overwritten with intermediate data!
*/
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)
{
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)*/
{
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)
{
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)
{
/*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,
((passw[i] * bpp + 7) / 8) * 8, passh[i]);
}
}
Adam7_deinterlace(out, in, w, h, bpp);
}
return 0;
}
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)
{
color->palettesize = 0;
return 83; /*alloc fail*/
}
if(color->palettesize > 256) return 38; /*error: palette too big*/
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*/
color->palette[4 * i + 3] = 255; /*alpha*/
}
return 0; /* OK */
}
static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
{
unsigned i;
if(color->colortype == LCT_PALETTE)
{
/*error: more alpha values given than there are palette entries*/
if(chunkLength > color->palettesize) return 38;
for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
}
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)
{
/*error: this chunk must be 6 bytes for RGB image*/
if(chunkLength != 6) return 41;
color->key_defined = 1;
color->key_r = 256u * data[0] + data[1];
color->key_g = 256u * data[2] + data[3];
color->key_b = 256u * data[4] + data[5];
}
else return 42; /*error: tRNS chunk not allowed for other color models*/
return 0; /* OK */
}
#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)
{
/*error: this chunk must be 1 byte for indexed color image*/
if(chunkLength != 1) return 43;
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)
{
/*error: this chunk must be 2 bytes for greyscale image*/
if(chunkLength != 2) return 44;
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)
{
/*error: this chunk must be 6 bytes for greyscale image*/
if(chunkLength != 6) return 45;
info->background_defined = 1;
info->background_r = 256u * data[0] + data[1];
info->background_g = 256u * data[2] + data[3];
info->background_b = 256u * data[4] + data[5];
}
return 0; /* OK */
}
/*text chunk (tEXt)*/
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*/
{
unsigned length, string2_begin;
length = 0;
while(length < chunkLength && data[length] != 0) ++length;
/*even though it's not allowed by the standard, no error is thrown if
there's no null termination char, if the text is empty*/
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
key = (char*)lodepng_malloc(length + 1);
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
key[length] = 0;
for(i = 0; i != length; ++i) key[i] = (char)data[i];
string2_begin = length + 1; /*skip keyword null terminator*/
length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin;
str = (char*)lodepng_malloc(length + 1);
if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
str[length] = 0;
for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i];
error = lodepng_add_text(info, key, str);
break;
}
lodepng_free(key);
lodepng_free(str);
return error;
}
/*compressed text chunk (zTXt)*/
static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
const unsigned char* data, size_t chunkLength)
{
unsigned error = 0;
unsigned i;
unsigned length, string2_begin;
char *key = 0;
ucvector decoded;
ucvector_init(&decoded);
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*/
key = (char*)lodepng_malloc(length + 1);
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
key[length] = 0;
for(i = 0; i != length; ++i) key[i] = (char)data[i];
if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
string2_begin = length + 2;
if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
length = chunkLength - string2_begin;
/*will fail if zlib error, e.g. if length is too small*/
error = zlib_decompress(&decoded.data, &decoded.size,
(unsigned char*)(&data[string2_begin]),
length, zlibsettings);
if(error) break;
ucvector_push_back(&decoded, 0);
error = lodepng_add_text(info, key, (char*)decoded.data);
break;
}
lodepng_free(key);
ucvector_cleanup(&decoded);
return error;
}
/*international text chunk (iTXt)*/
static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
const unsigned char* data, size_t chunkLength)
{
unsigned error = 0;
unsigned i;
unsigned length, begin, compressed;
char *key = 0, *langtag = 0, *transkey = 0;
ucvector decoded;
ucvector_init(&decoded);
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*/
/*read the key*/
for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
key = (char*)lodepng_malloc(length + 1);
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
key[length] = 0;
for(i = 0; i != length; ++i) key[i] = (char)data[i];
/*read the compression method*/
compressed = data[length + 1];
if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
/*even though it's not allowed by the standard, no error is thrown if
there's no null termination char, if the text is empty for the next 3 texts*/
/*read the langtag*/
begin = length + 3;
length = 0;
for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
langtag = (char*)lodepng_malloc(length + 1);
if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
langtag[length] = 0;
for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i];
/*read the transkey*/
begin += length + 1;
length = 0;
for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
transkey = (char*)lodepng_malloc(length + 1);
if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
transkey[length] = 0;
for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i];
/*read the actual text*/
begin += length + 1;
length = chunkLength < begin ? 0 : chunkLength - begin;
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]),
length, zlibsettings);
if(error) break;
if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
ucvector_push_back(&decoded, 0);
}
else
{
if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/);
decoded.data[length] = 0;
for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i];
}
error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data);
break;
}
lodepng_free(key);
lodepng_free(langtag);
lodepng_free(transkey);
ucvector_cleanup(&decoded);
return error;
}
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;
info->time.year = 256u * data[0] + data[1];
info->time.month = data[2];
info->time.day = data[3];
info->time.hour = data[4];
info->time.minute = data[5];
info->time.second = data[6];
return 0; /* OK */
}
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;
info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
info->phys_unit = data[8];
return 0; /* OK */
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*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)
{
unsigned char IEND = 0;
const unsigned char* chunk;
size_t i;
ucvector idat; /*the data from idat chunks*/
ucvector scanlines;
size_t predict;
size_t numpixels;
size_t outsize;
/*for unknown chunk order*/
unsigned unknown = 0;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*provide some proper output values if error will happen*/
*out = 0;
state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
if(state->error) return;
numpixels = *w * *h;
/*multiplication overflow*/
if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92);
/*multiplication overflow possible further below. Allows up to 2^31-1 pixel
bytes with 16-bit RGBA, the rest is room for filter bytes.*/
if(numpixels > 268435455) CERROR_RETURN(state->error, 92);
ucvector_init(&idat);
chunk = &in[33]; /*first byte of the first chunk after the header*/
/*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)
{
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) CERROR_BREAK(state->error, 30);
/*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) CERROR_BREAK(state->error, 63);
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*/
}
data = lodepng_chunk_data_const(chunk);
/*IDAT chunk, containing compressed image data*/
if(lodepng_chunk_type_equals(chunk, "IDAT"))
{
size_t oldsize = idat.size;
if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i];
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
critical_pos = 3;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
/*IEND chunk*/
else if(lodepng_chunk_type_equals(chunk, "IEND"))
{
IEND = 1;
}
/*palette chunk (PLTE)*/
else if(lodepng_chunk_type_equals(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)*/
else if(lodepng_chunk_type_equals(chunk, "tRNS"))
{
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"))
{
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)
{
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)
{
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)
{
state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
if(state->error) break;
}
}
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"))
{
state->error = readChunk_pHYs(&state->info_png, 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*/
{
/*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69);
unknown = 1;
#ifdef LODEPNG_COMPILE_ANCILLARY_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;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
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*/
}
if(!IEND) chunk = lodepng_chunk_next_const(chunk);
}
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)
{
/*The extra *h is added because this are the filter bytes every scanline starts with*/
predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h;
}
else
{
/*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/
const LodePNGColorMode* color = &state->info_png.color;
predict = 0;
predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3);
if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3);
predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color) + ((*h + 3) >> 3);
if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color) + ((*h + 3) >> 2);
predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color) + ((*h + 1) >> 2);
if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color) + ((*h + 1) >> 1);
predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color) + ((*h + 0) >> 1);
}
if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/
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)
{
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)
{
for(i = 0; i < outsize; i++) (*out)[i] = 0;
state->error = postProcessScanlines(*out, scanlines.data, *w, *h, &state->info_png);
}
ucvector_cleanup(&scanlines);
}
unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
LodePNGState* state,
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))
{
/*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)
{
state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
if(state->error) return state->error;
}
}
else
{
/*color conversion needed; sort of copy of the data*/
unsigned char* data = *out;
size_t outsize;
/*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))
{
return 56; /*unsupported color mode conversion*/
}
outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
*out = (unsigned char*)lodepng_malloc(outsize);
if(!(*out))
{
state->error = 83; /*alloc fail*/
return state->error;
}
else
{
data = *out;
state->error = lodepng_convert(*out, data, &state->info_raw, &state->info_png.color, *w, *h);
}
lodepng_free(data);
}
return state->error;
}
unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
size_t insize, LodePNGColorType colortype, unsigned bitdepth)
{
unsigned error;
LodePNGState state;
lodepng_state_init(&state);
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
error = lodepng_decode(out, w, h, &state, in, insize);
lodepng_state_cleanup(&state);
return error;
}
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)
{
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)
{
unsigned char* buffer = 0;
size_t buffersize;
unsigned error;
error = lodepng_load_file(&buffer, &buffersize, filename);
if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
lodepng_free(buffer);
return error;
}
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)
{
return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
}
#endif /*LODEPNG_COMPILE_DISK*/
void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings)
{
settings->color_convert = 1;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
settings->read_text_chunks = 1;
settings->remember_unknown_chunks = 0;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
settings->ignore_crc = 0;
lodepng_decompress_settings_init(&settings->zlibsettings);
}
#endif /*LODEPNG_COMPILE_DECODER*/
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
void lodepng_state_init(LodePNGState* state)
{
#ifdef LODEPNG_COMPILE_DECODER
lodepng_decoder_settings_init(&state->decoder);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
lodepng_encoder_settings_init(&state->encoder);
#endif /*LODEPNG_COMPILE_ENCODER*/
lodepng_color_mode_init(&state->info_raw);
lodepng_info_init(&state->info_png);
state->error = 1;
}
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)
{
lodepng_state_cleanup(dest);
*dest = *source;
lodepng_color_mode_init(&dest->info_raw);
lodepng_info_init(&dest->info_png);
dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
}
#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
#ifdef LODEPNG_COMPILE_ENCODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / PNG Encoder / */
/* ////////////////////////////////////////////////////////////////////////// */
/*chunkName must be string of 4 characters*/
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)
{
/*8 bytes PNG signature, aka the magic bytes*/
ucvector_push_back(out, 137);
ucvector_push_back(out, 80);
ucvector_push_back(out, 78);
ucvector_push_back(out, 71);
ucvector_push_back(out, 13);
ucvector_push_back(out, 10);
ucvector_push_back(out, 26);
ucvector_push_back(out, 10);
}
static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method)
{
unsigned error = 0;
ucvector header;
ucvector_init(&header);
lodepng_add32bitInt(&header, w); /*width*/
lodepng_add32bitInt(&header, h); /*height*/
ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/
ucvector_push_back(&header, (unsigned char)colortype); /*color type*/
ucvector_push_back(&header, 0); /*compression method*/
ucvector_push_back(&header, 0); /*filter method*/
ucvector_push_back(&header, interlace_method); /*interlace method*/
error = addChunk(out, "IHDR", header.data, header.size);
ucvector_cleanup(&header);
return error;
}
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)
{
/*add all channels except alpha channel*/
if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
}
error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
ucvector_cleanup(&PLTE);
return error;
}
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)
{
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)
{
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)
{
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)
{
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));
ucvector_push_back(&tRNS, (unsigned char)(info->key_g & 255));
ucvector_push_back(&tRNS, (unsigned char)(info->key_b >> 8));
ucvector_push_back(&tRNS, (unsigned char)(info->key_b & 255));
}
}
error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
ucvector_cleanup(&tRNS);
return error;
}
static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
LodePNGCompressSettings* zlibsettings)
{
ucvector zlibdata;
unsigned error = 0;
/*compress with the Zlib compressor*/
ucvector_init(&zlibdata);
error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
ucvector_cleanup(&zlibdata);
return error;
}
static unsigned addChunk_IEND(ucvector* out)
{
unsigned error = 0;
error = addChunk(out, "IEND", 0, 0);
return error;
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring)
{
unsigned error = 0;
size_t i;
ucvector text;
ucvector_init(&text);
for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]);
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
ucvector_push_back(&text, 0); /*0 termination char*/
for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]);
error = addChunk(out, "tEXt", text.data, text.size);
ucvector_cleanup(&text);
return error;
}
static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
LodePNGCompressSettings* zlibsettings)
{
unsigned error = 0;
ucvector data, compressed;
size_t i, textsize = strlen(textstring);
ucvector_init(&data);
ucvector_init(&compressed);
for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
ucvector_push_back(&data, 0); /*0 termination char*/
ucvector_push_back(&data, 0); /*compression method: 0*/
error = zlib_compress(&compressed.data, &compressed.size,
(unsigned char*)textstring, textsize, zlibsettings);
if(!error)
{
for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
error = addChunk(out, "zTXt", data.data, data.size);
}
ucvector_cleanup(&compressed);
ucvector_cleanup(&data);
return error;
}
static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag,
const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings)
{
unsigned error = 0;
ucvector data;
size_t i, textsize = strlen(textstring);
ucvector_init(&data);
for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
ucvector_push_back(&data, 0); /*null termination char*/
ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/
ucvector_push_back(&data, 0); /*compression method*/
for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]);
ucvector_push_back(&data, 0); /*null termination char*/
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)
{
ucvector compressed_data;
ucvector_init(&compressed_data);
error = zlib_compress(&compressed_data.data, &compressed_data.size,
(unsigned char*)textstring, textsize, zlibsettings);
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*/
{
for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]);
}
if(!error) error = addChunk(out, "iTXt", data.data, data.size);
ucvector_cleanup(&data);
return error;
}
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)
{
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)
{
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)
{
ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); /*palette index*/
}
error = addChunk(out, "bKGD", bKGD.data, bKGD.size);
ucvector_cleanup(&bKGD);
return error;
}
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*/
data[0] = (unsigned char)(time->year >> 8);
data[1] = (unsigned char)(time->year & 255);
data[2] = (unsigned char)time->month;
data[3] = (unsigned char)time->day;
data[4] = (unsigned char)time->hour;
data[5] = (unsigned char)time->minute;
data[6] = (unsigned char)time->second;
error = addChunk(out, "tIME", data, 7);
lodepng_free(data);
return error;
}
static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info)
{
unsigned error = 0;
ucvector data;
ucvector_init(&data);
lodepng_add32bitInt(&data, info->phys_x);
lodepng_add32bitInt(&data, info->phys_y);
ucvector_push_back(&data, info->phys_unit);
error = addChunk(out, "pHYs", data.data, data.size);
ucvector_cleanup(&data);
return error;
}
#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 i;
switch(filterType)
{
case 0: /*None*/
for(i = 0; i != length; ++i) out[i] = scanline[i];
break;
case 1: /*Sub*/
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
break;
case 2: /*Up*/
if(prevline)
{
for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
}
else
{
for(i = 0; i != length; ++i) out[i] = scanline[i];
}
break;
case 3: /*Average*/
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
{
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)
{
/*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)
{
out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
}
}
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]);
}
break;
default: return; /*unexisting filter type given*/
}
}
/* log2 approximation. A slight bit faster than std::log. */
static float flog2(float f)
{
float result = 0;
while(f > 32) { result += 4; f /= 16; }
while(f > 2) { ++result; f /= 2; }
return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f);
}
static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
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
the scanlines with 1 extra byte per scanline
*/
unsigned bpp = lodepng_get_bpp(info);
/*the width of a scanline in bytes, not including the filter type*/
size_t linebytes = (w * bpp + 7) / 8;
/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
size_t bytewidth = (bpp + 7) / 8;
const unsigned char* prevline = 0;
unsigned x, y;
unsigned error = 0;
LodePNGFilterStrategy strategy = settings->filter_strategy;
/*
There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
* If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
use fixed filtering, with the filter None).
* (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
all five filters and select the filter that produces the smallest sum of absolute values per row.
This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
heuristic is used.
*/
if(settings->filter_palette_zero &&
(info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO;
if(bpp == 0) return 31; /*error: invalid color type*/
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)
{
/*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)
{
attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
if(!attempt[type]) return 83; /*alloc fail*/
}
if(!error)
{
for(y = 0; y != h; ++y)
{
/*try the 5 filter types*/
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)
{
for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type][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.*/
unsigned char s = attempt[type][x];
sum[type] += s < 128 ? s : (255U - s);
}
}
/*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)
{
bestType = type;
smallest = sum[type];
}
}
prevline = &in[y * linebytes];
/*now fill the out values*/
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
}
}
for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
}
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)
{
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)
{
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)
{
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)
{
bestType = type;
smallest = sum[type];
}
}
prevline = &in[y * linebytes];
/*now fill the out values*/
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
}
for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
}
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];
out[outindex] = type; /*filter type byte*/
filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
prevline = &in[inindex];
}
}
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*/
size_t size[5];
unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
size_t smallest = 0;
unsigned type = 0, bestType = 0;
unsigned char* dummy;
LodePNGCompressSettings zlibsettings = settings->zlibsettings;
/*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
to simulate the true case where the tree is the same for the whole image. Sometimes it gives
better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
cases better compression. It does make this a bit less slow, so it's worth doing this.*/
zlibsettings.btype = 1;
/*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
images only, so disable it*/
zlibsettings.custom_zlib = 0;
zlibsettings.custom_deflate = 0;
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)
{
unsigned testsize = linebytes;
/*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
size[type] = 0;
dummy = 0;
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)
{
bestType = type;
smallest = size[type];
}
}
prevline = &in[y * linebytes];
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
}
for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
}
else return 88; /* unknown filter strategy */
return error;
}
static void addPaddingBits(unsigned char* out, const unsigned char* in,
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)
{
size_t x;
for(x = 0; x < ilinebits; ++x)
{
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
/*obp += diff; --> no, fill in some value in the padding bits too, to avoid
"Use of uninitialised value of size ###" warning from valgrind*/
for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
}
}
/*
in: non-interlaced image with size w*h
out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
no padding bits between scanlines, but between reduced images so that each
reduced image starts at a byte.
bpp: bits per pixel
there are no padding bits, not between scanlines, not between reduced images
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)
{
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)
{
unsigned x, y, b;
size_t bytewidth = bpp / 8;
for(y = 0; y < passh[i]; ++y)
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)
{
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)
{
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)
{
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)
{
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
}
}
}
}
/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
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)
{
/*
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
*) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
*/
unsigned bpp = lodepng_get_bpp(&info_png->color);
unsigned error = 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)
{
/*non multiple of 8 bits per scanline, padding bits needed per scanline*/
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)
{
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
{
/*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)*/
{
unsigned passw[7], passh[7];
size_t filter_passstart[8], padded_passstart[8], passstart[8];
unsigned char* adam7;
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
*outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
*out = (unsigned char*)lodepng_malloc(*outsize);
if(!(*out)) error = 83; /*alloc fail*/
adam7 = (unsigned char*)lodepng_malloc(passstart[7]);
if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
if(!error)
{
unsigned i;
Adam7_interlace(adam7, in, w, h, bpp);
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]],
((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]);
error = filter(&(*out)[filter_passstart[i]], padded,
passw[i], passh[i], &info_png->color, settings);
lodepng_free(padded);
}
else
{
error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
passw[i], passh[i], &info_png->color, settings);
}
if(error) break;
}
}
lodepng_free(adam7);
}
return error;
}
/*
palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
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)
{
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)
{
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*/
}
else if(palette[4 * i + 3] != 255) return 2;
/*when key, no opaque RGB may have key's RGB*/
else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2;
}
return key;
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize)
{
unsigned char* inchunk = data;
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);
}
return 0;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
unsigned lodepng_encode(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h,
LodePNGState* state)
{
LodePNGInfo info;
ucvector outv;
unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
size_t datasize = 0;
/*provide some proper output values if error will happen*/
*out = 0;
*outsize = 0;
state->error = 0;
lodepng_info_init(&info);
lodepng_info_copy(&info, &state->info_png);
if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette)
&& (info.color.palettesize == 0 || info.color.palettesize > 256))
{
state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
return state->error;
}
if(state->encoder.auto_convert)
{
state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw);
}
if(state->error) return state->error;
if(state->encoder.zlibsettings.btype > 2)
{
CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/
}
if(state->info_png.interlace_method > 1)
{
CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/
}
state->error = checkColorValidity(info.color.colortype, info.color.bitdepth);
if(state->error) return state->error; /*error: unexisting color type given*/
state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
if(state->error) return state->error; /*error: unexisting color type given*/
if(!lodepng_color_mode_equal(&state->info_raw, &info.color))
{
unsigned char* converted;
size_t size = (w * h * lodepng_get_bpp(&info.color) + 7) / 8;
converted = (unsigned char*)lodepng_malloc(size);
if(!converted && size) state->error = 83; /*alloc fail*/
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);
lodepng_free(converted);
}
else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
ucvector_init(&outv);
while(!state->error) /*while only executed once, to break on error*/
{
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
size_t i;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*write signature and chunks*/
writeSignature(&outv);
/*IHDR*/
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])
{
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
if(state->error) break;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*PLTE*/
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))
{
addChunk_PLTE(&outv, &info.color);
}
/*tRNS*/
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)
{
addChunk_tRNS(&outv, &info.color);
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*bKGD (must come between PLTE and the IDAt chunks*/
if(info.background_defined) addChunk_bKGD(&outv, &info);
/*pHYs (must come before the IDAT chunks)*/
if(info.phys_defined) addChunk_pHYs(&outv, &info);
/*unknown chunks between PLTE and IDAT*/
if(info.unknown_chunks_data[1])
{
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
if(state->error) break;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*IDAT (multiple IDAT chunks must be consecutive)*/
state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
if(state->error) break;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*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)
{
state->error = 66; /*text chunk too large*/
break;
}
if(strlen(info.text_keys[i]) < 1)
{
state->error = 67; /*text chunk too small*/
break;
}
if(state->encoder.text_compression)
{
addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
}
else
{
addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
}
}
/*LodePNG version id in text chunk*/
if(state->encoder.add_id)
{
unsigned alread_added_id_text = 0;
for(i = 0; i != info.text_num; ++i)
{
if(!strcmp(info.text_keys[i], "LodePNG"))
{
alread_added_id_text = 1;
break;
}
}
if(alread_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)
{
state->error = 66; /*text chunk too large*/
break;
}
if(strlen(info.itext_keys[i]) < 1)
{
state->error = 67; /*text chunk too small*/
break;
}
addChunk_iTXt(&outv, state->encoder.text_compression,
info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
&state->encoder.zlibsettings);
}
/*unknown chunks between IDAT and IEND*/
if(info.unknown_chunks_data[2])
{
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
if(state->error) break;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
addChunk_IEND(&outv);
break; /*this isn't really a while loop; no error happened so break out now!*/
}
lodepng_info_cleanup(&info);
lodepng_free(data);
/*instead of cleaning the vector up, give it to the output*/
*out = outv.data;
*outsize = outv.size;
return state->error;
}
unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
{
unsigned error;
LodePNGState state;
lodepng_state_init(&state);
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
state.info_png.color.colortype = colortype;
state.info_png.color.bitdepth = bitdepth;
lodepng_encode(out, outsize, image, w, h, &state);
error = state.error;
lodepng_state_cleanup(&state);
return error;
}
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)
{
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)
{
unsigned char* buffer;
size_t buffersize;
unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
if(!error) error = lodepng_save_file(buffer, buffersize, filename);
lodepng_free(buffer);
return error;
}
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)
{
return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
}
#endif /*LODEPNG_COMPILE_DISK*/
void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings)
{
lodepng_compress_settings_init(&settings->zlibsettings);
settings->filter_palette_zero = 1;
settings->filter_strategy = LFS_MINSUM;
settings->auto_convert = 1;
settings->force_palette = 0;
settings->predefined_filters = 0;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
settings->add_id = 0;
settings->text_compression = 1;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ERROR_TEXT
/*
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)
{
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*/
case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
case 13: return "problem while processing dynamic deflate block";
case 14: return "problem while processing dynamic deflate block";
case 15: return "problem while processing dynamic deflate block";
case 16: return "unexisting code while processing dynamic deflate block";
case 17: return "end of out buffer memory reached while inflating";
case 18: return "invalid distance code while inflating";
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.*/
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";
case 25: return "invalid compression method in zlib header";
case 26: return "FDICT encountered in zlib header while it's not used for PNG";
case 27: return "PNG file is smaller than a PNG header";
/*Checks the magic file header, the first 8 bytes of the PNG file*/
case 28: return "incorrect PNG signature, it's no PNG or corrupted";
case 29: return "first chunk is not the header chunk";
case 30: return "chunk length too large, chunk broken off at end of file";
case 31: return "illegal PNG color type or bpp";
case 32: return "illegal PNG compression method";
case 33: return "illegal PNG filter method";
case 34: return "illegal PNG interlace method";
case 35: return "chunk length of a chunk is too large or the chunk too small";
case 36: return "illegal PNG filter type encountered";
case 37: return "illegal bit depth for this color type given";
case 38: return "the palette is too big"; /*more than 256 colors*/
case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette";
case 40: return "tRNS chunk has wrong size for greyscale image";
case 41: return "tRNS chunk has wrong size for RGB image";
case 42: return "tRNS chunk appeared while it was not allowed for this color type";
case 43: return "bKGD chunk has wrong size for palette image";
case 44: return "bKGD chunk has wrong size for greyscale image";
case 45: return "bKGD chunk has wrong size for RGB image";
case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?";
case 49: return "jumped past memory while generating dynamic huffman tree";
case 50: return "jumped past memory while generating dynamic huffman tree";
case 51: return "jumped past memory while inflating huffman block";
case 52: return "jumped past memory while inflating";
case 53: return "size of zlib data too small";
case 54: return "repeat symbol in tree while there was no value symbol yet";
/*jumped past tree while generating huffman tree, this could be when the
tree will have more leaves than symbols after generating it out of the
given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
case 55: return "jumped past tree while generating huffman tree";
case 56: return "given output image colortype or bitdepth not supported for color conversion";
case 57: return "invalid CRC encountered (checking CRC can be disabled)";
case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
case 59: return "requested color conversion not supported";
case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
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)*/
/*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";
case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)";
case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)";
case 73: return "invalid tIME chunk size";
case 74: return "invalid pHYs chunk size";
/*length could be wrong, or data chopped off*/
case 75: return "no null termination char found while decoding text chunk";
case 76: return "iTXt chunk too short to contain required bytes";
case 77: return "integer overflow in buffer size";
case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
case 79: return "failed to open file for writing";
case 80: return "tried creating a tree of 0 symbols";
case 81: return "lazy matching at pos 0 is impossible";
case 82: return "color conversion to palette requested while a color isn't in palette";
case 83: return "memory allocation failed";
case 84: return "given image too small to contain all pixels to be encoded";
case 86: return "impossible offset in lz77 encoding (internal bug)";
case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
case 89: return "text chunk keyword too short or long: must have size 1-79";
/*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
case 90: return "windowsize must be a power of two";
case 91: return "invalid decompressed idat size";
case 92: return "too many pixels, not supported";
case 93: return "zero width or height is invalid";
case 94: return "header chunk must have a size of 13 bytes";
}
return "unknown error code";
}
#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // C++ Wrapper // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_CPP
namespace lodepng
{
#ifdef LODEPNG_COMPILE_DISK
unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename)
{
long size = lodepng_filesize(filename.c_str());
if(size < 0) return 78;
buffer.resize((size_t)size);
return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str());
}
/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename)
{
return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str());
}
#endif /* LODEPNG_COMPILE_DISK */
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_DECODER
unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
const LodePNGDecompressSettings& settings)
{
unsigned char* buffer = 0;
size_t buffersize = 0;
unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings);
if(buffer)
{
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
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<unsigned char>& out, const unsigned char* in, size_t insize,
const LodePNGCompressSettings& settings)
{
unsigned char* buffer = 0;
size_t buffersize = 0;
unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
if(buffer)
{
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
const LodePNGCompressSettings& settings)
{
return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
}
#endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_ZLIB */
#ifdef LODEPNG_COMPILE_PNG
State::State()
{
lodepng_state_init(this);
}
State::State(const State& other)
{
lodepng_state_init(this);
lodepng_state_copy(this, &other);
}
State::~State()
{
lodepng_state_cleanup(this);
}
State& State::operator=(const State& other)
{
lodepng_state_copy(this, &other);
return *this;
}
#ifdef LODEPNG_COMPILE_DECODER
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,
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)
{
State state;
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth)
{
return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
}
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
State& state,
const unsigned char* in, size_t insize)
{
unsigned char* buffer = NULL;
unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
if(buffer && !error)
{
size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
}
lodepng_free(buffer);
return error;
}
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
State& state,
const std::vector<unsigned char>& in)
{
return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
}
#ifdef LODEPNG_COMPILE_DISK
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,
LodePNGColorType colortype, unsigned bitdepth)
{
std::vector<unsigned char> buffer;
unsigned error = load_file(buffer, filename);
if(error) return error;
return decode(out, w, h, buffer, colortype, bitdepth);
}
#endif /* LODEPNG_COMPILE_DECODER */
#endif /* LODEPNG_COMPILE_DISK */
#ifdef LODEPNG_COMPILE_ENCODER
unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth)
{
unsigned char* buffer;
size_t buffersize;
unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
if(buffer)
{
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned encode(std::vector<unsigned char>& out,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
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<unsigned char>& out,
const unsigned char* in, unsigned w, unsigned h,
State& state)
{
unsigned char* buffer;
size_t buffersize;
unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
if(buffer)
{
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned encode(std::vector<unsigned char>& out,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
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);
}
#ifdef LODEPNG_COMPILE_DISK
unsigned encode(const std::string& filename,
const unsigned char* in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth)
{
std::vector<unsigned char> buffer;
unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
if(!error) error = save_file(buffer, filename);
return error;
}
unsigned encode(const std::string& filename,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
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);
}
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_PNG */
} /* namespace lodepng */
#endif /*LODEPNG_COMPILE_CPP*/
```
|
/content/code_sandbox/library/JQLibrary/src/JQZopfli/zopflipng/lodepng/lodepng.cpp
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 64,546
|
```c++
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "guetzli/jpeg_data_writer.h"
#include <assert.h>
#include <cstdlib>
#include <string.h>
#include "guetzli/entropy_encode.h"
#include "guetzli/fast_log.h"
#include "guetzli/jpeg_bit_writer.h"
namespace guetzli {
namespace {
static const int kJpegPrecision = 8;
// Writes len bytes from buf, using the out callback.
inline bool JPEGWrite(JPEGOutput out, const uint8_t* buf, size_t len) {
static const size_t kBlockSize = 1u << 30;
size_t pos = 0;
while (len - pos > kBlockSize) {
if (!out.Write(buf + pos, kBlockSize)) {
return false;
}
pos += kBlockSize;
}
return out.Write(buf + pos, len - pos);
}
// Writes a string using the out callback.
inline bool JPEGWrite(JPEGOutput out, const std::string& s) {
const uint8_t* data = reinterpret_cast<const uint8_t*>(&s[0]);
return JPEGWrite(out, data, s.size());
}
bool EncodeMetadata(const JPEGData& jpg, bool strip_metadata, JPEGOutput out) {
if (strip_metadata) {
const uint8_t kApp0Data[] = {
0xff, 0xe0, 0x00, 0x10, // APP0
0x4a, 0x46, 0x49, 0x46, 0x00, // 'JFIF'
0x01, 0x01, // v1.01
0x00, 0x00, 0x01, 0x00, 0x01, // aspect ratio = 1:1
0x00, 0x00 // thumbnail width/height
};
return JPEGWrite(out, kApp0Data, sizeof(kApp0Data));
}
bool ok = true;
for (int i = 0; i < (int)jpg.app_data.size(); ++i) {
uint8_t data[1] = { 0xff };
ok = ok && JPEGWrite(out, data, sizeof(data));
ok = ok && JPEGWrite(out, jpg.app_data[i]);
}
for (int i = 0; i < (int)jpg.com_data.size(); ++i) {
uint8_t data[2] = { 0xff, 0xfe };
ok = ok && JPEGWrite(out, data, sizeof(data));
ok = ok && JPEGWrite(out, jpg.com_data[i]);
}
return ok;
}
bool EncodeDQT(const std::vector<JPEGQuantTable>& quant, JPEGOutput out) {
int marker_len = 2;
for (int i = 0; i < (int)quant.size(); ++i) {
marker_len += 1 + (quant[i].precision ? 2 : 1) * kDCTBlockSize;
}
std::vector<uint8_t> data(marker_len + 2);
size_t pos = 0;
data[pos++] = 0xff;
data[pos++] = 0xdb;
data[pos++] = marker_len >> 8;
data[pos++] = marker_len & 0xff;
for (int i = 0; i < (int)quant.size(); ++i) {
const JPEGQuantTable& table = quant[i];
data[pos++] = (table.precision << 4) + table.index;
for (int k = 0; k < kDCTBlockSize; ++k) {
int val = table.values[kJPEGNaturalOrder[k]];
if (table.precision) {
data[pos++] = val >> 8;
}
data[pos++] = val & 0xff;
}
}
return JPEGWrite(out, &data[0], pos);
}
bool EncodeSOF(const JPEGData& jpg, JPEGOutput out) {
const size_t ncomps = jpg.components.size();
const size_t marker_len = 8 + 3 * ncomps;
std::vector<uint8_t> data(marker_len + 2);
size_t pos = 0;
data[pos++] = 0xff;
data[pos++] = 0xc1;
data[pos++] = marker_len >> 8;
data[pos++] = marker_len & 0xff;
data[pos++] = kJpegPrecision;
data[pos++] = jpg.height >> 8;
data[pos++] = jpg.height & 0xff;
data[pos++] = jpg.width >> 8;
data[pos++] = jpg.width & 0xff;
data[pos++] = ncomps;
for (size_t i = 0; i < ncomps; ++i) {
data[pos++] = jpg.components[i].id;
data[pos++] = ((jpg.components[i].h_samp_factor << 4) |
(jpg.components[i].v_samp_factor));
const int quant_idx = jpg.components[i].quant_idx;
if (quant_idx >= (int)jpg.quant.size()) {
return false;
}
data[pos++] = jpg.quant[quant_idx].index;
}
return JPEGWrite(out, &data[0], pos);
}
// Builds a JPEG-style huffman code from the given bit depths.
void BuildHuffmanCode(uint8_t* depth, int* counts, int* values) {
for (int i = 0; i < JpegHistogram::kSize; ++i) {
if (depth[i] > 0) {
++counts[depth[i]];
}
}
int offset[kJpegHuffmanMaxBitLength + 1] = { 0 };
for (int i = 1; i <= kJpegHuffmanMaxBitLength; ++i) {
offset[i] = offset[i - 1] + counts[i - 1];
}
for (int i = 0; i < JpegHistogram::kSize; ++i) {
if (depth[i] > 0) {
values[offset[depth[i]]++] = i;
}
}
}
void BuildHuffmanCodeTable(const int* counts, const int* values,
HuffmanCodeTable* table) {
int huffcode[256];
int huffsize[256];
int p = 0;
for (int l = 1; l <= kJpegHuffmanMaxBitLength; ++l) {
int i = counts[l];
while (i--) huffsize[p++] = l;
}
if (p == 0)
return;
huffsize[p - 1] = 0;
int lastp = p - 1;
int code = 0;
int si = huffsize[0];
p = 0;
while (huffsize[p]) {
while ((huffsize[p]) == si) {
huffcode[p++] = code;
code++;
}
code <<= 1;
si++;
}
for (p = 0; p < lastp; p++) {
int i = values[p];
table->depth[i] = huffsize[p];
table->code[i] = huffcode[p];
}
}
} // namespace
// Updates ac_histogram with the counts of the AC symbols that will be added by
// a sequential jpeg encoder for this block. Every symbol is counted twice so
// that we can add a fake symbol at the end with count 1 to be the last (least
// frequent) symbol with the all 1 code.
void UpdateACHistogramForDCTBlock(const coeff_t* coeffs,
JpegHistogram* ac_histogram) {
int r = 0;
for (int k = 1; k < 64; ++k) {
coeff_t coeff = coeffs[kJPEGNaturalOrder[k]];
if (coeff == 0) {
r++;
continue;
}
while (r > 15) {
ac_histogram->Add(0xf0);
r -= 16;
}
int nbits = Log2FloorNonZero(std::abs(coeff)) + 1;
int symbol = (r << 4) + nbits;
ac_histogram->Add(symbol);
r = 0;
}
if (r > 0) {
ac_histogram->Add(0);
}
}
size_t HistogramHeaderCost(const JpegHistogram& histo) {
size_t header_bits = 17 * 8;
for (int i = 0; i + 1 < JpegHistogram::kSize; ++i) {
if (histo.counts[i] > 0) {
header_bits += 8;
}
}
return header_bits;
}
size_t HistogramEntropyCost(const JpegHistogram& histo,
const uint8_t depths[256]) {
size_t bits = 0;
for (int i = 0; i + 1 < JpegHistogram::kSize; ++i) {
// JpegHistogram::Add() counts every symbol twice, so we have to divide by
// two here.
bits += (histo.counts[i] / 2) * (depths[i] + (i & 0xf));
}
// Estimate escape byte rate to be 0.75/256.
bits += (bits * 3 + 512) >> 10;
return bits;
}
void BuildDCHistograms(const JPEGData& jpg, JpegHistogram* histo) {
for (int i = 0; i < (int)jpg.components.size(); ++i) {
const JPEGComponent& c = jpg.components[i];
JpegHistogram* dc_histogram = &histo[i];
coeff_t last_dc_coeff = 0;
for (int mcu_y = 0; mcu_y < jpg.MCU_rows; ++mcu_y) {
for (int mcu_x = 0; mcu_x < jpg.MCU_cols; ++mcu_x) {
for (int iy = 0; iy < c.v_samp_factor; ++iy) {
for (int ix = 0; ix < c.h_samp_factor; ++ix) {
int block_y = mcu_y * c.v_samp_factor + iy;
int block_x = mcu_x * c.h_samp_factor + ix;
int block_idx = block_y * c.width_in_blocks + block_x;
coeff_t dc_coeff = c.coeffs[block_idx << 6];
int diff = std::abs(dc_coeff - last_dc_coeff);
int nbits = Log2Floor(diff) + 1;
dc_histogram->Add(nbits);
last_dc_coeff = dc_coeff;
}
}
}
}
}
}
void BuildACHistograms(const JPEGData& jpg, JpegHistogram* histo) {
for (int i = 0; i < (int)jpg.components.size(); ++i) {
const JPEGComponent& c = jpg.components[i];
JpegHistogram* ac_histogram = &histo[i];
for (int j = 0; j < (int)c.coeffs.size(); j += kDCTBlockSize) {
UpdateACHistogramForDCTBlock(&c.coeffs[j], ac_histogram);
}
}
}
// Size of everything except the Huffman codes and the entropy coded data.
size_t JpegHeaderSize(const JPEGData& jpg, bool strip_metadata) {
size_t num_bytes = 0;
num_bytes += 2; // SOI
if (strip_metadata) {
num_bytes += 18; // APP0
} else {
for (int i = 0; i < (int)jpg.app_data.size(); ++i) {
num_bytes += 1 + jpg.app_data[i].size();
}
for (int i = 0; i < (int)jpg.com_data.size(); ++i) {
num_bytes += 2 + jpg.com_data[i].size();
}
}
// DQT
num_bytes += 4;
for (int i = 0; i < (int)jpg.quant.size(); ++i) {
num_bytes += 1 + (jpg.quant[i].precision ? 2 : 1) * kDCTBlockSize;
}
num_bytes += 10 + 3 * jpg.components.size(); // SOF
num_bytes += 4; // DHT (w/o actual Huffman code data)
num_bytes += 8 + 2 * jpg.components.size(); // SOS
num_bytes += 2; // EOI
num_bytes += jpg.tail_data.size();
return num_bytes;
}
size_t ClusterHistograms(JpegHistogram* histo, size_t* num,
int* histo_indexes, uint8_t* depth) {
memset(depth, 0, *num * JpegHistogram::kSize);
size_t costs[kMaxComponents];
for (size_t i = 0; i < *num; ++i) {
histo_indexes[i] = i;
std::vector<HuffmanTree> tree(2 * JpegHistogram::kSize + 1);
CreateHuffmanTree(histo[i].counts, JpegHistogram::kSize,
kJpegHuffmanMaxBitLength, &tree[0],
&depth[i * JpegHistogram::kSize]);
costs[i] = (HistogramHeaderCost(histo[i]) +
HistogramEntropyCost(histo[i],
&depth[i * JpegHistogram::kSize]));
}
const size_t orig_num = *num;
while (*num > 1) {
size_t last = *num - 1;
size_t second_last = *num - 2;
JpegHistogram combined(histo[last]);
combined.AddHistogram(histo[second_last]);
std::vector<HuffmanTree> tree(2 * JpegHistogram::kSize + 1);
uint8_t depth_combined[JpegHistogram::kSize] = { 0 };
CreateHuffmanTree(combined.counts, JpegHistogram::kSize,
kJpegHuffmanMaxBitLength, &tree[0], depth_combined);
size_t cost_combined = (HistogramHeaderCost(combined) +
HistogramEntropyCost(combined, depth_combined));
if (cost_combined < costs[last] + costs[second_last]) {
histo[second_last] = combined;
histo[last] = JpegHistogram();
costs[second_last] = cost_combined;
memcpy(&depth[second_last * JpegHistogram::kSize], depth_combined,
sizeof(depth_combined));
for (size_t i = 0; i < orig_num; ++i) {
if (histo_indexes[i] == (int)last) {
histo_indexes[i] = second_last;
}
}
--(*num);
} else {
break;
}
}
size_t total_cost = 0;
for (int i = 0; i < (int)*num; ++i) {
total_cost += costs[i];
}
return (total_cost + 7) / 8;
}
size_t EstimateJpegDataSize(const int num_components,
const std::vector<JpegHistogram>& histograms) {
assert((int)histograms.size() == 2 * num_components);
std::vector<JpegHistogram> clustered = histograms;
size_t num_dc = num_components;
size_t num_ac = num_components;
int indexes[kMaxComponents];
uint8_t depth[kMaxComponents * JpegHistogram::kSize];
return (ClusterHistograms(&clustered[0], &num_dc, indexes, depth) +
ClusterHistograms(&clustered[num_components], &num_ac, indexes,
depth));
}
namespace {
// Writes DHT and SOS marker segments to out and fills in DC/AC Huffman tables
// for each component of the image.
bool BuildAndEncodeHuffmanCodes(const JPEGData& jpg, JPEGOutput out,
std::vector<HuffmanCodeTable>* dc_huff_tables,
std::vector<HuffmanCodeTable>* ac_huff_tables) {
const int ncomps = jpg.components.size();
dc_huff_tables->resize(ncomps);
ac_huff_tables->resize(ncomps);
// Build separate DC histograms for each component.
std::vector<JpegHistogram> histograms(ncomps);
BuildDCHistograms(jpg, &histograms[0]);
// Cluster DC histograms.
size_t num_dc_histo = ncomps;
int dc_histo_indexes[kMaxComponents];
std::vector<uint8_t> depths(ncomps * JpegHistogram::kSize);
ClusterHistograms(&histograms[0], &num_dc_histo, dc_histo_indexes,
&depths[0]);
// Build separate AC histograms for each component.
histograms.resize(num_dc_histo + ncomps);
depths.resize((num_dc_histo + ncomps) * JpegHistogram::kSize);
BuildACHistograms(jpg, &histograms[num_dc_histo]);
// Cluster AC histograms.
size_t num_ac_histo = ncomps;
int ac_histo_indexes[kMaxComponents];
ClusterHistograms(&histograms[num_dc_histo], &num_ac_histo, ac_histo_indexes,
&depths[num_dc_histo * JpegHistogram::kSize]);
// Compute DHT and SOS marker data sizes and start emitting DHT marker.
int num_histo = num_dc_histo + num_ac_histo;
histograms.resize(num_histo);
int total_count = 0;
for (int i = 0; i < (int)histograms.size(); ++i) {
total_count += histograms[i].NumSymbols();
}
const size_t dht_marker_len =
2 + num_histo * (kJpegHuffmanMaxBitLength + 1) + total_count;
const size_t sos_marker_len = 6 + 2 * ncomps;
std::vector<uint8_t> data(dht_marker_len + sos_marker_len + 4);
size_t pos = 0;
data[pos++] = 0xff;
data[pos++] = 0xc4;
data[pos++] = dht_marker_len >> 8;
data[pos++] = dht_marker_len & 0xff;
// Compute Huffman codes for each histograms.
for (size_t i = 0; i < (size_t)num_histo; ++i) {
const bool is_dc = i < num_dc_histo;
const int idx = is_dc ? i : i - num_dc_histo;
int counts[kJpegHuffmanMaxBitLength + 1] = { 0 };
int values[JpegHistogram::kSize] = { 0 };
BuildHuffmanCode(&depths[i * JpegHistogram::kSize], counts, values);
HuffmanCodeTable table;
for (int j = 0; j < 256; ++j) table.depth[j] = 255;
BuildHuffmanCodeTable(counts, values, &table);
for (int c = 0; c < ncomps; ++c) {
if (is_dc) {
if (dc_histo_indexes[c] == idx) (*dc_huff_tables)[c] = table;
} else {
if (ac_histo_indexes[c] == idx) (*ac_huff_tables)[c] = table;
}
}
int max_length = kJpegHuffmanMaxBitLength;
while (max_length > 0 && counts[max_length] == 0) --max_length;
--counts[max_length];
int total_count = 0;
for (int j = 0; j <= max_length; ++j) total_count += counts[j];
data[pos++] = is_dc ? i : i - num_dc_histo + 0x10;
for (size_t j = 1; j <= kJpegHuffmanMaxBitLength; ++j) {
data[pos++] = counts[j];
}
for (size_t j = 0; j < (size_t)total_count; ++j) {
data[pos++] = values[j];
}
}
// Emit SOS marker data.
data[pos++] = 0xff;
data[pos++] = 0xda;
data[pos++] = sos_marker_len >> 8;
data[pos++] = sos_marker_len & 0xff;
data[pos++] = ncomps;
for (int i = 0; i < ncomps; ++i) {
data[pos++] = jpg.components[i].id;
data[pos++] = (dc_histo_indexes[i] << 4) | ac_histo_indexes[i];
}
data[pos++] = 0;
data[pos++] = 63;
data[pos++] = 0;
assert(pos == data.size());
return JPEGWrite(out, &data[0], data.size());
}
void EncodeDCTBlockSequential(const coeff_t* coeffs,
const HuffmanCodeTable& dc_huff,
const HuffmanCodeTable& ac_huff,
coeff_t* last_dc_coeff,
BitWriter* bw) {
coeff_t temp2;
coeff_t temp;
temp2 = coeffs[0];
temp = temp2 - *last_dc_coeff;
*last_dc_coeff = temp2;
temp2 = temp;
if (temp < 0) {
temp = -temp;
temp2--;
}
int nbits = Log2Floor(temp) + 1;
bw->WriteBits(dc_huff.depth[nbits], dc_huff.code[nbits]);
if (nbits > 0) {
bw->WriteBits(nbits, temp2 & ((1 << nbits) - 1));
}
int r = 0;
for (int k = 1; k < 64; ++k) {
if ((temp = coeffs[kJPEGNaturalOrder[k]]) == 0) {
r++;
continue;
}
if (temp < 0) {
temp = -temp;
temp2 = ~temp;
} else {
temp2 = temp;
}
while (r > 15) {
bw->WriteBits(ac_huff.depth[0xf0], ac_huff.code[0xf0]);
r -= 16;
}
int nbits = Log2FloorNonZero(temp) + 1;
int symbol = (r << 4) + nbits;
bw->WriteBits(ac_huff.depth[symbol], ac_huff.code[symbol]);
bw->WriteBits(nbits, temp2 & ((1 << nbits) - 1));
r = 0;
}
if (r > 0) {
bw->WriteBits(ac_huff.depth[0], ac_huff.code[0]);
}
}
bool EncodeScan(const JPEGData& jpg,
const std::vector<HuffmanCodeTable>& dc_huff_table,
const std::vector<HuffmanCodeTable>& ac_huff_table,
JPEGOutput out) {
coeff_t last_dc_coeff[kMaxComponents] = { 0 };
BitWriter bw(1 << 17);
for (int mcu_y = 0; mcu_y < jpg.MCU_rows; ++mcu_y) {
for (int mcu_x = 0; mcu_x < jpg.MCU_cols; ++mcu_x) {
// Encode one MCU
for (int i = 0; i < (int)jpg.components.size(); ++i) {
const JPEGComponent& c = jpg.components[i];
int nblocks_y = c.v_samp_factor;
int nblocks_x = c.h_samp_factor;
for (int iy = 0; iy < nblocks_y; ++iy) {
for (int ix = 0; ix < nblocks_x; ++ix) {
int block_y = mcu_y * nblocks_y + iy;
int block_x = mcu_x * nblocks_x + ix;
int block_idx = block_y * c.width_in_blocks + block_x;
const coeff_t* coeffs = &c.coeffs[block_idx << 6];
EncodeDCTBlockSequential(coeffs, dc_huff_table[i], ac_huff_table[i],
&last_dc_coeff[i], &bw);
}
}
}
if (bw.pos > (1 << 16)) {
if (!JPEGWrite(out, bw.data.get(), bw.pos)) {
return false;
}
bw.pos = 0;
}
}
}
bw.JumpToByteBoundary();
return !bw.overflow && JPEGWrite(out, bw.data.get(), bw.pos);
}
} // namespace
bool WriteJpeg(const JPEGData& jpg, bool strip_metadata, JPEGOutput out) {
static const uint8_t kSOIMarker[2] = { 0xff, 0xd8 };
static const uint8_t kEOIMarker[2] = { 0xff, 0xd9 };
std::vector<HuffmanCodeTable> dc_codes;
std::vector<HuffmanCodeTable> ac_codes;
return (JPEGWrite(out, kSOIMarker, sizeof(kSOIMarker)) &&
EncodeMetadata(jpg, strip_metadata, out) &&
EncodeDQT(jpg.quant, out) &&
EncodeSOF(jpg, out) &&
BuildAndEncodeHuffmanCodes(jpg, out, &dc_codes, &ac_codes) &&
EncodeScan(jpg, dc_codes, ac_codes, out) &&
JPEGWrite(out, kEOIMarker, sizeof(kEOIMarker)) &&
(strip_metadata || JPEGWrite(out, jpg.tail_data)));
}
int NullOut(void* , const uint8_t* , size_t count) {
return count;
}
void BuildSequentialHuffmanCodes(
const JPEGData& jpg,
std::vector<HuffmanCodeTable>* dc_huffman_code_tables,
std::vector<HuffmanCodeTable>* ac_huffman_code_tables) {
JPEGOutput out(NullOut, nullptr);
BuildAndEncodeHuffmanCodes(jpg, out, dc_huffman_code_tables,
ac_huffman_code_tables);
}
} // namespace guetzli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/guetzli/jpeg_data_writer.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 5,701
|
```objective-c
/*
This file is part of JQLibrary
Contact email: 188080501@qq.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JQLIBRARY_INCLUDE_JQFOUNDATION_H_
#define JQLIBRARY_INCLUDE_JQFOUNDATION_H_
#if ((__cplusplus < 201103) && !(defined _MSC_VER)) || ((defined _MSC_VER) && (_MSC_VER < 1800))
# error("Please add c++11 config on pro file")
#endif
#ifndef QT_CORE_LIB
# error("Please add core in pro file")
#endif
#ifndef QT_GUI_LIB
# error("Please add gui in pro file")
#endif
// C++ lib import
#include <functional>
// Qt lib import
#include <QCoreApplication>
#include <QSharedPointer>
#include <QCryptographicHash>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMessageLogContext>
#include <QMap>
#include <QVector>
#include <QSize>
#include <QMutex>
#include <QTimer>
#include <QDateTime>
#include <QDebug>
#ifdef QT_CONCURRENT_LIB
# include <QThread>
# include <QThreadPool>
#endif
// JQLibrary lib import
#include <JQDeclare>
enum JQDebugEnum
{
JQDebugUnknown,
JQDebugForceConsoleMode,
JQDebugReset,
JQDebugBlue,
JQDebugGreen,
JQDebugRed,
JQDebugYellow,
JQDebugPurple,
JQDebugCyan,
JQDebugBlack,
JQDebugWhite,
};
QDebug operator<<(QDebug dbg, const QPair< QDateTime, QDateTime > &data);
QDebug operator<<(QDebug dbg, const JQDebugEnum &debugConfig);
std::ostream &operator<<(std::ostream &dbg, const JQDebugEnum &debugConfig);
namespace JQFoundation
{
QString hashString(const QByteArray &key, const QCryptographicHash::Algorithm &algorithm = QCryptographicHash::Sha1);
QString variantToString(const QVariant &value);
QString createUuidString();
QJsonObject jsonFilter(const QJsonObject &source, const QStringList &leftKey, const QJsonObject &mix = QJsonObject());
QJsonObject jsonFilter(const QJsonObject &source, const char *leftKey, const QJsonObject &mix = QJsonObject());
template< class Key, class T >
QMap< Key, T > mapFilter(const QMap< Key, T > &source, const QStringList &leftKey, const QMap< Key, T > &mix = QMap< Key, T >());
template< class Key, class T >
QMap< Key, T > mapFilter(const QMap< Key, T > &source, const char *leftKey, const QMap< Key, T > &mix = QMap< Key, T >());
template< class Key, class T >
QMap< Key, T > mapMix(const QMap< Key, T > &source, const QMap< Key, T > &mix);
QVariantList listVariantMapToVariantList(const QList< QVariantMap > &source);
QList< QVariantMap > variantListToListVariantMap(const QVariantList &source);
QVariantMap mapKeyTranslate(const QVariantMap &source, const QMap< QString, QString > &keyMap);
QVariantList listKeyTranslate(const QVariantList &source, const QMap< QString, QString > &keyMap);
QList< QVariantMap > listKeyTranslate(const QList< QVariantMap > &source, const QMap< QString, QString > &keyMap);
QSharedPointer< QTimer > JQLIBRARY_EXPORT setTimerCallback(
const int &interval,
const std::function< void(bool &continueFlag) > &callback,
const bool &callbackOnStart = false
);
#if ( defined QT_CONCURRENT_LIB ) && ( QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 ) )
void JQLIBRARY_EXPORT setTimerCallback(
const QDateTime &dateTime,
const std::function< void() > &callback,
const QSharedPointer< QThreadPool > &threadPool = nullptr
);
void JQLIBRARY_EXPORT setTimerCallback(
const std::function< QDateTime() > &nextTime,
const std::function< void() > &callback,
const QSharedPointer< QThreadPool > &threadPool = nullptr
);
#endif
void JQLIBRARY_EXPORT setDebugOutput(const QString &targetFilePath, const bool &argDateFlag = false);
void openDebugConsole();
bool JQLIBRARY_EXPORT singleApplication(const QString &flag);
bool JQLIBRARY_EXPORT singleApplicationExist(const QString &flag);
QString snakeCaseToCamelCase(const QString &source, const bool &firstCharUpper = false);
int rectOverflow(const QSize &frameSize, const QRect &rect, const int &redundancy = 0);
QRect scaleRect(const QRect &rect, const qreal &scale);
QRect scaleRect(const QRect &rect, const qreal &horizontalScale, const qreal &verticalScale);
QPoint scalePoint(const QPoint &point, const qreal &horizontalScale, const qreal &verticalScale);
QPointF scalePoint(const QPointF &point, const qreal &horizontalScale, const qreal &verticalScale);
QPoint pointFToPoint(const QPointF &point, const QSize &size);
QPointF pointToPointF(const QPoint &point, const QSize &size);
QLine pointFToLine(const QPointF &point1, const QPointF &point2, const QSize &size);
QRect rectFToRect(const QRectF &rect, const QSize &size);
QRectF rectToRectF(const QRect &rect, const QSize &size);
QLine lineFToLine(const QLineF &line, const QSize &size);
QRect cropRect(const QRect &rect, const QRect &bigRect);
#ifdef QT_CONCURRENT_LIB
QByteArray pixmapToByteArray(const QPixmap &pixmap, const QString &format, int quality = -1);
QByteArray imageToByteArray(const QImage &image, const QString &format, int quality = -1);
QImage imageCopy(const QImage &image, const QRect &rect);
QImage removeImageColor(const QImage &image, const QColor &color);
void waitFor(const std::function< bool() > &predicate, const int &timeout);
#endif
QList< QPair< QDateTime, QDateTime > > extractTimeRange(const QDateTime &startTime, const QDateTime &endTime, const qint64 &interval);
#if ( ( defined Q_OS_MAC ) && !( defined Q_OS_IOS ) ) || ( defined Q_OS_WIN ) || ( defined Q_OS_LINUX )
QPair< int, QByteArray > JQLIBRARY_EXPORT startProcessAndReadOutput(const QString &program, const QStringList &arguments, const int &maximumTime = 5 * 1000);
#endif
template< class Key, class T >
QMap< Key, T > mapFilter(const QMap< Key, T > &source, const QStringList &leftKey, const QMap< Key, T > &mix)
{
QMap< Key, T > result;
for ( const auto &key: leftKey )
{
auto buf = source.find( key );
if ( buf != source.end() )
{
result[ buf.key() ] = buf.value();
}
}
if ( !mix.isEmpty() )
{
for ( auto it = mix.begin(); it != mix.end(); ++it )
{
result.insert( it.key(), it.value() );
}
}
return result;
}
template< class Key, class T >
QMap< Key, T > mapFilter(const QMap< Key, T > &source, const char *leftKey, const QMap< Key, T > &mix)
{
return JQFoundation::mapFilter( source, QStringList( { leftKey } ), mix );
}
template< class Key, class T >
QMap< Key, T > mapMix(const QMap< Key, T > &source, const QMap< Key, T > &mix)
{
QMap< Key, T > result = source;
for ( auto it = mix.begin(); it != mix.end(); ++it )
{
result[ it.key() ] = it.value();
}
return result;
}
}
inline bool operator <(const QSize &a, const QSize &b)
{
if ( a.width() != b.width() ) { return a.width() < b.width(); }
return a.height() < b.height();
}
class JQLIBRARY_EXPORT JQTickCounter
{
public:
explicit JQTickCounter(const qint64 &timeRange = 5 * 1000); // ticktick
~JQTickCounter() = default;
public:
void tick(const int &count = 1);
qreal tickPerSecond();
QString tickPerSecondDisplayString();
private:
qint64 timeRange_;
QList< qint64 > tickRecord_;
QSharedPointer< QMutex > mutex_;
};
#ifdef QT_CONCURRENT_LIB
class JQLIBRARY_EXPORT JQFpsControl
{
public:
JQFpsControl(const qreal &fps = 15);
~JQFpsControl() = default;
void setFps(const qreal &fps);
void waitNextFrame();
bool readyNextFrame();
private:
qreal fps_;
qint64 lastTriggeredTime_ = 0;
};
class JQLIBRARY_EXPORT JQMemoryPool
{
private:
struct JQMemoryPoolNodeHead
{
qint32 flag = 0x3519;
QThread *mallocThread = nullptr;
qint64 mallocTime = 0;
size_t requestSize = 0;
void *memory = nullptr;
};
private:
JQMemoryPool() = default;
public:
~JQMemoryPool() = default;
static void initReleaseThreshold(const qreal &percentage = 0.2);
static qint64 realTotalMallocSize();
static qint64 totalMallocSize();
static qint64 totalMallocCount();
static void *requestMemory(const size_t &requestSize);
static void recoverMemory(void *memory);
private:
static JQMemoryPoolNodeHead makeNode(const size_t &requestSize);
private:
static QMutex mutex_;
static QMap< size_t, QVector< JQMemoryPoolNodeHead > > nodeMap_;
static QAtomicInteger< qint64 > realTotalMallocSize_;
static QAtomicInteger< qint64 > totalMallocSize_;
static QAtomicInteger< qint64 > totalMallocCount_;
static qint64 releaseThreshold_;
};
#endif
#endif//JQLIBRARY_INCLUDE_JQFOUNDATION_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQFoundation.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 2,407
|
```objective-c
/*
This file is part of JQLibrary
Contact email: 188080501@qq.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JQLIBRARY_INCLUDE_JQFILE_H_
#define JQLIBRARY_INCLUDE_JQFILE_H_
// C++ lib import
#include <functional>
// Qt lib import
#include <QByteArray>
#include <QPair>
#include <QDir>
#include <QCryptographicHash>
// JQLibrary lib import
#include <JQDeclare>
class QFileInfo;
class QDir;
class JQLIBRARY_EXPORT JQFile
{
public:
static void foreachFileFromDirectory(const QDir &directory, const std::function<void(const QFileInfo &)> &each, const bool &recursion = false);
static bool foreachFileFromDirectory(const QDir &directory, const std::function<void(const QFileInfo &, bool &)> &each, const bool &recursion = false);
static void foreachDirectoryFromDirectory(const QDir &directory, const std::function<void(const QDir &)> &each, const bool &recursion = false);
static QString tempFilePath(const QString &fileName);
static bool writeFile(const QFileInfo &targetFilePath, const QByteArray &data, const bool &cover = true);
static bool writeFileToDesktop(const QString &fileName, const QByteArray &data, const bool &cover = true);
static bool writeFileToTemp(const QString &fileName, const QByteArray &data, const bool &cover = true);
static bool appendFile(const QFileInfo &targetFilePath, const QByteArray &data);
static QPair< bool, QByteArray > readFile(const QFileInfo &filePath);
static QPair< bool, QByteArray > readFileFromDesktop(const QString &fileName);
static QPair< bool, QByteArray > readFileFromTemp(const QString &fileName);
static bool copyFile(const QFileInfo &sourceFileInfo, const QFileInfo &targetFileInfo, const bool &cover = true);
static bool copyFileToTemp(const QFileInfo &sourceFileInfo, const QString &fileName);
static QPair< bool, QString > copyFileToTemp(const QFileInfo &sourceFileInfo, const QCryptographicHash::Algorithm &fileNameHashAlgorithm = QCryptographicHash::Sha1, const QString &salt = "");
static bool copyDirectory(const QDir &sourceDirectory, const QDir &targetDirectory, const bool &cover = true);
static bool copy(const QFileInfo &source, const QFileInfo &target, const bool &cover = true);
static QString md5(const QFileInfo &fileInfo);
#if ( defined Q_OS_MAC ) || ( defined __MINGW32__ ) || ( defined Q_OS_LINUX )
static bool setFileLastReadAndLastModifiedTime(const char *fileName, const quint32 &lastRead, const quint32 &lastModified);
#endif
};
#endif//JQLIBRARY_INCLUDE_JQFILE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQFile.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 799
|
```c++
/*
This file is part of JQLibrary
Contact email: 188080501@qq.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JQLIBRARY_INCLUDE_JQDECLARE_HPP_
#define JQLIBRARY_INCLUDE_JQDECLARE_HPP_
// Macro define
#define JQPROPERTYDECLARE( Type, name, setName, ... ) \
private: \
Type name##_ __VA_ARGS__; \
\
public: \
inline const Type &name() const { return name##_; } \
inline void setName( const Type &name ) { name##_ = name; } \
\
private:
#define JQPROPERTYDECLAREWITHSLOT( Type, name, setName, ... ) \
private: \
Type name##_ __VA_ARGS__; \
public Q_SLOTS: \
Type name() const { return name##_; } \
void setName( const Type &name ) { name##_ = name; } \
\
private:
#define JQPTRPROPERTYDECLARE( Type, name, setName, ... ) \
private: \
Type *name##_ __VA_ARGS__; \
\
public: \
inline const Type *name() const { return name##_; } \
inline void setName( const Type &name ) \
{ \
if ( name##_ ) \
{ \
delete name##_; \
} \
name##_ = new Type( name ); \
} \
\
private:
#define JQ_READ_AND_SET_PROPERTY( Type, name, setName ) \
public: \
inline const Type &name() const { return name##_; } \
inline void setName( const Type &name ) { name##_ = name; } \
\
private:
#define JQ_STATIC_READ_AND_SET_PROPERTY( Type, name, setName ) \
public: \
static inline const Type &name() { return name##_; } \
static inline void setName( const Type &name ) { name##_ = name; } \
\
private:
#define JQ_STATIC_SET_PROPERTY( Type, name, setName ) \
public: \
static inline void setName( const Type &name ) { name##_ = name; } \
\
private:
#define RUNONOUTRANGEHELPER2( x, y ) x##y
#define RUNONOUTRANGEHELPER( x, y ) RUNONOUTRANGEHELPER2( x, y )
#define RUNONOUTRANGE( ... ) \
auto RUNONOUTRANGEHELPER( runOnOutRangeCallback, __LINE__ ) = __VA_ARGS__; \
QSharedPointer< int > RUNONOUTRANGEHELPER( runOnOutRange, __LINE__ )( \
new int, \
[ RUNONOUTRANGEHELPER( runOnOutRangeCallback, __LINE__ ) ]( int *data ) { \
RUNONOUTRANGEHELPER( runOnOutRangeCallback, __LINE__ ) \
(); \
delete data; \
} ); \
if ( RUNONOUTRANGEHELPER( runOnOutRange, __LINE__ ).data() == nullptr ) \
{ \
exit( -1 ); \
}
#define RUNONOUTRANGETIMER( message ) \
const auto &&runOnOutRangeTimerTime = QDateTime::currentMSecsSinceEpoch(); \
RUNONOUTRANGE( [ = ]() { \
qDebug() << message << ( QDateTime::currentMSecsSinceEpoch() - runOnOutRangeTimerTime ); \
} )
#define JQCONST( property ) static_cast< const decltype( property ) >( property )
#define JQTICKCOUNTERMESSAGE( message ) \
{ \
static JQTickCounter tickCounter; \
tickCounter.tick(); \
qDebug() << message << tickCounter.tickPerSecond(); \
}
#define JQBUILDDATETIMESTRING \
( QDateTime( \
QLocale( QLocale::English ).toDate( QString( __DATE__ ).replace( " ", " 0" ), "MMM dd yyyy" ), \
QTime::fromString( __TIME__, "hh:mm:ss" ) ) \
.toString( "yyyy-MM-dd hh:mm:ss" ) \
.toLatin1() \
.data() )
#define JQONLYONCE \
if ( []() { \
static auto flag = true; \
if ( flag ) \
{ \
flag = false; \
return true; \
} \
return false; \
}() )
#define JQSKIPFIRST \
if ( []() { \
static auto flag = true; \
if ( flag ) \
{ \
flag = false; \
return false; \
} \
return true; \
}() )
#define JQINTERVAL( timeInterval ) \
if ( []() { \
static qint64 lastTime = 0; \
const auto && currentTime = QDateTime::currentMSecsSinceEpoch(); \
if ( qAbs( currentTime - lastTime ) > timeInterval ) \
{ \
lastTime = currentTime; \
return true; \
} \
return false; \
}() )
// Export
#ifdef JQLIBRARY_EXPORT_ENABLE
# ifdef JQLIBRARY_EXPORT_MODE
# define JQLIBRARY_EXPORT Q_DECL_EXPORT
# else
# define JQLIBRARY_EXPORT Q_DECL_IMPORT
# endif
#else
# define JQLIBRARY_EXPORT
#endif
#endif // JQLIBRARY_INCLUDE_JQDECLARE_HPP_
```
|
/content/code_sandbox/library/JQLibrary/include/jqdeclare.hpp
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,454
|
```objective-c
/*
This file is part of JQLibrary
Contact email: 188080501@qq.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JQLIBRARY_JQBARCODE_H_
#define JQLIBRARY_JQBARCODE_H_
// Qt lib import
#include <QImage>
class JQBarcode
{
public:
static qint64 makeNumber(const qint64 &rawNumebr);
static QImage makeBarcode(const qint64 &number);
private:
static void paintByteA(QImage &image, const int &number, const int &pos);
static void paintByteB(QImage &image, const int &number, const int &pos);
static void paintByteC(QImage &image, const int &number, const int &pos);
static void paintLines(QImage &image, const QString &key, const int &pos, const int &len = 100);
static void paintLine(QImage &image, const bool &black, const int &pos, const int &len = 100);
};
#endif//JQLIBRARY_JQBARCODE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQBarcode.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 443
|
```objective-c
/*
This file is part of JQLibrary
Contact email: 188080501@qq.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JQQRCODEWRITER_H_
#define JQQRCODEWRITER_H_
// Qt lib import
#include <QString>
#include <QImage>
namespace JQQRCodeWriter
{
QImage makeQRcode(
const QString &data,
const QSize &size = QSize( 512, 512 ),
const QColor &colorForPoint = QColor( "#000000" )
);
}
#endif//JQQRCODEWRITER_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQQRCodeWriter/JQQRCodeWriter.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 337
|
```objective-c
/*
This file is part of JQLibrary
Contact email: 188080501@qq.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
QZxing
path_to_url
*/
#ifndef JQQRCODEREADER_H_
#define JQQRCODEREADER_H_
// Qt lib import
#include <QObject>
#include <QSharedPointer>
class QSemaphore;
namespace zxing { class MultiFormatReader; }
class JQQRCodeReader: public QObject
{
Q_OBJECT
Q_DISABLE_COPY( JQQRCodeReader )
public:
enum DecodeType
{
DecodeAztecType = 1 << 1,
DecodeCodaBarType = 1 << 2,
DecodeCode39Type = 1 << 3,
DecodeCode93Type = 1 << 4,
DecodeCode128Type = 1 << 5,
DecodeDataMatrixType = 1 << 6,
DecodeEan8Type = 1 << 7,
DecodeEan13Type = 1 << 8,
DecodeItfType = 1 << 9,
DecodeMaxiCodeType = 1 << 10,
DecodePdf417Type = 1 << 11,
DecodeQrCodeType = 1 << 12,
DecodeRss14Type = 1 << 13,
DecodeRssExpandedType = 1 << 14,
DecodeUpcAType = 1 << 15,
DecodeUpcEType = 1 << 16,
DecodeUpcEanExtensionType = 1 << 17
};
public:
JQQRCodeReader();
~JQQRCodeReader();
public slots:
QString decodeImage(const QImage &image, const int &decodeType = static_cast< int >( DecodeQrCodeType ) );
signals:
void decodingStarted();
void decodingFinished(bool succeeded);
void tagFound(QString tag);
private:
QSharedPointer< zxing::MultiFormatReader > decoder_;
QSharedPointer< QSemaphore > semaphore_;
};
#endif//JQQRCODEREADER_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQQRCodeReader/JQQRCodeReader.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 657
|
```objective-c
/*
This file is part of JQLibrary
Contact email: 188080501@qq.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JQQRCODEREADERFORQML_H_
#define JQQRCODEREADERFORQML_H_
// Qt lib import
#include <QObject>
#include <QSharedPointer>
#include <QPointer>
#include <QQmlContext>
#include <QQuickPaintedItem>
#include <QMutex>
#include <QPainter>
// JQLibrary import
#include "JQQRCodeReader.h"
#ifdef QT_QML_LIB
# define JQQRCODEREADERFORQML_REGISTERTYPE( engine ) \
engine.rootContext()->setContextProperty( "JQQRCodeReaderForQmlManage", new JQQRCodeReaderForQmlManage ); \
engine.addImportPath( ":/JQQRCodeReader/" ); \
qmlRegisterType< ImagePreviewView >( "ImagePreviewView", 1, 0, "ImagePreviewView" );
#endif
class QThreadPool;
class QSemaphore;
class QQuickItem;
class QQuickItemGrabResult;
class QImage;
class ImagePreviewView: public QQuickPaintedItem
{
Q_OBJECT
public:
ImagePreviewView() = default;
~ImagePreviewView() = default;
static void pushImage(const QImage &image);
private:
void paint(QPainter *p);
private:
static QPointer< ImagePreviewView > object_;
static QMutex mutex_;
static QImage image_;
};
class JQQRCodeReaderForQmlManage: public JQQRCodeReader
{
Q_OBJECT
Q_DISABLE_COPY( JQQRCodeReaderForQmlManage )
Q_PROPERTY(int decodeQrCodeType READ decodeQrCodeType WRITE setDecodeQrCodeType)
public:
JQQRCodeReaderForQmlManage();
~JQQRCodeReaderForQmlManage();
public slots:
void analysisItem(
QQuickItem *item,
const int &apertureX,
const int &apertureY,
const int &apertureWidth,
const int &apertureHeight
);
private:
static QImage binarization(const QImage &image, const qreal &correctionValue);
static int getReference(QImage &image, const int &xStart, const int &yStart, const int &xEnd, const int &yEnd, const qreal &correctionValue);
static qreal avgReference(const qreal &referenceAvg, const qreal ¤tReference);
static void processImage(QImage &image, const int &xStart, const int &yStart, const int &xEnd, const int &yEnd, const qreal &offset, const qreal &correctionValue);
private:
QSharedPointer< QThreadPool > threadPool_;
QSharedPointer< QSemaphore > semaphore_;
QSharedPointer< QQuickItemGrabResult > quickItemGrabResult_;
qreal defaultCorrectionValue_ = 1.42;
// Property code start
private: int decodeQrCodeType_ = JQQRCodeReader::DecodeQrCodeType;
public: Q_SLOT inline int decodeQrCodeType() const
{ return decodeQrCodeType_; }
public: Q_SLOT inline void setDecodeQrCodeType(const int &newValue)
{ if ( newValue == decodeQrCodeType_ ) { return; } decodeQrCodeType_ = newValue; }
private:
// Property code end
};
#endif//JQQRCODEREADERFORQML_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQQRCodeReader/JQQRCodeReaderForQml.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 961
|
```objective-c
/*
This file is part of JQLibrary
Contact email: 188080501@qq.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __JQLIBRARY_JQZOPFLI_INCLUDE_JQZOPFLI_H__
#define __JQLIBRARY_JQZOPFLI_INCLUDE_JQZOPFLI_H__
// Qt lib import
#include <QString>
namespace JQZopfli
{
struct OptimizeResult
{
bool optimizeSucceed = false;
int originalSize = 0;
int resultSize = 0;
qreal compressionRatio = 0.0;
int timeConsuming = 0;
};
OptimizeResult optimize(const QString &originalFilePath, const QString &resultFilePath);
}
#endif//__JQLIBRARY_JQZOPFLI_INCLUDE_JQZOPFLI_H__
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/JQZopfli.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 392
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Several utilities, including: #defines to try different compression results,
basic deflate specification values and generic program options.
*/
#ifndef ZOPFLI_UTIL_H_
#define ZOPFLI_UTIL_H_
#include <string.h>
#include <stdlib.h>
/* Minimum and maximum length that can be encoded in deflate. */
#define ZOPFLI_MAX_MATCH 258
#define ZOPFLI_MIN_MATCH 3
/* Number of distinct literal/length and distance symbols in DEFLATE */
#define ZOPFLI_NUM_LL 288
#define ZOPFLI_NUM_D 32
/*
The window size for deflate. Must be a power of two. This should be 32768, the
maximum possible by the deflate spec. Anything less hurts compression more than
speed.
*/
#define ZOPFLI_WINDOW_SIZE 32768
/*
The window mask used to wrap indices into the window. This is why the
window size must be a power of two.
*/
#define ZOPFLI_WINDOW_MASK (ZOPFLI_WINDOW_SIZE - 1)
/*
A block structure of huge, non-smart, blocks to divide the input into, to allow
operating on huge files without exceeding memory, such as the 1GB wiki9 corpus.
The whole compression algorithm, including the smarter block splitting, will
be executed independently on each huge block.
Dividing into huge blocks hurts compression, but not much relative to the size.
Set it to 0 to disable master blocks.
*/
#define ZOPFLI_MASTER_BLOCK_SIZE 1000000
/*
Used to initialize costs for example
*/
#define ZOPFLI_LARGE_FLOAT 1e30
/*
For longest match cache. max 256. Uses huge amounts of memory but makes it
faster. Uses this many times three bytes per single byte of the input data.
This is so because longest match finding has to find the exact distance
that belongs to each length for the best lz77 strategy.
Good values: e.g. 5, 8.
*/
#define ZOPFLI_CACHE_LENGTH 8
/*
limit the max hash chain hits for this hash value. This has an effect only
on files where the hash value is the same very often. On these files, this
gives worse compression (the value should ideally be 32768, which is the
ZOPFLI_WINDOW_SIZE, while zlib uses 4096 even for best level), but makes it
faster on some specific files.
Good value: e.g. 8192.
*/
#define ZOPFLI_MAX_CHAIN_HITS 8192
/*
Whether to use the longest match cache for ZopfliFindLongestMatch. This cache
consumes a lot of memory but speeds it up. No effect on compression size.
*/
#define ZOPFLI_LONGEST_MATCH_CACHE
/*
Enable to remember amount of successive identical bytes in the hash chain for
finding longest match
required for ZOPFLI_HASH_SAME_HASH and ZOPFLI_SHORTCUT_LONG_REPETITIONS
This has no effect on the compression result, and enabling it increases speed.
*/
#define ZOPFLI_HASH_SAME
/*
Switch to a faster hash based on the info from ZOPFLI_HASH_SAME once the
best length so far is long enough. This is way faster for files with lots of
identical bytes, on which the compressor is otherwise too slow. Regular files
are unaffected or maybe a tiny bit slower.
This has no effect on the compression result, only on speed.
*/
#define ZOPFLI_HASH_SAME_HASH
/*
Enable this, to avoid slowness for files which are a repetition of the same
character more than a multiple of ZOPFLI_MAX_MATCH times. This should not affect
the compression result.
*/
#define ZOPFLI_SHORTCUT_LONG_REPETITIONS
/*
Whether to use lazy matching in the greedy LZ77 implementation. This gives a
better result of ZopfliLZ77Greedy, but the effect this has on the optimal LZ77
varies from file to file.
*/
#define ZOPFLI_LAZY_MATCHING
/*
Appends value to dynamically allocated memory, doubling its allocation size
whenever needed.
value: the value to append, type T
data: pointer to the dynamic array to append to, type T**
size: pointer to the size of the array to append to, type size_t*. This is the
size that you consider the array to be, not the internal allocation size.
Precondition: allocated size of data is at least a power of two greater than or
equal than *size.
*/
#ifdef __cplusplus /* C++ cannot assign void* from malloc to *data */
#define ZOPFLI_APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\
if (!((*size) & ((*size) - 1))) {\
/*double alloc size if it's a power of two*/\
void** data_void = reinterpret_cast<void**>(data);\
*data_void = (*size) == 0 ? malloc(sizeof(**data))\
: realloc((*data), (*size) * 2 * sizeof(**data));\
}\
(*data)[(*size)] = (value);\
(*size)++;\
}
#else /* C gives problems with strict-aliasing rules for (void**) cast */
#define ZOPFLI_APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\
if (!((*size) & ((*size) - 1))) {\
/*double alloc size if it's a power of two*/\
(*data) = (*size) == 0 ? malloc(sizeof(**data))\
: realloc((*data), (*size) * 2 * sizeof(**data));\
}\
(*data)[(*size)] = (value);\
(*size)++;\
}
#endif
#endif /* ZOPFLI_UTIL_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/util.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,306
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Functions for basic LZ77 compression and utilities for the "squeeze" LZ77
compression.
*/
#ifndef ZOPFLI_LZ77_H_
#define ZOPFLI_LZ77_H_
#include <stdlib.h>
#include "cache.h"
#include "hash.h"
#include "zopfli.h"
/*
Stores lit/length and dist pairs for LZ77.
Parameter litlens: Contains the literal symbols or length values.
Parameter dists: Contains the distances. A value is 0 to indicate that there is
no dist and the corresponding litlens value is a literal instead of a length.
Parameter size: The size of both the litlens and dists arrays.
The memory can best be managed by using ZopfliInitLZ77Store to initialize it,
ZopfliCleanLZ77Store to destroy it, and ZopfliStoreLitLenDist to append values.
*/
typedef struct ZopfliLZ77Store {
unsigned short* litlens; /* Lit or len. */
unsigned short* dists; /* If 0: indicates literal in corresponding litlens,
if > 0: length in corresponding litlens, this is the distance. */
size_t size;
const unsigned char* data; /* original data */
size_t* pos; /* position in data where this LZ77 command begins */
unsigned short* ll_symbol;
unsigned short* d_symbol;
/* Cumulative histograms wrapping around per chunk. Each chunk has the amount
of distinct symbols as length, so using 1 value per LZ77 symbol, we have a
precise histogram at every N symbols, and the rest can be calculated by
looping through the actual symbols of this chunk. */
size_t* ll_counts;
size_t* d_counts;
} ZopfliLZ77Store;
void ZopfliInitLZ77Store(const unsigned char* data, ZopfliLZ77Store* store);
void ZopfliCleanLZ77Store(ZopfliLZ77Store* store);
void ZopfliCopyLZ77Store(const ZopfliLZ77Store* source, ZopfliLZ77Store* dest);
void ZopfliStoreLitLenDist(unsigned short length, unsigned short dist,
size_t pos, ZopfliLZ77Store* store);
void ZopfliAppendLZ77Store(const ZopfliLZ77Store* store,
ZopfliLZ77Store* target);
/* Gets the amount of raw bytes that this range of LZ77 symbols spans. */
size_t ZopfliLZ77GetByteRange(const ZopfliLZ77Store* lz77,
size_t lstart, size_t lend);
/* Gets the histogram of lit/len and dist symbols in the given range, using the
cumulative histograms, so faster than adding one by one for large range. Does
not add the one end symbol of value 256. */
void ZopfliLZ77GetHistogram(const ZopfliLZ77Store* lz77,
size_t lstart, size_t lend,
size_t* ll_counts, size_t* d_counts);
/*
Some state information for compressing a block.
This is currently a bit under-used (with mainly only the longest match cache),
but is kept for easy future expansion.
*/
typedef struct ZopfliBlockState {
const ZopfliOptions* options;
#ifdef ZOPFLI_LONGEST_MATCH_CACHE
/* Cache for length/distance pairs found so far. */
ZopfliLongestMatchCache* lmc;
#endif
/* The start (inclusive) and end (not inclusive) of the current block. */
size_t blockstart;
size_t blockend;
} ZopfliBlockState;
void ZopfliInitBlockState(const ZopfliOptions* options,
size_t blockstart, size_t blockend, int add_lmc,
ZopfliBlockState* s);
void ZopfliCleanBlockState(ZopfliBlockState* s);
/*
Finds the longest match (length and corresponding distance) for LZ77
compression.
Even when not using "sublen", it can be more efficient to provide an array,
because only then the caching is used.
array: the data
pos: position in the data to find the match for
size: size of the data
limit: limit length to maximum this value (default should be 258). This allows
finding a shorter dist for that length (= less extra bits). Must be
in the range [ZOPFLI_MIN_MATCH, ZOPFLI_MAX_MATCH].
sublen: output array of 259 elements, or null. Has, for each length, the
smallest distance required to reach this length. Only 256 of its 259 values
are used, the first 3 are ignored (the shortest length is 3. It is purely
for convenience that the array is made 3 longer).
*/
void ZopfliFindLongestMatch(
ZopfliBlockState *s, const ZopfliHash* h, const unsigned char* array,
size_t pos, size_t size, size_t limit,
unsigned short* sublen, unsigned short* distance, unsigned short* length);
/*
Verifies if length and dist are indeed valid, only used for assertion.
*/
void ZopfliVerifyLenDist(const unsigned char* data, size_t datasize, size_t pos,
unsigned short dist, unsigned short length);
/*
Does LZ77 using an algorithm similar to gzip, with lazy matching, rather than
with the slow but better "squeeze" implementation.
The result is placed in the ZopfliLZ77Store.
If instart is larger than 0, it uses values before instart as starting
dictionary.
*/
void ZopfliLZ77Greedy(ZopfliBlockState* s, const unsigned char* in,
size_t instart, size_t inend,
ZopfliLZ77Store* store, ZopfliHash* h);
#endif /* ZOPFLI_LZ77_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/lz77.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,392
|
```c++
//
//
// path_to_url
//
// Unless required by applicable law or agreed to in writing, software
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// Author: Jyrki Alakuijala (jyrki.alakuijala@gmail.com)
//
// The physical architecture of butteraugli is based on the following naming
// convention:
// * Opsin - dynamics of the photosensitive chemicals in the retina
// with their immediate electrical processing
// * Xyb - hybrid opponent/trichromatic color space
// x is roughly red-subtract-green.
// y is yellow.
// b is blue.
// Xyb values are computed from Opsin mixing, not directly from rgb.
// * Mask - for visual masking
// * Hf - color modeling for spatially high-frequency features
// * Lf - color modeling for spatially low-frequency features
// * Diffmap - to cluster and build an image of error between the images
// * Blur - to hold the smoothing code
#include "butteraugli/butteraugli.h"
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <array>
// Restricted pointers speed up Convolution(); MSVC uses a different keyword.
#ifdef _MSC_VER
#define __restrict__ __restrict
#endif
namespace butteraugli {
void *CacheAligned::Allocate(const size_t bytes) {
char *const allocated = static_cast<char *>(malloc(bytes + kCacheLineSize));
if (allocated == nullptr) {
return nullptr;
}
const uintptr_t misalignment =
reinterpret_cast<uintptr_t>(allocated) & (kCacheLineSize - 1);
// malloc is at least kPointerSize aligned, so we can store the "allocated"
// pointer immediately before the aligned memory.
assert(misalignment % kPointerSize == 0);
char *const aligned = allocated + kCacheLineSize - misalignment;
memcpy(aligned - kPointerSize, &allocated, kPointerSize);
return aligned;
}
void CacheAligned::Free(void *aligned_pointer) {
if (aligned_pointer == nullptr) {
return;
}
char *const aligned = static_cast<char *>(aligned_pointer);
assert(reinterpret_cast<uintptr_t>(aligned) % kCacheLineSize == 0);
char *allocated;
memcpy(&allocated, aligned - kPointerSize, kPointerSize);
assert(allocated <= aligned - kPointerSize);
assert(allocated >= aligned - kCacheLineSize);
free(allocated);
}
static inline bool IsNan(const float x) {
uint32_t bits;
memcpy(&bits, &x, sizeof(bits));
const uint32_t bitmask_exp = 0x7F800000;
return (bits & bitmask_exp) == bitmask_exp && (bits & 0x7FFFFF);
}
static inline bool IsNan(const double x) {
uint64_t bits;
memcpy(&bits, &x, sizeof(bits));
return (0x7ff0000000000001ULL <= bits && bits <= 0x7fffffffffffffffULL) ||
(0xfff0000000000001ULL <= bits && bits <= 0xffffffffffffffffULL);
}
static inline void CheckImage(const ImageF &image, const char *name) {
for (size_t y = 0; y < image.ysize(); ++y) {
ConstRestrict<const float *> row = image.Row(y);
for (size_t x = 0; x < image.xsize(); ++x) {
if (IsNan(row[x])) {
printf("Image %s @ %lu,%lu (of %lu,%lu)\n", name, x, y, image.xsize(),
image.ysize());
exit(1);
}
}
}
}
void RemoveWarningHeloer::something()
{
return;
IsNan( (double)1.11 );
CheckImage( ImageF(), nullptr );
}
#if BUTTERAUGLI_ENABLE_CHECKS
#define CHECK_NAN(x, str) \
do { \
if (IsNan(x)) { \
printf("%d: %s\n", __LINE__, str); \
abort(); \
} \
} while (0)
#define CHECK_IMAGE(image, name) CheckImage(image, name)
#else
#define CHECK_NAN(x, str)
#define CHECK_IMAGE(image, name)
#endif
static const double kInternalGoodQualityThreshold = 14.921561160295326;
static const double kGlobalScale = 1.0 / kInternalGoodQualityThreshold;
inline double DotProduct(const double u[3], const double v[3]) {
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
}
inline double DotProduct(const float u[3], const double v[3]) {
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
}
// Computes a horizontal convolution and transposes the result.
static void Convolution(size_t xsize, size_t ysize,
size_t xstep,
size_t len, size_t offset,
const float* __restrict__ multipliers,
const float* __restrict__ inp,
double border_ratio,
float* __restrict__ result) {
PROFILER_FUNC;
double weight_no_border = 0;
for (int j = 0; j <= 2 * (int)offset; ++j) {
weight_no_border += multipliers[j];
}
for (size_t x = 0, ox = 0; x < xsize; x += xstep, ox++) {
int minx = x < offset ? 0 : x - offset;
int maxx = std::min(xsize, x + len - offset) - 1;
double weight = 0.0;
for (int j = minx; j <= maxx; ++j) {
weight += multipliers[j - x + offset];
}
// Interpolate linearly between the no-border scaling and border scaling.
weight = (1.0 - border_ratio) * weight + border_ratio * weight_no_border;
double scale = 1.0 / weight;
for (size_t y = 0; y < ysize; ++y) {
double sum = 0.0;
for (int j = minx; j <= maxx; ++j) {
sum += inp[y * xsize + j] * multipliers[j - x + offset];
}
result[ox * ysize + y] = sum * scale;
}
}
}
void Blur(size_t xsize, size_t ysize, float* channel, double sigma,
double border_ratio) {
PROFILER_FUNC;
double m = 2.25; // Accuracy increases when m is increased.
const double scaler = -1.0 / (2 * sigma * sigma);
// For m = 9.0: exp(-scaler * diff * diff) < 2^ {-52}
const int diff = std::max<int>(1, m * fabs(sigma));
const int expn_size = 2 * diff + 1;
std::vector<float> expn(expn_size);
for (int i = -diff; i <= diff; ++i) {
expn[i + diff] = exp(scaler * i * i);
}
const int xstep = std::max(1, int(sigma / 3));
const int ystep = xstep;
int dxsize = (xsize + xstep - 1) / xstep;
int dysize = (ysize + ystep - 1) / ystep;
std::vector<float> tmp(dxsize * ysize);
std::vector<float> downsampled_output(dxsize * dysize);
Convolution(xsize, ysize, xstep, expn_size, diff, expn.data(), channel,
border_ratio,
tmp.data());
Convolution(ysize, dxsize, ystep, expn_size, diff, expn.data(), tmp.data(),
border_ratio,
downsampled_output.data());
for (int y = 0; y < (int)ysize; y++) {
for (int x = 0; x < (int)xsize; x++) {
// TODO: Use correct rounding.
channel[y * xsize + x] =
downsampled_output[(y / ystep) * dxsize + (x / xstep)];
}
}
}
// To change this to n, add the relevant FFTn function and kFFTnMapIndexTable.
constexpr size_t kBlockEdge = 8;
constexpr size_t kBlockSize = kBlockEdge * kBlockEdge;
constexpr size_t kBlockEdgeHalf = kBlockEdge / 2;
constexpr size_t kBlockHalf = kBlockEdge * kBlockEdgeHalf;
// Contrast sensitivity related weights.
static const double *GetContrastSensitivityMatrix() {
static double csf8x8[kBlockHalf + kBlockEdgeHalf + 1] = {
5.28270670524,
0.0,
0.0,
0.0,
0.3831134973,
0.676303603859,
3.58927792424,
18.6104367002,
18.6104367002,
3.09093131948,
1.0,
0.498250875965,
0.36198671102,
0.308982169883,
0.1312701920435,
2.37370549629,
3.58927792424,
1.0,
2.37370549629,
0.991205724152,
1.05178802919,
0.627264168628,
0.4,
0.1312701920435,
0.676303603859,
0.498250875965,
0.991205724152,
0.5,
0.3831134973,
0.349686450518,
0.627264168628,
0.308982169883,
0.3831134973,
0.36198671102,
1.05178802919,
0.3831134973,
0.12,
};
return &csf8x8[0];
}
std::array<double, 21> MakeHighFreqColorDiffDx() {
std::array<double, 21> lut;
static const double off = 11.38708334481672;
static const double inc = 14.550189611520716;
lut[0] = 0.0;
lut[1] = off;
for (int i = 2; i < 21; ++i) {
lut[i] = lut[i - 1] + inc;
}
return lut;
}
const double *GetHighFreqColorDiffDx() {
static const std::array<double, 21> kLut = MakeHighFreqColorDiffDx();
return kLut.data();
}
std::array<double, 21> MakeHighFreqColorDiffDy() {
std::array<double, 21> lut;
static const double off = 1.4103373714040413;
static const double inc = 0.7084088867024;
lut[0] = 0.0;
lut[1] = off;
for (int i = 2; i < 21; ++i) {
lut[i] = lut[i - 1] + inc;
}
return lut;
}
const double *GetHighFreqColorDiffDy() {
static const std::array<double, 21> kLut = MakeHighFreqColorDiffDy();
return kLut.data();
}
std::array<double, 21> MakeLowFreqColorDiffDy() {
std::array<double, 21> lut;
static const double inc = 5.2511644570349185;
lut[0] = 0.0;
for (int i = 1; i < 21; ++i) {
lut[i] = lut[i - 1] + inc;
}
return lut;
}
const double *GetLowFreqColorDiffDy() {
static const std::array<double, 21> kLut = MakeLowFreqColorDiffDy();
return kLut.data();
}
inline double Interpolate(const double *array, int size, double sx) {
double ix = fabs(sx);
assert(ix < 10000);
int baseix = static_cast<int>(ix);
double res;
if (baseix >= size - 1) {
res = array[size - 1];
} else {
double mix = ix - baseix;
int nextix = baseix + 1;
res = array[baseix] + mix * (array[nextix] - array[baseix]);
}
if (sx < 0) res = -res;
return res;
}
inline double InterpolateClampNegative(const double *array,
int size, double sx) {
if (sx < 0) {
sx = 0;
}
double ix = fabs(sx);
int baseix = static_cast<int>(ix);
double res;
if (baseix >= size - 1) {
res = array[size - 1];
} else {
double mix = ix - baseix;
int nextix = baseix + 1;
res = array[baseix] + mix * (array[nextix] - array[baseix]);
}
return res;
}
void RgbToXyb(double r, double g, double b,
double *valx, double *valy, double *valz) {
static const double a0 = 1.01611726948;
static const double a1 = 0.982482243696;
static const double a2 = 1.43571362627;
static const double a3 = 0.896039849412;
*valx = a0 * r - a1 * g;
*valy = a2 * r + a3 * g;
*valz = b;
}
static inline void XybToVals(double x, double y, double z,
double *valx, double *valy, double *valz) {
static const double xmul = 0.758304045695;
static const double ymul = 2.28148649801;
static const double zmul = 1.87816926918;
*valx = Interpolate(GetHighFreqColorDiffDx(), 21, x * xmul);
*valy = Interpolate(GetHighFreqColorDiffDy(), 21, y * ymul);
*valz = zmul * z;
}
// Rough psychovisual distance to gray for low frequency colors.
static void XybLowFreqToVals(double x, double y, double z,
double *valx, double *valy, double *valz) {
static const double xmul = 6.64482198135;
static const double ymul = 0.837846224276;
static const double zmul = 7.34905756986;
static const double y_to_z_mul = 0.0812519812628;
z += y_to_z_mul * y;
*valz = z * zmul;
*valx = x * xmul;
*valy = Interpolate(GetLowFreqColorDiffDy(), 21, y * ymul);
}
double RemoveRangeAroundZero(double v, double range) {
if (v >= -range && v < range) {
return 0;
}
if (v < 0) {
return v + range;
} else {
return v - range;
}
}
void XybDiffLowFreqSquaredAccumulate(double r0, double g0, double b0,
double r1, double g1, double b1,
double factor, double res[3]) {
double valx0, valy0, valz0;
double valx1, valy1, valz1;
XybLowFreqToVals(r0, g0, b0, &valx0, &valy0, &valz0);
if (r1 == 0.0 && g1 == 0.0 && b1 == 0.0) {
PROFILER_ZONE("XybDiff r1=g1=b1=0");
res[0] += factor * valx0 * valx0;
res[1] += factor * valy0 * valy0;
res[2] += factor * valz0 * valz0;
return;
}
XybLowFreqToVals(r1, g1, b1, &valx1, &valy1, &valz1);
// Approximate the distance of the colors by their respective distances
// to gray.
double valx = valx0 - valx1;
double valy = valy0 - valy1;
double valz = valz0 - valz1;
res[0] += factor * valx * valx;
res[1] += factor * valy * valy;
res[2] += factor * valz * valz;
}
struct Complex {
public:
double real;
double imag;
};
inline double abssq(const Complex& c) {
return c.real * c.real + c.imag * c.imag;
}
static void TransposeBlock(Complex data[kBlockSize]) {
for (int i = 0; i < (int)kBlockEdge; i++) {
for (int j = 0; j < i; j++) {
std::swap(data[kBlockEdge * i + j], data[kBlockEdge * j + i]);
}
}
}
// D. J. Bernstein's Fast Fourier Transform algorithm on 4 elements.
inline void FFT4(Complex* a) {
double t1, t2, t3, t4, t5, t6, t7, t8;
t5 = a[2].real;
t1 = a[0].real - t5;
t7 = a[3].real;
t5 += a[0].real;
t3 = a[1].real - t7;
t7 += a[1].real;
t8 = t5 + t7;
a[0].real = t8;
t5 -= t7;
a[1].real = t5;
t6 = a[2].imag;
t2 = a[0].imag - t6;
t6 += a[0].imag;
t5 = a[3].imag;
a[2].imag = t2 + t3;
t2 -= t3;
a[3].imag = t2;
t4 = a[1].imag - t5;
a[3].real = t1 + t4;
t1 -= t4;
a[2].real = t1;
t5 += a[1].imag;
a[0].imag = t6 + t5;
t6 -= t5;
a[1].imag = t6;
}
static const double kSqrtHalf = 0.70710678118654752440084436210484903;
// D. J. Bernstein's Fast Fourier Transform algorithm on 8 elements.
void FFT8(Complex* a) {
double t1, t2, t3, t4, t5, t6, t7, t8;
t7 = a[4].imag;
t4 = a[0].imag - t7;
t7 += a[0].imag;
a[0].imag = t7;
t8 = a[6].real;
t5 = a[2].real - t8;
t8 += a[2].real;
a[2].real = t8;
t7 = a[6].imag;
a[6].imag = t4 - t5;
t4 += t5;
a[4].imag = t4;
t6 = a[2].imag - t7;
t7 += a[2].imag;
a[2].imag = t7;
t8 = a[4].real;
t3 = a[0].real - t8;
t8 += a[0].real;
a[0].real = t8;
a[4].real = t3 - t6;
t3 += t6;
a[6].real = t3;
t7 = a[5].real;
t3 = a[1].real - t7;
t7 += a[1].real;
a[1].real = t7;
t8 = a[7].imag;
t6 = a[3].imag - t8;
t8 += a[3].imag;
a[3].imag = t8;
t1 = t3 - t6;
t3 += t6;
t7 = a[5].imag;
t4 = a[1].imag - t7;
t7 += a[1].imag;
a[1].imag = t7;
t8 = a[7].real;
t5 = a[3].real - t8;
t8 += a[3].real;
a[3].real = t8;
t2 = t4 - t5;
t4 += t5;
t6 = t1 - t4;
t8 = kSqrtHalf;
t6 *= t8;
a[5].real = a[4].real - t6;
t1 += t4;
t1 *= t8;
a[5].imag = a[4].imag - t1;
t6 += a[4].real;
a[4].real = t6;
t1 += a[4].imag;
a[4].imag = t1;
t5 = t2 - t3;
t5 *= t8;
a[7].imag = a[6].imag - t5;
t2 += t3;
t2 *= t8;
a[7].real = a[6].real - t2;
t2 += a[6].real;
a[6].real = t2;
t5 += a[6].imag;
a[6].imag = t5;
FFT4(a);
// Reorder to the correct output order.
// TODO: Modify the above computation so that this is not needed.
Complex tmp = a[2];
a[2] = a[3];
a[3] = a[5];
a[5] = a[7];
a[7] = a[4];
a[4] = a[1];
a[1] = a[6];
a[6] = tmp;
}
// Same as FFT8, but all inputs are real.
// TODO: Since this does not need to be in-place, maybe there is a
// faster FFT than this one, which is derived from DJB's in-place complex FFT.
void RealFFT8(const double* in, Complex* out) {
double t1, t2, t3, t5, t6, t7, t8;
t8 = in[6];
t5 = in[2] - t8;
t8 += in[2];
out[2].real = t8;
out[6].imag = -t5;
out[4].imag = t5;
t8 = in[4];
t3 = in[0] - t8;
t8 += in[0];
out[0].real = t8;
out[4].real = t3;
out[6].real = t3;
t7 = in[5];
t3 = in[1] - t7;
t7 += in[1];
out[1].real = t7;
t8 = in[7];
t5 = in[3] - t8;
t8 += in[3];
out[3].real = t8;
t2 = -t5;
t6 = t3 - t5;
t8 = kSqrtHalf;
t6 *= t8;
out[5].real = out[4].real - t6;
t1 = t3 + t5;
t1 *= t8;
out[5].imag = out[4].imag - t1;
t6 += out[4].real;
out[4].real = t6;
t1 += out[4].imag;
out[4].imag = t1;
t5 = t2 - t3;
t5 *= t8;
out[7].imag = out[6].imag - t5;
t2 += t3;
t2 *= t8;
out[7].real = out[6].real - t2;
t2 += out[6].real;
out[6].real = t2;
t5 += out[6].imag;
out[6].imag = t5;
t5 = out[2].real;
t1 = out[0].real - t5;
t7 = out[3].real;
t5 += out[0].real;
t3 = out[1].real - t7;
t7 += out[1].real;
t8 = t5 + t7;
out[0].real = t8;
t5 -= t7;
out[1].real = t5;
out[2].imag = t3;
out[3].imag = -t3;
out[3].real = t1;
out[2].real = t1;
out[0].imag = 0;
out[1].imag = 0;
// Reorder to the correct output order.
// TODO: Modify the above computation so that this is not needed.
Complex tmp = out[2];
out[2] = out[3];
out[3] = out[5];
out[5] = out[7];
out[7] = out[4];
out[4] = out[1];
out[1] = out[6];
out[6] = tmp;
}
// Fills in block[kBlockEdgeHalf..(kBlockHalf+kBlockEdgeHalf)], and leaves the
// rest unmodified.
void ButteraugliFFTSquared(double block[kBlockSize]) {
double global_mul = 0.000064;
Complex block_c[kBlockSize];
assert(kBlockEdge == 8);
for (int y = 0; y < (int)kBlockEdge; ++y) {
RealFFT8(block + y * kBlockEdge, block_c + y * kBlockEdge);
}
TransposeBlock(block_c);
double r0[kBlockEdge];
double r1[kBlockEdge];
for (int x = 0; x < (int)kBlockEdge; ++x) {
r0[x] = block_c[x].real;
r1[x] = block_c[kBlockHalf + x].real;
}
RealFFT8(r0, block_c);
RealFFT8(r1, block_c + kBlockHalf);
for (int y = 1; y < (int)kBlockEdgeHalf; ++y) {
FFT8(block_c + y * kBlockEdge);
}
for (int i = kBlockEdgeHalf; i < (int)kBlockHalf + (int)kBlockEdgeHalf + 1; ++i) {
block[i] = abssq(block_c[i]);
block[i] *= global_mul;
}
}
// Computes 8x8 FFT of each channel of xyb0 and xyb1 and adds the total squared
// 3-dimensional xybdiff of the two blocks to diff_xyb_{dc,ac} and the average
// diff on the edges to diff_xyb_edge_dc.
void ButteraugliBlockDiff(double xyb0[3 * kBlockSize],
double xyb1[3 * kBlockSize],
double diff_xyb_dc[3],
double diff_xyb_ac[3],
double diff_xyb_edge_dc[3]) {
PROFILER_FUNC;
const double *csf8x8 = GetContrastSensitivityMatrix();
double avgdiff_xyb[3] = {0.0};
double avgdiff_edge[3][4] = { {0.0} };
for (int i = 0; i < 3 * (int)kBlockSize; ++i) {
const double diff_xyb = xyb0[i] - xyb1[i];
const int c = i / kBlockSize;
avgdiff_xyb[c] += diff_xyb / kBlockSize;
const int k = i % kBlockSize;
const int kx = k % kBlockEdge;
const int ky = k / kBlockEdge;
const int h_edge_idx = ky == 0 ? 1 : ky == 7 ? 3 : -1;
const int v_edge_idx = kx == 0 ? 0 : kx == 7 ? 2 : -1;
if (h_edge_idx >= 0) {
avgdiff_edge[c][h_edge_idx] += diff_xyb / kBlockEdge;
}
if (v_edge_idx >= 0) {
avgdiff_edge[c][v_edge_idx] += diff_xyb / kBlockEdge;
}
}
XybDiffLowFreqSquaredAccumulate(avgdiff_xyb[0],
avgdiff_xyb[1],
avgdiff_xyb[2],
0, 0, 0, csf8x8[0],
diff_xyb_dc);
for (int i = 0; i < 4; ++i) {
XybDiffLowFreqSquaredAccumulate(avgdiff_edge[0][i],
avgdiff_edge[1][i],
avgdiff_edge[2][i],
0, 0, 0, csf8x8[0],
diff_xyb_edge_dc);
}
double* xyb_avg = xyb0;
double* xyb_halfdiff = xyb1;
for(int i = 0; i < 3 * (int)kBlockSize; ++i) {
double avg = (xyb0[i] + xyb1[i])/2;
double halfdiff = (xyb0[i] - xyb1[i])/2;
xyb_avg[i] = avg;
xyb_halfdiff[i] = halfdiff;
}
double *y_avg = &xyb_avg[kBlockSize];
double *x_halfdiff_squared = &xyb_halfdiff[0];
double *y_halfdiff = &xyb_halfdiff[kBlockSize];
double *z_halfdiff_squared = &xyb_halfdiff[2 * kBlockSize];
ButteraugliFFTSquared(y_avg);
ButteraugliFFTSquared(x_halfdiff_squared);
ButteraugliFFTSquared(y_halfdiff);
ButteraugliFFTSquared(z_halfdiff_squared);
static const double xmul = 64.8;
static const double ymul = 1.753123908348329;
static const double ymul2 = 1.51983458269;
static const double zmul = 2.4;
for (size_t i = kBlockEdgeHalf; i < kBlockHalf + kBlockEdgeHalf + 1; ++i) {
double d = csf8x8[i];
diff_xyb_ac[0] += d * xmul * x_halfdiff_squared[i];
diff_xyb_ac[2] += d * zmul * z_halfdiff_squared[i];
y_avg[i] = sqrt(y_avg[i]);
y_halfdiff[i] = sqrt(y_halfdiff[i]);
double y0 = y_avg[i] - y_halfdiff[i];
double y1 = y_avg[i] + y_halfdiff[i];
// Remove the impact of small absolute values.
// This improves the behavior with flat noise.
static const double ylimit = 0.04;
y0 = RemoveRangeAroundZero(y0, ylimit);
y1 = RemoveRangeAroundZero(y1, ylimit);
if (y0 != y1) {
double valy0 = Interpolate(GetHighFreqColorDiffDy(), 21, y0 * ymul2);
double valy1 = Interpolate(GetHighFreqColorDiffDy(), 21, y1 * ymul2);
double valy = ymul * (valy0 - valy1);
diff_xyb_ac[1] += d * valy * valy;
}
}
}
// Low frequency edge detectors.
// Two edge detectors are applied in each corner of the 8x8 square.
// The squared 3-dimensional error vector is added to diff_xyb.
void Butteraugli8x8CornerEdgeDetectorDiff(
const size_t pos_x,
const size_t pos_y,
const size_t xsize,
const size_t ysize,
const std::vector<std::vector<float> > &blurred0,
const std::vector<std::vector<float> > &blurred1,
double diff_xyb[3]) {
PROFILER_FUNC;
int local_count = 0;
double local_xyb[3] = { 0 };
static const double w = 0.711100840192;
for (int k = 0; k < 4; ++k) {
size_t step = 3;
size_t offset[4][2] = { { 0, 0 }, { 0, 7 }, { 7, 0 }, { 7, 7 } };
size_t x = pos_x + offset[k][0];
size_t y = pos_y + offset[k][1];
if (x >= step && x + step < xsize) {
size_t ix = y * xsize + (x - step);
size_t ix2 = ix + 2 * step;
XybDiffLowFreqSquaredAccumulate(
w * (blurred0[0][ix] - blurred0[0][ix2]),
w * (blurred0[1][ix] - blurred0[1][ix2]),
w * (blurred0[2][ix] - blurred0[2][ix2]),
w * (blurred1[0][ix] - blurred1[0][ix2]),
w * (blurred1[1][ix] - blurred1[1][ix2]),
w * (blurred1[2][ix] - blurred1[2][ix2]),
1.0, local_xyb);
++local_count;
}
if (y >= step && y + step < ysize) {
size_t ix = (y - step) * xsize + x;
size_t ix2 = ix + 2 * step * xsize;
XybDiffLowFreqSquaredAccumulate(
w * (blurred0[0][ix] - blurred0[0][ix2]),
w * (blurred0[1][ix] - blurred0[1][ix2]),
w * (blurred0[2][ix] - blurred0[2][ix2]),
w * (blurred1[0][ix] - blurred1[0][ix2]),
w * (blurred1[1][ix] - blurred1[1][ix2]),
w * (blurred1[2][ix] - blurred1[2][ix2]),
1.0, local_xyb);
++local_count;
}
}
static const double weight = 0.01617112696;
const double mul = weight * 8.0 / local_count;
for (int i = 0; i < 3; ++i) {
diff_xyb[i] += mul * local_xyb[i];
}
}
// path_to_url absordance modeling.
const double *GetOpsinAbsorbance() {
static const double kMix[12] = {
0.348036746003,
0.577814843137,
0.0544556093735,
0.774145581713,
0.26922717275,
0.767247733938,
0.0366922708552,
0.920130265014,
0.0882062883536,
0.158581714673,
0.712857943858,
10.6524069248,
};
return &kMix[0];
}
void OpsinAbsorbance(const double in[3], double out[3]) {
const double *mix = GetOpsinAbsorbance();
out[0] = mix[0] * in[0] + mix[1] * in[1] + mix[2] * in[2] + mix[3];
out[1] = mix[4] * in[0] + mix[5] * in[1] + mix[6] * in[2] + mix[7];
out[2] = mix[8] * in[0] + mix[9] * in[1] + mix[10] * in[2] + mix[11];
}
double GammaMinArg() {
double in[3] = { 0.0, 0.0, 0.0 };
double out[3];
OpsinAbsorbance(in, out);
return std::min(out[0], std::min(out[1], out[2]));
}
double GammaMaxArg() {
double in[3] = { 255.0, 255.0, 255.0 };
double out[3];
OpsinAbsorbance(in, out);
return std::max(out[0], std::max(out[1], out[2]));
}
ButteraugliComparator::ButteraugliComparator(
size_t xsize, size_t ysize, int step)
: xsize_(xsize),
ysize_(ysize),
num_pixels_(xsize * ysize),
step_(step),
res_xsize_((xsize + step - 1) / step),
res_ysize_((ysize + step - 1) / step) {
assert(step <= 4);
}
void MaskHighIntensityChange(
size_t xsize, size_t ysize,
const std::vector<std::vector<float> > &c0,
const std::vector<std::vector<float> > &c1,
std::vector<std::vector<float> > &xyb0,
std::vector<std::vector<float> > &xyb1) {
PROFILER_FUNC;
for (int y = 0; y < (int)ysize; ++y) {
for (int x = 0; x < (int)xsize; ++x) {
int ix = y * xsize + x;
const double ave[3] = {
(c0[0][ix] + c1[0][ix]) * 0.5,
(c0[1][ix] + c1[1][ix]) * 0.5,
(c0[2][ix] + c1[2][ix]) * 0.5,
};
double sqr_max_diff = -1;
{
int offset[4] =
{ -1, 1, -static_cast<int>(xsize), static_cast<int>(xsize) };
int border[4] =
{ x == 0, x + 1 == (int)xsize, y == 0, y + 1 == (int)ysize };
for (int dir = 0; dir < 4; ++dir) {
if (border[dir]) {
continue;
}
const int ix2 = ix + offset[dir];
double diff = 0.5 * (c0[1][ix2] + c1[1][ix2]) - ave[1];
diff *= diff;
if (sqr_max_diff < diff) {
sqr_max_diff = diff;
}
}
}
static const double kReductionX = 275.19165240059317;
static const double kReductionY = 18599.41286306991;
static const double kReductionZ = 410.8995306951065;
static const double kChromaBalance = 106.95800948271017;
double chroma_scale = kChromaBalance / (ave[1] + kChromaBalance);
const double mix[3] = {
chroma_scale * kReductionX / (sqr_max_diff + kReductionX),
kReductionY / (sqr_max_diff + kReductionY),
chroma_scale * kReductionZ / (sqr_max_diff + kReductionZ),
};
// Interpolate lineraly between the average color and the actual
// color -- to reduce the importance of this pixel.
for (int i = 0; i < 3; ++i) {
xyb0[i][ix] = mix[i] * c0[i][ix] + (1 - mix[i]) * ave[i];
xyb1[i][ix] = mix[i] * c1[i][ix] + (1 - mix[i]) * ave[i];
}
}
}
}
double SimpleGamma(double v) {
static const double kGamma = 0.387494322593;
static const double limit = 43.01745241042018;
double bright = v - limit;
if (bright >= 0) {
static const double mul = 0.0383723643799;
v -= bright * mul;
}
static const double limit2 = 94.68634353321337;
double bright2 = v - limit2;
if (bright2 >= 0) {
static const double mul = 0.22885405968;
v -= bright2 * mul;
}
static const double offset = 0.156775786057;
static const double scale = 8.898059160493739;
double retval = scale * (offset + pow(v, kGamma));
return retval;
}
static inline double Gamma(double v) {
// return SimpleGamma(v);
return GammaPolynomial(v);
}
void OpsinDynamicsImage(size_t xsize, size_t ysize,
std::vector<std::vector<float> > &rgb) {
PROFILER_FUNC;
std::vector<std::vector<float> > blurred = rgb;
static const double kSigma = 1.1;
for (int i = 0; i < 3; ++i) {
Blur(xsize, ysize, blurred[i].data(), kSigma, 0.0);
}
for (int i = 0; i < (int)rgb[0].size(); ++i) {
double sensitivity[3];
{
// Calculate sensitivity[3] based on the smoothed image gamma derivative.
double pre_rgb[3] = { blurred[0][i], blurred[1][i], blurred[2][i] };
double pre_mixed[3];
OpsinAbsorbance(pre_rgb, pre_mixed);
sensitivity[0] = Gamma(pre_mixed[0]) / pre_mixed[0];
sensitivity[1] = Gamma(pre_mixed[1]) / pre_mixed[1];
sensitivity[2] = Gamma(pre_mixed[2]) / pre_mixed[2];
}
double cur_rgb[3] = { rgb[0][i], rgb[1][i], rgb[2][i] };
double cur_mixed[3];
OpsinAbsorbance(cur_rgb, cur_mixed);
cur_mixed[0] *= sensitivity[0];
cur_mixed[1] *= sensitivity[1];
cur_mixed[2] *= sensitivity[2];
double x, y, z;
RgbToXyb(cur_mixed[0], cur_mixed[1], cur_mixed[2], &x, &y, &z);
rgb[0][i] = x;
rgb[1][i] = y;
rgb[2][i] = z;
}
}
static void ScaleImage(double scale, std::vector<float> *result) {
PROFILER_FUNC;
for (size_t i = 0; i < result->size(); ++i) {
(*result)[i] *= scale;
}
}
// Making a cluster of local errors to be more impactful than
// just a single error.
void CalculateDiffmap(const size_t xsize, const size_t ysize,
const int step,
std::vector<float>* diffmap) {
PROFILER_FUNC;
// Shift the diffmap more correctly above the pixels, from 2.5 pixels to 0.5
// pixels distance over the original image. The border of 2 pixels on top and
// left side and 3 pixels on right and bottom side are zeroed, but these
// values have no meaning, they only exist to keep the result map the same
// size as the input images.
int s2 = (8 - step) / 2;
// Upsample and take square root.
std::vector<float> diffmap_out(xsize * ysize);
const size_t res_xsize = (xsize + step - 1) / step;
for (size_t res_y = 0; res_y + 8 - step < ysize; res_y += step) {
for (size_t res_x = 0; res_x + 8 - step < xsize; res_x += step) {
size_t res_ix = (res_y * res_xsize + res_x) / step;
float orig_val = (*diffmap)[res_ix];
constexpr float kInitialSlope = 100;
// TODO(b/29974893): Until that is fixed do not call sqrt on very small
// numbers.
double val = orig_val < (1.0 / (kInitialSlope * kInitialSlope))
? kInitialSlope * orig_val
: std::sqrt(orig_val);
for (size_t off_y = 0; off_y < (size_t)step; ++off_y) {
for (size_t off_x = 0; off_x < (size_t)step; ++off_x) {
diffmap_out[(res_y + off_y + s2) * xsize + res_x + off_x + s2] = val;
}
}
}
}
*diffmap = diffmap_out;
{
static const double kSigma = 8.8510880283;
static const double mul1 = 24.8235314874;
static const double scale = 1.0 / (1.0 + mul1);
const int s = 8 - step;
std::vector<float> blurred((xsize - s) * (ysize - s));
for (int y = 0; y < (int)ysize - s; ++y) {
for (int x = 0; x < (int)xsize - s; ++x) {
blurred[y * (xsize - s) + x] = (*diffmap)[(y + s2) * xsize + x + s2];
}
}
static const double border_ratio = 0.03027655136;
Blur(xsize - s, ysize - s, blurred.data(), kSigma, border_ratio);
for (int y = 0; y < (int)ysize - s; ++y) {
for (int x = 0; x < (int)xsize - s; ++x) {
(*diffmap)[(y + s2) * xsize + x + s2]
+= mul1 * blurred[y * (xsize - s) + x];
}
}
ScaleImage(scale, diffmap);
}
}
void ButteraugliComparator::Diffmap(const std::vector<ImageF> &rgb0_arg,
const std::vector<ImageF> &rgb1_arg,
ImageF &result) {
result = ImageF(xsize_, ysize_);
if (xsize_ < 8 || ysize_ < 8) return;
std::vector<std::vector<float>> rgb0_c = PackedFromPlanes(rgb0_arg);
std::vector<std::vector<float>> rgb1_c = PackedFromPlanes(rgb1_arg);
OpsinDynamicsImage(xsize_, ysize_, rgb0_c);
OpsinDynamicsImage(xsize_, ysize_, rgb1_c);
std::vector<ImageF> pg0 = PlanesFromPacked(xsize_, ysize_, rgb0_c);
std::vector<ImageF> pg1 = PlanesFromPacked(xsize_, ysize_, rgb1_c);
DiffmapOpsinDynamicsImage(pg0, pg1, result);
}
void ButteraugliComparator::DiffmapOpsinDynamicsImage(
const std::vector<ImageF> &xyb0_arg, const std::vector<ImageF> &xyb1_arg,
ImageF &result) {
result = ImageF(xsize_, ysize_);
if (xsize_ < 8 || ysize_ < 8) return;
std::vector<std::vector<float>> xyb0 = PackedFromPlanes(xyb0_arg);
std::vector<std::vector<float>> xyb1 = PackedFromPlanes(xyb1_arg);
auto xyb0_c = xyb0;
auto xyb1_c = xyb1;
MaskHighIntensityChange(xsize_, ysize_, xyb0_c, xyb1_c, xyb0, xyb1);
assert(8 <= xsize_);
for (int i = 0; i < 3; i++) {
assert(xyb0[i].size() == num_pixels_);
assert(xyb1[i].size() == num_pixels_);
}
std::vector<std::vector<float> > mask_xyb(3);
std::vector<std::vector<float> > mask_xyb_dc(3);
std::vector<float> block_diff_dc(3 * res_xsize_ * res_ysize_);
std::vector<float> block_diff_ac(3 * res_xsize_ * res_ysize_);
std::vector<float> edge_detector_map(3 * res_xsize_ * res_ysize_);
std::vector<float> packed_result;
BlockDiffMap(xyb0, xyb1, &block_diff_dc, &block_diff_ac);
EdgeDetectorMap(xyb0, xyb1, &edge_detector_map);
EdgeDetectorLowFreq(xyb0, xyb1, &block_diff_ac);
Mask(xyb0, xyb1, xsize_, ysize_, &mask_xyb, &mask_xyb_dc);
CombineChannels(mask_xyb, mask_xyb_dc, block_diff_dc, block_diff_ac,
edge_detector_map, &packed_result);
CalculateDiffmap(xsize_, ysize_, step_, &packed_result);
CopyFromPacked(packed_result, &result);
}
void ButteraugliComparator::BlockDiffMap(
const std::vector<std::vector<float> > &xyb0,
const std::vector<std::vector<float> > &xyb1,
std::vector<float>* block_diff_dc,
std::vector<float>* block_diff_ac) {
PROFILER_FUNC;
for (size_t res_y = 0; res_y + (kBlockEdge - step_ - 1) < ysize_;
res_y += step_) {
for (size_t res_x = 0; res_x + (kBlockEdge - step_ - 1) < xsize_;
res_x += step_) {
size_t res_ix = (res_y * res_xsize_ + res_x) / step_;
size_t offset = (std::min(res_y, ysize_ - 8) * xsize_ +
std::min(res_x, xsize_ - 8));
double block0[3 * kBlockEdge * kBlockEdge];
double block1[3 * kBlockEdge * kBlockEdge];
for (int i = 0; i < 3; ++i) {
double *m0 = &block0[i * kBlockEdge * kBlockEdge];
double *m1 = &block1[i * kBlockEdge * kBlockEdge];
for (size_t y = 0; y < kBlockEdge; y++) {
for (size_t x = 0; x < kBlockEdge; x++) {
m0[kBlockEdge * y + x] = xyb0[i][offset + y * xsize_ + x];
m1[kBlockEdge * y + x] = xyb1[i][offset + y * xsize_ + x];
}
}
}
double diff_xyb_dc[3] = { 0.0 };
double diff_xyb_ac[3] = { 0.0 };
double diff_xyb_edge_dc[3] = { 0.0 };
ButteraugliBlockDiff(block0, block1,
diff_xyb_dc, diff_xyb_ac, diff_xyb_edge_dc);
for (int i = 0; i < 3; ++i) {
(*block_diff_dc)[3 * res_ix + i] = diff_xyb_dc[i];
(*block_diff_ac)[3 * res_ix + i] = diff_xyb_ac[i];
}
}
}
}
void ButteraugliComparator::EdgeDetectorMap(
const std::vector<std::vector<float> > &xyb0,
const std::vector<std::vector<float> > &xyb1,
std::vector<float>* edge_detector_map) {
PROFILER_FUNC;
static const double kSigma[3] = {
1.5,
0.586,
0.4,
};
std::vector<std::vector<float> > blurred0(xyb0);
std::vector<std::vector<float> > blurred1(xyb1);
for (int i = 0; i < 3; i++) {
Blur(xsize_, ysize_, blurred0[i].data(), kSigma[i], 0.0);
Blur(xsize_, ysize_, blurred1[i].data(), kSigma[i], 0.0);
}
for (size_t res_y = 0; res_y + (8 - step_) < ysize_; res_y += step_) {
for (size_t res_x = 0; res_x + (8 - step_) < xsize_; res_x += step_) {
size_t res_ix = (res_y * res_xsize_ + res_x) / step_;
double diff_xyb[3] = { 0.0 };
Butteraugli8x8CornerEdgeDetectorDiff(std::min(res_x, xsize_ - 8),
std::min(res_y, ysize_ - 8),
xsize_, ysize_,
blurred0, blurred1,
diff_xyb);
for (int i = 0; i < 3; ++i) {
(*edge_detector_map)[3 * res_ix + i] = diff_xyb[i];
}
}
}
}
void ButteraugliComparator::EdgeDetectorLowFreq(
const std::vector<std::vector<float> > &xyb0,
const std::vector<std::vector<float> > &xyb1,
std::vector<float>* block_diff_ac) {
PROFILER_FUNC;
static const double kSigma = 14;
static const double kMul = 10;
std::vector<std::vector<float> > blurred0(xyb0);
std::vector<std::vector<float> > blurred1(xyb1);
for (int i = 0; i < 3; i++) {
Blur(xsize_, ysize_, blurred0[i].data(), kSigma, 0.0);
Blur(xsize_, ysize_, blurred1[i].data(), kSigma, 0.0);
}
const int step = 8;
for (int y = 0; y + step < (int)ysize_; y += step_) {
int resy = y / step_;
int resx = step / step_;
for (int x = 0; x + step < (int)xsize_; x += step_, resx++) {
const int ix = y * xsize_ + x;
const int res_ix = resy * res_xsize_ + resx;
double diff[4][3];
for (int i = 0; i < 3; ++i) {
int ix2 = ix + 8;
diff[0][i] =
((blurred1[i][ix] - blurred0[i][ix]) +
(blurred0[i][ix2] - blurred1[i][ix2]));
ix2 = ix + 8 * xsize_;
diff[1][i] =
((blurred1[i][ix] - blurred0[i][ix]) +
(blurred0[i][ix2] - blurred1[i][ix2]));
ix2 = ix + 6 * xsize_ + 6;
diff[2][i] =
((blurred1[i][ix] - blurred0[i][ix]) +
(blurred0[i][ix2] - blurred1[i][ix2]));
ix2 = ix + 6 * xsize_ - 6;
diff[3][i] = x < step ? 0 :
((blurred1[i][ix] - blurred0[i][ix]) +
(blurred0[i][ix2] - blurred1[i][ix2]));
}
double max_diff_xyb[3] = { 0 };
for (int k = 0; k < 4; ++k) {
double diff_xyb[3] = { 0 };
XybDiffLowFreqSquaredAccumulate(diff[k][0], diff[k][1], diff[k][2],
0, 0, 0, 1.0,
diff_xyb);
for (int i = 0; i < 3; ++i) {
max_diff_xyb[i] = std::max<double>(max_diff_xyb[i], diff_xyb[i]);
}
}
for (int i = 0; i < 3; ++i) {
(*block_diff_ac)[3 * res_ix + i] += kMul * max_diff_xyb[i];
}
}
}
}
void ButteraugliComparator::CombineChannels(
const std::vector<std::vector<float> >& mask_xyb,
const std::vector<std::vector<float> >& mask_xyb_dc,
const std::vector<float>& block_diff_dc,
const std::vector<float>& block_diff_ac,
const std::vector<float>& edge_detector_map,
std::vector<float>* result) {
PROFILER_FUNC;
result->resize(res_xsize_ * res_ysize_);
for (size_t res_y = 0; res_y + (8 - step_) < ysize_; res_y += step_) {
for (size_t res_x = 0; res_x + (8 - step_) < xsize_; res_x += step_) {
size_t res_ix = (res_y * res_xsize_ + res_x) / step_;
double mask[3];
double dc_mask[3];
for (int i = 0; i < 3; ++i) {
mask[i] = mask_xyb[i][(res_y + 3) * xsize_ + (res_x + 3)];
dc_mask[i] = mask_xyb_dc[i][(res_y + 3) * xsize_ + (res_x + 3)];
}
(*result)[res_ix] =
(DotProduct(&block_diff_dc[3 * res_ix], dc_mask) +
DotProduct(&block_diff_ac[3 * res_ix], mask) +
DotProduct(&edge_detector_map[3 * res_ix], mask));
}
}
}
double ButteraugliScoreFromDiffmap(const ImageF& diffmap) {
PROFILER_FUNC;
float retval = 0.0f;
for (size_t y = 0; y < diffmap.ysize(); ++y) {
ConstRestrict<const float *> row = diffmap.Row(y);
for (size_t x = 0; x < diffmap.xsize(); ++x) {
retval = std::max(retval, row[x]);
}
}
return retval;
}
static std::array<double, 512> MakeMask(
double extmul, double extoff,
double mul, double offset,
double scaler) {
std::array<double, 512> lut;
for (int i = 0; i < (int)lut.size(); ++i) {
const double c = mul / ((0.01 * scaler * i) + offset);
lut[i] = 1.0 + extmul * (c + extoff);
assert(lut[i] >= 0.0);
lut[i] *= lut[i];
}
return lut;
}
double MaskX(double delta) {
PROFILER_FUNC;
static const double extmul = 0.975741017749;
static const double extoff = -4.25328244168;
static const double offset = 0.454909521427;
static const double scaler = 0.0738288224836;
static const double mul = 20.8029176447;
static const std::array<double, 512> lut =
MakeMask(extmul, extoff, mul, offset, scaler);
return InterpolateClampNegative(lut.data(), lut.size(), delta);
}
double MaskY(double delta) {
PROFILER_FUNC;
static const double extmul = 0.373995618954;
static const double extoff = 1.5307267433;
static const double offset = 0.911952641929;
static const double scaler = 1.1731667845;
static const double mul = 16.2447033988;
static const std::array<double, 512> lut =
MakeMask(extmul, extoff, mul, offset, scaler);
return InterpolateClampNegative(lut.data(), lut.size(), delta);
}
double MaskB(double delta) {
PROFILER_FUNC;
static const double extmul = 0.61582234137;
static const double extoff = -4.25376118646;
static const double offset = 1.05105070921;
static const double scaler = 0.47434643535;
static const double mul = 31.1444967089;
static const std::array<double, 512> lut =
MakeMask(extmul, extoff, mul, offset, scaler);
return InterpolateClampNegative(lut.data(), lut.size(), delta);
}
double MaskDcX(double delta) {
PROFILER_FUNC;
static const double extmul = 1.79116943438;
static const double extoff = -3.86797479189;
static const double offset = 0.670960225853;
static const double scaler = 0.486575865525;
static const double mul = 20.4563479139;
static const std::array<double, 512> lut =
MakeMask(extmul, extoff, mul, offset, scaler);
return InterpolateClampNegative(lut.data(), lut.size(), delta);
}
double MaskDcY(double delta) {
PROFILER_FUNC;
static const double extmul = 0.212223514236;
static const double extoff = -3.65647120524;
static const double offset = 1.73396799447;
static const double scaler = 0.170392660501;
static const double mul = 21.6566724788;
static const std::array<double, 512> lut =
MakeMask(extmul, extoff, mul, offset, scaler);
return InterpolateClampNegative(lut.data(), lut.size(), delta);
}
double MaskDcB(double delta) {
PROFILER_FUNC;
static const double extmul = 0.349376011816;
static const double extoff = -0.894711072781;
static const double offset = 0.901647926679;
static const double scaler = 0.380086095024;
static const double mul = 18.0373825149;
static const std::array<double, 512> lut =
MakeMask(extmul, extoff, mul, offset, scaler);
return InterpolateClampNegative(lut.data(), lut.size(), delta);
}
// Replaces values[x + y * xsize] with the minimum of the values in the
// square_size square with coordinates
// x - offset .. x + square_size - offset - 1,
// y - offset .. y + square_size - offset - 1.
void MinSquareVal(size_t square_size, size_t offset,
size_t xsize, size_t ysize,
float *values) {
PROFILER_FUNC;
// offset is not negative and smaller than square_size.
assert(offset < square_size);
std::vector<float> tmp(xsize * ysize);
for (size_t y = 0; y < ysize; ++y) {
const size_t minh = offset > y ? 0 : y - offset;
const size_t maxh = std::min<size_t>(ysize, y + square_size - offset);
for (size_t x = 0; x < xsize; ++x) {
double min = values[x + minh * xsize];
for (size_t j = minh + 1; j < maxh; ++j) {
min = fmin(min, values[x + j * xsize]);
}
tmp[x + y * xsize] = min;
}
}
for (size_t x = 0; x < xsize; ++x) {
const size_t minw = offset > x ? 0 : x - offset;
const size_t maxw = std::min<size_t>(xsize, x + square_size - offset);
for (size_t y = 0; y < ysize; ++y) {
double min = tmp[minw + y * xsize];
for (size_t j = minw + 1; j < maxw; ++j) {
min = fmin(min, tmp[j + y * xsize]);
}
values[x + y * xsize] = min;
}
}
}
// ===== Functions used by Mask only =====
void Average5x5(int xsize, int ysize, std::vector<float>* diffs) {
PROFILER_FUNC;
if (xsize < 4 || ysize < 4) {
// TODO: Make this work for small dimensions as well.
return;
}
static const float w = 0.679144890667;
static const float scale = 1.0 / (5.0 + 4 * w);
std::vector<float> result = *diffs;
std::vector<float> tmp0 = *diffs;
std::vector<float> tmp1 = *diffs;
ScaleImage(w, &tmp1);
for (int y = 0; y < ysize; y++) {
const int row0 = y * xsize;
result[row0 + 1] += tmp0[row0];
result[row0 + 0] += tmp0[row0 + 1];
result[row0 + 2] += tmp0[row0 + 1];
for (int x = 2; x < xsize - 2; ++x) {
result[row0 + x - 1] += tmp0[row0 + x];
result[row0 + x + 1] += tmp0[row0 + x];
}
result[row0 + xsize - 3] += tmp0[row0 + xsize - 2];
result[row0 + xsize - 1] += tmp0[row0 + xsize - 2];
result[row0 + xsize - 2] += tmp0[row0 + xsize - 1];
if (y > 0) {
const int rowd1 = row0 - xsize;
result[rowd1 + 1] += tmp1[row0];
result[rowd1 + 0] += tmp0[row0];
for (int x = 1; x < xsize - 1; ++x) {
result[rowd1 + x + 1] += tmp1[row0 + x];
result[rowd1 + x + 0] += tmp0[row0 + x];
result[rowd1 + x - 1] += tmp1[row0 + x];
}
result[rowd1 + xsize - 1] += tmp0[row0 + xsize - 1];
result[rowd1 + xsize - 2] += tmp1[row0 + xsize - 1];
}
if (y + 1 < ysize) {
const int rowu1 = row0 + xsize;
result[rowu1 + 1] += tmp1[row0];
result[rowu1 + 0] += tmp0[row0];
for (int x = 1; x < xsize - 1; ++x) {
result[rowu1 + x + 1] += tmp1[row0 + x];
result[rowu1 + x + 0] += tmp0[row0 + x];
result[rowu1 + x - 1] += tmp1[row0 + x];
}
result[rowu1 + xsize - 1] += tmp0[row0 + xsize - 1];
result[rowu1 + xsize - 2] += tmp1[row0 + xsize - 1];
}
}
*diffs = result;
ScaleImage(scale, diffs);
}
void DiffPrecompute(
const std::vector<std::vector<float> > &xyb0,
const std::vector<std::vector<float> > &xyb1,
size_t xsize, size_t ysize,
std::vector<std::vector<float> > *mask) {
PROFILER_FUNC;
mask->resize(3, std::vector<float>(xyb0[0].size()));
double valsh0[3] = { 0.0 };
double valsv0[3] = { 0.0 };
double valsh1[3] = { 0.0 };
double valsv1[3] = { 0.0 };
int ix2;
for (size_t y = 0; y < ysize; ++y) {
for (size_t x = 0; x < xsize; ++x) {
size_t ix = x + xsize * y;
if (x + 1 < xsize) {
ix2 = ix + 1;
} else {
ix2 = ix - 1;
}
{
double x0 = (xyb0[0][ix] - xyb0[0][ix2]);
double y0 = (xyb0[1][ix] - xyb0[1][ix2]);
double z0 = (xyb0[2][ix] - xyb0[2][ix2]);
XybToVals(x0, y0, z0, &valsh0[0], &valsh0[1], &valsh0[2]);
double x1 = (xyb1[0][ix] - xyb1[0][ix2]);
double y1 = (xyb1[1][ix] - xyb1[1][ix2]);
double z1 = (xyb1[2][ix] - xyb1[2][ix2]);
XybToVals(x1, y1, z1, &valsh1[0], &valsh1[1], &valsh1[2]);
}
if (y + 1 < ysize) {
ix2 = ix + xsize;
} else {
ix2 = ix - xsize;
}
{
double x0 = (xyb0[0][ix] - xyb0[0][ix2]);
double y0 = (xyb0[1][ix] - xyb0[1][ix2]);
double z0 = (xyb0[2][ix] - xyb0[2][ix2]);
XybToVals(x0, y0, z0, &valsv0[0], &valsv0[1], &valsv0[2]);
double x1 = (xyb1[0][ix] - xyb1[0][ix2]);
double y1 = (xyb1[1][ix] - xyb1[1][ix2]);
double z1 = (xyb1[2][ix] - xyb1[2][ix2]);
XybToVals(x1, y1, z1, &valsv1[0], &valsv1[1], &valsv1[2]);
}
for (int i = 0; i < 3; ++i) {
double sup0 = fabs(valsh0[i]) + fabs(valsv0[i]);
double sup1 = fabs(valsh1[i]) + fabs(valsv1[i]);
double m = std::min(sup0, sup1);
(*mask)[i][ix] = m;
}
}
}
}
void Mask(const std::vector<std::vector<float> > &xyb0,
const std::vector<std::vector<float> > &xyb1,
size_t xsize, size_t ysize,
std::vector<std::vector<float> > *mask,
std::vector<std::vector<float> > *mask_dc) {
PROFILER_FUNC;
mask->resize(3);
mask_dc->resize(3);
for (int i = 0; i < 3; ++i) {
(*mask)[i].resize(xsize * ysize);
(*mask_dc)[i].resize(xsize * ysize);
}
DiffPrecompute(xyb0, xyb1, xsize, ysize, mask);
for (int i = 0; i < 3; ++i) {
Average5x5(xsize, ysize, &(*mask)[i]);
MinSquareVal(4, 0, xsize, ysize, (*mask)[i].data());
static const double sigma[3] = {
9.65781083553,
14.2644604355,
4.53358927369,
};
Blur(xsize, ysize, (*mask)[i].data(), sigma[i], 0.0);
}
static const double w00 = 232.206464018;
static const double w11 = 22.9455222245;
static const double w22 = 503.962310606;
for (size_t y = 0; y < ysize; ++y) {
for (size_t x = 0; x < xsize; ++x) {
const size_t idx = y * xsize + x;
const double s0 = (*mask)[0][idx];
const double s1 = (*mask)[1][idx];
const double s2 = (*mask)[2][idx];
const double p0 = w00 * s0;
const double p1 = w11 * s1;
const double p2 = w22 * s2;
(*mask)[0][idx] = MaskX(p0);
(*mask)[1][idx] = MaskY(p1);
(*mask)[2][idx] = MaskB(p2);
(*mask_dc)[0][idx] = MaskDcX(p0);
(*mask_dc)[1][idx] = MaskDcY(p1);
(*mask_dc)[2][idx] = MaskDcB(p2);
}
}
for (int i = 0; i < 3; ++i) {
ScaleImage(kGlobalScale * kGlobalScale, &(*mask)[i]);
ScaleImage(kGlobalScale * kGlobalScale, &(*mask_dc)[i]);
}
}
void ButteraugliDiffmap(const std::vector<ImageF> &rgb0_image,
const std::vector<ImageF> &rgb1_image,
ImageF &result_image) {
const size_t xsize = rgb0_image[0].xsize();
const size_t ysize = rgb0_image[0].ysize();
ButteraugliComparator butteraugli(xsize, ysize, 3);
butteraugli.Diffmap(rgb0_image, rgb1_image, result_image);
}
bool ButteraugliInterface(const std::vector<ImageF> &rgb0,
const std::vector<ImageF> &rgb1,
ImageF &diffmap,
double &diffvalue) {
const size_t xsize = rgb0[0].xsize();
const size_t ysize = rgb0[0].ysize();
if (xsize < 1 || ysize < 1) {
// Butteraugli values for small (where xsize or ysize is smaller
// than 8 pixels) images are non-sensical, but most likely it is
// less disruptive to try to compute something than just give up.
return false; // No image.
}
for (int i = 1; i < 3; i++) {
if (rgb0[i].xsize() != xsize || rgb0[i].ysize() != ysize ||
rgb1[i].xsize() != xsize || rgb1[i].ysize() != ysize) {
return false; // Image planes must have same dimensions.
}
}
if (xsize < 8 || ysize < 8) {
for (int y = 0; y < (int)ysize; ++y) {
for (int x = 0; x < (int)xsize; ++x) {
diffmap.Row(y)[x] = 0;
}
}
diffvalue = 0;
return true;
}
ButteraugliDiffmap(rgb0, rgb1, diffmap);
diffvalue = ButteraugliScoreFromDiffmap(diffmap);
return true;
}
bool ButteraugliAdaptiveQuantization(size_t xsize, size_t ysize,
const std::vector<std::vector<float> > &rgb, std::vector<float> &quant) {
if (xsize < 16 || ysize < 16) {
return false; // Butteraugli is undefined for small images.
}
size_t size = xsize * ysize;
std::vector<std::vector<float> > scale_xyb(3);
std::vector<std::vector<float> > scale_xyb_dc(3);
Mask(rgb, rgb, xsize, ysize, &scale_xyb, &scale_xyb_dc);
quant.resize(size);
// Mask gives us values in 3 color channels, but for now we take only
// the intensity channel.
for (size_t i = 0; i < size; i++) {
quant[i] = scale_xyb[1][i];
}
return true;
}
double ButteraugliFuzzyClass(double score) {
static const double fuzzy_width_up = 10.287189655;
static const double fuzzy_width_down = 6.97490803335;
static const double m0 = 2.0;
double fuzzy_width = score < 1.0 ? fuzzy_width_down : fuzzy_width_up;
return m0 / (1.0 + exp((score - 1.0) * fuzzy_width));
}
double ButteraugliFuzzyInverse(double seek) {
double pos = 0;
for (double range = 1.0; range >= 1e-10; range *= 0.5) {
double cur = ButteraugliFuzzyClass(pos);
if (cur < seek) {
pos -= range;
} else {
pos += range;
}
}
return pos;
}
} // namespace butteraugli
```
|
/content/code_sandbox/library/JQLibrary/src/JQGuetzli/butteraugli/butteraugli.cc
|
c++
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 17,738
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
The hash for ZopfliFindLongestMatch of lz77.c.
*/
#ifndef ZOPFLI_HASH_H_
#define ZOPFLI_HASH_H_
#include "util.h"
typedef struct ZopfliHash {
int* head; /* Hash value to index of its most recent occurrence. */
unsigned short* prev; /* Index to index of prev. occurrence of same hash. */
int* hashval; /* Index to hash value at this index. */
int val; /* Current hash value. */
#ifdef ZOPFLI_HASH_SAME_HASH
/* Fields with similar purpose as the above hash, but for the second hash with
a value that is calculated differently. */
int* head2; /* Hash value to index of its most recent occurrence. */
unsigned short* prev2; /* Index to index of prev. occurrence of same hash. */
int* hashval2; /* Index to hash value at this index. */
int val2; /* Current hash value. */
#endif
#ifdef ZOPFLI_HASH_SAME
unsigned short* same; /* Amount of repetitions of same byte after this .*/
#endif
} ZopfliHash;
/* Allocates ZopfliHash memory. */
void ZopfliAllocHash(size_t window_size, ZopfliHash* h);
/* Resets all fields of ZopfliHash. */
void ZopfliResetHash(size_t window_size, ZopfliHash* h);
/* Frees ZopfliHash memory. */
void ZopfliCleanHash(ZopfliHash* h);
/*
Updates the hash values based on the current position in the array. All calls
to this must be made for consecutive bytes.
*/
void ZopfliUpdateHash(const unsigned char* array, size_t pos, size_t end,
ZopfliHash* h);
/*
Prepopulates hash:
Fills in the initial values in the hash, before ZopfliUpdateHash can be used
correctly.
*/
void ZopfliWarmupHash(const unsigned char* array, size_t pos, size_t end,
ZopfliHash* h);
#endif /* ZOPFLI_HASH_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/hash.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 552
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#ifndef ZOPFLI_KATAJAINEN_H_
#define ZOPFLI_KATAJAINEN_H_
#include <string.h>
/*
Outputs minimum-redundancy length-limited code bitlengths for symbols with the
given counts. The bitlengths are limited by maxbits.
The output is tailored for DEFLATE: symbols that never occur, get a bit length
of 0, and if only a single symbol occurs at least once, its bitlength will be 1,
and not 0 as would theoretically be needed for a single symbol.
frequencies: The amount of occurrences of each symbol.
n: The amount of symbols.
maxbits: Maximum bit length, inclusive.
bitlengths: Output, the bitlengths for the symbol prefix codes.
return: 0 for OK, non-0 for error.
*/
int ZopfliLengthLimitedCodeLengths(
const size_t* frequencies, int n, int maxbits, unsigned* bitlengths);
#endif /* ZOPFLI_KATAJAINEN_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/katajainen.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 294
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Utilities for using the lz77 symbols of the deflate spec.
*/
#ifndef ZOPFLI_SYMBOLS_H_
#define ZOPFLI_SYMBOLS_H_
/* __has_builtin available in clang */
#ifdef __has_builtin
# if __has_builtin(__builtin_clz)
# define ZOPFLI_HAS_BUILTIN_CLZ
# endif
/* __builtin_clz available beginning with GCC 3.4 */
#elif __GNUC__ * 100 + __GNUC_MINOR__ >= 304
# define ZOPFLI_HAS_BUILTIN_CLZ
#endif
/* Gets the amount of extra bits for the given dist, cfr. the DEFLATE spec. */
int ZopfliGetDistExtraBits(int dist);
/* Gets value of the extra bits for the given dist, cfr. the DEFLATE spec. */
int ZopfliGetDistExtraBitsValue(int dist);
/* Gets the symbol for the given dist, cfr. the DEFLATE spec. */
int ZopfliGetDistSymbol(int dist);
/* Gets the amount of extra bits for the given length, cfr. the DEFLATE spec. */
int ZopfliGetLengthExtraBits(int l);
/* Gets value of the extra bits for the given length, cfr. the DEFLATE spec. */
int ZopfliGetLengthExtraBitsValue(int l);
/*
Gets the symbol for the given length, cfr. the DEFLATE spec.
Returns the symbol in the range [257-285] (inclusive)
*/
int ZopfliGetLengthSymbol(int l);
/* Gets the amount of extra bits for the given length symbol. */
int ZopfliGetLengthSymbolExtraBits(int s);
/* Gets the amount of extra bits for the given distance symbol. */
int ZopfliGetDistSymbolExtraBits(int s);
#endif /* ZOPFLI_SYMBOLS_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/symbols.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 467
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
The cache that speeds up ZopfliFindLongestMatch of lz77.c.
*/
#ifndef ZOPFLI_CACHE_H_
#define ZOPFLI_CACHE_H_
#include "util.h"
#ifdef ZOPFLI_LONGEST_MATCH_CACHE
/*
Cache used by ZopfliFindLongestMatch to remember previously found length/dist
values.
This is needed because the squeeze runs will ask these values multiple times for
the same position.
Uses large amounts of memory, since it has to remember the distance belonging
to every possible shorter-than-the-best length (the so called "sublen" array).
*/
typedef struct ZopfliLongestMatchCache {
unsigned short* length;
unsigned short* dist;
unsigned char* sublen;
} ZopfliLongestMatchCache;
/* Initializes the ZopfliLongestMatchCache. */
void ZopfliInitCache(size_t blocksize, ZopfliLongestMatchCache* lmc);
/* Frees up the memory of the ZopfliLongestMatchCache. */
void ZopfliCleanCache(ZopfliLongestMatchCache* lmc);
/* Stores sublen array in the cache. */
void ZopfliSublenToCache(const unsigned short* sublen,
size_t pos, size_t length,
ZopfliLongestMatchCache* lmc);
/* Extracts sublen array from the cache. */
void ZopfliCacheToSublen(const ZopfliLongestMatchCache* lmc,
size_t pos, size_t length,
unsigned short* sublen);
/* Returns the length up to which could be stored in the cache. */
unsigned ZopfliMaxCachedSublen(const ZopfliLongestMatchCache* lmc,
size_t pos, size_t length);
#endif /* ZOPFLI_LONGEST_MATCH_CACHE */
#endif /* ZOPFLI_CACHE_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/cache.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 479
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Functions to choose good boundaries for block splitting. Deflate allows encoding
the data in multiple blocks, with a separate Huffman tree for each block. The
Huffman tree itself requires some bytes to encode, so by choosing certain
blocks, you can either hurt, or enhance compression. These functions choose good
ones that enhance it.
*/
#ifndef ZOPFLI_BLOCKSPLITTER_H_
#define ZOPFLI_BLOCKSPLITTER_H_
#include <stdlib.h>
#include "lz77.h"
#include "zopfli.h"
/*
Does blocksplitting on LZ77 data.
The output splitpoints are indices in the LZ77 data.
maxblocks: set a limit to the amount of blocks. Set to 0 to mean no limit.
*/
void ZopfliBlockSplitLZ77(const ZopfliOptions* options,
const ZopfliLZ77Store* lz77, size_t maxblocks,
size_t** splitpoints, size_t* npoints);
/*
Does blocksplitting on uncompressed data.
The output splitpoints are indices in the uncompressed bytes.
options: general program options.
in: uncompressed input data
instart: where to start splitting
inend: where to end splitting (not inclusive)
maxblocks: maximum amount of blocks to split into, or 0 for no limit
splitpoints: dynamic array to put the resulting split point coordinates into.
The coordinates are indices in the input array.
npoints: pointer to amount of splitpoints, for the dynamic array. The amount of
blocks is the amount of splitpoitns + 1.
*/
void ZopfliBlockSplit(const ZopfliOptions* options,
const unsigned char* in, size_t instart, size_t inend,
size_t maxblocks, size_t** splitpoints, size_t* npoints);
/*
Divides the input into equal blocks, does not even take LZ77 lengths into
account.
*/
void ZopfliBlockSplitSimple(const unsigned char* in,
size_t instart, size_t inend,
size_t blocksize,
size_t** splitpoints, size_t* npoints);
#endif /* ZOPFLI_BLOCKSPLITTER_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/blocksplitter.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 533
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
The squeeze functions do enhanced LZ77 compression by optimal parsing with a
cost model, rather than greedily choosing the longest length or using a single
step of lazy matching like regular implementations.
Since the cost model is based on the Huffman tree that can only be calculated
after the LZ77 data is generated, there is a chicken and egg problem, and
multiple runs are done with updated cost models to converge to a better
solution.
*/
#ifndef ZOPFLI_SQUEEZE_H_
#define ZOPFLI_SQUEEZE_H_
#include "lz77.h"
/*
Calculates lit/len and dist pairs for given data.
If instart is larger than 0, it uses values before instart as starting
dictionary.
*/
void ZopfliLZ77Optimal(ZopfliBlockState *s,
const unsigned char* in, size_t instart, size_t inend,
int numiterations,
ZopfliLZ77Store* store);
/*
Does the same as ZopfliLZ77Optimal, but optimized for the fixed tree of the
deflate standard.
The fixed tree never gives the best compression. But this gives the best
possible LZ77 encoding possible with the fixed tree.
This does not create or output any fixed tree, only LZ77 data optimized for
using with a fixed tree.
If instart is larger than 0, it uses values before instart as starting
dictionary.
*/
void ZopfliLZ77OptimalFixed(ZopfliBlockState *s,
const unsigned char* in,
size_t instart, size_t inend,
ZopfliLZ77Store* store);
#endif /* ZOPFLI_SQUEEZE_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/squeeze.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 440
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#ifndef ZOPFLI_GZIP_H_
#define ZOPFLI_GZIP_H_
/*
Functions to compress according to the Gzip specification.
*/
#include "zopfli.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
Compresses according to the gzip specification and append the compressed
result to the output.
options: global program options
out: pointer to the dynamic output array to which the result is appended. Must
be freed after use.
outsize: pointer to the dynamic output array size.
*/
void ZopfliGzipCompress(const ZopfliOptions* options,
const unsigned char* in, size_t insize,
unsigned char** out, size_t* outsize);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* ZOPFLI_GZIP_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/gzip_container.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 250
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#ifndef ZOPFLI_ZOPFLI_H_
#define ZOPFLI_ZOPFLI_H_
#include <stddef.h>
#include <stdlib.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
/*
Options used throughout the program.
*/
typedef struct ZopfliOptions {
/* Whether to print output */
int verbose;
/* Whether to print more detailed output */
int verbose_more;
/*
Maximum amount of times to rerun forward and backward pass to optimize LZ77
compression cost. Good values: 10, 15 for small files, 5 for files over
several MB in size or it will be too slow.
*/
int numiterations;
/*
If true, splits the data in multiple deflate blocks with optimal choice
for the block boundaries. Block splitting gives better compression. Default:
true (1).
*/
int blocksplitting;
/*
No longer used, left for compatibility.
*/
int blocksplittinglast;
/*
Maximum amount of blocks to split into (0 for unlimited, but this can give
extreme results that hurt compression on some files). Default value: 15.
*/
int blocksplittingmax;
} ZopfliOptions;
/* Initializes options with default values. */
void ZopfliInitOptions(ZopfliOptions* options);
/* Output format */
typedef enum {
ZOPFLI_FORMAT_GZIP,
ZOPFLI_FORMAT_ZLIB,
ZOPFLI_FORMAT_DEFLATE
} ZopfliFormat;
/*
Compresses according to the given output format and appends the result to the
output.
options: global program options
output_type: the output format to use
out: pointer to the dynamic output array to which the result is appended. Must
be freed after use
outsize: pointer to the dynamic output array size
*/
void ZopfliCompress(const ZopfliOptions* options, ZopfliFormat output_type,
const unsigned char* in, size_t insize,
unsigned char** out, size_t* outsize);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* ZOPFLI_ZOPFLI_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/zopfli.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 549
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#ifndef ZOPFLI_DEFLATE_H_
#define ZOPFLI_DEFLATE_H_
/*
Functions to compress according to the DEFLATE specification, using the
"squeeze" LZ77 compression backend.
*/
#include "lz77.h"
#include "zopfli.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
Compresses according to the deflate specification and append the compressed
result to the output.
This function will usually output multiple deflate blocks. If final is 1, then
the final bit will be set on the last block.
options: global program options
btype: the deflate block type. Use 2 for best compression.
-0: non compressed blocks (00)
-1: blocks with fixed tree (01)
-2: blocks with dynamic tree (10)
final: whether this is the last section of the input, sets the final bit to the
last deflate block.
in: the input bytes
insize: number of input bytes
bp: bit pointer for the output array. This must initially be 0, and for
consecutive calls must be reused (it can have values from 0-7). This is
because deflate appends blocks as bit-based data, rather than on byte
boundaries.
out: pointer to the dynamic output array to which the result is appended. Must
be freed after use.
outsize: pointer to the dynamic output array size.
*/
void ZopfliDeflate(const ZopfliOptions* options, int btype, int final,
const unsigned char* in, size_t insize,
unsigned char* bp, unsigned char** out, size_t* outsize);
/*
Like ZopfliDeflate, but allows to specify start and end byte with instart and
inend. Only that part is compressed, but earlier bytes are still used for the
back window.
*/
void ZopfliDeflatePart(const ZopfliOptions* options, int btype, int final,
const unsigned char* in, size_t instart, size_t inend,
unsigned char* bp, unsigned char** out,
size_t* outsize);
/*
Calculates block size in bits.
litlens: lz77 lit/lengths
dists: ll77 distances
lstart: start of block
lend: end of block (not inclusive)
*/
double ZopfliCalculateBlockSize(const ZopfliLZ77Store* lz77,
size_t lstart, size_t lend, int btype);
/*
Calculates block size in bits, automatically using the best btype.
*/
double ZopfliCalculateBlockSizeAutoType(const ZopfliLZ77Store* lz77,
size_t lstart, size_t lend);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* ZOPFLI_DEFLATE_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/deflate.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 681
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#ifndef ZOPFLI_ZLIB_H_
#define ZOPFLI_ZLIB_H_
/*
Functions to compress according to the Zlib specification.
*/
#include "zopfli.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
Compresses according to the zlib specification and append the compressed
result to the output.
options: global program options
out: pointer to the dynamic output array to which the result is appended. Must
be freed after use.
outsize: pointer to the dynamic output array size.
*/
void ZopfliZlibCompress(const ZopfliOptions* options,
const unsigned char* in, size_t insize,
unsigned char** out, size_t* outsize);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* ZOPFLI_ZLIB_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/zlib_container.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 250
|
```objective-c
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Utilities for creating and using Huffman trees.
*/
#ifndef ZOPFLI_TREE_H_
#define ZOPFLI_TREE_H_
#include <string.h>
/*
Calculates the bitlengths for the Huffman tree, based on the counts of each
symbol.
*/
void ZopfliCalculateBitLengths(const size_t* count, size_t n, int maxbits,
unsigned *bitlengths);
/*
Converts a series of Huffman tree bitlengths, to the bit values of the symbols.
*/
void ZopfliLengthsToSymbols(const unsigned* lengths, size_t n, unsigned maxbits,
unsigned* symbols);
/*
Calculates the entropy of each symbol, based on the counts of each symbol. The
result is similar to the result of ZopfliCalculateBitLengths, but with the
actual theoritical bit lengths according to the entropy. Since the resulting
values are fractional, they cannot be used to encode the tree specified by
DEFLATE.
*/
void ZopfliCalculateEntropy(const size_t* count, size_t n, double* bitlengths);
#endif /* ZOPFLI_TREE_H_ */
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopfli/tree.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 312
|
```objective-c
//
//
// path_to_url
//
// Unless required by applicable law or agreed to in writing, software
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// Author: lode.vandevenne@gmail.com (Lode Vandevenne)
// Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
// Library to recompress and optimize PNG images. Uses Zopfli as the compression
// backend, chooses optimal PNG color model, and tries out several PNG filter
// strategies.
#ifndef ZOPFLIPNG_LIB_H_
#define ZOPFLIPNG_LIB_H_
#ifdef __cplusplus
#include <string>
#include <vector>
extern "C" {
#endif
#include <stdlib.h>
enum ZopfliPNGFilterStrategy {
kStrategyZero = 0,
kStrategyOne = 1,
kStrategyTwo = 2,
kStrategyThree = 3,
kStrategyFour = 4,
kStrategyMinSum,
kStrategyEntropy,
kStrategyPredefined,
kStrategyBruteForce,
kNumFilterStrategies /* Not a strategy but used for the size of this enum */
};
typedef struct CZopfliPNGOptions {
int lossy_transparent;
int lossy_8bit;
enum ZopfliPNGFilterStrategy* filter_strategies;
// How many strategies to try.
int num_filter_strategies;
int auto_filter_strategy;
char** keepchunks;
// How many entries in keepchunks.
int num_keepchunks;
int use_zopfli;
int num_iterations;
int num_iterations_large;
int block_split_strategy;
} CZopfliPNGOptions;
// Sets the default options
// Does not allocate or set keepchunks or filter_strategies
void CZopfliPNGSetDefaults(CZopfliPNGOptions *png_options);
// Returns 0 on success, error code otherwise
// The caller must free resultpng after use
int CZopfliPNGOptimize(const unsigned char* origpng,
const size_t origpng_size,
const CZopfliPNGOptions* png_options,
int verbose,
unsigned char** resultpng,
size_t* resultpng_size);
#ifdef __cplusplus
} // extern "C"
#endif
// C++ API
#ifdef __cplusplus
struct ZopfliPNGOptions {
ZopfliPNGOptions();
bool verbose;
// Allow altering hidden colors of fully transparent pixels
bool lossy_transparent;
// Convert 16-bit per channel images to 8-bit per channel
bool lossy_8bit;
// Filter strategies to try
std::vector<ZopfliPNGFilterStrategy> filter_strategies;
// Automatically choose filter strategy using less good compression
bool auto_filter_strategy;
// PNG chunks to keep
// chunks to literally copy over from the original PNG to the resulting one
std::vector<std::string> keepchunks;
// Use Zopfli deflate compression
bool use_zopfli;
// Zopfli number of iterations
int num_iterations;
// Zopfli number of iterations on large images
int num_iterations_large;
// Unused, left for backwards compatiblity.
int block_split_strategy;
};
// Returns 0 on success, error code otherwise.
// If verbose is true, it will print some info while working.
int ZopfliPNGOptimize(const std::vector<unsigned char>& origpng,
const ZopfliPNGOptions& png_options,
bool verbose,
std::vector<unsigned char>* resultpng);
#endif // __cplusplus
#endif // ZOPFLIPNG_LIB_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopflipng/zopflipng_lib.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 795
|
```objective-c
/*
LodePNG Utils
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.
*/
/*
Extra C++ utilities for LodePNG, for convenience.
*/
#include <string>
#include <vector>
#include "lodepng.h"
#pragma once
namespace lodepng
{
/*
Returns info from the header of the PNG by value, purely for convenience.
Does NOT check for errors. Returns bogus info if the PNG has an error.
Does not require cleanup of allocated memory because no palette or text chunk
info is in the LodePNGInfo object after checking only the header of the PNG.
*/
LodePNGInfo getPNGHeaderInfo(const std::vector<unsigned char>& png);
/*
Get the names and sizes of all chunks in the PNG file.
Returns 0 if ok, non-0 if error happened.
*/
unsigned getChunkInfo(std::vector<std::string>& names, std::vector<size_t>& sizes,
const std::vector<unsigned char>& png);
/*
Returns the names and full chunks (including the name and everything else that
makes up the chunk) for all chunks except IHDR, PLTE, IDAT and IEND.
It separates the chunks into 3 separate lists, representing the chunks between
certain critical chunks: 0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND
Returns 0 if ok, non-0 if error happened.
*/
unsigned getChunks(std::vector<std::string> names[3],
std::vector<std::vector<unsigned char> > chunks[3],
const std::vector<unsigned char>& png);
/*
Inserts chunks into the given png file. The chunks must be fully encoded,
including length, type, content and CRC.
The array index determines where it goes:
0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND.
They're appended at the end of those locations within the PNG.
Returns 0 if ok, non-0 if error happened.
*/
unsigned insertChunks(std::vector<unsigned char>& png,
const std::vector<std::vector<unsigned char> > chunks[3]);
/*
Get the filtertypes of each scanline in this PNG file.
Returns 0 if ok, 1 if PNG decoding error happened.
For a non-interlaced PNG, it returns one filtertype per scanline, in order.
For interlaced PNGs, it returns a result as if it's not interlaced. It returns
one filtertype per scanline, in order. The values match pass 6 and 7 of the
Adam7 interlacing, alternating between the two, so that the values correspond
the most to their scanlines.
*/
unsigned getFilterTypes(std::vector<unsigned char>& filterTypes, const std::vector<unsigned char>& png);
/*
Get the filtertypes of each scanline in every interlace pass this PNG file.
Returns 0 if ok, 1 if PNG decoding error happened.
For a non-interlaced PNG, it returns one filtertype per scanline, in order, in
a single std::vector in filterTypes.
For an interlaced PNG, it returns 7 std::vectors in filterTypes, one for each
Adam7 pass. The amount of values per pass can be calculated as follows, where
w and h are the size of the image and all divisions are integer divisions:
pass 1: (h + 7) / 8
pass 2: w <= 4 ? 0 : (h + 7) / 8
pass 3: h <= 4 ? 0 : (h + 7) / 8
pass 4: w <= 2 ? 0 : (h + 3) / 4
pass 5: h <= 2 ? 0 : (h + 3) / 4
pass 6: w <= 1 ? 0 : (h + 1) / 2
pass 7: h <= 1 ? 0 : (h + 1) / 2
*/
unsigned getFilterTypesInterlaced(std::vector<std::vector<unsigned char> >& filterTypes,
const std::vector<unsigned char>& png);
/*
Returns the value of the i-th pixel in an image with 1, 2, 4 or 8-bit color.
E.g. if bits is 4 and i is 5, it returns the 5th nibble (4-bit group), which
is the second half of the 3th byte, in big endian (PNG's endian order).
*/
int getPaletteValue(const unsigned char* data, size_t i, int bits);
/*
The information for extractZlibInfo.
*/
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
// only filled in for block type 2
size_t treebits; //encoded tree size in bits
int hlit; //the HLIT value that was filled in for this tree
int hdist; //the HDIST value that was filled in for this tree
int hclen; //the HCLEN value that was filled in for this tree
std::vector<int> clcl; //19 code length code lengths (compressed tree's tree)
std::vector<int> treecodes; //N tree codes, with values 0-18. Values 17 or 18 are followed by the repetition value.
std::vector<int> litlenlengths; //288 code lengths for lit/len symbols
std::vector<int> distlengths; //32 code lengths for dist symbols
// only filled in for block types 1 or 2
std::vector<int> lz77_lcode; //LZ77 codes. 0-255: literals. 256: end symbol. 257-285: length code of length/dist pairs
// the next vectors have the same size as lz77_lcode, but an element only has meaningful value if lz77_lcode contains a length code.
std::vector<int> lz77_dcode;
std::vector<int> lz77_lbits;
std::vector<int> lz77_dbits;
std::vector<int> lz77_lvalue;
std::vector<int> lz77_dvalue;
size_t numlit; //number of lit codes in this block
size_t numlen; //number of len codes in this block
};
//Extracts all info needed from a PNG file to reconstruct the zlib compression exactly.
void extractZlibInfo(std::vector<ZlibBlockInfo>& zlibinfo, const std::vector<unsigned char>& in);
} // namespace lodepng
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopflipng/lodepng/lodepng_util.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,600
|
```objective-c
/*
This file is part of JQLibrary
Contact email: 188080501@qq.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JQGUETZLI_H_
#define JQGUETZLI_H_
// Qt lib import
#include <QString>
namespace JQGuetzli
{
struct ProcessResult
{
bool processSucceed = false;
int originalSize = 0;
int resultSize = 0;
qreal compressionRatio = 0.0;
int timeConsuming = 0;
};
ProcessResult process(const QString &inputImageFilePath, const QString &outputImageFilePath);
}
#endif//JQGUETZLI_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/JQGuetzli.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 356
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Data structures that represent the contents of a jpeg file.
#ifndef GUETZLI_JPEG_DATA_H_
#define GUETZLI_JPEG_DATA_H_
#include <stddef.h>
#include <stdint.h>
#include <string>
#include <vector>
#include "guetzli/jpeg_error.h"
namespace guetzli {
static const int kDCTBlockSize = 64;
static const int kMaxComponents = 4;
static const int kMaxQuantTables = 4;
static const int kMaxHuffmanTables = 4;
static const int kJpegHuffmanMaxBitLength = 16;
static const int kJpegHuffmanAlphabetSize = 256;
static const int kJpegDCAlphabetSize = 12;
static const int kMaxDHTMarkers = 512;
static const uint8_t kDefaultQuantMatrix[2][64] = {
{ 16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99 },
{ 17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99 }
};
const int kJPEGNaturalOrder[80] = {
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63,
// extra entries for safety in decoder
63, 63, 63, 63, 63, 63, 63, 63,
63, 63, 63, 63, 63, 63, 63, 63
};
const int kJPEGZigZagOrder[64] = {
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63
};
// Quantization values for an 8x8 pixel block.
struct JPEGQuantTable {
JPEGQuantTable() : values(kDCTBlockSize), precision(0),
index(0), is_last(true) {}
std::vector<int> values;
int precision;
// The index of this quantization table as it was parsed from the input JPEG.
// Each DQT marker segment contains an 'index' field, and we save this index
// here. Valid values are 0 to 3.
int index;
// Set to true if this table is the last one within its marker segment.
bool is_last;
};
// Huffman code and decoding lookup table used for DC and AC coefficients.
struct JPEGHuffmanCode {
JPEGHuffmanCode() : counts(kJpegHuffmanMaxBitLength + 1),
values(kJpegHuffmanAlphabetSize + 1),
slot_id(0),
is_last(true) {}
// Bit length histogram.
std::vector<int> counts;
// Symbol values sorted by increasing bit lengths.
std::vector<int> values;
// The index of the Huffman code in the current set of Huffman codes. For AC
// component Huffman codes, 0x10 is added to the index.
int slot_id;
// Set to true if this Huffman code is the last one within its marker segment.
bool is_last;
};
// Huffman table indexes used for one component of one scan.
struct JPEGComponentScanInfo {
int comp_idx;
int dc_tbl_idx;
int ac_tbl_idx;
};
// Contains information that is used in one scan.
struct JPEGScanInfo {
// Parameters used for progressive scans (named the same way as in the spec):
// Ss : Start of spectral band in zig-zag sequence.
// Se : End of spectral band in zig-zag sequence.
// Ah : Successive approximation bit position, high.
// Al : Successive approximation bit position, low.
int Ss;
int Se;
int Ah;
int Al;
std::vector<JPEGComponentScanInfo> components;
};
typedef int16_t coeff_t;
// Represents one component of a jpeg file.
struct JPEGComponent {
JPEGComponent() : id(0),
h_samp_factor(1),
v_samp_factor(1),
quant_idx(0),
width_in_blocks(0),
height_in_blocks(0) {}
// One-byte id of the component.
int id;
// Horizontal and vertical sampling factors.
// In interleaved mode, each minimal coded unit (MCU) has
// h_samp_factor x v_samp_factor DCT blocks from this component.
int h_samp_factor;
int v_samp_factor;
// The index of the quantization table used for this component.
int quant_idx;
// The dimensions of the component measured in 8x8 blocks.
int width_in_blocks;
int height_in_blocks;
int num_blocks;
// The DCT coefficients of this component, laid out block-by-block, divided
// through the quantization matrix values.
std::vector<coeff_t> coeffs;
};
// Represents a parsed jpeg file.
struct JPEGData {
JPEGData() : width(0),
height(0),
version(0),
max_h_samp_factor(1),
max_v_samp_factor(1),
MCU_rows(0),
MCU_cols(0),
restart_interval(0),
original_jpg(NULL),
original_jpg_size(0),
error(JPEG_OK) {}
bool Is420() const;
bool Is444() const;
int width;
int height;
int version;
int max_h_samp_factor;
int max_v_samp_factor;
int MCU_rows;
int MCU_cols;
int restart_interval;
std::vector<std::string> app_data;
std::vector<std::string> com_data;
std::vector<JPEGQuantTable> quant;
std::vector<JPEGHuffmanCode> huffman_code;
std::vector<JPEGComponent> components;
std::vector<JPEGScanInfo> scan_info;
std::vector<uint8_t> marker_order;
std::vector<std::string> inter_marker_data;
std::string tail_data;
const uint8_t* original_jpg;
size_t original_jpg_size;
JPEGReadError error;
};
void InitJPEGDataForYUV444(int w, int h, JPEGData* jpg);
void SaveQuantTables(const int q[3][kDCTBlockSize], JPEGData* jpg);
} // namespace guetzli
#endif // GUETZLI_JPEG_DATA_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/jpeg_data.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 2,228
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_DEBUG_PRINT_H_
#define GUETZLI_DEBUG_PRINT_H_
#include "guetzli/stats.h"
namespace guetzli {
void PrintDebug(ProcessStats* stats, std::string s);
} // namespace guetzli
#define GUETZLI_LOG(stats, ...) \
do { \
char debug_string[1024]; \
snprintf(debug_string, sizeof(debug_string), __VA_ARGS__); \
debug_string[sizeof(debug_string) - 1] = '\0'; \
::guetzli::PrintDebug( \
stats, std::string(debug_string)); \
} while (0)
#define GUETZLI_LOG_QUANT(stats, q) \
for (int y = 0; y < 8; ++y) { \
for (int c = 0; c < 3; ++c) { \
for (int x = 0; x < 8; ++x) \
GUETZLI_LOG(stats, " %2d", (q)[c][8 * y + x]); \
GUETZLI_LOG(stats, " "); \
} \
GUETZLI_LOG(stats, "\n"); \
}
#endif // GUETZLI_DEBUG_PRINT_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/debug_print.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 318
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_QUALITY_H_
#define GUETZLI_QUALITY_H_
namespace guetzli {
double ButteraugliScoreForQuality(double quality);
} // namespace guetzli
#endif // GUETZLI_QUALITY_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/quality.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 91
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_PROCESSOR_H_
#define GUETZLI_PROCESSOR_H_
#include <string>
#include <vector>
#include "guetzli/comparator.h"
#include "guetzli/jpeg_data.h"
#include "guetzli/stats.h"
namespace guetzli {
struct Params {
float butteraugli_target = 1.0;
bool clear_metadata = false;
bool try_420 = false;
bool force_420 = false;
bool use_silver_screen = false;
int zeroing_greedy_lookahead = 3;
bool new_zeroing_model = true;
};
bool Process(const Params& params, ProcessStats* stats,
const std::string& in_data,
std::string* out_data);
struct GuetzliOutput {
std::string jpeg_data;
std::vector<float> distmap;
double distmap_aggregate;
double score;
};
bool ProcessJpegData(const Params& params, const JPEGData& jpg_in,
Comparator* comparator, GuetzliOutput* out,
ProcessStats* stats);
// Sets *out to a jpeg encoded string that will decode to an image that is
// visually indistinguishable from the input rgb image.
bool Process(const Params& params, ProcessStats* stats,
const std::vector<uint8_t>& rgb, int w, int h,
std::string* out);
} // namespace guetzli
#endif // GUETZLI_PROCESSOR_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/processor.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 348
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_FDCT_H_
#define GUETZLI_FDCT_H_
#include "guetzli/jpeg_data.h"
namespace guetzli {
// Computes the DCT (Discrete Cosine Transform) of the 8x8 array in 'block',
// scaled up by a factor of 16. The values in 'block' are laid out row-by-row
// and the result is written to the same memory area.
void ComputeBlockDCT(coeff_t* block);
} // namespace guetzli
#endif // GUETZLI_FDCT_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/fdct.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 158
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_JPEG_BIT_WRITER_H_
#define GUETZLI_JPEG_BIT_WRITER_H_
#include <stdint.h>
#include <memory>
namespace guetzli {
// Returns non-zero if and only if x has a zero byte, i.e. one of
// x & 0xff, x & 0xff00, ..., x & 0xff00000000000000 is zero.
inline uint64_t HasZeroByte(uint64_t x) {
return (x - 0x0101010101010101ULL) & ~x & 0x8080808080808080ULL;
}
// Handles the packing of bits into output bytes.
struct BitWriter {
explicit BitWriter(size_t length) : len(length),
data(new uint8_t[len]),
pos(0),
put_buffer(0),
put_bits(64),
overflow(false) {}
void WriteBits(int nbits, uint64_t bits) {
put_bits -= nbits;
put_buffer |= (bits << put_bits);
if (put_bits <= 16) {
// At this point we are ready to emit the most significant 6 bytes of
// put_buffer_ to the output.
// The JPEG format requires that after every 0xff byte in the entropy
// coded section, there is a zero byte, therefore we first check if any of
// the 6 most significant bytes of put_buffer_ is 0xff.
if (HasZeroByte(~put_buffer | 0xffff)) {
// We have a 0xff byte somewhere, examine each byte and append a zero
// byte if necessary.
EmitByte((put_buffer >> 56) & 0xff);
EmitByte((put_buffer >> 48) & 0xff);
EmitByte((put_buffer >> 40) & 0xff);
EmitByte((put_buffer >> 32) & 0xff);
EmitByte((put_buffer >> 24) & 0xff);
EmitByte((put_buffer >> 16) & 0xff);
} else if (pos + 6 < (int)len) {
// We don't have any 0xff bytes, output all 6 bytes without checking.
data[pos] = (put_buffer >> 56) & 0xff;
data[pos + 1] = (put_buffer >> 48) & 0xff;
data[pos + 2] = (put_buffer >> 40) & 0xff;
data[pos + 3] = (put_buffer >> 32) & 0xff;
data[pos + 4] = (put_buffer >> 24) & 0xff;
data[pos + 5] = (put_buffer >> 16) & 0xff;
pos += 6;
} else {
overflow = true;
}
put_buffer <<= 48;
put_bits += 48;
}
}
// Writes the given byte to the output, writes an extra zero if byte is 0xff.
void EmitByte(int byte) {
if (pos < (int)len) {
data[pos++] = byte;
} else {
overflow = true;
}
if (byte == 0xff) {
EmitByte(0);
}
}
void JumpToByteBoundary() {
while (put_bits <= 56) {
int c = (put_buffer >> 56) & 0xff;
EmitByte(c);
put_buffer <<= 8;
put_bits += 8;
}
if (put_bits < 64) {
int padmask = 0xff >> (64 - put_bits);
int c = ((put_buffer >> 56) & ~padmask) | padmask;
EmitByte(c);
}
put_buffer = 0;
put_bits = 64;
}
size_t len;
std::unique_ptr<uint8_t[]> data;
int pos;
uint64_t put_buffer;
int put_bits;
bool overflow;
};
} // namespace guetzli
#endif // GUETZLI_JPEG_BIT_WRITER_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/jpeg_bit_writer.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 925
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_BUTTERAUGLI_COMPARATOR_H_
#define GUETZLI_BUTTERAUGLI_COMPARATOR_H_
#include <vector>
#include "butteraugli/butteraugli.h"
#include "guetzli/comparator.h"
#include "guetzli/jpeg_data.h"
#include "guetzli/output_image.h"
#include "guetzli/stats.h"
namespace guetzli {
constexpr int kButteraugliStep = 3;
class ButteraugliComparator : public Comparator {
public:
ButteraugliComparator(const int width, const int height,
const std::vector<uint8_t>& rgb,
const float target_distance, ProcessStats* stats);
void Compare(const OutputImage& img) override;
double CompareBlock(const OutputImage& img,
int block_x, int block_y) const override;
double ScoreOutputSize(int size) const override;
bool DistanceOK(double target_mul) const override {
return distance_ <= target_mul * target_distance_;
}
const std::vector<float> distmap() const override { return distmap_; }
float distmap_aggregate() const override { return distance_; }
float BlockErrorLimit() const override;
void ComputeBlockErrorAdjustmentWeights(
int direction, int max_block_dist, double target_mul, int factor_x,
int factor_y, const std::vector<float>& distmap,
std::vector<float>* block_weight) override;
private:
const int width_;
const int height_;
const float target_distance_;
std::vector<::butteraugli::ImageF> rgb_linear_pregamma_;
std::vector<std::vector<float>> mask_xyz_;
std::vector<std::vector<std::vector<float>>> per_block_pregamma_;
::butteraugli::ButteraugliComparator comparator_;
float distance_;
std::vector<float> distmap_;
ProcessStats* stats_;
};
} // namespace guetzli
#endif // GUETZLI_BUTTERAUGLI_COMPARATOR_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/butteraugli_comparator.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 472
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Definition of error codes for parsing jpeg files.
#ifndef GUETZLI_JPEG_ERROR_H_
#define GUETZLI_JPEG_ERROR_H_
namespace guetzli {
enum JPEGReadError {
JPEG_OK = 0,
JPEG_SOI_NOT_FOUND,
JPEG_SOF_NOT_FOUND,
JPEG_UNEXPECTED_EOF,
JPEG_MARKER_BYTE_NOT_FOUND,
JPEG_UNSUPPORTED_MARKER,
JPEG_WRONG_MARKER_SIZE,
JPEG_INVALID_PRECISION,
JPEG_INVALID_WIDTH,
JPEG_INVALID_HEIGHT,
JPEG_INVALID_NUMCOMP,
JPEG_INVALID_SAMP_FACTOR,
JPEG_INVALID_START_OF_SCAN,
JPEG_INVALID_END_OF_SCAN,
JPEG_INVALID_SCAN_BIT_POSITION,
JPEG_INVALID_COMPS_IN_SCAN,
JPEG_INVALID_HUFFMAN_INDEX,
JPEG_INVALID_QUANT_TBL_INDEX,
JPEG_INVALID_QUANT_VAL,
JPEG_INVALID_MARKER_LEN,
JPEG_INVALID_SAMPLING_FACTORS,
JPEG_INVALID_HUFFMAN_CODE,
JPEG_INVALID_SYMBOL,
JPEG_NON_REPRESENTABLE_DC_COEFF,
JPEG_NON_REPRESENTABLE_AC_COEFF,
JPEG_INVALID_SCAN,
JPEG_OVERLAPPING_SCANS,
JPEG_INVALID_SCAN_ORDER,
JPEG_EXTRA_ZERO_RUN,
JPEG_DUPLICATE_DRI,
JPEG_DUPLICATE_SOF,
JPEG_WRONG_RESTART_MARKER,
JPEG_DUPLICATE_COMPONENT_ID,
JPEG_COMPONENT_NOT_FOUND,
JPEG_HUFFMAN_TABLE_NOT_FOUND,
JPEG_HUFFMAN_TABLE_ERROR,
JPEG_QUANT_TABLE_NOT_FOUND,
JPEG_EMPTY_DHT,
JPEG_EMPTY_DQT,
JPEG_OUT_OF_BAND_COEFF,
JPEG_EOB_RUN_TOO_LONG,
JPEG_IMAGE_TOO_LARGE,
};
} // namespace guetzli
#endif // GUETZLI_JPEG_ERROR_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/jpeg_error.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 391
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_IDCT_H_
#define GUETZLI_IDCT_H_
#include "guetzli/jpeg_data.h"
namespace guetzli {
// Fills in 'result' with the inverse DCT of 'block'.
// The arguments 'block' and 'result' point to 8x8 arrays that are arranged in
// a row-by-row memory layout.
void ComputeBlockIDCT(const coeff_t* block, uint8_t* result);
} // namespace guetzli
#endif // GUETZLI_IDCT_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/idct.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 153
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_OUTPUT_IMAGE_H_
#define GUETZLI_OUTPUT_IMAGE_H_
#include <stdint.h>
#include <vector>
#include "guetzli/jpeg_data.h"
namespace guetzli {
class OutputImageComponent {
public:
OutputImageComponent(int w, int h);
void Reset(int factor_x, int factor_y);
int width() const { return width_; }
int height() const { return height_; }
int factor_x() const { return factor_x_; }
int factor_y() const { return factor_y_; }
int width_in_blocks() const { return width_in_blocks_; }
int height_in_blocks() const { return height_in_blocks_; }
const coeff_t* coeffs() const { return &coeffs_[0]; }
const int* quant() const { return &quant_[0]; }
bool IsAllZero() const;
// Fills in block[] with the 8x8 coefficient block with block coordinates
// (block_x, block_y).
// NOTE: If the component is 2x2 subsampled, this corresponds to the 16x16
// pixel area with upper-left corner (16 * block_x, 16 * block_y).
void GetCoeffBlock(int block_x, int block_y,
coeff_t block[kDCTBlockSize]) const;
// Fills in out[] array with the 8-bit pixel view of this component cropped
// to the specified window. The window's upper-left corner, (xmin, ymin) must
// be within the image, but the window may extend past the image. In that
// case the edge pixels are duplicated.
void ToPixels(int xmin, int ymin, int xsize, int ysize,
uint8_t* out, int stride) const;
// Fills in out[] array with the floating-point precision pixel view of the
// component.
// REQUIRES: factor_x() == 1 and factor_y() == 1.
void ToFloatPixels(float* out, int stride) const;
// Sets the 8x8 coefficient block with block coordinates (block_x, block_y)
// to block[].
// NOTE: If the component is 2x2 subsampled, this corresponds to the 16x16
// pixel area with upper-left corner (16 * block_x, 16 * block_y).
// REQUIRES: block[k] % quant()[k] == 0 for each coefficient index k.
void SetCoeffBlock(int block_x, int block_y,
const coeff_t block[kDCTBlockSize]);
// Requires that comp is not downsampled.
void CopyFromJpegComponent(const JPEGComponent& comp,
int factor_x, int factor_y,
const int* quant);
void ApplyGlobalQuantization(const int q[kDCTBlockSize]);
private:
void UpdatePixelsForBlock(int block_x, int block_y,
const uint8_t idct[kDCTBlockSize]);
const int width_;
const int height_;
int factor_x_;
int factor_y_;
int width_in_blocks_;
int height_in_blocks_;
int num_blocks_;
std::vector<coeff_t> coeffs_;
std::vector<uint16_t> pixels_;
// Same as last argument of ApplyGlobalQuantization() (default is all 1s).
int quant_[kDCTBlockSize];
};
class OutputImage {
public:
OutputImage(int w, int h);
int width() const { return width_; }
int height() const { return height_; }
OutputImageComponent& component(int c) { return components_[c]; }
const OutputImageComponent& component(int c) const { return components_[c]; }
// Requires that jpg is in YUV444 format.
void CopyFromJpegData(const JPEGData& jpg);
void ApplyGlobalQuantization(const int q[3][kDCTBlockSize]);
// If sharpen or blur are enabled, preprocesses image before downsampling U or
// V to improve butteraugli score and/or reduce file size.
// u_sharpen: sharpen the u channel in red areas to improve score (not as
// effective as v_sharpen, blue is not so important)
// u_blur: blur the u channel in some areas to reduce file size
// v_sharpen: sharpen the v channel in red areas to improve score
// v_blur: blur the v channel in some areas to reduce file size
struct DownsampleConfig {
// Default is YUV420.
DownsampleConfig() : u_factor_x(2), u_factor_y(2),
v_factor_x(2), v_factor_y(2),
u_sharpen(true), u_blur(true),
v_sharpen(true), v_blur(true),
use_silver_screen(false) {}
int u_factor_x;
int u_factor_y;
int v_factor_x;
int v_factor_y;
bool u_sharpen;
bool u_blur;
bool v_sharpen;
bool v_blur;
bool use_silver_screen;
};
void Downsample(const DownsampleConfig& cfg);
void SaveToJpegData(JPEGData* jpg) const;
std::vector<uint8_t> ToSRGB() const;
std::vector<uint8_t> ToSRGB(int xmin, int ymin, int xsize, int ysize) const;
void ToLinearRGB(std::vector<std::vector<float> >* rgb) const;
void ToLinearRGB(int xmin, int ymin, int xsize, int ysize,
std::vector<std::vector<float> >* rgb) const;
std::string FrameTypeStr() const;
private:
const int width_;
const int height_;
std::vector<OutputImageComponent> components_;
};
} // namespace guetzli
#endif // GUETZLI_OUTPUT_IMAGE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/output_image.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,296
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Functions for reading a jpeg byte stream into a JPEGData object.
#ifndef GUETZLI_JPEG_DATA_READER_H_
#define GUETZLI_JPEG_DATA_READER_H_
#include <stddef.h>
#include <stdint.h>
#include <string>
#include "guetzli/jpeg_data.h"
namespace guetzli {
enum JpegReadMode {
JPEG_READ_HEADER, // only basic headers
JPEG_READ_TABLES, // headers and tables (quant, Huffman, ...)
JPEG_READ_ALL, // everything
};
// Parses the jpeg stream contained in data[*pos ... len) and fills in *jpg with
// the parsed information.
// If mode is JPEG_READ_HEADER, it fills in only the image dimensions in *jpg.
// Returns false if the data is not valid jpeg, or if it contains an unsupported
// jpeg feature.
bool ReadJpeg(const uint8_t* data, const size_t len, JpegReadMode mode,
JPEGData* jpg);
// string variant
bool ReadJpeg(const std::string& data, JpegReadMode mode,
JPEGData* jpg);
} // namespace guetzli
#endif // GUETZLI_JPEG_DATA_READER_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/jpeg_data_reader.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 292
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_STATS_H_
#define GUETZLI_STATS_H_
#include <cstdio>
#include <map>
#include <string>
#include <utility>
#include <vector>
namespace guetzli {
static const char* const kNumItersCnt = "number of iterations";
static const char* const kNumItersUpCnt = "number of iterations up";
static const char* const kNumItersDownCnt = "number of iterations down";
struct ProcessStats {
ProcessStats() {}
std::map<std::string, int> counters;
std::string* debug_output = nullptr;
FILE* debug_output_file = nullptr;
std::string filename;
};
} // namespace guetzli
#endif // GUETZLI_STATS_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/stats.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 198
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_JPEG_DATA_ENCODER_H_
#define GUETZLI_JPEG_DATA_ENCODER_H_
#include <stdint.h>
#include "guetzli/jpeg_data.h"
namespace guetzli {
// Adds APP0 header data.
void AddApp0Data(JPEGData* jpg);
// Creates a JPEG from the rgb pixel data. Returns true on success.
bool EncodeRGBToJpeg(const std::vector<uint8_t>& rgb, int w, int h,
JPEGData* jpg);
// Creates a JPEG from the rgb pixel data. Returns true on success. The given
// quantization table must have 3 * kDCTBlockSize values.
bool EncodeRGBToJpeg(const std::vector<uint8_t>& rgb, int w, int h,
const int* quant, JPEGData* jpg);
} // namespace guetzli
#endif // GUETZLI_JPEG_DATA_ENCODER_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/jpeg_data_encoder.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 231
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Functions for writing a JPEGData object into a jpeg byte stream.
#ifndef GUETZLI_JPEG_DATA_WRITER_H_
#define GUETZLI_JPEG_DATA_WRITER_H_
#include <stdint.h>
#include <string.h>
#include <vector>
#include "guetzli/jpeg_data.h"
namespace guetzli {
// Function pointer type used to write len bytes into buf. Returns the
// number of bytes written or -1 on error.
typedef int (*JPEGOutputHook)(void* data, const uint8_t* buf, size_t len);
// Output callback function with associated data.
struct JPEGOutput {
JPEGOutput(JPEGOutputHook cb, void* data) : cb(cb), data(data) {}
bool Write(const uint8_t* buf, size_t len) const {
return ((int)len == 0) || (cb(data, buf, len) == (int)len);
}
private:
JPEGOutputHook cb;
void* data;
};
bool WriteJpeg(const JPEGData& jpg, bool strip_metadata, JPEGOutput out);
struct HuffmanCodeTable {
uint8_t depth[256];
int code[256];
};
void BuildSequentialHuffmanCodes(
const JPEGData& jpg, std::vector<HuffmanCodeTable>* dc_huffman_code_tables,
std::vector<HuffmanCodeTable>* ac_huffman_code_tables);
struct JpegHistogram {
static const int kSize = kJpegHuffmanAlphabetSize + 1;
JpegHistogram() { Clear(); }
void Clear() {
memset(counts, 0, sizeof(counts));
counts[kSize - 1] = 1;
}
void Add(int symbol) {
counts[symbol] += 2;
}
void Add(int symbol, int weight) {
counts[symbol] += 2 * weight;
}
void AddHistogram(const JpegHistogram& other) {
for (int i = 0; i + 1 < kSize; ++i) {
counts[i] += other.counts[i];
}
counts[kSize - 1] = 1;
}
int NumSymbols() const {
int n = 0;
for (int i = 0; i + 1 < kSize; ++i) {
n += (counts[i] > 0 ? 1 : 0);
}
return n;
}
uint32_t counts[kSize];
};
void BuildDCHistograms(const JPEGData& jpg, JpegHistogram* histo);
void BuildACHistograms(const JPEGData& jpg, JpegHistogram* histo);
size_t JpegHeaderSize(const JPEGData& jpg, bool strip_metadata);
size_t EstimateJpegDataSize(const int num_components,
const std::vector<JpegHistogram>& histograms);
size_t HistogramEntropyCost(const JpegHistogram& histo,
const uint8_t depths[256]);
size_t HistogramHeaderCost(const JpegHistogram& histo);
void UpdateACHistogramForDCTBlock(const coeff_t* coeffs,
JpegHistogram* ac_histogram);
size_t ClusterHistograms(JpegHistogram* histo, size_t* num, int* histo_indexes,
uint8_t* depths);
} // namespace guetzli
#endif // GUETZLI_JPEG_DATA_WRITER_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/jpeg_data_writer.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 736
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_COMPARATOR_H_
#define GUETZLI_COMPARATOR_H_
#include <vector>
#include "guetzli/output_image.h"
#include "guetzli/stats.h"
namespace guetzli {
// Represents a baseline image, a comparison metric and an image acceptance
// criteria based on this metric.
class Comparator {
public:
Comparator() {}
virtual ~Comparator() {}
// Compares img with the baseline image and saves the resulting distance map
// inside the object. The provided image must have the same dimensions as the
// baseline image.
virtual void Compare(const OutputImage& img) = 0;
// Compares an 8x8 block of the baseline image with the same block of img and
// returns the resulting per-block distance. The interpretation of the
// returned distance depends on the comparator used.
virtual double CompareBlock(const OutputImage& img,
int block_x, int block_y) const = 0;
// Returns the combined score of the output image in the last Compare() call
// (or the baseline image, if Compare() was not called yet), based on output
// size and the similarity metric.
virtual double ScoreOutputSize(int size) const = 0;
// Returns true if the argument of the last Compare() call (or the baseline
// image, if Compare() was not called yet) meets the image acceptance
// criteria. The target_mul modifies the acceptance criteria used in this call
// the following way:
// = 1.0 : the original acceptance criteria is used,
// < 1.0 : a more strict acceptance criteria is used,
// > 1.0 : a less strict acceptance criteria is used.
virtual bool DistanceOK(double target_mul) const = 0;
// Returns the distance map between the baseline image and the image in the
// last Compare() call (or the baseline image, if Compare() was not called
// yet).
// The dimensions of the distance map are the same as the baseline image.
// The interpretation of the distance values depend on the comparator used.
virtual const std::vector<float> distmap() const = 0;
// Returns an aggregate distance or similarity value between the baseline
// image and the image in the last Compare() call (or the baseline image, if
// Compare() was not called yet).
// The interpretation of this aggregate value depends on the comparator used.
virtual float distmap_aggregate() const = 0;
// Returns a heuristic cutoff on block errors in the sense that we won't
// consider distortions where a block error is greater than this.
virtual float BlockErrorLimit() const = 0;
// Given the search direction (+1 for upwards and -1 for downwards) and the
// current distance map, fills in *block_weight image with the relative block
// error adjustment weights.
// The target_mul param has the same semantics as in DistanceOK().
// Note that this is essentially a static function in the sense that it does
// not depend on the last Compare() call.
virtual void ComputeBlockErrorAdjustmentWeights(
int direction, int max_block_dist, double target_mul, int factor_x,
int factor_y, const std::vector<float>& distmap,
std::vector<float>* block_weight) = 0;
};
} // namespace guetzli
#endif // GUETZLI_COMPARATOR_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/comparator.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 781
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Entropy encoding (Huffman) utilities.
#ifndef GUETZLI_ENTROPY_ENCODE_H_
#define GUETZLI_ENTROPY_ENCODE_H_
#include <stddef.h>
#include <stdint.h>
namespace guetzli {
// A node of a Huffman tree.
struct HuffmanTree {
HuffmanTree() {}
HuffmanTree(uint32_t count, int16_t left, int16_t right)
: total_count_(count),
index_left_(left),
index_right_or_value_(right) {
}
uint32_t total_count_;
int16_t index_left_;
int16_t index_right_or_value_;
};
bool SetDepth(int p, HuffmanTree *pool, uint8_t *depth, int max_depth);
// This function will create a Huffman tree.
//
// The (data,length) contains the population counts.
// The tree_limit is the maximum bit depth of the Huffman codes.
//
// The depth contains the tree, i.e., how many bits are used for
// the symbol.
//
// The actual Huffman tree is constructed in the tree[] array, which has to
// be at least 2 * length + 1 long.
//
// See path_to_url
void CreateHuffmanTree(const uint32_t *data,
const size_t length,
const int tree_limit,
HuffmanTree* tree,
uint8_t *depth);
} // namespace guetzli
#endif // GUETZLI_ENTROPY_ENCODE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/entropy_encode.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 343
|
```objective-c
/*
LodePNG version 20160409
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.
*/
#ifndef LODEPNG_H
#define LODEPNG_H
#include <string.h> /*for size_t*/
extern const char* LODEPNG_VERSION_STRING;
/*
The following #defines are used to create code sections. They can be disabled
to disable code sections, which can give faster compile time and smaller binary.
The "NO_COMPILE" defines are designed to be used to pass as defines to the
compiler command to disable them without modifying this header, e.g.
-DLODEPNG_NO_COMPILE_ZLIB for gcc.
In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to
allow implementing a custom lodepng_crc32.
*/
/*deflate & zlib. If disabled, you must specify alternative zlib functions in
the custom_zlib field of the compress and decompress settings*/
#ifndef LODEPNG_NO_COMPILE_ZLIB
#define LODEPNG_COMPILE_ZLIB
#endif
/*png encoder and png decoder*/
#ifndef LODEPNG_NO_COMPILE_PNG
#define LODEPNG_COMPILE_PNG
#endif
/*deflate&zlib decoder and png decoder*/
#ifndef LODEPNG_NO_COMPILE_DECODER
#define LODEPNG_COMPILE_DECODER
#endif
/*deflate&zlib encoder and png encoder*/
#ifndef LODEPNG_NO_COMPILE_ENCODER
#define LODEPNG_COMPILE_ENCODER
#endif
/*the optional built in harddisk file loading and saving functions*/
#ifndef LODEPNG_NO_COMPILE_DISK
#define LODEPNG_COMPILE_DISK
#endif
/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/
#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS
#define LODEPNG_COMPILE_ANCILLARY_CHUNKS
#endif
/*ability to convert error numerical codes to English text string*/
#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT
#define LODEPNG_COMPILE_ERROR_TEXT
#endif
/*Compile the default allocators (C's free, malloc and realloc). If you disable this,
you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your
source files with custom allocators.*/
#ifndef LODEPNG_NO_COMPILE_ALLOCATORS
#define LODEPNG_COMPILE_ALLOCATORS
#endif
/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/
#ifdef __cplusplus
#ifndef LODEPNG_NO_COMPILE_CPP
#define LODEPNG_COMPILE_CPP
#endif
#endif
#ifdef LODEPNG_COMPILE_CPP
#include <vector>
#include <string>
#endif /*LODEPNG_COMPILE_CPP*/
#ifdef LODEPNG_COMPILE_PNG
/*The PNG color types (also used for raw).*/
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*/
LCT_GREY_ALPHA = 4, /*greyscale with alpha: 8,16 bit*/
LCT_RGBA = 6 /*RGB with alpha: 8,16 bit*/
} LodePNGColorType;
#ifdef LODEPNG_COMPILE_DECODER
/*
Converts PNG data in memory to raw pixel data.
out: Output parameter. Pointer to buffer that will contain the raw pixel data.
After decoding, its size is w * h * (bytes per pixel) bytes larger than
initially. Bytes per pixel depends on colortype and bitdepth.
Must be freed after usage with free(*out).
Note: for 16-bit per channel colors, uses big endian format like PNG does.
w: Output parameter. Pointer to width of pixel data.
h: Output parameter. Pointer to height of pixel data.
in: Memory buffer with the PNG file.
insize: size of the in buffer.
colortype: the desired color type for the raw output image. See explanation on PNG color types.
bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types.
Return value: LodePNG error code (0 means no error).
*/
unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h,
const unsigned char* in, size_t insize,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/
unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h,
const unsigned char* in, size_t insize);
/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/
unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h,
const unsigned char* in, size_t insize);
#ifdef LODEPNG_COMPILE_DISK
/*
Load PNG from disk, from file with given name.
Same as the other decode functions, but instead takes a filename as input.
*/
unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h,
const char* filename,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/
unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h,
const char* filename);
/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/
unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h,
const char* filename);
#endif /*LODEPNG_COMPILE_DISK*/
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*
Converts raw pixel data into a PNG image in memory. The colortype and bitdepth
of the output PNG image cannot be chosen, they are automatically determined
by the colortype, bitdepth and content of the input pixel data.
Note: for 16-bit per channel colors, needs big endian format like PNG does.
out: Output parameter. Pointer to buffer that will contain the PNG image data.
Must be freed after usage with free(*out).
outsize: Output parameter. Pointer to the size in bytes of the out buffer.
image: The raw pixel data to encode. The size of this buffer should be
w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth.
w: width of the raw pixel data in pixels.
h: height of the raw pixel data in pixels.
colortype: the color type of the raw input image. See explanation on PNG color types.
bitdepth: the bit depth of the raw input image. See explanation on PNG color types.
Return value: LodePNG error code (0 means no error).
*/
unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/
unsigned lodepng_encode32(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h);
/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/
unsigned lodepng_encode24(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h);
#ifdef LODEPNG_COMPILE_DISK
/*
Converts raw pixel data into a PNG file on disk.
Same as the other encode functions, but instead takes a filename as output.
NOTE: This overwrites existing files without warning!
*/
unsigned lodepng_encode_file(const char* filename,
const unsigned char* image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/
unsigned lodepng_encode32_file(const char* filename,
const unsigned char* image, unsigned w, unsigned h);
/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/
unsigned lodepng_encode24_file(const char* filename,
const unsigned char* image, unsigned w, unsigned h);
#endif /*LODEPNG_COMPILE_DISK*/
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_CPP
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.*/
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
const unsigned char* in, size_t insize,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
const std::vector<unsigned char>& in,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#ifdef LODEPNG_COMPILE_DISK
/*
Converts PNG file from disk to raw pixel data in memory.
Same as the other decode functions, but instead takes a filename as input.
*/
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
const std::string& filename,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_DECODER */
#ifdef LODEPNG_COMPILE_ENCODER
/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype
is that of the raw input data. The output PNG color type will be auto chosen.*/
unsigned encode(std::vector<unsigned char>& out,
const unsigned char* in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned encode(std::vector<unsigned char>& out,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#ifdef LODEPNG_COMPILE_DISK
/*
Converts 32-bit RGBA raw pixel data into a PNG file on disk.
Same as the other encode functions, but instead takes a filename as output.
NOTE: This overwrites existing files without warning!
*/
unsigned encode(const std::string& filename,
const unsigned char* in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned encode(const std::string& filename,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_ENCODER */
} /* namespace lodepng */
#endif /*LODEPNG_COMPILE_CPP*/
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ERROR_TEXT
/*Returns an English description of the numerical error code.*/
const char* lodepng_error_text(unsigned code);
#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
#ifdef LODEPNG_COMPILE_DECODER
/*Settings for zlib decompression*/
typedef struct LodePNGDecompressSettings LodePNGDecompressSettings;
struct LodePNGDecompressSettings
{
unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/
/*use custom zlib decoder instead of built in one (default: null)*/
unsigned (*custom_zlib)(unsigned char**, size_t*,
const unsigned char*, size_t,
const LodePNGDecompressSettings*);
/*use custom deflate decoder instead of built in one (default: null)
if custom_zlib is used, custom_deflate is ignored since only the built in
zlib function will call custom_deflate*/
unsigned (*custom_inflate)(unsigned char**, size_t*,
const unsigned char*, size_t,
const LodePNGDecompressSettings*);
const void* custom_context; /*optional custom settings for custom functions*/
};
extern const LodePNGDecompressSettings lodepng_default_decompress_settings;
void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*
Settings for zlib compression. Tweaking these settings tweaks the balance
between speed and compression ratio.
*/
typedef struct LodePNGCompressSettings LodePNGCompressSettings;
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.*/
unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/
unsigned minmatch; /*mininum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/
unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/
unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/
/*use custom zlib encoder instead of built in one (default: null)*/
unsigned (*custom_zlib)(unsigned char**, size_t*,
const unsigned char*, size_t,
const LodePNGCompressSettings*);
/*use custom deflate encoder instead of built in one (default: null)
if custom_zlib is used, custom_deflate is ignored since only the built in
zlib function will call custom_deflate*/
unsigned (*custom_deflate)(unsigned char**, size_t*,
const unsigned char*, size_t,
const LodePNGCompressSettings*);
const void* custom_context; /*optional custom settings for custom functions*/
};
extern const LodePNGCompressSettings lodepng_default_compress_settings;
void lodepng_compress_settings_init(LodePNGCompressSettings* settings);
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_PNG
/*
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
{
/*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*/
/*
palette (PLTE and tRNS)
Dynamically allocated with the colors of the palette, including alpha.
When encoding a PNG, to store your colors in the palette of the LodePNGColorMode, first use
lodepng_palette_clear, then for each color use lodepng_palette_add.
If you encode an image without alpha with palette, don't forget to put value 255 in each A byte of the palette.
When decoding, by default you can ignore this palette, since LodePNG already
fills the palette colors in the pixels of the raw RGBA output.
The palette is only supported for color type 3.
*/
unsigned char* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/
size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/
/*
transparent color key (tRNS)
This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit.
For greyscale PNGs, r, g and b will all 3 be set to the same.
When decoding, by default you can ignore this information, since LodePNG sets
pixels with this key to transparent already in the raw RGBA output.
The color key is only supported for color types 0 and 2.
*/
unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/
unsigned key_r; /*red/greyscale component of color key*/
unsigned key_g; /*green component of color key*/
unsigned key_b; /*blue component of color key*/
} LodePNGColorMode;
/*init, cleanup and copy functions to use with this struct*/
void lodepng_color_mode_init(LodePNGColorMode* info);
void lodepng_color_mode_cleanup(LodePNGColorMode* info);
/*return value is error code (0 means no error)*/
unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source);
void lodepng_palette_clear(LodePNGColorMode* info);
/*add 1 color to the palette*/
unsigned lodepng_palette_add(LodePNGColorMode* info,
unsigned char r, unsigned char g, unsigned char b, unsigned char a);
/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/
unsigned lodepng_get_bpp(const LodePNGColorMode* info);
/*get the amount of color channels used, based on colortype in the struct.
If a palette is used, it counts as 1 channel.*/
unsigned lodepng_get_channels(const LodePNGColorMode* info);
/*is it a greyscale type? (only colortype 0 or 4)*/
unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info);
/*has it got an alpha channel? (only colortype 2 or 6)*/
unsigned lodepng_is_alpha_type(const LodePNGColorMode* info);
/*has it got a palette? (only colortype 3)*/
unsigned lodepng_is_palette_type(const LodePNGColorMode* info);
/*only returns true if there is a palette and there is a value in the palette with alpha < 255.
Loops through the palette to check this.*/
unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info);
/*
Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image.
Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels).
Returns false if the image can only have opaque pixels.
In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values,
or if "key_defined" is true.
*/
unsigned lodepng_can_have_alpha(const LodePNGColorMode* info);
/*Returns the byte size of a raw image buffer with given width, height and color mode*/
size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*The information of a Time chunk in PNG.*/
typedef struct LodePNGTime
{
unsigned year; /*2 bytes used (0-65535)*/
unsigned month; /*1-12*/
unsigned day; /*1-31*/
unsigned hour; /*0-23*/
unsigned minute; /*0-59*/
unsigned second; /*0-60 (to allow for leap seconds)*/
} LodePNGTime;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*Information about the PNG image, except pixels, width and height.*/
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*/
unsigned interlace_method; /*interlace method of the original file*/
LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*
suggested background color chunk (bKGD)
This color uses the same color mode as the PNG (except alpha channel), which can be 1-bit to 16-bit.
For greyscale PNGs, r, g and b will all 3 be set to the same. When encoding
the encoder writes the red one. For palette PNGs: When decoding, the RGB value
will be stored, not a palette index. But when encoding, specify the index of
the palette in background_r, the other two are then ignored.
The decoder does not use this background color to edit the color of pixels.
*/
unsigned background_defined; /*is a suggested background color given?*/
unsigned background_r; /*red component of suggested background color*/
unsigned background_g; /*green component of suggested background color*/
unsigned background_b; /*blue component of suggested background color*/
/*
non-international text chunks (tEXt and zTXt)
The char** arrays each contain num strings. The actual messages are in
text_strings, while text_keys are keywords that give a short description what
the actual text represents, e.g. Title, Author, Description, or anything else.
A keyword is minimum 1 character and maximum 79 characters long. It's
discouraged to use a single line length longer than 79 characters for texts.
Don't allocate these text buffers yourself. Use the init/cleanup functions
correctly and use lodepng_add_text and lodepng_clear_text.
*/
size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/
char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/
char** text_strings; /*the actual text*/
/*
international text chunks (iTXt)
Similar to the non-international text chunks, but with additional strings
"langtags" and "transkeys".
*/
size_t itext_num; /*the amount of international texts in this PNG*/
char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/
char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/
char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/
char** itext_strings; /*the actual international text - UTF-8 string*/
/*time chunk (tIME)*/
unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/
LodePNGTime time;
/*phys chunk (pHYs)*/
unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/
unsigned phys_x; /*pixels per unit in x direction*/
unsigned phys_y; /*pixels per unit in y direction*/
unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/
/*
unknown chunks
There are 3 buffers, one for each position in the PNG where unknown chunks can appear
each buffer contains all unknown chunks for that position consecutively
The 3 buffers are the unknown chunks between certain critical chunks:
0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND
Do not allocate or traverse this data yourself. Use the chunk traversing functions declared
later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct.
*/
unsigned char* unknown_chunks_data[3];
size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGInfo;
/*init, cleanup and copy functions to use with this struct*/
void lodepng_info_init(LodePNGInfo* info);
void lodepng_info_cleanup(LodePNGInfo* info);
/*return value is error code (0 means no error)*/
unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/
unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/
void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/
unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*
Converts raw buffer from one color type to another color type, based on
LodePNGColorMode structs to describe the input and output color type.
See the reference manual at the end of this header file to see which color conversions are supported.
return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported)
The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel
of the output color type (lodepng_get_bpp).
For < 8 bpp images, there should not be padding bits at the end of scanlines.
For 16-bit per channel colors, uses big endian format like PNG does.
Return value is LodePNG error code
*/
unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
unsigned w, unsigned h);
#ifdef LODEPNG_COMPILE_DECODER
/*
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
{
LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/
unsigned ignore_crc; /*ignore CRC checksums*/
unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/
/*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/
unsigned remember_unknown_chunks;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGDecoderSettings;
void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/
typedef enum LodePNGFilterStrategy
{
/*every filter at zero*/
LFS_ZERO,
/*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/
LFS_MINSUM,
/*Use the filter type that gives smallest Shannon entropy for this scanline. Depending
on the image, this is better or worse than minsum.*/
LFS_ENTROPY,
/*
Brute-force-search PNG filters by compressing each filter for each scanline.
Experimental, very slow, and only rarely gives better compression than MINSUM.
*/
LFS_BRUTE_FORCE,
/*use predefined_filters buffer: you specify the filter type for each scanline*/
LFS_PREDEFINED
} LodePNGFilterStrategy;
/*Gives characteristics about the colors of the image, 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.*/
typedef struct LodePNGColorProfile
{
unsigned colored; /*not greyscale*/
unsigned key; /*if true, image is not opaque. Only if true and alpha is false, color key is possible.*/
unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/
unsigned short key_g;
unsigned short key_b;
unsigned alpha; /*alpha channel or alpha palette required*/
unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/
unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/
unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/
} LodePNGColorProfile;
void lodepng_color_profile_init(LodePNGColorProfile* profile);
/*Get a LodePNGColorProfile of the image.*/
unsigned lodepng_get_color_profile(LodePNGColorProfile* profile,
const unsigned char* image, unsigned w, unsigned h,
const LodePNGColorMode* mode_in);
/*The function LodePNG uses internally to decide the PNG color with auto_convert.
Chooses an optimal color model, e.g. grey if only grey pixels, palette if < 256 colors, ...*/
unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out,
const unsigned char* image, unsigned w, unsigned h,
const LodePNGColorMode* mode_in);
/*Settings for the encoder.*/
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*/
/*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than
8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to
completely follow the official PNG heuristic, filter_palette_zero must be true and
filter_strategy must be LFS_MINSUM*/
unsigned filter_palette_zero;
/*Which filter strategy to use when not using zeroes due to filter_palette_zero.
Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/
LodePNGFilterStrategy filter_strategy;
/*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with
the same length as the amount of scanlines in the image, and each value must <= 5. You
have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero
must be set to 0 to ensure this is also used on palette or low bitdepth images.*/
const unsigned char* predefined_filters;
/*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette).
If colortype is 3, PLTE is _always_ created.*/
unsigned force_palette;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*add LodePNG identifier and version as a text chunk, for debugging*/
unsigned add_id;
/*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/
unsigned text_compression;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGEncoderSettings;
void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings);
#endif /*LODEPNG_COMPILE_ENCODER*/
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
/*The settings, state and information for extended encoding and decoding.*/
typedef struct LodePNGState
{
#ifdef LODEPNG_COMPILE_DECODER
LodePNGDecoderSettings decoder; /*the decoding settings*/
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
LodePNGEncoderSettings encoder; /*the encoding settings*/
#endif /*LODEPNG_COMPILE_ENCODER*/
LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/
LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/
unsigned error;
#ifdef LODEPNG_COMPILE_CPP
/* For the lodepng::State subclass. */
virtual ~LodePNGState(){}
#endif
} LodePNGState;
/*init, cleanup and copy functions to use with this struct*/
void lodepng_state_init(LodePNGState* state);
void lodepng_state_cleanup(LodePNGState* state);
void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source);
#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
#ifdef LODEPNG_COMPILE_DECODER
/*
Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and
getting much more information about the PNG image and color mode.
*/
unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
LodePNGState* state,
const unsigned char* in, size_t insize);
/*
Read the PNG header, but not the actual data. This returns only the information
that is in the header chunk of the PNG, such as width, height and color type. The
information is placed in the info_png field of the LodePNGState.
*/
unsigned lodepng_inspect(unsigned* w, unsigned* h,
LodePNGState* state,
const unsigned char* in, size_t insize);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/
unsigned lodepng_encode(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h,
LodePNGState* state);
#endif /*LODEPNG_COMPILE_ENCODER*/
/*
The lodepng_chunk functions are normally not needed, except to traverse the
unknown chunks stored in the LodePNGInfo struct, or add new ones to it.
It also allows traversing the chunks of an encoded PNG file yourself.
PNG standard chunk naming conventions:
First byte: uppercase = critical, lowercase = ancillary
Second byte: uppercase = public, lowercase = private
Third byte: must be uppercase
Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy
*/
/*
Gets the length of the data of the chunk. Total chunk length has 12 bytes more.
There must be at least 4 bytes to read from. If the result value is too large,
it may be corrupt data.
*/
unsigned lodepng_chunk_length(const unsigned char* chunk);
/*puts the 4-byte type in null terminated string*/
void lodepng_chunk_type(char type[5], const unsigned char* chunk);
/*check if the type is the given type*/
unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type);
/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/
unsigned char lodepng_chunk_ancillary(const unsigned char* chunk);
/*0: public, 1: private (see PNG standard)*/
unsigned char lodepng_chunk_private(const unsigned char* chunk);
/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk);
/*get pointer to the data of the chunk, where the input points to the header of the chunk*/
unsigned char* lodepng_chunk_data(unsigned char* chunk);
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk);
/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/
unsigned lodepng_chunk_check_crc(const unsigned char* chunk);
/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/
void lodepng_chunk_generate_crc(unsigned char* chunk);
/*iterate to next chunks. don't use on IEND chunk, as there is no next chunk then*/
unsigned char* lodepng_chunk_next(unsigned char* chunk);
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk);
/*
Appends chunk to the data in out. The given chunk should already have its chunk header.
The out variable and outlength are updated to reflect the new reallocated buffer.
Returns error code (0 if it went ok)
*/
unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk);
/*
Appends new chunk to out. The chunk to append is given by giving its length, type
and data separately. The type is a 4-letter string.
The out variable and outlength are updated to reflect the new reallocated buffer.
Returne error code (0 if it went ok)
*/
unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
const char* type, const unsigned char* data);
/*Calculate CRC32 of buffer*/
unsigned lodepng_crc32(const unsigned char* buf, size_t len);
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ZLIB
/*
This zlib part can be used independently to zlib compress and decompress a
buffer. It cannot be used to create gzip files however, and it only supports the
part of zlib that is required for PNG, it does not support dictionaries.
*/
#ifdef LODEPNG_COMPILE_DECODER
/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/
unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGDecompressSettings* settings);
/*
Decompresses Zlib data. Reallocates the out buffer and appends the data. The
data must be according to the zlib specification.
Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
buffer and *outsize its size in bytes. out must be freed by user after usage.
*/
unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGDecompressSettings* settings);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*
Compresses data with Zlib. Reallocates the out buffer and appends the data.
Zlib adds a small header and trailer around the deflate data.
The data is output in the format of the zlib specification.
Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
buffer and *outsize its size in bytes. out must be freed by user after usage.
*/
unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings);
/*
Find length-limited Huffman code for given frequencies. This function is in the
public interface only for tests, it's used internally by lodepng_deflate.
*/
unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
size_t numcodes, unsigned maxbitlen);
/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/
unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings);
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
#ifdef LODEPNG_COMPILE_DISK
/*
Load a file from disk into buffer. The function allocates the out buffer, and
after usage you should free it.
out: output parameter, contains pointer to loaded buffer.
outsize: output parameter, size of the allocated out buffer
filename: the path to the file to load
return value: error code (0 means ok)
*/
unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename);
/*
Save a file from buffer to disk. Warning, if it exists, this function overwrites
the file without warning!
buffer: the buffer to write
buffersize: size of the buffer to write
filename: the path to the file to save to
return value: error code (0 means ok)
*/
unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename);
#endif /*LODEPNG_COMPILE_DISK*/
#ifdef LODEPNG_COMPILE_CPP
/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */
namespace lodepng
{
#ifdef LODEPNG_COMPILE_PNG
class State : public LodePNGState
{
public:
State();
State(const State& other);
virtual ~State();
State& operator=(const State& other);
};
#ifdef LODEPNG_COMPILE_DECODER
/* Same as other lodepng::decode, but using a State for more settings and information. */
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
State& state,
const unsigned char* in, size_t insize);
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
State& state,
const std::vector<unsigned char>& in);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/* Same as other lodepng::encode, but using a State for more settings and information. */
unsigned encode(std::vector<unsigned char>& out,
const unsigned char* in, unsigned w, unsigned h,
State& state);
unsigned encode(std::vector<unsigned char>& out,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
State& state);
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DISK
/*
Load a file from disk into an std::vector.
return value: error code (0 means ok)
*/
unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename);
/*
Save the binary data in an std::vector to a file on disk. The file is overwritten
without warning.
*/
unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename);
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_PNG */
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_DECODER
/* Zlib-decompress an unsigned char buffer */
unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);
/* Zlib-decompress an std::vector */
unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);
#endif /* LODEPNG_COMPILE_DECODER */
#ifdef LODEPNG_COMPILE_ENCODER
/* Zlib-compress an unsigned char buffer */
unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
const LodePNGCompressSettings& settings = lodepng_default_compress_settings);
/* Zlib-compress an std::vector */
unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
const LodePNGCompressSettings& settings = lodepng_default_compress_settings);
#endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_ZLIB */
} /* namespace lodepng */
#endif /*LODEPNG_COMPILE_CPP*/
/*
TODO:
[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often
[.] check compatibility with various compilers - done but needs to be redone for every newer version
[X] converting color to 16-bit per channel types
[ ] read all public PNG chunk types (but never let the color profile and gamma ones touch RGB values)
[ ] make sure encoder generates no chunks with size > (2^31)-1
[ ] partial decoding (stream processing)
[X] let the "isFullyOpaque" function check color keys and transparent palettes too
[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl"
[ ] don't stop decoding on errors like 69, 57, 58 (make warnings)
[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes
[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ...
[ ] allow user to give data (void*) to custom allocator
*/
#endif /*LODEPNG_H inclusion guard*/
/*
LodePNG Documentation
---------------------
0. table of contents
--------------------
1. about
1.1. supported features
1.2. features not supported
2. C and C++ version
3. security
4. decoding
5. encoding
6. color conversions
6.1. PNG color types
6.2. color conversions
6.3. padding bits
6.4. A note about 16-bits per channel and endianness
7. error values
8. chunks and PNG editing
9. compiler support
10. examples
10.1. decoder C++ example
10.2. decoder C example
11. state settings reference
12. changes
13. contact information
1. about
--------
PNG is a file format to store raster images losslessly with good compression,
supporting different color types and alpha channel.
LodePNG is a PNG codec according to the Portable Network Graphics (PNG)
Specification (Second Edition) - W3C Recommendation 10 November 2003.
The specifications used are:
*) Portable Network Graphics (PNG) Specification (Second Edition):
path_to_url
*) RFC 1950 ZLIB Compressed Data Format version 3.3:
path_to_url
*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3:
path_to_url
The most recent version of LodePNG can currently be found at
path_to_url
LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds
extra functionality.
LodePNG exists out of two files:
-lodepng.h: the header file for both C and C++
-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage
If you want to start using LodePNG right away without reading this doc, get the
examples from the LodePNG website to see how to use it in code, or check the
smaller examples in chapter 13 here.
LodePNG is simple but only supports the basic requirements. To achieve
simplicity, the following design choices were made: There are no dependencies
on any external library. There are functions to decode and encode a PNG with
a single function call, and extended versions of these functions taking a
LodePNGState struct allowing to specify or get more information. By default
the colors of the raw image are always RGB or RGBA, no matter what color type
the PNG file uses. To read and write files, there are simple functions to
convert the files to/from buffers in memory.
This all makes LodePNG suitable for loading textures in games, demos and small
programs, ... It's less suitable for full fledged image editors, loading PNGs
over network (it requires all the image data to be available before decoding can
begin), life-critical systems, ...
1.1. supported features
-----------------------
The following features are supported by the decoder:
*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image,
or the same color type as the PNG
*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image
*) Adam7 interlace and deinterlace for any color type
*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk
*) support for alpha channels, including RGBA color model, translucent palettes and color keying
*) zlib decompression (inflate)
*) zlib compression (deflate)
*) CRC32 and ADLER32 checksums
*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks.
*) the following chunks are supported (generated/interpreted) by both encoder and decoder:
IHDR: header information
PLTE: color palette
IDAT: pixel data
IEND: the final chunk
tRNS: transparency for palettized images
tEXt: textual information
zTXt: compressed textual information
iTXt: international textual information
bKGD: suggested background color
pHYs: physical dimensions
tIME: modification time
1.2. features not supported
---------------------------
The following features are _not_ supported:
*) some features needed to make a conformant PNG-Editor might be still missing.
*) partial loading/stream processing. All data must be available and is processed in one call.
*) The following public chunks are not supported but treated as unknown chunks by LodePNG
cHRM, gAMA, iCCP, sRGB, sBIT, hIST, sPLT
Some of these are not supported on purpose: LodePNG wants to provide the RGB values
stored in the pixels, not values modified by system dependent gamma or color models.
2. C and C++ version
--------------------
The C version uses buffers allocated with alloc that you need to free()
yourself. You need to use init and cleanup functions for each struct whenever
using a struct from the C version to avoid exploits and memory leaks.
The C++ version has extra functions with std::vectors in the interface and the
lodepng::State class which is a LodePNGState with constructor and destructor.
These files work without modification for both C and C++ compilers because all
the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers
ignore it, and the C code is made to compile both with strict ISO C90 and C++.
To use the C++ version, you need to rename the source file to lodepng.cpp
(instead of lodepng.c), and compile it with a C++ compiler.
To use the C version, you need to rename the source file to lodepng.c (instead
of lodepng.cpp), and compile it with a C compiler.
3. Security
-----------
Even if carefully designed, it's always possible that LodePNG contains possible
exploits. If you discover one, please let me know, and it will be fixed.
When using LodePNG, care has to be taken with the C version of LodePNG, as well
as the C-style structs when working with C++. The following conventions are used
for all C-style structs:
-if a struct has a corresponding init function, always call the init function when making a new one
-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks
-if a struct has a corresponding copy function, use the copy function instead of "=".
The destination must also be inited already.
4. Decoding
-----------
Decoding converts a PNG compressed image to a raw pixel buffer.
Most documentation on using the decoder is at its declarations in the header
above. For C, simple decoding can be done with functions such as
lodepng_decode32, and more advanced decoding can be done with the struct
LodePNGState and lodepng_decode. For C++, all decoding can be done with the
various lodepng::decode functions, and lodepng::State can be used for advanced
features.
When using the LodePNGState, it uses the following fields for decoding:
*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here
*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get
*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use
LodePNGInfo info_png
--------------------
After decoding, this contains extra information of the PNG image, except the actual
pixels, width and height because these are already gotten directly from the decoder
functions.
It contains for example the original color type of the PNG image, text comments,
suggested background color, etc... More details about the LodePNGInfo struct are
at its declaration documentation.
LodePNGColorMode info_raw
-------------------------
When decoding, here you can specify which color type you want
the resulting raw image to be. If this is different from the colortype of the
PNG, then the decoder will automatically convert the result. This conversion
always works, except if you want it to convert a color PNG to greyscale or to
a palette with missing colors.
By default, 32-bit color is used for the result.
LodePNGDecoderSettings decoder
------------------------------
The settings can be used to ignore the errors created by invalid CRC and Adler32
chunks, and to disable the decoding of tEXt chunks.
There's also a setting color_convert, true by default. If false, no conversion
is done, the resulting data will be as it was in the PNG (after decompression)
and you'll have to puzzle the colors of the pixels together yourself using the
color type information in the LodePNGInfo.
5. Encoding
-----------
Encoding converts a raw pixel buffer to a PNG compressed image.
Most documentation on using the encoder is at its declarations in the header
above. For C, simple encoding can be done with functions such as
lodepng_encode32, and more advanced decoding can be done with the struct
LodePNGState and lodepng_encode. For C++, all encoding can be done with the
various lodepng::encode functions, and lodepng::State can be used for advanced
features.
Like the decoder, the encoder can also give errors. However it gives less errors
since the encoder input is trusted, the decoder input (a PNG image that could
be forged by anyone) is not trusted.
When using the LodePNGState, it uses the following fields for encoding:
*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be.
*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has
*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use
LodePNGInfo info_png
--------------------
When encoding, you use this the opposite way as when decoding: for encoding,
you fill in the values you want the PNG to have before encoding. By default it's
not needed to specify a color type for the PNG since it's automatically chosen,
but it's possible to choose it yourself given the right settings.
The encoder will not always exactly match the LodePNGInfo struct you give,
it tries as close as possible. Some things are ignored by the encoder. The
encoder uses, for example, the following settings from it when applicable:
colortype and bitdepth, text chunks, time chunk, the color key, the palette, the
background color, the interlace method, unknown chunks, ...
When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk.
If the palette contains any colors for which the alpha channel is not 255 (so
there are translucent colors in the palette), it'll add a tRNS chunk.
LodePNGColorMode info_raw
-------------------------
You specify the color type of the raw image that you give to the input here,
including a possible transparent color key and palette you happen to be using in
your raw image data.
By default, 32-bit color is assumed, meaning your input has to be in RGBA
format with 4 bytes (unsigned chars) per pixel.
LodePNGEncoderSettings encoder
------------------------------
The following settings are supported (some are in sub-structs):
*) auto_convert: when this option is enabled, the encoder will
automatically choose the smallest possible color mode (including color key) that
can encode the colors of all pixels without information loss.
*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree,
2 = dynamic huffman tree (best compression). Should be 2 for proper
compression.
*) use_lz77: whether or not to use LZ77 for compressed block types. Should be
true for proper compression.
*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value
2048 by default, but can be set to 32768 for better, but slow, compression.
*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE
chunk if force_palette is true. This can used as suggested palette to convert
to by viewers that don't support more than 256 colors (if those still exist)
*) add_id: add text chunk "Encoder: LodePNG <version>" to the image.
*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks.
zTXt chunks use zlib compression on the text. This gives a smaller result on
large texts but a larger result on small texts (such as a single program name).
It's all tEXt or all zTXt though, there's no separate setting per text yet.
6. color conversions
--------------------
An important thing to note about LodePNG, is that the color type of the PNG, and
the color type of the raw image, are completely independent. By default, when
you decode a PNG, you get the result as a raw image in the color type you want,
no matter whether the PNG was encoded with a palette, greyscale or RGBA color.
And if you encode an image, by default LodePNG will automatically choose the PNG
color type that gives good compression based on the values of colors and amount
of colors in the image. It can be configured to let you control it instead as
well, though.
To be able to do this, LodePNG does conversions from one color mode to another.
It can convert from almost any color type to any other color type, except the
following conversions: RGB to greyscale is not supported, and converting to a
palette when the palette doesn't have a required color is not supported. This is
not supported on purpose: this is information loss which requires a color
reduction algorithm that is beyong the scope of a PNG encoder (yes, RGB to grey
is easy, but there are multiple ways if you want to give some channels more
weight).
By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB
color, no matter what color type the PNG has. And by default when encoding,
LodePNG automatically picks the best color model for the output PNG, and expects
the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control
the color format of the images yourself, you can skip this chapter.
6.1. PNG color types
--------------------
A PNG image can have many color types, ranging from 1-bit color to 64-bit color,
as well as palettized color modes. After the zlib decompression and unfiltering
in the PNG image is done, the raw pixel data will have that color type and thus
a certain amount of bits per pixel. If you want the output raw image after
decoding to have another color type, a conversion is done by LodePNG.
The PNG specification gives the following color types:
0: greyscale, bit depths 1, 2, 4, 8, 16
2: RGB, bit depths 8 and 16
3: palette, bit depths 1, 2, 4 and 8
4: greyscale with alpha, bit depths 8 and 16
6: RGBA, bit depths 8 and 16
Bit depth is the amount of bits per pixel per color channel. So the total amount
of bits per pixel is: amount of channels * bitdepth.
6.2. color conversions
----------------------
As explained in the sections about the encoder and decoder, you can specify
color types and bit depths in info_png and info_raw to change the default
behaviour.
If, when decoding, you want the raw image to be something else than the default,
you need to set the color type and bit depth you want in the LodePNGColorMode,
or the parameters colortype and bitdepth of the simple decoding function.
If, when encoding, you use another color type than the default in the raw input
image, you need to specify its color type and bit depth in the LodePNGColorMode
of the raw image, or use the parameters colortype and bitdepth of the simple
encoding function.
If, when encoding, you don't want LodePNG to choose the output PNG color type
but control it yourself, you need to set auto_convert in the encoder settings
to false, and specify the color type you want in the LodePNGInfo of the
encoder (including palette: it can generate a palette if auto_convert is true,
otherwise not).
If the input and output color type differ (whether user chosen or auto chosen),
LodePNG will do a color conversion, which follows the rules below, and may
sometimes result in an error.
To avoid some confusion:
-the decoder converts from PNG to raw image
-the encoder converts from raw image to PNG
-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image
-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG
-when encoding, the color type in LodePNGInfo is ignored if auto_convert
is enabled, it is automatically generated instead
-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original
PNG image, but it can be ignored since the raw image has the color type you requested instead
-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion
between the color types is done if the color types are supported. If it is not
supported, an error is returned. If the types are the same, no conversion is done.
-even though some conversions aren't supported, LodePNG supports loading PNGs from any
colortype and saving PNGs to any colortype, sometimes it just requires preparing
the raw image correctly before encoding.
-both encoder and decoder use the same color converter.
Non supported color conversions:
-color to greyscale: no error is thrown, but the result will look ugly because
only the red channel is taken
-anything to palette when that palette does not have that color in it: in this
case an error is thrown
Supported color conversions:
-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA
-any grey or grey+alpha, to grey or grey+alpha
-anything to a palette, as long as the palette has the requested colors in it
-removing alpha channel
-higher to smaller bitdepth, and vice versa
If you want no color conversion to be done (e.g. for speed or control):
-In the encoder, you can make it save a PNG with any color type by giving the
raw color mode and LodePNGInfo the same color mode, and setting auto_convert to
false.
-In the decoder, you can make it store the pixel data in the same color type
as the PNG has, by setting the color_convert setting to false. Settings in
info_raw are then ignored.
The function lodepng_convert does the color conversion. It is available in the
interface but normally isn't needed since the encoder and decoder already call
it.
6.3. padding bits
-----------------
In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines
have a bit amount that isn't a multiple of 8, then padding bits are used so that each
scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output.
The raw input image you give to the encoder, and the raw output image you get from the decoder
will NOT have these padding bits, e.g. in the case of a 1-bit image with a width
of 7 pixels, the first pixel of the second scanline will the the 8th bit of the first byte,
not the first bit of a new byte.
6.4. A note about 16-bits per channel and endianness
----------------------------------------------------
LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like
for any other color format. The 16-bit values are stored in big endian (most
significant byte first) in these arrays. This is the opposite order of the
little endian used by x86 CPU's.
LodePNG always uses big endian because the PNG file format does so internally.
Conversions to other formats than PNG uses internally are not supported by
LodePNG on purpose, there are myriads of formats, including endianness of 16-bit
colors, the order in which you store R, G, B and A, and so on. Supporting and
converting to/from all that is outside the scope of LodePNG.
This may mean that, depending on your use case, you may want to convert the big
endian output of LodePNG to little endian with a for loop. This is certainly not
always needed, many applications and libraries support big endian 16-bit colors
anyway, but it means you cannot simply cast the unsigned char* buffer to an
unsigned short* buffer on x86 CPUs.
7. error values
---------------
All functions in LodePNG that return an error code, return 0 if everything went
OK, or a non-zero code if there was an error.
The meaning of the LodePNG error values can be retrieved with the function
lodepng_error_text: given the numerical error code, it returns a description
of the error in English as a string.
Check the implementation of lodepng_error_text to see the meaning of each code.
8. chunks and PNG editing
-------------------------
If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG
editor that should follow the rules about handling of unknown chunks, or if your
program is able to read other types of chunks than the ones handled by LodePNG,
then that's possible with the chunk functions of LodePNG.
A PNG chunk has the following layout:
4 bytes length
4 bytes type name
length bytes data
4 bytes CRC
8.1. iterating through chunks
-----------------------------
If you have a buffer containing the PNG image data, then the first chunk (the
IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the
signature of the PNG and are not part of a chunk. But if you start at byte 8
then you have a chunk, and can check the following things of it.
NOTE: none of these functions check for memory buffer boundaries. To avoid
exploits, always make sure the buffer contains all the data of the chunks.
When using lodepng_chunk_next, make sure the returned value is within the
allocated memory.
unsigned lodepng_chunk_length(const unsigned char* chunk):
Get the length of the chunk's data. The total chunk length is this length + 12.
void lodepng_chunk_type(char type[5], const unsigned char* chunk):
unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type):
Get the type of the chunk or compare if it's a certain type
unsigned char lodepng_chunk_critical(const unsigned char* chunk):
unsigned char lodepng_chunk_private(const unsigned char* chunk):
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk):
Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are).
Check if the chunk is private (public chunks are part of the standard, private ones not).
Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical
chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your
program doesn't handle that type of unknown chunk.
unsigned char* lodepng_chunk_data(unsigned char* chunk):
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk):
Get a pointer to the start of the data of the chunk.
unsigned lodepng_chunk_check_crc(const unsigned char* chunk):
void lodepng_chunk_generate_crc(unsigned char* chunk):
Check if the crc is correct or generate a correct one.
unsigned char* lodepng_chunk_next(unsigned char* chunk):
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk):
Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these
functions do no boundary checking of the allocated data whatsoever, so make sure there is enough
data available in the buffer to be able to go to the next chunk.
unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk):
unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
const char* type, const unsigned char* data):
These functions are used to create new chunks that are appended to the data in *out that has
length *outlength. The append function appends an existing chunk to the new data. The create
function creates a new chunk with the given parameters and appends it. Type is the 4-letter
name of the chunk.
8.2. chunks in info_png
-----------------------
The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3
buffers (each with size) to contain 3 types of unknown chunks:
the ones that come before the PLTE chunk, the ones that come between the PLTE
and the IDAT chunks, and the ones that come after the IDAT chunks.
It's necessary to make the distionction between these 3 cases because the PNG
standard forces to keep the ordering of unknown chunks compared to the critical
chunks, but does not force any other ordering rules.
info_png.unknown_chunks_data[0] is the chunks before PLTE
info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT
info_png.unknown_chunks_data[2] is the chunks after IDAT
The chunks in these 3 buffers can be iterated through and read by using the same
way described in the previous subchapter.
When using the decoder to decode a PNG, you can make it store all unknown chunks
if you set the option settings.remember_unknown_chunks to 1. By default, this
option is off (0).
The encoder will always encode unknown chunks that are stored in the info_png.
If you need it to add a particular chunk that isn't known by LodePNG, you can
use lodepng_chunk_append or lodepng_chunk_create to the chunk data in
info_png.unknown_chunks_data[x].
Chunks that are known by LodePNG should not be added in that way. E.g. to make
LodePNG add a bKGD chunk, set background_defined to true and add the correct
parameters there instead.
9. compiler support
-------------------
No libraries other than the current standard C library are needed to compile
LodePNG. For the C++ version, only the standard C++ library is needed on top.
Add the files lodepng.c(pp) and lodepng.h to your project, include
lodepng.h where needed, and your program can read/write PNG files.
It is compatible with C90 and up, and C++03 and up.
If performance is important, use optimization when compiling! For both the
encoder and decoder, this makes a large difference.
Make sure that LodePNG is compiled with the same compiler of the same version
and with the same settings as the rest of the program, or the interfaces with
std::vectors and std::strings in C++ can be incompatible.
CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets.
*) gcc and g++
LodePNG is developed in gcc so this compiler is natively supported. It gives no
warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++
version 4.7.1 on Linux, 32-bit and 64-bit.
*) Clang
Fully supported and warning-free.
*) Mingw
The Mingw compiler (a port of gcc for Windows) should be fully supported by
LodePNG.
*) Visual Studio and Visual C++ Express Edition
LodePNG should be warning-free with warning level W4. Two warnings were disabled
with pragmas though: warning 4244 about implicit conversions, and warning 4996
where it wants to use a non-standard function fopen_s instead of the standard C
fopen.
Visual Studio may want "stdafx.h" files to be included in each source file and
give an error "unexpected end of file while looking for precompiled header".
This is not standard C++ and will not be added to the stock LodePNG. You can
disable it for lodepng.cpp only by right clicking it, Properties, C/C++,
Precompiled Headers, and set it to Not Using Precompiled Headers there.
NOTE: Modern versions of VS should be fully supported, but old versions, e.g.
VS6, are not guaranteed to work.
*) Compilers on Macintosh
LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for
C and C++.
*) Other Compilers
If you encounter problems on any compilers, feel free to let me know and I may
try to fix it if the compiler is modern and standards complient.
10. examples
------------
This decoder example shows the most basic usage of LodePNG. More complex
examples can be found on the LodePNG website.
10.1. decoder C++ example
-------------------------
#include "lodepng.h"
#include <iostream>
int main(int argc, char *argv[])
{
const char* filename = argc > 1 ? argv[1] : "test.png";
//load and decode
std::vector<unsigned char> image;
unsigned width, height;
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, ...
}
10.2. decoder C example
-----------------------
#include "lodepng.h"
int main(int argc, char *argv[])
{
unsigned error;
unsigned char* image;
size_t width, height;
const char* filename = argc > 1 ? argv[1] : "test.png";
error = lodepng_decode32_file(&image, &width, &height, filename);
if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error));
/ * use image here * /
free(image);
return 0;
}
11. state settings reference
----------------------------
A quick reference of some settings to set on the LodePNGState
For decoding:
state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums
state.decoder.zlibsettings.custom_...: use custom inflate function
state.decoder.ignore_crc: ignore CRC checksums
state.decoder.color_convert: convert internal PNG color to chosen one
state.decoder.read_text_chunks: whether to read in text metadata chunks
state.decoder.remember_unknown_chunks: whether to read in unknown chunks
state.info_raw.colortype: desired color type for decoded image
state.info_raw.bitdepth: desired bit depth for decoded image
state.info_raw....: more color settings, see struct LodePNGColorMode
state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo
For encoding:
state.encoder.zlibsettings.btype: disable compression by setting it to 0
state.encoder.zlibsettings.use_lz77: use LZ77 in compression
state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize
state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match
state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching
state.encoder.zlibsettings.lazymatching: try one more LZ77 matching
state.encoder.zlibsettings.custom_...: use custom deflate function
state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png
state.encoder.filter_palette_zero: PNG filter strategy for palette
state.encoder.filter_strategy: PNG filter strategy to encode with
state.encoder.force_palette: add palette even if not encoding to one
state.encoder.add_id: add LodePNG identifier and version as a text chunk
state.encoder.text_compression: use compressed text chunks for metadata
state.info_raw.colortype: color type of raw input image you provide
state.info_raw.bitdepth: bit depth of raw input image you provide
state.info_raw: more color settings, see struct LodePNGColorMode
state.info_png.color.colortype: desired color type if auto_convert is false
state.info_png.color.bitdepth: desired bit depth if auto_convert is false
state.info_png.color....: more color settings, see struct LodePNGColorMode
state.info_png....: more PNG related settings, see struct LodePNGInfo
12. changes
-----------
The version number of LodePNG is the date of the change given in the format
yyyymmdd.
Some changes aren't backwards compatible. Those are indicated with a (!)
symbol.
*) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within
the limits of pure C90).
*) 08 dec 2015: Made load_file function return error if file can't be opened.
*) 24 okt 2015: Bugfix with decoding to palette output.
*) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding.
*) 23 aug 2014: Reduced needless memory usage of decoder.
*) 28 jun 2014: Removed fix_png setting, always support palette OOB for
simplicity. Made ColorProfile public.
*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization.
*) 22 dec 2013: Power of two windowsize required for optimization.
*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key.
*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png).
*) 11 mar 2013 (!): Bugfix with custom free. Changed from "my" to "lodepng_"
prefix for the custom allocators and made it possible with a new #define to
use custom ones in your project without needing to change lodepng's code.
*) 28 jan 2013: Bugfix with color key.
*) 27 okt 2012: Tweaks in text chunk keyword length error handling.
*) 8 okt 2012 (!): Added new filter strategy (entropy) and new auto color mode.
(no palette). Better deflate tree encoding. New compression tweak settings.
Faster color conversions while decoding. Some internal cleanups.
*) 23 sep 2012: Reduced warnings in Visual Studio a little bit.
*) 1 sep 2012 (!): Removed #define's for giving custom (de)compression functions
and made it work with function pointers instead.
*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc
and free functions and toggle #defines from compiler flags. Small fixes.
*) 6 may 2012 (!): Made plugging in custom zlib/deflate functions more flexible.
*) 22 apr 2012 (!): Made interface more consistent, renaming a lot. Removed
redundant C++ codec classes. Reduced amount of structs. Everything changed,
but it is cleaner now imho and functionality remains the same. Also fixed
several bugs and shrunk the implementation code. Made new samples.
*) 6 nov 2011 (!): By default, the encoder now automatically chooses the best
PNG color model and bit depth, based on the amount and type of colors of the
raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color.
*) 9 okt 2011: simpler hash chain implementation for the encoder.
*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching.
*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking.
A bug with the PNG filtertype heuristic was fixed, so that it chooses much
better ones (it's quite significant). A setting to do an experimental, slow,
brute force search for PNG filter types is added.
*) 17 aug 2011 (!): changed some C zlib related function names.
*) 16 aug 2011: made the code less wide (max 120 characters per line).
*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors.
*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled.
*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman
to optimize long sequences of zeros.
*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and
LodePNG_InfoColor_canHaveAlpha functions for convenience.
*) 7 nov 2010: added LodePNG_error_text function to get error code description.
*) 30 okt 2010: made decoding slightly faster
*) 26 okt 2010: (!) changed some C function and struct names (more consistent).
Reorganized the documentation and the declaration order in the header.
*) 08 aug 2010: only changed some comments and external samples.
*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version.
*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers.
*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could
read by ignoring the problem but windows apps couldn't.
*) 06 jun 2008: added more error checks for out of memory cases.
*) 26 apr 2008: added a few more checks here and there to ensure more safety.
*) 06 mar 2008: crash with encoding of strings fixed
*) 02 feb 2008: support for international text chunks added (iTXt)
*) 23 jan 2008: small cleanups, and #defines to divide code in sections
*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor.
*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder.
*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added
Also various fixes, such as in the deflate and the padding bits code.
*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved
filtering code of encoder.
*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A
C++ wrapper around this provides an interface almost identical to before.
Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code
are together in these files but it works both for C and C++ compilers.
*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks
*) 30 aug 2007: bug fixed which makes this Borland C++ compatible
*) 09 aug 2007: some VS2005 warnings removed again
*) 21 jul 2007: deflate code placed in new namespace separate from zlib code
*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images
*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing
invalid std::vector element [0] fixed, and level 3 and 4 warnings removed
*) 02 jun 2007: made the encoder add a tag with version by default
*) 27 may 2007: zlib and png code separated (but still in the same file),
simple encoder/decoder functions added for more simple usage cases
*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69),
moved some examples from here to lodepng_examples.cpp
*) 12 may 2007: palette decoding bug fixed
*) 24 apr 2007: changed the license from BSD to the zlib license
*) 11 mar 2007: very simple addition: ability to encode bKGD chunks.
*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding
palettized PNG images. Plus little interface change with palette and texts.
*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes.
Fixed a bug where the end code of a block had length 0 in the Huffman tree.
*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented
and supported by the encoder, resulting in smaller PNGs at the output.
*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone.
*) 24 jan 2007: gave encoder an error interface. Added color conversion from any
greyscale type to 8-bit greyscale with or without alpha.
*) 21 jan 2007: (!) Totally changed the interface. It allows more color types
to convert to and is more uniform. See the manual for how it works now.
*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days:
encode/decode custom tEXt chunks, separate classes for zlib & deflate, and
at last made the decoder give errors for incorrect Adler32 or Crc.
*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel.
*) 29 dec 2006: Added support for encoding images without alpha channel, and
cleaned out code as well as making certain parts faster.
*) 28 dec 2006: Added "Settings" to the encoder.
*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now.
Removed some code duplication in the decoder. Fixed little bug in an example.
*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter.
Fixed a bug of the decoder with 16-bit per color.
*) 15 okt 2006: Changed documentation structure
*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the
given image buffer, however for now it's not compressed.
*) 08 sep 2006: (!) Changed to interface with a Decoder class
*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different
way. Renamed decodePNG to decodePNGGeneric.
*) 29 jul 2006: (!) Changed the interface: image info is now returned as a
struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy.
*) 28 jul 2006: Cleaned the code and added new error checks.
Corrected terminology "deflate" into "inflate".
*) 23 jun 2006: Added SDL example in the documentation in the header, this
example allows easy debugging by displaying the PNG and its transparency.
*) 22 jun 2006: (!) Changed way to obtain error value. Added
loadFile function for convenience. Made decodePNG32 faster.
*) 21 jun 2006: (!) Changed type of info vector to unsigned.
Changed position of palette in info vector. Fixed an important bug that
happened on PNGs with an uncompressed block.
*) 16 jun 2006: Internally changed unsigned into unsigned where
needed, and performed some optimizations.
*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them
in LodePNG namespace. Changed the order of the parameters. Rewrote the
documentation in the header. Renamed files to lodepng.cpp and lodepng.h
*) 22 apr 2006: Optimized and improved some code
*) 07 sep 2005: (!) Changed to std::vector interface
*) 12 aug 2005: Initial release (C++, decoder only)
13. contact information
-----------------------
Feel free to contact me with suggestions, problems, comments, ... concerning
LodePNG. If you encounter a PNG image that doesn't work properly with this
decoder, feel free to send it and I'll use it to find and fix the problem.
My email address is (puzzle the account and domain together with an @ symbol):
Domain: gmail dot com.
Account: lode dot vandevenne.
*/
```
|
/content/code_sandbox/library/JQLibrary/include/JQZopfli/zopflipng/lodepng/lodepng.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 19,506
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_DCT_DOUBLE_H_
#define GUETZLI_DCT_DOUBLE_H_
namespace guetzli {
// Performs in-place floating point 8x8 DCT on block[0..63].
// Note that the DCT used here is the DCT-2 with the first term multiplied by
// 1/sqrt(2) and the result scaled by 1/2.
void ComputeBlockDCTDouble(double block[64]);
// Performs in-place floating point 8x8 inverse DCT on block[0..63].
void ComputeBlockIDCTDouble(double block[64]);
} // namespace guetzli
#endif // GUETZLI_DCT_DOUBLE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/dct_double.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 184
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_FAST_LOG_H_
#define GUETZLI_FAST_LOG_H_
#include <math.h>
namespace guetzli {
inline int Log2FloorNonZero(uint32_t n) {
#ifdef __GNUC__
return 31 ^ __builtin_clz(n);
#else
unsigned int result = 0;
while (n >>= 1) result++;
return result;
#endif
}
inline int Log2Floor(uint32_t n) {
return n == 0 ? -1 : Log2FloorNonZero(n);
}
} // namespace guetzli
#endif // GUETZLI_FAST_LOG_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/fast_log.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 170
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Library to decode jpeg coefficients into an RGB image.
#ifndef GUETZLI_JPEG_DATA_DECODER_H_
#define GUETZLI_JPEG_DATA_DECODER_H_
#include <stdint.h>
#include "guetzli/jpeg_data.h"
namespace guetzli {
// Decodes the parsed jpeg coefficients into an RGB image.
// There can be only either 1 or 3 image components, in either case, an RGB
// output image will be generated.
// Only YUV420 and YUV444 sampling factors are supported.
// Vector will be empty if a decoding error occurred.
std::vector<uint8_t> DecodeJpegToRGB(const JPEGData& jpg);
// Mimic libjpeg's heuristics to guess jpeg color space.
// Requires that the jpg has 3 components.
bool HasYCbCrColorSpace(const JPEGData& jpg);
} // namespace guetzli
#endif // GUETZLI_JPEG_DATA_DECODER_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/jpeg_data_decoder.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 239
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_COLOR_TRANSFORM_H_
#define GUETZLI_COLOR_TRANSFORM_H_
namespace guetzli {
static const int kCrToRedTable[256] = {
-179, -178, -177, -175, -174, -172, -171, -170, -168, -167, -165, -164,
-163, -161, -160, -158, -157, -156, -154, -153, -151, -150, -149, -147,
-146, -144, -143, -142, -140, -139, -137, -136, -135, -133, -132, -130,
-129, -128, -126, -125, -123, -122, -121, -119, -118, -116, -115, -114,
-112, -111, -109, -108, -107, -105, -104, -102, -101, -100, -98, -97,
-95, -94, -93, -91, -90, -88, -87, -86, -84, -83, -81, -80,
-79, -77, -76, -74, -73, -72, -70, -69, -67, -66, -64, -63,
-62, -60, -59, -57, -56, -55, -53, -52, -50, -49, -48, -46,
-45, -43, -42, -41, -39, -38, -36, -35, -34, -32, -31, -29,
-28, -27, -25, -24, -22, -21, -20, -18, -17, -15, -14, -13,
-11, -10, -8, -7, -6, -4, -3, -1, 0, 1, 3, 4,
6, 7, 8, 10, 11, 13, 14, 15, 17, 18, 20, 21,
22, 24, 25, 27, 28, 29, 31, 32, 34, 35, 36, 38,
39, 41, 42, 43, 45, 46, 48, 49, 50, 52, 53, 55,
56, 57, 59, 60, 62, 63, 64, 66, 67, 69, 70, 72,
73, 74, 76, 77, 79, 80, 81, 83, 84, 86, 87, 88,
90, 91, 93, 94, 95, 97, 98, 100, 101, 102, 104, 105,
107, 108, 109, 111, 112, 114, 115, 116, 118, 119, 121, 122,
123, 125, 126, 128, 129, 130, 132, 133, 135, 136, 137, 139,
140, 142, 143, 144, 146, 147, 149, 150, 151, 153, 154, 156,
157, 158, 160, 161, 163, 164, 165, 167, 168, 170, 171, 172,
174, 175, 177, 178
};
static const int kCbToBlueTable[256] = {
-227, -225, -223, -222, -220, -218, -216, -214, -213, -211, -209, -207,
-206, -204, -202, -200, -198, -197, -195, -193, -191, -190, -188, -186,
-184, -183, -181, -179, -177, -175, -174, -172, -170, -168, -167, -165,
-163, -161, -159, -158, -156, -154, -152, -151, -149, -147, -145, -144,
-142, -140, -138, -136, -135, -133, -131, -129, -128, -126, -124, -122,
-120, -119, -117, -115, -113, -112, -110, -108, -106, -105, -103, -101,
-99, -97, -96, -94, -92, -90, -89, -87, -85, -83, -82, -80,
-78, -76, -74, -73, -71, -69, -67, -66, -64, -62, -60, -58,
-57, -55, -53, -51, -50, -48, -46, -44, -43, -41, -39, -37,
-35, -34, -32, -30, -28, -27, -25, -23, -21, -19, -18, -16,
-14, -12, -11, -9, -7, -5, -4, -2, 0, 2, 4, 5,
7, 9, 11, 12, 14, 16, 18, 19, 21, 23, 25, 27,
28, 30, 32, 34, 35, 37, 39, 41, 43, 44, 46, 48,
50, 51, 53, 55, 57, 58, 60, 62, 64, 66, 67, 69,
71, 73, 74, 76, 78, 80, 82, 83, 85, 87, 89, 90,
92, 94, 96, 97, 99, 101, 103, 105, 106, 108, 110, 112,
113, 115, 117, 119, 120, 122, 124, 126, 128, 129, 131, 133,
135, 136, 138, 140, 142, 144, 145, 147, 149, 151, 152, 154,
156, 158, 159, 161, 163, 165, 167, 168, 170, 172, 174, 175,
177, 179, 181, 183, 184, 186, 188, 190, 191, 193, 195, 197,
198, 200, 202, 204, 206, 207, 209, 211, 213, 214, 216, 218,
220, 222, 223, 225,
};
static const int kCrToGreenTable[256] = {
5990656, 5943854, 5897052, 5850250, 5803448, 5756646, 5709844, 5663042,
5616240, 5569438, 5522636, 5475834, 5429032, 5382230, 5335428, 5288626,
5241824, 5195022, 5148220, 5101418, 5054616, 5007814, 4961012, 4914210,
4867408, 4820606, 4773804, 4727002, 4680200, 4633398, 4586596, 4539794,
4492992, 4446190, 4399388, 4352586, 4305784, 4258982, 4212180, 4165378,
4118576, 4071774, 4024972, 3978170, 3931368, 3884566, 3837764, 3790962,
3744160, 3697358, 3650556, 3603754, 3556952, 3510150, 3463348, 3416546,
3369744, 3322942, 3276140, 3229338, 3182536, 3135734, 3088932, 3042130,
2995328, 2948526, 2901724, 2854922, 2808120, 2761318, 2714516, 2667714,
2620912, 2574110, 2527308, 2480506, 2433704, 2386902, 2340100, 2293298,
2246496, 2199694, 2152892, 2106090, 2059288, 2012486, 1965684, 1918882,
1872080, 1825278, 1778476, 1731674, 1684872, 1638070, 1591268, 1544466,
1497664, 1450862, 1404060, 1357258, 1310456, 1263654, 1216852, 1170050,
1123248, 1076446, 1029644, 982842, 936040, 889238, 842436, 795634,
748832, 702030, 655228, 608426, 561624, 514822, 468020, 421218,
374416, 327614, 280812, 234010, 187208, 140406, 93604, 46802,
0, -46802, -93604, -140406, -187208, -234010, -280812, -327614,
-374416, -421218, -468020, -514822, -561624, -608426, -655228, -702030,
-748832, -795634, -842436, -889238, -936040, -982842, -1029644, -1076446,
-1123248, -1170050, -1216852, -1263654, -1310456, -1357258, -1404060, -1450862,
-1497664, -1544466, -1591268, -1638070, -1684872, -1731674, -1778476, -1825278,
-1872080, -1918882, -1965684, -2012486, -2059288, -2106090, -2152892, -2199694,
-2246496, -2293298, -2340100, -2386902, -2433704, -2480506, -2527308, -2574110,
-2620912, -2667714, -2714516, -2761318, -2808120, -2854922, -2901724, -2948526,
-2995328, -3042130, -3088932, -3135734, -3182536, -3229338, -3276140, -3322942,
-3369744, -3416546, -3463348, -3510150, -3556952, -3603754, -3650556, -3697358,
-3744160, -3790962, -3837764, -3884566, -3931368, -3978170, -4024972, -4071774,
-4118576, -4165378, -4212180, -4258982, -4305784, -4352586, -4399388, -4446190,
-4492992, -4539794, -4586596, -4633398, -4680200, -4727002, -4773804, -4820606,
-4867408, -4914210, -4961012, -5007814, -5054616, -5101418, -5148220, -5195022,
-5241824, -5288626, -5335428, -5382230, -5429032, -5475834, -5522636, -5569438,
-5616240, -5663042, -5709844, -5756646, -5803448, -5850250, -5897052, -5943854,
};
static const int kCbToGreenTable[256] = {
2919680, 2897126, 2874572, 2852018, 2829464, 2806910, 2784356, 2761802,
2739248, 2716694, 2694140, 2671586, 2649032, 2626478, 2603924, 2581370,
2558816, 2536262, 2513708, 2491154, 2468600, 2446046, 2423492, 2400938,
2378384, 2355830, 2333276, 2310722, 2288168, 2265614, 2243060, 2220506,
2197952, 2175398, 2152844, 2130290, 2107736, 2085182, 2062628, 2040074,
2017520, 1994966, 1972412, 1949858, 1927304, 1904750, 1882196, 1859642,
1837088, 1814534, 1791980, 1769426, 1746872, 1724318, 1701764, 1679210,
1656656, 1634102, 1611548, 1588994, 1566440, 1543886, 1521332, 1498778,
1476224, 1453670, 1431116, 1408562, 1386008, 1363454, 1340900, 1318346,
1295792, 1273238, 1250684, 1228130, 1205576, 1183022, 1160468, 1137914,
1115360, 1092806, 1070252, 1047698, 1025144, 1002590, 980036, 957482,
934928, 912374, 889820, 867266, 844712, 822158, 799604, 777050,
754496, 731942, 709388, 686834, 664280, 641726, 619172, 596618,
574064, 551510, 528956, 506402, 483848, 461294, 438740, 416186,
393632, 371078, 348524, 325970, 303416, 280862, 258308, 235754,
213200, 190646, 168092, 145538, 122984, 100430, 77876, 55322,
32768, 10214, -12340, -34894, -57448, -80002, -102556, -125110,
-147664, -170218, -192772, -215326, -237880, -260434, -282988, -305542,
-328096, -350650, -373204, -395758, -418312, -440866, -463420, -485974,
-508528, -531082, -553636, -576190, -598744, -621298, -643852, -666406,
-688960, -711514, -734068, -756622, -779176, -801730, -824284, -846838,
-869392, -891946, -914500, -937054, -959608, -982162, -1004716, -1027270,
-1049824, -1072378, -1094932, -1117486, -1140040, -1162594, -1185148, -1207702,
-1230256, -1252810, -1275364, -1297918, -1320472, -1343026, -1365580, -1388134,
-1410688, -1433242, -1455796, -1478350, -1500904, -1523458, -1546012, -1568566,
-1591120, -1613674, -1636228, -1658782, -1681336, -1703890, -1726444, -1748998,
-1771552, -1794106, -1816660, -1839214, -1861768, -1884322, -1906876, -1929430,
-1951984, -1974538, -1997092, -2019646, -2042200, -2064754, -2087308, -2109862,
-2132416, -2154970, -2177524, -2200078, -2222632, -2245186, -2267740, -2290294,
-2312848, -2335402, -2357956, -2380510, -2403064, -2425618, -2448172, -2470726,
-2493280, -2515834, -2538388, -2560942, -2583496, -2606050, -2628604, -2651158,
-2673712, -2696266, -2718820, -2741374, -2763928, -2786482, -2809036, -2831590,
};
static const uint8_t kRangeLimitLut[4 * 256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
};
static const uint8_t* kRangeLimit = kRangeLimitLut + 384;
inline void ColorTransformYCbCrToRGB(uint8_t* pixel) {
int y = pixel[0];
int cb = pixel[1];
int cr = pixel[2];
pixel[0] = kRangeLimit[y + kCrToRedTable[cr]];
pixel[1] = kRangeLimit[y +
((kCrToGreenTable[cr] + kCbToGreenTable[cb]) >> 16)];
pixel[2] = kRangeLimit[y + kCbToBlueTable[cb]];
}
} // namespace guetzli
#endif // GUETZLI_COLOR_TRANSFORM_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/color_transform.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 8,526
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_SCORE_H_
#define GUETZLI_SCORE_H_
#include <vector>
namespace guetzli {
double ScoreJPEG(double butteraugli_distance, int size,
double butteraugli_target);
} // namespace guetzli
#endif // GUETZLI_SCORE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/score.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 101
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Utility function for building a Huffman lookup table for the jpeg decoder.
#ifndef GUETZLI_JPEG_HUFFMAN_DECODE_H_
#define GUETZLI_JPEG_HUFFMAN_DECODE_H_
#include <inttypes.h>
namespace guetzli {
static const int kJpegHuffmanRootTableBits = 8;
// Maximum huffman lookup table size.
// According to zlib/examples/enough.c, 758 entries are always enough for
// an alphabet of 257 symbols (256 + 1 special symbol for the all 1s code) and
// max bit length 16 if the root table has 8 bits.
static const int kJpegHuffmanLutSize = 758;
struct HuffmanTableEntry {
// Initialize the value to an invalid symbol so that we can recognize it
// when reading the bit stream using a Huffman code with space > 0.
HuffmanTableEntry() : bits(0), value(0xffff) {}
uint8_t bits; // number of bits used for this symbol
uint16_t value; // symbol value or table offset
};
// Builds jpeg-style Huffman lookup table from the given symbols.
// The symbols are in order of increasing bit lengths. The number of symbols
// with bit length n is given in counts[n] for each n >= 1.
// Returns the size of the lookup table.
int BuildJpegHuffmanTable(const int* counts, const int* symbols,
HuffmanTableEntry* lut);
} // namespace guetzli
#endif // GUETZLI_JPEG_HUFFMAN_DECODE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/jpeg_huffman_decode.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 374
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_GAMMA_CORRECT_H_
#define GUETZLI_GAMMA_CORRECT_H_
namespace guetzli {
const double* Srgb8ToLinearTable();
} // namespace guetzli
#endif // GUETZLI_GAMMA_CORRECT_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/gamma_correct.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 100
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Preprocesses U and V channel for better results after downsampling.
#ifndef GUETZLI_PREPROCESS_DOWNSAMPLE_H_
#define GUETZLI_PREPROCESS_DOWNSAMPLE_H_
#include <stdint.h>
#include <vector>
namespace guetzli {
// Preprocesses the u (1) or v (2) channel of the given YUV image (range 0-255).
std::vector<std::vector<float>> PreProcessChannel(
int w, int h, int channel, float sigma, float amount, bool blur,
bool sharpen, const std::vector<std::vector<float>>& image);
// Gamma-compensated chroma subsampling.
// Returns Y, U, V image planes, each with width x height dimensions, but the
// U and V planes are composed of 2x2 blocks with the same values.
std::vector<std::vector<float> > RGBToYUV420(
const std::vector<uint8_t>& rgb_in, const int width, const int height);
} // namespace guetzli
#endif // GUETZLI_PREPROCESS_DOWNSAMPLE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/preprocess_downsample.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 274
|
```sourcepawn
// Automatically generated by guetzli/order:update_c_code
static const float csf[192] = {
0.0,
1.71014,
0.298711,
0.233709,
0.223126,
0.207072,
0.192775,
0.161201,
2.05807,
0.222927,
0.203406,
0.188465,
0.184668,
0.169993,
0.159142,
0.130155,
0.430518,
0.204939,
0.206655,
0.192231,
0.182941,
0.169455,
0.157599,
0.127153,
0.234757,
0.191098,
0.192698,
0.17425,
0.166503,
0.142154,
0.126182,
0.104196,
0.226117,
0.185373,
0.183825,
0.166643,
0.159414,
0.12636,
0.108696,
0.0911974,
0.207463,
0.171517,
0.170124,
0.141582,
0.126213,
0.103627,
0.0882436,
0.0751848,
0.196436,
0.161947,
0.159271,
0.126938,
0.109125,
0.0878027,
0.0749842,
0.0633859,
0.165232,
0.132905,
0.128679,
0.105766,
0.0906087,
0.0751544,
0.0641187,
0.0529921,
0.0,
0.147235,
0.11264,
0.0757892,
0.0493929,
0.0280663,
0.0075012,
-0.000945567,
0.149251,
0.0964806,
0.0786224,
0.05206,
0.0292758,
0.00353094,
-0.00277912,
-0.00404481,
0.115551,
0.0793142,
0.0623735,
0.0405019,
0.0152656,
-0.00145742,
-0.00370369,
-0.00375106,
0.0791547,
0.0537506,
0.0413634,
0.0193486,
0.000609066,
-0.00510923,
-0.0046452,
-0.00385187,
0.0544534,
0.0334066,
0.0153899,
0.000539088,
-0.00356085,
-0.00535661,
-0.00429145,
-0.00343131,
0.0356439,
0.00865645,
0.00165229,
-0.00425931,
-0.00507324,
-0.00459083,
-0.003703,
-0.00310327,
0.0121926,
-0.0009259,
-0.00330991,
-0.00499378,
-0.00437381,
-0.00377427,
-0.00311731,
-0.00255125,
-0.000320593,
-0.00426043,
-0.00416549,
-0.00419364,
-0.00365418,
-0.00317499,
-0.00255932,
-0.00217917,
0.0,
0.143471,
0.124336,
0.0947465,
0.0814066,
0.0686776,
0.0588122,
0.0374415,
0.146315,
0.105334,
0.0949415,
0.0784241,
0.0689064,
0.0588304,
0.0495961,
0.0202342,
0.123818,
0.0952654,
0.0860556,
0.0724158,
0.0628307,
0.0529965,
0.0353941,
0.00815821,
0.097054,
0.080422,
0.0731085,
0.0636154,
0.055606,
0.0384127,
0.0142879,
0.00105195,
0.0849312,
0.071115,
0.0631183,
0.0552972,
0.0369221,
0.00798314,
0.000716374,
-0.00200948,
0.0722298,
0.0599559,
0.054841,
0.0387529,
0.0107262,
0.000355315,
-0.00244803,
-0.00335222,
0.0635335,
0.0514196,
0.0406309,
0.0125833,
0.00151305,
-0.00140269,
-0.00362547,
-0.00337649,
0.0472024,
0.0198725,
0.0113437,
0.00266305,
-0.00137183,
-0.00354158,
-0.00341292,
-0.00290074
};
static const float bias[192] = {
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0
};
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/order.inc
|
sourcepawn
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 2,647
|
```objective-c
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef GUETZLI_QUANTIZE_H_
#define GUETZLI_QUANTIZE_H_
#include "guetzli/jpeg_data.h"
namespace guetzli {
inline coeff_t Quantize(coeff_t raw_coeff, int quant) {
const int r = raw_coeff % quant;
const coeff_t delta =
2 * r > quant ? quant - r : (-2) * r > quant ? -quant - r : -r;
return raw_coeff + delta;
}
bool QuantizeBlock(coeff_t block[kDCTBlockSize], const int q[kDCTBlockSize]);
} // namespace guetzli
#endif // GUETZLI_QUANTIZE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/guetzli/quantize.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 179
|
```objective-c
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---
//
// Implement helpful bash-style command line flag completions
//
// ** Functional API:
// HandleCommandLineCompletions() should be called early during
// program startup, but after command line flag code has been
// initialized, such as the beginning of HandleCommandLineHelpFlags().
// It checks the value of the flag --tab_completion_word. If this
// flag is empty, nothing happens here. If it contains a string,
// however, then HandleCommandLineCompletions() will hijack the
// process, attempting to identify the intention behind this
// completion. Regardless of the outcome of this deduction, the
// process will be terminated, similar to --helpshort flag
// handling.
//
// ** Overview of Bash completions:
// Bash can be told to programatically determine completions for the
// current 'cursor word'. It does this by (in this case) invoking a
// command with some additional arguments identifying the command
// being executed, the word being completed, and the previous word
// (if any). Bash then expects a sequence of output lines to be
// printed to stdout. If these lines all contain a common prefix
// longer than the cursor word, bash will replace the cursor word
// with that common prefix, and display nothing. If there isn't such
// a common prefix, bash will display the lines in pages using 'more'.
//
// ** Strategy taken for command line completions:
// If we can deduce either the exact flag intended, or a common flag
// prefix, we'll output exactly that. Otherwise, if information
// must be displayed to the user, we'll take the opportunity to add
// some helpful information beyond just the flag name (specifically,
// we'll include the default flag value and as much of the flag's
// description as can fit on a single terminal line width, as specified
// by the flag --tab_completion_columns). Furthermore, we'll try to
// make bash order the output such that the most useful or relevent
// flags are the most likely to be shown at the top.
//
// ** Additional features:
// To assist in finding that one really useful flag, substring matching
// was implemented. Before pressing a <TAB> to get completion for the
// current word, you can append one or more '?' to the flag to do
// substring matching. Here's the semantics:
// --foo<TAB> Show me all flags with names prefixed by 'foo'
// --foo?<TAB> Show me all flags with 'foo' somewhere in the name
// --foo??<TAB> Same as prior case, but also search in module
// definition path for 'foo'
// --foo???<TAB> Same as prior case, but also search in flag
// descriptions for 'foo'
// Finally, we'll trim the output to a relatively small number of
// flags to keep bash quiet about the verbosity of output. If one
// really wanted to see all possible matches, appending a '+' to the
// search word will force the exhaustive list of matches to be printed.
//
// ** How to have bash accept completions from a binary:
// Bash requires that it be informed about each command that programmatic
// completion should be enabled for. Example addition to a .bashrc
// file would be (your path to gflags_completions.sh file may differ):
/*
$ complete -o bashdefault -o default -o nospace -C \
'/home/build/eng/bash/bash_completions.sh --tab_completion_columns $COLUMNS' \
time env binary_name another_binary [...]
*/
// This would allow the following to work:
// $ /path/to/binary_name --vmodule<TAB>
// Or:
// $ ./bin/path/another_binary --gfs_u<TAB>
// (etc)
//
// Sadly, it appears that bash gives no easy way to force this behavior for
// all commands. That's where the "time" in the above example comes in.
// If you haven't specifically added a command to the list of completion
// supported commands, you can still get completions by prefixing the
// entire command with "env".
// $ env /some/brand/new/binary --vmod<TAB>
// Assuming that "binary" is a newly compiled binary, this should still
// produce the expected completion output.
#ifndef GFLAGS_COMPLETIONS_H_
#define GFLAGS_COMPLETIONS_H_
namespace google {
extern void HandleCommandLineCompletions(void);
}
#endif // GFLAGS_COMPLETIONS_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/gflags/gflags_completions.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,281
|
```objective-c
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// your_sha256_hash-------------
// Imports the gflags library symbols into an alternative/deprecated namespace.
#ifndef GFLAGS_GFLAGS_H_
# error The internal header gflags_gflags.h may only be included by gflags.h
#endif
#ifndef GFLAGS_NS_GFLAGS_H_
#define GFLAGS_NS_GFLAGS_H_
namespace gflags {
using GFLAGS_NAMESPACE::int32;
using GFLAGS_NAMESPACE::uint32;
using GFLAGS_NAMESPACE::int64;
using GFLAGS_NAMESPACE::uint64;
using GFLAGS_NAMESPACE::RegisterFlagValidator;
using GFLAGS_NAMESPACE::CommandLineFlagInfo;
using GFLAGS_NAMESPACE::GetAllFlags;
using GFLAGS_NAMESPACE::ShowUsageWithFlags;
using GFLAGS_NAMESPACE::ShowUsageWithFlagsRestrict;
using GFLAGS_NAMESPACE::DescribeOneFlag;
using GFLAGS_NAMESPACE::SetArgv;
using GFLAGS_NAMESPACE::GetArgvs;
using GFLAGS_NAMESPACE::GetArgv;
using GFLAGS_NAMESPACE::GetArgv0;
using GFLAGS_NAMESPACE::GetArgvSum;
using GFLAGS_NAMESPACE::ProgramInvocationName;
using GFLAGS_NAMESPACE::ProgramInvocationShortName;
using GFLAGS_NAMESPACE::ProgramUsage;
using GFLAGS_NAMESPACE::VersionString;
using GFLAGS_NAMESPACE::GetCommandLineOption;
using GFLAGS_NAMESPACE::GetCommandLineFlagInfo;
using GFLAGS_NAMESPACE::GetCommandLineFlagInfoOrDie;
using GFLAGS_NAMESPACE::FlagSettingMode;
using GFLAGS_NAMESPACE::SET_FLAGS_VALUE;
using GFLAGS_NAMESPACE::SET_FLAG_IF_DEFAULT;
using GFLAGS_NAMESPACE::SET_FLAGS_DEFAULT;
using GFLAGS_NAMESPACE::SetCommandLineOption;
using GFLAGS_NAMESPACE::SetCommandLineOptionWithMode;
using GFLAGS_NAMESPACE::FlagSaver;
using GFLAGS_NAMESPACE::CommandlineFlagsIntoString;
using GFLAGS_NAMESPACE::ReadFlagsFromString;
using GFLAGS_NAMESPACE::AppendFlagsIntoFile;
using GFLAGS_NAMESPACE::ReadFromFlagsFile;
using GFLAGS_NAMESPACE::BoolFromEnv;
using GFLAGS_NAMESPACE::Int32FromEnv;
using GFLAGS_NAMESPACE::Uint32FromEnv;
using GFLAGS_NAMESPACE::Int64FromEnv;
using GFLAGS_NAMESPACE::Uint64FromEnv;
using GFLAGS_NAMESPACE::DoubleFromEnv;
using GFLAGS_NAMESPACE::StringFromEnv;
using GFLAGS_NAMESPACE::SetUsageMessage;
using GFLAGS_NAMESPACE::SetVersionString;
using GFLAGS_NAMESPACE::ParseCommandLineNonHelpFlags;
using GFLAGS_NAMESPACE::HandleCommandLineHelpFlags;
using GFLAGS_NAMESPACE::AllowCommandLineReparsing;
using GFLAGS_NAMESPACE::ReparseCommandLineNonHelpFlags;
using GFLAGS_NAMESPACE::ShutDownCommandLineFlags;
using GFLAGS_NAMESPACE::FlagRegisterer;
#ifndef SWIG
using GFLAGS_NAMESPACE::ParseCommandLineFlags;
#endif
} // namespace gflags
#endif // GFLAGS_NS_GFLAGS_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/gflags/gflags_gflags.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 860
|
```objective-c
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
//
// Revamped and reorganized by Craig Silverstein
//
// This is the file that should be included by any file which declares
// command line flag.
#ifndef GFLAGS_DECLARE_H_
#define GFLAGS_DECLARE_H_
// your_sha256_hash-----------
// Namespace of gflags library symbols.
#define GFLAGS_NAMESPACE google
// your_sha256_hash-----------
// Windows DLL import/export.
// Whether gflags library is a DLL.
//
// Set to 1 by default when the shared gflags library was built on Windows.
// Must be overwritten when this header file is used with the optionally also
// built static library instead; set by CMake's INTERFACE_COMPILE_DEFINITIONS.
#ifndef GFLAGS_IS_A_DLL
# define GFLAGS_IS_A_DLL 1
#endif
// We always want to import the symbols of the gflags library.
#ifndef GFLAGS_DLL_DECL
# if GFLAGS_IS_A_DLL && defined(_MSC_VER)
# define GFLAGS_DLL_DECL __declspec(dllimport)
# else
# define GFLAGS_DLL_DECL
# endif
#endif
// We always want to import variables declared in user code.
#ifndef GFLAGS_DLL_DECLARE_FLAG
# if GFLAGS_IS_A_DLL && defined(_MSC_VER)
# define GFLAGS_DLL_DECLARE_FLAG __declspec(dllimport)
# else
# define GFLAGS_DLL_DECLARE_FLAG
# endif
#endif
// your_sha256_hash-----------
// Flag types
#include <string>
#if 1
# include <stdint.h> // the normal place uint32_t is defined
#elif 1
# include <sys/types.h> // the normal place u_int32_t is defined
#elif 1
# include <inttypes.h> // a third place for uint32_t or u_int32_t
#endif
namespace GFLAGS_NAMESPACE {
#if 1 // C99
typedef int32_t int32;
typedef uint32_t uint32;
typedef int64_t int64;
typedef uint64_t uint64;
#elif 0 // BSD
typedef int32_t int32;
typedef u_int32_t uint32;
typedef int64_t int64;
typedef u_int64_t uint64;
#elif 0 // Windows
typedef __int32 int32;
typedef unsigned __int32 uint32;
typedef __int64 int64;
typedef unsigned __int64 uint64;
#else
# error Do not know how to define a 32-bit integer quantity on your system
#endif
} // namespace GFLAGS_NAMESPACE
namespace fLS {
// The meaning of "string" might be different between now and when the
// macros below get invoked (e.g., if someone is experimenting with
// other string implementations that get defined after this file is
// included). Save the current meaning now and use it in the macros.
typedef std::string clstring;
} // namespace fLS
#define DECLARE_VARIABLE(type, shorttype, name) \
/* We always want to import declared variables, dll or no */ \
namespace fL##shorttype { extern GFLAGS_DLL_DECLARE_FLAG type FLAGS_##name; } \
using fL##shorttype::FLAGS_##name
#define DECLARE_bool(name) \
DECLARE_VARIABLE(bool, B, name)
#define DECLARE_int32(name) \
DECLARE_VARIABLE(::GFLAGS_NAMESPACE::int32, I, name)
#define DECLARE_uint32(name) \
DECLARE_VARIABLE(::GFLAGS_NAMESPACE::uint32, U, name)
#define DECLARE_int64(name) \
DECLARE_VARIABLE(::GFLAGS_NAMESPACE::int64, I64, name)
#define DECLARE_uint64(name) \
DECLARE_VARIABLE(::GFLAGS_NAMESPACE::uint64, U64, name)
#define DECLARE_double(name) \
DECLARE_VARIABLE(double, D, name)
#define DECLARE_string(name) \
/* We always want to import declared variables, dll or no */ \
namespace fLS { \
using ::fLS::clstring; \
extern GFLAGS_DLL_DECLARE_FLAG ::fLS::clstring& FLAGS_##name; \
} \
using fLS::FLAGS_##name
#endif // GFLAGS_DECLARE_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/gflags/gflags_declare.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,164
|
```objective-c
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Revamped and reorganized by Craig Silverstein
//
// This is the file that should be included by any file which declares
// or defines a command line flag or wants to parse command line flags
// or print a program usage message (which will include information about
// flags). Executive summary, in the form of an example foo.cc file:
//
// #include "foo.h" // foo.h has a line "DECLARE_int32(start);"
// #include "validators.h" // hypothetical file defining ValidateIsFile()
//
// DEFINE_int32(end, 1000, "The last record to read");
//
// DEFINE_string(filename, "my_file.txt", "The file to read");
// // Crash if the specified file does not exist.
// static bool dummy = RegisterFlagValidator(&FLAGS_filename,
// &ValidateIsFile);
//
// DECLARE_bool(verbose); // some other file has a DEFINE_bool(verbose, ...)
//
// void MyFunc() {
// if (FLAGS_verbose) printf("Records %d-%d\n", FLAGS_start, FLAGS_end);
// }
//
// Then, at the command-line:
// ./foo --noverbose --start=5 --end=100
//
// For more details, see
// doc/gflags.html
//
// --- A note about thread-safety:
//
// We describe many functions in this routine as being thread-hostile,
// thread-compatible, or thread-safe. Here are the meanings we use:
//
// thread-safe: it is safe for multiple threads to call this routine
// (or, when referring to a class, methods of this class)
// concurrently.
// thread-hostile: it is not safe for multiple threads to call this
// routine (or methods of this class) concurrently. In gflags,
// most thread-hostile routines are intended to be called early in,
// or even before, main() -- that is, before threads are spawned.
// thread-compatible: it is safe for multiple threads to read from
// this variable (when applied to variables), or to call const
// methods of this class (when applied to classes), as long as no
// other thread is writing to the variable or calling non-const
// methods of this class.
#ifndef GFLAGS_GFLAGS_H_
#define GFLAGS_GFLAGS_H_
#include <string>
#include <vector>
#include "gflags/gflags_declare.h" // IWYU pragma: export
// We always want to export variables defined in user code
#ifndef GFLAGS_DLL_DEFINE_FLAG
# ifdef _MSC_VER
# define GFLAGS_DLL_DEFINE_FLAG __declspec(dllexport)
# else
# define GFLAGS_DLL_DEFINE_FLAG
# endif
#endif
namespace GFLAGS_NAMESPACE {
// your_sha256_hash----
// To actually define a flag in a file, use DEFINE_bool,
// DEFINE_string, etc. at the bottom of this file. You may also find
// it useful to register a validator with the flag. This ensures that
// when the flag is parsed from the commandline, or is later set via
// SetCommandLineOption, we call the validation function. It is _not_
// called when you assign the value to the flag directly using the = operator.
//
// The validation function should return true if the flag value is valid, and
// false otherwise. If the function returns false for the new setting of the
// flag, the flag will retain its current value. If it returns false for the
// default value, ParseCommandLineFlags() will die.
//
// This function is safe to call at global construct time (as in the
// example below).
//
// Example use:
// static bool ValidatePort(const char* flagname, int32 value) {
// if (value > 0 && value < 32768) // value is ok
// return true;
// printf("Invalid value for --%s: %d\n", flagname, (int)value);
// return false;
// }
// DEFINE_int32(port, 0, "What port to listen on");
// static bool dummy = RegisterFlagValidator(&FLAGS_port, &ValidatePort);
// Returns true if successfully registered, false if not (because the
// first argument doesn't point to a command-line flag, or because a
// validator is already registered for this flag).
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const bool* flag, bool (*validate_fn)(const char*, bool));
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const int32* flag, bool (*validate_fn)(const char*, int32));
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const uint32* flag, bool (*validate_fn)(const char*, uint32));
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const int64* flag, bool (*validate_fn)(const char*, int64));
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const uint64* flag, bool (*validate_fn)(const char*, uint64));
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const double* flag, bool (*validate_fn)(const char*, double));
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const std::string* flag, bool (*validate_fn)(const char*, const std::string&));
// Convenience macro for the registration of a flag validator
#define DEFINE_validator(name, validator) \
static const bool name##_validator_registered = \
GFLAGS_NAMESPACE::RegisterFlagValidator(&FLAGS_##name, validator)
// your_sha256_hash----
// These methods are the best way to get access to info about the
// list of commandline flags. Note that these routines are pretty slow.
// GetAllFlags: mostly-complete info about the list, sorted by file.
// ShowUsageWithFlags: pretty-prints the list to stdout (what --help does)
// ShowUsageWithFlagsRestrict: limit to filenames with restrict as a substr
//
// In addition to accessing flags, you can also access argv[0] (the program
// name) and argv (the entire commandline), which we sock away a copy of.
// These variables are static, so you should only set them once.
//
// No need to export this data only structure from DLL, avoiding VS warning 4251.
struct CommandLineFlagInfo {
std::string name; // the name of the flag
std::string type; // the type of the flag: int32, etc
std::string description; // the "help text" associated with the flag
std::string current_value; // the current value, as a string
std::string default_value; // the default value, as a string
std::string filename; // 'cleaned' version of filename holding the flag
bool has_validator_fn; // true if RegisterFlagValidator called on this flag
bool is_default; // true if the flag has the default value and
// has not been set explicitly from the cmdline
// or via SetCommandLineOption
const void* flag_ptr; // pointer to the flag's current value (i.e. FLAGS_foo)
};
// Using this inside of a validator is a recipe for a deadlock.
// TODO(user) Fix locking when validators are running, to make it safe to
// call validators during ParseAllFlags.
// Also make sure then to uncomment the corresponding unit test in
// gflags_unittest.sh
extern GFLAGS_DLL_DECL void GetAllFlags(std::vector<CommandLineFlagInfo>* OUTPUT);
// These two are actually defined in gflags_reporting.cc.
extern GFLAGS_DLL_DECL void ShowUsageWithFlags(const char *argv0); // what --help does
extern GFLAGS_DLL_DECL void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict);
// Create a descriptive string for a flag.
// Goes to some trouble to make pretty line breaks.
extern GFLAGS_DLL_DECL std::string DescribeOneFlag(const CommandLineFlagInfo& flag);
// Thread-hostile; meant to be called before any threads are spawned.
extern GFLAGS_DLL_DECL void SetArgv(int argc, const char** argv);
// The following functions are thread-safe as long as SetArgv() is
// only called before any threads start.
extern GFLAGS_DLL_DECL const std::vector<std::string>& GetArgvs();
extern GFLAGS_DLL_DECL const char* GetArgv(); // all of argv as a string
extern GFLAGS_DLL_DECL const char* GetArgv0(); // only argv0
extern GFLAGS_DLL_DECL uint32 GetArgvSum(); // simple checksum of argv
extern GFLAGS_DLL_DECL const char* ProgramInvocationName(); // argv0, or "UNKNOWN" if not set
extern GFLAGS_DLL_DECL const char* ProgramInvocationShortName(); // basename(argv0)
// ProgramUsage() is thread-safe as long as SetUsageMessage() is only
// called before any threads start.
extern GFLAGS_DLL_DECL const char* ProgramUsage(); // string set by SetUsageMessage()
// VersionString() is thread-safe as long as SetVersionString() is only
// called before any threads start.
extern GFLAGS_DLL_DECL const char* VersionString(); // string set by SetVersionString()
// your_sha256_hash----
// Normally you access commandline flags by just saying "if (FLAGS_foo)"
// or whatever, and set them by calling "FLAGS_foo = bar" (or, more
// commonly, via the DEFINE_foo macro). But if you need a bit more
// control, we have programmatic ways to get/set the flags as well.
// These programmatic ways to access flags are thread-safe, but direct
// access is only thread-compatible.
// Return true iff the flagname was found.
// OUTPUT is set to the flag's value, or unchanged if we return false.
extern GFLAGS_DLL_DECL bool GetCommandLineOption(const char* name, std::string* OUTPUT);
// Return true iff the flagname was found. OUTPUT is set to the flag's
// CommandLineFlagInfo or unchanged if we return false.
extern GFLAGS_DLL_DECL bool GetCommandLineFlagInfo(const char* name, CommandLineFlagInfo* OUTPUT);
// Return the CommandLineFlagInfo of the flagname. exit() if name not found.
// Example usage, to check if a flag's value is currently the default value:
// if (GetCommandLineFlagInfoOrDie("foo").is_default) ...
extern GFLAGS_DLL_DECL CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name);
enum GFLAGS_DLL_DECL FlagSettingMode {
// update the flag's value (can call this multiple times).
SET_FLAGS_VALUE,
// update the flag's value, but *only if* it has not yet been updated
// with SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef".
SET_FLAG_IF_DEFAULT,
// set the flag's default value to this. If the flag has not yet updated
// yet (via SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef")
// change the flag's current value to the new default value as well.
SET_FLAGS_DEFAULT
};
// Set a particular flag ("command line option"). Returns a string
// describing the new value that the option has been set to. The
// return value API is not well-specified, so basically just depend on
// it to be empty if the setting failed for some reason -- the name is
// not a valid flag name, or the value is not a valid value -- and
// non-empty else.
// SetCommandLineOption uses set_mode == SET_FLAGS_VALUE (the common case)
extern GFLAGS_DLL_DECL std::string SetCommandLineOption (const char* name, const char* value);
extern GFLAGS_DLL_DECL std::string SetCommandLineOptionWithMode(const char* name, const char* value, FlagSettingMode set_mode);
// your_sha256_hash----
// Saves the states (value, default value, whether the user has set
// the flag, registered validators, etc) of all flags, and restores
// them when the FlagSaver is destroyed. This is very useful in
// tests, say, when you want to let your tests change the flags, but
// make sure that they get reverted to the original states when your
// test is complete.
//
// Example usage:
// void TestFoo() {
// FlagSaver s1;
// FLAG_foo = false;
// FLAG_bar = "some value";
//
// // test happens here. You can return at any time
// // without worrying about restoring the FLAG values.
// }
//
// Note: This class is marked with GFLAGS_ATTRIBUTE_UNUSED because all
// the work is done in the constructor and destructor, so in the standard
// usage example above, the compiler would complain that it's an
// unused variable.
//
// This class is thread-safe. However, its destructor writes to
// exactly the set of flags that have changed value during its
// lifetime, so concurrent _direct_ access to those flags
// (i.e. FLAGS_foo instead of {Get,Set}CommandLineOption()) is unsafe.
class GFLAGS_DLL_DECL FlagSaver {
public:
FlagSaver();
~FlagSaver();
private:
class FlagSaverImpl* impl_; // we use pimpl here to keep API steady
FlagSaver(const FlagSaver&); // no copying!
void operator=(const FlagSaver&);
};
// your_sha256_hash----
// Some deprecated or hopefully-soon-to-be-deprecated functions.
// This is often used for logging. TODO(csilvers): figure out a better way
extern GFLAGS_DLL_DECL std::string CommandlineFlagsIntoString();
// Usually where this is used, a FlagSaver should be used instead.
extern GFLAGS_DLL_DECL
bool ReadFlagsFromString(const std::string& flagfilecontents,
const char* prog_name,
bool errors_are_fatal); // uses SET_FLAGS_VALUE
// These let you manually implement --flagfile functionality.
// DEPRECATED.
extern GFLAGS_DLL_DECL bool AppendFlagsIntoFile(const std::string& filename, const char* prog_name);
extern GFLAGS_DLL_DECL bool ReadFromFlagsFile(const std::string& filename, const char* prog_name, bool errors_are_fatal); // uses SET_FLAGS_VALUE
// your_sha256_hash----
// Useful routines for initializing flags from the environment.
// In each case, if 'varname' does not exist in the environment
// return defval. If 'varname' does exist but is not valid
// (e.g., not a number for an int32 flag), abort with an error.
// Otherwise, return the value. NOTE: for booleans, for true use
// 't' or 'T' or 'true' or '1', for false 'f' or 'F' or 'false' or '0'.
extern GFLAGS_DLL_DECL bool BoolFromEnv(const char *varname, bool defval);
extern GFLAGS_DLL_DECL int32 Int32FromEnv(const char *varname, int32 defval);
extern GFLAGS_DLL_DECL uint32 Uint32FromEnv(const char *varname, uint32 defval);
extern GFLAGS_DLL_DECL int64 Int64FromEnv(const char *varname, int64 defval);
extern GFLAGS_DLL_DECL uint64 Uint64FromEnv(const char *varname, uint64 defval);
extern GFLAGS_DLL_DECL double DoubleFromEnv(const char *varname, double defval);
extern GFLAGS_DLL_DECL const char *StringFromEnv(const char *varname, const char *defval);
// your_sha256_hash----
// The next two functions parse gflags from main():
// Set the "usage" message for this program. For example:
// string usage("This program does nothing. Sample usage:\n");
// usage += argv[0] + " <uselessarg1> <uselessarg2>";
// SetUsageMessage(usage);
// Do not include commandline flags in the usage: we do that for you!
// Thread-hostile; meant to be called before any threads are spawned.
extern GFLAGS_DLL_DECL void SetUsageMessage(const std::string& usage);
// Sets the version string, which is emitted with --version.
// For instance: SetVersionString("1.3");
// Thread-hostile; meant to be called before any threads are spawned.
extern GFLAGS_DLL_DECL void SetVersionString(const std::string& version);
// Looks for flags in argv and parses them. Rearranges argv to put
// flags first, or removes them entirely if remove_flags is true.
// If a flag is defined more than once in the command line or flag
// file, the last definition is used. Returns the index (into argv)
// of the first non-flag argument.
// See top-of-file for more details on this function.
#ifndef SWIG // In swig, use ParseCommandLineFlagsScript() instead.
extern GFLAGS_DLL_DECL uint32 ParseCommandLineFlags(int *argc, char*** argv, bool remove_flags);
#endif
// Calls to ParseCommandLineNonHelpFlags and then to
// HandleCommandLineHelpFlags can be used instead of a call to
// ParseCommandLineFlags during initialization, in order to allow for
// changing default values for some FLAGS (via
// e.g. SetCommandLineOptionWithMode calls) between the time of
// command line parsing and the time of dumping help information for
// the flags as a result of command line parsing. If a flag is
// defined more than once in the command line or flag file, the last
// definition is used. Returns the index (into argv) of the first
// non-flag argument. (If remove_flags is true, will always return 1.)
extern GFLAGS_DLL_DECL uint32 ParseCommandLineNonHelpFlags(int *argc, char*** argv, bool remove_flags);
// This is actually defined in gflags_reporting.cc.
// This function is misnamed (it also handles --version, etc.), but
// it's too late to change that now. :-(
extern GFLAGS_DLL_DECL void HandleCommandLineHelpFlags(); // in gflags_reporting.cc
// Allow command line reparsing. Disables the error normally
// generated when an unknown flag is found, since it may be found in a
// later parse. Thread-hostile; meant to be called before any threads
// are spawned.
extern GFLAGS_DLL_DECL void AllowCommandLineReparsing();
// Reparse the flags that have not yet been recognized. Only flags
// registered since the last parse will be recognized. Any flag value
// must be provided as part of the argument using "=", not as a
// separate command line argument that follows the flag argument.
// Intended for handling flags from dynamically loaded libraries,
// since their flags are not registered until they are loaded.
extern GFLAGS_DLL_DECL void ReparseCommandLineNonHelpFlags();
// Clean up memory allocated by flags. This is only needed to reduce
// the quantity of "potentially leaked" reports emitted by memory
// debugging tools such as valgrind. It is not required for normal
// operation, or for the google perftools heap-checker. It must only
// be called when the process is about to exit, and all threads that
// might access flags are quiescent. Referencing flags after this is
// called will have unexpected consequences. This is not safe to run
// when multiple threads might be running: the function is
// thread-hostile.
extern GFLAGS_DLL_DECL void ShutDownCommandLineFlags();
// your_sha256_hash----
// Now come the command line flag declaration/definition macros that
// will actually be used. They're kind of hairy. A major reason
// for this is initialization: we want people to be able to access
// variables in global constructors and have that not crash, even if
// their global constructor runs before the global constructor here.
// (Obviously, we can't guarantee the flags will have the correct
// default value in that case, but at least accessing them is safe.)
// The only way to do that is have flags point to a static buffer.
// So we make one, using a union to ensure proper alignment, and
// then use placement-new to actually set up the flag with the
// correct default value. In the same vein, we have to worry about
// flag access in global destructors, so FlagRegisterer has to be
// careful never to destroy the flag-values it constructs.
//
// Note that when we define a flag variable FLAGS_<name>, we also
// preemptively define a junk variable, FLAGS_no<name>. This is to
// cause a link-time error if someone tries to define 2 flags with
// names like "logging" and "nologging". We do this because a bool
// flag FLAG can be set from the command line to true with a "-FLAG"
// argument, and to false with a "-noFLAG" argument, and so this can
// potentially avert confusion.
//
// We also put flags into their own namespace. It is purposefully
// named in an opaque way that people should have trouble typing
// directly. The idea is that DEFINE puts the flag in the weird
// namespace, and DECLARE imports the flag from there into the current
// namespace. The net result is to force people to use DECLARE to get
// access to a flag, rather than saying "extern GFLAGS_DLL_DECL bool FLAGS_whatever;"
// or some such instead. We want this so we can put extra
// functionality (like sanity-checking) in DECLARE if we want, and
// make sure it is picked up everywhere.
//
// We also put the type of the variable in the namespace, so that
// people can't DECLARE_int32 something that they DEFINE_bool'd
// elsewhere.
class GFLAGS_DLL_DECL FlagRegisterer {
public:
// We instantiate this template ctor for all supported types,
// so it is possible to place implementation of the FlagRegisterer ctor in
// .cc file.
// Calling this constructor with unsupported type will produce linker error.
template <typename FlagType>
FlagRegisterer(const char* name,
const char* help, const char* filename,
FlagType* current_storage, FlagType* defvalue_storage);
};
// If your application #defines STRIP_FLAG_HELP to a non-zero value
// before #including this file, we remove the help message from the
// binary file. This can reduce the size of the resulting binary
// somewhat, and may also be useful for security reasons.
extern GFLAGS_DLL_DECL const char kStrippedFlagHelp[];
} // namespace GFLAGS_NAMESPACE
#ifndef SWIG // In swig, ignore the main flag declarations
#if defined(STRIP_FLAG_HELP) && STRIP_FLAG_HELP > 0
// Need this construct to avoid the 'defined but not used' warning.
#define MAYBE_STRIPPED_HELP(txt) \
(false ? (txt) : GFLAGS_NAMESPACE::kStrippedFlagHelp)
#else
#define MAYBE_STRIPPED_HELP(txt) txt
#endif
// Each command-line flag has two variables associated with it: one
// with the current value, and one with the default value. However,
// we have a third variable, which is where value is assigned; it's a
// constant. This guarantees that FLAG_##value is initialized at
// static initialization time (e.g. before program-start) rather than
// than global construction time (which is after program-start but
// before main), at least when 'value' is a compile-time constant. We
// use a small trick for the "default value" variable, and call it
// FLAGS_no<name>. This serves the second purpose of assuring a
// compile error if someone tries to define a flag named no<name>
// which is illegal (--foo and --nofoo both affect the "foo" flag).
#define DEFINE_VARIABLE(type, shorttype, name, value, help) \
namespace fL##shorttype { \
static const type FLAGS_nono##name = value; \
/* We always want to export defined variables, dll or no */ \
GFLAGS_DLL_DEFINE_FLAG type FLAGS_##name = FLAGS_nono##name; \
type FLAGS_no##name = FLAGS_nono##name; \
static GFLAGS_NAMESPACE::FlagRegisterer o_##name( \
#name, MAYBE_STRIPPED_HELP(help), __FILE__, \
&FLAGS_##name, &FLAGS_no##name); \
} \
using fL##shorttype::FLAGS_##name
// For DEFINE_bool, we want to do the extra check that the passed-in
// value is actually a bool, and not a string or something that can be
// coerced to a bool. These declarations (no definition needed!) will
// help us do that, and never evaluate From, which is important.
// We'll use 'sizeof(IsBool(val))' to distinguish. This code requires
// that the compiler have different sizes for bool & double. Since
// this is not guaranteed by the standard, we check it with a
// COMPILE_ASSERT.
namespace fLB {
struct CompileAssert {};
typedef CompileAssert expected_sizeof_double_neq_sizeof_bool[
(sizeof(double) != sizeof(bool)) ? 1 : -1];
template<typename From> double GFLAGS_DLL_DECL IsBoolFlag(const From& from);
GFLAGS_DLL_DECL bool IsBoolFlag(bool from);
} // namespace fLB
// Here are the actual DEFINE_*-macros. The respective DECLARE_*-macros
// are in a separate include, gflags_declare.h, for reducing
// the physical transitive size for DECLARE use.
#define DEFINE_bool(name, val, txt) \
namespace fLB { \
typedef ::fLB::CompileAssert FLAG_##name##_value_is_not_a_bool[ \
(sizeof(::fLB::IsBoolFlag(val)) != sizeof(double))? 1: -1]; \
} \
DEFINE_VARIABLE(bool, B, name, val, txt)
#define DEFINE_int32(name, val, txt) \
DEFINE_VARIABLE(GFLAGS_NAMESPACE::int32, I, \
name, val, txt)
#define DEFINE_uint32(name,val, txt) \
DEFINE_VARIABLE(GFLAGS_NAMESPACE::uint32, U, \
name, val, txt)
#define DEFINE_int64(name, val, txt) \
DEFINE_VARIABLE(GFLAGS_NAMESPACE::int64, I64, \
name, val, txt)
#define DEFINE_uint64(name,val, txt) \
DEFINE_VARIABLE(GFLAGS_NAMESPACE::uint64, U64, \
name, val, txt)
#define DEFINE_double(name, val, txt) \
DEFINE_VARIABLE(double, D, name, val, txt)
// Strings are trickier, because they're not a POD, so we can't
// construct them at static-initialization time (instead they get
// constructed at global-constructor time, which is much later). To
// try to avoid crashes in that case, we use a char buffer to store
// the string, which we can static-initialize, and then placement-new
// into it later. It's not perfect, but the best we can do.
namespace fLS {
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
const char *value) {
return new(stringspot) clstring(value);
}
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
const clstring &value) {
return new(stringspot) clstring(value);
}
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
int value);
// Auxiliary class used to explicitly call destructor of string objects
// allocated using placement new during static program deinitialization.
// The destructor MUST be an inline function such that the explicit
// destruction occurs in the same compilation unit as the placement new.
class StringFlagDestructor {
void *current_storage_;
void *defvalue_storage_;
public:
StringFlagDestructor(void *current, void *defvalue)
: current_storage_(current), defvalue_storage_(defvalue) {}
~StringFlagDestructor() {
reinterpret_cast<clstring*>(current_storage_ )->~clstring();
reinterpret_cast<clstring*>(defvalue_storage_)->~clstring();
}
};
} // namespace fLS
// We need to define a var named FLAGS_no##name so people don't define
// --string and --nostring. And we need a temporary place to put val
// so we don't have to evaluate it twice. Two great needs that go
// great together!
// The weird 'using' + 'extern' inside the fLS namespace is to work around
// an unknown compiler bug/issue with the gcc 4.2.1 on SUSE 10. See
// path_to_url
#define DEFINE_string(name, val, txt) \
namespace fLS { \
using ::fLS::clstring; \
using ::fLS::StringFlagDestructor; \
static union { void* align; char s[sizeof(clstring)]; } s_##name[2]; \
clstring* const FLAGS_no##name = ::fLS:: \
dont_pass0toDEFINE_string(s_##name[0].s, \
val); \
static GFLAGS_NAMESPACE::FlagRegisterer o_##name( \
#name, MAYBE_STRIPPED_HELP(txt), __FILE__, \
FLAGS_no##name, new (s_##name[1].s) clstring(*FLAGS_no##name)); \
static StringFlagDestructor d_##name(s_##name[0].s, s_##name[1].s); \
extern GFLAGS_DLL_DEFINE_FLAG clstring& FLAGS_##name; \
using fLS::FLAGS_##name; \
clstring& FLAGS_##name = *FLAGS_no##name; \
} \
using fLS::FLAGS_##name
#endif // SWIG
// Import gflags library symbols into alternative/deprecated namespace(s)
#include "gflags_gflags.h"
#endif // GFLAGS_GFLAGS_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/gflags/gflags.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 6,702
|
```objective-c
//
//
// path_to_url
//
// Unless required by applicable law or agreed to in writing, software
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// Disclaimer: This is not an official Google product.
//
// Author: Jyrki Alakuijala (jyrki.alakuijala@gmail.com)
#ifndef BUTTERAUGLI_BUTTERAUGLI_H_
#define BUTTERAUGLI_BUTTERAUGLI_H_
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <vector>
#ifndef PROFILER_ENABLED
#define PROFILER_ENABLED 0
#endif
#if PROFILER_ENABLED
#else
#define PROFILER_FUNC
#define PROFILER_ZONE(name)
#endif
#define BUTTERAUGLI_ENABLE_CHECKS 0
// This is the main interface to butteraugli image similarity
// analysis function.
namespace butteraugli {
template<typename T>
class Image;
using Image8 = Image<uint8_t>;
using ImageF = Image<float>;
using ImageD = Image<double>;
// ButteraugliInterface defines the public interface for butteraugli.
//
// It calculates the difference between rgb0 and rgb1.
//
// rgb0 and rgb1 contain the images. rgb0[c][px] and rgb1[c][px] contains
// the red image for c == 0, green for c == 1, blue for c == 2. Location index
// px is calculated as y * xsize + x.
//
// Value of pixels of images rgb0 and rgb1 need to be represented as raw
// intensity. Most image formats store gamma corrected intensity in pixel
// values. This gamma correction has to be removed, by applying the following
// function:
// butteraugli_val = 255.0 * pow(png_val / 255.0, gamma);
// A typical value of gamma is 2.2. It is usually stored in the image header.
// Take care not to confuse that value with its inverse. The gamma value should
// be always greater than one.
// Butteraugli does not work as intended if the caller does not perform
// gamma correction.
//
// diffmap will contain an image of the size xsize * ysize, containing
// localized differences for values px (indexed with the px the same as rgb0
// and rgb1). diffvalue will give a global score of similarity.
//
// A diffvalue smaller than kButteraugliGood indicates that images can be
// observed as the same image.
// diffvalue larger than kButteraugliBad indicates that a difference between
// the images can be observed.
// A diffvalue between kButteraugliGood and kButteraugliBad indicates that
// a subtle difference can be observed between the images.
//
// Returns true on success.
bool ButteraugliInterface(const std::vector<ImageF> &rgb0,
const std::vector<ImageF> &rgb1,
ImageF &diffmap,
double &diffvalue);
const double kButteraugliQuantLow = 0.26;
const double kButteraugliQuantHigh = 1.454;
// Converts the butteraugli score into fuzzy class values that are continuous
// at the class boundary. The class boundary location is based on human
// raters, but the slope is arbitrary. Particularly, it does not reflect
// the expectation value of probabilities of the human raters. It is just
// expected that a smoother class boundary will allow for higher-level
// optimization algorithms to work faster.
//
// Returns 2.0 for a perfect match, and 1.0 for 'ok', 0.0 for bad. Because the
// scoring is fuzzy, a butteraugli score of 0.96 would return a class of
// around 1.9.
double ButteraugliFuzzyClass(double score);
// Input values should be in range 0 (bad) to 2 (good). Use
// kButteraugliNormalization as normalization.
double ButteraugliFuzzyInverse(double seek);
// Returns a map which can be used for adaptive quantization. Values can
// typically range from kButteraugliQuantLow to kButteraugliQuantHigh. Low
// values require coarse quantization (e.g. near random noise), high values
// require fine quantization (e.g. in smooth bright areas).
bool ButteraugliAdaptiveQuantization(size_t xsize, size_t ysize,
const std::vector<std::vector<float> > &rgb, std::vector<float> &quant);
// Implementation details, don't use anything below or your code will
// break in the future.
#ifdef _MSC_VER
#define BUTTERAUGLI_RESTRICT
#else
#define BUTTERAUGLI_RESTRICT __restrict__
#endif
#ifdef _MSC_VER
#define BUTTERAUGLI_CACHE_ALIGNED_RETURN /* not supported */
#else
#define BUTTERAUGLI_CACHE_ALIGNED_RETURN __attribute__((assume_aligned(64)))
#endif
// Alias for unchangeable, non-aliased pointers. T is a pointer type,
// possibly to a const type. Example: ConstRestrict<uint8_t*> ptr = nullptr.
// The conventional syntax uint8_t* const RESTRICT is more confusing - it is
// not immediately obvious that the pointee is non-const.
template <typename T>
using ConstRestrict = T const BUTTERAUGLI_RESTRICT;
// Functions that depend on the cache line size.
class CacheAligned {
public:
static constexpr size_t kPointerSize = sizeof(void *);
static constexpr size_t kCacheLineSize = 64;
// The aligned-return annotation is only allowed on function declarations.
static void *Allocate(const size_t bytes) BUTTERAUGLI_CACHE_ALIGNED_RETURN;
static void Free(void *aligned_pointer);
};
template <typename T>
using CacheAlignedUniquePtrT = std::unique_ptr<T[], void (*)(void *)>;
using CacheAlignedUniquePtr = CacheAlignedUniquePtrT<uint8_t>;
template <typename T = uint8_t>
static inline CacheAlignedUniquePtrT<T> Allocate(const size_t entries) {
return CacheAlignedUniquePtrT<T>(
static_cast<ConstRestrict<T *>>(
CacheAligned::Allocate(entries * sizeof(T))),
CacheAligned::Free);
}
// Returns the smallest integer not less than "amount" that is divisible by
// "multiple", which must be a power of two.
template <size_t multiple>
static inline size_t Align(const size_t amount) {
static_assert(multiple != 0 && ((multiple & (multiple - 1)) == 0),
"Align<> argument must be a power of two");
return (amount + multiple - 1) & ~(multiple - 1);
}
// Single channel, contiguous (cache-aligned) rows separated by padding.
// T must be POD.
//
// Rationale: vectorization benefits from aligned operands - unaligned loads and
// especially stores are expensive when the address crosses cache line
// boundaries. Introducing padding after each row ensures the start of a row is
// aligned, and that row loops can process entire vectors (writes to the padding
// are allowed and ignored).
//
// We prefer a planar representation, where channels are stored as separate
// 2D arrays, because that simplifies vectorization (repeating the same
// operation on multiple adjacent components) without the complexity of a
// hybrid layout (8 R, 8 G, 8 B, ...). In particular, clients can easily iterate
// over all components in a row and Image requires no knowledge of the pixel
// format beyond the component type "T". The downside is that we duplicate the
// xsize/ysize members for each channel.
//
// This image layout could also be achieved with a vector and a row accessor
// function, but a class wrapper with support for "deleter" allows wrapping
// existing memory allocated by clients without copying the pixels. It also
// provides convenient accessors for xsize/ysize, which shortens function
// argument lists. Supports move-construction so it can be stored in containers.
template <typename ComponentType>
class Image {
// Returns cache-aligned row stride, being careful to avoid 2K aliasing.
static size_t BytesPerRow(const size_t xsize) {
// Allow reading one extra AVX-2 vector on the right margin.
const size_t row_size = xsize * sizeof(T) + 32;
const size_t align = CacheAligned::kCacheLineSize;
size_t bytes_per_row = (row_size + align - 1) & ~(align - 1);
// During the lengthy window before writes are committed to memory, CPUs
// guard against read after write hazards by checking the address, but
// only the lower 11 bits. We avoid a false dependency between writes to
// consecutive rows by ensuring their sizes are not multiples of 2 KiB.
if (bytes_per_row % 2048 == 0) {
bytes_per_row += align;
}
return bytes_per_row;
}
public:
using T = ComponentType;
Image() : xsize_(0), ysize_(0), bytes_per_row_(0), bytes_(static_cast<uint8_t*>(nullptr), Ignore) {}
Image(const size_t xsize, const size_t ysize)
: xsize_(xsize),
ysize_(ysize),
bytes_per_row_(BytesPerRow(xsize)),
bytes_(Allocate(bytes_per_row_ * ysize)) {}
Image(const size_t xsize, const size_t ysize, ConstRestrict<uint8_t *> bytes,
const size_t bytes_per_row)
: xsize_(xsize),
ysize_(ysize),
bytes_per_row_(bytes_per_row),
bytes_(bytes, Ignore) {}
// Move constructor (required for returning Image from function)
Image(Image &&other)
: xsize_(other.xsize_),
ysize_(other.ysize_),
bytes_per_row_(other.bytes_per_row_),
bytes_(std::move(other.bytes_)) {}
// Move assignment (required for std::vector)
Image &operator=(Image &&other) {
xsize_ = other.xsize_;
ysize_ = other.ysize_;
bytes_per_row_ = other.bytes_per_row_;
bytes_ = std::move(other.bytes_);
return *this;
}
void Swap(Image &other) {
std::swap(xsize_, other.xsize_);
std::swap(ysize_, other.ysize_);
std::swap(bytes_per_row_, other.bytes_per_row_);
std::swap(bytes_, other.bytes_);
}
// How many pixels.
size_t xsize() const { return xsize_; }
size_t ysize() const { return ysize_; }
ConstRestrict<T *> Row(const size_t y) BUTTERAUGLI_CACHE_ALIGNED_RETURN {
#ifdef BUTTERAUGLI_ENABLE_CHECKS
if (y >= ysize_) {
printf("Row %zu out of bounds (ysize=%zu)\n", y, ysize_);
abort();
}
#endif
return reinterpret_cast<T *>(bytes_.get() + y * bytes_per_row_);
}
ConstRestrict<const T *> Row(const size_t y) const
BUTTERAUGLI_CACHE_ALIGNED_RETURN {
#ifdef BUTTERAUGLI_ENABLE_CHECKS
if (y >= ysize_) {
printf("Const row %zu out of bounds (ysize=%zu)\n", y, ysize_);
abort();
}
#endif
return reinterpret_cast<const T *>(bytes_.get() + y * bytes_per_row_);
}
// Raw access to byte contents, for interfacing with other libraries.
// Unsigned char instead of char to avoid surprises (sign extension).
ConstRestrict<uint8_t *> bytes() { return bytes_.get(); }
ConstRestrict<const uint8_t *> bytes() const { return bytes_.get(); }
size_t bytes_per_row() const { return bytes_per_row_; }
// Returns number of pixels (some of which are padding) per row. Useful for
// computing other rows via pointer arithmetic.
intptr_t PixelsPerRow() const {
static_assert(CacheAligned::kCacheLineSize % sizeof(T) == 0,
"Padding must be divisible by the pixel size.");
return static_cast<intptr_t>(bytes_per_row_ / sizeof(T));
}
private:
// Deleter used when bytes are not owned.
static void Ignore(void *) {}
// (Members are non-const to enable assignment during move-assignment.)
size_t xsize_; // original intended pixels, not including any padding.
size_t ysize_;
size_t bytes_per_row_; // [bytes] including padding.
CacheAlignedUniquePtr bytes_;
};
class RemoveWarningHeloer
{
void something();
};
// Returns newly allocated planes of the given dimensions.
template <typename T>
static inline std::vector<Image<T>> CreatePlanes(const size_t xsize,
const size_t ysize,
const size_t num_planes) {
std::vector<Image<T>> planes;
planes.reserve(num_planes);
for (size_t i = 0; i < num_planes; ++i) {
planes.emplace_back(xsize, ysize);
}
return planes;
}
// Returns a new image with the same dimensions and pixel values.
template <typename T>
static inline Image<T> CopyPixels(const Image<T> &other) {
Image<T> copy(other.xsize(), other.ysize());
const void *BUTTERAUGLI_RESTRICT from = other.bytes();
void *BUTTERAUGLI_RESTRICT to = copy.bytes();
memcpy(to, from, other.ysize() * other.bytes_per_row());
return copy;
}
// Returns new planes with the same dimensions and pixel values.
template <typename T>
static inline std::vector<Image<T>> CopyPlanes(
const std::vector<Image<T>> &planes) {
std::vector<Image<T>> copy;
copy.reserve(planes.size());
for (const Image<T> &plane : planes) {
copy.push_back(CopyPixels(plane));
}
return copy;
}
// Compacts a padded image into a preallocated packed vector.
template <typename T>
static inline void CopyToPacked(const Image<T> &from, std::vector<T> *to) {
const size_t xsize = from.xsize();
const size_t ysize = from.ysize();
#if BUTTERAUGLI_ENABLE_CHECKS
if (to->size() < xsize * ysize) {
printf("%zu x %zu exceeds %zu capacity\n", xsize, ysize, to->size());
abort();
}
#endif
for (size_t y = 0; y < ysize; ++y) {
ConstRestrict<const float*> row_from = from.Row(y);
ConstRestrict<float*> row_to = to->data() + y * xsize;
memcpy(row_to, row_from, xsize * sizeof(T));
}
}
// Expands a packed vector into a preallocated padded image.
template <typename T>
static inline void CopyFromPacked(const std::vector<T> &from, Image<T> *to) {
const size_t xsize = to->xsize();
const size_t ysize = to->ysize();
assert(from.size() == xsize * ysize);
for (size_t y = 0; y < ysize; ++y) {
ConstRestrict<const float*> row_from = from.data() + y * xsize;
ConstRestrict<float*> row_to = to->Row(y);
memcpy(row_to, row_from, xsize * sizeof(T));
}
}
template <typename T>
static inline std::vector<Image<T>> PlanesFromPacked(
const size_t xsize, const size_t ysize,
const std::vector<std::vector<T>> &packed) {
std::vector<Image<T>> planes;
planes.reserve(packed.size());
for (const std::vector<T> &p : packed) {
planes.push_back(Image<T>(xsize, ysize));
CopyFromPacked(p, &planes.back());
}
return planes;
}
template <typename T>
static inline std::vector<std::vector<T>> PackedFromPlanes(
const std::vector<Image<T>> &planes) {
assert(!planes.empty());
const size_t num_pixels = planes[0].xsize() * planes[0].ysize();
std::vector<std::vector<T>> packed;
packed.reserve(planes.size());
for (const Image<T> &image : planes) {
packed.push_back(std::vector<T>(num_pixels));
CopyToPacked(image, &packed.back());
}
return packed;
}
class ButteraugliComparator {
public:
ButteraugliComparator(size_t xsize, size_t ysize, int step);
// Computes the butteraugli map between rgb0 and rgb1 and updates result.
void Diffmap(const std::vector<ImageF> &rgb0,
const std::vector<ImageF> &rgb1,
ImageF &result);
// Same as above, but OpsinDynamicsImage() was already applied to
// rgb0 and rgb1.
void DiffmapOpsinDynamicsImage(const std::vector<ImageF> &rgb0,
const std::vector<ImageF> &rgb1,
ImageF &result);
private:
void BlockDiffMap(const std::vector<std::vector<float> > &rgb0,
const std::vector<std::vector<float> > &rgb1,
std::vector<float>* block_diff_dc,
std::vector<float>* block_diff_ac);
void EdgeDetectorMap(const std::vector<std::vector<float> > &rgb0,
const std::vector<std::vector<float> > &rgb1,
std::vector<float>* edge_detector_map);
void EdgeDetectorLowFreq(const std::vector<std::vector<float> > &rgb0,
const std::vector<std::vector<float> > &rgb1,
std::vector<float>* block_diff_ac);
void CombineChannels(const std::vector<std::vector<float> >& scale_xyb,
const std::vector<std::vector<float> >& scale_xyb_dc,
const std::vector<float>& block_diff_dc,
const std::vector<float>& block_diff_ac,
const std::vector<float>& edge_detector_map,
std::vector<float>* result);
const size_t xsize_;
const size_t ysize_;
const size_t num_pixels_;
const int step_;
const size_t res_xsize_;
const size_t res_ysize_;
};
void ButteraugliDiffmap(const std::vector<ImageF> &rgb0,
const std::vector<ImageF> &rgb1,
ImageF &diffmap);
double ButteraugliScoreFromDiffmap(const ImageF& distmap);
// Compute values of local frequency and dc masking based on the activity
// in the two images.
void Mask(const std::vector<std::vector<float> > &rgb0,
const std::vector<std::vector<float> > &rgb1,
size_t xsize, size_t ysize,
std::vector<std::vector<float> > *mask,
std::vector<std::vector<float> > *mask_dc);
// Computes difference metrics for one 8x8 block.
void ButteraugliBlockDiff(double rgb0[192],
double rgb1[192],
double diff_xyb_dc[3],
double diff_xyb_ac[3],
double diff_xyb_edge_dc[3]);
void OpsinAbsorbance(const double in[3], double out[3]);
void OpsinDynamicsImage(size_t xsize, size_t ysize,
std::vector<std::vector<float> > &rgb);
void MaskHighIntensityChange(
size_t xsize, size_t ysize,
const std::vector<std::vector<float> > &c0,
const std::vector<std::vector<float> > &c1,
std::vector<std::vector<float> > &rgb0,
std::vector<std::vector<float> > &rgb1);
void Blur(size_t xsize, size_t ysize, float* channel, double sigma,
double border_ratio = 0.0);
void RgbToXyb(double r, double g, double b,
double *valx, double *valy, double *valz);
double SimpleGamma(double v);
double GammaMinArg();
double GammaMaxArg();
// Polynomial evaluation via Clenshaw's scheme (similar to Horner's).
// Template enables compile-time unrolling of the recursion, but must reside
// outside of a class due to the specialization.
template <int INDEX>
static inline void ClenshawRecursion(const double x, const double *coefficients,
double *b1, double *b2) {
const double x_b1 = x * (*b1);
const double t = (x_b1 + x_b1) - (*b2) + coefficients[INDEX];
*b2 = *b1;
*b1 = t;
ClenshawRecursion<INDEX - 1>(x, coefficients, b1, b2);
}
// Base case
template <>
inline void ClenshawRecursion<0>(const double x, const double *coefficients,
double *b1, double *b2) {
const double x_b1 = x * (*b1);
// The final iteration differs - no 2 * x_b1 here.
*b1 = x_b1 - (*b2) + coefficients[0];
}
// Rational polynomial := dividing two polynomial evaluations. These are easier
// to find than minimax polynomials.
struct RationalPolynomial {
template <int N>
static double EvaluatePolynomial(const double x,
const double (&coefficients)[N]) {
double b1 = 0.0;
double b2 = 0.0;
ClenshawRecursion<N - 1>(x, coefficients, &b1, &b2);
return b1;
}
// Evaluates the polynomial at x (in [min_value, max_value]).
inline double operator()(const float x) const {
// First normalize to [0, 1].
const double x01 = (x - min_value) / (max_value - min_value);
// And then to [-1, 1] domain of Chebyshev polynomials.
const double xc = 2.0 * x01 - 1.0;
const double yp = EvaluatePolynomial(xc, p);
const double yq = EvaluatePolynomial(xc, q);
if (yq == 0.0) return 0.0;
return static_cast<float>(yp / yq);
}
// Domain of the polynomials; they are undefined elsewhere.
double min_value;
double max_value;
// Coefficients of T_n (Chebyshev polynomials of the first kind).
// Degree 5/5 is a compromise between accuracy (0.1%) and numerical stability.
double p[5 + 1];
double q[5 + 1];
};
static inline float GammaPolynomial(float value) {
// Generated by gamma_polynomial.m from equispaced x/gamma(x) samples.
static const RationalPolynomial r = {
0.770000000000000, 274.579999999999984,
{
881.979476556478289, 1496.058452015812463, 908.662212739659481,
373.566100223287378, 85.840860336314364, 6.683258861509244,
},
{
12.262350348616792, 20.557285797683576, 12.161463238367844,
4.711532733641639, 0.899112889751053, 0.035662329617191,
}};
return r(value);
}
} // namespace butteraugli
#endif // BUTTERAUGLI_BUTTERAUGLI_H_
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/butteraugli/butteraugli.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 5,174
|
```objective-c
/* pngconf.h - machine configurable file for libpng
*
* libpng version 1.6.29, March 16, 2017
*
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*
* Any machine specific code is near the front of this file, so if you
* are configuring libpng for a machine, you may want to read the section
* starting here down to where it starts to typedef png_color, png_text,
* and png_info.
*/
#ifndef PNGCONF_H
#define PNGCONF_H
#ifndef PNG_BUILDING_SYMBOL_TABLE /* else includes may cause problems */
/* From libpng 1.6.0 libpng requires an ANSI X3.159-1989 ("ISOC90") compliant C
* compiler for correct compilation. The following header files are required by
* the standard. If your compiler doesn't provide these header files, or they
* do not match the standard, you will need to provide/improve them.
*/
#include <limits.h>
#include <stddef.h>
/* Library header files. These header files are all defined by ISOC90; libpng
* expects conformant implementations, however, an ISOC90 conformant system need
* not provide these header files if the functionality cannot be implemented.
* In this case it will be necessary to disable the relevant parts of libpng in
* the build of pnglibconf.h.
*
* Prior to 1.6.0 string.h was included here; the API changes in 1.6.0 to not
* include this unnecessary header file.
*/
#ifdef PNG_STDIO_SUPPORTED
/* Required for the definition of FILE: */
# include <stdio.h>
#endif
#ifdef PNG_SETJMP_SUPPORTED
/* Required for the definition of jmp_buf and the declaration of longjmp: */
# include <setjmp.h>
#endif
#ifdef PNG_CONVERT_tIME_SUPPORTED
/* Required for struct tm: */
# include <time.h>
#endif
#endif /* PNG_BUILDING_SYMBOL_TABLE */
/* Prior to 1.6.0 it was possible to turn off 'const' in declarations using
* PNG_NO_CONST; this is no longer supported except for data declarations which
* apparently still cause problems in 2011 on some compilers.
*/
#define PNG_CONST const /* backward compatibility only */
/* This controls optimization of the reading of 16-bit and 32-bit values
* from PNG files. It can be set on a per-app-file basis - it
* just changes whether a macro is used when the function is called.
* The library builder sets the default; if read functions are not
* built into the library the macro implementation is forced on.
*/
#ifndef PNG_READ_INT_FUNCTIONS_SUPPORTED
# define PNG_USE_READ_MACROS
#endif
#if !defined(PNG_NO_USE_READ_MACROS) && !defined(PNG_USE_READ_MACROS)
# if PNG_DEFAULT_READ_MACROS
# define PNG_USE_READ_MACROS
# endif
#endif
/* COMPILER SPECIFIC OPTIONS.
*
* These options are provided so that a variety of difficult compilers
* can be used. Some are fixed at build time (e.g. PNG_API_RULE
* below) but still have compiler specific implementations, others
* may be changed on a per-file basis when compiling against libpng.
*/
/* The PNGARG macro was used in versions of libpng prior to 1.6.0 to protect
* against legacy (pre ISOC90) compilers that did not understand function
* prototypes. It is not required for modern C compilers.
*/
#ifndef PNGARG
# define PNGARG(arglist) arglist
#endif
/* Function calling conventions.
* =============================
* Normally it is not necessary to specify to the compiler how to call
* a function - it just does it - however on x86 systems derived from
* Microsoft and Borland C compilers ('IBM PC', 'DOS', 'Windows' systems
* and some others) there are multiple ways to call a function and the
* default can be changed on the compiler command line. For this reason
* libpng specifies the calling convention of every exported function and
* every function called via a user supplied function pointer. This is
* done in this file by defining the following macros:
*
* PNGAPI Calling convention for exported functions.
* PNGCBAPI Calling convention for user provided (callback) functions.
* PNGCAPI Calling convention used by the ANSI-C library (required
* for longjmp callbacks and sometimes used internally to
* specify the calling convention for zlib).
*
* These macros should never be overridden. If it is necessary to
* change calling convention in a private build this can be done
* by setting PNG_API_RULE (which defaults to 0) to one of the values
* below to select the correct 'API' variants.
*
* PNG_API_RULE=0 Use PNGCAPI - the 'C' calling convention - throughout.
* This is correct in every known environment.
* PNG_API_RULE=1 Use the operating system convention for PNGAPI and
* the 'C' calling convention (from PNGCAPI) for
* callbacks (PNGCBAPI). This is no longer required
* in any known environment - if it has to be used
* please post an explanation of the problem to the
* libpng mailing list.
*
* These cases only differ if the operating system does not use the C
* calling convention, at present this just means the above cases
* (x86 DOS/Windows sytems) and, even then, this does not apply to
* Cygwin running on those systems.
*
* Note that the value must be defined in pnglibconf.h so that what
* the application uses to call the library matches the conventions
* set when building the library.
*/
/* Symbol export
* =============
* When building a shared library it is almost always necessary to tell
* the compiler which symbols to export. The png.h macro 'PNG_EXPORT'
* is used to mark the symbols. On some systems these symbols can be
* extracted at link time and need no special processing by the compiler,
* on other systems the symbols are flagged by the compiler and just
* the declaration requires a special tag applied (unfortunately) in a
* compiler dependent way. Some systems can do either.
*
* A small number of older systems also require a symbol from a DLL to
* be flagged to the program that calls it. This is a problem because
* we do not know in the header file included by application code that
* the symbol will come from a shared library, as opposed to a statically
* linked one. For this reason the application must tell us by setting
* the magic flag PNG_USE_DLL to turn on the special processing before
* it includes png.h.
*
* Four additional macros are used to make this happen:
*
* PNG_IMPEXP The magic (if any) to cause a symbol to be exported from
* the build or imported if PNG_USE_DLL is set - compiler
* and system specific.
*
* PNG_EXPORT_TYPE(type) A macro that pre or appends PNG_IMPEXP to
* 'type', compiler specific.
*
* PNG_DLL_EXPORT Set to the magic to use during a libpng build to
* make a symbol exported from the DLL. Not used in the
* public header files; see pngpriv.h for how it is used
* in the libpng build.
*
* PNG_DLL_IMPORT Set to the magic to force the libpng symbols to come
* from a DLL - used to define PNG_IMPEXP when
* PNG_USE_DLL is set.
*/
/* System specific discovery.
* ==========================
* This code is used at build time to find PNG_IMPEXP, the API settings
* and PNG_EXPORT_TYPE(), it may also set a macro to indicate the DLL
* import processing is possible. On Windows systems it also sets
* compiler-specific macros to the values required to change the calling
* conventions of the various functions.
*/
#if defined(_Windows) || defined(_WINDOWS) || defined(WIN32) ||\
defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
/* Windows system (DOS doesn't support DLLs). Includes builds under Cygwin or
* MinGW on any architecture currently supported by Windows. Also includes
* Watcom builds but these need special treatment because they are not
* compatible with GCC or Visual C because of different calling conventions.
*/
# if PNG_API_RULE == 2
/* If this line results in an error, either because __watcall is not
* understood or because of a redefine just below you cannot use *this*
* build of the library with the compiler you are using. *This* build was
* build using Watcom and applications must also be built using Watcom!
*/
# define PNGCAPI __watcall
# endif
# if defined(__GNUC__) || (defined(_MSC_VER) && (_MSC_VER >= 800))
# define PNGCAPI __cdecl
# if PNG_API_RULE == 1
/* If this line results in an error __stdcall is not understood and
* PNG_API_RULE should not have been set to '1'.
*/
# define PNGAPI __stdcall
# endif
# else
/* An older compiler, or one not detected (erroneously) above,
* if necessary override on the command line to get the correct
* variants for the compiler.
*/
# ifndef PNGCAPI
# define PNGCAPI _cdecl
# endif
# if PNG_API_RULE == 1 && !defined(PNGAPI)
# define PNGAPI _stdcall
# endif
# endif /* compiler/api */
/* NOTE: PNGCBAPI always defaults to PNGCAPI. */
# if defined(PNGAPI) && !defined(PNG_USER_PRIVATEBUILD)
# error "PNG_USER_PRIVATEBUILD must be defined if PNGAPI is changed"
# endif
# if (defined(_MSC_VER) && _MSC_VER < 800) ||\
(defined(__BORLANDC__) && __BORLANDC__ < 0x500)
/* older Borland and MSC
* compilers used '__export' and required this to be after
* the type.
*/
# ifndef PNG_EXPORT_TYPE
# define PNG_EXPORT_TYPE(type) type PNG_IMPEXP
# endif
# define PNG_DLL_EXPORT __export
# else /* newer compiler */
# define PNG_DLL_EXPORT __declspec(dllexport)
# ifndef PNG_DLL_IMPORT
# define PNG_DLL_IMPORT __declspec(dllimport)
# endif
# endif /* compiler */
#else /* !Windows */
# if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
# define PNGAPI _System
# else /* !Windows/x86 && !OS/2 */
/* Use the defaults, or define PNG*API on the command line (but
* this will have to be done for every compile!)
*/
# endif /* other system, !OS/2 */
#endif /* !Windows/x86 */
/* Now do all the defaulting . */
#ifndef PNGCAPI
# define PNGCAPI
#endif
#ifndef PNGCBAPI
# define PNGCBAPI PNGCAPI
#endif
#ifndef PNGAPI
# define PNGAPI PNGCAPI
#endif
/* PNG_IMPEXP may be set on the compilation system command line or (if not set)
* then in an internal header file when building the library, otherwise (when
* using the library) it is set here.
*/
#ifndef PNG_IMPEXP
# if defined(PNG_USE_DLL) && defined(PNG_DLL_IMPORT)
/* This forces use of a DLL, disallowing static linking */
# define PNG_IMPEXP PNG_DLL_IMPORT
# endif
# ifndef PNG_IMPEXP
# define PNG_IMPEXP
# endif
#endif
/* In 1.5.2 the definition of PNG_FUNCTION has been changed to always treat
* 'attributes' as a storage class - the attributes go at the start of the
* function definition, and attributes are always appended regardless of the
* compiler. This considerably simplifies these macros but may cause problems
* if any compilers both need function attributes and fail to handle them as
* a storage class (this is unlikely.)
*/
#ifndef PNG_FUNCTION
# define PNG_FUNCTION(type, name, args, attributes) attributes type name args
#endif
#ifndef PNG_EXPORT_TYPE
# define PNG_EXPORT_TYPE(type) PNG_IMPEXP type
#endif
/* The ordinal value is only relevant when preprocessing png.h for symbol
* table entries, so we discard it here. See the .dfn files in the
* scripts directory.
*/
#ifndef PNG_EXPORTA
# define PNG_EXPORTA(ordinal, type, name, args, attributes) \
PNG_FUNCTION(PNG_EXPORT_TYPE(type), (PNGAPI name), PNGARG(args), \
PNG_LINKAGE_API attributes)
#endif
/* ANSI-C (C90) does not permit a macro to be invoked with an empty argument,
* so make something non-empty to satisfy the requirement:
*/
#define PNG_EMPTY /*empty list*/
#define PNG_EXPORT(ordinal, type, name, args) \
PNG_EXPORTA(ordinal, type, name, args, PNG_EMPTY)
/* Use PNG_REMOVED to comment out a removed interface. */
#ifndef PNG_REMOVED
# define PNG_REMOVED(ordinal, type, name, args, attributes)
#endif
#ifndef PNG_CALLBACK
# define PNG_CALLBACK(type, name, args) type (PNGCBAPI name) PNGARG(args)
#endif
/* Support for compiler specific function attributes. These are used
* so that where compiler support is available incorrect use of API
* functions in png.h will generate compiler warnings.
*
* Added at libpng-1.2.41.
*/
#ifndef PNG_NO_PEDANTIC_WARNINGS
# ifndef PNG_PEDANTIC_WARNINGS_SUPPORTED
# define PNG_PEDANTIC_WARNINGS_SUPPORTED
# endif
#endif
#ifdef PNG_PEDANTIC_WARNINGS_SUPPORTED
/* Support for compiler specific function attributes. These are used
* so that where compiler support is available, incorrect use of API
* functions in png.h will generate compiler warnings. Added at libpng
* version 1.2.41. Disabling these removes the warnings but may also produce
* less efficient code.
*/
# if defined(__clang__) && defined(__has_attribute)
/* Clang defines both __clang__ and __GNUC__. Check __clang__ first. */
# if !defined(PNG_USE_RESULT) && __has_attribute(__warn_unused_result__)
# define PNG_USE_RESULT __attribute__((__warn_unused_result__))
# endif
# if !defined(PNG_NORETURN) && __has_attribute(__noreturn__)
# define PNG_NORETURN __attribute__((__noreturn__))
# endif
# if !defined(PNG_ALLOCATED) && __has_attribute(__malloc__)
# define PNG_ALLOCATED __attribute__((__malloc__))
# endif
# if !defined(PNG_DEPRECATED) && __has_attribute(__deprecated__)
# define PNG_DEPRECATED __attribute__((__deprecated__))
# endif
# if !defined(PNG_PRIVATE)
# ifdef __has_extension
# if __has_extension(attribute_unavailable_with_message)
# define PNG_PRIVATE __attribute__((__unavailable__(\
"This function is not exported by libpng.")))
# endif
# endif
# endif
# ifndef PNG_RESTRICT
# define PNG_RESTRICT __restrict
# endif
# elif defined(__GNUC__)
# ifndef PNG_USE_RESULT
# define PNG_USE_RESULT __attribute__((__warn_unused_result__))
# endif
# ifndef PNG_NORETURN
# define PNG_NORETURN __attribute__((__noreturn__))
# endif
# if __GNUC__ >= 3
# ifndef PNG_ALLOCATED
# define PNG_ALLOCATED __attribute__((__malloc__))
# endif
# ifndef PNG_DEPRECATED
# define PNG_DEPRECATED __attribute__((__deprecated__))
# endif
# ifndef PNG_PRIVATE
# if 0 /* Doesn't work so we use deprecated instead*/
# define PNG_PRIVATE \
__attribute__((warning("This function is not exported by libpng.")))
# else
# define PNG_PRIVATE \
__attribute__((__deprecated__))
# endif
# endif
# if ((__GNUC__ > 3) || !defined(__GNUC_MINOR__) || (__GNUC_MINOR__ >= 1))
# ifndef PNG_RESTRICT
# define PNG_RESTRICT __restrict
# endif
# endif /* __GNUC__.__GNUC_MINOR__ > 3.0 */
# endif /* __GNUC__ >= 3 */
# elif defined(_MSC_VER) && (_MSC_VER >= 1300)
# ifndef PNG_USE_RESULT
# define PNG_USE_RESULT /* not supported */
# endif
# ifndef PNG_NORETURN
# define PNG_NORETURN __declspec(noreturn)
# endif
# ifndef PNG_ALLOCATED
# if (_MSC_VER >= 1400)
# define PNG_ALLOCATED __declspec(restrict)
# endif
# endif
# ifndef PNG_DEPRECATED
# define PNG_DEPRECATED __declspec(deprecated)
# endif
# ifndef PNG_PRIVATE
# define PNG_PRIVATE __declspec(deprecated)
# endif
# ifndef PNG_RESTRICT
# if (_MSC_VER >= 1400)
# define PNG_RESTRICT __restrict
# endif
# endif
# elif defined(__WATCOMC__)
# ifndef PNG_RESTRICT
# define PNG_RESTRICT __restrict
# endif
# endif
#endif /* PNG_PEDANTIC_WARNINGS */
#ifndef PNG_DEPRECATED
# define PNG_DEPRECATED /* Use of this function is deprecated */
#endif
#ifndef PNG_USE_RESULT
# define PNG_USE_RESULT /* The result of this function must be checked */
#endif
#ifndef PNG_NORETURN
# define PNG_NORETURN /* This function does not return */
#endif
#ifndef PNG_ALLOCATED
# define PNG_ALLOCATED /* The result of the function is new memory */
#endif
#ifndef PNG_PRIVATE
# define PNG_PRIVATE /* This is a private libpng function */
#endif
#ifndef PNG_RESTRICT
# define PNG_RESTRICT /* The C99 "restrict" feature */
#endif
#ifndef PNG_FP_EXPORT /* A floating point API. */
# ifdef PNG_FLOATING_POINT_SUPPORTED
# define PNG_FP_EXPORT(ordinal, type, name, args)\
PNG_EXPORT(ordinal, type, name, args);
# else /* No floating point APIs */
# define PNG_FP_EXPORT(ordinal, type, name, args)
# endif
#endif
#ifndef PNG_FIXED_EXPORT /* A fixed point API. */
# ifdef PNG_FIXED_POINT_SUPPORTED
# define PNG_FIXED_EXPORT(ordinal, type, name, args)\
PNG_EXPORT(ordinal, type, name, args);
# else /* No fixed point APIs */
# define PNG_FIXED_EXPORT(ordinal, type, name, args)
# endif
#endif
#ifndef PNG_BUILDING_SYMBOL_TABLE
/* Some typedefs to get us started. These should be safe on most of the common
* platforms.
*
* png_uint_32 and png_int_32 may, currently, be larger than required to hold a
* 32-bit value however this is not normally advisable.
*
* png_uint_16 and png_int_16 should always be two bytes in size - this is
* verified at library build time.
*
* png_byte must always be one byte in size.
*
* The checks below use constants from limits.h, as defined by the ISOC90
* standard.
*/
#if CHAR_BIT == 8 && UCHAR_MAX == 255
typedef unsigned char png_byte;
#else
# error "libpng requires 8-bit bytes"
#endif
#if INT_MIN == -32768 && INT_MAX == 32767
typedef int png_int_16;
#elif SHRT_MIN == -32768 && SHRT_MAX == 32767
typedef short png_int_16;
#else
# error "libpng requires a signed 16-bit type"
#endif
#if UINT_MAX == 65535
typedef unsigned int png_uint_16;
#elif USHRT_MAX == 65535
typedef unsigned short png_uint_16;
#else
# error "libpng requires an unsigned 16-bit type"
#endif
#if INT_MIN < -2147483646 && INT_MAX > 2147483646
typedef int png_int_32;
#elif LONG_MIN < -2147483646 && LONG_MAX > 2147483646
typedef long int png_int_32;
#else
# error "libpng requires a signed 32-bit (or more) type"
#endif
#if UINT_MAX > 4294967294U
typedef unsigned int png_uint_32;
#elif ULONG_MAX > 4294967294U
typedef unsigned long int png_uint_32;
#else
# error "libpng requires an unsigned 32-bit (or more) type"
#endif
/* Prior to 1.6.0 it was possible to disable the use of size_t, 1.6.0, however,
* requires an ISOC90 compiler and relies on consistent behavior of sizeof.
*/
typedef size_t png_size_t;
typedef ptrdiff_t png_ptrdiff_t;
/* libpng needs to know the maximum value of 'size_t' and this controls the
* definition of png_alloc_size_t, below. This maximum value of size_t limits
* but does not control the maximum allocations the library makes - there is
* direct application control of this through png_set_user_limits().
*/
#ifndef PNG_SMALL_SIZE_T
/* Compiler specific tests for systems where size_t is known to be less than
* 32 bits (some of these systems may no longer work because of the lack of
* 'far' support; see above.)
*/
# if (defined(__TURBOC__) && !defined(__FLAT__)) ||\
(defined(_MSC_VER) && defined(MAXSEG_64K))
# define PNG_SMALL_SIZE_T
# endif
#endif
/* png_alloc_size_t is guaranteed to be no smaller than png_size_t, and no
* smaller than png_uint_32. Casts from png_size_t or png_uint_32 to
* png_alloc_size_t are not necessary; in fact, it is recommended not to use
* them at all so that the compiler can complain when something turns out to be
* problematic.
*
* Casts in the other direction (from png_alloc_size_t to png_size_t or
* png_uint_32) should be explicitly applied; however, we do not expect to
* encounter practical situations that require such conversions.
*
* PNG_SMALL_SIZE_T must be defined if the maximum value of size_t is less than
* 4294967295 - i.e. less than the maximum value of png_uint_32.
*/
#ifdef PNG_SMALL_SIZE_T
typedef png_uint_32 png_alloc_size_t;
#else
typedef png_size_t png_alloc_size_t;
#endif
/* Prior to 1.6.0 libpng offered limited support for Microsoft C compiler
* implementations of Intel CPU specific support of user-mode segmented address
* spaces, where 16-bit pointers address more than 65536 bytes of memory using
* separate 'segment' registers. The implementation requires two different
* types of pointer (only one of which includes the segment value.)
*
* If required this support is available in version 1.2 of libpng and may be
* available in versions through 1.5, although the correctness of the code has
* not been verified recently.
*/
/* Typedef for floating-point numbers that are converted to fixed-point with a
* multiple of 100,000, e.g., gamma
*/
typedef png_int_32 png_fixed_point;
/* Add typedefs for pointers */
typedef void * png_voidp;
typedef const void * png_const_voidp;
typedef png_byte * png_bytep;
typedef const png_byte * png_const_bytep;
typedef png_uint_32 * png_uint_32p;
typedef const png_uint_32 * png_const_uint_32p;
typedef png_int_32 * png_int_32p;
typedef const png_int_32 * png_const_int_32p;
typedef png_uint_16 * png_uint_16p;
typedef const png_uint_16 * png_const_uint_16p;
typedef png_int_16 * png_int_16p;
typedef const png_int_16 * png_const_int_16p;
typedef char * png_charp;
typedef const char * png_const_charp;
typedef png_fixed_point * png_fixed_point_p;
typedef const png_fixed_point * png_const_fixed_point_p;
typedef png_size_t * png_size_tp;
typedef const png_size_t * png_const_size_tp;
#ifdef PNG_STDIO_SUPPORTED
typedef FILE * png_FILE_p;
#endif
#ifdef PNG_FLOATING_POINT_SUPPORTED
typedef double * png_doublep;
typedef const double * png_const_doublep;
#endif
/* Pointers to pointers; i.e. arrays */
typedef png_byte * * png_bytepp;
typedef png_uint_32 * * png_uint_32pp;
typedef png_int_32 * * png_int_32pp;
typedef png_uint_16 * * png_uint_16pp;
typedef png_int_16 * * png_int_16pp;
typedef const char * * png_const_charpp;
typedef char * * png_charpp;
typedef png_fixed_point * * png_fixed_point_pp;
#ifdef PNG_FLOATING_POINT_SUPPORTED
typedef double * * png_doublepp;
#endif
/* Pointers to pointers to pointers; i.e., pointer to array */
typedef char * * * png_charppp;
#endif /* PNG_BUILDING_SYMBOL_TABLE */
#endif /* PNGCONF_H */
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/png/pngconf.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 5,585
|
```objective-c
/* pnglibconf.h - library build configuration */
/* libpng version 1.6.29, March 16, 2017 */
/* This code is released under the libpng license. */
/* For conditions of distribution and use, see the disclaimer */
/* and license in png.h */
/* pnglibconf.h */
/* Machine generated file: DO NOT EDIT */
/* Derived from: scripts/pnglibconf.dfa */
#ifndef PNGLCONF_H
#define PNGLCONF_H
/* options */
#define PNG_16BIT_SUPPORTED
#define PNG_ALIGNED_MEMORY_SUPPORTED
/*#undef PNG_ARM_NEON_API_SUPPORTED*/
/*#undef PNG_ARM_NEON_CHECK_SUPPORTED*/
#define PNG_BENIGN_ERRORS_SUPPORTED
#define PNG_BENIGN_READ_ERRORS_SUPPORTED
/*#undef PNG_BENIGN_WRITE_ERRORS_SUPPORTED*/
#define PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED
#define PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
#define PNG_COLORSPACE_SUPPORTED
#define PNG_CONSOLE_IO_SUPPORTED
#define PNG_CONVERT_tIME_SUPPORTED
#define PNG_EASY_ACCESS_SUPPORTED
/*#undef PNG_ERROR_NUMBERS_SUPPORTED*/
#define PNG_ERROR_TEXT_SUPPORTED
#define PNG_FIXED_POINT_SUPPORTED
#define PNG_FLOATING_ARITHMETIC_SUPPORTED
#define PNG_FLOATING_POINT_SUPPORTED
#define PNG_FORMAT_AFIRST_SUPPORTED
#define PNG_FORMAT_BGR_SUPPORTED
#define PNG_GAMMA_SUPPORTED
#define PNG_GET_PALETTE_MAX_SUPPORTED
#define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
#define PNG_INCH_CONVERSIONS_SUPPORTED
#define PNG_INFO_IMAGE_SUPPORTED
#define PNG_IO_STATE_SUPPORTED
#define PNG_MNG_FEATURES_SUPPORTED
#define PNG_POINTER_INDEXING_SUPPORTED
/*#undef PNG_POWERPC_VSX_API_SUPPORTED*/
/*#undef PNG_POWERPC_VSX_CHECK_SUPPORTED*/
#define PNG_PROGRESSIVE_READ_SUPPORTED
#define PNG_READ_16BIT_SUPPORTED
#define PNG_READ_ALPHA_MODE_SUPPORTED
#define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
#define PNG_READ_BACKGROUND_SUPPORTED
#define PNG_READ_BGR_SUPPORTED
#define PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
#define PNG_READ_COMPOSITE_NODIV_SUPPORTED
#define PNG_READ_COMPRESSED_TEXT_SUPPORTED
#define PNG_READ_EXPAND_16_SUPPORTED
#define PNG_READ_EXPAND_SUPPORTED
#define PNG_READ_FILLER_SUPPORTED
#define PNG_READ_GAMMA_SUPPORTED
#define PNG_READ_GET_PALETTE_MAX_SUPPORTED
#define PNG_READ_GRAY_TO_RGB_SUPPORTED
#define PNG_READ_INTERLACING_SUPPORTED
#define PNG_READ_INT_FUNCTIONS_SUPPORTED
#define PNG_READ_INVERT_ALPHA_SUPPORTED
#define PNG_READ_INVERT_SUPPORTED
#define PNG_READ_OPT_PLTE_SUPPORTED
#define PNG_READ_PACKSWAP_SUPPORTED
#define PNG_READ_PACK_SUPPORTED
#define PNG_READ_QUANTIZE_SUPPORTED
#define PNG_READ_RGB_TO_GRAY_SUPPORTED
#define PNG_READ_SCALE_16_TO_8_SUPPORTED
#define PNG_READ_SHIFT_SUPPORTED
#define PNG_READ_STRIP_16_TO_8_SUPPORTED
#define PNG_READ_STRIP_ALPHA_SUPPORTED
#define PNG_READ_SUPPORTED
#define PNG_READ_SWAP_ALPHA_SUPPORTED
#define PNG_READ_SWAP_SUPPORTED
#define PNG_READ_TEXT_SUPPORTED
#define PNG_READ_TRANSFORMS_SUPPORTED
#define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_READ_USER_CHUNKS_SUPPORTED
#define PNG_READ_USER_TRANSFORM_SUPPORTED
#define PNG_READ_bKGD_SUPPORTED
#define PNG_READ_cHRM_SUPPORTED
#define PNG_READ_gAMA_SUPPORTED
#define PNG_READ_hIST_SUPPORTED
#define PNG_READ_iCCP_SUPPORTED
#define PNG_READ_iTXt_SUPPORTED
#define PNG_READ_oFFs_SUPPORTED
#define PNG_READ_pCAL_SUPPORTED
#define PNG_READ_pHYs_SUPPORTED
#define PNG_READ_sBIT_SUPPORTED
#define PNG_READ_sCAL_SUPPORTED
#define PNG_READ_sPLT_SUPPORTED
#define PNG_READ_sRGB_SUPPORTED
#define PNG_READ_tEXt_SUPPORTED
#define PNG_READ_tIME_SUPPORTED
#define PNG_READ_tRNS_SUPPORTED
#define PNG_READ_zTXt_SUPPORTED
#define PNG_SAVE_INT_32_SUPPORTED
#define PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_SEQUENTIAL_READ_SUPPORTED
#define PNG_SETJMP_SUPPORTED
#define PNG_SET_OPTION_SUPPORTED
#define PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_SET_USER_LIMITS_SUPPORTED
#define PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
#define PNG_SIMPLIFIED_READ_BGR_SUPPORTED
#define PNG_SIMPLIFIED_READ_SUPPORTED
#define PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
#define PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
#define PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
#define PNG_SIMPLIFIED_WRITE_SUPPORTED
#define PNG_STDIO_SUPPORTED
#define PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_TEXT_SUPPORTED
#define PNG_TIME_RFC1123_SUPPORTED
#define PNG_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_USER_CHUNKS_SUPPORTED
#define PNG_USER_LIMITS_SUPPORTED
#define PNG_USER_MEM_SUPPORTED
#define PNG_USER_TRANSFORM_INFO_SUPPORTED
#define PNG_USER_TRANSFORM_PTR_SUPPORTED
#define PNG_WARNINGS_SUPPORTED
#define PNG_WRITE_16BIT_SUPPORTED
#define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
#define PNG_WRITE_BGR_SUPPORTED
#define PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
#define PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
#define PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
#define PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
#define PNG_WRITE_FILLER_SUPPORTED
#define PNG_WRITE_FILTER_SUPPORTED
#define PNG_WRITE_FLUSH_SUPPORTED
#define PNG_WRITE_GET_PALETTE_MAX_SUPPORTED
#define PNG_WRITE_INTERLACING_SUPPORTED
#define PNG_WRITE_INT_FUNCTIONS_SUPPORTED
#define PNG_WRITE_INVERT_ALPHA_SUPPORTED
#define PNG_WRITE_INVERT_SUPPORTED
#define PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
#define PNG_WRITE_PACKSWAP_SUPPORTED
#define PNG_WRITE_PACK_SUPPORTED
#define PNG_WRITE_SHIFT_SUPPORTED
#define PNG_WRITE_SUPPORTED
#define PNG_WRITE_SWAP_ALPHA_SUPPORTED
#define PNG_WRITE_SWAP_SUPPORTED
#define PNG_WRITE_TEXT_SUPPORTED
#define PNG_WRITE_TRANSFORMS_SUPPORTED
#define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
#define PNG_WRITE_USER_TRANSFORM_SUPPORTED
#define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
#define PNG_WRITE_bKGD_SUPPORTED
#define PNG_WRITE_cHRM_SUPPORTED
#define PNG_WRITE_gAMA_SUPPORTED
#define PNG_WRITE_hIST_SUPPORTED
#define PNG_WRITE_iCCP_SUPPORTED
#define PNG_WRITE_iTXt_SUPPORTED
#define PNG_WRITE_oFFs_SUPPORTED
#define PNG_WRITE_pCAL_SUPPORTED
#define PNG_WRITE_pHYs_SUPPORTED
#define PNG_WRITE_sBIT_SUPPORTED
#define PNG_WRITE_sCAL_SUPPORTED
#define PNG_WRITE_sPLT_SUPPORTED
#define PNG_WRITE_sRGB_SUPPORTED
#define PNG_WRITE_tEXt_SUPPORTED
#define PNG_WRITE_tIME_SUPPORTED
#define PNG_WRITE_tRNS_SUPPORTED
#define PNG_WRITE_zTXt_SUPPORTED
#define PNG_bKGD_SUPPORTED
#define PNG_cHRM_SUPPORTED
#define PNG_gAMA_SUPPORTED
#define PNG_hIST_SUPPORTED
#define PNG_iCCP_SUPPORTED
#define PNG_iTXt_SUPPORTED
#define PNG_oFFs_SUPPORTED
#define PNG_pCAL_SUPPORTED
#define PNG_pHYs_SUPPORTED
#define PNG_sBIT_SUPPORTED
#define PNG_sCAL_SUPPORTED
#define PNG_sPLT_SUPPORTED
#define PNG_sRGB_SUPPORTED
#define PNG_tEXt_SUPPORTED
#define PNG_tIME_SUPPORTED
#define PNG_tRNS_SUPPORTED
#define PNG_zTXt_SUPPORTED
/* end of options */
/* settings */
#define PNG_API_RULE 0
#define PNG_DEFAULT_READ_MACROS 1
#define PNG_GAMMA_THRESHOLD_FIXED 5000
#define PNG_IDAT_READ_SIZE PNG_ZBUF_SIZE
#define PNG_INFLATE_BUF_SIZE 1024
#define PNG_LINKAGE_API extern
#define PNG_LINKAGE_CALLBACK extern
#define PNG_LINKAGE_DATA extern
#define PNG_LINKAGE_FUNCTION extern
#define PNG_MAX_GAMMA_8 11
#define PNG_QUANTIZE_BLUE_BITS 5
#define PNG_QUANTIZE_GREEN_BITS 5
#define PNG_QUANTIZE_RED_BITS 5
#define PNG_TEXT_Z_DEFAULT_COMPRESSION (-1)
#define PNG_TEXT_Z_DEFAULT_STRATEGY 0
#define PNG_USER_CHUNK_CACHE_MAX 1000
#define PNG_USER_CHUNK_MALLOC_MAX 8000000
#define PNG_USER_HEIGHT_MAX 1000000
#define PNG_USER_WIDTH_MAX 1000000
#define PNG_ZBUF_SIZE 8192
#define PNG_ZLIB_VERNUM 0x1280
#define PNG_Z_DEFAULT_COMPRESSION (-1)
#define PNG_Z_DEFAULT_NOFILTER_STRATEGY 0
#define PNG_Z_DEFAULT_STRATEGY 1
#define PNG_sCAL_PRECISION 5
#define PNG_sRGB_PROFILE_CHECKS 2
/* end of settings */
#endif /* PNGLCONF_H */
```
|
/content/code_sandbox/library/JQLibrary/include/JQGuetzli/png/pnglibconf.h
|
objective-c
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,648
|
```qml
import QtQuick 2.5
import "./Element"
import "./Interface"
Item {
id: materialUI
// Theme.qml
property color primaryColor: "#FAFAFA"
/*!
A darker version of the primary color used for the window titlebar (if client-side
decorations are not used), unless a \l Page specifies its own primary and primary dark
colors. This can be customized via the \l ApplicationWindow::theme group property. According
to the Material Design guidelines, this should normally be the 700 color version of your
aplication's primary color, taken from one of the color palettes at
\l {path_to_url#color-color-palette}.
*/
property color primaryDarkColor: Qt.rgba(0,0,0, 0.54)
/*!
The accent color complements the primary color, and is used for any primary action buttons
along with switches, sliders, and other components that do not specifically set a color.
This can be customized via the \l ApplicationWindow::theme group property. According
to the Material Design guidelines, this should taken from a second color palette that
complements the primary color palette at
\l {path_to_url#color-color-palette}.
*/
property color accentColor: "#2196F3"
/*!
The default background color for the application.
*/
property color backgroundColor: "#f3f3f3"
/*!
The color of the higlight indicator for selected tabs. By default this is the accent color,
but it can also be white (for a dark primary color/toolbar background).
*/
property color tabHighlightColor: accentColor
/*!
Standard colors specifically meant for light surfaces. This includes text colors along with
a light version of the accent color.
*/
property ThemePalette light: ThemePalette {
light: true
}
/*!
Standard colors specifically meant for dark surfaces. This includes text colors along with
a dark version of the accent color.
*/
property ThemePalette dark: ThemePalette {
light: false
}
/*!
A utility method for changing the alpha on colors. Returns a new object, and does not modify
the original color at all.
*/
function alpha(color, alpha) {
var realColor = Qt.darker(color, 1)
realColor.a = alpha
return realColor
}
/*!
Select a color depending on whether the background is light or dark.
\c lightColor is the color used on a light background.
\c darkColor is the color used on a dark background.
*/
function lightDark(background, lightColor, darkColor) {
return isDarkColor(background) ? darkColor : lightColor
}
/*!
Returns true if the color is dark and should have light content on top
*/
function isDarkColor(background) {
var temp = Qt.darker(background, 1)
var a = 1 - ( 0.299 * temp.r + 0.587 * temp.g + 0.114 * temp.b);
return temp.a > 0 && a >= 0.3
}
// Other
property alias loadingVisible: progressCircle.visible
property var onDarkBackgroundClicked: null
property var onStealthBackgroundClicked: null
property var stealthBackgroundFilterItem: null
property var swipeToRefreshOnRefreshCallback: null
property var swipeToRefreshOnCancelCallback: null
property var swipeToRefreshOnCompleted: null
property string materialFontName: "Material-Design-Iconic-Font"
property alias progressCircleLabelColor: labelForProgressCircle.color
property string dialogOKText: "OK"
property string dialogCancelText: "Cancel"
function isSmartPhone() {
return (Qt.platform.os === "ios") || (Qt.platform.os === "android");
}
function addSwipeToRefresh(listModel, onRefreshCallback, onCancelCallback, onCompleted) {
listModel.insert(0,
{
type: "component",
source: "qrc:/MaterialUI/Interface/MaterialSwipeToRefresh.qml"
});
swipeToRefreshOnRefreshCallback = onRefreshCallback;
swipeToRefreshOnCancelCallback = onCancelCallback;
swipeToRefreshOnCompleted = onCompleted;
}
function showDialogAlert(title, message, callbackOnOK) {
if (!loaderForDialogAlert.active)
{
loaderForDialogAlert.active = true;
loaderForDialogAlert.item.positiveButtonText = materialUI.dialogOKText;
}
loaderForDialogAlert.item.show(title, message, callbackOnOK);
}
function showDialogConfirm(title, message, callbackOnCancel, callbackOnOK) {
if (!loaderForDialogConfirm.active)
{
loaderForDialogConfirm.active = true;
loaderForDialogConfirm.item.positiveButtonText = materialUI.dialogOKText;
loaderForDialogConfirm.item.negativeButtonText = materialUI.dialogCancelText;
}
loaderForDialogConfirm.item.show(title, message, callbackOnCancel, callbackOnOK);
}
function showDialogPrompt(title, message, placeholderText, currentText, callbackOnCancel, callbackOnOK) {
if (!loaderForDialogPrompt.active)
{
loaderForDialogPrompt.active = true;
loaderForDialogPrompt.item.positiveButtonText = materialUI.dialogOKText;
loaderForDialogPrompt.item.negativeButtonText = materialUI.dialogCancelText;
}
loaderForDialogPrompt.item.show(title, message, placeholderText, currentText, callbackOnCancel, callbackOnOK);
}
function showDialogTextArea(title, message, currentText, callbackOnCancel, callbackOnOK) {
if (!loaderForDialogTextArea.active)
{
loaderForDialogTextArea.active = true;
loaderForDialogTextArea.item.positiveButtonText = materialUI.dialogOKText;
loaderForDialogTextArea.item.negativeButtonText = materialUI.dialogCancelText;
}
loaderForDialogTextArea.item.show(title, message, currentText, callbackOnCancel, callbackOnOK);
}
function showDialogScrolling(title, message, listData, callbackOnCancel, callbackOnOK) {
if (!loaderForDialogScrolling.active)
{
loaderForDialogScrolling.active = true;
loaderForDialogScrolling.item.positiveButtonText = materialUI.dialogOKText;
loaderForDialogScrolling.item.negativeButtonText = materialUI.dialogCancelText;
}
loaderForDialogScrolling.item.show(title, message, listData, callbackOnCancel, callbackOnOK);
}
function showDialogDatePicker(title, message, currentDate, callbackOnCancel, callbackOnOK) {
if (!loaderForDialogDatePicker.active)
{
loaderForDialogDatePicker.active = true;
loaderForDialogDatePicker.item.positiveButtonText = materialUI.dialogOKText;
loaderForDialogDatePicker.item.negativeButtonText = materialUI.dialogCancelText;
}
loaderForDialogDatePicker.item.show(title, message, currentDate, callbackOnCancel, callbackOnOK);
}
function showDialogTimePicker(title, message, currentTime, callbackOnCancel, callbackOnOK) {
if (!loaderForDialogTimePicker.active)
{
loaderForDialogTimePicker.active = true;
loaderForDialogTimePicker.item.positiveButtonText = materialUI.dialogOKText;
loaderForDialogTimePicker.item.negativeButtonText = materialUI.dialogCancelText;
}
loaderForDialogTimePicker.item.show(title, message, currentTime, callbackOnCancel, callbackOnOK);
}
function showBottomActionSheet(title, sheetData, callbackOnCancel, callbackOnOK) {
actionSheet.show(title, sheetData, callbackOnCancel, callbackOnOK);
}
function showDarkBackground(onDarkBackgroundClicked) {
darkBackground.opacity = 1;
switch (arguments.length)
{
case 1:
materialUI.onDarkBackgroundClicked = onDarkBackgroundClicked;
break;
default:
materialUI.onDarkBackgroundClicked = null;
break;
}
}
function showStealthBackground(onStealthBackgroundClicked, stealthBackgroundFilterItem) {
stealthBackground.opacity = 1;
switch (arguments.length)
{
case 2:
materialUI.stealthBackgroundFilterItem = stealthBackgroundFilterItem;
case 1:
materialUI.onStealthBackgroundClicked = onStealthBackgroundClicked;
break;
default:
materialUI.onStealthBackgroundClicked = null;
break;
}
}
function hideDarkBackground() {
darkBackground.opacity = 0;
}
function hideStealthBackground() {
stealthBackground.opacity = 0;
}
function showSnackbarMessage(message) {
snackbar.open(message);
}
function showLoading(text, callbackOnClicked) {
progressCircle.visible = true;
switch (arguments.length)
{
case 1:
case 2:
labelForProgressCircle.text = text;
break;
default:
labelForProgressCircle.text = "";
break;
}
showDarkBackground((arguments.length == 2) ? (callbackOnClicked) : (null));
}
function hideLoading() {
progressCircle.visible = false;
hideDarkBackground();
}
Rectangle {
id: darkBackground
anchors.fill: parent
color: "#55000000"
visible: opacity !== 0
opacity: 0
Behavior on opacity {
NumberAnimation { duration: 500; easing.type: Easing.OutCubic }
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.AllButtons
onClicked: {
if (materialUI.onDarkBackgroundClicked)
{
materialUI.onDarkBackgroundClicked();
}
}
}
}
Rectangle {
id: stealthBackground
anchors.fill: parent
color: "#00000000"
visible: opacity !== 0
opacity: 0
Behavior on opacity {
NumberAnimation { duration: 500; easing.type: Easing.OutCubic }
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton
onPressed: {
if (materialUI.stealthBackgroundFilterItem)
{
var item = materialUI.stealthBackgroundFilterItem;
var currentX = item.x;
var currentY = item.y;
var parent = item.parent;
while (parent && ("x" in parent))
{
currentX += parent.x;
currentY += parent.y;
parent = parent.parent;
}
if (((mouseX > currentX) && (mouseX < (currentX + item.width))) &&
((mouseY > currentY) && (mouseY < (currentY + item.height))))
{
mouse.accepted = false;
}
}
}
onClicked: {
if (materialUI.onStealthBackgroundClicked)
{
materialUI.onStealthBackgroundClicked();
}
}
}
}
MaterialProgressCircle {
id: progressCircle
width: 40
height: 40
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
anchors.verticalCenterOffset: -20
indeterminate: parent.visible
autoChangeColor: parent.visible
visible: false
MaterialLabel {
id: labelForProgressCircle
anchors.top: parent.bottom
anchors.topMargin: 10
anchors.horizontalCenter: parent.horizontalCenter
font.pixelSize: 15
horizontalAlignment: Text.AlignHCenter
}
}
MaterialBottomActionSheet {
id: actionSheet
}
MaterialSnackbar {
id: snackbar
}
FontLoader {
id: materialFont
source: "qrc:/MaterialUI/Material-Design-Iconic-Font.ttf"
}
Loader {
id: loaderForDialogAlert
anchors.centerIn: parent
source: "qrc:/MaterialUI/Interface/MaterialDialogAlert.qml"
active: false
}
Loader {
id: loaderForDialogConfirm
anchors.centerIn: parent
source: "qrc:/MaterialUI/Interface/MaterialDialogConfirm.qml"
active: false
}
Loader {
id: loaderForDialogPrompt
anchors.centerIn: parent
source: "qrc:/MaterialUI/Interface/MaterialDialogPrompt.qml"
active: false
}
Loader {
id: loaderForDialogTextArea
anchors.centerIn: parent
source: "qrc:/MaterialUI/Interface/MaterialDialogTextArea.qml"
active: false
}
Loader {
id: loaderForDialogScrolling
anchors.centerIn: parent
source: "qrc:/MaterialUI/Interface/MaterialDialogScrolling.qml"
active: false
}
Loader {
id: loaderForDialogDatePicker
anchors.centerIn: parent
source: "qrc:/MaterialUI/Interface/MaterialDialogDatePicker.qml"
active: false
}
Loader {
id: loaderForDialogTimePicker
anchors.centerIn: parent
source: "qrc:/MaterialUI/Interface/MaterialDialogTimePicker.qml"
active: false
}
}
```
|
/content/code_sandbox/library/MaterialUI/MaterialUI.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 2,818
|
```qmake
RESOURCES *= \
$$PWD/MaterialUI.qrc
```
|
/content/code_sandbox/library/MaterialUI/MaterialUI.pri
|
qmake
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 14
|
```qml
/*
* QML Material - An application framework implementing Material Design.
*
* This program is free software: you can redistribute it and/or modify
* published by the Free Software Foundation, either version 2.1 of the
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
import QtQuick 2.5
import "../Element"
View {
id: snackbar
property string buttonText
property color buttonColor: "#2196f3"
property string text
property bool opened
property int duration: 2000
property bool fullWidth: materialUI.isSmartPhone()
signal clicked
function open(text) {
snackbar.text = text
opened = true;
timer.restart();
}
anchors {
left: parent.left
right: fullWidth ? parent.right : undefined
bottom: parent.bottom
leftMargin: fullWidth ? 0 : (16)
bottomMargin: opened ? fullWidth ? 0 : (16) : -snackbar.height
Behavior on bottomMargin {
NumberAnimation { duration: 400; easing.type: Easing.OutQuad }
}
}
radius: fullWidth ? 0 : (2)
backgroundColor: "#cc323232"
height: (48)
width: fullWidth ? parent.width
: Math.min(Math.max(implicitWidth, (288)), (568))
opacity: opened ? 1 : 0
implicitWidth: buttonText == "" ? snackText.paintedWidth + (48)
: snackText.paintedWidth + (72) + snackButton.width
Timer {
id: timer
interval: snackbar.duration
onTriggered: {
if (!running) {
snackbar.opened = false;
}
}
}
MaterialLabel {
id: snackText
anchors {
right: snackbar.buttonText == "" ? parent.right : snackButton.left
left: parent.left
top: parent.top
bottom: parent.bottom
leftMargin: (24)
topMargin: (16)
rightMargin: (24)
}
text: snackbar.text
color: "white"
}
MaterialButton {
id: snackButton
opacity: snackbar.buttonText == "" ? 0 : 1
textColor: snackbar.buttonColor
text: snackbar.buttonText
context: "snackbar"
elevation: 0
onClicked: snackbar.clicked()
anchors {
right: parent.right
//left: snackText.right
top: parent.top
bottom: parent.bottom
// Recommended button touch target is 36dp
topMargin: (6)
bottomMargin: (6)
// Normal margin is 24dp, but button itself uses 8dp margins
rightMargin: snackbar.buttonText == "" ? 0 : (16)
}
}
Behavior on opacity {
NumberAnimation { duration: 300 }
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialSnackbar.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 676
|
```qml
/*
* QML Material - An application framework implementing Material Design.
*
* This program is free software: you can redistribute it and/or modify
* published by the Free Software Foundation, either version 2.1 of the
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
import QtQuick 2.5
import QtQuick.Controls 1.4 as Controls
import QtQuick.Controls.Styles 1.4 as ControlStyles
import "../Element"
Controls.CheckBox {
id: checkBox
/*!
The checkbox color. By default this is the app's accent color
*/
property color color: "#2196f3"
property color textColor: enabled ? darkBackground ? "#ffffff"
: "#d8000000"
: darkBackground ? "#4cffffff"
: "#42000000"
/*!
Set to \c true if the checkbox is on a dark background
*/
property bool darkBackground
style: ControlStyles.CheckBoxStyle {
id: checkboxStyle
spacing: (2)
label: Item {
implicitWidth: text.implicitWidth + 2
implicitHeight: text.implicitHeight
baselineOffset: text.baselineOffset
MaterialLabel {
id: text
anchors.centerIn: parent
color: textColor
text: control.text
font.pixelSize: 14
}
}
indicator: Item {
id: parentRect
implicitWidth: (54)
implicitHeight: (54)
Rectangle {
id: indicatorRect
anchors.centerIn: parent
property color __internalColor: control.enabled ? control.color
: control.darkBackground ? "#4cffffff"
: "#42000000"
width: (24)
height: (24)
radius: (2)
border.width: (2)
border.color: control.enabled ? control.checked ? control.color
: control.darkBackground ? "#b2ffffff"
: "#89000000"
: control.darkBackground ? "#4cffffff"
: "#42000000"
color: control.checked ? __internalColor : "transparent"
Behavior on color {
ColorAnimation {
easing.type: Easing.InOutQuad
duration: 200
}
}
Behavior on border.color {
ColorAnimation {
easing.type: Easing.InOutQuad
duration: 200
}
}
Item {
id: container
anchors.centerIn: indicatorRect
height: parent.height
width: parent.width
opacity: control.checked ? 1 : 0
property int thickness: (4)
Behavior on opacity {
NumberAnimation {
easing.type: Easing.InOutQuad
duration: 200
}
}
Rectangle {
id: vert
anchors {
top: parent.top
right: parent.right
bottom: parent.bottom
}
radius: (1)
color: control.darkBackground ? "#d8000000" : "#ffffff"
width: container.thickness * 2
}
Rectangle {
anchors {
left: parent.left
right: vert.left
bottom: parent.bottom
}
radius: (1)
color: control.darkBackground ? "#d8000000" : "#ffffff"
height: container.thickness
}
transform: [
Scale {
origin { x: container.width / 2; y: container.height / 2 }
xScale: 0.5
yScale: 1
},
Rotation {
origin { x: container.width / 2; y: container.height / 2 }
angle: 45;
},
Scale {
id: widthScale
origin { x: container.width / 2; y: container.height / 2 }
xScale: control.checked ? 0.6 : 0.2
yScale: control.checked ? 0.6 : 0.2
Behavior on xScale {
NumberAnimation {
easing.type: Easing.InOutQuad
duration: 200
}
}
Behavior on yScale {
NumberAnimation {
easing.type: Easing.InOutQuad
duration: 200
}
}
},
Translate { y: -(container.height - (container.height * 0.9)) }
]
}
}
}
}
Ink {
anchors {
verticalCenter: parent.verticalCenter
left: parent.left
leftMargin: (54-48)/2
}
width: (48)
height: (48)
color: checkBox.checked ? alpha(checkBox.color, 0.20)
: darkBackground ? Qt.rgba(1,1,1,0.1) : Qt.rgba(0,0,0,0.1)
enabled: checkBox.enabled
circular: true
centered: true
onClicked: {
checkBox.checked = !checkBox.checked
checkBox.clicked();
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialCheckBox.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,117
|
```qml
/*
* QML Material - An application framework implementing Material Design.
*
* This program is free software: you can redistribute it and/or modify
* published by the Free Software Foundation, either version 2.1 of the
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
import QtQuick 2.5
import QtQuick.Controls 1.4 as Controls
import QtQuick.Controls.Styles 1.4 as ControlStyles
import QtGraphicalEffects 1.0
import "../Element"
Controls.Button {
id: button
width: 56
height: 56
property color backgroundColor: "#2196f3"
property color textColor: lightDark(button.backgroundColor,
"#89000000",
"#ffffff")
property int textSize: 15
property string textFontFamily: {
switch (Qt.platform.os)
{
case "windows": return "";
default: return "Roboto";
}
}
property int elevation: backgroundColor == "white" ? 0 : 1
function lightDark(background, lightColor, darkColor) {
return isDarkColor(background) ? darkColor : lightColor
}
function isDarkColor(background) {
var temp = Qt.darker(background, 1)
var a = 1 - ( 0.299 * temp.r + 0.587 * temp.g + 0.114 * temp.b);
return temp.a > 0 && a >= 0.3
}
style: ControlStyles.ButtonStyle {
background: Item {
RectangularGlow {
anchors.centerIn: parent
anchors.verticalCenterOffset: elevation == 1 ? (1.5)
: (1)
width: parent.width
height: parent.height
visible: elevation > 0
glowRadius: elevation == 1 ? (0.75) : (0.3)
opacity: elevation == 1 ? 0.6 : 0.3
spread: elevation == 1 ? 0.7 : 0.85
color: "black"
cornerRadius: height/2
}
View {
anchors.fill: parent
radius: width/2
backgroundColor: button.backgroundColor
tintColor: control.pressed ||
(control.focus && !button.elevation) ||
(control.hovered && !button.elevation) ?
Qt.rgba(0,0,0, control.pressed ? 0.1 : 0.05) : "transparent"
Ink {
id: mouseArea
anchors.fill: parent
Connections {
target: control.__behavior
onPressed: mouseArea.onPressed(mouse)
onCanceled: mouseArea.onCanceled()
onReleased: mouseArea.onReleased(mouse)
}
circular: true
}
}
}
label: Controls.Label {
font.pixelSize: textSize
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
text: control.text
color: textColor
elide: Text.ElideLeft
font.family: button.textFontFamily
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialActionButton.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 712
|
```qml
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
Rectangle {
id: swipeToRefresh
width: parent.width
height: 0
color: "#00000000"
property var base: parent.parent
property int targetHeight: 150
property real offsetY: 0
property real swipePercentage: 0
property real buttonBottomMargin: 5
property var onRefreshCallback: null
property var onCancelCallback: null
property bool refreshing: false
property bool finishing: false
function refresh() {
refreshing = true;
}
function finish() {
refreshing = false;
finishing = true;
swipePercentage = 0;
animation.start();
}
Component.onCompleted: {
parent.z = 2;
onRefreshCallback = materialUI.swipeToRefreshOnRefreshCallback;
onCancelCallback = materialUI.swipeToRefreshOnCancelCallback;
if (materialUI.swipeToRefreshOnCompleted)
{
materialUI.swipeToRefreshOnCompleted(swipeToRefresh);
}
materialUI.swipeToRefreshOnRefreshCallback = null;
materialUI.swipeToRefreshOnCancelCallback = null;
materialUI.swipeToRefreshOnCompleted = null;
}
Connections {
target: base
onYChanged: {
if (base.y > 0)
{
var bufHeight;
if (base.y > 2)
{
bufHeight = (((base.y - 2) < targetHeight) ? (base.y - 2) : (targetHeight));
}
else
{
bufHeight = 0;
}
if (refreshing)
{
if (bufHeight > (targetHeight * 0.6))
{
swipeToRefresh.height = bufHeight;
}
}
else
{
swipeToRefresh.height = bufHeight;
}
swipePercentage = swipeToRefresh.height / (targetHeight * 0.6);
progressCircle.setValue(swipePercentage);
if (swipePercentage >= 1)
{
swipePercentage = 1;
if (!refreshing && !finishing && onRefreshCallback)
{
onRefreshCallback();
}
}
base.y = 0;
}
else if (base.y < 0)
{
if (refreshing)
{
base.y = 0;
}
swipePercentage = 0;
}
}
}
PropertyAnimation {
id: animation
target: button
properties: "scale"
easing.type: Easing.OutQuad
to: 0
duration: 250
onStopped: {
swipeToRefresh.height = 0;
button.scale = 1;
finishing = false;
}
}
MaterialActionButton {
id: button
anchors.bottom: parent.bottom
anchors.bottomMargin: buttonBottomMargin
anchors.horizontalCenter: parent.horizontalCenter
width: 40
height: 40
backgroundColor: "#fafafa"
MaterialProgressCircle {
id: progressCircle
width: 25
height: 25
anchors.centerIn: parent
circleColor: "#a0a0a0"
indeterminate: refreshing || finishing
function setValue(value_) {
if (value_ < 0.25)
{
value = 0;
}
value = value_ * (4 / 3) - (1 / 3);
}
}
MouseArea {
anchors.fill: parent
onClicked: {
if (onCancelCallback)
{
onCancelCallback();
}
}
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialSwipeToRefresh.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 814
|
```qml
import QtQuick 2.5
import QtQuick.Layouts 1.1
import "qrc:/MaterialUI/Element/"
Item {
id: materialTabbed
width: 40
height: 40
property int itemWidth: 100
property alias model: listView.model
property var iconDatas
property alias textColor: button.textColor
property alias backgroundColor: button.backgroundColor
readonly property string selectedText: (listView.currentItem) ? (listView.currentItem.text) : ("")
property alias selectedIndex: listView.currentIndex
property int maxVisibleItems: 4
signal itemSelected(int index, string text);
MaterialActionButton {
id: button
anchors.fill: parent
elevation: 0
textFontFamily: "Material-Design-Iconic-Font"
text: "\uF2A3"
textSize: 22
onClicked: {
dropdown.open(this, -8, 8);
}
Dropdown {
id: dropdown
width: itemWidth
height: Math.min(maxVisibleItems * (48) + (24), listView.height)
ListView {
id: listView
width: dropdown.width
height: Math.min(count > 0 ? contentHeight : 0, 4.5 * (48));
interactive: true
delegate: Standard {
id: delegateItem
text: modelData
onClicked: {
listView.currentIndex = index;
dropdown.close();
itemSelected(index, listView.currentItem.text);
}
Text {
id: labelForIcon
anchors.verticalCenter: parent.verticalCenter
color: "#000000"
visible: text !== ""
font.pixelSize: 20
Component.onCompleted: {
if (materialTabbed.iconDatas && (materialTabbed.iconDatas.length >= index) && materialTabbed.iconDatas[index])
{
labelForIcon.text = materialTabbed.iconDatas[index]["text"];
labelForIcon.font.family = materialTabbed.iconDatas[index]["fontFamily"];
}
}
}
}
}
Scrollbar {
flickableItem: listView
}
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialTabbed.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 466
|
```qml
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtGraphicalEffects 1.0
Rectangle {
id: materialPage
width: parent.width
height: parent.height
color: "#efefef"
property alias titleText: labelForTitle.text
property alias tabbedModel: tabbed.model
property alias tabbedIconDatas: tabbed.iconDatas
property alias tabbedItemWidth: tabbed.itemWidth
property alias tabbedZ: tabbed.z
property bool hideBackButton: false
property bool hideTopShadow: false
property bool destroyOnHide: false
signal tabbedItemSelected(int index, string text)
function show() {
visible = true;
animationForShowAndClose.from = width;
animationForShowAndClose.to = 0;
animationForShowAndClose.easing.type = Easing.OutQuad;
animationForShowAndClose.duration = Math.min(width * 1.5, 800);
animationForShowAndClose.start();
}
function hide() {
animationForShowAndClose.from = 0;
animationForShowAndClose.to = width;
animationForShowAndClose.easing.type = Easing.InQuad;
animationForShowAndClose.duration = Math.min(width * 1.2, 800);
animationForShowAndClose.start();
}
MouseArea {
anchors.fill: parent
}
RectangularGlow {
z: 1
anchors.fill: topRectangle
glowRadius: 6
spread: 0.22
color: "#40000000"
visible: !hideTopShadow
}
RectangularGlow {
z: -1
anchors.fill: materialPage
glowRadius: 6
spread: 0.22
color: "#40000000"
visible: !hideTopShadow
}
Rectangle {
id: topRectangle
z: 2
width: parent.width
height: (48)
color: "#07bdd3"
MaterialActionButton {
width: height
height: parent.height
elevation: 0
textFontFamily: "Material-Design-Iconic-Font"
text: "\uF297"
textSize: 22
textColor: "#ffffff"
backgroundColor: topRectangle.color
visible: !hideBackButton
onClicked: {
materialPage.hide();
}
}
MaterialLabel {
id: labelForTitle
anchors.centerIn: parent
color: "#ffffff"
font.pixelSize: 18
}
}
MaterialTabbed {
id: tabbed
z: 2
width: height
height: topRectangle.height
anchors.top: topRectangle.top
anchors.right: topRectangle.right
visible: (model) ? (model.length > 0) : (false)
textColor: "#ffffff"
backgroundColor: topRectangle.color
onItemSelected: {
tabbedItemSelected(index, text);
}
}
NumberAnimation {
id: animationForShowAndClose
target: materialPage
property: "x"
onStopped: {
if (to === width)
{
visible = false;
if (destroyOnHide)
{
materialPage.destroy();
}
}
else
{
focus = true;
}
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialPage.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 742
|
```qml
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtGraphicalEffects 1.0
import "../Element"
TreeView {
id: tableView
width: 400
height: 400
enabled: modelForTableView.count > -1
alternatingRowColors: false
backgroundVisible: false
headerVisible: true
sortIndicatorVisible: true
frameVisible: false
horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff
verticalScrollBarPolicy: Qt.ScrollBarAlwaysOff
property real itemHeight: 35
property real headerHeight: 40
property bool branchEnabled: true
model: ListModel {
id: modelForTableView
}
style: TreeViewStyle {
branchDelegate: Label {
x: 3
width: 16
height: 16
visible: styleData.column === 0 && styleData.hasChildren
text: styleData.isExpanded ? "\uF1B4" : "\uF1B6"
color: "#000000"
font.family: "Material-Design-Iconic-Font"
font.pixelSize: 18
renderType: Text.NativeRendering
MouseArea {
anchors.fill: parent
visible: !branchEnabled
}
}
}
headerDelegate: Rectangle {
width: 80
height: headerHeight
color: "#ffffff"
radius: 3
Rectangle {
anchors.bottom: parent.bottom
width: parent.width
height: 1
color: "#00000000"
border.width: 1
border.color: "#e1e1e1"
}
Label {
anchors.fill: parent
text: styleData.value
font.pixelSize: 15
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
color: "#606060"
font.family: {
switch (Qt.platform.os)
{
case "windows": return "";
default: return "Roboto";
}
}
}
}
itemDelegate: Rectangle {
color: (styleData.selected) ? ("#f3f3f3") : ("#00000000")
Rectangle {
anchors.bottom: parent.bottom
width: parent.width
height: 1
color: "#00000000"
border.width: 1
border.color: "#e1e1e1"
}
Label {
id: label
anchors.fill: parent
clip: true
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
color: "#000000"
font.pixelSize: 14
elide: Text.ElideRight
font.family: {
switch (Qt.platform.os)
{
case "windows": return "";
default: return "Roboto";
}
}
}
Connections {
target: styleData
onValueChanged: {
if (((typeof styleData.value) !== "string") && ((typeof styleData.value) !== "number")) { return; }
label.text = styleData.value;
}
}
}
rowDelegate: Item {
height: itemHeight
}
function appendText(texts) {
var buf = new Object;
for (var index = 0; index < texts.length; index++)
{
buf["text" + index] = texts[index];
}
model.append(buf)
}
RectangularGlow {
x: 0
y: 1
z: -1
width: parent.width
height: parent.height
glowRadius: 2
spread: 0.22
color: "#30000000"
cornerRadius: 3
}
Rectangle {
z: -1
id: rectangleForBacaground
anchors.fill: parent
color: "#ffffff"
radius: 3
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialTreeView.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 871
|
```qml
import QtQuick 2.5
import QtQuick.Controls 1.4 as Controls
import QtQuick.Controls.Styles 1.4 as ControlStyles
MaterialDialog {
id: dialog
negativeButtonText: ""
positiveButtonText: ("OK")
property var callbackOnOK: null
function show(title, message, callbackOnOK) {
dialog.title = title;
dialog.text = message;
dialog.callbackOnOK = callbackOnOK;
dialog.open();
materialUI.showDarkBackground(function() {
dialog.close();
materialUI.hideDarkBackground();
if (dialog.callbackOnOK)
{
dialog.callbackOnOK();
}
});
}
onAccepted: {
materialUI.hideDarkBackground();
if (callbackOnOK)
{
callbackOnOK();
}
}
onRejected: {
materialUI.hideDarkBackground();
if (callbackOnOK)
{
callbackOnOK();
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialDialogAlert.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 204
|
```qml
/*
* QML Material - An application framework implementing Material Design.
*
* This program is free software: you can redistribute it and/or modify
* published by the Free Software Foundation, either version 2.1 of the
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
import QtQuick 2.5
import QtQuick.Layouts 1.1
import "../Element"
PopupBase {
id: dialog
overlayLayer: "dialogOverlayLayer"
overlayColor: Qt.rgba(0, 0, 0, 0.3)
opacity: showing ? 1 : 0
visible: opacity > 0
width: Math.max(minimumWidth,
content.contentWidth + (32))
height: headerView.height + (32) +
content.contentHeight +
content.topMargin +
content.bottomMargin +
buttonContainer.height
property int minimumWidth: (270)
property alias title: titleLabel.text
property alias text: textLabel.text
property string negativeButtonText: "Negative"
property string positiveButtonText: "Positive"
property bool hasActions: true
property alias positiveButtonEnabled: positiveButton.enabled
default property alias dialogContent: column.data
signal accepted()
signal rejected()
anchors {
centerIn: parent
verticalCenterOffset: (showing) ? ((height > 400) ? (-15) : (-10)) : ((dialog.height / -3) - 20)
Behavior on verticalCenterOffset {
NumberAnimation { duration: 300; easing.type: Easing.OutQuad }
}
}
Behavior on opacity {
NumberAnimation { duration: 200 }
}
Keys.onEscapePressed: {
dialog.close();
rejected();
}
View {
id: dialogContainer
anchors.fill: parent
elevation: 5
radius: (2)
MouseArea {
anchors.fill: parent
propagateComposedEvents: false
onClicked: {
mouse.accepted = false
}
}
Item {
anchors {
left: parent.left
right: parent.right
top: parent.top
topMargin: (8)
}
clip: true
height: headerView.height + (32)
View {
backgroundColor: "white"
elevation: content.atYBeginning ? 0 : 1
fullWidth: true
anchors {
left: parent.left
right: parent.right
top: parent.top
}
height: headerView.height + (16)
}
}
Column {
id: headerView
spacing: (16)
anchors {
left: parent.left
right: parent.right
top: parent.top
leftMargin: (16)
rightMargin: (16)
topMargin: (16)
}
MaterialLabel {
id: titleLabel
width: parent.width
wrapMode: Text.Wrap
style: "title"
visible: text != ""
}
MaterialLabel {
id: textLabel
width: parent.width
wrapMode: Text.Wrap
style: "dialog"
visible: text != ""
}
}
Flickable {
id: content
contentWidth: column.implicitWidth
contentHeight: column.height
clip: true
anchors {
left: parent.left
right: parent.right
top: headerView.bottom
topMargin: (8)
bottomMargin: (-8)
bottom: buttonContainer.top
}
interactive: contentHeight + (8) > height
bottomMargin: hasActions ? 0 : (8)
Rectangle {
width: content.width
height: content.height
color: "#ffffff"
}
Column {
id: column
anchors {
left: parent.left
margins: (16)
}
width: content.width - (32)
spacing: (16)
}
}
Scrollbar {
flickableItem: content
}
Item {
id: buttonContainer
anchors {
bottomMargin: (8)
bottom: parent.bottom
right: parent.right
left: parent.left
}
height: hasActions ? buttonView.height + (8) : 0
clip: true
View {
id: buttonView
height: hasActions ? positiveButton.implicitHeight + (8) : 0
visible: hasActions
backgroundColor: "white"
elevation: content.atYEnd ? 0 : 1
fullWidth: true
elevationInverted: true
anchors {
bottom: parent.bottom
right: parent.right
left: parent.left
}
MaterialButton {
id: negativeButton
elevation: 0
text: negativeButtonText
textColor: "#2196f3"
context: "dialog"
visible: negativeButtonText !== ""
anchors {
top: parent.top
right: positiveButton.left
topMargin: (8)
rightMargin: (8)
}
onClicked: {
dialog.close()
rejected();
}
}
MaterialButton {
id: positiveButton
elevation: 0
text: positiveButtonText
textColor: "#2196f3"
context: "dialog"
visible: positiveButtonText !== ""
anchors {
top: parent.top
topMargin: (8)
rightMargin: (16)
right: parent.right
}
onClicked: {
dialog.close()
accepted();
}
}
}
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialDialog.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,246
|
```qml
import QtQuick 2.5
import QtQuick.Controls 1.4 as Controls
import QtQuick.Controls.Styles 1.4 as ControlStyles
MaterialDialog {
id: dialog
negativeButtonText: ("Cancel")
positiveButtonText: ("OK")
property var callbackOnCancel: null
property var callbackOnOK: null
function show(title, message, currentDate, callbackOnCancel, callbackOnOK) {
dialog.title = title;
dialog.text = message;
dialog.callbackOnCancel = callbackOnCancel;
dialog.callbackOnOK = callbackOnOK;
dialog.open();
if (currentDate)
{
datePicker.selectedDate = currentDate;
}
else
{
datePicker.selectedDate = new Date;
}
materialUI.showDarkBackground();
}
onAccepted: {
materialUI.hideDarkBackground();
if (callbackOnOK)
{
callbackOnOK( datePicker.selectedDate );
}
}
onRejected: {
materialUI.hideDarkBackground();
if (callbackOnCancel)
{
callbackOnCancel();
}
}
Item {
width: datePicker.width
height: datePicker.height
MaterialDatePicker {
id: datePicker
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialDialogDatePicker.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 262
|
```qml
/*
* QML Material - An application framework implementing Material Design.
*
* This program is free software: you can redistribute it and/or modify
* published by the Free Software Foundation, either version 2.1 of the
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
import QtQuick 2.5
import QtQuick.Controls 1.4
import "../Element"
/*
* Note that this is a FocusScope, not a TextInput. If you need to read or
* write properties of the input itself, use the input property.
*/
FocusScope {
id: field
property color accentColor: "#2196f3"
property color errorColor: "#F44336"
property alias readOnly: textInput.readOnly
property alias text: textInput.text
property alias echoMode: textInput.echoMode
property alias validator: textInput.validator
property alias placeholderText: fieldPlaceholder.text
property alias helperText: helperTextLabel.text
readonly property int characterCount: text.length
property bool floatingLabel: true
property bool hasError: false
property int characterLimit: -1
property bool characterLimitVisible: true
readonly property rect inputRect: Qt.rect(textInput.x, textInput.y, textInput.width, textInput.height)
readonly property alias input: textInput
signal accepted()
signal editingFinished()
implicitHeight: __internal.showHelperText ? helperTextLabel.y + helperTextLabel.height + (4)
: underline.y + (8)
width: (200)
height: (56)
QtObject {
id: __internal
property bool showHelperText: helperText.length > 0
property bool showCharacterCounter: (characterLimit > 0) && characterLimitVisible
}
MouseArea {
anchors.fill: parent
onClicked: field.forceActiveFocus(Qt.MouseFocusReason)
}
TextInput {
id: textInput
focus: true
color: "#d8000000"
selectedTextColor: "white"
selectionColor: Qt.darker(field.accentColor, 1)
// selectByMouse: Device.type === Device.desktop
selectByMouse: true
activeFocusOnTab: true
maximumLength: (characterLimit !== -1) ? (characterLimit) : (32767)
width: parent.width
clip: true
y: {
if ( !floatingLabel )
return (16)
if ( floatingLabel && !__internal.showHelperText )
return (40)
return (28)
}
font {
family: {
if ((echoMode == TextInput.Password) && (field.text.length > 0))
{
return "";
}
switch (Qt.platform.os)
{
case "windows": return "";
default: return "Roboto";
}
}
pixelSize: (16)
}
onAccepted: field.accepted()
onEditingFinished: field.editingFinished()
MouseArea {
anchors.fill: parent
cursorShape: Qt.IBeamCursor
acceptedButtons: Qt.NoButton
}
}
MaterialLabel {
id: fieldPlaceholder
text: field.placeholderText
font.pixelSize: (16)
anchors.baseline: textInput.baseline
anchors.bottomMargin: (8)
color: "#42000000"
states: [
State {
name: "floating"
when: textInput.displayText.length > 0 && floatingLabel
AnchorChanges {
target: fieldPlaceholder
anchors.baseline: undefined
anchors.bottom: textInput.top
}
PropertyChanges {
target: fieldPlaceholder
font.pixelSize: (12)
}
},
State {
name: "hidden"
when: textInput.displayText.length > 0 && !floatingLabel
PropertyChanges {
target: fieldPlaceholder
visible: false
}
}
]
transitions: [
Transition {
id: floatingTransition
enabled: false
AnchorAnimation {
duration: 200
}
NumberAnimation {
duration: 200
property: "font.pixelSize"
}
}
]
Component.onCompleted: floatingTransition.enabled = true
}
Rectangle {
id: underline
color: field.hasError || (__internal.showCharacterCounter && field.characterCount > field.characterLimit)
? field.errorColor : field.activeFocus ? field.accentColor : "#42000000"
height: field.activeFocus ? (2) : (1)
anchors {
left: parent.left
right: parent.right
top: textInput.bottom
topMargin: (8)
}
Behavior on height {
NumberAnimation { duration: 200 }
}
Behavior on color {
ColorAnimation { duration: 200 }
}
}
MaterialLabel {
id: helperTextLabel
visible: __internal.showHelperText
font.pixelSize: (12)
color: field.hasError ? field.errorColor : Qt.darker("#42000000")
anchors {
left: parent.left
right: parent.right
top: underline.top
topMargin: (4)
}
Behavior on color {
ColorAnimation { duration: 200 }
}
}
MaterialLabel {
id: characterCounterLabel
visible: __internal.showCharacterCounter
font.pixelSize: (12)
font.weight: Font.Light
color: field.characterCount <= field.characterLimit ? Qt.darker("#42000000") : field.errorColor
text: field.characterCount + " / " + field.characterLimit
anchors {
right: parent.right
top: underline.top
topMargin: (8)
}
Behavior on color {
ColorAnimation { duration: 200 }
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialTextField.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,290
|
```qml
/*
* QML Material - An application framework implementing Material Design.
*
* This program is free software: you can redistribute it and/or modify
* published by the Free Software Foundation, either version 2.1 of the
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
import QtQuick 2.5
import QtQuick.Controls 1.4 as Controls
import QtQuick.Controls.Styles 1.4 as ControlStyles
import "../Element"
Controls.Button {
id: button
height: 36
property int elevation: 1
property color backgroundColor: elevation > 0 ? "white" : "transparent"
property color textColor: lightDark(button.backgroundColor,
"#d8000000",
"#ffffff")
property string textFontFamily: {
switch (Qt.platform.os)
{
case "windows": return "";
default: return "Roboto";
}
}
property int textSize: 16
property int textVerticalAlignment: Text.AlignVCenter
property int textHorizontalAlignment: Text.AlignHCenter
property bool textFontBold: false
property string context: "default" // or "dialog" or "snackbar"
property int labelWidth
property var itemForLabel: null
property bool iconVisible: false
property int iconSize: 40
property string iconFontFamily: ""
property string iconText: ""
function lightDark(background, lightColor, darkColor) {
return isDarkColor(background) ? darkColor : lightColor
}
function isDarkColor(background) {
var temp = Qt.darker(background, 1)
var a = 1 - ( 0.299 * temp.r + 0.587 * temp.g + 0.114 * temp.b);
return temp.a > 0 && a >= 0.3
}
style: ControlStyles.ButtonStyle {
padding {
left: 0
right: 0
top: 0
bottom: 0
}
background: View {
radius: (2)
elevation: {
var elevation = button.elevation
if (elevation > 0 && (control.focus || mouseArea.currentCircle))
elevation++;
return elevation;
}
backgroundColor: button.backgroundColor
tintColor: mouseArea.currentCircle || control.focus || ((isSmartPhone()) ? (false) : (control.hovered))
? Qt.rgba(0,0,0, mouseArea.currentCircle
? 0.1 : button.elevation > 0 ? 0.03 : 0.05)
: "transparent"
function isSmartPhone() {
return (Qt.platform.os === "ios") || (Qt.platform.os === "android");
}
Ink {
id: mouseArea
anchors.fill: parent
focused: control.focus && button.context != "dialog" && button.context != "snackbar"
focusWidth: parent.width - (30)
focusColor: Qt.darker(button.backgroundColor, 1.05)
Connections {
target: control.__behavior
onPressed: mouseArea.onPressed(mouse)
onCanceled: mouseArea.onCanceled()
onReleased: mouseArea.onReleased(mouse)
}
}
}
label: Item {
implicitHeight: Math.max((36), label.height + (16))
implicitWidth: button.context == "dialog" ? Math.max((64), label.width + (16))
: button.context == "snackbar" ? label.width + (16)
: Math.max((88), label.width + (32))
Controls.Label {
id: label
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenterOffset: (iconVisible) ? (iconSize / 2) : (0)
font.pixelSize: textSize
text: control.text
font.family: textFontFamily
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
color: (control.enabled) ? (button.textColor) : (alpha(button.textColor, 0.4))
renderType: Text.QtRendering
function alpha(color, alpha) {
var realColor = Qt.darker(color, 1)
realColor.a = alpha
return realColor
}
onWidthChanged: {
labelWidth = width;
}
Component.onCompleted: {
button.itemForLabel = this;
}
Controls.Label {
anchors.right: parent.left
anchors.rightMargin: 5
anchors.verticalCenter: parent.verticalCenter
font.pixelSize: iconSize
font.family: iconFontFamily
visible: iconVisible
color: parent.color
text: iconText
}
}
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialButton.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,064
|
```qml
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
MaterialDialog {
id: dialog
negativeButtonText: ("Cancel")
positiveButtonText: ("OK")
positiveButtonEnabled: currentItemIndex !== -1
property var callbackOnCancel: null
property var callbackOnOK: null
property int currentItemIndex
property string currentItemText
property var currentItemFlag
function show(title, message, listData, callbackOnCancel, callbackOnOK) {
dialog.title = title;
dialog.text = message;
dialog.callbackOnCancel = callbackOnCancel;
dialog.callbackOnOK = callbackOnOK;
dialog.open();
listView.contentY = 0;
currentItemIndex = -1;
currentItemText = "";
currentItemFlag = null;
materialUI.showDarkBackground();
listModel.clear();
for (var index = 0; index < listData.length; index++)
{
listModel.append({
itemIndex: index,
itemText: listData[index]["text"],
itemFlag: ("flag" in listData[index]) ? (listData[index]["flag"]) : (""),
itemTooltip: ("tooltip" in listData[index]) ? (listData[index]["tooltip"]) : (""),
defaultChecked: ("checked" in listData[index]) ? (listData[index]["checked"]) : (false)
});
}
}
onAccepted: {
materialUI.hideDarkBackground();
if (callbackOnOK)
{
callbackOnOK(currentItemIndex, currentItemText, currentItemFlag);
}
}
onRejected: {
materialUI.hideDarkBackground();
if (callbackOnCancel)
{
callbackOnCancel();
}
}
ExclusiveGroup {
id: checkGroup
}
ListView {
id: listView
x: 0
y: 55
width: 270
height: 150
clip: true
boundsBehavior: Flickable.StopAtBounds
onContentYChanged: {
slider.value = -1 * contentY;
}
delegate: Item {
width: 270
height: 50
Component.onCompleted: {
if (defaultChecked || (itemIndex === 0))
{
radioButton.checked = true;
currentItemIndex = itemIndex;
currentItemText = itemText;
currentItemFlag = itemFlag;
}
}
MaterialButton {
anchors.fill: parent
tooltip: itemTooltip
elevation: 0
onClicked: {
radioButton.checked = true;
currentItemIndex = itemIndex;
currentItemText = itemText;
currentItemFlag = itemFlag;
}
}
Rectangle {
x: 10
y: 49
width: 270
height: 1
color: "#50afafbc"
}
MaterialLabel {
x: 50
y: 15
text: itemText
font.pixelSize: 17
}
MaterialRadioButton {
id: radioButton
y: 15
width: 25
height: 20
exclusiveGroup: checkGroup
checked: defaultChecked
onCheckedChanged: {
if ( !checked ) { return; }
radioButton.checked = true;
currentItemIndex = itemIndex;
currentItemText = itemText;
currentItemFlag = itemFlag;
}
}
}
model: ListModel {
id: listModel
}
Rectangle {
width: parent.width
height: 1
color: "#e7e7e7"
anchors.left: listView.left
anchors.bottom: listView.bottom
}
Rectangle {
width: parent.width
height: 1
color: "#e7e7e7"
anchors.left: listView.left
anchors.top: listView.top
}
Slider {
id: slider
anchors.right: listView.right
anchors.rightMargin: line.width - 16
anchors.top: listView.top
width: 16
height: listView.height
minimumValue: -1 * (((listView.contentHeight - listView.height) > 0) ? (listView.contentHeight - listView.height) : (0))
maximumValue: listModel.count * 0
orientation: Qt.Vertical
visible: ((listView.contentHeight - listView.height) > 0) && !materialUI.isSmartPhone()
onValueChanged: {
listView.contentY = -1 * value;
}
style: SliderStyle {
groove: Rectangle {
color: "#00000000"
}
handle: Rectangle {
width: 32
height: 16
color: "#00000000"
Rectangle {
x: 1
y: (height - 2) / 5
width: 30
height: (control.hovered || control.pressed) ? (12) : (7)
color: "#dd666666"
implicitWidth: 34
implicitHeight: 34
radius: height / 2
opacity: 0.8
onHeightChanged: {
line.width = height + 4;
}
Behavior on height { PropertyAnimation { } }
}
}
}
Rectangle {
id: line
y: -1
width: 10
height: parent.height + 2
border.color: "#88999999"
color: "#11999999"
opacity: (width - 11) / 5
}
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialDialogScrolling.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 1,207
|
```qml
import QtQuick 2.5
import QtQuick.Controls 1.4 as Controls
import QtGraphicalEffects 1.0
import "../Element"
Controls.TableView {
id: tableView
width: 400
height: 400
enabled: modelForTableView.count > -1
alternatingRowColors: false
backgroundVisible: false
headerVisible: true
sortIndicatorVisible: true
frameVisible: false
horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff
verticalScrollBarPolicy: Qt.ScrollBarAlwaysOff
property real headerHeight: 40
property real itemHeight: 35
property real rectangularGlowCornerRadius: 3
model: ListModel {
id: modelForTableView
}
headerDelegate: Rectangle {
width: 80
height: headerHeight
color: "#ffffff"
radius: 3
Rectangle {
anchors.bottom: parent.bottom
width: parent.width
height: 1
color: "#00000000"
border.width: 1
border.color: "#e1e1e1"
}
Controls.Label {
anchors.fill: parent
text: styleData.value
font.pixelSize: 15
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
color: "#606060"
elide: Text.ElideRight
font.family: {
switch (Qt.platform.os)
{
case "windows": return "";
default: return "Roboto";
}
}
}
}
itemDelegate: Rectangle {
id: itemForTableView
color: (styleData.selected) ? ("#f3f3f3") : ("#00000000")
Rectangle {
anchors.bottom: parent.bottom
width: parent.width
height: 1
color: "#00000000"
border.width: 1
border.color: "#e1e1e1"
}
Controls.Label {
anchors.fill: parent
text: styleData.value
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
color: "#000000"
font.pixelSize: 13
elide: Text.ElideRight
font.family: {
switch (Qt.platform.os)
{
case "windows": return "";
default: return "Roboto";
}
}
}
}
rowDelegate: Item {
height: itemHeight
}
function appendText(texts) {
var buf = new Object;
for (var index = 0; index < texts.length; index++)
{
buf["text" + index] = texts[index];
}
modelForTableView.append(buf)
}
function setText(row, texts) {
if (modelForTableView.count <= row)
{
appendText(texts);
}
else
{
for (var index = 0; index < texts.length; index++)
{
modelForTableView.get(row)["text" + index] = texts[index];
}
}
}
function clear() {
modelForTableView.clear();
}
RectangularGlow {
x: 0
y: 1
z: -1
width: parent.width
height: parent.height
glowRadius: 2
spread: 0.22
color: "#30000000"
}
Rectangle {
z: -1
id: rectangleForBacaground
anchors.fill: parent
color: "#ffffff"
radius: tableView.rectangularGlowCornerRadius
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialTableView.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 787
|
```qml
import QtQuick 2.5
import QtQuick.Controls 1.4 as Controls
import QtQuick.Controls.Styles 1.4 as ControlStyles
import QtGraphicalEffects 1.0
Item {
id: tabs
signal indexRefreshed();
property var tabSource
property var iconDatas
property int currentItemX
property int currentItemWidth
property int tabHeight: 48
property int tabsAlignment: Qt.AlignHCenter
property alias currentIndex: tabView.currentIndex
property alias tabPosition: tabView.tabPosition
property bool hideTopShadow: false
property bool hideTopBackground: false
property alias tabView: tabView
property alias needleColor: needle.color
property alias backgroundColor: tabBackground.color
Component.onCompleted: {
for (var index = 0; index < tabSource.length; index++)
{
var tab = tabView.addTab(tabSource[index]["title"], tabSource[index]["source"]);
if ("objectName" in tabSource[index])
{
tab.children[0].item.objectName = tabSource[index]["objectName"];
}
}
indexRefreshed();
}
Controls.TabView {
id: tabView
anchors.fill: parent
clip: false
style: ControlStyles.TabViewStyle {
frameOverlap: 0
tabOverlap: 0
tabsAlignment: tabs.tabsAlignment
tab: MaterialButton {
height: tabs.tabHeight
text: styleData.title
textColor: (styleData.selected) ? ("#ffffff") : ("#a2ffffff")
implicitWidth: Math.min(Math.max(labelWidth + 40, 80), tabView.width / tabView.count)
elevation: 0
Component.onCompleted: {
if (tabs.iconDatas && (tabs.iconDatas.length >= styleData.index) && tabs.iconDatas[styleData.index])
{
iconVisible = true;
iconFontFamily = tabs.iconDatas[styleData.index]["fontFamily"];
iconText = tabs.iconDatas[styleData.index]["text"];
iconSize = textSize * 1.5;
}
if ( "implicitWidth" in tabs.tabSource[ styleData.index ] )
{
implicitWidth = tabs.tabSource[ styleData.index ][ "implicitWidth" ];
}
}
function refreshPosition() {
if (tabView.currentIndex === styleData.index)
{
needle.x = parent.parent.x + parent.parent.parent.parent.x
needle.width = width
}
}
onClicked: {
tabView.currentIndex = styleData.index;
}
Connections {
target: parent.parent.parent.parent
onXChanged: {
refreshPosition();
}
}
Connections {
target: tabs
onWidthChanged: {
refreshPosition();
}
onCurrentIndexChanged: {
refreshPosition();
}
onIndexRefreshed: {
refreshPosition();
}
}
Behavior on textColor {
ColorAnimation { duration: 200; }
}
}
frame: Rectangle {
color: "#00000000"
}
}
RectangularGlow {
z: 1
anchors.fill: tabBackground
glowRadius: 6
spread: 0.22
color: "#40000000"
visible: !hideTopShadow
}
Rectangle {
id: tabBackground
x: 0
y: -1 * (tabs.tabHeight)
z: 1
width: tabView.width
height: (tabs.tabHeight)
color: "#07bdd3"
visible: !hideTopBackground
}
}
Rectangle {
id: needle
x: 0
y: (tabs.tabPosition === Qt.TopEdge) ? (tabs.tabHeight - 2) : (parent.height - tabs.tabHeight)
width: 20
height: (2)
color: "#ffff95"
Behavior on x {
NumberAnimation { duration: 200; easing.type: Easing.OutCubic }
}
Behavior on width {
NumberAnimation { duration: 200; }
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialTabs.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 892
|
```qml
/*
* QML Material - An application framework implementing Material Design.
*
* This program is free software: you can redistribute it and/or modify
* published by the Free Software Foundation, either version 2.1 of the
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*/
import QtQuick 2.5
import QtQuick.Controls 1.4
import "../Element"
/*!
\qmltype BottomActionSheet
\inqmlmodule Material 0.1
\brief Represents a bottom sheet displaying a list of actions with an optional title.
*/
BottomSheet {
id: bottomSheet
property string title
property var callbackOnCancel: null
property var callbackOnOK: null
implicitHeight: title !== "" ? header.height + listViewContainer.implicitHeight
: listViewContainer.implicitHeight
function show(title, sheetData, callbackOnCancel, callbackOnOK) {
bottomSheet.title = title;
bottomSheet.callbackOnCancel = callbackOnCancel;
bottomSheet.callbackOnOK = callbackOnOK;
bottomSheet.open();
materialUI.showDarkBackground(function() {
bottomSheet.close();
materialUI.hideDarkBackground();
if (bottomSheet.callbackOnCancel)
{
bottomSheet.callbackOnCancel();
}
});
listModel.clear();
for (var index = 0; index < sheetData.length; index++)
{
listModel.append({
itemIndex: index,
itemText: sheetData[index]["text"],
itemFlag: ("flag" in sheetData[index]) ? (sheetData[index]["flag"]) : (null),
hasDividerAfter: ("hasDividerAfter" in sheetData[index]) ? (sheetData[index]["hasDividerAfter"]) : (false)
});
}
}
Column {
id: column
anchors.fill: parent
Subheader {
id: header
text: title
visible: title !== ""
height: (56)
style: "subheading"
backgroundColor: "white"
elevation: listView.atYBeginning ? 0 : 1
fullWidth: true
z: 2
}
Item {
id: listViewContainer
width: parent.width
height: title !== "" ? parent.height - header.height : parent.height
implicitHeight: listView.contentHeight + listView.topMargin + listView.bottomMargin
Flickable {
id: listView
width: parent.width
height: parent.height
interactive: bottomSheet.height < bottomSheet.implicitHeight
topMargin: title !== "" ? 0 : (8)
bottomMargin: (8)
contentWidth: width
contentHeight: subColumn.height
Column {
id: subColumn
width: parent.width
Repeater {
model: ListModel {
id: listModel
}
delegate: Column {
width: subColumn.width
Standard {
id: listItem
text: itemText
visible: subColumn.visible
enabled: subColumn.enabled
labelHorizontalAlignment: Text.AlignHCenter
onClicked: {
actionSheet.close();
materialUI.hideDarkBackground();
if (callbackOnOK)
{
callbackOnOK(itemIndex, itemText, (((typeof itemFlag) !== "undefined") ? (itemFlag) : (null)));
}
}
}
Divider {
visible: hasDividerAfter
}
}
}
}
}
Scrollbar {
flickableItem: listView
}
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialBottomActionSheet.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 795
|
```qml
import QtQuick 2.5
import QtQuick.Controls 1.4 as Controls
import QtQuick.Controls.Styles 1.4 as ControlStyles
MaterialDialog {
id: dialog
negativeButtonText: ("Cancel")
positiveButtonText: ("OK")
Component.onCompleted: {
dialog.open()
}
property var callbackOnCancel: null
property var callbackOnOK: null
function show(title, message, currentText, callbackOnCancel, callbackOnOK) {
dialog.title = title;
dialog.text = message;
dialog.callbackOnCancel = callbackOnCancel;
dialog.callbackOnOK = callbackOnOK;
dialog.open();
textArea.text = currentText;
materialUI.showDarkBackground();
}
onAccepted: {
materialUI.hideDarkBackground();
if (callbackOnOK)
{
callbackOnOK(textArea.text);
}
}
onRejected: {
materialUI.hideDarkBackground();
if (callbackOnCancel)
{
callbackOnCancel();
}
}
Item {
width: 300
height: 300
clip: true
Controls.TextArea {
id: textArea
x: -5
y: -5
width: parent.width + 10
height: parent.height + 10
wrapMode: TextInput.WordWrap
textMargin: 10
style: ControlStyles.TextAreaStyle {
selectedTextColor: "#ffffff"
selectionColor: "#2799f3"
textColor: "#000000"
}
}
Rectangle {
x: 1
y: 1
width: parent.width - 2
height: parent.height - 2
border.color: "#a1a1a1"
border.width: 1
color: "#00000000"
}
}
}
```
|
/content/code_sandbox/library/MaterialUI/Interface/MaterialDialogTextArea.qml
|
qml
| 2016-05-15T04:09:51
| 2024-08-15T07:23:05
|
JQTools
|
188080501/JQTools
| 1,683
| 399
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.