Merge lp:~widelands-dev/widelands/richtext_testing into lp:widelands

Proposed by SirVer
Status: Merged
Merged at revision: 7063
Proposed branch: lp:~widelands-dev/widelands/richtext_testing
Merge into: lp:widelands
Diff against target: 13329 lines (+1268/-9925)
102 files modified
CMakeLists.txt (+1/-0)
CREDITS (+0/-5)
doc/sphinx/source/index.rst (+0/-1)
doc/sphinx/source/manual_testing.rst (+0/-23)
manual_test/README (+0/-4)
manual_test/richtext/SConstruct (+0/-43)
manual_test/richtext/from_file_image_loader.cc (+0/-73)
manual_test/richtext/from_file_image_loader.h (+0/-29)
manual_test/richtext/lodepng.cc (+0/-5896)
manual_test/richtext/lodepng.h (+0/-1596)
manual_test/richtext/pyrt_render.pyx (+0/-70)
manual_test/richtext/site_scons/site_tools/README_cython.txt (+0/-38)
manual_test/richtext/site_scons/site_tools/_cython_dependencies.py (+0/-95)
manual_test/richtext/site_scons/site_tools/cython.py (+0/-88)
manual_test/richtext/site_scons/site_tools/pyext.py (+0/-238)
manual_test/richtext/test.py (+0/-87)
src/CMakeLists.txt (+12/-2)
src/graphic/CMakeLists.txt (+18/-8)
src/graphic/color.cc (+10/-1)
src/graphic/color.h (+4/-0)
src/graphic/font_handler1.cc (+13/-17)
src/graphic/font_handler1.h (+1/-1)
src/graphic/graphic.cc (+7/-104)
src/graphic/graphic.h (+0/-12)
src/graphic/image_cache.cc (+21/-53)
src/graphic/image_cache.h (+13/-9)
src/graphic/image_io.cc (+114/-16)
src/graphic/image_io.h (+31/-19)
src/graphic/image_loader_impl.h (+0/-35)
src/graphic/render/gamerenderer_gl.cc (+3/-10)
src/graphic/render/sdl_helper.cc (+0/-1)
src/graphic/render/sdl_surface.cc (+7/-0)
src/graphic/render/sdl_surface.h (+1/-6)
src/graphic/surface.cc (+21/-11)
src/graphic/surface.h (+7/-0)
src/graphic/surface_cache.cc (+0/-1)
src/graphic/text/CMakeLists.txt (+8/-4)
src/graphic/text/font_io.cc (+19/-41)
src/graphic/text/font_io.h (+34/-0)
src/graphic/text/rt_errors.h (+2/-1)
src/graphic/text/rt_errors_impl.h (+3/-0)
src/graphic/text/rt_parse.cc (+48/-109)
src/graphic/text/rt_parse.h (+78/-39)
src/graphic/text/rt_render.cc (+103/-121)
src/graphic/text/rt_render.h (+20/-19)
src/graphic/text/sdl_ttf_font.cc (+7/-3)
src/graphic/text/sdl_ttf_font.h (+9/-8)
src/graphic/text/sdl_ttf_font_loader_from_file.cc (+0/-64)
src/graphic/text/test/CMakeLists.txt (+42/-0)
src/graphic/text/test/data/b1206712/input01.txt (+1/-0)
src/graphic/text/test/data/b1206712/width (+1/-0)
src/graphic/text/test/data/bullet_point/input00.txt (+3/-3)
src/graphic/text/test/data/hline/input00.txt (+1/-1)
src/graphic/text/test/data/hspace_dynamic1/input00.txt (+1/-1)
src/graphic/text/test/data/hspace_dynamic2/input00.txt (+1/-1)
src/graphic/text/test/data/hspace_dynamic_img/input00.txt (+3/-3)
src/graphic/text/test/data/hspace_fixed/input00.txt (+1/-1)
src/graphic/text/test/data/img_simple/input00.txt (+1/-1)
src/graphic/text/test/data/p_valign_center/input00.txt (+1/-1)
src/graphic/text/test/data/p_valign_default/input00.txt (+1/-1)
src/graphic/text/test/data/p_valign_top/input00.txt (+1/-1)
src/graphic/text/test/data/rt_padding/input00.txt (+1/-1)
src/graphic/text/test/data/rt_padding_allsites/input00.txt (+1/-1)
src/graphic/text/test/data/sub_autowidth_floatleftimg/input00.txt (+1/-1)
src/graphic/text/test/data/sub_background_img/input00.txt (+1/-1)
src/graphic/text/test/data/sub_fixedwidth_floatleftimg/input00.txt (+1/-1)
src/graphic/text/test/data/sub_margin_bgimg/input00.txt (+1/-1)
src/graphic/text/test/data/sub_nonfloating_valign/input00.txt (+2/-2)
src/graphic/text/test/data/sub_padding/input00.txt (+1/-1)
src/graphic/text/test/data/vspace/input00.txt (+2/-2)
src/graphic/text/test/paths.h.cmake (+8/-0)
src/graphic/text/test/render.cc (+23/-157)
src/graphic/text/test/render.h (+22/-6)
src/graphic/text/test/render_richtext.cc (+139/-0)
src/graphic/text/test/test_richtext_renderer.cc (+301/-0)
src/io/CMakeLists.txt (+0/-1)
src/io/filesystem/disk_filesystem.cc (+3/-1)
src/io/filesystem/layered_filesystem.cc (+20/-174)
src/io/filesystem/layered_filesystem.h (+11/-25)
src/io/filewrite.cc (+4/-0)
src/io/filewrite.h (+4/-0)
src/logic/CMakeLists.txt (+1/-0)
src/logic/expedition_bootstrap.cc (+1/-1)
src/logic/game.cc (+2/-2)
src/logic/immovable.cc (+0/-2)
src/logic/terrain_affinity.cc (+1/-1)
src/logic/walkingdir.cc (+1/-2)
src/map_io/CMakeLists.txt (+1/-1)
src/network/CMakeLists.txt (+1/-0)
src/scripting/CMakeLists.txt (+1/-1)
src/scripting/lua_map.cc (+3/-1)
src/scripting/test/test_luna.cc (+4/-2)
src/sound/CMakeLists.txt (+1/-1)
src/third_party/CMakeLists.txt (+0/-1)
src/third_party/eris/lua.c (+0/-497)
src/ui_basic/CMakeLists.txt (+1/-0)
src/ui_fsmenu/CMakeLists.txt (+2/-0)
src/ui_fsmenu/loadgame.cc (+3/-4)
src/ui_fsmenu/loadgame.h (+0/-4)
src/wlapplication.cc (+9/-10)
src/wui/CMakeLists.txt (+1/-0)
src/wui/chatoverlay.cc (+16/-5)
To merge this branch: bzr merge lp:~widelands-dev/widelands/richtext_testing
Reviewer Review Type Date Requested Status
Hans Joachim Desserud Needs Fixing
Tino Approve
SirVer Needs Resubmitting
Review via email: mp+225733@code.launchpad.net

Description of the change

Suggested commit message:

Now that the cmake refactoring is in place, it became feasible to move the rich text test suite into ctest and the standard build process. This now runs the tests as unit tests after each compile.

- Get rid of manual_testing and related documentation.
- Moves all tests in manual_testing/richtext into src/graphic/text/test and run them with cmake.
- This simplified a lot of code. I could get rid of some interfaces and the dependency on lodepng.
- Split png saving/image_loading away from graphic.cc into a image_io library.
- Fixes a bunch of TODO.
- Removed luac.c as it defined a main() function. This was troublesome for tests.
- Fixes bug 1206712 (again) and 1283693.

To post a comment you must log in.
Revision history for this message
Hans Joachim Desserud (hjd) wrote :

Even after applying my fix so it finds the SDL-headers, this still fails to build for me (Ubuntu 14.04 / GCC 4.8.2):
Linking CXX executable test_richtext_renderer
1../../../third_party/libthird_party_eris.a(loslib.c.o): In function `os_tmpname':
/home/user/dev/richtext_testing/src/third_party/eris/loslib.c:108: warning: the use of `tmpnam' is dangerous, better use `mkstemp'
../../../ui_basic/libui_basic.a(multilinetextarea.cc.o): In function `UI::Multiline_Textarea::recompute()':
/home/user/dev/richtext_testing/src/ui_basic/multilinetextarea.cc:123: undefined reference to `UI::RichText::set_width(unsigned int)'
/home/user/dev/richtext_testing/src/ui_basic/multilinetextarea.cc:124: undefined reference to `UI::RichText::parse(std::string const&)'
/home/user/dev/richtext_testing/src/ui_basic/multilinetextarea.cc:125: undefined reference to `UI::RichText::height()'
../../../ui_basic/libui_basic.a(multilinetextarea.cc.o): In function `UI::Multiline_Textarea::draw(RenderTarget&)':
/home/user/dev/richtext_testing/src/ui_basic/multilinetextarea.cc:175: undefined reference to `UI::RichText::draw(RenderTarget&, Point const&, bool)'
../../../ui_basic/libui_basic.a(multilinetextarea.cc.o): In function `UI::Multiline_Textarea::Impl::Impl()':
/home/user/dev/richtext_testing/src/ui_basic/multilinetextarea.cc:38: undefined reference to `UI::RichText::RichText()'
../../../ui_basic/libui_basic.a(multilinetextarea.cc.o): In function `UI::Multiline_Textarea::Impl::~Impl()':
/home/user/dev/richtext_testing/src/ui_basic/multilinetextarea.cc:33: undefined reference to `UI::RichText::~RichText()'
collect2: error: ld returned 1 exit status

review: Needs Fixing
Revision history for this message
SirVer (sirver) wrote :

should be fixed. Can you try again?

Revision history for this message
SirVer (sirver) wrote :

one more try. I try now to initialize all pixels, maybe the differences now go away.

Revision history for this message
Tino (tino79) wrote :
Download full text (4.7 KiB)

Hey,

it looks better. I've made a small change and now i've only a few errors left, some of where black pixels are generated (255,555,255) and white expected (0,0,0).
But still some deviations are so big, that kMax[Alpha|Clr]Distance doesn't make sense.

Logoutput:

2/4 Testing: test_richtext_renderer
2/4 Test: test_richtext_renderer
Command: "C:/data/wl_blocks/src/graphic/text/test/test_richtext_renderer.exe"
Directory: C:/data/wl_blocks/src/graphic/text/test
"test_richtext_renderer" start time: Jul 07 08:35 Mitteleurop[NON-UTF-8-BYTE-0xE4]ische Sommerzeit
Output:
----------------------------------------------------------
Running 49 test cases...
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
Mismatched pixel: (92, 0)
 expected: (0, 0, 0, 0)
 seen: (255, 255, 255, 0)
Mismatched pixel: (48, 19)
 expected: (0, 0, 0, 0)
 seen: (255, 255, 255, 0)
Mismatched pixel: (65, 20)
 expected: (0, 0, 0, 0)
 seen: (255, 255, 255, 0)
Mismatched pixel: (0, 39)
 expected: (0, 0, 0, 0)
 seen: (255, 255, 255, 0)
 wrong pixels: 0.00 %
Render output of data\font_shadow\input00.txt does not compare equal to correct.png. Saved wrong.png.
c:/data/bzr/widelands/working/src/graphic/text/test/test_richtext_renderer.cc(261): error in "font_shadow": check compare_for_test(sar.renderer()) failed
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
Mismatched pixel: (0, 24)
 expected: (255, 255, 255, 1)
 seen: (203, 187, 136, 1)
Mismatched pixel: (1, 24)
 expected: (204, 204, 153, 5)
 seen: (225, 208, 146, 5)
Mismatched pixel: (198, 24)
 expected: (255, 255, 127, 2)
 seen: (225, 205, 142, 2)
Mismatched pixel: (199, 24)
 expected: (0, 0, 0, 1)
 seen: (112, 58, 3, 1)
Mismatched pixel: (0, 25)
 expected: (204, 204, 153, 5)
 seen: (215, 196, 135, 5)
Mismatched pixel: (199, 25)
 expected: (170, 85, 0, 3)
 seen: (152, 88, 3, 3)
 wrong pixels: 0.00 %
Render output of data\hline\input00.txt does not compare equal to correct.png. Saved wrong.png.
c:/data/bzr/widelands/working/src/graphic/text/test/test_richtext_renderer.cc(266): error in "hline": check compare_for_test(sar.renderer()) failed
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No version file found
No ...

Read more...

Revision history for this message
Hans Joachim Desserud (hjd) wrote :

After the tweaks done by Tino, most of the failures have gone away on Ubuntu too.
However the two remaining ones require a substantial increase in the difference tolerated that I worry it will end up passing things which should fail.

See the output below for details, but these are the values I found when experimenting.

kMaxClearDistance values
8 (hline + font_shadow failing)
120 (hline starts passing)
256+ Everyting passes, but I assume I have made the tests useless at this point.

Mismatched pixel: (92, 0)
 expected: (0, 0, 0, 0)
 seen: (255, 255, 255, 0)
Mismatched pixel: (48, 19)
 expected: (0, 0, 0, 0)
 seen: (255, 255, 255, 0)
Mismatched pixel: (65, 20)
 expected: (0, 0, 0, 0)
 seen: (255, 255, 255, 0)
Mismatched pixel: (0, 39)
 expected: (0, 0, 0, 0)
 seen: (255, 255, 255, 0)
 wrong pixels: 0.00 %
Render output of data/font_shadow/input00.txt does not compare equal to correct.png. Saved wrong.png.
/home/user/dev/richtext_testing/src/graphic/text/test/test_richtext_renderer.cc(261): error in "font_shadow": check compare_for_test(sar.renderer()) failed

Mismatched pixel: (0, 24)
 expected: (255, 255, 255, 1)
 seen: (203, 187, 136, 1)
Mismatched pixel: (1, 24)
 expected: (204, 204, 153, 5)
 seen: (225, 208, 146, 5)
Mismatched pixel: (198, 24)
 expected: (255, 255, 127, 2)
 seen: (225, 205, 142, 2)
Mismatched pixel: (199, 24)
 expected: (0, 0, 0, 1)
 seen: (112, 58, 3, 1)
Mismatched pixel: (0, 25)
 expected: (204, 204, 153, 5)
 seen: (215, 196, 135, 5)
Mismatched pixel: (199, 25)
 expected: (170, 85, 0, 3)
 seen: (152, 88, 3, 3)
 wrong pixels: 0.00 %
Render output of data/hline/input00.txt does not compare equal to correct.png. Saved wrong.png.
/home/user/dev/richtext_testing/src/graphic/text/test/test_richtext_renderer.cc(266): error in "hline": check compare_for_test(sar.renderer()) failed

Revision history for this message
SirVer (sirver) wrote :

Thanks for looking into this again. I am worried that there is (also?) a real bug lurking in the code and we are not properly updating the Alpha channel somehow. I will add something that randomizes the initially created surfaces to make sure that we are really updating everything.

Revision history for this message
SirVer (sirver) wrote :

One more test please. I found a machine were the tests did not pass and I copied their wrong.png to correct.png and the tests still pass on my machine - weirdly enough. This points me to some weirdness in how PNGs are saved or loaded.

My guess is that the tests now pass on your machines too. If that is the case, I'll call this done.

review: Needs Resubmitting
Revision history for this message
Tino (tino79) wrote :

Compiles, linkes, tests, runs!
*Thumbs up*

review: Approve
Revision history for this message
Hans Joachim Desserud (hjd) wrote :

All tests are green on Ubuntu too. Yay, it's working :)

But, if I have built Widelands and there is a new commit and I try to build it again (via update); I run into this issue:

Version file found with id "bzr7057[richtext_testing]" (real "bzr7058[richtext_testing]" )
not equal strings
File system NOT added
No version file found
unknown location(0): fatal error in "vspace": std::runtime_error: Could not find file: could not find file or directory: fonts/DejaVuSerif.ttf
/home/user/dev/richtext_testing/src/graphic/text/test/test_richtext_renderer.cc(299): last checkpoint

(A simple fix which seemed to work was to delete the VERSION file, but then if the rebuild fails, I would have no idea what the latest successful build was. I am not sure why the version number is compared and what the gain is.)

review: Needs Fixing
Revision history for this message
SirVer (sirver) wrote :

After positive feedback from win32 and linux I merged this now. Thanks for the help everybody.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'CMakeLists.txt'
2--- CMakeLists.txt 2014-07-07 16:06:30 +0000
3+++ CMakeLists.txt 2014-07-08 19:15:38 +0000
4@@ -181,6 +181,7 @@
5
6 # Turn some warnings into errors.
7 add_flag(WL_COMPILE_DIAGNOSTICS "-Werror=uninitialized")
8+add_flag(WL_COMPILE_DIAGNOSTICS "-Werror=return-type")
9
10 IF (WIN32)
11 set (CMAKE_EXE_LINKER_FLAGS "-Wl,--large-address-aware" CACHE STRING "Set by widelands CMakeLists.txt" FORCE)
12
13=== modified file 'CREDITS'
14--- CREDITS 2013-10-19 10:42:47 +0000
15+++ CREDITS 2014-07-08 19:15:38 +0000
16@@ -80,11 +80,6 @@
17 * https://github.com/fnuecke/eris
18
19
20- Lodepng (for testing, not in Widelands itself)
21- * by Lode Vandevenne
22- * http://lodev.org/lodepng/
23-
24-
25 and last but not least:
26 http://www.launchpad.org
27 * for their bazaar service
28
29=== modified file 'doc/sphinx/source/index.rst'
30--- doc/sphinx/source/index.rst 2014-07-03 07:36:22 +0000
31+++ doc/sphinx/source/index.rst 2014-07-08 19:15:38 +0000
32@@ -15,7 +15,6 @@
33 server
34 geometry
35 productionsite_program
36- manual_testing
37 lua_index
38
39
40
41=== removed file 'doc/sphinx/source/manual_testing.rst'
42--- doc/sphinx/source/manual_testing.rst 2013-09-20 19:09:03 +0000
43+++ doc/sphinx/source/manual_testing.rst 1970-01-01 00:00:00 +0000
44@@ -1,23 +0,0 @@
45-Manual Testing
46-==============
47-
48-The ``manual_test`` directory contains various directories with testing
49-data/scripts/programs that can be used to manually exercise some subpart of
50-widelands. These tests are not integrated into any kind of automated test
51-suite but can be run on a as-needed basis by individual programmers.
52-
53-The following directories are currently available:
54-
55-``richtext/``
56- This contains a test suite for the rich text rendering engine that is
57- contained in ``src/graphic/text/``. The test stuff consists of a thin
58- python wrapper (using cython) and a stand alone c++ program that can render
59- rich text. Compilation is done using SCons, take a look at SConscript for
60- details. The ``test.py`` script renders all examples in the ``test``
61- sub-directory and checks if they match pixel by pixel. To get everything
62- working in this directory, you need SDL, SDL_TTF, cython and numpy.
63-
64-
65-
66-
67-
68
69=== removed directory 'manual_test'
70=== removed file 'manual_test/README'
71--- manual_test/README 2012-06-20 09:07:10 +0000
72+++ manual_test/README 1970-01-01 00:00:00 +0000
73@@ -1,4 +0,0 @@
74-See Manual Testing in the docs (in ../doc/sphinx/source/manual_testing.rst).
75-
76-If you add something to this directory, remember to update the docs.
77-
78
79=== removed file 'manual_test/richtext/SConstruct'
80--- manual_test/richtext/SConstruct 2013-04-20 20:48:48 +0000
81+++ manual_test/richtext/SConstruct 1970-01-01 00:00:00 +0000
82@@ -1,43 +0,0 @@
83-import os
84-import numpy
85-
86-env = Environment(CXX="clang++")
87-env.Append(CCFLAGS= "-Wall -g")
88-
89-## The main library
90-env.ParseConfig("pkg-config sdl --cflags")
91-env.ParseConfig("pkg-config sdl --libs")
92-env.Append(LIBS="SDL_ttf")
93-env.Append(CPPPATH="../../src/")
94-env.Append(CPPPATH="/usr/local/include") # for boost
95-rt_lib = env.Library([
96- "../../src/graphic/image_cache.cc",
97- "../../src/graphic/render/sdl_helper.cc",
98- "../../src/graphic/render/sdl_surface.cc",
99- "../../src/graphic/surface_cache.cc",
100- "../../src/graphic/text/rt_parse.cc",
101- "../../src/graphic/text/rt_render.cc",
102- "../../src/graphic/text/sdl_ttf_font_impl.cc",
103- "../../src/graphic/text/sdl_ttf_font_loader_from_file.cc",
104- "../../src/graphic/text/textstream.cc",
105- "../../src/log.cc",
106-])
107-
108-# Debug program that renders one text
109-render_env = env.Clone()
110-render_env.Append(CXXFLAGS=["-DRENDER_AS_PROGRAM"])
111-render_env.Append(LIBS=[rt_lib])
112-render_env.Program("render", ["render.cc", "lodepng.cc", "from_file_image_loader.cc"])
113-
114-# Python library
115-pylib_env = env.Environment(PYEXT_USE_DISTUTILS=True, SHCXX="clang++", ENV = {'PATH': os.environ["PATH"]})
116-pylib_env.Tool("pyext")
117-pylib_env.Tool("cython")
118-pylib_env.ParseConfig("pkg-config sdl --cflags")
119-pylib_env.ParseConfig("pkg-config sdl --libs")
120-pylib_env.Append(CPPPATH="../../src/")
121-pylib_env.Append(LIBS=["SDL_ttf", rt_lib])
122-pylib_env.Append(CPPPATH=numpy.get_include())
123-ext = pylib_env.PythonExtension("pyrt_render",
124- ["pyrt_render.pyx", "lodepng.cc", "render.cc", "from_file_image_loader.cc"],
125-)
126
127=== removed file 'manual_test/richtext/from_file_image_loader.cc'
128--- manual_test/richtext/from_file_image_loader.cc 2013-07-26 20:19:36 +0000
129+++ manual_test/richtext/from_file_image_loader.cc 1970-01-01 00:00:00 +0000
130@@ -1,73 +0,0 @@
131-/*
132- * Copyright (C) 2006-2013 by the Widelands Development Team
133- *
134- * This program is free software; you can redistribute it and/or
135- * modify it under the terms of the GNU General Public License
136- * as published by the Free Software Foundation; either version 2
137- * of the License, or (at your option) any later version.
138- *
139- * This program is distributed in the hope that it will be useful,
140- * but WITHOUT ANY WARRANTY; without even the implied warranty of
141- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
142- * GNU General Public License for more details.
143- *
144- * You should have received a copy of the GNU General Public License
145- * along with this program; if not, write to the Free Software
146- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
147- *
148- */
149-
150-#include "/Users/sirver/Desktop/Programming/cpp/widelands/bzr_repo/test/richtext/from_file_image_loader.h"
151-
152-#include <SDL.h>
153-#include <boost/format.hpp>
154-
155-#include "graphic/render/sdl_surface.h"
156-#include "graphic/text/rt_errors.h"
157-#include "/Users/sirver/Desktop/Programming/cpp/widelands/bzr_repo/test/richtext/lodepng.h"
158-
159-using namespace boost;
160-using namespace std;
161-
162-class FromFileImageLoader : public IImageLoader {
163-public:
164- virtual ~FromFileImageLoader() {}
165-
166- // Implements IImageLoader.
167- virtual Surface* load(const string& s) const {
168- unsigned w, h;
169- unsigned char * image;
170-
171- unsigned error = lodepng_decode32_file
172- (&image, &w, &h, ("imgs/" + s).c_str());
173- if (error)
174- throw RT::BadImage
175- ((format("Problem loading image %s: %s\n") % s % lodepng_error_text(error)).str());
176-
177- Uint32 rmask, gmask, bmask, amask;
178- /* SDL interprets each pixel as a 32-bit number, so our masks must depend
179- on the endianness (byte order) of the machine */
180-#if SDL_BYTEORDER == SDL_BIG_ENDIAN
181- rmask = 0xff000000;
182- gmask = 0x00ff0000;
183- bmask = 0x0000ff00;
184- amask = 0x000000ff;
185-#else
186- rmask = 0x000000ff;
187- gmask = 0x0000ff00;
188- bmask = 0x00ff0000;
189- amask = 0xff000000;
190-#endif
191-
192- SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(image, w, h, 32, w * 4, rmask, gmask, bmask, amask);
193- if (!surf)
194- throw RT::BadImage
195- ((format("Problem creating surface for image %s: %s\n") % s % SDL_GetError()).str());
196-
197- return new SDLSurface(surf);
198- }
199-};
200-
201-IImageLoader* create_from_file_image_loader() {
202- return new FromFileImageLoader();
203-}
204
205=== removed file 'manual_test/richtext/from_file_image_loader.h'
206--- manual_test/richtext/from_file_image_loader.h 2013-04-20 20:20:34 +0000
207+++ manual_test/richtext/from_file_image_loader.h 1970-01-01 00:00:00 +0000
208@@ -1,29 +0,0 @@
209-/*
210- * Copyright (C) 2006-2013 by the Widelands Development Team
211- *
212- * This program is free software; you can redistribute it and/or
213- * modify it under the terms of the GNU General Public License
214- * as published by the Free Software Foundation; either version 2
215- * of the License, or (at your option) any later version.
216- *
217- * This program is distributed in the hope that it will be useful,
218- * but WITHOUT ANY WARRANTY; without even the implied warranty of
219- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
220- * GNU General Public License for more details.
221- *
222- * You should have received a copy of the GNU General Public License
223- * along with this program; if not, write to the Free Software
224- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
225- *
226- */
227-
228-#ifndef FROM_FILE_IMAGE_LOADER_H
229-#define FROM_FILE_IMAGE_LOADER_H
230-
231-#include "graphic/image_loader.h"
232-
233-IImageLoader* create_from_file_image_loader();
234-
235-#endif /* end of include guard: FROM_FILE_IMAGE_LOADER_H */
236-
237-
238
239=== removed file 'manual_test/richtext/imgs/wl-ico-128.png'
240Binary files manual_test/richtext/imgs/wl-ico-128.png 2012-06-20 09:59:07 +0000 and manual_test/richtext/imgs/wl-ico-128.png 1970-01-01 00:00:00 +0000 differ
241=== removed file 'manual_test/richtext/lodepng.cc'
242--- manual_test/richtext/lodepng.cc 2013-07-21 08:25:22 +0000
243+++ manual_test/richtext/lodepng.cc 1970-01-01 00:00:00 +0000
244@@ -1,5896 +0,0 @@
245-/*
246-LodePNG version 20120528
247-
248-Copyright (c) 2005-2012 Lode Vandevenne
249-
250-This software is provided 'as-is', without any express or implied
251-warranty. In no event will the authors be held liable for any damages
252-arising from the use of this software.
253-
254-Permission is granted to anyone to use this software for any purpose,
255-including commercial applications, and to alter it and redistribute it
256-freely, subject to the following restrictions:
257-
258- 1. The origin of this software must not be misrepresented; you must not
259- claim that you wrote the original software. If you use this software
260- in a product, an acknowledgment in the product documentation would be
261- appreciated but is not required.
262-
263- 2. Altered source versions must be plainly marked as such, and must not be
264- misrepresented as being the original software.
265-
266- 3. This notice may not be removed or altered from any source
267- distribution.
268-*/
269-
270-/*
271-The manual and changelog are in the header file "lodepng.h"
272-Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.
273-*/
274-
275-#include "lodepng.h"
276-
277-#include <stdio.h>
278-#include <stdlib.h>
279-
280-#ifdef LODEPNG_COMPILE_CPP
281-#include <fstream>
282-#endif /*LODEPNG_COMPILE_CPP*/
283-
284-#define VERSION_STRING "20120528"
285-
286-/*
287-This source file is built up in the following large parts. The code sections
288-with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
289--Tools for C and common code for PNG and Zlib
290--C Code for Zlib (huffman, deflate, ...)
291--C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
292--The C++ wrapper around all of the above
293-*/
294-
295-/*The malloc, realloc and free functions defined here with "my" in front of the
296-name, so that you can easily change them to others related to your platform in
297-this one location if needed. Everything else in the code calls these.*/
298-
299-static void* mymalloc(size_t size)
300-{
301- return malloc(size);
302-}
303-
304-static void* myrealloc(void* ptr, size_t new_size)
305-{
306- return realloc(ptr, new_size);
307-}
308-
309-static void myfree(void* ptr)
310-{
311- free(ptr);
312-}
313-
314-/*
315-Declaration of the custom functions used if LODEPNG_COMPILE_ZLIB isn't defined
316-or LODEPNG_CUSTOM_ZLIB_DECODER or LODEPNG_CUSTOM_ZLIB_ENCODER are enabled.
317-
318-In that case, you need to define these yourself (which you can do in one of your
319-own source files) so that LodePNG can link to it.
320-
321-By default, this is not needed. If LODEPNG_COMPILE_ZLIB isn't defined, then only
322-the two zlib related ones are needed.
323-
324-If needed, the functions must act as follows:
325-*out must be nullptr and *outsize must be 0 initially, and after the function is done,
326-*out must point to the decompressed data, *outsize must be the size of it, and must
327-be the size of the useful data in bytes, not the alloc size.
328-*/
329-unsigned lodepng_custom_zlib_decompress(unsigned char** out, size_t* outsize,
330- const unsigned char* in, size_t insize,
331- const LodePNGDecompressSettings* settings);
332-unsigned lodepng_custom_zlib_compress(unsigned char** out, size_t* outsize,
333- const unsigned char* in, size_t insize,
334- const LodePNGCompressSettings* settings);
335-unsigned lodepng_custom_inflate(unsigned char** out, size_t* outsize,
336- const unsigned char* in, size_t insize,
337- const LodePNGDecompressSettings* settings);
338-unsigned lodepng_custom_deflate(unsigned char** out, size_t* outsize,
339- const unsigned char* in, size_t insize,
340- const LodePNGCompressSettings* settings);
341-
342-/* ////////////////////////////////////////////////////////////////////////// */
343-/* ////////////////////////////////////////////////////////////////////////// */
344-/* // Tools for C, and common code for PNG and Zlib. // */
345-/* ////////////////////////////////////////////////////////////////////////// */
346-/* ////////////////////////////////////////////////////////////////////////// */
347-
348-/*
349-Often in case of an error a value is assigned to a variable and then it breaks
350-out of a loop (to go to the cleanup phase of a function). This macro does that.
351-It makes the error handling code shorter and more readable.
352-
353-Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
354-*/
355-#define CERROR_BREAK(errorvar, code)\
356-{\
357- errorvar = code;\
358- break;\
359-}
360-
361-/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
362-#define ERROR_BREAK(code) CERROR_BREAK(error, code)
363-
364-/*Set error var to the error code, and return it.*/
365-#define CERROR_RETURN_ERROR(errorvar, code)\
366-{\
367- errorvar = code;\
368- return code;\
369-}
370-
371-/*Try the code, if it returns error, also return the error.*/
372-#define CERROR_TRY_RETURN(call)\
373-{\
374- unsigned error = call;\
375- if(error) return error;\
376-}
377-
378-/*
379-About uivector, ucvector and string:
380--All of them wrap dynamic arrays or text strings in a similar way.
381--LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
382--The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
383--They're not used in the interface, only internally in this file as static functions.
384--As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
385-*/
386-
387-#ifdef LODEPNG_COMPILE_ZLIB
388-/*dynamic vector of unsigned ints*/
389-typedef struct uivector
390-{
391- unsigned* data;
392- size_t size; /*size in number of unsigned longs*/
393- size_t allocsize; /*allocated size in bytes*/
394-} uivector;
395-
396-static void uivector_cleanup(void* p)
397-{
398- ((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
399- myfree(((uivector*)p)->data);
400- ((uivector*)p)->data = nullptr;
401-}
402-
403-/*returns 1 if success, 0 if failure ==> nothing done*/
404-static unsigned uivector_resize(uivector* p, size_t size)
405-{
406- if(size * sizeof(unsigned) > p->allocsize)
407- {
408- size_t newsize = size * sizeof(unsigned) * 2;
409- void* data = myrealloc(p->data, newsize);
410- if(data)
411- {
412- p->allocsize = newsize;
413- p->data = (unsigned*)data;
414- p->size = size;
415- }
416- else return 0;
417- }
418- else p->size = size;
419- return 1;
420-}
421-
422-/*resize and give all new elements the value*/
423-static unsigned uivector_resizev(uivector* p, size_t size, unsigned value)
424-{
425- size_t oldsize = p->size, i;
426- if(!uivector_resize(p, size)) return 0;
427- for(i = oldsize; i < size; i++) p->data[i] = value;
428- return 1;
429-}
430-
431-static void uivector_init(uivector* p)
432-{
433- p->data = nullptr;
434- p->size = p->allocsize = 0;
435-}
436-
437-#ifdef LODEPNG_COMPILE_ENCODER
438-/*returns 1 if success, 0 if failure ==> nothing done*/
439-static unsigned uivector_push_back(uivector* p, unsigned c)
440-{
441- if(!uivector_resize(p, p->size + 1)) return 0;
442- p->data[p->size - 1] = c;
443- return 1;
444-}
445-
446-/*copy q to p, returns 1 if success, 0 if failure ==> nothing done*/
447-static unsigned uivector_copy(uivector* p, const uivector* q)
448-{
449- size_t i;
450- if(!uivector_resize(p, q->size)) return 0;
451- for(i = 0; i < q->size; i++) p->data[i] = q->data[i];
452- return 1;
453-}
454-
455-static void uivector_swap(uivector* p, uivector* q)
456-{
457- size_t tmp;
458- unsigned* tmpp;
459- tmp = p->size; p->size = q->size; q->size = tmp;
460- tmp = p->allocsize; p->allocsize = q->allocsize; q->allocsize = tmp;
461- tmpp = p->data; p->data = q->data; q->data = tmpp;
462-}
463-#endif /*LODEPNG_COMPILE_ENCODER*/
464-#endif /*LODEPNG_COMPILE_ZLIB*/
465-
466-/* /////////////////////////////////////////////////////////////////////////// */
467-
468-/*dynamic vector of unsigned chars*/
469-typedef struct ucvector
470-{
471- unsigned char* data;
472- size_t size; /*used size*/
473- size_t allocsize; /*allocated size*/
474-} ucvector;
475-
476-static void ucvector_cleanup(void* p)
477-{
478- ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0;
479- myfree(((ucvector*)p)->data);
480- ((ucvector*)p)->data = nullptr;
481-}
482-
483-/*returns 1 if success, 0 if failure ==> nothing done*/
484-static unsigned ucvector_resize(ucvector* p, size_t size)
485-{
486- if(size * sizeof(unsigned char) > p->allocsize)
487- {
488- size_t newsize = size * sizeof(unsigned char) * 2;
489- void* data = myrealloc(p->data, newsize);
490- if(data)
491- {
492- p->allocsize = newsize;
493- p->data = (unsigned char*)data;
494- p->size = size;
495- }
496- else return 0; /*error: not enough memory*/
497- }
498- else p->size = size;
499- return 1;
500-}
501-
502-#ifdef LODEPNG_COMPILE_DECODER
503-#ifdef LODEPNG_COMPILE_PNG
504-/*resize and give all new elements the value*/
505-static unsigned ucvector_resizev(ucvector* p, size_t size, unsigned char value)
506-{
507- size_t oldsize = p->size, i;
508- if(!ucvector_resize(p, size)) return 0;
509- for(i = oldsize; i < size; i++) p->data[i] = value;
510- return 1;
511-}
512-#endif /*LODEPNG_COMPILE_PNG*/
513-#endif /*LODEPNG_COMPILE_DECODER*/
514-
515-static void ucvector_init(ucvector* p)
516-{
517- p->data = nullptr;
518- p->size = p->allocsize = 0;
519-}
520-
521-#ifdef LODEPNG_COMPILE_ZLIB
522-/*you can both convert from vector to buffer&size and vica versa. If you use
523-init_buffer to take over a buffer and size, it is not needed to use cleanup*/
524-static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size)
525-{
526- p->data = buffer;
527- p->allocsize = p->size = size;
528-}
529-#endif /*LODEPNG_COMPILE_ZLIB*/
530-
531-#ifdef LODEPNG_COMPILE_ENCODER
532-/*returns 1 if success, 0 if failure ==> nothing done*/
533-static unsigned ucvector_push_back(ucvector* p, unsigned char c)
534-{
535- if(!ucvector_resize(p, p->size + 1)) return 0;
536- p->data[p->size - 1] = c;
537- return 1;
538-}
539-#endif /*LODEPNG_COMPILE_ENCODER*/
540-
541-
542-/* ////////////////////////////////////////////////////////////////////////// */
543-
544-#ifdef LODEPNG_COMPILE_PNG
545-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
546-/*returns 1 if success, 0 if failure ==> nothing done*/
547-static unsigned string_resize(char** out, size_t size)
548-{
549- char* data = (char*)myrealloc(*out, size + 1);
550- if(data)
551- {
552- data[size] = 0; /*null termination char*/
553- *out = data;
554- }
555- return data != 0;
556-}
557-
558-/*init a {char*, size_t} pair for use as string*/
559-static void string_init(char** out)
560-{
561- *out = nullptr;
562- string_resize(out, 0);
563-}
564-
565-/*free the above pair again*/
566-static void string_cleanup(char** out)
567-{
568- myfree(*out);
569- *out = nullptr;
570-}
571-
572-static void string_set(char** out, const char* in)
573-{
574- size_t insize = strlen(in), i = 0;
575- if(string_resize(out, insize))
576- {
577- for(i = 0; i < insize; i++)
578- {
579- (*out)[i] = in[i];
580- }
581- }
582-}
583-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
584-#endif /*LODEPNG_COMPILE_PNG*/
585-
586-/* ////////////////////////////////////////////////////////////////////////// */
587-
588-unsigned lodepng_read32bitInt(const unsigned char* buffer)
589-{
590- return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
591-}
592-
593-/*buffer must have at least 4 allocated bytes available*/
594-static void lodepng_set32bitInt(unsigned char* buffer, unsigned value)
595-{
596- buffer[0] = (unsigned char)((value >> 24) & 0xff);
597- buffer[1] = (unsigned char)((value >> 16) & 0xff);
598- buffer[2] = (unsigned char)((value >> 8) & 0xff);
599- buffer[3] = (unsigned char)((value ) & 0xff);
600-}
601-
602-#ifdef LODEPNG_COMPILE_ENCODER
603-static void lodepng_add32bitInt(ucvector* buffer, unsigned value)
604-{
605- ucvector_resize(buffer, buffer->size + 4);
606- lodepng_set32bitInt(&buffer->data[buffer->size - 4], value);
607-}
608-#endif /*LODEPNG_COMPILE_ENCODER*/
609-
610-/* ////////////////////////////////////////////////////////////////////////// */
611-/* / File IO / */
612-/* ////////////////////////////////////////////////////////////////////////// */
613-
614-#ifdef LODEPNG_COMPILE_DISK
615-
616-unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename)
617-{
618- FILE* file;
619- long size;
620-
621- /*provide some proper output values if error will happen*/
622- *out = 0;
623- *outsize = 0;
624-
625- file = fopen(filename, "rb");
626- if(!file) return 78;
627-
628- /*get filesize:*/
629- fseek(file , 0 , SEEK_END);
630- size = ftell(file);
631- rewind(file);
632-
633- /*read contents of the file into the vector*/
634- *outsize = 0;
635- *out = (unsigned char*)mymalloc((size_t)size);
636- if(size && (*out)) (*outsize) = fread(*out, 1, (size_t)size, file);
637-
638- fclose(file);
639- if(!(*out) && size) return 83; /*the above malloc failed*/
640- return 0;
641-}
642-
643-/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
644-unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename)
645-{
646- FILE* file;
647- file = fopen(filename, "wb" );
648- if(!file) return 79;
649- fwrite((char*)buffer , 1 , buffersize, file);
650- fclose(file);
651- return 0;
652-}
653-
654-#endif /*LODEPNG_COMPILE_DISK*/
655-
656-/* ////////////////////////////////////////////////////////////////////////// */
657-/* ////////////////////////////////////////////////////////////////////////// */
658-/* // End of common code and tools. Begin of Zlib related code. // */
659-/* ////////////////////////////////////////////////////////////////////////// */
660-/* ////////////////////////////////////////////////////////////////////////// */
661-
662-#ifdef LODEPNG_COMPILE_ZLIB
663-#ifdef LODEPNG_COMPILE_ENCODER
664-static void addBitToStream(size_t* bitpointer, ucvector* bitstream, unsigned char bit)
665-{
666- /*add a new byte at the end*/
667- if((*bitpointer) % 8 == 0) ucvector_push_back(bitstream, (unsigned char)0);
668- /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
669- (bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));
670- (*bitpointer)++;
671-}
672-
673-static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
674-{
675- size_t i;
676- for(i = 0; i < nbits; i++) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1));
677-}
678-
679-static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
680-{
681- size_t i;
682- for(i = 0; i < nbits; i++) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1));
683-}
684-#endif /*LODEPNG_COMPILE_ENCODER*/
685-
686-#ifdef LODEPNG_COMPILE_DECODER
687-
688-#define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
689-
690-static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream)
691-{
692- unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream));
693- (*bitpointer)++;
694- return result;
695-}
696-
697-static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
698-{
699- unsigned result = 0, i;
700- for(i = 0; i < nbits; i++)
701- {
702- result += ((unsigned)READBIT(*bitpointer, bitstream)) << i;
703- (*bitpointer)++;
704- }
705- return result;
706-}
707-#endif /*LODEPNG_COMPILE_DECODER*/
708-
709-/* ////////////////////////////////////////////////////////////////////////// */
710-/* / Deflate - Huffman / */
711-/* ////////////////////////////////////////////////////////////////////////// */
712-
713-#define FIRST_LENGTH_CODE_INDEX 257
714-#define LAST_LENGTH_CODE_INDEX 285
715-/*256 literals, the end code, some length codes, and 2 unused codes*/
716-#define NUM_DEFLATE_CODE_SYMBOLS 288
717-/*the distance codes have their own symbols, 30 used, 2 unused*/
718-#define NUM_DISTANCE_SYMBOLS 32
719-/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
720-#define NUM_CODE_LENGTH_CODES 19
721-
722-/*the base lengths represented by codes 257-285*/
723-static const unsigned LENGTHBASE[29]
724- = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
725- 67, 83, 99, 115, 131, 163, 195, 227, 258};
726-
727-/*the extra bits used by codes 257-285 (added to base length)*/
728-static const unsigned LENGTHEXTRA[29]
729- = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
730- 4, 4, 4, 4, 5, 5, 5, 5, 0};
731-
732-/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
733-static const unsigned DISTANCEBASE[30]
734- = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
735- 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
736-
737-/*the extra bits of backwards distances (added to base)*/
738-static const unsigned DISTANCEEXTRA[30]
739- = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
740- 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
741-
742-/*the order in which "code length alphabet code lengths" are stored, out of this
743-the huffman tree of the dynamic huffman tree lengths is generated*/
744-static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
745- = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
746-
747-/* ////////////////////////////////////////////////////////////////////////// */
748-
749-/*
750-Huffman tree struct, containing multiple representations of the tree
751-*/
752-typedef struct HuffmanTree
753-{
754- unsigned* tree2d;
755- unsigned* tree1d;
756- unsigned* lengths; /*the lengths of the codes of the 1d-tree*/
757- unsigned maxbitlen; /*maximum number of bits a single code can get*/
758- unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
759-} HuffmanTree;
760-
761-/*function used for debug purposes to draw the tree in ascii art with C++*/
762-/*#include <iostream>
763-static void HuffmanTree_draw(HuffmanTree* tree)
764-{
765- std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl;
766- for(size_t i = 0; i < tree->tree1d.size; i++)
767- {
768- if(tree->lengths.data[i])
769- std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl;
770- }
771- std::cout << std::endl;
772-}*/
773-
774-static void HuffmanTree_init(HuffmanTree* tree)
775-{
776- tree->tree2d = 0;
777- tree->tree1d = 0;
778- tree->lengths = 0;
779-}
780-
781-static void HuffmanTree_cleanup(HuffmanTree* tree)
782-{
783- myfree(tree->tree2d);
784- myfree(tree->tree1d);
785- myfree(tree->lengths);
786-}
787-
788-/*the tree representation used by the decoder. return value is error*/
789-static unsigned HuffmanTree_make2DTree(HuffmanTree* tree)
790-{
791- unsigned nodefilled = 0; /*up to which node it is filled*/
792- unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/
793- unsigned n, i;
794-
795- tree->tree2d = (unsigned*)mymalloc(tree->numcodes * 2 * sizeof(unsigned));
796- if(!tree->tree2d) return 83; /*alloc fail*/
797-
798- /*
799- convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
800- uninited, a value >= numcodes is an address to another bit, a value < numcodes
801- is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
802- many columns as codes - 1.
803- A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
804- Here, the internal nodes are stored (what their 0 and 1 option point to).
805- There is only memory for such good tree currently, if there are more nodes
806- (due to too long length codes), error 55 will happen
807- */
808- for(n = 0; n < tree->numcodes * 2; n++)
809- {
810- tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/
811- }
812-
813- for(n = 0; n < tree->numcodes; n++) /*the codes*/
814- {
815- for(i = 0; i < tree->lengths[n]; i++) /*the bits for this code*/
816- {
817- unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1);
818- if(treepos > tree->numcodes - 2) return 55; /*oversubscribed, see comment in lodepng_error_text*/
819- if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/
820- {
821- if(i + 1 == tree->lengths[n]) /*last bit*/
822- {
823- tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/
824- treepos = 0;
825- }
826- else
827- {
828- /*put address of the next step in here, first that address has to be found of course
829- (it's just nodefilled + 1)...*/
830- nodefilled++;
831- /*addresses encoded with numcodes added to it*/
832- tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes;
833- treepos = nodefilled;
834- }
835- }
836- else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
837- }
838- }
839-
840- for(n = 0; n < tree->numcodes * 2; n++)
841- {
842- if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/
843- }
844-
845- return 0;
846-}
847-
848-/*
849-Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
850-numcodes, lengths and maxbitlen must already be filled in correctly. return
851-value is error.
852-*/
853-static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree)
854-{
855- uivector blcount;
856- uivector nextcode;
857- unsigned bits, n, error = 0;
858-
859- uivector_init(&blcount);
860- uivector_init(&nextcode);
861-
862- tree->tree1d = (unsigned*)mymalloc(tree->numcodes * sizeof(unsigned));
863- if(!tree->tree1d) error = 83; /*alloc fail*/
864-
865- if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0)
866- || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0))
867- error = 83; /*alloc fail*/
868-
869- if(!error)
870- {
871- /*step 1: count number of instances of each code length*/
872- for(bits = 0; bits < tree->numcodes; bits++) blcount.data[tree->lengths[bits]]++;
873- /*step 2: generate the nextcode values*/
874- for(bits = 1; bits <= tree->maxbitlen; bits++)
875- {
876- nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1;
877- }
878- /*step 3: generate all the codes*/
879- for(n = 0; n < tree->numcodes; n++)
880- {
881- if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++;
882- }
883- }
884-
885- uivector_cleanup(&blcount);
886- uivector_cleanup(&nextcode);
887-
888- if(!error) return HuffmanTree_make2DTree(tree);
889- else return error;
890-}
891-
892-/*
893-given the code lengths (as stored in the PNG file), generate the tree as defined
894-by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
895-return value is error.
896-*/
897-static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
898- size_t numcodes, unsigned maxbitlen)
899-{
900- unsigned i;
901- tree->lengths = (unsigned*)mymalloc(numcodes * sizeof(unsigned));
902- if(!tree->lengths) return 83; /*alloc fail*/
903- for(i = 0; i < numcodes; i++) tree->lengths[i] = bitlen[i];
904- tree->numcodes = (unsigned)numcodes; /*number of symbols*/
905- tree->maxbitlen = maxbitlen;
906- return HuffmanTree_makeFromLengths2(tree);
907-}
908-
909-#ifdef LODEPNG_COMPILE_ENCODER
910-
911-/*
912-A coin, this is the terminology used for the package-merge algorithm and the
913-coin collector's problem. This is used to generate the huffman tree.
914-A coin can be multiple coins (when they're merged)
915-*/
916-typedef struct Coin
917-{
918- uivector symbols;
919- float weight; /*the sum of all weights in this coin*/
920-} Coin;
921-
922-static void coin_init(Coin* c)
923-{
924- uivector_init(&c->symbols);
925-}
926-
927-/*argument c is void* so that this dtor can be given as function pointer to the vector resize function*/
928-static void coin_cleanup(void* c)
929-{
930- uivector_cleanup(&((Coin*)c)->symbols);
931-}
932-
933-static void coin_copy(Coin* c1, const Coin* c2)
934-{
935- c1->weight = c2->weight;
936- uivector_copy(&c1->symbols, &c2->symbols);
937-}
938-
939-static void add_coins(Coin* c1, const Coin* c2)
940-{
941- size_t i;
942- for(i = 0; i < c2->symbols.size; i++) uivector_push_back(&c1->symbols, c2->symbols.data[i]);
943- c1->weight += c2->weight;
944-}
945-
946-static void init_coins(Coin* coins, size_t num)
947-{
948- size_t i;
949- for(i = 0; i < num; i++) coin_init(&coins[i]);
950-}
951-
952-static void cleanup_coins(Coin* coins, size_t num)
953-{
954- size_t i;
955- for(i = 0; i < num; i++) coin_cleanup(&coins[i]);
956-}
957-
958-/*
959-This uses a simple combsort to sort the data. This function is not critical for
960-overall encoding speed and the data amount isn't that large.
961-*/
962-static void sort_coins(Coin* data, size_t amount)
963-{
964- size_t gap = amount;
965- unsigned char swapped = 0;
966- while((gap > 1) || swapped)
967- {
968- size_t i;
969- gap = (gap * 10) / 13; /*shrink factor 1.3*/
970- if(gap == 9 || gap == 10) gap = 11; /*combsort11*/
971- if(gap < 1) gap = 1;
972- swapped = 0;
973- for(i = 0; i < amount - gap; i++)
974- {
975- size_t j = i + gap;
976- if(data[j].weight < data[i].weight)
977- {
978- float temp = data[j].weight; data[j].weight = data[i].weight; data[i].weight = temp;
979- uivector_swap(&data[i].symbols, &data[j].symbols);
980- swapped = 1;
981- }
982- }
983- }
984-}
985-
986-static unsigned append_symbol_coins(Coin* coins, const unsigned* frequencies, unsigned numcodes, size_t sum)
987-{
988- unsigned i;
989- unsigned j = 0; /*index of present symbols*/
990- for(i = 0; i < numcodes; i++)
991- {
992- if(frequencies[i] != 0) /*only include symbols that are present*/
993- {
994- coins[j].weight = frequencies[i] / (float)sum;
995- uivector_push_back(&coins[j].symbols, i);
996- j++;
997- }
998- }
999- return 0;
1000-}
1001-
1002-unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
1003- size_t numcodes, unsigned maxbitlen)
1004-{
1005- unsigned i, j;
1006- size_t sum = 0, numpresent = 0;
1007- unsigned error = 0;
1008- Coin* coins; /*the coins of the currently calculated row*/
1009- Coin* prev_row; /*the previous row of coins*/
1010- unsigned numcoins;
1011- unsigned coinmem;
1012-
1013- if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
1014-
1015- for(i = 0; i < numcodes; i++)
1016- {
1017- if(frequencies[i] > 0)
1018- {
1019- numpresent++;
1020- sum += frequencies[i];
1021- }
1022- }
1023-
1024- for(i = 0; i < numcodes; i++) lengths[i] = 0;
1025-
1026- /*there are no symbols at all, in that case add one symbol of value 0 to the tree (see RFC 1951 section 3.2.7) */
1027- if(numpresent == 0)
1028- {
1029- lengths[0] = 1;
1030- }
1031- /*the package merge algorithm gives wrong results if there's only one symbol
1032- (theoretically 0 bits would then suffice, but we need a proper symbol for zlib)*/
1033- else if(numpresent == 1)
1034- {
1035- for(i = 0; i < numcodes; i++) if(frequencies[i]) lengths[i] = 1;
1036- }
1037- else
1038- {
1039- /*Package-Merge algorithm represented by coin collector's problem
1040- For every symbol, maxbitlen coins will be created*/
1041-
1042- coinmem = numpresent * 2; /*max amount of coins needed with the current algo*/
1043- coins = (Coin*)mymalloc(sizeof(Coin) * coinmem);
1044- prev_row = (Coin*)mymalloc(sizeof(Coin) * coinmem);
1045- if(!coins || !prev_row) return 83; /*alloc fail*/
1046- init_coins(coins, coinmem);
1047- init_coins(prev_row, coinmem);
1048-
1049- /*first row, lowest denominator*/
1050- error = append_symbol_coins(coins, frequencies, numcodes, sum);
1051- numcoins = numpresent;
1052- sort_coins(coins, numcoins);
1053- if(!error)
1054- {
1055- unsigned numprev = 0;
1056- for(j = 1; j <= maxbitlen && !error; j++) /*each of the remaining rows*/
1057- {
1058- unsigned tempnum;
1059- Coin* tempcoins;
1060- /*swap prev_row and coins, and their amounts*/
1061- tempcoins = prev_row; prev_row = coins; coins = tempcoins;
1062- tempnum = numprev; numprev = numcoins; numcoins = tempnum;
1063-
1064- cleanup_coins(coins, numcoins);
1065- init_coins(coins, numcoins);
1066-
1067- numcoins = 0;
1068-
1069- /*fill in the merged coins of the previous row*/
1070- for(i = 0; i + 1 < numprev; i += 2)
1071- {
1072- /*merge prev_row[i] and prev_row[i + 1] into new coin*/
1073- Coin* coin = &coins[numcoins++];
1074- coin_copy(coin, &prev_row[i]);
1075- add_coins(coin, &prev_row[i + 1]);
1076- }
1077- /*fill in all the original symbols again*/
1078- if(j < maxbitlen)
1079- {
1080- error = append_symbol_coins(coins + numcoins, frequencies, numcodes, sum);
1081- numcoins += numpresent;
1082- }
1083- sort_coins(coins, numcoins);
1084- }
1085- }
1086-
1087- if(!error)
1088- {
1089- /*calculate the lenghts of each symbol, as the amount of times a coin of each symbol is used*/
1090- for(i = 0; i < numpresent - 1; i++)
1091- {
1092- Coin* coin = &coins[i];
1093- for(j = 0; j < coin->symbols.size; j++) lengths[coin->symbols.data[j]]++;
1094- }
1095- }
1096-
1097- cleanup_coins(coins, coinmem);
1098- myfree(coins);
1099- cleanup_coins(prev_row, coinmem);
1100- myfree(prev_row);
1101- }
1102-
1103- return error;
1104-}
1105-
1106-/*Create the Huffman tree given the symbol frequencies*/
1107-static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
1108- size_t numcodes, unsigned maxbitlen)
1109-{
1110- unsigned error = 0;
1111- tree->maxbitlen = maxbitlen;
1112- tree->numcodes = (unsigned)numcodes; /*number of symbols*/
1113- tree->lengths = (unsigned*)myrealloc(tree->lengths, numcodes * sizeof(unsigned));
1114- if(!tree->lengths) return 83; /*alloc fail*/
1115- /*initialize all lengths to 0*/
1116- memset(tree->lengths, 0, numcodes * sizeof(unsigned));
1117-
1118- error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
1119- if(!error) error = HuffmanTree_makeFromLengths2(tree);
1120- return error;
1121-}
1122-
1123-static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index)
1124-{
1125- return tree->tree1d[index];
1126-}
1127-
1128-static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index)
1129-{
1130- return tree->lengths[index];
1131-}
1132-#endif /*LODEPNG_COMPILE_ENCODER*/
1133-
1134-/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
1135-static unsigned generateFixedLitLenTree(HuffmanTree* tree)
1136-{
1137- unsigned i, error = 0;
1138- unsigned* bitlen = (unsigned*)mymalloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
1139- if(!bitlen) return 83; /*alloc fail*/
1140-
1141- /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
1142- for(i = 0; i <= 143; i++) bitlen[i] = 8;
1143- for(i = 144; i <= 255; i++) bitlen[i] = 9;
1144- for(i = 256; i <= 279; i++) bitlen[i] = 7;
1145- for(i = 280; i <= 287; i++) bitlen[i] = 8;
1146-
1147- error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
1148-
1149- myfree(bitlen);
1150- return error;
1151-}
1152-
1153-/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
1154-static unsigned generateFixedDistanceTree(HuffmanTree* tree)
1155-{
1156- unsigned i, error = 0;
1157- unsigned* bitlen = (unsigned*)mymalloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
1158- if(!bitlen) return 83; /*alloc fail*/
1159-
1160- /*there are 32 distance codes, but 30-31 are unused*/
1161- for(i = 0; i < NUM_DISTANCE_SYMBOLS; i++) bitlen[i] = 5;
1162- error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
1163-
1164- myfree(bitlen);
1165- return error;
1166-}
1167-
1168-#ifdef LODEPNG_COMPILE_DECODER
1169-
1170-/*
1171-returns the code, or (unsigned)(-1) if error happened
1172-inbitlength is the length of the complete buffer, in bits (so its byte length times 8)
1173-*/
1174-static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp,
1175- const HuffmanTree* codetree, size_t inbitlength)
1176-{
1177- unsigned treepos = 0, ct;
1178- for(;;)
1179- {
1180- if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/
1181- /*
1182- decode the symbol from the tree. The "readBitFromStream" code is inlined in
1183- the expression below because this is the biggest bottleneck while decoding
1184- */
1185- ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)];
1186- (*bp)++;
1187- if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/
1188- else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/
1189-
1190- if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/
1191- }
1192-}
1193-#endif /*LODEPNG_COMPILE_DECODER*/
1194-
1195-#ifdef LODEPNG_COMPILE_DECODER
1196-
1197-/* ////////////////////////////////////////////////////////////////////////// */
1198-/* / Inflator (Decompressor) / */
1199-/* ////////////////////////////////////////////////////////////////////////// */
1200-
1201-/*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
1202-static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d)
1203-{
1204- generateFixedLitLenTree(tree_ll);
1205- generateFixedDistanceTree(tree_d);
1206-}
1207-
1208-/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
1209-static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
1210- const unsigned char* in, size_t* bp, size_t inlength)
1211-{
1212- /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
1213- unsigned error = 0;
1214- unsigned n, HLIT, HDIST, HCLEN, i;
1215- size_t inbitlength = inlength * 8;
1216-
1217- /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
1218- unsigned* bitlen_ll = 0; /*lit,len code lengths*/
1219- unsigned* bitlen_d = 0; /*dist code lengths*/
1220- /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
1221- unsigned* bitlen_cl = 0;
1222- HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
1223-
1224- if((*bp) >> 3 >= inlength - 2) return 49; /*error: the bit pointer is or will go past the memory*/
1225-
1226- /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
1227- HLIT = readBitsFromStream(bp, in, 5) + 257;
1228- /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
1229- HDIST = readBitsFromStream(bp, in, 5) + 1;
1230- /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
1231- HCLEN = readBitsFromStream(bp, in, 4) + 4;
1232-
1233- HuffmanTree_init(&tree_cl);
1234-
1235- while(!error)
1236- {
1237- /*read the code length codes out of 3 * (amount of code length codes) bits*/
1238-
1239- bitlen_cl = (unsigned*)mymalloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
1240- if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/);
1241-
1242- for(i = 0; i < NUM_CODE_LENGTH_CODES; i++)
1243- {
1244- if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3);
1245- else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/
1246- }
1247-
1248- error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
1249- if(error) break;
1250-
1251- /*now we can use this tree to read the lengths for the tree that this function will return*/
1252- bitlen_ll = (unsigned*)mymalloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
1253- bitlen_d = (unsigned*)mymalloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
1254- if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
1255- for(i = 0; i < NUM_DEFLATE_CODE_SYMBOLS; i++) bitlen_ll[i] = 0;
1256- for(i = 0; i < NUM_DISTANCE_SYMBOLS; i++) bitlen_d[i] = 0;
1257-
1258- /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
1259- i = 0;
1260- while(i < HLIT + HDIST)
1261- {
1262- unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength);
1263- if(code <= 15) /*a length code*/
1264- {
1265- if(i < HLIT) bitlen_ll[i] = code;
1266- else bitlen_d[i - HLIT] = code;
1267- i++;
1268- }
1269- else if(code == 16) /*repeat previous*/
1270- {
1271- unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
1272- unsigned value; /*set value to the previous code*/
1273-
1274- if(*bp >= inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1275- if (i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
1276-
1277- replength += readBitsFromStream(bp, in, 2);
1278-
1279- if(i < HLIT + 1) value = bitlen_ll[i - 1];
1280- else value = bitlen_d[i - HLIT - 1];
1281- /*repeat this value in the next lengths*/
1282- for(n = 0; n < replength; n++)
1283- {
1284- if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
1285- if(i < HLIT) bitlen_ll[i] = value;
1286- else bitlen_d[i - HLIT] = value;
1287- i++;
1288- }
1289- }
1290- else if(code == 17) /*repeat "0" 3-10 times*/
1291- {
1292- unsigned replength = 3; /*read in the bits that indicate repeat length*/
1293- if(*bp >= inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1294-
1295- replength += readBitsFromStream(bp, in, 3);
1296-
1297- /*repeat this value in the next lengths*/
1298- for(n = 0; n < replength; n++)
1299- {
1300- if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
1301-
1302- if(i < HLIT) bitlen_ll[i] = 0;
1303- else bitlen_d[i - HLIT] = 0;
1304- i++;
1305- }
1306- }
1307- else if(code == 18) /*repeat "0" 11-138 times*/
1308- {
1309- unsigned replength = 11; /*read in the bits that indicate repeat length*/
1310- if(*bp >= inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
1311-
1312- replength += readBitsFromStream(bp, in, 7);
1313-
1314- /*repeat this value in the next lengths*/
1315- for(n = 0; n < replength; n++)
1316- {
1317- if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
1318-
1319- if(i < HLIT) bitlen_ll[i] = 0;
1320- else bitlen_d[i - HLIT] = 0;
1321- i++;
1322- }
1323- }
1324- else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1325- {
1326- if(code == (unsigned)(-1))
1327- {
1328- /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1329- (10=no endcode, 11=wrong jump outside of tree)*/
1330- error = (*bp) > inbitlength ? 10 : 11;
1331- }
1332- else error = 16; /*unexisting code, this can never happen*/
1333- break;
1334- }
1335- }
1336- if(error) break;
1337-
1338- if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
1339-
1340- /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
1341- error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
1342- if(error) break;
1343- error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
1344-
1345- break; /*end of error-while*/
1346- }
1347-
1348- myfree(bitlen_cl);
1349- myfree(bitlen_ll);
1350- myfree(bitlen_d);
1351- HuffmanTree_cleanup(&tree_cl);
1352-
1353- return error;
1354-}
1355-
1356-/*inflate a block with dynamic of fixed Huffman tree*/
1357-static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp,
1358- size_t* pos, size_t inlength, unsigned btype)
1359-{
1360- unsigned error = 0;
1361- HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
1362- HuffmanTree tree_d; /*the huffman tree for distance codes*/
1363- size_t inbitlength = inlength * 8;
1364-
1365- HuffmanTree_init(&tree_ll);
1366- HuffmanTree_init(&tree_d);
1367-
1368- if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d);
1369- else if(btype == 2)
1370- {
1371- error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength);
1372- }
1373-
1374- while(!error) /*decode all symbols until end reached, breaks at end code*/
1375- {
1376- /*code_ll is literal, length or end code*/
1377- unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength);
1378- if(code_ll <= 255) /*literal symbol*/
1379- {
1380- if((*pos) >= out->size)
1381- {
1382- /*reserve more room at once*/
1383- if(!ucvector_resize(out, ((*pos) + 1) * 2)) ERROR_BREAK(83 /*alloc fail*/);
1384- }
1385- out->data[(*pos)] = (unsigned char)(code_ll);
1386- (*pos)++;
1387- }
1388- else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/
1389- {
1390- unsigned code_d, distance;
1391- unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
1392- size_t start, forward, backward, length;
1393-
1394- /*part 1: get length base*/
1395- length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
1396-
1397- /*part 2: get extra bits and add the value of that to length*/
1398- numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
1399- if(*bp >= inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1400- length += readBitsFromStream(bp, in, numextrabits_l);
1401-
1402- /*part 3: get distance code*/
1403- code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength);
1404- if(code_d > 29)
1405- {
1406- if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1407- {
1408- /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1409- (10=no endcode, 11=wrong jump outside of tree)*/
1410- error = (*bp) > inlength * 8 ? 10 : 11;
1411- }
1412- else error = 18; /*error: invalid distance code (30-31 are never used)*/
1413- break;
1414- }
1415- distance = DISTANCEBASE[code_d];
1416-
1417- /*part 4: get extra bits from distance*/
1418- numextrabits_d = DISTANCEEXTRA[code_d];
1419- if(*bp >= inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
1420-
1421- distance += readBitsFromStream(bp, in, numextrabits_d);
1422-
1423- /*part 5: fill in all the out[n] values based on the length and dist*/
1424- start = (*pos);
1425- if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
1426- backward = start - distance;
1427- if((*pos) + length >= out->size)
1428- {
1429- /*reserve more room at once*/
1430- if(!ucvector_resize(out, ((*pos) + length) * 2)) ERROR_BREAK(83 /*alloc fail*/);
1431- }
1432-
1433- for(forward = 0; forward < length; forward++)
1434- {
1435- out->data[(*pos)] = out->data[backward];
1436- (*pos)++;
1437- backward++;
1438- if(backward >= start) backward = start - distance;
1439- }
1440- }
1441- else if(code_ll == 256)
1442- {
1443- break; /*end code, break the loop*/
1444- }
1445- else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
1446- {
1447- /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
1448- (10=no endcode, 11=wrong jump outside of tree)*/
1449- error = (*bp) > inlength * 8 ? 10 : 11;
1450- break;
1451- }
1452- }
1453-
1454- HuffmanTree_cleanup(&tree_ll);
1455- HuffmanTree_cleanup(&tree_d);
1456-
1457- return error;
1458-}
1459-
1460-static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength)
1461-{
1462- /*go to first boundary of byte*/
1463- size_t p;
1464- unsigned LEN, NLEN, n, error = 0;
1465- while(((*bp) & 0x7) != 0) (*bp)++;
1466- p = (*bp) / 8; /*byte position*/
1467-
1468- /*read LEN (2 bytes) and NLEN (2 bytes)*/
1469- if(p >= inlength - 4) return 52; /*error, bit pointer will jump past memory*/
1470- LEN = in[p] + 256 * in[p + 1]; p += 2;
1471- NLEN = in[p] + 256 * in[p + 1]; p += 2;
1472-
1473- /*check if 16-bit NLEN is really the one's complement of LEN*/
1474- if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/
1475-
1476- if((*pos) + LEN >= out->size)
1477- {
1478- if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/
1479- }
1480-
1481- /*read the literal data: LEN bytes are now stored in the out buffer*/
1482- if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/
1483- for(n = 0; n < LEN; n++) out->data[(*pos)++] = in[p++];
1484-
1485- (*bp) = p * 8;
1486-
1487- return error;
1488-}
1489-
1490-static unsigned lodepng_inflatev(ucvector* out,
1491- const unsigned char* in, size_t insize,
1492- const LodePNGDecompressSettings* settings)
1493-{
1494- /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/
1495- size_t bp = 0;
1496- unsigned BFINAL = 0;
1497- size_t pos = 0; /*byte position in the out buffer*/
1498-
1499- unsigned error = 0;
1500-
1501- (void)settings;
1502-
1503- while(!BFINAL)
1504- {
1505- unsigned BTYPE;
1506- if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/
1507- BFINAL = readBitFromStream(&bp, in);
1508- BTYPE = 1 * readBitFromStream(&bp, in);
1509- BTYPE += 2 * readBitFromStream(&bp, in);
1510-
1511- if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
1512- else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/
1513- else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/
1514-
1515- if(error) return error;
1516- }
1517-
1518- /*Only now we know the true size of out, resize it to that*/
1519- if(!ucvector_resize(out, pos)) error = 83; /*alloc fail*/
1520-
1521- return error;
1522-}
1523-
1524-unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
1525- const unsigned char* in, size_t insize,
1526- const LodePNGDecompressSettings* settings)
1527-{
1528-#if LODEPNG_CUSTOM_ZLIB_DECODER == 2
1529- if(settings->custom_decoder)
1530- {
1531- return lodepng_custom_inflate(out, outsize, in, insize, settings);
1532- }
1533- else
1534- {
1535-#endif /*LODEPNG_CUSTOM_ZLIB_DECODER == 2*/
1536- unsigned error;
1537- ucvector v;
1538- ucvector_init_buffer(&v, *out, *outsize);
1539- error = lodepng_inflatev(&v, in, insize, settings);
1540- *out = v.data;
1541- *outsize = v.size;
1542- return error;
1543-#if LODEPNG_CUSTOM_ZLIB_DECODER == 2
1544- }
1545-#endif /*LODEPNG_CUSTOM_ZLIB_DECODER == 2*/
1546-}
1547-
1548-#endif /*LODEPNG_COMPILE_DECODER*/
1549-
1550-#ifdef LODEPNG_COMPILE_ENCODER
1551-
1552-/* ////////////////////////////////////////////////////////////////////////// */
1553-/* / Deflator (Compressor) / */
1554-/* ////////////////////////////////////////////////////////////////////////// */
1555-
1556-static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258;
1557-
1558-/*bitlen is the size in bits of the code*/
1559-static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen)
1560-{
1561- addBitsToStreamReversed(bp, compressed, code, bitlen);
1562-}
1563-
1564-/*search the index in the array, that has the largest value smaller than or equal to the given value,
1565-given array must be sorted (if no value is smaller, it returns the size of the given array)*/
1566-static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value)
1567-{
1568- /*linear search implementation*/
1569- /*for(size_t i = 1; i < array_size; i++) if(array[i] > value) return i - 1;
1570- return array_size - 1;*/
1571-
1572- /*binary search implementation (not that much faster) (precondition: array_size > 0)*/
1573- size_t left = 1;
1574- size_t right = array_size - 1;
1575- while(left <= right)
1576- {
1577- size_t mid = (left + right) / 2;
1578- if(array[mid] <= value) left = mid + 1; /*the value to find is more to the right*/
1579- else if(array[mid - 1] > value) right = mid - 1; /*the value to find is more to the left*/
1580- else return mid - 1;
1581- }
1582- return array_size - 1;
1583-}
1584-
1585-static void addLengthDistance(uivector* values, size_t length, size_t distance)
1586-{
1587- /*values in encoded vector are those used by deflate:
1588- 0-255: literal bytes
1589- 256: end
1590- 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
1591- 286-287: invalid*/
1592-
1593- unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
1594- unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
1595- unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
1596- unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
1597-
1598- uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX);
1599- uivector_push_back(values, extra_length);
1600- uivector_push_back(values, dist_code);
1601- uivector_push_back(values, extra_distance);
1602-}
1603-
1604-static const unsigned HASH_NUM_VALUES = 65536;
1605-static const unsigned HASH_NUM_CHARACTERS = 3;
1606-static const unsigned HASH_SHIFT = 2;
1607-/*
1608-The HASH_NUM_CHARACTERS value is used to make encoding faster by using longer
1609-sequences to generate a hash value from the stream bytes. Setting it to 3
1610-gives exactly the same compression as the brute force method, since deflate's
1611-run length encoding starts with lengths of 3. Setting it to higher values,
1612-like 6, can make the encoding faster (not always though!), but will cause the
1613-encoding to miss any length between 3 and this value, so that the compression
1614-may be worse (but this can vary too depending on the image, sometimes it is
1615-even a bit better instead).
1616-The HASH_NUM_VALUES is the amount of unique possible hash values that
1617-combinations of bytes can give, the higher it is the more memory is needed, but
1618-if it's too low the advantage of hashing is gone.
1619-*/
1620-
1621-typedef struct Hash
1622-{
1623- int* head; /*hash value to head circular pos*/
1624- int* val; /*circular pos to hash value*/
1625- /*circular pos to prev circular pos*/
1626- unsigned short* chain;
1627- unsigned short* zeros;
1628-} Hash;
1629-
1630-static unsigned hash_init(Hash* hash, unsigned windowsize)
1631-{
1632- unsigned i;
1633- hash->head = (int*)mymalloc(sizeof(int) * HASH_NUM_VALUES);
1634- hash->val = (int*)mymalloc(sizeof(int) * windowsize);
1635- hash->chain = (unsigned short*)mymalloc(sizeof(unsigned short) * windowsize);
1636- hash->zeros = (unsigned short*)mymalloc(sizeof(unsigned short) * windowsize);
1637-
1638- if(!hash->head || !hash->val || !hash->chain || !hash->zeros) return 83; /*alloc fail*/
1639-
1640- /*initialize hash table*/
1641- for(i = 0; i < HASH_NUM_VALUES; i++) hash->head[i] = -1;
1642- for(i = 0; i < windowsize; i++) hash->val[i] = -1;
1643- for(i = 0; i < windowsize; i++) hash->chain[i] = i; /*same value as index indicates uninitialized*/
1644-
1645- return 0;
1646-}
1647-
1648-static void hash_cleanup(Hash* hash)
1649-{
1650- myfree(hash->head);
1651- myfree(hash->val);
1652- myfree(hash->chain);
1653- myfree(hash->zeros);
1654-}
1655-
1656-static unsigned getHash(const unsigned char* data, size_t size, size_t pos)
1657-{
1658- unsigned result = 0;
1659- size_t amount, i;
1660- if(pos >= size) return 0;
1661- amount = HASH_NUM_CHARACTERS;
1662- if(pos + amount >= size) amount = size - pos;
1663- for(i = 0; i < amount; i++) result ^= (data[pos + i] << (i * HASH_SHIFT));
1664- return result % HASH_NUM_VALUES;
1665-}
1666-
1667-static unsigned countZeros(const unsigned char* data, size_t size, size_t pos)
1668-{
1669- const unsigned char* start = data + pos;
1670- const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
1671- if(end > data + size) end = data + size;
1672- data = start;
1673- while (data != end && *data == 0) data++;
1674- return data - start;
1675-}
1676-
1677-static void updateHashChain(Hash* hash,
1678- size_t pos, int hashval, unsigned windowsize)
1679-{
1680- unsigned wpos = pos % windowsize;
1681- hash->val[wpos] = hashval;
1682- if(hash->head[hashval] != -1)
1683- {
1684- hash->chain[wpos] = hash->head[hashval];
1685- }
1686- hash->head[hashval] = wpos;
1687-}
1688-
1689-/*Enable to use lazy instead of greedy matching. It looks one byte further
1690-to see if that one gives a longer distance. This gives slightly better compression, at the cost
1691-of a speed loss.*/
1692-#define LAZY_MATCHING
1693-
1694-/*
1695-LZ77-encode the data. Return value is error code. The input are raw bytes, the output
1696-is in the form of unsigned integers with codes representing for example literal bytes, or
1697-length/distance pairs.
1698-It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
1699-sliding window (of windowsize) is used, and all past bytes in that window can be used as
1700-the "dictionary". A brute force search through all possible distances would be slow, and
1701-this hash technique is one out of several ways to speed this up.
1702-*/
1703-static unsigned encodeLZ77(uivector* out, Hash* hash,
1704- const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize)
1705-{
1706- unsigned short numzeros = 0;
1707- int usezeros = windowsize >= 8192; /*for small window size, the 'max chain length' optimization does a better job*/
1708- unsigned pos, i, error = 0;
1709-
1710- if(!error)
1711- {
1712- unsigned offset; /*the offset represents the distance in LZ77 terminology*/
1713- unsigned length;
1714-#ifdef LAZY_MATCHING
1715- unsigned lazy = 0;
1716- unsigned lazylength = 0, lazyoffset = 0;
1717-#endif /*LAZY_MATCHING*/
1718- unsigned hashval;
1719- unsigned current_offset, current_length;
1720- const unsigned char *lastptr, *foreptr, *backptr;
1721- unsigned short hashpos, prevpos;
1722-
1723- for(pos = inpos; pos < insize; pos++)
1724- {
1725- size_t wpos = pos % windowsize; /*position for in 'circular' hash buffers*/
1726-
1727- hashval = getHash(in, insize, pos);
1728- updateHashChain(hash, pos, hashval, windowsize);
1729-
1730- if(usezeros && hashval == 0)
1731- {
1732- numzeros = countZeros(in, insize, pos);
1733- hash->zeros[wpos] = numzeros;
1734- }
1735-
1736-
1737- /*the length and offset found for the current position*/
1738- length = 0;
1739- offset = 0;
1740-
1741- prevpos = hash->head[hashval];
1742- hashpos = hash->chain[prevpos];
1743-
1744- lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
1745-
1746- /*search for the longest string*/
1747- if(hash->val[wpos] == (int)hashval)
1748- {
1749- /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
1750- unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8;
1751- for(;;)
1752- {
1753- /*stop when went completely around the circular buffer*/
1754- if(prevpos < wpos && hashpos > prevpos && hashpos <= wpos) break;
1755- if(prevpos > wpos && (hashpos <= wpos || hashpos > prevpos)) break;
1756- if(maxchainlength-- == 0) break;
1757-
1758- current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize;
1759- if(current_offset > 0) {
1760- /*test the next characters*/
1761- foreptr = &in[pos];
1762- backptr = &in[pos - current_offset];
1763-
1764- /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
1765- if(usezeros && hashval == 0 && hash->val[hashpos] == 0 /*hashval[hashpos] may be out of date*/)
1766- {
1767- unsigned short skip = hash->zeros[hashpos];
1768- if(skip > numzeros) skip = numzeros;
1769- backptr += skip;
1770- foreptr += skip;
1771- }
1772-
1773- /* multiple checks at once per array bounds check */
1774- while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/
1775- {
1776- ++backptr;
1777- ++foreptr;
1778- }
1779- current_length = (unsigned)(foreptr - &in[pos]);
1780-
1781- if(current_length > length)
1782- {
1783- length = current_length; /*the longest length*/
1784- offset = current_offset; /*the offset that is related to this longest length*/
1785- /*jump out once a length of max length is found (speed gain)*/
1786- if(current_length == MAX_SUPPORTED_DEFLATE_LENGTH) break;
1787- }
1788- }
1789-
1790- if(hashpos == hash->chain[hashpos]) break;
1791-
1792- prevpos = hashpos;
1793- hashpos = hash->chain[hashpos];
1794- }
1795- }
1796-
1797-#ifdef LAZY_MATCHING
1798- if(!lazy && length >= 3 && length < MAX_SUPPORTED_DEFLATE_LENGTH)
1799- {
1800- lazy = 1;
1801- lazylength = length;
1802- lazyoffset = offset;
1803- continue;
1804- }
1805- if(lazy)
1806- {
1807- lazy = 0;
1808- if(pos == 0) ERROR_BREAK(81);
1809- if(length > lazylength + 1)
1810- {
1811- /*push the previous character as literal*/
1812- if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
1813- }
1814- else
1815- {
1816- length = lazylength;
1817- offset = lazyoffset;
1818- hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
1819- pos--;
1820- }
1821- }
1822-#endif /*LAZY_MATCHING*/
1823-
1824- if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
1825-
1826-
1827- /**encode it as length/distance pair or literal value**/
1828- if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/
1829- {
1830- if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
1831- }
1832- else
1833- {
1834- if(length == 3 && offset > 2048)
1835- {
1836- /*compensate for the fact that longer offsets have more extra bits, a
1837- length of only 3 may be not worth it then*/
1838- if(!uivector_push_back(out, in[pos + 0])) ERROR_BREAK(83 /*alloc fail*/);
1839- if(!uivector_push_back(out, in[pos + 1])) ERROR_BREAK(83 /*alloc fail*/);
1840- if(!uivector_push_back(out, in[pos + 2])) ERROR_BREAK(83 /*alloc fail*/);
1841- }
1842- else
1843- {
1844- addLengthDistance(out, length, offset);
1845- }
1846- for(i = 1; i < length; i++)
1847- {
1848- pos++;
1849- hashval = getHash(in, insize, pos);
1850- updateHashChain(hash, pos, hashval, windowsize);
1851- if(usezeros && hashval == 0)
1852- {
1853- hash->zeros[pos % windowsize] = countZeros(in, insize, pos);
1854- }
1855- }
1856- }
1857-
1858- } /*end of the loop through each character of input*/
1859- } /*end of "if(!error)"*/
1860-
1861- return error;
1862-}
1863-
1864-/* /////////////////////////////////////////////////////////////////////////// */
1865-
1866-static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize)
1867-{
1868- /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
1869- 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
1870-
1871- size_t i, j, numdeflateblocks = (datasize + 65534) / 65535;
1872- unsigned datapos = 0;
1873- for(i = 0; i < numdeflateblocks; i++)
1874- {
1875- unsigned BFINAL, BTYPE, LEN, NLEN;
1876- unsigned char firstbyte;
1877-
1878- BFINAL = (i == numdeflateblocks - 1);
1879- BTYPE = 0;
1880-
1881- firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1));
1882- ucvector_push_back(out, firstbyte);
1883-
1884- LEN = 65535;
1885- if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos;
1886- NLEN = 65535 - LEN;
1887-
1888- ucvector_push_back(out, (unsigned char)(LEN % 256));
1889- ucvector_push_back(out, (unsigned char)(LEN / 256));
1890- ucvector_push_back(out, (unsigned char)(NLEN % 256));
1891- ucvector_push_back(out, (unsigned char)(NLEN / 256));
1892-
1893- /*Decompressed data*/
1894- for(j = 0; j < 65535 && datapos < datasize; j++)
1895- {
1896- ucvector_push_back(out, data[datapos++]);
1897- }
1898- }
1899-
1900- return 0;
1901-}
1902-
1903-/*
1904-write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
1905-tree_ll: the tree for lit and len codes.
1906-tree_d: the tree for distance codes.
1907-*/
1908-static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded,
1909- const HuffmanTree* tree_ll, const HuffmanTree* tree_d)
1910-{
1911- size_t i = 0;
1912- for(i = 0; i < lz77_encoded->size; i++)
1913- {
1914- unsigned val = lz77_encoded->data[i];
1915- addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val));
1916- if(val > 256) /*for a length code, 3 more things have to be added*/
1917- {
1918- unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
1919- unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
1920- unsigned length_extra_bits = lz77_encoded->data[++i];
1921-
1922- unsigned distance_code = lz77_encoded->data[++i];
1923-
1924- unsigned distance_index = distance_code;
1925- unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
1926- unsigned distance_extra_bits = lz77_encoded->data[++i];
1927-
1928- addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits);
1929- addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code),
1930- HuffmanTree_getLength(tree_d, distance_code));
1931- addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits);
1932- }
1933- }
1934-}
1935-
1936-/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
1937-static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash,
1938- const unsigned char* data, size_t datapos, size_t dataend,
1939- const LodePNGCompressSettings* settings, int final)
1940-{
1941- unsigned error = 0;
1942-
1943- /*
1944- A block is compressed as follows: The PNG data is lz77 encoded, resulting in
1945- literal bytes and length/distance pairs. This is then huffman compressed with
1946- two huffman trees. One huffman tree is used for the lit and len values ("ll"),
1947- another huffman tree is used for the dist values ("d"). These two trees are
1948- stored using their code lengths, and to compress even more these code lengths
1949- are also run-length encoded and huffman compressed. This gives a huffman tree
1950- of code lengths "cl". The code lenghts used to describe this third tree are
1951- the code length code lengths ("clcl").
1952- */
1953-
1954- /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
1955- uivector lz77_encoded;
1956- HuffmanTree tree_ll; /*tree for lit,len values*/
1957- HuffmanTree tree_d; /*tree for distance codes*/
1958- HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
1959- uivector frequencies_ll; /*frequency of lit,len codes*/
1960- uivector frequencies_d; /*frequency of dist codes*/
1961- uivector frequencies_cl; /*frequency of code length codes*/
1962- uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/
1963- uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/
1964- /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
1965- (these are written as is in the file, it would be crazy to compress these using yet another huffman
1966- tree that needs to be represented by yet another set of code lengths)*/
1967- uivector bitlen_cl;
1968- size_t datasize = dataend - datapos;
1969-
1970- /*
1971- Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies:
1972- bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
1973- bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
1974- bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
1975- */
1976-
1977- unsigned BFINAL = final;
1978- size_t numcodes_ll, numcodes_d, i;
1979- unsigned HLIT, HDIST, HCLEN;
1980-
1981- uivector_init(&lz77_encoded);
1982- HuffmanTree_init(&tree_ll);
1983- HuffmanTree_init(&tree_d);
1984- HuffmanTree_init(&tree_cl);
1985- uivector_init(&frequencies_ll);
1986- uivector_init(&frequencies_d);
1987- uivector_init(&frequencies_cl);
1988- uivector_init(&bitlen_lld);
1989- uivector_init(&bitlen_lld_e);
1990- uivector_init(&bitlen_cl);
1991-
1992- /*This while loop is never loops due to a break at the end, it is here to
1993- allow breaking out of it to the cleanup phase on error conditions.*/
1994- while(!error)
1995- {
1996- if(settings->use_lz77)
1997- {
1998- error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize); /*LZ77 encoded*/
1999- if(error) break;
2000- }
2001- else
2002- {
2003- if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
2004- for(i = datapos; i < dataend; i++) lz77_encoded.data[i] = data[i]; /*no LZ77, but still will be Huffman compressed*/
2005- }
2006-
2007- if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
2008- if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
2009-
2010- /*Count the frequencies of lit, len and dist codes*/
2011- for(i = 0; i < lz77_encoded.size; i++)
2012- {
2013- unsigned symbol = lz77_encoded.data[i];
2014- frequencies_ll.data[symbol]++;
2015- if(symbol > 256)
2016- {
2017- unsigned dist = lz77_encoded.data[i + 2];
2018- frequencies_d.data[dist]++;
2019- i += 3;
2020- }
2021- }
2022- frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
2023-
2024- /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
2025- error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, frequencies_ll.size, 15);
2026- if(error) break;
2027- error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, frequencies_d.size, 15);
2028- if(error) break;
2029-
2030- numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286;
2031- numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30;
2032- /*store the code lengths of both generated trees in bitlen_lld*/
2033- for(i = 0; i < numcodes_ll; i++) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i));
2034- for(i = 0; i < numcodes_d; i++) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i));
2035-
2036- /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
2037- 17 (3-10 zeroes), 18 (11-138 zeroes)*/
2038- for(i = 0; i < (unsigned)bitlen_lld.size; i++)
2039- {
2040- unsigned j = 0; /*amount of repititions*/
2041- while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) j++;
2042-
2043- if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/
2044- {
2045- j++; /*include the first zero*/
2046- if(j <= 10) /*repeat code 17 supports max 10 zeroes*/
2047- {
2048- uivector_push_back(&bitlen_lld_e, 17);
2049- uivector_push_back(&bitlen_lld_e, j - 3);
2050- }
2051- else /*repeat code 18 supports max 138 zeroes*/
2052- {
2053- if(j > 138) j = 138;
2054- uivector_push_back(&bitlen_lld_e, 18);
2055- uivector_push_back(&bitlen_lld_e, j - 11);
2056- }
2057- i += (j - 1);
2058- }
2059- else if(j >= 3) /*repeat code for value other than zero*/
2060- {
2061- size_t k;
2062- unsigned num = j / 6, rest = j % 6;
2063- uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
2064- for(k = 0; k < num; k++)
2065- {
2066- uivector_push_back(&bitlen_lld_e, 16);
2067- uivector_push_back(&bitlen_lld_e, 6 - 3);
2068- }
2069- if(rest >= 3)
2070- {
2071- uivector_push_back(&bitlen_lld_e, 16);
2072- uivector_push_back(&bitlen_lld_e, rest - 3);
2073- }
2074- else j -= rest;
2075- i += j;
2076- }
2077- else /*too short to benefit from repeat code*/
2078- {
2079- uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
2080- }
2081- }
2082-
2083- /*generate tree_cl, the huffmantree of huffmantrees*/
2084-
2085- if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/);
2086- for(i = 0; i < bitlen_lld_e.size; i++)
2087- {
2088- frequencies_cl.data[bitlen_lld_e.data[i]]++;
2089- /*after a repeat code come the bits that specify the number of repetitions,
2090- those don't need to be in the frequencies_cl calculation*/
2091- if(bitlen_lld_e.data[i] >= 16) i++;
2092- }
2093-
2094- error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data, frequencies_cl.size, 7);
2095- if(error) break;
2096-
2097- if(!uivector_resize(&bitlen_cl, NUM_CODE_LENGTH_CODES)) ERROR_BREAK(83 /*alloc fail*/);
2098- for(i = 0; i < NUM_CODE_LENGTH_CODES; i++)
2099- {
2100- /*lenghts of code length tree is in the order as specified by deflate*/
2101- bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]);
2102- }
2103- while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4)
2104- {
2105- /*remove zeros at the end, but minimum size must be 4*/
2106- if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/);
2107- }
2108- if(error) break;
2109-
2110- /*
2111- Write everything into the output
2112-
2113- After the BFINAL and BTYPE, the dynamic block consists out of the following:
2114- - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
2115- - (HCLEN+4)*3 bits code lengths of code length alphabet
2116- - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length
2117- alphabet, + possible repetition codes 16, 17, 18)
2118- - HDIST + 1 code lengths of distance alphabet (encoded using the code length
2119- alphabet, + possible repetition codes 16, 17, 18)
2120- - compressed data
2121- - 256 (end code)
2122- */
2123-
2124- /*Write block type*/
2125- addBitToStream(bp, out, BFINAL);
2126- addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/
2127- addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/
2128-
2129- /*write the HLIT, HDIST and HCLEN values*/
2130- HLIT = (unsigned)(numcodes_ll - 257);
2131- HDIST = (unsigned)(numcodes_d - 1);
2132- HCLEN = (unsigned)bitlen_cl.size - 4;
2133- addBitsToStream(bp, out, HLIT, 5);
2134- addBitsToStream(bp, out, HDIST, 5);
2135- addBitsToStream(bp, out, HCLEN, 4);
2136-
2137- /*write the code lenghts of the code length alphabet*/
2138- for(i = 0; i < HCLEN + 4; i++) addBitsToStream(bp, out, bitlen_cl.data[i], 3);
2139-
2140- /*write the lenghts of the lit/len AND the dist alphabet*/
2141- for(i = 0; i < bitlen_lld_e.size; i++)
2142- {
2143- addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]),
2144- HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i]));
2145- /*extra bits of repeat codes*/
2146- if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2);
2147- else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3);
2148- else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7);
2149- }
2150-
2151- /*write the compressed data symbols*/
2152- writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
2153- /*error: the length of the end code 256 must be larger than 0*/
2154- if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64);
2155-
2156- /*write the end code*/
2157- addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
2158-
2159- break; /*end of error-while*/
2160- }
2161-
2162- /*cleanup*/
2163- uivector_cleanup(&lz77_encoded);
2164- HuffmanTree_cleanup(&tree_ll);
2165- HuffmanTree_cleanup(&tree_d);
2166- HuffmanTree_cleanup(&tree_cl);
2167- uivector_cleanup(&frequencies_ll);
2168- uivector_cleanup(&frequencies_d);
2169- uivector_cleanup(&frequencies_cl);
2170- uivector_cleanup(&bitlen_lld_e);
2171- uivector_cleanup(&bitlen_lld);
2172- uivector_cleanup(&bitlen_cl);
2173-
2174- return error;
2175-}
2176-
2177-static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash,
2178- const unsigned char* data,
2179- size_t datapos, size_t dataend,
2180- const LodePNGCompressSettings* settings, int final)
2181-{
2182- HuffmanTree tree_ll; /*tree for literal values and length codes*/
2183- HuffmanTree tree_d; /*tree for distance codes*/
2184-
2185- unsigned BFINAL = final;
2186- unsigned error = 0;
2187- size_t i;
2188-
2189- HuffmanTree_init(&tree_ll);
2190- HuffmanTree_init(&tree_d);
2191-
2192- generateFixedLitLenTree(&tree_ll);
2193- generateFixedDistanceTree(&tree_d);
2194-
2195- addBitToStream(bp, out, BFINAL);
2196- addBitToStream(bp, out, 1); /*first bit of BTYPE*/
2197- addBitToStream(bp, out, 0); /*second bit of BTYPE*/
2198-
2199- if(settings->use_lz77) /*LZ77 encoded*/
2200- {
2201- uivector lz77_encoded;
2202- uivector_init(&lz77_encoded);
2203- error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize);
2204- if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
2205- uivector_cleanup(&lz77_encoded);
2206- }
2207- else /*no LZ77, but still will be Huffman compressed*/
2208- {
2209- for(i = datapos; i < dataend; i++)
2210- {
2211- addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i]));
2212- }
2213- }
2214- /*add END code*/
2215- if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
2216-
2217- /*cleanup*/
2218- HuffmanTree_cleanup(&tree_ll);
2219- HuffmanTree_cleanup(&tree_d);
2220-
2221- return error;
2222-}
2223-
2224-static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
2225- const LodePNGCompressSettings* settings)
2226-{
2227-#if LODEPNG_CUSTOM_ZLIB_ENCODER == 2
2228- if(settings->custom_encoder)
2229- {
2230- unsigned char** out2 = &out->data;
2231- size_t* outsize = &out->size;
2232-
2233- unsigned error = lodepng_custom_deflate(out2, outsize, in, insize, settings);
2234-
2235- if(!error) ucvector_init_buffer(out, *out2, *outsize);
2236- return error;
2237- }
2238- else
2239- {
2240-#endif /*LODEPNG_CUSTOM_ZLIB_ENCODER == 2*/
2241- unsigned error = 0;
2242- size_t i, blocksize, numdeflateblocks;
2243- size_t bp = 0; /*the bit pointer*/
2244- Hash hash;
2245-
2246- if(settings->btype > 2) return 61;
2247-
2248- if(settings->btype == 0) return deflateNoCompression(out, in, insize);
2249-
2250- if(settings->btype == 1) blocksize = insize;
2251- else /*if(settings->btype == 2)*/
2252- {
2253- blocksize = insize / 8 + 8;
2254- if(blocksize < 65535) blocksize = 65535;
2255- }
2256-
2257- numdeflateblocks = (insize + blocksize - 1) / blocksize;
2258- if(numdeflateblocks == 0) numdeflateblocks = 1;
2259-
2260- error = hash_init(&hash, settings->windowsize);
2261- if(error) return error;
2262-
2263- for(i = 0; i < numdeflateblocks && !error; i++)
2264- {
2265- int final = i == numdeflateblocks - 1;
2266- size_t start = i * blocksize;
2267- size_t end = start + blocksize;
2268- if(end > insize) end = insize;
2269-
2270- if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final);
2271- else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final);
2272- }
2273-
2274- hash_cleanup(&hash);
2275-
2276- return error;
2277-#if LODEPNG_CUSTOM_ZLIB_ENCODER == 2
2278- }
2279-#endif /*LODEPNG_CUSTOM_ZLIB_ENCODER == 2*/
2280-}
2281-
2282-unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
2283- const unsigned char* in, size_t insize,
2284- const LodePNGCompressSettings* settings)
2285-{
2286- unsigned error;
2287- ucvector v;
2288- ucvector_init_buffer(&v, *out, *outsize);
2289- error = lodepng_deflatev(&v, in, insize, settings);
2290- *out = v.data;
2291- *outsize = v.size;
2292- return error;
2293-}
2294-
2295-#endif /*LODEPNG_COMPILE_DECODER*/
2296-
2297-/* ////////////////////////////////////////////////////////////////////////// */
2298-/* / Adler32 */
2299-/* ////////////////////////////////////////////////////////////////////////// */
2300-
2301-static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len)
2302-{
2303- unsigned s1 = adler & 0xffff;
2304- unsigned s2 = (adler >> 16) & 0xffff;
2305-
2306- while(len > 0)
2307- {
2308- /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/
2309- unsigned amount = len > 5550 ? 5550 : len;
2310- len -= amount;
2311- while(amount > 0)
2312- {
2313- s1 = (s1 + *data++);
2314- s2 = (s2 + s1);
2315- amount--;
2316- }
2317- s1 %= 65521;
2318- s2 %= 65521;
2319- }
2320-
2321- return (s2 << 16) | s1;
2322-}
2323-
2324-/*Return the adler32 of the bytes data[0..len-1]*/
2325-static unsigned adler32(const unsigned char* data, unsigned len)
2326-{
2327- return update_adler32(1L, data, len);
2328-}
2329-
2330-/* ////////////////////////////////////////////////////////////////////////// */
2331-/* / Zlib / */
2332-/* ////////////////////////////////////////////////////////////////////////// */
2333-
2334-#ifdef LODEPNG_COMPILE_DECODER
2335-
2336-unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2337- size_t insize, const LodePNGDecompressSettings* settings)
2338-{
2339-#if LODEPNG_CUSTOM_ZLIB_DECODER == 1
2340- if(settings->custom_decoder)
2341- {
2342- return lodepng_custom_zlib_decompress(out, outsize, in, insize, settings);
2343- }
2344- else
2345- {
2346-#endif /*LODEPNG_CUSTOM_ZLIB_DECODER == 1*/
2347- unsigned error = 0;
2348- unsigned CM, CINFO, FDICT;
2349-
2350- if(insize < 2) return 53; /*error, size of zlib data too small*/
2351- /*read information from zlib header*/
2352- if((in[0] * 256 + in[1]) % 31 != 0)
2353- {
2354- /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
2355- return 24;
2356- }
2357-
2358- CM = in[0] & 15;
2359- CINFO = (in[0] >> 4) & 15;
2360- /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
2361- FDICT = (in[1] >> 5) & 1;
2362- /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
2363-
2364- if(CM != 8 || CINFO > 7)
2365- {
2366- /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
2367- return 25;
2368- }
2369- if(FDICT != 0)
2370- {
2371- /*error: the specification of PNG says about the zlib stream:
2372- "The additional flags shall not specify a preset dictionary."*/
2373- return 26;
2374- }
2375-
2376- error = lodepng_inflate(out, outsize, in + 2, insize - 2, settings);
2377- if(error) return error;
2378-
2379- if(!settings->ignore_adler32)
2380- {
2381- unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
2382- unsigned checksum = adler32(*out, (unsigned)(*outsize));
2383- if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
2384- }
2385-
2386- return 0; /*no error*/
2387-#if LODEPNG_CUSTOM_ZLIB_DECODER == 1
2388- }
2389-#endif /*LODEPNG_CUSTOM_ZLIB_DECODER == 1*/
2390-}
2391-
2392-#endif /*LODEPNG_COMPILE_DECODER*/
2393-
2394-#ifdef LODEPNG_COMPILE_ENCODER
2395-
2396-unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2397- size_t insize, const LodePNGCompressSettings* settings)
2398-{
2399-#if LODEPNG_CUSTOM_ZLIB_ENCODER == 1
2400- if(settings->custom_encoder)
2401- {
2402- return lodepng_custom_zlib_decompress(out, outsize, in, insize, settings);
2403- }
2404- else
2405- {
2406-#endif /*LODEPNG_CUSTOM_ZLIB_ENCODER == 1*/
2407- /*initially, *out must be nullptr and outsize 0, if you just give some random *out
2408- that's pointing to a non allocated buffer, this'll crash*/
2409- ucvector deflatedata, outv;
2410- size_t i;
2411- unsigned error;
2412-
2413- unsigned ADLER32;
2414- /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
2415- unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
2416- unsigned FLEVEL = 0;
2417- unsigned FDICT = 0;
2418- unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
2419- unsigned FCHECK = 31 - CMFFLG % 31;
2420- CMFFLG += FCHECK;
2421-
2422- /*ucvector-controlled version of the output buffer, for dynamic array*/
2423- ucvector_init_buffer(&outv, *out, *outsize);
2424-
2425- ucvector_push_back(&outv, (unsigned char)(CMFFLG / 256));
2426- ucvector_push_back(&outv, (unsigned char)(CMFFLG % 256));
2427-
2428- ucvector_init(&deflatedata);
2429- error = lodepng_deflatev(&deflatedata, in, insize, settings);
2430-
2431- if(!error)
2432- {
2433- ADLER32 = adler32(in, (unsigned)insize);
2434- for(i = 0; i < deflatedata.size; i++) ucvector_push_back(&outv, deflatedata.data[i]);
2435- ucvector_cleanup(&deflatedata);
2436- lodepng_add32bitInt(&outv, ADLER32);
2437- }
2438-
2439- *out = outv.data;
2440- *outsize = outv.size;
2441-
2442- return error;
2443-#if LODEPNG_CUSTOM_ZLIB_ENCODER == 1
2444- }
2445-#endif /*LODEPNG_CUSTOM_ZLIB_ENCODER == 1*/
2446-}
2447-
2448-#endif /*LODEPNG_COMPILE_ENCODER*/
2449-
2450-#else /*no LODEPNG_COMPILE_ZLIB*/
2451-
2452-#ifdef LODEPNG_COMPILE_DECODER
2453-static unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
2454- size_t insize, const LodePNGDecompressSettings* settings)
2455-{
2456- return lodepng_custom_zlib_decompress(out, outsize, in, insize, settings);
2457-}
2458-#endif /*LODEPNG_COMPILE_DECODER*/
2459-#ifdef LODEPNG_COMPILE_ENCODER
2460-static unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
2461- size_t insize, const LodePNGCompressSettings* settings)
2462-{
2463- return lodepng_custom_zlib_compress(out, outsize, in, insize, settings);
2464-}
2465-#endif /*LODEPNG_COMPILE_ENCODER*/
2466-
2467-#endif /*LODEPNG_COMPILE_ZLIB*/
2468-
2469-/* ////////////////////////////////////////////////////////////////////////// */
2470-
2471-#ifdef LODEPNG_COMPILE_ENCODER
2472-
2473-/*this is a good tradeoff between speed and compression ratio*/
2474-#define DEFAULT_WINDOWSIZE 2048
2475-
2476-void lodepng_compress_settings_init(LodePNGCompressSettings* settings)
2477-{
2478- /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
2479- settings->btype = 2;
2480- settings->use_lz77 = 1;
2481- settings->windowsize = DEFAULT_WINDOWSIZE;
2482-#if LODEPNG_CUSTOM_ZLIB_ENCODER == 0
2483- settings->custom_encoder = 0;
2484-#else
2485- settings->custom_encoder = 1;
2486-#endif
2487-}
2488-
2489-#if LODEPNG_CUSTOM_ZLIB_ENCODER == 0
2490-const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 0};
2491-#else
2492-const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 1};
2493-#endif
2494-
2495-
2496-#endif /*LODEPNG_COMPILE_ENCODER*/
2497-
2498-#ifdef LODEPNG_COMPILE_DECODER
2499-
2500-void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings)
2501-{
2502- settings->ignore_adler32 = 0;
2503-#if LODEPNG_CUSTOM_ZLIB_DECODER == 0
2504- settings->custom_decoder = 0;
2505-#else
2506- settings->custom_decoder = 1;
2507-#endif
2508-}
2509-
2510-#if LODEPNG_CUSTOM_ZLIB_DECODER == 0
2511-const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0};
2512-#else
2513-const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 1};
2514-#endif
2515-
2516-#endif /*LODEPNG_COMPILE_DECODER*/
2517-
2518-/* ////////////////////////////////////////////////////////////////////////// */
2519-/* ////////////////////////////////////////////////////////////////////////// */
2520-/* // End of Zlib related code. Begin of PNG related code. // */
2521-/* ////////////////////////////////////////////////////////////////////////// */
2522-/* ////////////////////////////////////////////////////////////////////////// */
2523-
2524-#ifdef LODEPNG_COMPILE_PNG
2525-
2526-/* ////////////////////////////////////////////////////////////////////////// */
2527-/* / CRC32 / */
2528-/* ////////////////////////////////////////////////////////////////////////// */
2529-
2530-static unsigned Crc32_crc_table_computed = 0;
2531-static unsigned Crc32_crc_table[256];
2532-
2533-/*Make the table for a fast CRC.*/
2534-static void Crc32_make_crc_table(void)
2535-{
2536- unsigned c, k, n;
2537- for(n = 0; n < 256; n++)
2538- {
2539- c = n;
2540- for(k = 0; k < 8; k++)
2541- {
2542- if(c & 1) c = 0xedb88320L ^ (c >> 1);
2543- else c = c >> 1;
2544- }
2545- Crc32_crc_table[n] = c;
2546- }
2547- Crc32_crc_table_computed = 1;
2548-}
2549-
2550-/*Update a running CRC with the bytes buf[0..len-1]--the CRC should be
2551-initialized to all 1's, and the transmitted value is the 1's complement of the
2552-final running CRC (see the crc() routine below).*/
2553-static unsigned Crc32_update_crc(const unsigned char* buf, unsigned crc, size_t len)
2554-{
2555- unsigned c = crc;
2556- size_t n;
2557-
2558- if(!Crc32_crc_table_computed) Crc32_make_crc_table();
2559- for(n = 0; n < len; n++)
2560- {
2561- c = Crc32_crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
2562- }
2563- return c;
2564-}
2565-
2566-/*Return the CRC of the bytes buf[0..len-1].*/
2567-unsigned lodepng_crc32(const unsigned char* buf, size_t len)
2568-{
2569- return Crc32_update_crc(buf, 0xffffffffL, len) ^ 0xffffffffL;
2570-}
2571-
2572-/* ////////////////////////////////////////////////////////////////////////// */
2573-/* / Reading and writing single bits and bytes from/to stream for LodePNG / */
2574-/* ////////////////////////////////////////////////////////////////////////// */
2575-
2576-static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream)
2577-{
2578- unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
2579- (*bitpointer)++;
2580- return result;
2581-}
2582-
2583-static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
2584-{
2585- unsigned result = 0;
2586- size_t i;
2587- for(i = nbits - 1; i < nbits; i--)
2588- {
2589- result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i;
2590- }
2591- return result;
2592-}
2593-
2594-#ifdef LODEPNG_COMPILE_DECODER
2595-static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2596-{
2597- /*the current bit in bitstream must be 0 for this to work*/
2598- if(bit)
2599- {
2600- /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
2601- bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7)));
2602- }
2603- (*bitpointer)++;
2604-}
2605-#endif /*LODEPNG_COMPILE_DECODER*/
2606-
2607-static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
2608-{
2609- /*the current bit in bitstream may be 0 or 1 for this to work*/
2610- if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7))));
2611- else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7)));
2612- (*bitpointer)++;
2613-}
2614-
2615-/* ////////////////////////////////////////////////////////////////////////// */
2616-/* / PNG chunks / */
2617-/* ////////////////////////////////////////////////////////////////////////// */
2618-
2619-unsigned lodepng_chunk_length(const unsigned char* chunk)
2620-{
2621- return lodepng_read32bitInt(&chunk[0]);
2622-}
2623-
2624-void lodepng_chunk_type(char type[5], const unsigned char* chunk)
2625-{
2626- unsigned i;
2627- for(i = 0; i < 4; i++) type[i] = chunk[4 + i];
2628- type[4] = 0; /*null termination char*/
2629-}
2630-
2631-unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type)
2632-{
2633- if(strlen(type) != 4) return 0;
2634- return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
2635-}
2636-
2637-unsigned char lodepng_chunk_ancillary(const unsigned char* chunk)
2638-{
2639- return((chunk[4] & 32) != 0);
2640-}
2641-
2642-unsigned char lodepng_chunk_private(const unsigned char* chunk)
2643-{
2644- return((chunk[6] & 32) != 0);
2645-}
2646-
2647-unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk)
2648-{
2649- return((chunk[7] & 32) != 0);
2650-}
2651-
2652-unsigned char* lodepng_chunk_data(unsigned char* chunk)
2653-{
2654- return &chunk[8];
2655-}
2656-
2657-const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk)
2658-{
2659- return &chunk[8];
2660-}
2661-
2662-unsigned lodepng_chunk_check_crc(const unsigned char* chunk)
2663-{
2664- unsigned length = lodepng_chunk_length(chunk);
2665- unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
2666- /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
2667- unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
2668- if(CRC != checksum) return 1;
2669- else return 0;
2670-}
2671-
2672-void lodepng_chunk_generate_crc(unsigned char* chunk)
2673-{
2674- unsigned length = lodepng_chunk_length(chunk);
2675- unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
2676- lodepng_set32bitInt(chunk + 8 + length, CRC);
2677-}
2678-
2679-unsigned char* lodepng_chunk_next(unsigned char* chunk)
2680-{
2681- unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2682- return &chunk[total_chunk_length];
2683-}
2684-
2685-const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk)
2686-{
2687- unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2688- return &chunk[total_chunk_length];
2689-}
2690-
2691-unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk)
2692-{
2693- unsigned i;
2694- unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
2695- unsigned char *chunk_start, *new_buffer;
2696- size_t new_length = (*outlength) + total_chunk_length;
2697- if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
2698-
2699- new_buffer = (unsigned char*)myrealloc(*out, new_length);
2700- if(!new_buffer) return 83; /*alloc fail*/
2701- (*out) = new_buffer;
2702- (*outlength) = new_length;
2703- chunk_start = &(*out)[new_length - total_chunk_length];
2704-
2705- for(i = 0; i < total_chunk_length; i++) chunk_start[i] = chunk[i];
2706-
2707- return 0;
2708-}
2709-
2710-unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
2711- const char* type, const unsigned char* data)
2712-{
2713- unsigned i;
2714- unsigned char *chunk, *new_buffer;
2715- size_t new_length = (*outlength) + length + 12;
2716- if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
2717- new_buffer = (unsigned char*)myrealloc(*out, new_length);
2718- if(!new_buffer) return 83; /*alloc fail*/
2719- (*out) = new_buffer;
2720- (*outlength) = new_length;
2721- chunk = &(*out)[(*outlength) - length - 12];
2722-
2723- /*1: length*/
2724- lodepng_set32bitInt(chunk, (unsigned)length);
2725-
2726- /*2: chunk name (4 letters)*/
2727- chunk[4] = type[0];
2728- chunk[5] = type[1];
2729- chunk[6] = type[2];
2730- chunk[7] = type[3];
2731-
2732- /*3: the data*/
2733- for(i = 0; i < length; i++) chunk[8 + i] = data[i];
2734-
2735- /*4: CRC (of the chunkname characters and the data)*/
2736- lodepng_chunk_generate_crc(chunk);
2737-
2738- return 0;
2739-}
2740-
2741-/* ////////////////////////////////////////////////////////////////////////// */
2742-/* / Color types and such / */
2743-/* ////////////////////////////////////////////////////////////////////////// */
2744-
2745-/*return type is a LodePNG error code*/
2746-static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/
2747-{
2748- switch(colortype)
2749- {
2750- case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/
2751- case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/
2752- case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/
2753- case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/
2754- case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/
2755- default: return 31;
2756- }
2757- return 0; /*allowed color type / bits combination*/
2758-}
2759-
2760-static unsigned getNumColorChannels(LodePNGColorType colortype)
2761-{
2762- switch(colortype)
2763- {
2764- case 0: return 1; /*grey*/
2765- case 2: return 3; /*RGB*/
2766- case 3: return 1; /*palette*/
2767- case 4: return 2; /*grey + alpha*/
2768- case 6: return 4; /*RGBA*/
2769- }
2770- return 0; /*unexisting color type*/
2771-}
2772-
2773-static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth)
2774-{
2775- /*bits per pixel is amount of channels * bits per channel*/
2776- return getNumColorChannels(colortype) * bitdepth;
2777-}
2778-
2779-/* ////////////////////////////////////////////////////////////////////////// */
2780-
2781-void lodepng_color_mode_init(LodePNGColorMode* info)
2782-{
2783- info->key_defined = 0;
2784- info->key_r = info->key_g = info->key_b = 0;
2785- info->colortype = LCT_RGBA;
2786- info->bitdepth = 8;
2787- info->palette = 0;
2788- info->palettesize = 0;
2789-}
2790-
2791-void lodepng_color_mode_cleanup(LodePNGColorMode* info)
2792-{
2793- lodepng_palette_clear(info);
2794-}
2795-
2796-unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source)
2797-{
2798- size_t i;
2799- lodepng_color_mode_cleanup(dest);
2800- *dest = *source;
2801- if(source->palette)
2802- {
2803- dest->palette = (unsigned char*)mymalloc(source->palettesize * 4);
2804- if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
2805- for(i = 0; i < source->palettesize * 4; i++) dest->palette[i] = source->palette[i];
2806- }
2807- return 0;
2808-}
2809-
2810-static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b)
2811-{
2812- size_t i;
2813- if(a->colortype != b->colortype) return 0;
2814- if(a->bitdepth != b->bitdepth) return 0;
2815- if(a->key_defined != b->key_defined) return 0;
2816- if(a->key_defined)
2817- {
2818- if(a->key_r != b->key_r) return 0;
2819- if(a->key_g != b->key_g) return 0;
2820- if(a->key_b != b->key_b) return 0;
2821- }
2822- if(a->palettesize != b->palettesize) return 0;
2823- for(i = 0; i < a->palettesize * 4; i++)
2824- {
2825- if(a->palette[i] != b->palette[i]) return 0;
2826- }
2827- return 1;
2828-}
2829-
2830-void lodepng_palette_clear(LodePNGColorMode* info)
2831-{
2832- if(info->palette) myfree(info->palette);
2833- info->palettesize = 0;
2834-}
2835-
2836-unsigned lodepng_palette_add(LodePNGColorMode* info,
2837- unsigned char r, unsigned char g, unsigned char b, unsigned char a)
2838-{
2839- unsigned char* data;
2840- /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with
2841- the max of 256 colors, it'll have the exact alloc size*/
2842- if(!(info->palettesize & (info->palettesize - 1))) /*if palettesize is 0 or a power of two*/
2843- {
2844- /*allocated data must be at least 4* palettesize (for 4 color bytes)*/
2845- size_t alloc_size = info->palettesize == 0 ? 4 : info->palettesize * 4 * 2;
2846- data = (unsigned char*)myrealloc(info->palette, alloc_size);
2847- if(!data) return 83; /*alloc fail*/
2848- else info->palette = data;
2849- }
2850- info->palette[4 * info->palettesize + 0] = r;
2851- info->palette[4 * info->palettesize + 1] = g;
2852- info->palette[4 * info->palettesize + 2] = b;
2853- info->palette[4 * info->palettesize + 3] = a;
2854- info->palettesize++;
2855- return 0;
2856-}
2857-
2858-unsigned lodepng_get_bpp(const LodePNGColorMode* info)
2859-{
2860- /*calculate bits per pixel out of colortype and bitdepth*/
2861- return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
2862-}
2863-
2864-unsigned lodepng_get_channels(const LodePNGColorMode* info)
2865-{
2866- return getNumColorChannels(info->colortype);
2867-}
2868-
2869-unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info)
2870-{
2871- return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
2872-}
2873-
2874-unsigned lodepng_is_alpha_type(const LodePNGColorMode* info)
2875-{
2876- return (info->colortype & 4) != 0; /*4 or 6*/
2877-}
2878-
2879-unsigned lodepng_is_palette_type(const LodePNGColorMode* info)
2880-{
2881- return info->colortype == LCT_PALETTE;
2882-}
2883-
2884-unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info)
2885-{
2886- size_t i;
2887- for(i = 0; i < info->palettesize; i++)
2888- {
2889- if(info->palette[i * 4 + 3] < 255) return 1;
2890- }
2891- return 0;
2892-}
2893-
2894-unsigned lodepng_can_have_alpha(const LodePNGColorMode* info)
2895-{
2896- return info->key_defined
2897- || lodepng_is_alpha_type(info)
2898- || lodepng_has_palette_alpha(info);
2899-}
2900-
2901-size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color)
2902-{
2903- return (w * h * lodepng_get_bpp(color) + 7) / 8;
2904-}
2905-
2906-size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
2907-{
2908- return (w * h * lodepng_get_bpp_lct(colortype, bitdepth) + 7) / 8;
2909-}
2910-
2911-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
2912-
2913-static void LodePNGUnknownChunks_init(LodePNGInfo* info)
2914-{
2915- unsigned i;
2916- for(i = 0; i < 3; i++) info->unknown_chunks_data[i] = 0;
2917- for(i = 0; i < 3; i++) info->unknown_chunks_size[i] = 0;
2918-}
2919-
2920-static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info)
2921-{
2922- unsigned i;
2923- for(i = 0; i < 3; i++) myfree(info->unknown_chunks_data[i]);
2924-}
2925-
2926-static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src)
2927-{
2928- unsigned i;
2929-
2930- LodePNGUnknownChunks_cleanup(dest);
2931-
2932- for(i = 0; i < 3; i++)
2933- {
2934- size_t j;
2935- dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
2936- dest->unknown_chunks_data[i] = (unsigned char*)mymalloc(src->unknown_chunks_size[i]);
2937- if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
2938- for(j = 0; j < src->unknown_chunks_size[i]; j++)
2939- {
2940- dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
2941- }
2942- }
2943-
2944- return 0;
2945-}
2946-
2947-/******************************************************************************/
2948-
2949-static void LodePNGText_init(LodePNGInfo* info)
2950-{
2951- info->text_num = 0;
2952- info->text_keys = nullptr;
2953- info->text_strings = nullptr;
2954-}
2955-
2956-static void LodePNGText_cleanup(LodePNGInfo* info)
2957-{
2958- size_t i;
2959- for(i = 0; i < info->text_num; i++)
2960- {
2961- string_cleanup(&info->text_keys[i]);
2962- string_cleanup(&info->text_strings[i]);
2963- }
2964- myfree(info->text_keys);
2965- myfree(info->text_strings);
2966-}
2967-
2968-static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
2969-{
2970- size_t i = 0;
2971- dest->text_keys = 0;
2972- dest->text_strings = 0;
2973- dest->text_num = 0;
2974- for(i = 0; i < source->text_num; i++)
2975- {
2976- CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
2977- }
2978- return 0;
2979-}
2980-
2981-void lodepng_clear_text(LodePNGInfo* info)
2982-{
2983- LodePNGText_cleanup(info);
2984-}
2985-
2986-unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str)
2987-{
2988- char** new_keys = (char**)(myrealloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
2989- char** new_strings = (char**)(myrealloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
2990- if(!new_keys || !new_strings)
2991- {
2992- myfree(new_keys);
2993- myfree(new_strings);
2994- return 83; /*alloc fail*/
2995- }
2996-
2997- info->text_num++;
2998- info->text_keys = new_keys;
2999- info->text_strings = new_strings;
3000-
3001- string_init(&info->text_keys[info->text_num - 1]);
3002- string_set(&info->text_keys[info->text_num - 1], key);
3003-
3004- string_init(&info->text_strings[info->text_num - 1]);
3005- string_set(&info->text_strings[info->text_num - 1], str);
3006-
3007- return 0;
3008-}
3009-
3010-/******************************************************************************/
3011-
3012-static void LodePNGIText_init(LodePNGInfo* info)
3013-{
3014- info->itext_num = 0;
3015- info->itext_keys = nullptr;
3016- info->itext_langtags = nullptr;
3017- info->itext_transkeys = nullptr;
3018- info->itext_strings = nullptr;
3019-}
3020-
3021-static void LodePNGIText_cleanup(LodePNGInfo* info)
3022-{
3023- size_t i;
3024- for(i = 0; i < info->itext_num; i++)
3025- {
3026- string_cleanup(&info->itext_keys[i]);
3027- string_cleanup(&info->itext_langtags[i]);
3028- string_cleanup(&info->itext_transkeys[i]);
3029- string_cleanup(&info->itext_strings[i]);
3030- }
3031- myfree(info->itext_keys);
3032- myfree(info->itext_langtags);
3033- myfree(info->itext_transkeys);
3034- myfree(info->itext_strings);
3035-}
3036-
3037-static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
3038-{
3039- size_t i = 0;
3040- dest->itext_keys = 0;
3041- dest->itext_langtags = 0;
3042- dest->itext_transkeys = 0;
3043- dest->itext_strings = 0;
3044- dest->itext_num = 0;
3045- for(i = 0; i < source->itext_num; i++)
3046- {
3047- CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
3048- source->itext_transkeys[i], source->itext_strings[i]));
3049- }
3050- return 0;
3051-}
3052-
3053-void lodepng_clear_itext(LodePNGInfo* info)
3054-{
3055- LodePNGIText_cleanup(info);
3056-}
3057-
3058-unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
3059- const char* transkey, const char* str)
3060-{
3061- char** new_keys = (char**)(myrealloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
3062- char** new_langtags = (char**)(myrealloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
3063- char** new_transkeys = (char**)(myrealloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
3064- char** new_strings = (char**)(myrealloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
3065- if(!new_keys || !new_langtags || !new_transkeys || !new_strings)
3066- {
3067- myfree(new_keys);
3068- myfree(new_langtags);
3069- myfree(new_transkeys);
3070- myfree(new_strings);
3071- return 83; /*alloc fail*/
3072- }
3073-
3074- info->itext_num++;
3075- info->itext_keys = new_keys;
3076- info->itext_langtags = new_langtags;
3077- info->itext_transkeys = new_transkeys;
3078- info->itext_strings = new_strings;
3079-
3080- string_init(&info->itext_keys[info->itext_num - 1]);
3081- string_set(&info->itext_keys[info->itext_num - 1], key);
3082-
3083- string_init(&info->itext_langtags[info->itext_num - 1]);
3084- string_set(&info->itext_langtags[info->itext_num - 1], langtag);
3085-
3086- string_init(&info->itext_transkeys[info->itext_num - 1]);
3087- string_set(&info->itext_transkeys[info->itext_num - 1], transkey);
3088-
3089- string_init(&info->itext_strings[info->itext_num - 1]);
3090- string_set(&info->itext_strings[info->itext_num - 1], str);
3091-
3092- return 0;
3093-}
3094-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
3095-
3096-void lodepng_info_init(LodePNGInfo* info)
3097-{
3098- lodepng_color_mode_init(&info->color);
3099- info->interlace_method = 0;
3100- info->compression_method = 0;
3101- info->filter_method = 0;
3102-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
3103- info->background_defined = 0;
3104- info->background_r = info->background_g = info->background_b = 0;
3105-
3106- LodePNGText_init(info);
3107- LodePNGIText_init(info);
3108-
3109- info->time_defined = 0;
3110- info->phys_defined = 0;
3111-
3112- LodePNGUnknownChunks_init(info);
3113-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
3114-}
3115-
3116-void lodepng_info_cleanup(LodePNGInfo* info)
3117-{
3118- lodepng_color_mode_cleanup(&info->color);
3119-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
3120- LodePNGText_cleanup(info);
3121- LodePNGIText_cleanup(info);
3122-
3123- LodePNGUnknownChunks_cleanup(info);
3124-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
3125-}
3126-
3127-unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source)
3128-{
3129- lodepng_info_cleanup(dest);
3130- *dest = *source;
3131- lodepng_color_mode_init(&dest->color);
3132- CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
3133-
3134-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
3135- CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
3136- CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
3137-
3138- LodePNGUnknownChunks_init(dest);
3139- CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
3140-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
3141- return 0;
3142-}
3143-
3144-void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b)
3145-{
3146- LodePNGInfo temp = *a;
3147- *a = *b;
3148- *b = temp;
3149-}
3150-
3151-/* ////////////////////////////////////////////////////////////////////////// */
3152-
3153-/*index: bitgroup index, bits: bitgroup size(1, 2 or 4, in: bitgroup value, out: octet array to add bits to*/
3154-static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in)
3155-{
3156- /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
3157- unsigned p = index % (8 / bits);
3158- in &= (1 << bits) - 1; /*filter out any other bits of the input value*/
3159- in = in << (bits * (8 / bits - p - 1));
3160- if(p == 0) out[index * bits / 8] = in;
3161- else out[index * bits / 8] |= in;
3162-}
3163-
3164-typedef struct ColorTree ColorTree;
3165-
3166-/*
3167-One node of a color tree
3168-This is the data structure used to count the number of unique colors and to get a palette
3169-index for a color. This could use up to 256x the memory of the amount of colors, but it
3170-is only used to count up to 256, and is used because implementing a whole dictionary data
3171-structure in C here would take too much room.
3172-*/
3173-struct ColorTree
3174-{
3175- ColorTree* next; /*null, or array of 256 pointers to ColorTree of next level*/
3176- int index; /*the payload. Only has a meaningful value if this is in the 4th level*/
3177-};
3178-
3179-static void color_tree_make_next(ColorTree* tree);
3180-
3181-/*next: whether to create the next array or not*/
3182-static void color_tree_init(ColorTree* tree, int next)
3183-{
3184- if(next) color_tree_make_next(tree);
3185- else tree->next = 0;
3186- tree->index = -1;
3187-}
3188-
3189-static void color_tree_make_next(ColorTree* tree)
3190-{
3191- int i;
3192- tree->next = (ColorTree*)mymalloc(256 * sizeof(ColorTree));
3193- for(i = 0; i < 256; i++) color_tree_init(&tree->next[i], 0);
3194-}
3195-
3196-static void color_tree_cleanup(ColorTree* tree)
3197-{
3198- if(tree->next)
3199- {
3200- int i;
3201- for(i = 0; i < 256; i++) color_tree_cleanup(&tree->next[i]);
3202- myfree(tree->next);
3203- }
3204-}
3205-
3206-/*returns -1 if color not present, its index otherwise*/
3207-static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
3208-{
3209- tree = &tree->next[r];
3210- if(tree->next == 0) return -1;
3211- tree = &tree->next[g];
3212- if(tree->next == 0) return -1;
3213- tree = &tree->next[b];
3214- if(tree->next == 0) return -1;
3215- tree = &tree->next[a];
3216-
3217- return tree->index;
3218-}
3219-
3220-#ifdef LODEPNG_COMPILE_ENCODER
3221-static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
3222-{
3223- return color_tree_get(tree, r, g, b, a) >= 0;
3224-}
3225-#endif /*LODEPNG_COMPILE_ENCODER*/
3226-
3227-/*color is not allowed to already exist. Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
3228-static void color_tree_add(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a, int index)
3229-{
3230- tree = &tree->next[r];
3231- if(tree->next == 0) color_tree_make_next(tree);
3232- tree = &tree->next[g];
3233- if(tree->next == 0) color_tree_make_next(tree);
3234- tree = &tree->next[b];
3235- if(tree->next == 0) color_tree_make_next(tree);
3236- tree = &tree->next[a];
3237-
3238- tree->index = index;
3239-}
3240-
3241-/*put a pixel, given its RGBA color, into image of any color type*/
3242-static unsigned rgba8ToPixel(unsigned char* out, size_t i,
3243- const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
3244- unsigned char r, unsigned char g, unsigned char b, unsigned char a)
3245-{
3246- if(mode->colortype == LCT_GREY)
3247- {
3248- unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
3249- if(mode->bitdepth == 8) out[i] = grey;
3250- else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey;
3251- else
3252- {
3253- /*take the most significant bits of grey*/
3254- grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1);
3255- addColorBits(out, i, mode->bitdepth, grey);
3256- }
3257- }
3258- else if(mode->colortype == LCT_RGB)
3259- {
3260- if(mode->bitdepth == 8)
3261- {
3262- out[i * 3 + 0] = r;
3263- out[i * 3 + 1] = g;
3264- out[i * 3 + 2] = b;
3265- }
3266- else
3267- {
3268- out[i * 6 + 0] = out[i * 6 + 1] = r;
3269- out[i * 6 + 2] = out[i * 6 + 3] = g;
3270- out[i * 6 + 4] = out[i * 6 + 5] = b;
3271- }
3272- }
3273- else if(mode->colortype == LCT_PALETTE)
3274- {
3275- int index = color_tree_get(tree, r, g, b, a);
3276- if(index < 0) return 82; /*color not in palette*/
3277- if(mode->bitdepth == 8) out[i] = index;
3278- else addColorBits(out, i, mode->bitdepth, index);
3279- }
3280- else if(mode->colortype == LCT_GREY_ALPHA)
3281- {
3282- unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
3283- if(mode->bitdepth == 8)
3284- {
3285- out[i * 2 + 0] = grey;
3286- out[i * 2 + 1] = a;
3287- }
3288- else if(mode->bitdepth == 16)
3289- {
3290- out[i * 4 + 0] = out[i * 4 + 1] = grey;
3291- out[i * 4 + 2] = out[i * 4 + 3] = a;
3292- }
3293- }
3294- else if(mode->colortype == LCT_RGBA)
3295- {
3296- if(mode->bitdepth == 8)
3297- {
3298- out[i * 4 + 0] = r;
3299- out[i * 4 + 1] = g;
3300- out[i * 4 + 2] = b;
3301- out[i * 4 + 3] = a;
3302- }
3303- else
3304- {
3305- out[i * 8 + 0] = out[i * 8 + 1] = r;
3306- out[i * 8 + 2] = out[i * 8 + 3] = g;
3307- out[i * 8 + 4] = out[i * 8 + 5] = b;
3308- out[i * 8 + 6] = out[i * 8 + 7] = a;
3309- }
3310- }
3311-
3312- return 0; /*no error*/
3313-}
3314-
3315-/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
3316-static unsigned rgba16ToPixel(unsigned char* out, size_t i,
3317- const LodePNGColorMode* mode,
3318- unsigned short r, unsigned short g, unsigned short b, unsigned short a)
3319-{
3320- if(mode->bitdepth != 16) return 85; /*must be 16 for this function*/
3321- if(mode->colortype == LCT_GREY)
3322- {
3323- unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3324- out[i * 2 + 0] = (grey >> 8) & 255;
3325- out[i * 2 + 1] = grey & 255;
3326- }
3327- else if(mode->colortype == LCT_RGB)
3328- {
3329- out[i * 6 + 0] = (r >> 8) & 255;
3330- out[i * 6 + 1] = r & 255;
3331- out[i * 6 + 2] = (g >> 8) & 255;
3332- out[i * 6 + 3] = g & 255;
3333- out[i * 6 + 4] = (b >> 8) & 255;
3334- out[i * 6 + 5] = b & 255;
3335- }
3336- else if(mode->colortype == LCT_GREY_ALPHA)
3337- {
3338- unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
3339- out[i * 4 + 0] = (grey >> 8) & 255;
3340- out[i * 4 + 1] = grey & 255;
3341- out[i * 4 + 2] = (a >> 8) & 255;
3342- out[i * 4 + 3] = a & 255;
3343- }
3344- else if(mode->colortype == LCT_RGBA)
3345- {
3346- out[i * 8 + 0] = (r >> 8) & 255;
3347- out[i * 8 + 1] = r & 255;
3348- out[i * 8 + 2] = (g >> 8) & 255;
3349- out[i * 8 + 3] = g & 255;
3350- out[i * 8 + 4] = (b >> 8) & 255;
3351- out[i * 8 + 5] = b & 255;
3352- out[i * 8 + 6] = (a >> 8) & 255;
3353- out[i * 8 + 7] = a & 255;
3354- }
3355-
3356- return 0; /*no error*/
3357-}
3358-
3359-/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
3360-static unsigned getPixelColorRGBA8(unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a,
3361- const unsigned char* in, size_t i, const LodePNGColorMode* mode)
3362-{
3363- if(mode->colortype == LCT_GREY)
3364- {
3365- if(mode->bitdepth == 8)
3366- {
3367- *r = *g = *b = in[i];
3368- if(mode->key_defined && *r == mode->key_r) *a = 0;
3369- else *a = 255;
3370- }
3371- else if(mode->bitdepth == 16)
3372- {
3373- *r = *g = *b = in[i * 2 + 0];
3374- if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3375- else *a = 255;
3376- }
3377- else
3378- {
3379- unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
3380- size_t j = i * mode->bitdepth;
3381- unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
3382- *r = *g = *b = (value * 255) / highest;
3383- if(mode->key_defined && value == mode->key_r) *a = 0;
3384- else *a = 255;
3385- }
3386- }
3387- else if(mode->colortype == LCT_RGB)
3388- {
3389- if(mode->bitdepth == 8)
3390- {
3391- *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
3392- if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
3393- else *a = 255;
3394- }
3395- else
3396- {
3397- *r = in[i * 6 + 0];
3398- *g = in[i * 6 + 2];
3399- *b = in[i * 6 + 4];
3400- if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3401- && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3402- && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3403- else *a = 255;
3404- }
3405- }
3406- else if(mode->colortype == LCT_PALETTE)
3407- {
3408- unsigned index;
3409- if(mode->bitdepth == 8) index = in[i];
3410- else
3411- {
3412- size_t j = i * mode->bitdepth;
3413- index = readBitsFromReversedStream(&j, in, mode->bitdepth);
3414- }
3415- if(index >= mode->palettesize) return 47; /*index out of palette*/
3416- *r = mode->palette[index * 4 + 0];
3417- *g = mode->palette[index * 4 + 1];
3418- *b = mode->palette[index * 4 + 2];
3419- *a = mode->palette[index * 4 + 3];
3420- }
3421- else if(mode->colortype == LCT_GREY_ALPHA)
3422- {
3423- if(mode->bitdepth == 8)
3424- {
3425- *r = *g = *b = in[i * 2 + 0];
3426- *a = in[i * 2 + 1];
3427- }
3428- else
3429- {
3430- *r = *g = *b = in[i * 4 + 0];
3431- *a = in[i * 4 + 2];
3432- }
3433- }
3434- else if(mode->colortype == LCT_RGBA)
3435- {
3436- if(mode->bitdepth == 8)
3437- {
3438- *r = in[i * 4 + 0]; *g = in[i * 4 + 1]; *b = in[i * 4 + 2]; *a = in[i * 4 + 3];
3439- }
3440- else
3441- {
3442- *r = in[i * 8 + 0]; *g = in[i * 8 + 2]; *b = in[i * 8 + 4]; *a = in[i * 8 + 6];
3443- }
3444- }
3445-
3446- return 0; /*no error*/
3447-}
3448-
3449-/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
3450-given color type, but the given color type must be 16-bit itself.*/
3451-static unsigned getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
3452- const unsigned char* in, size_t i, const LodePNGColorMode* mode)
3453-{
3454- if(mode->bitdepth != 16) return 85; /*error: this function only supports 16-bit input*/
3455-
3456- if(mode->colortype == LCT_GREY)
3457- {
3458- *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
3459- if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
3460- else *a = 65535;
3461- }
3462- else if(mode->colortype == LCT_RGB)
3463- {
3464- *r = 256 * in[i * 6 + 0] + in[i * 6 + 1];
3465- *g = 256 * in[i * 6 + 2] + in[i * 6 + 3];
3466- *b = 256 * in[i * 6 + 4] + in[i * 6 + 5];
3467- if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
3468- && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
3469- && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
3470- else *a = 65535;
3471- }
3472- else if(mode->colortype == LCT_GREY_ALPHA)
3473- {
3474- *r = *g = *b = 256 * in[i * 4 + 0] + in[i * 4 + 1];
3475- *a = 256 * in[i * 4 + 2] + in[i * 4 + 3];
3476- }
3477- else if(mode->colortype == LCT_RGBA)
3478- {
3479- *r = 256 * in[i * 8 + 0] + in[i * 8 + 1];
3480- *g = 256 * in[i * 8 + 2] + in[i * 8 + 3];
3481- *b = 256 * in[i * 8 + 4] + in[i * 8 + 5];
3482- *a = 256 * in[i * 8 + 6] + in[i * 8 + 7];
3483- }
3484- else return 85; /*error: this function only supports 16-bit input*/
3485-
3486- return 0; /*no error*/
3487-}
3488-
3489-/*
3490-converts from any color type to 24-bit or 32-bit (later maybe more supported). return value = LodePNG error code
3491-the out buffer must have (w * h * bpp + 7) / 8 bytes, where bpp is the bits per pixel of the output color type
3492-(lodepng_get_bpp) for < 8 bpp images, there may _not_ be padding bits at the end of scanlines.
3493-*/
3494-unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
3495- LodePNGColorMode* mode_out, LodePNGColorMode* mode_in,
3496- unsigned w, unsigned h)
3497-{
3498- unsigned error = 0;
3499- size_t i;
3500- ColorTree tree;
3501-
3502- if(lodepng_color_mode_equal(mode_out, mode_in))
3503- {
3504- size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
3505- for(i = 0; i < numbytes; i++) out[i] = in[i];
3506- return error;
3507- }
3508-
3509- if(mode_out->colortype == LCT_PALETTE)
3510- {
3511- size_t palsize = 1 << mode_out->bitdepth;
3512- if(mode_out->palettesize < palsize) palsize = mode_out->palettesize;
3513- color_tree_init(&tree, 1);
3514- for(i = 0; i < palsize; i++)
3515- {
3516- unsigned char* p = &mode_out->palette[i * 4];
3517- color_tree_add(&tree, p[0], p[1], p[2], p[3], i);
3518- }
3519- }
3520-
3521- if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16)
3522- {
3523- size_t numpixels = w * h;
3524- for(i = 0; i < numpixels; i++)
3525- {
3526- unsigned short r = 0, g = 0, b = 0, a = 0;
3527- error = getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
3528- if(error) return error;
3529- error = rgba16ToPixel(out, i, mode_out, r, g, b, a);
3530- if(error) return error;
3531- }
3532- }
3533- else
3534- {
3535- size_t numpixels = w * h;
3536- for(i = 0; i < numpixels; i++)
3537- {
3538- unsigned char r = 0, g = 0, b = 0, a = 0;
3539- error = getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
3540- if(error) return error;
3541- error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
3542- if(error) return error;
3543- }
3544- }
3545-
3546- if(mode_out->colortype == LCT_PALETTE)
3547- {
3548- color_tree_cleanup(&tree);
3549- }
3550-
3551- return error;
3552-}
3553-
3554-#ifdef LODEPNG_COMPILE_ENCODER
3555-
3556-typedef struct ColorProfile
3557-{
3558- unsigned char sixteenbit; /*needs more than 8 bits per channel*/
3559- unsigned char sixteenbit_done;
3560-
3561-
3562- unsigned char colored; /*not greyscale*/
3563- unsigned char colored_done;
3564-
3565- unsigned char key; /*a color key is required, or more*/
3566- unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/
3567- unsigned short key_g;
3568- unsigned short key_b;
3569- unsigned char alpha; /*alpha channel, or alpha palette, required*/
3570- unsigned char alpha_done;
3571-
3572- unsigned numcolors;
3573- ColorTree tree; /*for listing the counted colors, up to 256*/
3574- unsigned char* palette; /*size 1024. Remember up to the first 256 RGBA colors*/
3575- unsigned maxnumcolors; /*if more than that amount counted*/
3576- unsigned char numcolors_done;
3577-
3578- unsigned greybits; /*amount of bits required for greyscale (1, 2, 4, 8). Does not take 16 bit into account.*/
3579- unsigned char greybits_done;
3580-
3581-} ColorProfile;
3582-
3583-static void color_profile_init(ColorProfile* profile, LodePNGColorMode* mode)
3584-{
3585- profile->sixteenbit = 0;
3586- profile->sixteenbit_done = mode->bitdepth == 16 ? 0 : 1;
3587-
3588- profile->colored = 0;
3589- profile->colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0;
3590-
3591- profile->key = 0;
3592- profile->alpha = 0;
3593- profile->alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1;
3594-
3595- profile->numcolors = 0;
3596- color_tree_init(&profile->tree, 1);
3597- profile->palette = (unsigned char*)mymalloc(1024);
3598- profile->maxnumcolors = 257;
3599- if(lodepng_get_bpp(mode) <= 8)
3600- {
3601- int bpp = lodepng_get_bpp(mode);
3602- profile->maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256));
3603- }
3604- profile->numcolors_done = 0;
3605-
3606- profile->greybits = 1;
3607- profile->greybits_done = lodepng_get_bpp(mode) == 1 ? 1 : 0;
3608-}
3609-
3610-static void color_profile_cleanup(ColorProfile* profile)
3611-{
3612- color_tree_cleanup(&profile->tree);
3613- myfree(profile->palette);
3614-}
3615-
3616-/*function used for debug purposes with C++*/
3617-/*void printColorProfile(ColorProfile* p)
3618-{
3619- std::cout << "sixteenbit: " << (int)p->sixteenbit << std::endl;
3620- std::cout << "sixteenbit_done: " << (int)p->sixteenbit_done << std::endl;
3621- std::cout << "colored: " << (int)p->colored << std::endl;
3622- std::cout << "colored_done: " << (int)p->colored_done << std::endl;
3623- std::cout << "key: " << (int)p->key << std::endl;
3624- std::cout << "key_r: " << (int)p->key_r << std::endl;
3625- std::cout << "key_g: " << (int)p->key_g << std::endl;
3626- std::cout << "key_b: " << (int)p->key_b << std::endl;
3627- std::cout << "alpha: " << (int)p->alpha << std::endl;
3628- std::cout << "alpha_done: " << (int)p->alpha_done << std::endl;
3629- std::cout << "numcolors: " << (int)p->numcolors << std::endl;
3630- std::cout << "maxnumcolors: " << (int)p->maxnumcolors << std::endl;
3631- std::cout << "numcolors_done: " << (int)p->numcolors_done << std::endl;
3632- std::cout << "greybits: " << (int)p->greybits << std::endl;
3633- std::cout << "greybits_done: " << (int)p->greybits_done << std::endl;
3634-}*/
3635-
3636-/*Returns how many bits needed to represent given value (max 8 bit)*/
3637-unsigned getValueRequiredBits(unsigned char value)
3638-{
3639- if(value == 0 || value == 255) return 1;
3640- /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
3641- if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
3642- return 8;
3643-}
3644-
3645-/*profile must already have been inited with mode.
3646-It's ok to set some parameters of profile to done already.*/
3647-static unsigned get_color_profile(ColorProfile* profile,
3648- const unsigned char* in, size_t numpixels,
3649- LodePNGColorMode* mode)
3650-{
3651- unsigned error = 0;
3652- size_t i;
3653-
3654- if(mode->bitdepth == 16)
3655- {
3656- for(i = 0; i < numpixels; i++)
3657- {
3658- unsigned short r, g, b, a;
3659- error = getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
3660- if(error) break;
3661-
3662- /*a color is considered good for 8-bit if the first byte and the second byte are equal,
3663- (so if it's divisible through 257), NOT necessarily if the second byte is 0*/
3664- if(!profile->sixteenbit_done
3665- && (((r & 255) != ((r >> 8) & 255))
3666- || ((g & 255) != ((g >> 8) & 255))
3667- || ((b & 255) != ((b >> 8) & 255))))
3668- {
3669- profile->sixteenbit = 1;
3670- profile->sixteenbit_done = 1;
3671- profile->greybits_done = 1; /*greybits is not applicable anymore at 16-bit*/
3672- profile->numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
3673- }
3674-
3675- if(!profile->colored_done && (r != g || r != b))
3676- {
3677- profile->colored = 1;
3678- profile->colored_done = 1;
3679- profile->greybits_done = 1; /*greybits is not applicable anymore*/
3680- }
3681-
3682- if(!profile->alpha_done && a != 255)
3683- {
3684- if(a == 0 && !(profile->key && (r != profile->key_r || g != profile->key_g || b != profile->key_b)))
3685- {
3686- if(!profile->key)
3687- {
3688- profile->key = 1;
3689- profile->key_r = r;
3690- profile->key_g = g;
3691- profile->key_b = b;
3692- }
3693- }
3694- else
3695- {
3696- profile->alpha = 1;
3697- profile->alpha_done = 1;
3698- profile->greybits_done = 1; /*greybits is not applicable anymore*/
3699- }
3700- }
3701-
3702- if(!profile->greybits_done)
3703- {
3704- /*assuming 8-bit r, this test does not care about 16-bit*/
3705- unsigned bits = getValueRequiredBits(r);
3706- if(bits > profile->greybits) profile->greybits = bits;
3707- if(profile->greybits >= 8) profile->greybits_done = 1;
3708- }
3709-
3710- if(!profile->numcolors_done)
3711- {
3712- /*assuming 8-bit rgba, this test does not care about 16-bit*/
3713- if(!color_tree_has(&profile->tree, r, g, b, a))
3714- {
3715- color_tree_add(&profile->tree, r, g, b, a, profile->numcolors);
3716- if(profile->numcolors < 256)
3717- {
3718- unsigned char* p = profile->palette;
3719- unsigned i = profile->numcolors;
3720- p[i * 4 + 0] = r;
3721- p[i * 4 + 1] = g;
3722- p[i * 4 + 2] = b;
3723- p[i * 4 + 3] = a;
3724- }
3725- profile->numcolors++;
3726- if(profile->numcolors >= profile->maxnumcolors) profile->numcolors_done = 1;
3727- }
3728- }
3729-
3730- if(profile->alpha_done && profile->numcolors_done
3731- && profile->colored_done && profile->sixteenbit_done && profile->greybits_done)
3732- {
3733- break;
3734- }
3735- };
3736- }
3737- else
3738- {
3739- for(i = 0; i < numpixels; i++)
3740- {
3741- unsigned char r, g, b, a;
3742- error = getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode);
3743- if(error) break;
3744-
3745- if(!profile->colored_done && (r != g || r != b))
3746- {
3747- profile->colored = 1;
3748- profile->colored_done = 1;
3749- profile->greybits_done = 1; /*greybits is not applicable anymore*/
3750- }
3751-
3752- if(!profile->alpha_done && a != 255)
3753- {
3754- if(a == 0 && !(profile->key && (r != profile->key_r || g != profile->key_g || b != profile->key_b)))
3755- {
3756- if(!profile->key)
3757- {
3758- profile->key = 1;
3759- profile->key_r = r;
3760- profile->key_g = g;
3761- profile->key_b = b;
3762- }
3763- }
3764- else
3765- {
3766- profile->alpha = 1;
3767- profile->alpha_done = 1;
3768- profile->greybits_done = 1; /*greybits is not applicable anymore*/
3769- }
3770- }
3771-
3772- if(!profile->greybits_done)
3773- {
3774- unsigned bits = getValueRequiredBits(r);
3775- if(bits > profile->greybits) profile->greybits = bits;
3776- if(profile->greybits >= 8) profile->greybits_done = 1;
3777- }
3778-
3779- if(!profile->numcolors_done)
3780- {
3781- if(!color_tree_has(&profile->tree, r, g, b, a))
3782- {
3783-
3784- color_tree_add(&profile->tree, r, g, b, a, profile->numcolors);
3785- if(profile->numcolors < 256)
3786- {
3787- unsigned char* p = profile->palette;
3788- unsigned i = profile->numcolors;
3789- p[i * 4 + 0] = r;
3790- p[i * 4 + 1] = g;
3791- p[i * 4 + 2] = b;
3792- p[i * 4 + 3] = a;
3793- }
3794- profile->numcolors++;
3795- if(profile->numcolors >= profile->maxnumcolors) profile->numcolors_done = 1;
3796- }
3797- }
3798-
3799- if(profile->alpha_done && profile->numcolors_done && profile->colored_done && profile->greybits_done)
3800- {
3801- break;
3802- }
3803- };
3804- }
3805-
3806- /*make the profile's key always 16-bit for consistency*/
3807- if(mode->bitdepth < 16)
3808- {
3809- /*repeat each byte twice*/
3810- profile->key_r *= 257;
3811- profile->key_g *= 257;
3812- profile->key_b *= 257;
3813- }
3814-
3815- return error;
3816-}
3817-
3818-/*updates values of mode with a potentially smaller color model. mode_out should
3819-contain the user chosen color model, but will be overwritten with the new chosen one.*/
3820-static unsigned doAutoChooseColor(LodePNGColorMode* mode_out,
3821- const unsigned char* image, unsigned w, unsigned h, LodePNGColorMode* mode_in,
3822- LodePNGAutoConvert auto_convert)
3823-{
3824- ColorProfile profile;
3825- unsigned error = 0;
3826-
3827- if(auto_convert == LAC_ALPHA)
3828- {
3829- if(mode_out->colortype != LCT_RGBA && mode_out->colortype != LCT_GREY_ALPHA) return 0;
3830- }
3831-
3832- color_profile_init(&profile, mode_in);
3833- if(auto_convert == LAC_ALPHA)
3834- {
3835- profile.colored_done = 1;
3836- profile.greybits_done = 1;
3837- profile.numcolors_done = 1;
3838- profile.sixteenbit_done = 1;
3839- }
3840- error = get_color_profile(&profile, image, w * h, mode_in);
3841-
3842- if(!error && auto_convert == LAC_ALPHA)
3843- {
3844- if(!profile.alpha)
3845- {
3846- mode_out->colortype = (mode_out->colortype == LCT_RGBA ? LCT_RGB : LCT_GREY);
3847- }
3848- }
3849- else if(!error && auto_convert != LAC_ALPHA)
3850- {
3851- mode_out->key_defined = 0;
3852-
3853- if(profile.sixteenbit)
3854- {
3855- mode_out->bitdepth = 16;
3856- if(profile.alpha)
3857- {
3858- mode_out->colortype = profile.colored ? LCT_RGBA : LCT_GREY_ALPHA;
3859- }
3860- else
3861- {
3862- mode_out->colortype = profile.colored ? LCT_RGB : LCT_GREY;
3863- if(profile.key)
3864- {
3865- mode_out->key_defined = 1;
3866- mode_out->key_r = profile.key_r;
3867- mode_out->key_g = profile.key_g;
3868- mode_out->key_b = profile.key_b;
3869- }
3870- }
3871- }
3872- else /*less than 16 bits per channel*/
3873- {
3874- /*don't add palette overhead if image hasn't got a lot of pixels*/
3875- unsigned n = profile.numcolors;
3876- int palette_ok = n <= 256 && (n * 2 < w * h);
3877- unsigned palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
3878- int grey_ok = !profile.colored && !profile.alpha; /*grey without alpha, with potentially low bits*/
3879- if(palette_ok || grey_ok)
3880- {
3881- if(!palette_ok || (grey_ok && profile.greybits <= palettebits))
3882- {
3883- mode_out->colortype = LCT_GREY;
3884- mode_out->bitdepth = profile.greybits;
3885- if(profile.key)
3886- {
3887- unsigned keyval = profile.key_r;
3888- keyval &= (profile.greybits - 1); /*same subgroup of bits repeated, so taking right bits is fine*/
3889- mode_out->key_defined = 1;
3890- mode_out->key_r = keyval;
3891- mode_out->key_g = keyval;
3892- mode_out->key_b = keyval;
3893- }
3894- }
3895- else
3896- {
3897- /*fill in the palette*/
3898- unsigned i;
3899- unsigned char* p = profile.palette;
3900- for(i = 0; i < profile.numcolors; i++)
3901- {
3902- error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
3903- if(error) break;
3904- }
3905-
3906- mode_out->colortype = LCT_PALETTE;
3907- mode_out->bitdepth = palettebits;
3908- }
3909- }
3910- else /*8-bit per channel*/
3911- {
3912- mode_out->bitdepth = 8;
3913- if(profile.alpha)
3914- {
3915- mode_out->colortype = profile.colored ? LCT_RGBA : LCT_GREY_ALPHA;
3916- }
3917- else
3918- {
3919- mode_out->colortype = profile.colored ? LCT_RGB : LCT_GREY /*LCT_GREY normally won't occur, already done earlier*/;
3920- if(profile.key)
3921- {
3922- mode_out->key_defined = 1;
3923- mode_out->key_r = profile.key_r % 256;
3924- mode_out->key_g = profile.key_g % 256;
3925- mode_out->key_b = profile.key_b % 256;
3926- }
3927- }
3928- }
3929- }
3930- }
3931-
3932- color_profile_cleanup(&profile);
3933-
3934- if(mode_in->colortype == LCT_PALETTE && mode_out->colortype == LCT_PALETTE
3935- && mode_in->palettesize == mode_out->palettesize) {
3936- /*In this case keep the palette order of the input, so that the user can choose an optimal one*/
3937- size_t i;
3938- for(i = 0; i < mode_in->palettesize * 4; i++)
3939- {
3940- mode_out->palette[i] = mode_in->palette[i];
3941- }
3942- }
3943-
3944- if(auto_convert == LAC_AUTO_NO_NIBBLES && mode_out->bitdepth < 8)
3945- {
3946- /*palette can keep its small amount of colors, as long as no indices use it*/
3947- mode_out->bitdepth = 8;
3948- }
3949-
3950- return error;
3951-}
3952-
3953-#endif /* #ifdef LODEPNG_COMPILE_ENCODER */
3954-
3955-/*
3956-Paeth predicter, used by PNG filter type 4
3957-The parameters are of type short, but should come from unsigned chars, the shorts
3958-are only needed to make the paeth calculation correct.
3959-*/
3960-static unsigned char paethPredictor(short a, short b, short c)
3961-{
3962- short pa = abs(b - c);
3963- short pb = abs(a - c);
3964- short pc = abs(a + b - c - c);
3965-
3966- /*short pc = a + b - c;
3967- short pa = abs(pc - a);
3968- short pb = abs(pc - b);
3969- pc = abs(pc - c);*/
3970-
3971- if(pa <= pb && pa <= pc) return (unsigned char)a;
3972- else if(pb <= pc) return (unsigned char)b;
3973- else return (unsigned char)c;
3974-}
3975-
3976-/*shared values used by multiple Adam7 related functions*/
3977-
3978-static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
3979-static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
3980-static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
3981-static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
3982-
3983-static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
3984- size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp)
3985-{
3986- /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
3987- unsigned i;
3988-
3989- /*calculate width and height in pixels of each pass*/
3990- for(i = 0; i < 7; i++)
3991- {
3992- passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
3993- passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
3994- if(passw[i] == 0) passh[i] = 0;
3995- if(passh[i] == 0) passw[i] = 0;
3996- }
3997-
3998- filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
3999- for(i = 0; i < 7; i++)
4000- {
4001- /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
4002- filter_passstart[i + 1] = filter_passstart[i]
4003- + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0);
4004- /*bits padded if needed to fill full byte at end of each scanline*/
4005- padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8);
4006- /*only padded at end of reduced image*/
4007- passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8;
4008- }
4009-}
4010-
4011-#ifdef LODEPNG_COMPILE_DECODER
4012-
4013-/* ////////////////////////////////////////////////////////////////////////// */
4014-/* / PNG Decoder / */
4015-/* ////////////////////////////////////////////////////////////////////////// */
4016-
4017-/*read the information from the header and store it in the LodePNGInfo. return value is error*/
4018-unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
4019- const unsigned char* in, size_t insize)
4020-{
4021- LodePNGInfo* info = &state->info_png;
4022- if(insize == 0 || in == 0)
4023- {
4024- CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
4025- }
4026- if(insize < 29)
4027- {
4028- CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
4029- }
4030-
4031- /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
4032- lodepng_info_cleanup(info);
4033- lodepng_info_init(info);
4034-
4035- if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
4036- || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10)
4037- {
4038- CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
4039- }
4040- if(in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R')
4041- {
4042- CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
4043- }
4044-
4045- /*read the values given in the header*/
4046- *w = lodepng_read32bitInt(&in[16]);
4047- *h = lodepng_read32bitInt(&in[20]);
4048- info->color.bitdepth = in[24];
4049- info->color.colortype = (LodePNGColorType)in[25];
4050- info->compression_method = in[26];
4051- info->filter_method = in[27];
4052- info->interlace_method = in[28];
4053-
4054- if(!state->decoder.ignore_crc)
4055- {
4056- unsigned CRC = lodepng_read32bitInt(&in[29]);
4057- unsigned checksum = lodepng_crc32(&in[12], 17);
4058- if(CRC != checksum)
4059- {
4060- CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
4061- }
4062- }
4063-
4064- /*error: only compression method 0 is allowed in the specification*/
4065- if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
4066- /*error: only filter method 0 is allowed in the specification*/
4067- if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
4068- /*error: only interlace methods 0 and 1 exist in the specification*/
4069- if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
4070-
4071- state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
4072- return state->error;
4073-}
4074-
4075-static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
4076- size_t bytewidth, unsigned char filterType, size_t length)
4077-{
4078- /*
4079- For PNG filter method 0
4080- unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
4081- the filter works byte per byte (bytewidth = 1)
4082- precon is the previous unfiltered scanline, recon the result, scanline the current one
4083- the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
4084- recon and scanline MAY be the same memory address! precon must be disjoint.
4085- */
4086-
4087- size_t i;
4088- switch(filterType)
4089- {
4090- case 0:
4091- for(i = 0; i < length; i++) recon[i] = scanline[i];
4092- break;
4093- case 1:
4094- for(i = 0; i < bytewidth; i++) recon[i] = scanline[i];
4095- for(i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth];
4096- break;
4097- case 2:
4098- if(precon)
4099- {
4100- for(i = 0; i < length; i++) recon[i] = scanline[i] + precon[i];
4101- }
4102- else
4103- {
4104- for(i = 0; i < length; i++) recon[i] = scanline[i];
4105- }
4106- break;
4107- case 3:
4108- if(precon)
4109- {
4110- for(i = 0; i < bytewidth; i++) recon[i] = scanline[i] + precon[i] / 2;
4111- for(i = bytewidth; i < length; i++) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2);
4112- }
4113- else
4114- {
4115- for(i = 0; i < bytewidth; i++) recon[i] = scanline[i];
4116- for(i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth] / 2;
4117- }
4118- break;
4119- case 4:
4120- if(precon)
4121- {
4122- for(i = 0; i < bytewidth; i++)
4123- {
4124- recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
4125- }
4126- for(i = bytewidth; i < length; i++)
4127- {
4128- recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
4129- }
4130- }
4131- else
4132- {
4133- for(i = 0; i < bytewidth; i++)
4134- {
4135- recon[i] = scanline[i];
4136- }
4137- for(i = bytewidth; i < length; i++)
4138- {
4139- /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
4140- recon[i] = (scanline[i] + recon[i - bytewidth]);
4141- }
4142- }
4143- break;
4144- default: return 36; /*error: unexisting filter type given*/
4145- }
4146- return 0;
4147-}
4148-
4149-static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
4150-{
4151- /*
4152- For PNG filter method 0
4153- this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
4154- out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
4155- w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
4156- in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
4157- */
4158-
4159- unsigned y;
4160- unsigned char* prevline = 0;
4161-
4162- /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
4163- size_t bytewidth = (bpp + 7) / 8;
4164- size_t linebytes = (w * bpp + 7) / 8;
4165-
4166- for(y = 0; y < h; y++)
4167- {
4168- size_t outindex = linebytes * y;
4169- size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
4170- unsigned char filterType = in[inindex];
4171-
4172- CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
4173-
4174- prevline = &out[outindex];
4175- }
4176-
4177- return 0;
4178-}
4179-
4180-static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
4181-{
4182- /*Note: this function works on image buffers WITHOUT padding bits at end of scanlines
4183- with non-multiple-of-8 bit amounts, only between reduced images is padding
4184- out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
4185- (because that's likely a little bit faster)*/
4186- unsigned passw[7], passh[7];
4187- size_t filter_passstart[8], padded_passstart[8], passstart[8];
4188- unsigned i;
4189-
4190- Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4191-
4192- if(bpp >= 8)
4193- {
4194- for(i = 0; i < 7; i++)
4195- {
4196- unsigned x, y, b;
4197- size_t bytewidth = bpp / 8;
4198- for(y = 0; y < passh[i]; y++)
4199- for(x = 0; x < passw[i]; x++)
4200- {
4201- size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
4202- size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
4203- for(b = 0; b < bytewidth; b++)
4204- {
4205- out[pixeloutstart + b] = in[pixelinstart + b];
4206- }
4207- }
4208- }
4209- }
4210- else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
4211- {
4212- for(i = 0; i < 7; i++)
4213- {
4214- unsigned x, y, b;
4215- unsigned ilinebits = bpp * passw[i];
4216- unsigned olinebits = bpp * w;
4217- size_t obp, ibp; /*bit pointers (for out and in buffer)*/
4218- for(y = 0; y < passh[i]; y++)
4219- for(x = 0; x < passw[i]; x++)
4220- {
4221- ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
4222- obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
4223- for(b = 0; b < bpp; b++)
4224- {
4225- unsigned char bit = readBitFromReversedStream(&ibp, in);
4226- /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
4227- setBitOfReversedStream0(&obp, out, bit);
4228- }
4229- }
4230- }
4231- }
4232-}
4233-
4234-static void removePaddingBits(unsigned char* out, const unsigned char* in,
4235- size_t olinebits, size_t ilinebits, unsigned h)
4236-{
4237- /*
4238- After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
4239- to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
4240- for the Adam7 code, the color convert code and the output to the user.
4241- in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
4242- have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
4243- also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
4244- only useful if (ilinebits - olinebits) is a value in the range 1..7
4245- */
4246- unsigned y;
4247- size_t diff = ilinebits - olinebits;
4248- size_t ibp = 0, obp = 0; /*input and output bit pointers*/
4249- for(y = 0; y < h; y++)
4250- {
4251- size_t x;
4252- for(x = 0; x < olinebits; x++)
4253- {
4254- unsigned char bit = readBitFromReversedStream(&ibp, in);
4255- setBitOfReversedStream(&obp, out, bit);
4256- }
4257- ibp += diff;
4258- }
4259-}
4260-
4261-/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
4262-the IDAT chunks (with filter index bytes and possible padding bits)
4263-return value is error*/
4264-static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
4265- unsigned w, unsigned h, const LodePNGInfo* info_png)
4266-{
4267- /*
4268- This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
4269- Steps:
4270- *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
4271- *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
4272- NOTE: the in buffer will be overwritten with intermediate data!
4273- */
4274- unsigned bpp = lodepng_get_bpp(&info_png->color);
4275- if(bpp == 0) return 31; /*error: invalid colortype*/
4276-
4277- if(info_png->interlace_method == 0)
4278- {
4279- if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
4280- {
4281- CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
4282- removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h);
4283- }
4284- /*we can immediatly filter into the out buffer, no other steps needed*/
4285- else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
4286- }
4287- else /*interlace_method is 1 (Adam7)*/
4288- {
4289- unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
4290- unsigned i;
4291-
4292- Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
4293-
4294- for(i = 0; i < 7; i++)
4295- {
4296- CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
4297- if(bpp < 8)
4298- {
4299- /*remove padding bits in scanlines; after this there still may be padding
4300- bits between the different reduced images: each reduced image still starts nicely at a byte*/
4301- removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
4302- ((passw[i] * bpp + 7) / 8) * 8, passh[i]);
4303- }
4304- }
4305-
4306- Adam7_deinterlace(out, in, w, h, bpp);
4307- }
4308-
4309- return 0;
4310-}
4311-
4312-/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
4313-static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
4314- LodePNGState* state,
4315- const unsigned char* in, size_t insize)
4316-{
4317- unsigned char IEND = 0;
4318- const unsigned char* chunk;
4319- size_t i;
4320- ucvector idat; /*the data from idat chunks*/
4321-
4322- /*for unknown chunk order*/
4323- unsigned unknown = 0;
4324-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4325- unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
4326-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4327-
4328- /*provide some proper output values if error will happen*/
4329- *out = 0;
4330-
4331- state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
4332- if(state->error) return;
4333-
4334- ucvector_init(&idat);
4335- chunk = &in[33]; /*first byte of the first chunk after the header*/
4336-
4337- /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
4338- IDAT data is put at the start of the in buffer*/
4339- while(!IEND && !state->error)
4340- {
4341- unsigned chunkLength;
4342- const unsigned char* data; /*the data in the chunk*/
4343-
4344- /*error: size of the in buffer too small to contain next chunk*/
4345- if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30);
4346-
4347- /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
4348- chunkLength = lodepng_chunk_length(chunk);
4349- /*error: chunk length larger than the max PNG chunk size*/
4350- if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63);
4351-
4352- if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in)
4353- {
4354- CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
4355- }
4356-
4357- data = lodepng_chunk_data_const(chunk);
4358-
4359- /*IDAT chunk, containing compressed image data*/
4360- if(lodepng_chunk_type_equals(chunk, "IDAT"))
4361- {
4362- size_t oldsize = idat.size;
4363- if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
4364- for(i = 0; i < chunkLength; i++) idat.data[oldsize + i] = data[i];
4365-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4366- critical_pos = 3;
4367-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4368- }
4369- /*IEND chunk*/
4370- else if(lodepng_chunk_type_equals(chunk, "IEND"))
4371- {
4372- IEND = 1;
4373- }
4374- /*palette chunk (PLTE)*/
4375- else if(lodepng_chunk_type_equals(chunk, "PLTE"))
4376- {
4377- unsigned pos = 0;
4378- if(state->info_png.color.palette) myfree(state->info_png.color.palette);
4379- state->info_png.color.palettesize = chunkLength / 3;
4380- state->info_png.color.palette = (unsigned char*)mymalloc(4 * state->info_png.color.palettesize);
4381- if(!state->info_png.color.palette && state->info_png.color.palettesize)
4382- {
4383- state->info_png.color.palettesize = 0;
4384- CERROR_BREAK(state->error, 83); /*alloc fail*/
4385- }
4386- if(state->info_png.color.palettesize > 256) CERROR_BREAK(state->error, 38); /*error: palette too big*/
4387-
4388- for(i = 0; i < state->info_png.color.palettesize; i++)
4389- {
4390- state->info_png.color.palette[4 * i + 0] = data[pos++]; /*R*/
4391- state->info_png.color.palette[4 * i + 1] = data[pos++]; /*G*/
4392- state->info_png.color.palette[4 * i + 2] = data[pos++]; /*B*/
4393- state->info_png.color.palette[4 * i + 3] = 255; /*alpha*/
4394- }
4395-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4396- critical_pos = 2;
4397-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4398- }
4399- /*palette transparency chunk (tRNS)*/
4400- else if(lodepng_chunk_type_equals(chunk, "tRNS"))
4401- {
4402- if(state->info_png.color.colortype == LCT_PALETTE)
4403- {
4404- /*error: more alpha values given than there are palette entries*/
4405- if(chunkLength > state->info_png.color.palettesize) CERROR_BREAK(state->error, 38);
4406-
4407- for(i = 0; i < chunkLength; i++) state->info_png.color.palette[4 * i + 3] = data[i];
4408- }
4409- else if(state->info_png.color.colortype == LCT_GREY)
4410- {
4411- /*error: this chunk must be 2 bytes for greyscale image*/
4412- if(chunkLength != 2) CERROR_BREAK(state->error, 30);
4413-
4414- state->info_png.color.key_defined = 1;
4415- state->info_png.color.key_r = state->info_png.color.key_g
4416- = state->info_png.color.key_b = 256 * data[0] + data[1];
4417- }
4418- else if(state->info_png.color.colortype == LCT_RGB)
4419- {
4420- /*error: this chunk must be 6 bytes for RGB image*/
4421- if(chunkLength != 6) CERROR_BREAK(state->error, 41);
4422-
4423- state->info_png.color.key_defined = 1;
4424- state->info_png.color.key_r = 256 * data[0] + data[1];
4425- state->info_png.color.key_g = 256 * data[2] + data[3];
4426- state->info_png.color.key_b = 256 * data[4] + data[5];
4427- }
4428- else CERROR_BREAK(state->error, 42); /*error: tRNS chunk not allowed for other color models*/
4429- }
4430-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4431- /*background color chunk (bKGD)*/
4432- else if(lodepng_chunk_type_equals(chunk, "bKGD"))
4433- {
4434- if(state->info_png.color.colortype == LCT_PALETTE)
4435- {
4436- /*error: this chunk must be 1 byte for indexed color image*/
4437- if(chunkLength != 1) CERROR_BREAK(state->error, 43);
4438-
4439- state->info_png.background_defined = 1;
4440- state->info_png.background_r = state->info_png.background_g = state->info_png.background_b = data[0];
4441- }
4442- else if(state->info_png.color.colortype == LCT_GREY || state->info_png.color.colortype == LCT_GREY_ALPHA)
4443- {
4444- /*error: this chunk must be 2 bytes for greyscale image*/
4445- if(chunkLength != 2) CERROR_BREAK(state->error, 44);
4446-
4447- state->info_png.background_defined = 1;
4448- state->info_png.background_r = state->info_png.background_g = state->info_png.background_b
4449- = 256 * data[0] + data[1];
4450- }
4451- else if(state->info_png.color.colortype == LCT_RGB || state->info_png.color.colortype == LCT_RGBA)
4452- {
4453- /*error: this chunk must be 6 bytes for greyscale image*/
4454- if(chunkLength != 6) CERROR_BREAK(state->error, 45);
4455-
4456- state->info_png.background_defined = 1;
4457- state->info_png.background_r = 256 * data[0] + data[1];
4458- state->info_png.background_g = 256 * data[2] + data[3];
4459- state->info_png.background_b = 256 * data[4] + data[5];
4460- }
4461- }
4462- /*text chunk (tEXt)*/
4463- else if(lodepng_chunk_type_equals(chunk, "tEXt"))
4464- {
4465- if(state->decoder.read_text_chunks)
4466- {
4467- char *key = 0, *str = 0;
4468-
4469- while(!state->error) /*not really a while loop, only used to break on error*/
4470- {
4471- unsigned length, string2_begin;
4472-
4473- length = 0;
4474- while(length < chunkLength && data[length] != 0) length++;
4475- /*error, end reached, no null terminator?*/
4476- if(length + 1 >= chunkLength) CERROR_BREAK(state->error, 75);
4477-
4478- key = (char*)mymalloc(length + 1);
4479- if(!key) CERROR_BREAK(state->error, 83); /*alloc fail*/
4480-
4481- key[length] = 0;
4482- for(i = 0; i < length; i++) key[i] = data[i];
4483-
4484- string2_begin = length + 1;
4485- /*error, end reached, no null terminator?*/
4486- if(string2_begin > chunkLength) CERROR_BREAK(state->error, 75);
4487-
4488- length = chunkLength - string2_begin;
4489- str = (char*)mymalloc(length + 1);
4490- if(!str) CERROR_BREAK(state->error, 83); /*alloc fail*/
4491-
4492- str[length] = 0;
4493- for(i = 0; i < length; i++) str[i] = data[string2_begin + i];
4494-
4495- state->error = lodepng_add_text(&state->info_png, key, str);
4496-
4497- break;
4498- }
4499-
4500- myfree(key);
4501- myfree(str);
4502- }
4503- }
4504- /*compressed text chunk (zTXt)*/
4505- else if(lodepng_chunk_type_equals(chunk, "zTXt"))
4506- {
4507- if(state->decoder.read_text_chunks)
4508- {
4509- unsigned length, string2_begin;
4510- char *key = 0;
4511- ucvector decoded;
4512-
4513- ucvector_init(&decoded);
4514-
4515- while(!state->error) /*not really a while loop, only used to break on error*/
4516- {
4517- for(length = 0; length < chunkLength && data[length] != 0; length++) ;
4518- if(length + 2 >= chunkLength) CERROR_BREAK(state->error, 75); /*no null termination, corrupt?*/
4519-
4520- key = (char*)mymalloc(length + 1);
4521- if(!key) CERROR_BREAK(state->error, 83); /*alloc fail*/
4522-
4523- key[length] = 0;
4524- for(i = 0; i < length; i++) key[i] = data[i];
4525-
4526- if(data[length + 1] != 0) CERROR_BREAK(state->error, 72); /*the 0 byte indicating compression must be 0*/
4527-
4528- string2_begin = length + 2;
4529- if(string2_begin > chunkLength) CERROR_BREAK(state->error, 75); /*no null termination, corrupt?*/
4530-
4531- length = chunkLength - string2_begin;
4532- state->error = lodepng_zlib_decompress(&decoded.data, &decoded.size,
4533- (unsigned char*)(&data[string2_begin]),
4534- length, &state->decoder.zlibsettings);
4535- if(state->error) break;
4536- ucvector_push_back(&decoded, 0);
4537-
4538- state->error = lodepng_add_text(&state->info_png, key, (char*)decoded.data);
4539-
4540- break;
4541- }
4542-
4543- myfree(key);
4544- ucvector_cleanup(&decoded);
4545- if(state->error) break;
4546- }
4547- }
4548- /*international text chunk (iTXt)*/
4549- else if(lodepng_chunk_type_equals(chunk, "iTXt"))
4550- {
4551- if(state->decoder.read_text_chunks)
4552- {
4553- unsigned length, begin, compressed;
4554- char *key = 0, *langtag = 0, *transkey = 0;
4555- ucvector decoded;
4556- ucvector_init(&decoded);
4557-
4558- while(!state->error) /*not really a while loop, only used to break on error*/
4559- {
4560- /*Quick check if the chunk length isn't too small. Even without check
4561- it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
4562- if(chunkLength < 5) CERROR_BREAK(state->error, 30); /*iTXt chunk too short*/
4563-
4564- /*read the key*/
4565- for(length = 0; length < chunkLength && data[length] != 0; length++) ;
4566- if(length + 2 >= chunkLength) CERROR_BREAK(state->error, 75); /*no null termination char found*/
4567-
4568- key = (char*)mymalloc(length + 1);
4569- if(!key) CERROR_BREAK(state->error, 83); /*alloc fail*/
4570-
4571- key[length] = 0;
4572- for(i = 0; i < length; i++) key[i] = data[i];
4573-
4574- /*read the compression method*/
4575- compressed = data[length + 1];
4576- if(data[length + 2] != 0) CERROR_BREAK(state->error, 72); /*the 0 byte indicating compression must be 0*/
4577-
4578- /*read the langtag*/
4579- begin = length + 3;
4580- length = 0;
4581- for(i = begin; i < chunkLength && data[i] != 0; i++) length++;
4582- if(begin + length + 1 >= chunkLength) CERROR_BREAK(state->error, 75); /*no null termination char found*/
4583-
4584- langtag = (char*)mymalloc(length + 1);
4585- if(!langtag) CERROR_BREAK(state->error, 83); /*alloc fail*/
4586-
4587- langtag[length] = 0;
4588- for(i = 0; i < length; i++) langtag[i] = data[begin + i];
4589-
4590- /*read the transkey*/
4591- begin += length + 1;
4592- length = 0;
4593- for(i = begin; i < chunkLength && data[i] != 0; i++) length++;
4594- if(begin + length + 1 >= chunkLength) CERROR_BREAK(state->error, 75); /*no null termination, corrupt?*/
4595-
4596- transkey = (char*)mymalloc(length + 1);
4597- if(!transkey) CERROR_BREAK(state->error, 83); /*alloc fail*/
4598-
4599- transkey[length] = 0;
4600- for(i = 0; i < length; i++) transkey[i] = data[begin + i];
4601-
4602- /*read the actual text*/
4603- begin += length + 1;
4604- if(begin > chunkLength) CERROR_BREAK(state->error, 75); /*no null termination, corrupt?*/
4605-
4606- length = chunkLength - begin;
4607-
4608- if(compressed)
4609- {
4610- state->error = lodepng_zlib_decompress(&decoded.data, &decoded.size,
4611- (unsigned char*)(&data[begin]),
4612- length, &state->decoder.zlibsettings);
4613- if(state->error) break;
4614- if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
4615- ucvector_push_back(&decoded, 0);
4616- }
4617- else
4618- {
4619- if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
4620-
4621- decoded.data[length] = 0;
4622- for(i = 0; i < length; i++) decoded.data[i] = data[begin + i];
4623- }
4624-
4625- state->error = lodepng_add_itext(&state->info_png, key, langtag, transkey, (char*)decoded.data);
4626-
4627- break;
4628- }
4629-
4630- myfree(key);
4631- myfree(langtag);
4632- myfree(transkey);
4633- ucvector_cleanup(&decoded);
4634- if(state->error) break;
4635- }
4636- }
4637- else if(lodepng_chunk_type_equals(chunk, "tIME"))
4638- {
4639- if(chunkLength != 7) CERROR_BREAK(state->error, 73); /*invalid tIME chunk size*/
4640-
4641- state->info_png.time_defined = 1;
4642- state->info_png.time.year = 256 * data[0] + data[+ 1];
4643- state->info_png.time.month = data[2];
4644- state->info_png.time.day = data[3];
4645- state->info_png.time.hour = data[4];
4646- state->info_png.time.minute = data[5];
4647- state->info_png.time.second = data[6];
4648- }
4649- else if(lodepng_chunk_type_equals(chunk, "pHYs"))
4650- {
4651- if(chunkLength != 9) CERROR_BREAK(state->error, 74); /*invalid pHYs chunk size*/
4652-
4653- state->info_png.phys_defined = 1;
4654- state->info_png.phys_x = 16777216 * data[0] + 65536 * data[1] + 256 * data[2] + data[3];
4655- state->info_png.phys_y = 16777216 * data[4] + 65536 * data[5] + 256 * data[6] + data[7];
4656- state->info_png.phys_unit = data[8];
4657- }
4658-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4659- else /*it's not an implemented chunk type, so ignore it: skip over the data*/
4660- {
4661- /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
4662- if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69);
4663-
4664- unknown = 1;
4665-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4666- if(state->decoder.remember_unknown_chunks)
4667- {
4668- state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
4669- &state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
4670- if(state->error) break;
4671- }
4672-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4673- }
4674-
4675- if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/
4676- {
4677- if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
4678- }
4679-
4680- if(!IEND) chunk = lodepng_chunk_next_const(chunk);
4681- }
4682-
4683- if(!state->error)
4684- {
4685- ucvector scanlines;
4686- ucvector_init(&scanlines);
4687-
4688- /*maximum final image length is already reserved in the vector's length - this is not really necessary*/
4689- if(!ucvector_resize(&scanlines, lodepng_get_raw_size(*w, *h, &state->info_png.color) + *h))
4690- {
4691- state->error = 83; /*alloc fail*/
4692- }
4693- if(!state->error)
4694- {
4695- /*decompress with the Zlib decompressor*/
4696- state->error = lodepng_zlib_decompress(&scanlines.data, &scanlines.size, idat.data,
4697- idat.size, &state->decoder.zlibsettings);
4698- }
4699-
4700- if(!state->error)
4701- {
4702- ucvector outv;
4703- ucvector_init(&outv);
4704- if(!ucvector_resizev(&outv,
4705- lodepng_get_raw_size(*w, *h, &state->info_png.color), 0)) state->error = 83; /*alloc fail*/
4706- if(!state->error) state->error = postProcessScanlines(outv.data, scanlines.data, *w, *h, &state->info_png);
4707- *out = outv.data;
4708- }
4709- ucvector_cleanup(&scanlines);
4710- }
4711-
4712- ucvector_cleanup(&idat);
4713-}
4714-
4715-unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
4716- LodePNGState* state,
4717- const unsigned char* in, size_t insize)
4718-{
4719- *out = 0;
4720- decodeGeneric(out, w, h, state, in, insize);
4721- if(state->error) return state->error;
4722- if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color))
4723- {
4724- /*same color type, no copying or converting of data needed*/
4725- /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
4726- the raw image has to the end user*/
4727- if(!state->decoder.color_convert)
4728- {
4729- state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
4730- if(state->error) return state->error;
4731- }
4732- }
4733- else
4734- {
4735- /*color conversion needed; sort of copy of the data*/
4736- unsigned char* data = *out;
4737- size_t outsize;
4738-
4739- if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
4740- && !(state->info_raw.bitdepth == 8))
4741- {
4742- return 56; /*unsupported color mode conversion*/
4743- }
4744-
4745- outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
4746- *out = (unsigned char*)mymalloc(outsize);
4747- if(!(*out))
4748- {
4749- state->error = 83; /*alloc fail*/
4750- }
4751- else state->error = lodepng_convert(*out, data, &state->info_raw, &state->info_png.color, *w, *h);
4752- myfree(data);
4753- }
4754- return state->error;
4755-}
4756-
4757-unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
4758- size_t insize, LodePNGColorType colortype, unsigned bitdepth)
4759-{
4760- unsigned error;
4761- LodePNGState state;
4762- lodepng_state_init(&state);
4763- state.info_raw.colortype = colortype;
4764- state.info_raw.bitdepth = bitdepth;
4765- error = lodepng_decode(out, w, h, &state, in, insize);
4766- lodepng_state_cleanup(&state);
4767- return error;
4768-}
4769-
4770-unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4771-{
4772- return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
4773-}
4774-
4775-unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
4776-{
4777- return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
4778-}
4779-
4780-#ifdef LODEPNG_COMPILE_DISK
4781-unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
4782- LodePNGColorType colortype, unsigned bitdepth)
4783-{
4784- unsigned char* buffer;
4785- size_t buffersize;
4786- unsigned error;
4787- error = lodepng_load_file(&buffer, &buffersize, filename);
4788- if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
4789- myfree(buffer);
4790- return error;
4791-}
4792-
4793-unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4794-{
4795- return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
4796-}
4797-
4798-unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
4799-{
4800- return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
4801-}
4802-#endif /*LODEPNG_COMPILE_DISK*/
4803-
4804-void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings)
4805-{
4806- settings->color_convert = 1;
4807-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4808- settings->read_text_chunks = 1;
4809- settings->remember_unknown_chunks = 0;
4810-#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
4811- settings->ignore_crc = 0;
4812- lodepng_decompress_settings_init(&settings->zlibsettings);
4813-}
4814-
4815-#endif /*LODEPNG_COMPILE_DECODER*/
4816-
4817-#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
4818-
4819-void lodepng_state_init(LodePNGState* state)
4820-{
4821-#ifdef LODEPNG_COMPILE_DECODER
4822- lodepng_decoder_settings_init(&state->decoder);
4823-#endif /*LODEPNG_COMPILE_DECODER*/
4824-#ifdef LODEPNG_COMPILE_ENCODER
4825- lodepng_encoder_settings_init(&state->encoder);
4826-#endif /*LODEPNG_COMPILE_ENCODER*/
4827- lodepng_color_mode_init(&state->info_raw);
4828- lodepng_info_init(&state->info_png);
4829- state->error = 1;
4830-}
4831-
4832-void lodepng_state_cleanup(LodePNGState* state)
4833-{
4834- lodepng_color_mode_cleanup(&state->info_raw);
4835- lodepng_info_cleanup(&state->info_png);
4836-}
4837-
4838-void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source)
4839-{
4840- lodepng_state_cleanup(dest);
4841- *dest = *source;
4842- lodepng_color_mode_init(&dest->info_raw);
4843- lodepng_info_init(&dest->info_png);
4844- dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
4845- dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
4846-}
4847-
4848-#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
4849-
4850-#ifdef LODEPNG_COMPILE_ENCODER
4851-
4852-/* ////////////////////////////////////////////////////////////////////////// */
4853-/* / PNG Encoder / */
4854-/* ////////////////////////////////////////////////////////////////////////// */
4855-
4856-/*chunkName must be string of 4 characters*/
4857-static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length)
4858-{
4859- CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data));
4860- out->allocsize = out->size; /*fix the allocsize again*/
4861- return 0;
4862-}
4863-
4864-static void writeSignature(ucvector* out)
4865-{
4866- /*8 bytes PNG signature, aka the magic bytes*/
4867- ucvector_push_back(out, 137);
4868- ucvector_push_back(out, 80);
4869- ucvector_push_back(out, 78);
4870- ucvector_push_back(out, 71);
4871- ucvector_push_back(out, 13);
4872- ucvector_push_back(out, 10);
4873- ucvector_push_back(out, 26);
4874- ucvector_push_back(out, 10);
4875-}
4876-
4877-static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
4878- LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method)
4879-{
4880- unsigned error = 0;
4881- ucvector header;
4882- ucvector_init(&header);
4883-
4884- lodepng_add32bitInt(&header, w); /*width*/
4885- lodepng_add32bitInt(&header, h); /*height*/
4886- ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/
4887- ucvector_push_back(&header, (unsigned char)colortype); /*color type*/
4888- ucvector_push_back(&header, 0); /*compression method*/
4889- ucvector_push_back(&header, 0); /*filter method*/
4890- ucvector_push_back(&header, interlace_method); /*interlace method*/
4891-
4892- error = addChunk(out, "IHDR", header.data, header.size);
4893- ucvector_cleanup(&header);
4894-
4895- return error;
4896-}
4897-
4898-static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info)
4899-{
4900- unsigned error = 0;
4901- size_t i;
4902- ucvector PLTE;
4903- ucvector_init(&PLTE);
4904- for(i = 0; i < info->palettesize * 4; i++)
4905- {
4906- /*add all channels except alpha channel*/
4907- if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
4908- }
4909- error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
4910- ucvector_cleanup(&PLTE);
4911-
4912- return error;
4913-}
4914-
4915-static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info)
4916-{
4917- unsigned error = 0;
4918- size_t i;
4919- ucvector tRNS;
4920- ucvector_init(&tRNS);
4921- if(info->colortype == LCT_PALETTE)
4922- {
4923- /*add only alpha channel*/
4924- for(i = 0; i < info->palettesize; i++) ucvector_push_back(&tRNS, info->palette[4 * i + 3]);
4925- }
4926- else if(info->colortype == LCT_GREY)
4927- {
4928- if(info->key_defined)
4929- {
4930- ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256));
4931- ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256));
4932- }
4933- }
4934- else if(info->colortype == LCT_RGB)
4935- {
4936- if(info->key_defined)
4937- {
4938- ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256));
4939- ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256));
4940- ucvector_push_back(&tRNS, (unsigned char)(info->key_g / 256));
4941- ucvector_push_back(&tRNS, (unsigned char)(info->key_g % 256));
4942- ucvector_push_back(&tRNS, (unsigned char)(info->key_b / 256));
4943- ucvector_push_back(&tRNS, (unsigned char)(info->key_b % 256));
4944- }
4945- }
4946-
4947- error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
4948- ucvector_cleanup(&tRNS);
4949-
4950- return error;
4951-}
4952-
4953-static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
4954- LodePNGCompressSettings* zlibsettings)
4955-{
4956- ucvector zlibdata;
4957- unsigned error = 0;
4958-
4959- /*compress with the Zlib compressor*/
4960- ucvector_init(&zlibdata);
4961- error = lodepng_zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
4962- if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
4963- ucvector_cleanup(&zlibdata);
4964-
4965- return error;
4966-}
4967-
4968-static unsigned addChunk_IEND(ucvector* out)
4969-{
4970- unsigned error = 0;
4971- error = addChunk(out, "IEND", 0, 0);
4972- return error;
4973-}
4974-
4975-#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
4976-
4977-static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring)
4978-{
4979- unsigned error = 0;
4980- size_t i;
4981- ucvector text;
4982- ucvector_init(&text);
4983- for(i = 0; keyword[i] != 0; i++) ucvector_push_back(&text, (unsigned char)keyword[i]);
4984- ucvector_push_back(&text, 0);
4985- for(i = 0; textstring[i] != 0; i++) ucvector_push_back(&text, (unsigned char)textstring[i]);
4986- error = addChunk(out, "tEXt", text.data, text.size);
4987- ucvector_cleanup(&text);
4988-
4989- return error;
4990-}
4991-
4992-static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
4993- LodePNGCompressSettings* zlibsettings)
4994-{
4995- unsigned error = 0;
4996- ucvector data, compressed;
4997- size_t i, textsize = strlen(textstring);
4998-
4999- ucvector_init(&data);
5000- ucvector_init(&compressed);
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches

to status/vote changes: