From 07b24c6e6e266999dbaaa12ffb201f402190cad1 Mon Sep 17 00:00:00 2001 From: ziplantil Date: Sun, 19 Apr 2020 16:29:36 +0300 Subject: [PATCH 001/186] add append_images support for ico, much like icns --- src/PIL/IcoImagePlugin.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py index e4a74321b..0186751be 100644 --- a/src/PIL/IcoImagePlugin.py +++ b/src/PIL/IcoImagePlugin.py @@ -52,6 +52,9 @@ def _save(im, fp, filename): sizes = list(sizes) fp.write(struct.pack(" Date: Sun, 19 Apr 2020 16:45:12 +0300 Subject: [PATCH 002/186] add test for ico append_images --- Tests/test_file_ico.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Tests/test_file_ico.py b/Tests/test_file_ico.py index 9ed1ffcb7..7fb52b12d 100644 --- a/Tests/test_file_ico.py +++ b/Tests/test_file_ico.py @@ -85,6 +85,24 @@ def test_only_save_relevant_sizes(tmp_path): assert im_saved.info["sizes"] == {(16, 16), (24, 24), (32, 32), (48, 48)} +def test_only_save_append_images(tmp_path): + """append_images should work to provide alternative sizes""" + im = hopper() + provided_im = Image.new("RGBA", (32, 32), (255, 0, 0, 255)) + outfile = str(tmp_path / "temp_saved_multi_icon.ico") + im.save(outfile, sizes = [(32, 32), (64, 64)], append_images = [provided_im]) + + with Image.open(outfile) as reread: + reread.size = (64, 64) + reread.load() + assert_image_equal(reread, hopper().resize((64, 64), Image.LANCZOS)) + + with Image.open(outfile) as reread: + reread.size = (32, 32) + reread.load() + assert_image_equal(reread, provided_im) + + def test_unexpected_size(): # This image has been manually hexedited to state that it is 16x32 # while the image within is still 16x16 From 39f47387753d88b3c24743a71907e09245867d01 Mon Sep 17 00:00:00 2001 From: ziplantil Date: Sun, 19 Apr 2020 16:54:53 +0300 Subject: [PATCH 003/186] lint --- Tests/test_file_ico.py | 2 +- src/PIL/IcoImagePlugin.py | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Tests/test_file_ico.py b/Tests/test_file_ico.py index 7fb52b12d..ba9f84f5e 100644 --- a/Tests/test_file_ico.py +++ b/Tests/test_file_ico.py @@ -90,7 +90,7 @@ def test_only_save_append_images(tmp_path): im = hopper() provided_im = Image.new("RGBA", (32, 32), (255, 0, 0, 255)) outfile = str(tmp_path / "temp_saved_multi_icon.ico") - im.save(outfile, sizes = [(32, 32), (64, 64)], append_images = [provided_im]) + im.save(outfile, sizes=[(32, 32), (64, 64)], append_images=[provided_im]) with Image.open(outfile) as reread: reread.size = (64, 64) diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py index 0186751be..62a1fb4ab 100644 --- a/src/PIL/IcoImagePlugin.py +++ b/src/PIL/IcoImagePlugin.py @@ -52,9 +52,7 @@ def _save(im, fp, filename): sizes = list(sizes) fp.write(struct.pack(" Date: Mon, 20 Apr 2020 12:08:41 +0300 Subject: [PATCH 004/186] commit suggestion; update src/PIL/IcoImagePlugin.py Co-Authored-By: Andrew Murray <3112309+radarhere@users.noreply.github.com> --- src/PIL/IcoImagePlugin.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py index 62a1fb4ab..dc2d6606a 100644 --- a/src/PIL/IcoImagePlugin.py +++ b/src/PIL/IcoImagePlugin.py @@ -64,9 +64,8 @@ def _save(im, fp, filename): fp.write(struct.pack(" Date: Mon, 12 Oct 2020 18:38:36 +1100 Subject: [PATCH 005/186] Moved warning to end of execution --- setup.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/setup.py b/setup.py index 2f7c85e9b..e02095bd2 100755 --- a/setup.py +++ b/setup.py @@ -38,12 +38,16 @@ ZLIB_ROOT = None if sys.platform == "win32" and sys.version_info >= (3, 10): - warnings.warn( - f"Pillow {PILLOW_VERSION} does not support Python " - f"{sys.version_info.major}.{sys.version_info.minor} and does not provide " - "prebuilt Windows binaries. We do not recommend building from source on " - "Windows.", - RuntimeWarning, + import atexit + + atexit.register( + lambda: warnings.warn( + f"Pillow {PILLOW_VERSION} does not support Python " + f"{sys.version_info.major}.{sys.version_info.minor} and does not provide " + "prebuilt Windows binaries. We do not recommend building from source on " + "Windows.", + RuntimeWarning, + ) ) From 1e4d81f160ce37de635bd45a5162cf5c080a55fa Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 14 Oct 2020 17:31:21 +0100 Subject: [PATCH 006/186] add Python 3.10-dev to GHA --- .github/workflows/test-windows.yml | 2 +- .github/workflows/test.yml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test-windows.yml b/.github/workflows/test-windows.yml index d384a7d29..0ebeed7cd 100644 --- a/.github/workflows/test-windows.yml +++ b/.github/workflows/test-windows.yml @@ -8,7 +8,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.6", "3.7", "3.8", "3.9", "pypy3"] + python-version: ["3.6", "3.7", "3.8", "3.9", "3.10-dev", "pypy3"] architecture: ["x86", "x64"] include: - architecture: "x86" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6cb099640..72291876a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -14,6 +14,7 @@ jobs: ] python-version: [ "pypy3", + "3.10-dev", "3.9", "3.8", "3.7", From 26cfe04fea451f689e9a4d137fc8ff8dbf292993 Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 14 Oct 2020 20:52:16 +0100 Subject: [PATCH 007/186] fix PY_SSIZE_T_CLEAN in display.c --- src/display.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/display.c b/src/display.c index 2eb4a5855..c95844bbc 100644 --- a/src/display.c +++ b/src/display.c @@ -22,7 +22,7 @@ * See the README file for information on usage and redistribution. */ - +#define PY_SSIZE_T_CLEAN #include "Python.h" #include "libImaging/Imaging.h" @@ -196,7 +196,7 @@ static PyObject* _frombytes(ImagingDisplayObject* display, PyObject* args) { char* ptr; - int bytes; + Py_ssize_t bytes; if (!PyArg_ParseTuple(args, "y#:frombytes", &ptr, &bytes)) { return NULL; @@ -777,7 +777,7 @@ PyImaging_DrawWmf(PyObject* self, PyObject* args) char* ptr; char* data; - int datasize; + Py_ssize_t datasize; int width, height; int x0, y0, x1, y1; if (!PyArg_ParseTuple(args, "y#(ii)(iiii):_load", &data, &datasize, From bdcc48f0a2d5af58155c6e10a127536d4ac79374 Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 14 Oct 2020 20:59:19 +0100 Subject: [PATCH 008/186] skip wheels on 3.10-dev due to wheel#354 --- .github/workflows/test-windows.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test-windows.yml b/.github/workflows/test-windows.yml index 0ebeed7cd..7c28b5075 100644 --- a/.github/workflows/test-windows.yml +++ b/.github/workflows/test-windows.yml @@ -187,14 +187,16 @@ jobs: - name: Build wheel id: wheel - if: "github.event_name == 'push'" + # Skip wheels on 3.10 due to https://github.com/pypa/wheel/issues/354 + if: "github.event_name == 'push' && !contains(matrix.python-version, '3.10')" run: | for /f "tokens=3 delims=/" %%a in ("${{ github.ref }}") do echo ::set-output name=dist::dist-%%a winbuild\\build\\build_pillow.cmd --disable-imagequant bdist_wheel shell: cmd - uses: actions/upload-artifact@v2 - if: "github.event_name == 'push'" + # Skip wheels on 3.10 due to https://github.com/pypa/wheel/issues/354 + if: "github.event_name == 'push' && !contains(matrix.python-version, '3.10')" with: name: ${{ steps.wheel.outputs.dist }} path: dist\*.whl From b305f99416aafbdf6b799418bb2b9bf1af6be3f1 Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 14 Oct 2020 19:26:45 +0100 Subject: [PATCH 009/186] skip numpy on 3.10-dev due to wheel#354 --- .ci/install.sh | 3 ++- .github/workflows/macos-install.sh | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.ci/install.sh b/.ci/install.sh index afb88eb17..8e1e263e1 100755 --- a/.ci/install.sh +++ b/.ci/install.sh @@ -31,7 +31,8 @@ pip install -U pytest pip install -U pytest-cov pip install pyroma pip install test-image-results -pip install numpy +# TODO Remove condition when numpy supports 3.10 +if ! [ "$GHA_PYTHON_VERSION" == "3.10-dev" ]; then pip install numpy ; fi # TODO Remove when 3.8 / 3.9 / PyPy3 includes setuptools 49.3.2+: if [ "$GHA_PYTHON_VERSION" == "3.8" ]; then pip install -U "setuptools>=49.3.2" ; fi diff --git a/.github/workflows/macos-install.sh b/.github/workflows/macos-install.sh index 16f532edf..4d5e54b27 100755 --- a/.github/workflows/macos-install.sh +++ b/.github/workflows/macos-install.sh @@ -13,7 +13,8 @@ pip install pyroma pip install test-image-results echo -e "[openblas]\nlibraries = openblas\nlibrary_dirs = /usr/local/opt/openblas/lib" >> ~/.numpy-site.cfg -pip install numpy +# TODO Remove condition when numpy supports 3.10 +if ! [ "$GHA_PYTHON_VERSION" == "3.10-dev" ]; then pip install numpy ; fi # TODO Remove when 3.8 / 3.9 includes setuptools 49.3.2+: if [ "$GHA_PYTHON_VERSION" == "3.8" ]; then pip install -U "setuptools>=49.3.2" ; fi From 42e23ff4d1b025acca68391a024afb06b6c509be Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 15 Oct 2020 14:39:49 +0300 Subject: [PATCH 010/186] Replace viewdoc with markdown2 and twine check --- Makefile | 4 ++-- RELEASING.md | 26 +++++++++++++++++++------- requirements.txt | 2 +- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/Makefile b/Makefile index 4fd031b69..519dadb30 100644 --- a/Makefile +++ b/Makefile @@ -94,7 +94,7 @@ release-test: python3 -m pytest -qq check-manifest pyroma . - viewdoc + $(MAKE) readme .PHONY: sdist sdist: @@ -106,4 +106,4 @@ test: .PHONY: readme readme: - viewdoc + python3 setup.py --long-description | markdown2 > .long-description.html && open .long-description.html diff --git a/RELEASING.md b/RELEASING.md index c9a0439d8..514c61519 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -21,12 +21,17 @@ Released quarterly on January 2nd, April 1st, July 1st and October 15th. git push --all git push --tags ``` -* [ ] Create source distributions e.g.: +* [ ] Create and check source distribution: ```bash make sdist + twine check dist/* ``` * [ ] Create [binary distributions](https://github.com/python-pillow/Pillow/blob/master/RELEASING.md#binary-distributions) -* [ ] Upload all binaries and source distributions e.g. `twine upload dist/Pillow-5.2.0*` +* [ ] Check and upload all binaries and source distributions e.g.: + ```bash + twine check dist/* + twine upload dist/Pillow-5.2.0* + ``` * [ ] Create a [new release on GitHub](https://github.com/python-pillow/Pillow/releases/new) * [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), increment and append `.dev0` to version identifier in `src/PIL/_version.py` @@ -56,12 +61,17 @@ Released as needed for security, installation or critical bug fixes. git push git push --tags ``` -* [ ] Create source distributions e.g.: +* [ ] Create and check source distribution: ```bash make sdist + twine check dist/* ``` * [ ] Create [binary distributions](https://github.com/python-pillow/Pillow/blob/master/RELEASING.md#binary-distributions) -* [ ] Upload all binaries and source distributions e.g. `twine upload dist/Pillow-5.2.1*` +* [ ] Check and upload all binaries and source distributions e.g.: + ```bash + twine check dist/* + twine upload dist/Pillow-5.2.0* + ``` * [ ] Create a [new release on GitHub](https://github.com/python-pillow/Pillow/releases/new) ## Embargoed Release @@ -81,9 +91,10 @@ Released as needed privately to individual vendors for critical security-related git push origin 2.5.x git push origin --tags ``` -* [ ] Create source distributions e.g.: +* [ ] Create and check source distribution: ```bash make sdist + twine check dist/* ``` * [ ] Create [binary distributions](https://github.com/python-pillow/Pillow/blob/master/RELEASING.md#binary-distributions) * [ ] Create a [new release on GitHub](https://github.com/python-pillow/Pillow/releases/new) @@ -92,7 +103,7 @@ Released as needed privately to individual vendors for critical security-related ### Windows * [ ] Contact `@cgohlke` for Windows binaries via release ticket e.g. https://github.com/python-pillow/Pillow/issues/1174. -* [ ] Download and extract tarball from `@cgohlke` and `twine upload *`. +* [ ] Download and extract tarball from `@cgohlke` and copy into `dist/` ### Mac and Linux * [ ] Use the [Pillow Wheel Builder](https://github.com/python-pillow/pillow-wheels): @@ -101,7 +112,8 @@ Released as needed privately to individual vendors for critical security-related cd pillow-wheels ./update-pillow-tag.sh [[release tag]] ``` -* [ ] Download wheels from the [Pillow Wheel Builder release](https://github.com/python-pillow/pillow-wheels/releases). +* [ ] Download wheels from the [Pillow Wheel Builder release](https://github.com/python-pillow/pillow-wheels/releases) + and copy into `dist/` ## Publicize Release diff --git a/requirements.txt b/requirements.txt index 9758f91fd..7b52e1253 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ black check-manifest coverage -jarn.viewdoc +markdown2 olefile pycodestyle pyflakes From 919fdcc49c6f9f803d6c3086c7ec7cf9a75c15a3 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 20 Oct 2020 19:55:44 +1100 Subject: [PATCH 011/186] Updated freetype to 2.10.4 --- winbuild/build_prepare.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/winbuild/build_prepare.py b/winbuild/build_prepare.py index 352c3f76b..6c431f4d6 100644 --- a/winbuild/build_prepare.py +++ b/winbuild/build_prepare.py @@ -184,9 +184,9 @@ deps = { "libs": [r"libpng16.lib"], }, "freetype": { - "url": "https://download.savannah.gnu.org/releases/freetype/freetype-2.10.3.tar.gz", # noqa: E501 - "filename": "freetype-2.10.3.tar.gz", - "dir": "freetype-2.10.3", + "url": "https://download.savannah.gnu.org/releases/freetype/freetype-2.10.4.tar.gz", # noqa: E501 + "filename": "freetype-2.10.4.tar.gz", + "dir": "freetype-2.10.4", "patch": { r"builds\windows\vc2010\freetype.vcxproj": { # freetype setting is /MD for .dll and /MT for .lib, we need /MD From 558b2e6cf6143acd6323f0887c112043f34b5fb4 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 22 Oct 2020 15:45:58 +0300 Subject: [PATCH 012/186] Add release notes for 8.0.1 --- CHANGES.rst | 6 ++++++ docs/releasenotes/8.0.1.rst | 23 +++++++++++++++++++++++ docs/releasenotes/index.rst | 1 + 3 files changed, 30 insertions(+) create mode 100644 docs/releasenotes/8.0.1.rst diff --git a/CHANGES.rst b/CHANGES.rst index 6e1970cba..95a7d1c46 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -8,6 +8,12 @@ Changelog (Pillow) - Support raw rgba8888 for DDS #4760 [qiankanglai] +8.0.1 (2020-10-22) +------------------ + +- Update FreeType used in binary wheels to 2.10.4 to fix CVE-2020-15999. + [radarhere] + 8.0.0 (2020-10-15) ------------------ diff --git a/docs/releasenotes/8.0.1.rst b/docs/releasenotes/8.0.1.rst new file mode 100644 index 000000000..be10d8e47 --- /dev/null +++ b/docs/releasenotes/8.0.1.rst @@ -0,0 +1,23 @@ +8.0.1 +----- + +Security +======== + +Update FreeType used in binary wheels to `2.10.4`_ to fix CVE-2020-15999_: + + - A heap buffer overflow has been found in the handling of embedded PNG bitmaps, + introduced in FreeType version 2.6. + + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-15999 + + If you use option ``FT_CONFIG_OPTION_USE_PNG`` you should upgrade immediately. + +Before Pillow 8.0.0 bitmap fonts were disabled with ``FT_LOAD_NO_BITMAP``, but it is not +clear if this prevents the exploit and we recommend updating to Pillow 8.0.1. + +Pillow 8.0.0 and earlier are potentially vulnerable releases, including the last release +to support Python 2.7, namely Pillow 6.2.2. + +.. _2.10.4: https://sourceforge.net/projects/freetype/files/freetype2/2.10.4/ +.. _CVE-2020-15999: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-15999 diff --git a/docs/releasenotes/index.rst b/docs/releasenotes/index.rst index ba81fbaf8..5c74bed9b 100644 --- a/docs/releasenotes/index.rst +++ b/docs/releasenotes/index.rst @@ -13,6 +13,7 @@ expected to be backported to earlier versions. .. toctree:: :maxdepth: 2 + 8.0.1 8.0.0 7.2.0 7.1.2 From ac348ea3b1807f805c165cd29a54734000f14c3a Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 22 Oct 2020 17:09:20 +0300 Subject: [PATCH 013/186] Clarify wording [CI skip] Co-authored-by: nulano --- docs/releasenotes/8.0.1.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/releasenotes/8.0.1.rst b/docs/releasenotes/8.0.1.rst index be10d8e47..e50596e5c 100644 --- a/docs/releasenotes/8.0.1.rst +++ b/docs/releasenotes/8.0.1.rst @@ -13,7 +13,9 @@ Update FreeType used in binary wheels to `2.10.4`_ to fix CVE-2020-15999_: If you use option ``FT_CONFIG_OPTION_USE_PNG`` you should upgrade immediately. -Before Pillow 8.0.0 bitmap fonts were disabled with ``FT_LOAD_NO_BITMAP``, but it is not +We strongly recommend updating to Pillow 8.0.1 if you are using Pillow 8.0.0, which improved support for bitmap fonts. + +In Pillow 7.2.0 and earlier bitmap fonts were disabled with ``FT_LOAD_NO_BITMAP``, but it is not clear if this prevents the exploit and we recommend updating to Pillow 8.0.1. Pillow 8.0.0 and earlier are potentially vulnerable releases, including the last release From ece120d63c1d645e4bf986757dd41986365eb0e5 Mon Sep 17 00:00:00 2001 From: nulano Date: Thu, 22 Oct 2020 15:53:16 +0100 Subject: [PATCH 014/186] replace test images when copying from pillow-depends --- .appveyor.yml | 2 +- .github/workflows/test-windows.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.appveyor.yml b/.appveyor.yml index 8ef91212d..23ac977ae 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -22,7 +22,7 @@ install: - curl -fsSL -o pillow-depends.zip https://github.com/python-pillow/pillow-depends/archive/master.zip - 7z x pillow-depends.zip -oc:\ - mv c:\pillow-depends-master c:\pillow-depends -- xcopy /s c:\pillow-depends\test_images\* c:\pillow\tests\images +- xcopy /S /Y c:\pillow-depends\test_images\* c:\pillow\tests\images - 7z x ..\pillow-depends\nasm-2.14.02-win64.zip -oc:\ - ..\pillow-depends\gs9533w32.exe /S - path c:\nasm-2.14.02;C:\Program Files (x86)\gs\gs9.53.3\bin;%PATH% diff --git a/.github/workflows/test-windows.yml b/.github/workflows/test-windows.yml index d384a7d29..9864455de 100644 --- a/.github/workflows/test-windows.yml +++ b/.github/workflows/test-windows.yml @@ -76,7 +76,7 @@ jobs: winbuild\depends\gs9533w32.exe /S echo "C:\Program Files (x86)\gs\gs9.53.3\bin" >> $env:GITHUB_PATH - xcopy /s winbuild\depends\test_images\* Tests\images\ + xcopy /S /Y winbuild\depends\test_images\* Tests\images\ shell: pwsh - name: Cache build From 82c8b76a3683da75ec95b9c64094db9a2681614c Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 23 Oct 2020 08:22:17 +1100 Subject: [PATCH 015/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 95a7d1c46..e7090219f 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -14,6 +14,9 @@ Changelog (Pillow) - Update FreeType used in binary wheels to 2.10.4 to fix CVE-2020-15999. [radarhere] +- Moved string_dimension image to pillow-depends #4993 + [radarhere] + 8.0.0 (2020-10-15) ------------------ From d1650cb2b3bae7f79b3b002f83eb81ba50bfa575 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 23 Oct 2020 21:08:06 +1100 Subject: [PATCH 016/186] Document FreeMono license [ci skip] --- Tests/fonts/LICENSE.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/fonts/LICENSE.txt b/Tests/fonts/LICENSE.txt index db3af7c34..06eaa9a4e 100644 --- a/Tests/fonts/LICENSE.txt +++ b/Tests/fonts/LICENSE.txt @@ -11,6 +11,8 @@ BungeeColor-Regular_colr_Windows.ttf, from https://github.com/djrrb/bungee All of the above fonts are published under the SIL Open Font License (OFL) v1.1 (http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL), which allows you to copy, modify, and redistribute them if you need to. +FreeMono.ttf is licensed under GPLv3, with the GPL font exception. + OpenSansCondensed-LightItalic.tt, from https://fonts.google.com/specimen/Open+Sans, under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0) DejaVuSans-24-{1,2,4,8}-stripped.ttf are based on DejaVuSans.ttf converted using FontForge to add bitmap strikes and keep only the ASCII range. From 07cfe1d0d0799673ab922537cb7ba7958b8be496 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 24 Oct 2020 13:14:51 +1100 Subject: [PATCH 017/186] Updated macOS tested Pillow versions [ci skip] --- docs/installation.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/installation.rst b/docs/installation.rst index c09b641ab..4a70b7fbf 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -469,7 +469,9 @@ These platforms have been reported to work at the versions mentioned. +----------------------------------+------------------------------+--------------------------------+-----------------------+ |**Operating system** |**Tested Python versions** |**Latest tested Pillow version**|**Tested processors** | +----------------------------------+------------------------------+--------------------------------+-----------------------+ -| macOS 10.15 Catalina | 3.5, 3.6, 3.7, 3.8 | 7.2.0 |x86-64 | +| macOS 10.15 Catalina | 3.6, 3.7, 3.8, 3.9 | 8.0.1 |x86-64 | +| +------------------------------+--------------------------------+ + +| | 3.5 | 7.2.0 | | +----------------------------------+------------------------------+--------------------------------+-----------------------+ | macOS 10.14 Mojave | 3.5, 3.6, 3.7, 3.8 | 7.2.0 |x86-64 | | +------------------------------+--------------------------------+ + From 25be3364575c8f2c2051a86e0995a2415f93f8ed Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Sun, 25 Oct 2020 14:40:40 +0200 Subject: [PATCH 018/186] Add a 'git push' to point release, adjust MD formatting for issues [CI skip] --- RELEASING.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/RELEASING.md b/RELEASING.md index c9a0439d8..ad166527c 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -6,10 +6,7 @@ Released quarterly on January 2nd, April 1st, July 1st and October 15th. * [ ] Open a release ticket e.g. https://github.com/python-pillow/Pillow/issues/3154 * [ ] Develop and prepare release in `master` branch. -* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), - [Travis CI](https://travis-ci.org/github/python-pillow/Pillow) and - [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm - passing tests in `master` branch. +* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), [Travis CI](https://travis-ci.org/github/python-pillow/Pillow) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in `master` branch. * [ ] Check that all of the wheel builds [Pillow Wheel Builder](https://github.com/python-pillow/pillow-wheels) pass the tests in Travis CI. * [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), update version identifier in `src/PIL/_version.py` * [ ] Update `CHANGES.rst`. @@ -40,14 +37,11 @@ Released as needed for security, installation or critical bug fixes. ```bash git checkout -t remotes/origin/5.2.x ``` -* [ ] Cherry pick individual commits from `master` branch to release branch e.g. `5.2.x`. +* [ ] Cherry pick individual commits from `master` branch to release branch e.g. `5.2.x`, then `git push`. -* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), - [Travis CI](https://travis-ci.org/github/python-pillow/Pillow) and - [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm - passing tests in release branch e.g. `5.2.x`. +* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), [Travis CI](https://travis-ci.org/github/python-pillow/Pillow) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in release branch e.g. `5.2.x`. * [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), update version identifier in `src/PIL/_version.py` * [ ] Run pre-release check via `make release-test`. * [ ] Create tag for release e.g.: From 3581600bf34d98f4f50684037459cd7c52e3054b Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 26 Oct 2020 06:58:20 +1100 Subject: [PATCH 019/186] Clarified that "text" must be a string [ci skip] --- docs/reference/ImageDraw.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/reference/ImageDraw.rst b/docs/reference/ImageDraw.rst index 6052d2833..57d1c2dda 100644 --- a/docs/reference/ImageDraw.rst +++ b/docs/reference/ImageDraw.rst @@ -296,7 +296,7 @@ Methods Draws the string at the given position. :param xy: The anchor coordinates of the text. - :param text: Text to be drawn. If it contains any newline characters, + :param text: String to be drawn. If it contains any newline characters, the text is passed on to :py:meth:`~PIL.ImageDraw.ImageDraw.multiline_text`. :param fill: Color to use for the text. @@ -362,7 +362,7 @@ Methods Draws the string at the given position. :param xy: The anchor coordinates of the text. - :param text: Text to be drawn. + :param text: String to be drawn. :param fill: Color to use for the text. :param font: An :py:class:`~PIL.ImageFont.ImageFont` instance. From 3fca42f27db2ea7cc83d16b2ccd4c2fc97a71251 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Mon, 26 Oct 2020 21:59:24 +0200 Subject: [PATCH 020/186] Test on Python 3.9 final --- .travis.yml | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index b02f054d0..da8aedf8c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,8 +28,8 @@ matrix: - python: "pypy3.6-7.3.1" name: "PyPy3 Xenial" - - python: "3.9-dev" - name: "3.9-dev Xenial" + - python: "3.9" + name: "3.9 Xenial" services: xvfb - python: "3.8" name: "3.8 Xenial" @@ -43,9 +43,6 @@ matrix: env: PYTHONOPTIMIZE=1 services: xvfb - allow_failures: - - python: "3.9-dev" - install: - | if [ "$LINT" == "true" ]; then From 5eab56860bc79ff8a68dd519bfe8051393a93cb3 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 27 Oct 2020 21:12:51 +1100 Subject: [PATCH 021/186] Updated CI targets [ci skip] --- docs/installation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/installation.rst b/docs/installation.rst index 4a70b7fbf..131a60692 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -438,7 +438,7 @@ These platforms are built and tested for every change. +----------------------------------+--------------------------+-----------------------+ | macOS 10.15 Catalina | 3.6, 3.7, 3.8, 3.9, PyPy3|x86-64 | +----------------------------------+--------------------------+-----------------------+ -| Ubuntu Linux 16.04 LTS (Xenial) | 3.6, 3.7, 3.8, PyPy3 |x86-64 | +| Ubuntu Linux 16.04 LTS (Xenial) | 3.6, 3.7, 3.8, 3.9, PyPy3|x86-64 | +----------------------------------+--------------------------+-----------------------+ | Ubuntu Linux 18.04 LTS (Bionic) | 3.6, 3.7, 3.8, 3.9, PyPy3|x86-64 | +----------------------------------+--------------------------+-----------------------+ From 91de1880b3bdd9b56a22f115ea83e5c92cc252a9 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Tue, 27 Oct 2020 21:47:06 +0200 Subject: [PATCH 022/186] Add Fedora 33 --- .github/workflows/test-docker.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/test-docker.yml b/.github/workflows/test-docker.yml index 2d6d12933..ddec1bee4 100644 --- a/.github/workflows/test-docker.yml +++ b/.github/workflows/test-docker.yml @@ -21,6 +21,7 @@ jobs: amazon-1-amd64, amazon-2-amd64, fedora-32-amd64, + fedora-33-amd64, ] dockerTag: [master] From 1b3685aeddaea9fadeeed120d87e68a8d0b44e59 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Tue, 27 Oct 2020 21:54:04 +0200 Subject: [PATCH 023/186] Test on Python 3.9 final --- .appveyor.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.appveyor.yml b/.appveyor.yml index 23ac977ae..092b73748 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -1,5 +1,4 @@ version: '{build}' -image: Visual Studio 2017 clone_folder: c:\pillow init: - ECHO %PYTHON% @@ -12,10 +11,12 @@ environment: TEST_OPTIONS: DEPLOY: YES matrix: - - PYTHON: C:/Python38 + - PYTHON: C:/Python39 ARCHITECTURE: x86 + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - PYTHON: C:/Python36-x64 ARCHITECTURE: x64 + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 install: @@ -32,6 +33,7 @@ install: c:\pillow\winbuild\build\build_dep_all.cmd $host.SetShouldExit(0) - path C:\pillow\winbuild\build\bin;%PATH% +- '%PYTHON%\%PIP_DIR%\pip.exe install -U "setuptools>=49.3.2"' build_script: - ps: | From d171afc19ee4401530ab9e0d7862f4206e7ce6e1 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 28 Oct 2020 22:03:27 +1100 Subject: [PATCH 024/186] Describe effect of WebP save_all [ci skip] --- docs/handbook/image-file-formats.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/handbook/image-file-formats.rst b/docs/handbook/image-file-formats.rst index 680582f12..2b6f9483b 100644 --- a/docs/handbook/image-file-formats.rst +++ b/docs/handbook/image-file-formats.rst @@ -947,9 +947,10 @@ Saving sequences library is v0.5.0 or later. You can check webp animation support at runtime by calling ``features.check("webp_anim")``. -When calling :py:meth:`~PIL.Image.Image.save` to write a WebP file, the -following options are available when the ``save_all`` argument is present and -true. +When calling :py:meth:`~PIL.Image.Image.save` to write a WebP file, by default +only the first frame of a multiframe image will be saved. If the ``save_all`` +argument is present and true, then all frames will be saved, and the following +options will also be available. **append_images** A list of images to append as additional frames. Each of the From b3f0f9ae8ca09d53ea6982254ec0984a0e6424af Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 29 Oct 2020 18:40:46 +1100 Subject: [PATCH 025/186] Updated CI targets [ci skip] --- docs/installation.rst | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/installation.rst b/docs/installation.rst index 131a60692..0a8c41ba6 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -444,9 +444,7 @@ These platforms are built and tested for every change. +----------------------------------+--------------------------+-----------------------+ | Ubuntu Linux 20.04 LTS (Focal) | 3.8 |x86-64 | +----------------------------------+--------------------------+-----------------------+ -| Windows Server 2016 | 3.8 |x86 | -| +--------------------------+-----------------------+ -| | 3.6 |x86-64 | +| Windows Server 2016 | 3.6 |x86-64 | +----------------------------------+--------------------------+-----------------------+ | Windows Server 2019 | 3.6, 3.7, 3.8, 3.9 |x86, x86-64 | | +--------------------------+-----------------------+ From 6a50e1076afff4c8f04a11f55bd0e6512dbfd8d9 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 29 Oct 2020 22:41:29 +1100 Subject: [PATCH 026/186] Invoke pip using Python --- .appveyor.yml | 8 ++++---- .ci/install.sh | 28 ++++++++++++++-------------- .github/workflows/macos-install.sh | 20 ++++++++++---------- .github/workflows/test-windows.yml | 2 +- .github/workflows/test.yml | 4 ++-- .travis.yml | 2 +- depends/diffcover-install.sh | 2 +- docs/releasenotes/6.0.0.rst | 2 +- tox.ini | 4 ++-- winbuild/build.rst | 2 +- 10 files changed, 37 insertions(+), 37 deletions(-) diff --git a/.appveyor.yml b/.appveyor.yml index 092b73748..45b748140 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -33,7 +33,7 @@ install: c:\pillow\winbuild\build\build_dep_all.cmd $host.SetShouldExit(0) - path C:\pillow\winbuild\build\bin;%PATH% -- '%PYTHON%\%PIP_DIR%\pip.exe install -U "setuptools>=49.3.2"' +- '%PYTHON%\%EXECUTABLE% -m pip install -U "setuptools>=49.3.2"' build_script: - ps: | @@ -44,13 +44,13 @@ build_script: test_script: - cd c:\pillow -- '%PYTHON%\%PIP_DIR%\pip.exe install pytest pytest-cov' +- '%PYTHON%\%EXECUTABLE% -m pip install pytest pytest-cov' - c:\"Program Files (x86)"\"Windows Kits"\10\Debuggers\x86\gflags.exe /p /enable %PYTHON%\%EXECUTABLE% - '%PYTHON%\%EXECUTABLE% -m pytest -vx --cov PIL --cov Tests --cov-report term --cov-report xml Tests' #- '%PYTHON%\%EXECUTABLE% test-installed.py -v -s %TEST_OPTIONS%' TODO TEST_OPTIONS with pytest? after_test: -- pip install codecov +- python -m pip install codecov - codecov --file coverage.xml --name %PYTHON% --flags AppVeyor matrix: @@ -67,7 +67,7 @@ artifacts: before_deploy: - cd c:\pillow - - '%PYTHON%\%PIP_DIR%\pip.exe install wheel' + - '%PYTHON%\%EXECUTABLE% -m pip install wheel' - cd c:\pillow\winbuild\ - c:\pillow\winbuild\build\build_pillow.cmd bdist_wheel - cd c:\pillow diff --git a/.ci/install.sh b/.ci/install.sh index 6f83fef22..6b9ade699 100755 --- a/.ci/install.sh +++ b/.ci/install.sh @@ -23,32 +23,32 @@ sudo apt-get -qq install libfreetype6-dev liblcms2-dev python3-tk\ if [[ $TRAVIS_CPU_ARCH == "s390x" ]]; then sudo chown $USER ~/.cache/pip/wheels ; fi -pip install --upgrade pip -PYTHONOPTIMIZE=0 pip install cffi -pip install coverage -pip install olefile -pip install -U pytest -pip install -U pytest-cov -pip install pyroma -pip install test-image-results -pip install numpy +python3 -m pip install --upgrade pip +PYTHONOPTIMIZE=0 python3 -m pip install cffi +python3 -m pip install coverage +python3 -m pip install olefile +python3 -m pip install -U pytest +python3 -m pip install -U pytest-cov +python3 -m pip install pyroma +python3 -m pip install test-image-results +python3 -m pip install numpy # TODO Remove when 3.8 / 3.9 / PyPy3 includes setuptools 49.3.2+: -if [ "$GHA_PYTHON_VERSION" == "3.8" ]; then pip install -U "setuptools>=49.3.2" ; fi -if [ "$GHA_PYTHON_VERSION" == "3.9" ]; then pip install -U "setuptools>=49.3.2" ; fi -if [ "$TRAVIS_PYTHON_VERSION" == "pypy3.6-7.3.1" ]; then pip install -U "setuptools>=49.3.2" ; fi +if [ "$GHA_PYTHON_VERSION" == "3.8" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi +if [ "$GHA_PYTHON_VERSION" == "3.9" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi +if [ "$TRAVIS_PYTHON_VERSION" == "pypy3.6-7.3.1" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi if [[ $TRAVIS_PYTHON_VERSION == 3.* ]]; then # arm64, ppc64le, s390x CPUs: # "ERROR: Could not find a version that satisfies the requirement pyqt5" if [[ $TRAVIS_CPU_ARCH == "amd64" ]]; then sudo apt-get -qq install libxcb-xinerama0 pyqt5-dev-tools - pip install pyqt5 + python3 -m pip install pyqt5 fi fi # docs only on Python 3.8 -if [ "$TRAVIS_PYTHON_VERSION" == "3.8" ]; then pip install -r requirements.txt ; fi +if [ "$TRAVIS_PYTHON_VERSION" == "3.8" ]; then python3 -m pip install -r requirements.txt ; fi # webp pushd depends && ./install_webp.sh && popd diff --git a/.github/workflows/macos-install.sh b/.github/workflows/macos-install.sh index 16f532edf..473412d3b 100755 --- a/.github/workflows/macos-install.sh +++ b/.github/workflows/macos-install.sh @@ -4,20 +4,20 @@ set -e brew install libtiff libjpeg openjpeg libimagequant webp little-cms2 freetype openblas -PYTHONOPTIMIZE=0 pip install cffi -pip install coverage -pip install olefile -pip install -U pytest -pip install -U pytest-cov -pip install pyroma -pip install test-image-results +PYTHONOPTIMIZE=0 python3 -m pip install cffi +python3 -m pip install coverage +python3 -m pip install olefile +python3 -m pip install -U pytest +python3 -m pip install -U pytest-cov +python3 -m pip install pyroma +python3 -m pip install test-image-results echo -e "[openblas]\nlibraries = openblas\nlibrary_dirs = /usr/local/opt/openblas/lib" >> ~/.numpy-site.cfg -pip install numpy +python3 -m pip install numpy # TODO Remove when 3.8 / 3.9 includes setuptools 49.3.2+: -if [ "$GHA_PYTHON_VERSION" == "3.8" ]; then pip install -U "setuptools>=49.3.2" ; fi -if [ "$GHA_PYTHON_VERSION" == "3.9" ]; then pip install -U "setuptools>=49.3.2" ; fi +if [ "$GHA_PYTHON_VERSION" == "3.8" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi +if [ "$GHA_PYTHON_VERSION" == "3.9" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi # extra test images pushd depends && ./install_extra_test_images.sh && popd diff --git a/.github/workflows/test-windows.yml b/.github/workflows/test-windows.yml index a52f092c6..a7fb2bdbc 100644 --- a/.github/workflows/test-windows.yml +++ b/.github/workflows/test-windows.yml @@ -55,7 +55,7 @@ jobs: - name: Print build system information run: python .github/workflows/system-info.py - - name: pip install wheel pytest pytest-cov + - name: python -m pip install wheel pytest pytest-cov run: python -m pip install wheel pytest pytest-cov # TODO Remove when 3.8 / 3.9 includes setuptools 49.3.2+: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6cb099640..df5f6f07c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -44,7 +44,7 @@ jobs: - name: Get pip cache dir id: pip-cache run: | - echo "::set-output name=dir::$(pip cache dir)" + echo "::set-output name=dir::$(python3 -m pip cache dir)" - name: pip cache uses: actions/cache@v2 @@ -96,7 +96,7 @@ jobs: - name: Docs if: startsWith(matrix.os, 'ubuntu') && matrix.python-version == 3.8 run: | - pip install sphinx-removed-in sphinx-rtd-theme + python3 -m pip install sphinx-removed-in sphinx-rtd-theme make doccheck - name: After success diff --git a/.travis.yml b/.travis.yml index da8aedf8c..2966cdf19 100644 --- a/.travis.yml +++ b/.travis.yml @@ -46,7 +46,7 @@ matrix: install: - | if [ "$LINT" == "true" ]; then - pip install tox + python3 -m pip install tox else .ci/install.sh; fi diff --git a/depends/diffcover-install.sh b/depends/diffcover-install.sh index a0b462b56..18be4f9f9 100755 --- a/depends/diffcover-install.sh +++ b/depends/diffcover-install.sh @@ -5,4 +5,4 @@ git fetch origin master:refs/remotes/origin/master # CFLAGS=-O0 means build with no optimisation. # Makes build much quicker for lxml and other dependencies. -time CFLAGS=-O0 pip install diff_cover +time CFLAGS=-O0 python3 -m pip install diff_cover diff --git a/docs/releasenotes/6.0.0.rst b/docs/releasenotes/6.0.0.rst index 0145347f2..3e3b945a0 100644 --- a/docs/releasenotes/6.0.0.rst +++ b/docs/releasenotes/6.0.0.rst @@ -17,7 +17,7 @@ Removed deprecated PIL.OleFileIO PIL.OleFileIO was removed as a vendored file and in Pillow 4.0.0 (2017-01) in favour of the upstream olefile Python package, and replaced with an ``ImportError``. The deprecated file has now been removed from Pillow. If needed, install from PyPI (eg. -``pip install olefile``). +``python3 -m pip install olefile``). Removed deprecated ImageOps functions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tox.ini b/tox.ini index 81c6e19cf..2557d5067 100644 --- a/tox.ini +++ b/tox.ini @@ -1,7 +1,7 @@ # Tox (https://tox.readthedocs.io/en/latest/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the -# test suite on all supported python versions. To use it, "pip install tox" -# and then run "tox" from this directory. +# test suite on all supported python versions. To use it, +# "python3 -m pip install tox" and then run "tox" from this directory. [tox] envlist = diff --git a/winbuild/build.rst b/winbuild/build.rst index ba568a030..cd4a45e87 100644 --- a/winbuild/build.rst +++ b/winbuild/build.rst @@ -82,7 +82,7 @@ Pillow for the selected version of Python. instead of installing Pillow. You can also use ``winbuild\build\build_pillow.cmd --inplace develop`` to build -and install Pillow in develop mode (instead of ``pip install --editable``). +and install Pillow in develop mode (instead of ``python3 -m pip install --editable``). Testing Pillow -------------- From 0823b37d41f0d36d38187e74d868015d6eb2c80e Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 30 Oct 2020 19:25:50 +1100 Subject: [PATCH 027/186] Removed PIP_DIR variable --- .appveyor.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.appveyor.yml b/.appveyor.yml index 45b748140..a77033ec1 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -7,7 +7,6 @@ init: environment: EXECUTABLE: python.exe - PIP_DIR: Scripts TEST_OPTIONS: DEPLOY: YES matrix: From 57ac10a3faf930c11078b7105a9f06d0ae151cf6 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 29 Oct 2020 21:26:44 +1100 Subject: [PATCH 028/186] Updated Python for diffcover to 3.9 --- .ci/after_success.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ci/after_success.sh b/.ci/after_success.sh index dcf276daa..762670f10 100755 --- a/.ci/after_success.sh +++ b/.ci/after_success.sh @@ -12,7 +12,7 @@ if [[ $TRAVIS ]]; then codecov --flags TravisCI fi -if [ "$TRAVIS_PYTHON_VERSION" == "3.8" ]; then +if [ "$TRAVIS_PYTHON_VERSION" == "3.9" ]; then # Coverage and quality reports on just the latest diff. depends/diffcover-install.sh depends/diffcover-run.sh From c309c64d0ab9603442c2a5564a4babb5d91b9e46 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 30 Oct 2020 23:51:41 +1100 Subject: [PATCH 029/186] Updated Python for doccheck to 3.9 --- .ci/install.sh | 4 ++-- .ci/test.sh | 2 +- .github/workflows/test.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.ci/install.sh b/.ci/install.sh index 6b9ade699..a8e82fa49 100755 --- a/.ci/install.sh +++ b/.ci/install.sh @@ -47,8 +47,8 @@ if [[ $TRAVIS_PYTHON_VERSION == 3.* ]]; then fi fi -# docs only on Python 3.8 -if [ "$TRAVIS_PYTHON_VERSION" == "3.8" ]; then python3 -m pip install -r requirements.txt ; fi +# docs only on Python 3.9 +if [ "$TRAVIS_PYTHON_VERSION" == "3.9" ]; then python3 -m pip install -r requirements.txt ; fi # webp pushd depends && ./install_webp.sh && popd diff --git a/.ci/test.sh b/.ci/test.sh index 579372a62..1396445e0 100755 --- a/.ci/test.sh +++ b/.ci/test.sh @@ -5,6 +5,6 @@ set -e python -bb -m pytest -v -x -W always --cov PIL --cov Tests --cov-report term Tests # Docs -if [ "$TRAVIS_PYTHON_VERSION" == "3.8" ] && [ "$TRAVIS_CPU_ARCH" == "amd64" ]; then +if [ "$TRAVIS_PYTHON_VERSION" == "3.9" ] && [ "$TRAVIS_CPU_ARCH" == "amd64" ]; then make doccheck fi diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index df5f6f07c..1fc8a09cb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -94,7 +94,7 @@ jobs: path: Tests/errors - name: Docs - if: startsWith(matrix.os, 'ubuntu') && matrix.python-version == 3.8 + if: startsWith(matrix.os, 'ubuntu') && matrix.python-version == 3.9 run: | python3 -m pip install sphinx-removed-in sphinx-rtd-theme make doccheck From c34cf8ccb9e694583cbcf87875b6fd624c71645d Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Fri, 30 Oct 2020 21:11:31 +0200 Subject: [PATCH 030/186] Update Travis CI links for .com --- .github/CONTRIBUTING.md | 4 ++-- README.md | 8 ++++---- RELEASING.md | 4 ++-- docs/about.rst | 2 +- docs/index.rst | 8 ++++---- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 3d27b5d88..a65487d5e 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -9,7 +9,7 @@ Please send a pull request to the master branch. Please include [documentation]( - Fork the Pillow repository. - Create a branch from master. - Develop bug fixes, features, tests, etc. -- Run the test suite. You can enable [Travis CI](https://travis-ci.org/profile/) and [AppVeyor](https://ci.appveyor.com/projects/new) on your repo to catch test failures prior to the pull request, and [Codecov](https://codecov.io/gh) to see if the changed code is covered by tests. +- Run the test suite. You can enable [Travis CI](https://travis-ci.com/account/repositories) and [AppVeyor](https://ci.appveyor.com/projects/new) on your repo to catch test failures prior to the pull request, and [Codecov](https://codecov.io/gh) to see if the changed code is covered by tests. - Create a pull request to pull the changes from your branch to the Pillow master. ### Guidelines @@ -17,7 +17,7 @@ Please send a pull request to the master branch. Please include [documentation]( - Separate code commits from reformatting commits. - Provide tests for any newly added code. - Follow PEP 8. -- When committing only documentation changes please include [ci skip] in the commit message to avoid running tests on Travis-CI and AppVeyor. +- When committing only documentation changes please include `[ci skip]` in the commit message to avoid running tests on Travis CI and AppVeyor. ## Reporting Issues diff --git a/README.md b/README.md index 0e6fa1157..9ead486a0 100644 --- a/README.md +++ b/README.md @@ -24,12 +24,12 @@ As of 2019, Pillow development is tests - Travis CI build status (Linux) - + Travis CI build status (macOS) + src="https://img.shields.io/travis/com/python-pillow/pillow-wheels/master.svg?label=macOS%20build"> AppVeyor CI build status (Windows) diff --git a/RELEASING.md b/RELEASING.md index ad166527c..dac0ba731 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -6,7 +6,7 @@ Released quarterly on January 2nd, April 1st, July 1st and October 15th. * [ ] Open a release ticket e.g. https://github.com/python-pillow/Pillow/issues/3154 * [ ] Develop and prepare release in `master` branch. -* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), [Travis CI](https://travis-ci.org/github/python-pillow/Pillow) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in `master` branch. +* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), [Travis CI](https://travis-ci.com/github/python-pillow/Pillow) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in `master` branch. * [ ] Check that all of the wheel builds [Pillow Wheel Builder](https://github.com/python-pillow/pillow-wheels) pass the tests in Travis CI. * [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), update version identifier in `src/PIL/_version.py` * [ ] Update `CHANGES.rst`. @@ -41,7 +41,7 @@ Released as needed for security, installation or critical bug fixes. -* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), [Travis CI](https://travis-ci.org/github/python-pillow/Pillow) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in release branch e.g. `5.2.x`. +* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), [Travis CI](https://travis-ci.com/github/python-pillow/Pillow) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in release branch e.g. `5.2.x`. * [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), update version identifier in `src/PIL/_version.py` * [ ] Run pre-release check via `make release-test`. * [ ] Create tag for release e.g.: diff --git a/docs/about.rst b/docs/about.rst index 283135aca..e2bd75561 100644 --- a/docs/about.rst +++ b/docs/about.rst @@ -10,7 +10,7 @@ The fork author's goal is to foster and support active development of PIL throug - Publicized development activity on `GitHub`_ - Regular releases to the `Python Package Index`_ -.. _Travis CI: https://travis-ci.org/python-pillow/Pillow +.. _Travis CI: https://travis-ci.com/github/python-pillow/Pillow .. _AppVeyor: https://ci.appveyor.com/project/Python-pillow/pillow .. _GitHub Actions: https://github.com/python-pillow/Pillow/actions .. _GitHub: https://github.com/python-pillow/Pillow diff --git a/docs/index.rst b/docs/index.rst index fb59a6c00..eafcb1fec 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -9,12 +9,12 @@ Pillow for enterprise is available via the Tidelift Subscription. `Learn more Date: Fri, 30 Oct 2020 21:28:35 +0200 Subject: [PATCH 031/186] Update Travis CI status check for .com --- .github/mergify.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/mergify.yml b/.github/mergify.yml index 3683bc483..fd4b5271f 100644 --- a/.github/mergify.yml +++ b/.github/mergify.yml @@ -7,8 +7,8 @@ pull_request_rules: - status-success=Test Successful - status-success=Docker Test Successful - status-success=Windows Test Successful + - status-success=Travis CI - Pull Request - status-success=continuous-integration/appveyor/pr - - status-success=continuous-integration/travis-ci/pr actions: merge: method: merge From 84052eb8c528df381642167b0cf51570295e98a6 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 31 Oct 2020 14:20:14 +1100 Subject: [PATCH 032/186] Added Fedora 33 to CI targets [ci skip] --- docs/installation.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/installation.rst b/docs/installation.rst index 0a8c41ba6..bb8c06580 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -436,6 +436,8 @@ These platforms are built and tested for every change. +----------------------------------+--------------------------+-----------------------+ | Fedora 32 | 3.8 |x86-64 | +----------------------------------+--------------------------+-----------------------+ +| Fedora 33 | 3.9 |x86-64 | ++----------------------------------+--------------------------+-----------------------+ | macOS 10.15 Catalina | 3.6, 3.7, 3.8, 3.9, PyPy3|x86-64 | +----------------------------------+--------------------------+-----------------------+ | Ubuntu Linux 16.04 LTS (Xenial) | 3.6, 3.7, 3.8, 3.9, PyPy3|x86-64 | From 81078e8a0d26c9094446a64aadfa8047b8af3484 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 31 Oct 2020 14:51:41 +1100 Subject: [PATCH 033/186] Refer to "HPND License" instead of "PIL Software License" --- LICENSE | 2 +- docs/about.rst | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/LICENSE b/LICENSE index 4aac532f4..eb9c41f56 100644 --- a/LICENSE +++ b/LICENSE @@ -7,7 +7,7 @@ Pillow is the friendly PIL fork. It is Copyright © 2010-2020 by Alex Clark and contributors -Like PIL, Pillow is licensed under the open source PIL Software License: +Like PIL, Pillow is licensed under the open source HPND License: By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply diff --git a/docs/about.rst b/docs/about.rst index e2bd75561..acd361fa8 100644 --- a/docs/about.rst +++ b/docs/about.rst @@ -19,7 +19,7 @@ The fork author's goal is to foster and support active development of PIL throug License ------- -Like PIL, Pillow is `licensed under the open source PIL Software License `_ +Like PIL, Pillow is `licensed under the open source HPND License `_ Why a fork? ----------- From 8593e17b0500b847070014e219b5e2cbebd9f9c2 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 2 Nov 2020 20:58:51 +1100 Subject: [PATCH 034/186] Removed unused methods --- src/display.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/display.c b/src/display.c index 2eb4a5855..9960d829f 100644 --- a/src/display.c +++ b/src/display.c @@ -234,8 +234,6 @@ static struct PyMethodDef methods[] = { {"releasedc", (PyCFunction)_releasedc, 1}, {"frombytes", (PyCFunction)_frombytes, 1}, {"tobytes", (PyCFunction)_tobytes, 1}, - {"fromstring", (PyCFunction)_frombytes, 1}, - {"tostring", (PyCFunction)_tobytes, 1}, {NULL, NULL} /* sentinel */ }; From 1ff21dd5b0e0d4c898709e79c0d172fd2f2b743d Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 2 Nov 2020 21:47:57 +1100 Subject: [PATCH 035/186] Updated extra test images list --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index ef7520c0d..15add232b 100644 --- a/.gitignore +++ b/.gitignore @@ -81,6 +81,10 @@ docs/_build/ # Extra test images installed from pillow-depends/test_images Tests/images/README.md +Tests/images/crash_1.tif +Tests/images/crash_2.tif +Tests/images/string_dimension.tiff +Tests/images/jpeg2000 Tests/images/msp Tests/images/picins Tests/images/sunraster From ddd363f7df8374a06c00ebb44bcda746d2121264 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Mon, 2 Nov 2020 23:02:24 +0200 Subject: [PATCH 036/186] Remove excess Travis CI jobs --- .travis.yml | 46 ++++------------------------------------------ 1 file changed, 4 insertions(+), 42 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2966cdf19..e239ed496 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,24 +1,13 @@ dist: xenial language: python -cache: - pip: true - directories: - - $HOME/.cache/pre-commit +cache: pip notifications: irc: "chat.freenode.net#pil" -# Run fast lint first to get fast feedback. -# Run slower CPUs next, to give them a headstart and reduce waiting time. -# Then run the remainder. - matrix: fast_finish: true include: - - python: "3.6" - name: "Lint" - env: LINT="true" - - python: "3.6" arch: arm64 - python: "3.7" @@ -26,42 +15,15 @@ matrix: - python: "3.8" arch: s390x - - python: "pypy3.6-7.3.1" - name: "PyPy3 Xenial" - - python: "3.9" - name: "3.9 Xenial" - services: xvfb - - python: "3.8" - name: "3.8 Xenial" - services: xvfb - - python: '3.7' - name: "3.7 Xenial PYTHONOPTIMIZE=2" - env: PYTHONOPTIMIZE=2 - services: xvfb - - python: '3.6' - name: "3.6 Xenial PYTHONOPTIMIZE=1" - env: PYTHONOPTIMIZE=1 - services: xvfb - install: - | - if [ "$LINT" == "true" ]; then - python3 -m pip install tox - else - .ci/install.sh; - fi + .ci/install.sh; script: -- | - if [ "$LINT" == "true" ]; then - tox -e lint - else + - | .ci/build.sh .ci/test.sh - fi after_success: -- | - if [ "$LINT" == "" ]; then + - | .ci/after_success.sh - fi From b01567fb0b7ce9c5ffa6e2a50bbe993bac11109b Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Tue, 3 Nov 2020 17:31:59 +0200 Subject: [PATCH 037/186] Fix setting PYTHONOPTIMIZE env var --- .github/workflows/test.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3da945f39..8403e2ee5 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,9 +22,9 @@ jobs: ] include: - python-version: "3.6" - env: PYTHONOPTIMIZE=1 + PYTHONOPTIMIZE: 1 - python-version: "3.7" - env: PYTHONOPTIMIZE=2 + PYTHONOPTIMIZE: 2 # Include new variables for Codecov - os: ubuntu-latest codecov-flag: GHA_Ubuntu @@ -80,6 +80,8 @@ jobs: - name: Test run: | .ci/test.sh + env: + PYTHONOPTIMIZE: ${{ matrix.PYTHONOPTIMIZE }} - name: Prepare to upload errors if: failure() From 8ec8d23af47e4f718d1b3a0c1f3cbf645c1be649 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Tue, 3 Nov 2020 18:49:16 +0200 Subject: [PATCH 038/186] Install Qt on GHA --- .ci/install.sh | 6 +++--- .github/workflows/test.yml | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.ci/install.sh b/.ci/install.sh index 77dccaa4a..db259bdca 100755 --- a/.ci/install.sh +++ b/.ci/install.sh @@ -39,13 +39,13 @@ if [ "$GHA_PYTHON_VERSION" == "3.8" ]; then python3 -m pip install -U "setuptool if [ "$GHA_PYTHON_VERSION" == "3.9" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi if [ "$TRAVIS_PYTHON_VERSION" == "pypy3.6-7.3.1" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi -if [[ $TRAVIS_PYTHON_VERSION == 3.* ]]; then +# PyQt5 doesn't support PyPy3 +# Wheel doesn't yet support 3.10 +if [[ $GHA_PYTHON_VERSION == 3.* && $GHA_PYTHON_VERSION != "3.10-dev" ]]; then # arm64, ppc64le, s390x CPUs: # "ERROR: Could not find a version that satisfies the requirement pyqt5" - if [[ $TRAVIS_CPU_ARCH == "amd64" ]]; then sudo apt-get -qq install libxcb-xinerama0 pyqt5-dev-tools python3 -m pip install pyqt5 - fi fi # docs only on Python 3.9 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8403e2ee5..b33b2195a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -78,8 +78,9 @@ jobs: .ci/build.sh - name: Test - run: | - .ci/test.sh + uses: GabrielBB/xvfb-action@v1 + with: + run: .ci/test.sh env: PYTHONOPTIMIZE: ${{ matrix.PYTHONOPTIMIZE }} From 5b2da5f7b0c0186a43c810a3b44d3463487b7df1 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 4 Nov 2020 21:52:00 +1100 Subject: [PATCH 039/186] Link directly to pilfont script [ci skip] --- docs/reference/ImageFont.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/reference/ImageFont.rst b/docs/reference/ImageFont.rst index ff79bdcd8..dbab0f395 100644 --- a/docs/reference/ImageFont.rst +++ b/docs/reference/ImageFont.rst @@ -8,10 +8,10 @@ The :py:mod:`~PIL.ImageFont` module defines a class with the same name. Instance this class store bitmap fonts, and are used with the :py:meth:`PIL.ImageDraw.ImageDraw.text` method. -PIL uses its own font file format to store bitmap fonts. You can use the -:command:`pilfont` utility from -`pillow-scripts `_ -to convert BDF and PCF font descriptors (X window font formats) to this format. +PIL uses its own font file format to store bitmap fonts. You can use +`pilfont.py `_ +from `pillow-scripts `_ to convert BDF and +PCF font descriptors (X window font formats) to this format. Starting with version 1.1.4, PIL can be configured to support TrueType and OpenType fonts (as well as other font formats supported by the FreeType From a357ff12ad38f23190dfcf632fcbd6abd3065bc3 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 4 Nov 2020 22:39:25 +1100 Subject: [PATCH 040/186] Simplified test --- Tests/test_file_ico.py | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Tests/test_file_ico.py b/Tests/test_file_ico.py index ba9f84f5e..a5f728c42 100644 --- a/Tests/test_file_ico.py +++ b/Tests/test_file_ico.py @@ -87,19 +87,15 @@ def test_only_save_relevant_sizes(tmp_path): def test_only_save_append_images(tmp_path): """append_images should work to provide alternative sizes""" - im = hopper() - provided_im = Image.new("RGBA", (32, 32), (255, 0, 0, 255)) + im = hopper("RGBA") + provided_im = Image.new("RGBA", (32, 32), (255, 0, 0)) outfile = str(tmp_path / "temp_saved_multi_icon.ico") - im.save(outfile, sizes=[(32, 32), (64, 64)], append_images=[provided_im]) + im.save(outfile, sizes=[(32, 32), (128, 128)], append_images=[provided_im]) with Image.open(outfile) as reread: - reread.size = (64, 64) - reread.load() - assert_image_equal(reread, hopper().resize((64, 64), Image.LANCZOS)) + assert_image_equal(reread, hopper("RGBA")) - with Image.open(outfile) as reread: reread.size = (32, 32) - reread.load() assert_image_equal(reread, provided_im) From 2ae597c357134a25a6c8ec3da669fedee11bd8f9 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 4 Nov 2020 22:42:53 +1100 Subject: [PATCH 041/186] Renamed variable to match IcnsImagePlugin --- src/PIL/IcoImagePlugin.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py index dc2d6606a..152d2a275 100644 --- a/src/PIL/IcoImagePlugin.py +++ b/src/PIL/IcoImagePlugin.py @@ -52,7 +52,7 @@ def _save(im, fp, filename): sizes = list(sizes) fp.write(struct.pack(" Date: Wed, 4 Nov 2020 22:52:45 +1100 Subject: [PATCH 042/186] Document ICO append_images [ci skip] --- docs/handbook/image-file-formats.rst | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/handbook/image-file-formats.rst b/docs/handbook/image-file-formats.rst index 40db9fe2b..691892536 100644 --- a/docs/handbook/image-file-formats.rst +++ b/docs/handbook/image-file-formats.rst @@ -127,8 +127,8 @@ following options are available:: images in the list can be single or multiframe images. This is currently supported for GIF, PDF, TIFF, and WebP. - It is also supported for ICNS. If images are passed in of relevant sizes, - they will be used instead of scaling down the main image. + It is also supported for ICO and ICNS. If images are passed in of relevant + sizes, they will be used instead of scaling down the main image. **include_color_table** Whether or not to include local color table. @@ -238,6 +238,15 @@ The :py:meth:`~PIL.Image.Image.save` method supports the following options: (64, 64), (128, 128), (256, 256)]``. Any sizes bigger than the original size or 256 will be ignored. +The :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments: + +**append_images** + A list of images to replace the scaled down versions of the image. + The order of the images does not matter, as their use is determined by + the size of each image. + + .. versionadded:: 8.1.0 + IM ^^ From 6806fa1a20e56ef8a7b2102b3f43cbc6cdf73985 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 4 Nov 2020 22:56:14 +1100 Subject: [PATCH 043/186] PNG supports append_images [ci skip] --- docs/handbook/image-file-formats.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/handbook/image-file-formats.rst b/docs/handbook/image-file-formats.rst index 2b6f9483b..e15a02aed 100644 --- a/docs/handbook/image-file-formats.rst +++ b/docs/handbook/image-file-formats.rst @@ -125,7 +125,7 @@ following options are available:: **append_images** A list of images to append as additional frames. Each of the images in the list can be single or multiframe images. - This is currently supported for GIF, PDF, TIFF, and WebP. + This is currently supported for GIF, PDF, PNG, TIFF, and WebP. It is also supported for ICNS. If images are passed in of relevant sizes, they will be used instead of scaling down the main image. From 85e991e5b6f99b97df612a1914ec5c42f6d16f5b Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Wed, 4 Nov 2020 15:36:02 +0200 Subject: [PATCH 044/186] Don't include test-skipping 'except' in coverage --- Tests/test_image_quantize.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/test_image_quantize.py b/Tests/test_image_quantize.py index 192617a52..921c39e3f 100644 --- a/Tests/test_image_quantize.py +++ b/Tests/test_image_quantize.py @@ -21,7 +21,7 @@ def test_libimagequant_quantize(): image = hopper() try: converted = image.quantize(100, Image.LIBIMAGEQUANT) - except ValueError as ex: + except ValueError as ex: # pragma: no cover if "dependency" in str(ex).lower(): pytest.skip("libimagequant support not available") else: From d8d8a2c74d6f9611d2b92313db01e711e51b8319 Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 4 Nov 2020 13:58:33 +0000 Subject: [PATCH 045/186] set xvfb bit depth --- .github/workflows/test.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b33b2195a..51ce9d085 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -78,9 +78,12 @@ jobs: .ci/build.sh - name: Test - uses: GabrielBB/xvfb-action@v1 - with: - run: .ci/test.sh + run: | + if [ "${{ matrix.os }}" = "ubuntu-latest" ]; then + xvfb-run -s '-screen 0 1024x768x24' .ci/test.sh + else + .ci/test.sh + fi env: PYTHONOPTIMIZE: ${{ matrix.PYTHONOPTIMIZE }} From 7e2015c75f35b07e8a050d9fbb4d8db0a472fedb Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 11 Nov 2020 21:05:57 +1100 Subject: [PATCH 046/186] init() if one of the formats is unrecognised --- src/PIL/Image.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index f9a5d82fd..8d3f6b0aa 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2905,6 +2905,8 @@ def open(fp, mode="r", formats=None): def _open_core(fp, filename, prefix, formats): for i in formats: + if i not in OPEN: + init() try: factory, accept = OPEN[i] result = not accept or accept(prefix) From 4f0b9185a3b497a92ca9f251e8e7307bd6a37946 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 14 Nov 2020 08:41:44 +1100 Subject: [PATCH 047/186] Fixed link formatting --- src/PIL/ImageFont.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py index 89d180ce8..3a8a309c6 100644 --- a/src/PIL/ImageFont.py +++ b/src/PIL/ImageFont.py @@ -285,7 +285,7 @@ class FreeTypeFont: the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code - ` + `_ Requires libraqm. :return: Width for horizontal, height for vertical text. @@ -338,7 +338,7 @@ class FreeTypeFont: the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code - ` + `_ Requires libraqm. :param stroke_width: The width of the text stroke. @@ -398,7 +398,7 @@ class FreeTypeFont: the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code - ` + `_ Requires libraqm. .. versionadded:: 6.0.0 @@ -455,7 +455,7 @@ class FreeTypeFont: the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code - ` + `_ Requires libraqm. .. versionadded:: 6.0.0 @@ -539,7 +539,7 @@ class FreeTypeFont: the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code - ` + `_ Requires libraqm. .. versionadded:: 6.0.0 @@ -625,7 +625,7 @@ class FreeTypeFont: the font which language the text is in, and to apply the correct substitutions as appropriate, if available. It should be a `BCP 47 language code - ` + `_ Requires libraqm. .. versionadded:: 6.0.0 From a8b6fc84a3b2155279af4da0da12625d9ebe0e4c Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 17 Nov 2020 23:34:55 +1100 Subject: [PATCH 048/186] Updated libjpeg-turbo to 2.0.6 --- winbuild/build_prepare.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/winbuild/build_prepare.py b/winbuild/build_prepare.py index 6c431f4d6..e6060b9cc 100644 --- a/winbuild/build_prepare.py +++ b/winbuild/build_prepare.py @@ -105,9 +105,9 @@ header = [ # dependencies, listed in order of compilation deps = { "libjpeg": { - "url": SF_MIRROR + "/project/libjpeg-turbo/2.0.5/libjpeg-turbo-2.0.5.tar.gz", - "filename": "libjpeg-turbo-2.0.5.tar.gz", - "dir": "libjpeg-turbo-2.0.5", + "url": SF_MIRROR + "/project/libjpeg-turbo/2.0.6/libjpeg-turbo-2.0.6.tar.gz", + "filename": "libjpeg-turbo-2.0.6.tar.gz", + "dir": "libjpeg-turbo-2.0.6", "build": [ cmd_cmake( [ From 7383e77bf6db75e1bbe46f2ca305837cf4b15dc9 Mon Sep 17 00:00:00 2001 From: Nulano Date: Sat, 21 Nov 2020 15:07:31 +0100 Subject: [PATCH 049/186] add line breaks in test-windows --- .github/workflows/test-windows.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/test-windows.yml b/.github/workflows/test-windows.yml index 4d3619edb..9797b4895 100644 --- a/.github/workflows/test-windows.yml +++ b/.github/workflows/test-windows.yml @@ -91,25 +91,32 @@ jobs: - name: Build dependencies / libjpeg-turbo if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_libjpeg.cmd" + - name: Build dependencies / zlib if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_zlib.cmd" + - name: Build dependencies / LibTiff if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_libtiff.cmd" + - name: Build dependencies / WebP if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_libwebp.cmd" + # for FreeType CBDT font support - name: Build dependencies / libpng if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_libpng.cmd" + - name: Build dependencies / FreeType if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_freetype.cmd" + - name: Build dependencies / LCMS2 if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_lcms2.cmd" + - name: Build dependencies / OpenJPEG if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_openjpeg.cmd" @@ -123,9 +130,11 @@ jobs: - name: Build dependencies / HarfBuzz if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_harfbuzz.cmd" + - name: Build dependencies / FriBidi if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_fribidi.cmd" + - name: Build dependencies / Raqm if: steps.build-cache.outputs.cache-hit != 'true' run: "& winbuild\\build\\build_dep_libraqm.cmd" From 12918605c122281e8e14fd02b54f91ef2033155a Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Sun, 22 Nov 2020 12:41:17 +0200 Subject: [PATCH 050/186] Add logo to docs [CI skip] --- docs/conf.py | 2 +- docs/resources/pillow-logo.png | Bin 0 -> 15681 bytes 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 docs/resources/pillow-logo.png diff --git a/docs/conf.py b/docs/conf.py index b5f8ad59d..a8f101141 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -143,7 +143,7 @@ html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The name of an image file (relative to this directory) to place at the top # of the sidebar. -# html_logo = None +html_logo = "resources/pillow-logo.png" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 diff --git a/docs/resources/pillow-logo.png b/docs/resources/pillow-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..1cc2006a6f78e04c9129bbc911ccbaabd5c1989b GIT binary patch literal 15681 zcmY+r19&D)@Gttt_8aSstxd8U+qSdO#8Yu% z>YAzUuKD$JxPqKG5uO_L2j)=+n9b`=Sz>(4K9w;O%^BT)d%EB}+;|0BOUWw_{?4zUg2;dd zcYRw1wQ(QCcsGmJUkf_1U?z(7-{Jm@isk0e=)A7e^qtfea}}Er?e4*l4=*=CWx|N9 z#G&0q+Tn{P5^W#lFulgzZ5){Qko|^6*-3FAs`(GK3(ZqhlMb99^Kux-TIe{7MHgi} zcwD@pgMp1;JncjEny;;NV4}%;P9lOjfVi_2FNW(5)bAG8BoP%4m=F$Ww5UC>lhmEP z;auJd+>7fM$FyG?g?R(J$$oxc9STw7f~4F8GcC$5a`lUp)!)j`cSrUkx;c4M!eq;5 z^_Dh{ z{73RT0sx$u0e};I0DvnE0Km4(`m4zEbpy^$LemidU?lr5gSi#)yL`Q0O>-3uCkx!4u%*n})i;2nA)s@kemC@G0 zl!=9tlaq=08`HOM3||}!j_x*225t;Cj%5E^$p0fp#Msfu!Q9Tt+|~y4pIie&TW2R; zQqunv{onMz+v#L(^8aeGar{4KeHqB~-yJ3vMrNk}EBmV|&wo@dc?WajFU|kS=VRgd zAI|?D?f>ZEVfs(`|EDqk+tUA`ewoS#&%^Y89~&RMOfQut0KnNNDI%!iwsP(brGc&a z_?dRvcDhnsO)3RTON(V_P`OTM3G*Eb7RxXX2NXdHPg+y}-b@;?wEmUAHecQ*aW9|n zHI){UT!46KV9!;Jv}`M?zpEk?s>jGRPBeN z5Epm(er`|{dEqX)`WY=&>vB@_MI5E2RLke`ZTIxSaM<7AG+VC+%+saz_{O8CwT$&g zpefht-?oN`NX+R5O>z1oYunT5kVY~^{8zaLsoN_4 z?8Q;_v*yr?3oNck(j5|a@rMOxj|{%aMUHn{d`US_Z%Jo{{i#nxZ+HScI%82JJ0y9! zQPJ6{MnAOE*dotbSUajz7j1S_rQ6GquF_fwA)D@dk3vNTj@EDFmxT(H8m@VyAv&oS zLc)5=vvAEKzy9-0tB?7V0LXS)xKn^b`qKPZyh@iU01m77J)GKq*J+Xt3L!ytj)mKv z4_^2i;N}Mk<$yd9zkL*gm{%m@{ZwltA^nX{9T8WB)U!ghhka6oE@9E>a_`>)%;IIW z{^1a$x<4kEPwdsusbWoNGiRj$BiO*Xpb^TpuG(DVV|=$*Ap*Xz;h-vTO_RIl~ zFTQS7adGMV8e$dKM?Syn1)D4(pTXt_FLN2_m|=8ZpbU>Y@InltMi zuBq-Fv8C8GI@vtVLOHQ)rHV)$(Wl+hrO1D^w0`qVL(gufF)jB9mq*QGEwpeP{Wv>S zMl-eCAIgqlM`i8CefMk(m~F}6Xf#b$qn;Q0Y!*~GP$SQSag!6s4+#^7h>uw#Y4^A< zHzeJ^!xW%?14oT0!3AZ-(m;Utp+Px6Y&PP+5*kW>;qX-Q%fB@4jbfoqR@4X6*s6;W z&sqL8Pzvrm(rm$d0ais#K#kW{FX$66o(AQ~ShEOx8)~fo4m9a4n0QB3--Jum4%V+8 zHA}iA&DVmEyge9aB^nz3Tqx2*pNhnb4uMiF0T1&ByEz!g&qVZl`-F*uN@dbZ0aN;2 zM!|J&W3G=Rq3(F?r642}U?sS+SPAnAFFQ3phO8??SJ0#aX<2M1YOjg&l zh6;8d{vW`m?*YHa^IasRo&Kp}RUf$ESXn?J(7{!!T9TGuqmETBfn!Ls_d*UspK49^ zXK;R)@%MtCdo0AAwm97HbfJSHR6){;Q9<{0^;Q)@{kVKa$5Eb*CQfFIrbe>>p9^oRa7vDI{?rEs?n}hz=Vu_!C(iB{S?x`;<_B? zgTWj=ZZL5{&KByT%kV`C>k}!yr{RrCXu}F6oeUNWbdeTKl?n}NG{6catiVjQzM~8Z zmbz%Tm!&o+JKbo=*)k7`Q+Y-Sc*W|M9Qxckx+35ZRx_GCGU4E;$GCVk>FL4!p7yPd6aG&k z+mB0~ZTma9*yLBV1y%-QI-#3rh?i6@O8J~DP71$vujd3PU9uf>XxKxe7a~8qRVA(; z#V6{`jqtQ3yAMTFkG@)8lnU1SoF;;M3@x$4mBZt%6y^?kQp{cX`Mlod z+EtW9#m=XIE1EWG4koEIS;m`uvEKHW+o*-I;rQ2XTj+sYHl21OCe7ORV|fl1t=?nBLAP@q%tsnLP9|F?tAM9Mrp^hcU_ zEHQs|3Xmh^rkiK=55{z02wuuG0a?tEgQuiperaLrtmX`lQyg3DtMp6B1^UDr`L-Jx zTxQWsSb|KQ*hzqJ0!FjM`*di8W0He@!7s*1L0UA?hh*l~dPu57f;1C`o-T8&DB1)l zBEp;9rT#3tx_81(_Q-7q6_R$1L@3X!Dw6$FyR9j{Wi2EJ{?d570W$~J=y?gkKjwuG zEO=$QY||-0l*n}}5JSXt0_M4EJ^~)yJtiq>-=mIpzGA{Xj9Pe{qa1%21=x(3bZIO| zttvGvRKt2x3y|W)tXCkz3=)>kgnSC19YttARstDBKi3W%yJr=E)R=)p1%q!rFNk6T z6IqWfkIhKiB1x#L9@a+%6RWSA=NGz>V4Fd8iW`DKI0P|1UU_cq4n$&pR zVOdNmA&vySJZj9m=-9Uw=yT0;;DFIOm1WA)mi1hQ> z(s3e+yrFOJl$PkW#vG(k1%6+X3(MF^BEsYMl)n8VCM?KV@QL5cX}d?^ejV1eni5JoH2j}|HKSR!6piQ}IMD3xXg(WO+Peph}Dt4Vj}P+`=W zuZ5UG@w5WK?E;=rsHb!$L~ud~Z9w!TKel8|8~UuBS3nJT>(#m068&XPLEKha-TRt-YuaH)oqBj|WhVWdz63I}0n z=J0#wLweg}yw5(W_+65n2bX)5(G<$~SJW$@X1}3V(%_0s1l!&_z|tr~1X|M>N_@;L3EalvM^f;#Imtl(3z+{i?K`2$!SpxAfG?Hh*M%tJ zb*Ep?#v#kpEj_enwqOlz2@=LT6Llnv>a2w*@Bpnr3ju7$e?Bg+fo`BgPw=|K$ri*? z*Emu#(ZdMfMKHOQ%g+fDh7SM9+@`ccc-;@kXRBFiQaZux&7~J8Jwt`22-Z@4`HFoO zMj~e&_$U>{A^?i5Bt~gvh(6Qe&u3|XNc{WXi0h-njAWKh5lqINa9jTb6oD|o$S3ux z&N8TPi(y>9e$LoN77i*Id+*@L6zECuY1%8afXY6~lEidbI`PnczJ60XYi;+vCa9vI zF%Zz?t_RN7P8H%oAF>F?i8AyjS%oYs;ety^a=h6<9#)E7#aY#{=)qXgY(gl*Ck^cM zR@I3+bf;*=XsC7Z7w=WX(Cp(GN!DS7vEW55-R#!3PLKns>GJ)|iJZ*RP)66N3ps~O z9($MeX}5!H;dnN!V|Z<_!tj5>fsJS8>1LNNvCH(nBiztp1vK*v9{IJU;do*1g4-Ic zC1m34`a&3C=?%5`o#IHdv0UMC$?@l2-9={&P*pjiQ6Ry^As`?HUmNOke1!WaYT+hL zWL6;tYmp+ezh#arXSuOUy}xevg+fuE(?J&i(!?6KnE;B=F~J$S@YT|ixoUo4^{vrb ziemL&Pno$0*z^02{;0mV=m`T_%z-E0G#dwW;x(ph!>T#915d1SVd8$RBUy80=!8BZ zR0rr%{QE}-RK+Xu!7oC4~mgc$Xw;5GJ2Fr4-lBK--POLMoxU&0Q67+&bKc zQz|c51y(sCZr)5ZWha)=jw*6Sk~U_5(*pFcIFUv(KR}(Rg_B!D8G_X)s6RoZVX}ao z$t5Q)A?zu`UKN^-g~Z&YM1@$s3|OaK5CChiV*W82y(zUv>3V8fpl9z<1$8k56uPp* zAo!^SZ+e)%os^4Y=p9u@^$+g{83j+*?eYNp<~0GU8h>AV)8rQ6J@99|JhSIL*_hTn z>a6-&sP;c=8Ti&4uJD|Ys{xlDc1v10IHsD<(@ zb;K0JZ}rH=7=a>4sO6Uw5J58~a9^`qIGE5iF*ItqQISMuw>K#tjblyu$Vp-ZlZ!5oz;4F5W9d7T) zyyC6AE^*T?b(7P9#J3p zq~*?dgTWrYD+2Oe3UNUZA;mltD(?o{v#=DTU8B_il2$^O>5W98qo#Zq__=M7tDhI-g^nPu=I0d~eT@SnTcPj!~gU^1MrSmknicHC{Q*x621-#Ig5F^DR z0~``f{hz@TEh?^Xq*76X^s5&d4?_|n>h?Y9-w^DYpM_dhodc8916rqTOAVC~@v~Np zOzzQfROyLH#rFqXsNf7;; zIRpa097JWe-ju-Ae<{f?W~muBig51&MIAcOf6@;TftMAHn#NVMus?A`yrn+HDrU+V zy4`J1ZZlQ~v847A8DN=w6yE-x&>K+ByFKo^py@pkddp!y8uJ`aR>HVm^lBuq5mwO} zcvR_at8>#WJSNn()&!|Ow4!QV@^kFGA`n@Pgft-3@2s@v+HF=a%gM%VsaLU+;>83D z*Kr;FY(ed{5+f-ck$6%i_LJna>}xeau(Hbvw05apn(_Ij#SWrN5DsuQCL25ZgdsRh z`yH>zCv#yNmFUm*=h!?#;?^HX#0Jt_!-JEdE0C+@!AU3%nw|LVU3QkUjR!zT%c2lR0t-65wZA=+ zc0BRK1hc3M1T7C7dA?+Bao4@yQWd;|P~^ij47y=vCU2nMnJ$FE4mPBXPU(7nH~!#mt_zbEF{DcsXWWn>DDCG zJB~ZBrOSq`bAu($Pi9$9>T<+@Yhbu<5>|^Fm_5jfx?;vgsbU=}3&F$Ep~nvdVV}B= zC|Aj$NfYAVe%>4K(vC>hdWrN;B4BW~JjFdFC7ir`V3wv=BO&So8OfroFN2n(sHhpUtW6Lj$#}_QjB9@euw~O|v+XlJIxAz*uoRhBTDrlYAVv_;Oa9W)2S2zp`QI?z+ zvUKCDE;U?m=r=_VV_#{P)1yCuN0Z{vEWz6Ds&PWNQDdHr!iDk4MGjd(sjf8V!ue@V zhG;vVKkbY8OBNUr#C0?BxYZhZ;?CSrr+A2MUQ7n7%9iWu92vpo!OpaN9EnN)$sDKQD3n;PRY(6h2E6o?ULm67pgh*)9LoSX#wo zIQ=1V@vW=(uNRFQIYqhZpCD%>$HppixKwB?GwuD`v?{*x>$Zxn;*5`!VULupf{c5v?Shg(#3$R3C#MJU_ACqRt!MW6dIuT!?C^q=D? zZWhJQt{yo$fwZz?s4&v@Bt8Y$9G(_>L_{3CF~*a>Ne@$Rl*GKAJrGH1ezgjp`hL{6 zu>m4A%i^X6yMJ4lfU$C?ig>}MR$!1VPBN8jM;m0|@{C3Fs-NYsK3)`iNo$&#Kvcjo zwcoXWZemde_08qsaO+VCPfXH7hQo;fpH!F-x=#Tf_kP9nuBuJ0NIwKz3;z8g3E&hHpvOum6- zinh$0JNKqq@9>Fg9RaH&sdl>01l4po25&bdIM@$3M#97fUQ5D=4_!3~(cTnHtr+|N zq0UCZgVGgHij8e0O3+B~K*3*ne4Ks?8Hex!9J#1#Krm9s-8KN}hy*++0yR00k6htN zR6#T+%;}7UCdHYqO{&1gy(?_Q+wpXvs#j9eUCL1owpOlAXD%gh#1Z{u?d~;wD^pJ9 zt%7d1R82`I7a+)>`b-pnO)Ro9pm*(0n#(gN?-x#v>vgIwB%n$rQi)F6h2ZDlIroq2p#n+r@eX)1Wc2xMQ~J(&ZZ7j11ur-bfImzN33|_;*3* zur>9l1VymLjcLGZwiq*r8~g?IUig%hkV0!Y&jwNw@d)Z4*gw<^+6F$<46uVaZ|>8$wY=iOsfy+z^7#&VEz zTK>*&!A3!O_@XQYdRZKSHNO0R)pQpaOeuDJ(9JV8iVHeLxS+I18Fk4yQ&Q0ZCT&m_BRvQ->to!TYzWf zbFX!u0^zYT$V!ep!6m+ecf6pBMWs?v>UR@(4B+3~zR5@7v{>I%|(}?%5;8lM8?Pip#^#>vZ!wrL;g+FOs`|JnSKEbW{dZ@gi z;&aO0OB3o-$4JCw?gKOMsCbp}V^-_})H#fPYaO18+BAV-!kVZwP7+|CNjIh8-tOl) zfFgpIp`YEdln1;r6l~MDbm2VhxfDD|ihp^L>Tii(>TT^pG4s69QTVgyb8JI#Njn!M zNv%41jeZ%^h-3IHoIwiJL(*Z~(I}ka&vt+i%>7$XFIs>&4>C0A@;Iqo(m~_d&*_d> z(#wagESD|ayQ`ueYLUdd??rS5zvdlaZKw>aCtcE3+nBz8XAIY9gXfqjrNvs(Fvx2{ zlWWo53QG*aUN!Y@Mum)9n$4|^3vwNER#=irs=PqQ$3(3f6OfY5hGVn}(s^=Z$N5gk8IiIbujrz(IXQ{#f1A zziw8)iZt+mo4lXAJ4Nx0+e9KA$z9-tg$PQQ8Z#{(p~DBtFOp}^z%-=ne+%Q7gUh$b z1qwVt(M#P%HL;i~5-Oskh>xDFY?z`W$D|jYfIfw<NQH! zj;zxrJ~nx7;DG@`>a?~j+QbpQsBd;Jqb`8=r8>IrDOCSfkdx1+#(Kfo`g$TZAka7s zfgvB129ka7X6k+Dyw+0sQL1QX*|gghc?{@$?Wwv2N55+%{P+#u;RqL42p0{`|N^--|2x&#rGga?nLg$6w6-2@7h#a9JT1e2y4kw6F0 zlH70e2uUD;-zl71naWuci@;Wh!L|s_4;@Q3X&zI}YbrpfMk9(e^tTdInme$!;0V&fOXOku8! zgM39#H_%fGs8dvHSzriqx29hr6kaQiuD|E#v}HPIl@t0kJ@FD|55rOZSVW+Nrzv2UEH72)*5=XZSpE zs3EzX;muTQ@ab5&`3lTL;S+9@k*EG3(0=3A@RsCX0WH{{)IBfYqc6{x-34#v{;=7uWg0r`h|fL>=` z1ObhwSpe!}Be=-3?78`{5ao@4IdL$A@@kOk{Hkb+xYh{OZOFR%%nJ>XsHwm44;c-I zY(R-1>|<)P0v@)rb^@+^X;ShUu?+-oTj9#%aG}kcpKDS&gT!-&$&tbY?7K8j2$TXyxsdlh3~V=D+ED^3Q6o}k3@sh8Gyy@JP-wT zzIBKZlQ&<23Uo)7R?8Jun1iC%^@h$zE2-l-0jh~)3+(;H(CB!eCS4>RdO;GewV1c5 zgkANYr*ko!uP4;NY|f^JrV}neYyL$h^tMPsu1`3yNHXIKwSzS-aF*4xw9k##<|Sru zn*^qDxq`yoE>3FG$-2T<_tnkGVNhFZ5Ur$c z6#!|$Nt=S(UY?0ugSk;Vnv-5z%?`xrHNXuS^N;)yZuLe@GPm-B8v3ib8mVxXJ>!jy z7W?1iMbmK1-os=P+uAdmI=}H%pFrxfYQ9?~=n461s;qN#1`$|l1I(obLBr8!TQikd z?OdvZr50Wp>b>>x=f^-uK<7 zf6%bj#Z*U>y(Oc*}_!x^84U)enzA9@+1fiiFo2mHPnZyBm1Ih!#W z>Qys)DBvoG4C|c?Mce`1CG#rAH}s<1*(-Nn z!sozLoIR^^IRI3qFB2=yzAAD+;`0!q@(zJzc7zxv9x7Pnup;7{q6~OUZfhK`2>M#I zy+L2|8pkPlRwy8$Vu9eDFsQf&S}gftacjKs=N9WVIUA<^&6<}yA(wjt zfqNQ!~t=*TCY&-h}nnY5gq=RqT#MQB@BPj{JukfYlzAMya?uh#x zBsatDm~Zp2MD%jz$OB#~Zbf^>qW#|aPjp4^;hT$!v?yJ6+gUs)W%uIlNo5K6##Xm^ z2Fc)NN}bFZz-Ez(@{}W$#jMXy03{d42!PZ64wh>LuVPRz*`CbZgmy24r6$!r7X zT#HRGaxi+TT~oQyYC)tp#yaD-^=R?Yd>JNzNAu8Dbyb*FU!A;o6yXvQ+3P#p(8qeM zTNH2e7+x^p?NB2Aehf#~a9ED?LXRn1^J}zVWiG;ZH%|TaN|Law4dRO7rqw-88EBcg zsC>w=ZCCm8Z`ZzfKPrZmOyNL z4PEO;b*$FBwL-HJluCV*zizh0(NY29i;G1Rm~KXIohw}nvQ;c@Ut9N3E7jZJqi9|x zubK?L3|koe6l!HUZ&oEV+;f0EN23+i4mhPzA5Vt38`6-+C7K9Xoxj=a8rl+%E#!B1 z6ycyDK#=T3wEiLyY~~#PD0Qcog)cqf;&QD|4~MXaUaKmEh}ja;iWsal4?^IS$h8PI z%{W>!GSAVOShy2B$BuiKKg@SdeqHA{ChQ{LEG$22p;4@Wldd5x)kak;C*He7QgMg@r1-N>hJrsa*73-jaS9Wq}dN#T1n+tpO$Tjg@Z_U_n}MJ6=QE9~zWgKEG|GdNCGykH z&=2)Q9K@@K#6RRVcwdW$%*fXeS2Mt9RmA6oNgTk5nxBP1Wrik65NL|18fx?j1HtFc zz-&Xtg{2GExhZgt|IU1i<~);_6vtPo9+fa52*xv{46S#;3c!)Si@&(8X6QFp#1$d! zhzX9#y%ovbF`&tIQ-uh+S;OA9`-tV4K5Qo6|4kPlI++=%ibFyCM{pw_D^u@nOa+Z7 zxpp3v`^_OYso9b5g4@zfN}2N--%W~``W>;(o$4_&Y&6cFlrIf*8+xhOnww-QBrsI* zl5^5hDi5Lj^C$hb!@m92cLg5CB6~GA@poK?!TZEss_730npSnGL+gEPDzElE%&Lt0 zD*eSg9;;K$f;wx=#=7c=ji%GS1(|@|mPyCB#35uOh2I5fyGwxr)7jlqFw&A&!s{;> z@l*0gp_qx#`uj=#U$F+N5Y;^u62D)NCyv@AL5wOZL2Ux{Tz1YRPQbmRm?3*G-P&uS z_I?y$q)x4~KbfJIIk;Tc??djHU)~%A2T=n3X9keeQrzBgi1fwDds++xO2S>NUIsfT z-wTf+9KJ9-uxnGc|9~*#PM|h_ZLsj;0EOaeP}vna0&{X~4`|^H;yFB_?5E=0t#fBY^w7Md zOoy$NZs2RrBpvsG52j^WO&(Bz68q|5{>T9nYh>>j-P7$}ko2 z>7A^C0jbS)R?1+`zKL6$EodpN&iOpqWm$4z8Rqh8{Trw(9c_$bRgp0lr{F`bQ_oyY zbK}I*GCxe?vKM~0iT1we6Av`u)>m~|n|R{nyQBek((6t4<&GwG{BCL5ncRGb?(sJ;?wDrKtpjD9jJ{v=aX_TY1SWYA+%|Jd(+{DLh?eo?4? zE^K=yix&6a7l%%Urz|%3%yx}RMA@-O@LxlQFAhEb)+f#0?7&xNX)G^<%lwWrYJPJj z39vt($6gvQ(M zpj6z39kV^S+}GlK0UIoC_u6Z}*5#x^#z*?;UiEsttC#fM+h%c5Z}&rup$HnbO|~%j z3+8gwr}>yy#JFDeJ&;w~SAIUeukh_JvdFyol>YYl&&y(4^)oiEYu7ihaEsB~u{G;Q z6K^UTCTZt;5@)L2%7-|j9? z2Tt_VvH#>~^&w(RplGdiCJBzTvp*%xTH6YAoJO!WZ{ugQy`|V1o6}wWgLn9YX)0Ii z)SRPX8T*Gz=+4<+O}wxDFZ^%0ZYEzUU$ns-J|~c5o@S*m_*T*CdX(#Ilc{2=(?c7y zu@cy?2H?O4;w6|!<-vyuIDI%AzJr-U`x|^muE`1K9W61iO~aqCLV$L<`HY_us2SMz zwyd*#{?)g9G{DiYAZ+CJxJL{HYYR{+CDH$P=tG?Y78gaQ3%K5orGF!r#Cvt|)gQ@w zfVDf7o|E5rTHQO1!uhOQ5_ODksVxgbN)H&99yF?Z1ypJtMXBD3>1WqqXl84MArbtZ z^@{6aBfQ&LY0?489sF316&st&T@|WUPilj{>~yH}p%!5L+0K#h$j+$yw~$2t*MFu` z`i;50ToL)kvluYv{yAB|X%KfBEC_$!-e1D}sP?Y4deIkoZPj-@BDd0F3o)a232jZB zzY^HAy{^S7#6pJr9E}?H0@m; zEa(Re%^a$PTSH_|!haUa0u;Xkxdm#3y9W2!)-x9Ug-b%xE~em=L!JC$rBR+_j{-4S z3IBaT`>?Qr$}c2VF9KFNTVY6do|fGl8DniD827v+M$RiJHx+diS0COa(BOz#E?sx8 z<^^5czY4^xg5S!Zk7L3A1tVaG+|Dq9k>`ZPTH5hIfN<3_0Hk~Xm#j@P_ZG`j4@7g2 zdB@#V|H6#VrAIkkzwtIKLB@>=@x?;5fMG3 z^goY&p``0Qw5&Bt$uxP(#dL1Se(fDCV&VyL?Wv5{-P)f+`mlL`P5UKZjXf?~j6~{( z*i(;-tic+qQ|bP@&N-aUg)vhO%b30yCT5X%{cEAEC-L6$Fj{2pjPGTsHXY6o+xsfE zk;q~zo7c0M!2cJa{|=HidQPqKn;Nvhx9U6C#G8#vwv>%hV`-Kn6q=s(&iEd04fQdX zlVGUbm)^;FB0eJzrS`=`$v2T=z8m`_W)$$TC=v~JQ}TtE7~#8w;ibJptECqGAcMd^ z-o4@0bjiOd5qt{w74%MY)xaeU3iu8uvbmi;-kvR|r>FUi|Leqb0&|~)sq$b{?Y{2> z@&0^iD_vzKLaFd8?tR)vUPBLTV-9Cvo7WE--<+wzi;=~;_xx{oD7+37Dj)E`KCgKZ zr74}JpSiv-K+7MOEq73&uDCKKv1-VjaDCGJ_;ww`12*s^&Vc+&=hG&RIwj~6%?vQ@ z+3_7reKJ=}M}-=^BsxHQb8zK4d(`3pv9d_>Y)*o8GC#&d>=O?!wsW3cu-ex`-7UJO zE=|?V;S~K2@A;GaCKXk9cXwC19P<0DZ@%vcN!u9i?`(VTSWuZB3FlGK81cZ9>j~a7pqf>lJUjDM&HCaO6WzBkNzwx9UrK zY4i>aGGCT~jL-4RC;qbyk&l1_)Yh;^`4PHH*$Qm%&ciK(!DRdQA2l+=Xb9}Yf}bg_ zh@_;X^^QNUo3)C8)Vm`sAEsbE)nZs>HtUtibm|i(#>UAVBH`$qX%Rr0UNt|OlBz1} z>T2D#1HvCRIzA{Uu>myE>d&7wctl>|#a&mG|Umr!OH8$&i-Kj5YvbwzT zZ@O@Bao4@q4ANy>sfY|ppsFFs4Q3DwcL>U%=>v+ zR5qrRLP?pDwb8D@!up~cFv`NDHCL)pXDHg@RbB(~ryyRRv{s#>rGhy81dtgI1EdD; zHv!^USOQpL($b@P(Qv5rr9x(rnYiicsq{bF8_VL&TN5axRG1k|w1R)FF0{K{pOF7+ z8k0^cHBxJL<89b6@zub|T=>JxZmlrWUzjiSmN~<|b(j@1n+c>d5x>S$$zez~6*g97 zWBEp7Yh$Go0@lA($6QZ6l4sDZfmQpa3Kp3JmK1eL3@L7c#kGC1N7hO|rj^~TkPtK< zQ7Iw{9avV!0+G+iYc5dU6>e@ndvHKW$w0F)*ywisKsiWB7{-->pXpTKnGNNPHkW>> z{2~W*0o68<*)@IzP%{xDmV(#CNq!BJhxG*}a-_6_W64@~meXeTbJf^YNpA>>~ok@d35YH$uhnvEENX)V8MwE4$SNfr!l zXi9DR=AT%DgT+?Um9YJ1FL2Tcb>x}$?{)|`P@uDkTIqpXIF}Mwg5>3B!&Hf8g2Lm^ zNsF{*)5vZROR}J022g@85pF%P$DjaO9DAU^&KM!KoX}SwK7h-5v5D+k{nbq zf6>rpy!Q3)YCshCmG>-DwQBeRB5X5`j-26RM7Lu4&i=B))vugtL&TrZ_W3t@nz4x3 zbh|I60=?B(Om*KB-1Z|5$;i{XG$X>fYSgabfs@i26|83e4(sBnPU+{^wkd1p3>U*F z51KF%q1F!%t#FrU%P0?%TX-4_O^lb7(r|IpM=_ib$lL>dmYYq#A?oCi*}n$u|4Z}z z8icap+LFx5Qo;J@v@1I_HI{p?bcz}+T2sS=Gg7^mF%3_R46O1=jg+OYWyb6ye1C4R z|1bnNxFd=&>Q(0L?|8KOKmiH4P0qr Date: Mon, 23 Nov 2020 07:08:05 +1100 Subject: [PATCH 051/186] Updated libimagequant to 2.13.1 --- depends/install_imagequant.sh | 2 +- docs/installation.rst | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/depends/install_imagequant.sh b/depends/install_imagequant.sh index ae70bde8f..ed438f904 100755 --- a/depends/install_imagequant.sh +++ b/depends/install_imagequant.sh @@ -1,7 +1,7 @@ #!/bin/bash # install libimagequant -archive=libimagequant-2.13.0 +archive=libimagequant-2.13.1 ./download-and-extract.sh $archive https://raw.githubusercontent.com/python-pillow/pillow-depends/master/$archive.tar.gz diff --git a/docs/installation.rst b/docs/installation.rst index bb8c06580..0d28b8347 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -177,7 +177,7 @@ Many of Pillow's features require external libraries: * **libimagequant** provides improved color quantization - * Pillow has been tested with libimagequant **2.6-2.13.0** + * Pillow has been tested with libimagequant **2.6-2.13.1** * Libimagequant is licensed GPLv3, which is more restrictive than the Pillow license, therefore we will not be distributing binaries with libimagequant support enabled. From effb351d09daf2bd4327ddccfd1943433db3f3ca Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Tue, 24 Nov 2020 12:25:40 +0200 Subject: [PATCH 052/186] Don't add light mode bg to 4th level menu items [CI skip] --- docs/resources/js/script.js | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/resources/js/script.js b/docs/resources/js/script.js index 3bc216c2d..d58571d6d 100644 --- a/docs/resources/js/script.js +++ b/docs/resources/js/script.js @@ -30,7 +30,6 @@ jQuery(document).ready(function ($) { if (!$upperA.find('.toctree-expand').length) { $upperA.prepend($('').addClass('toctree-expand')); } - $a.css('background-color', '#c9c9c9'); $a.css('padding-left', '5em'); } else { $a.css('background-color', '#bdbdbd'); From dea2eb54affa99f213eb9cafff4fefbcb2a5e5ca Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Tue, 24 Nov 2020 13:10:01 +0200 Subject: [PATCH 053/186] Set background-color depending on dark/light mode --- docs/conf.py | 1 + docs/resources/css/dark.css | 4 ++++ docs/resources/css/light.css | 7 +++++++ 3 files changed, 12 insertions(+) create mode 100644 docs/resources/css/light.css diff --git a/docs/conf.py b/docs/conf.py index a8f101141..bd17da0e6 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -310,3 +310,4 @@ texinfo_documents = [ def setup(app): app.add_js_file("js/script.js") app.add_css_file("css/dark.css") + app.add_css_file("css/light.css") diff --git a/docs/resources/css/dark.css b/docs/resources/css/dark.css index c746e76cf..2ed958429 100644 --- a/docs/resources/css/dark.css +++ b/docs/resources/css/dark.css @@ -1196,6 +1196,10 @@ color: rgb(166, 158, 146); } + .wy-menu-vertical li.toctree-l3.current a { + background-color: #363636; + } + .wy-menu-vertical li ul li a { color: rgb(208, 204, 198); } diff --git a/docs/resources/css/light.css b/docs/resources/css/light.css new file mode 100644 index 000000000..ae3debc91 --- /dev/null +++ b/docs/resources/css/light.css @@ -0,0 +1,7 @@ +@media (prefers-color-scheme: light) { + + .wy-menu-vertical li.toctree-l3.current a { + background-color: #c9c9c9; + } + +} From a89705493098e009f311d212b94d7393a5a7e011 Mon Sep 17 00:00:00 2001 From: nulano Date: Tue, 24 Nov 2020 12:53:42 +0000 Subject: [PATCH 054/186] GHA: make windows cache depend on VS version --- .github/workflows/test-windows.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test-windows.yml b/.github/workflows/test-windows.yml index 9797b4895..91d41fdb0 100644 --- a/.github/workflows/test-windows.yml +++ b/.github/workflows/test-windows.yml @@ -64,6 +64,7 @@ jobs: run: python -m pip install -U "setuptools>=49.3.2" - name: Install dependencies + id: install run: | 7z x winbuild\depends\nasm-2.14.02-win64.zip "-o$env:RUNNER_WORKSPACE\" echo "$env:RUNNER_WORKSPACE\nasm-2.14.02" >> $env:GITHUB_PATH @@ -72,6 +73,9 @@ jobs: echo "C:\Program Files (x86)\gs\gs9.53.3\bin" >> $env:GITHUB_PATH xcopy /S /Y winbuild\depends\test_images\* Tests\images\ + + # make cache key depend on VS version + & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" | find """catalog_buildVersion""" | ForEach-Object { $a = $_.split(" ")[1]; echo "::set-output name=vs::$a" } shell: pwsh - name: Cache build @@ -80,7 +84,7 @@ jobs: with: path: winbuild\build key: - ${{ hashFiles('winbuild\build_prepare.py') }}-${{ hashFiles('.github\workflows\test-windows.yml') }}-${{ env.pythonLocation }} + ${{ hashFiles('winbuild\build_prepare.py') }}-${{ hashFiles('.github\workflows\test-windows.yml') }}-${{ env.pythonLocation }}-${{ steps.install.outputs.vs }} - name: Prepare build if: steps.build-cache.outputs.cache-hit != 'true' From e095391a3532e72d95f8df487369c99fd5ac237b Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Fri, 16 Oct 2020 17:17:51 +0300 Subject: [PATCH 055/186] Add release drafter to draft releases --- .github/release-drafter.yml | 14 ++++++++++++++ .github/workflows/release-drafter.yml | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 .github/release-drafter.yml create mode 100644 .github/workflows/release-drafter.yml diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 000000000..0412bd9dd --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,14 @@ +name-template: "$NEXT_MINOR_VERSION" +tag-template: "$NEXT_MINOR_VERSION" +change-template: '- $TITLE #$NUMBER [@$AUTHOR]' + +exclude-labels: + - "changelog: skip" + +template: | + + https://pillow.readthedocs.io/en/stable/releasenotes/$NEXT_MINOR_VERSION.html + + ## Changes + + $CHANGES diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml new file mode 100644 index 000000000..52456597b --- /dev/null +++ b/.github/workflows/release-drafter.yml @@ -0,0 +1,17 @@ +name: Release drafter + +on: + push: + # branches to consider in the event; optional, defaults to all + branches: + - master + +jobs: + update_release_draft: + if: github.repository == 'python-pillow/Pillow' + runs-on: ubuntu-latest + steps: + # Drafts your next release notes as pull requests are merged into "master" + - uses: release-drafter/release-drafter@v5 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From e377d243b167dc1a053c01b3fd21765425f78411 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Tue, 24 Nov 2020 23:25:20 +0200 Subject: [PATCH 056/186] Remove soon-EOL Amazon Linux 1 and CentOS 6 --- .github/workflows/test-docker.yml | 2 -- docs/installation.rst | 4 ---- 2 files changed, 6 deletions(-) diff --git a/.github/workflows/test-docker.yml b/.github/workflows/test-docker.yml index ddec1bee4..6acb6cf70 100644 --- a/.github/workflows/test-docker.yml +++ b/.github/workflows/test-docker.yml @@ -15,10 +15,8 @@ jobs: ubuntu-18.04-bionic-amd64, ubuntu-20.04-focal-amd64, debian-10-buster-x86, - centos-6-amd64, centos-7-amd64, centos-8-amd64, - amazon-1-amd64, amazon-2-amd64, fedora-32-amd64, fedora-33-amd64, diff --git a/docs/installation.rst b/docs/installation.rst index bb8c06580..279d78704 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -422,12 +422,8 @@ These platforms are built and tested for every change. +----------------------------------+--------------------------+-----------------------+ | Arch | 3.8 |x86-64 | +----------------------------------+--------------------------+-----------------------+ -| Amazon Linux 1 | 3.6 |x86-64 | -+----------------------------------+--------------------------+-----------------------+ | Amazon Linux 2 | 3.7 |x86-64 | +----------------------------------+--------------------------+-----------------------+ -| CentOS 6 | 3.6 |x86-64 | -+----------------------------------+--------------------------+-----------------------+ | CentOS 7 | 3.6 |x86-64 | +----------------------------------+--------------------------+-----------------------+ | CentOS 8 | 3.6 |x86-64 | From 5abdbe12313162e40e6e9e65e7793d808fad8fb0 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Wed, 25 Nov 2020 00:02:34 +0200 Subject: [PATCH 057/186] Sort for easier reference --- .github/workflows/test-docker.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test-docker.yml b/.github/workflows/test-docker.yml index 6acb6cf70..f6814f932 100644 --- a/.github/workflows/test-docker.yml +++ b/.github/workflows/test-docker.yml @@ -11,15 +11,15 @@ jobs: matrix: docker: [ alpine, + amazon-2-amd64, arch, - ubuntu-18.04-bionic-amd64, - ubuntu-20.04-focal-amd64, - debian-10-buster-x86, centos-7-amd64, centos-8-amd64, - amazon-2-amd64, + debian-10-buster-x86, fedora-32-amd64, fedora-33-amd64, + ubuntu-18.04-bionic-amd64, + ubuntu-20.04-focal-amd64, ] dockerTag: [master] From ece157b09cb5418e69de1153b892203ebd60feb3 Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 25 Nov 2020 06:58:13 +0000 Subject: [PATCH 058/186] install raqm on macos --- .github/workflows/macos-install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/macos-install.sh b/.github/workflows/macos-install.sh index fb8869c7d..afcb9a5a7 100755 --- a/.github/workflows/macos-install.sh +++ b/.github/workflows/macos-install.sh @@ -2,7 +2,7 @@ set -e -brew install libtiff libjpeg openjpeg libimagequant webp little-cms2 freetype openblas +brew install libtiff libjpeg openjpeg libimagequant webp little-cms2 freetype openblas libraqm PYTHONOPTIMIZE=0 python3 -m pip install cffi python3 -m pip install coverage From 74048f9b4ffd0bfee645cd13f276a888434332d1 Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 25 Nov 2020 07:27:11 +0000 Subject: [PATCH 059/186] remove FT 2.3 from tests --- Tests/test_imagefont.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py index 7824b7f53..f779463e6 100644 --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -35,14 +35,6 @@ class TestImageFont: # Freetype has different metrics depending on the version. # (and, other things, but first things first) METRICS = { - (">=2.3", "<2.4"): { - "multiline": 30, - "textsize": 12, - "getters": (13, 16), - "mask": (107, 13), - "multiline-anchor": 6, - "getlength": (36, 27, 27, 33), - }, (">=2.7",): { "multiline": 6.2, "textsize": 2.5, From 86993df834ace1e6bbe0a05ebd8d288a601eeb9d Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 25 Nov 2020 07:38:13 +0000 Subject: [PATCH 060/186] remove duplicate values --- Tests/test_imagefont.py | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py index f779463e6..06ed42658 100644 --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -35,22 +35,8 @@ class TestImageFont: # Freetype has different metrics depending on the version. # (and, other things, but first things first) METRICS = { - (">=2.7",): { - "multiline": 6.2, - "textsize": 2.5, - "getters": (12, 16), - "mask": (108, 13), - "multiline-anchor": 4, - "getlength": (36, 21, 24, 33), - }, - "Default": { - "multiline": 0.5, - "textsize": 0.5, - "getters": (12, 16), - "mask": (108, 13), - "multiline-anchor": 4, - "getlength": (36, 24, 24, 33), - }, + (">=2.7",): {"multiline": 6.2, "textsize": 2.5, "getlength": (36, 21, 24, 33)}, + "Default": {"multiline": 0.5, "textsize": 0.5, "getlength": (36, 24, 24, 33)}, } @classmethod @@ -387,7 +373,7 @@ class TestImageFont: mask = transposed_font.getmask(text) # Assert - assert mask.size == self.metrics["mask"][::-1] + assert mask.size == (13, 108) def test_unrotated_transposed_font_get_mask(self): # Arrange @@ -400,7 +386,7 @@ class TestImageFont: mask = transposed_font.getmask(text) # Assert - assert mask.size == self.metrics["mask"] + assert mask.size == (108, 13) def test_free_type_font_get_name(self): # Arrange @@ -444,7 +430,7 @@ class TestImageFont: mask = font.getmask(text) # Assert - assert mask.size == self.metrics["mask"] + assert mask.size == (108, 13) def test_load_path_not_found(self): # Arrange @@ -625,7 +611,7 @@ class TestImageFont: assert t.font.glyphs == 4177 assert t.getsize("A") == (12, 16) assert t.getsize("AB") == (24, 16) - assert t.getsize("M") == self.metrics["getters"] + assert t.getsize("M") == (12, 16) assert t.getsize("y") == (12, 20) assert t.getsize("a") == (12, 16) assert t.getsize_multiline("A") == (12, 16) @@ -861,7 +847,7 @@ class TestImageFont: ) with Image.open(target) as expected: - assert_image_similar(im, expected, self.metrics["multiline-anchor"]) + assert_image_similar(im, expected, 4) def test_anchor_invalid(self): font = self.get_font() From fba3ece341566b625f0e8ce699cd35fb27479478 Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Thu, 26 Nov 2020 01:01:38 +1100 Subject: [PATCH 061/186] Updated libraqm to 0.7.1 --- winbuild/build_prepare.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/winbuild/build_prepare.py b/winbuild/build_prepare.py index e6060b9cc..fd5ac40f0 100644 --- a/winbuild/build_prepare.py +++ b/winbuild/build_prepare.py @@ -300,9 +300,9 @@ deps = { "libs": [r"*.lib"], }, "libraqm": { - "url": "https://github.com/HOST-Oman/libraqm/archive/v0.7.0.zip", - "filename": "libraqm-0.7.0.zip", - "dir": "libraqm-0.7.0", + "url": "https://github.com/HOST-Oman/libraqm/archive/v0.7.1.zip", + "filename": "libraqm-0.7.1.zip", + "dir": "libraqm-0.7.1", "build": [ cmd_copy(r"{winbuild_dir}\raqm.cmake", r"CMakeLists.txt"), cmd_cmake(), From dd1a514346841ce3baddd78be5806806a4141fae Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 25 Nov 2020 21:40:16 +0000 Subject: [PATCH 062/186] update FriBiDi to 1.0.10 --- winbuild/build_prepare.py | 6 +++--- winbuild/fribidi.cmake | 2 +- winbuild/raqm.cmake | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/winbuild/build_prepare.py b/winbuild/build_prepare.py index fd5ac40f0..178194ffe 100644 --- a/winbuild/build_prepare.py +++ b/winbuild/build_prepare.py @@ -287,9 +287,9 @@ deps = { "libs": [r"*.lib"], }, "fribidi": { - "url": "https://github.com/fribidi/fribidi/archive/v1.0.9.zip", - "filename": "fribidi-1.0.9.zip", - "dir": "fribidi-1.0.9", + "url": "https://github.com/fribidi/fribidi/archive/v1.0.10.zip", + "filename": "fribidi-1.0.10.zip", + "dir": "fribidi-1.0.10", "build": [ cmd_copy(r"{winbuild_dir}\fribidi.cmake", r"CMakeLists.txt"), cmd_cmake(), diff --git a/winbuild/fribidi.cmake b/winbuild/fribidi.cmake index 112174731..47ab2c329 100644 --- a/winbuild/fribidi.cmake +++ b/winbuild/fribidi.cmake @@ -99,4 +99,4 @@ add_library(fribidi STATIC ${FRIBIDI_SOURCES_GENERATED}) fribidi_definitions(fribidi) target_compile_definitions(fribidi - PUBLIC -DFRIBIDI_ENTRY=extern) + PUBLIC -DFRIBIDI_LIB_STATIC) diff --git a/winbuild/raqm.cmake b/winbuild/raqm.cmake index e8e71800e..82c9cdc70 100644 --- a/winbuild/raqm.cmake +++ b/winbuild/raqm.cmake @@ -7,7 +7,7 @@ find_library(fribidi NAMES fribidi) find_library(harfbuzz NAMES harfbuzz) find_library(freetype NAMES freetype) -add_definitions(-DFRIBIDI_ENTRY=extern) +add_definitions(-DFRIBIDI_LIB_STATIC) function(raqm_conf) From 6f64eef699b571874b34641c6561c8a948e81a12 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 27 Nov 2020 15:12:14 +1100 Subject: [PATCH 063/186] Updated instructions now that draft releases may exist [ci skip] --- RELEASING.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/RELEASING.md b/RELEASING.md index dac0ba731..5e00e5724 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -24,7 +24,7 @@ Released quarterly on January 2nd, April 1st, July 1st and October 15th. ``` * [ ] Create [binary distributions](https://github.com/python-pillow/Pillow/blob/master/RELEASING.md#binary-distributions) * [ ] Upload all binaries and source distributions e.g. `twine upload dist/Pillow-5.2.0*` -* [ ] Create a [new release on GitHub](https://github.com/python-pillow/Pillow/releases/new) +* [ ] Publish the [release on GitHub](https://github.com/python-pillow/Pillow/releases) * [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), increment and append `.dev0` to version identifier in `src/PIL/_version.py` ## Point Release @@ -56,7 +56,7 @@ Released as needed for security, installation or critical bug fixes. ``` * [ ] Create [binary distributions](https://github.com/python-pillow/Pillow/blob/master/RELEASING.md#binary-distributions) * [ ] Upload all binaries and source distributions e.g. `twine upload dist/Pillow-5.2.1*` -* [ ] Create a [new release on GitHub](https://github.com/python-pillow/Pillow/releases/new) +* [ ] Publish the [release on GitHub](https://github.com/python-pillow/Pillow/releases) ## Embargoed Release @@ -80,7 +80,7 @@ Released as needed privately to individual vendors for critical security-related make sdist ``` * [ ] Create [binary distributions](https://github.com/python-pillow/Pillow/blob/master/RELEASING.md#binary-distributions) -* [ ] Create a [new release on GitHub](https://github.com/python-pillow/Pillow/releases/new) +* [ ] Publish the [release on GitHub](https://github.com/python-pillow/Pillow/releases) ## Binary Distributions From 3d80b743427f3b93722f27b2c2fbdada7890d45f Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 27 Nov 2020 18:50:31 +1100 Subject: [PATCH 064/186] Updated macOS tested Pillow versions [ci skip] --- docs/installation.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/installation.rst b/docs/installation.rst index bb8c06580..de97d7676 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -469,6 +469,8 @@ These platforms have been reported to work at the versions mentioned. +----------------------------------+------------------------------+--------------------------------+-----------------------+ |**Operating system** |**Tested Python versions** |**Latest tested Pillow version**|**Tested processors** | +----------------------------------+------------------------------+--------------------------------+-----------------------+ +| macOS 11.0 Big Sur | 3.6, 3.7, 3.8, 3.9 | 8.0.1 |x86-64 | ++----------------------------------+------------------------------+--------------------------------+-----------------------+ | macOS 10.15 Catalina | 3.6, 3.7, 3.8, 3.9 | 8.0.1 |x86-64 | | +------------------------------+--------------------------------+ + | | 3.5 | 7.2.0 | | From cf9158f635a892c551961bf3ed6f8855f22cc0ce Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 28 Nov 2020 12:10:20 +1100 Subject: [PATCH 065/186] Corrected syntax [ci skip] --- docs/handbook/writing-your-own-file-decoder.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/handbook/writing-your-own-file-decoder.rst b/docs/handbook/writing-your-own-file-decoder.rst index 97cb5abe1..03b4ca601 100644 --- a/docs/handbook/writing-your-own-file-decoder.rst +++ b/docs/handbook/writing-your-own-file-decoder.rst @@ -157,7 +157,7 @@ The raw decoder The ``raw`` decoder is used to read uncompressed data from an image file. It can be used with most uncompressed file formats, such as PPM, BMP, uncompressed TIFF, and many others. To use the raw decoder with the -:py:func:`PIL.Image.frombytes` function, use the following syntax:: +:py:func:`PIL.Image.frombytes` function, use the following syntax: .. code-block:: python From ce1e73e5a87b2acc4b1356fada4d042fdb1e99f1 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 30 Nov 2020 01:20:51 +1100 Subject: [PATCH 066/186] Updated libraqm to 0.7.1 --- depends/install_raqm.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/depends/install_raqm.sh b/depends/install_raqm.sh index 38a5bfd52..a7ce16792 100755 --- a/depends/install_raqm.sh +++ b/depends/install_raqm.sh @@ -2,7 +2,7 @@ # install raqm -archive=raqm-0.7.0 +archive=raqm-0.7.1 ./download-and-extract.sh $archive https://raw.githubusercontent.com/python-pillow/pillow-depends/master/$archive.tar.gz From 8c110b7232c9b9341926252862c2948298f7875e Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Wed, 2 Dec 2020 18:15:09 +0200 Subject: [PATCH 067/186] Add 'Release notes' and 'Changelog' links to PyPI [CI skip] --- README.md | 1 + setup.py | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/README.md b/README.md index 9ead486a0..6c323413d 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,7 @@ The core image library is designed for fast access to data stored in a few basic - [Contribute](https://github.com/python-pillow/Pillow/blob/master/.github/CONTRIBUTING.md) - [Issues](https://github.com/python-pillow/Pillow/issues) - [Pull requests](https://github.com/python-pillow/Pillow/pulls) +- [Release notes](https://pillow.readthedocs.io/en/stable/releasenotes/index.html) - [Changelog](https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst) - [Pre-fork](https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst#pre-fork) diff --git a/setup.py b/setup.py index 5bc683c8c..cbc2641c5 100755 --- a/setup.py +++ b/setup.py @@ -877,6 +877,10 @@ try: "Source": "https://github.com/python-pillow/Pillow", "Funding": "https://tidelift.com/subscription/pkg/pypi-pillow?" "utm_source=pypi-pillow&utm_medium=pypi", + "Release notes": "https://pillow.readthedocs.io/en/stable/releasenotes/" + "index.html", + "Changelog": "https://github.com/python-pillow/Pillow/blob/master/" + "CHANGES.rst", }, classifiers=[ "Development Status :: 6 - Mature", From a0565bc8acbd9137fab94118c9c43f18956a03b1 Mon Sep 17 00:00:00 2001 From: Alex Clark Date: Fri, 4 Dec 2020 18:24:22 -0500 Subject: [PATCH 068/186] Update CHANGES.rst https://twitter.com/aclark4life/status/1335001987075747841 --- CHANGES.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index e7090219f..b05fa78df 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -4039,8 +4039,8 @@ Changelog (Pillow) 1.0 (07/30/2010) ---------------- -- Remove support for ``import Image``, etc. from the standard namespace. ``from PIL import Image`` etc. now required. -- Forked PIL based on `Hanno Schlichting's re-packaging `_ +- Remove support for ``import Image``. ``from PIL import Image`` now required. +- Forked PIL based on `Chris McDonough and Hanno Schlichting's setuptools compatible re-packaging `_ [aclark4life] Pre-fork From 1e8e7fea7de598cd629af973bb15f781b0beb1ad Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Mon, 7 Dec 2020 22:01:25 +0200 Subject: [PATCH 069/186] Add categories to Release Drafter [CI skip] --- .github/release-drafter.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index 0412bd9dd..aa49c2ec0 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -2,6 +2,18 @@ name-template: "$NEXT_MINOR_VERSION" tag-template: "$NEXT_MINOR_VERSION" change-template: '- $TITLE #$NUMBER [@$AUTHOR]' +categories: + - title: "Dependencies" + label: "Dependencies" + - title: "Deprecations" + label: "Deprecation" + - title: "Documentation" + label: "Documentation" + - title: "Removals" + label: "Removal" + - title: "Testing" + label: "Testing" + exclude-labels: - "changelog: skip" From 786fddb794f68dd3f7c68ba9b9ce51fc6abd3699 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Tue, 8 Dec 2020 12:23:53 +0200 Subject: [PATCH 070/186] Fix label name Co-authored-by: Andrew Murray <3112309+radarhere@users.noreply.github.com> --- .github/release-drafter.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index aa49c2ec0..4d855469a 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -4,7 +4,7 @@ change-template: '- $TITLE #$NUMBER [@$AUTHOR]' categories: - title: "Dependencies" - label: "Dependencies" + label: "Dependency" - title: "Deprecations" label: "Deprecation" - title: "Documentation" From 0893f502c3699736269817d54a61d51229aaf9c8 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 10 Dec 2020 14:32:43 +0200 Subject: [PATCH 071/186] Document when deprecations will be removed [CI skip] --- docs/deprecations.rst | 18 +++++++++--------- src/PIL/Image.py | 6 +++--- src/PIL/ImageFile.py | 2 +- src/PIL/__init__.py | 2 +- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/deprecations.rst b/docs/deprecations.rst index e3ad2a9e3..07d845dd6 100644 --- a/docs/deprecations.rst +++ b/docs/deprecations.rst @@ -17,7 +17,7 @@ Image.show command parameter .. deprecated:: 7.2.0 -The ``command`` parameter was deprecated and will be removed in a future release. +The ``command`` parameter will be removed in Pillow 9.0.0 (2022-01-02). Use a subclass of :py:class:`.ImageShow.Viewer` instead. Image._showxv @@ -25,26 +25,26 @@ Image._showxv .. deprecated:: 7.2.0 -``Image._showxv`` has been deprecated. Use :py:meth:`.Image.Image.show` -instead. If custom behaviour is required, use :py:func:`.ImageShow.register` to add -a custom :py:class:`.ImageShow.Viewer` class. +``Image._showxv`` will be removed in Pillow 9.0.0 (2022-01-02). +Use :py:meth:`.Image.Image.show` instead. If custom behaviour is required, use +:py:func:`.ImageShow.register` to add a custom :py:class:`.ImageShow.Viewer` class. ImageFile.raise_ioerror ~~~~~~~~~~~~~~~~~~~~~~~ .. deprecated:: 7.2.0 -``IOError`` was merged into ``OSError`` in Python 3.3. So, ``ImageFile.raise_ioerror`` -is now deprecated and will be removed in a future release. Use -``ImageFile.raise_oserror`` instead. +``IOError`` was merged into ``OSError`` in Python 3.3. +So, ``ImageFile.raise_ioerror`` will be removed in Pillow 9.0.0 (2022-01-02). +Use ``ImageFile.raise_oserror`` instead. PILLOW_VERSION constant ~~~~~~~~~~~~~~~~~~~~~~~ .. deprecated:: 5.2.0 -``PILLOW_VERSION`` has been deprecated and will be removed in a future release. Use -``__version__`` instead. +``PILLOW_VERSION`` will be removed in Pillow 9.0.0 (2022-01-02). +Use ``__version__`` instead. It was initially removed in Pillow 7.0.0, but brought back in 7.1.0 to give projects more time to upgrade. diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 8d3f6b0aa..ae2559d11 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2197,8 +2197,8 @@ class Image: if command is not None: warnings.warn( - "The command parameter is deprecated and will be removed in a future " - "release. Use a subclass of ImageShow.Viewer instead.", + "The command parameter is deprecated and will be removed in Pillow 9 " + "(2022-01-02). Use a subclass of ImageShow.Viewer instead.", DeprecationWarning, ) @@ -3176,7 +3176,7 @@ def _showxv(image, title=None, **options): del options["_internal_pillow"] else: warnings.warn( - "_showxv is deprecated and will be removed in a future release. " + "_showxv is deprecated and will be removed in Pillow 9 (2022-01-02). " "Use Image.show instead.", DeprecationWarning, ) diff --git a/src/PIL/ImageFile.py b/src/PIL/ImageFile.py index 49633ef51..f2a55cb54 100644 --- a/src/PIL/ImageFile.py +++ b/src/PIL/ImageFile.py @@ -69,7 +69,7 @@ def raise_oserror(error): def raise_ioerror(error): warnings.warn( - "raise_ioerror is deprecated and will be removed in a future release. " + "raise_ioerror is deprecated and will be removed in Pillow 9 (2022-01-02). " "Use raise_oserror instead.", DeprecationWarning, ) diff --git a/src/PIL/__init__.py b/src/PIL/__init__.py index d4f5ea76a..890ae44f5 100644 --- a/src/PIL/__init__.py +++ b/src/PIL/__init__.py @@ -26,7 +26,7 @@ __version__ = _version.__version__ # Use __version__ instead. def _raise_version_warning(): warnings.warn( - "PILLOW_VERSION is deprecated and will be removed in a future release. " + "PILLOW_VERSION is deprecated and will be removed in Pillow 9 (2022-01-02). " "Use __version__ instead.", DeprecationWarning, stacklevel=3, From 1c82fbd5e9da2b80f42727d90e158865d37e3a90 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Fri, 11 Dec 2020 20:46:00 +0200 Subject: [PATCH 072/186] Disable Travis from automerge --- .github/mergify.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/mergify.yml b/.github/mergify.yml index fd4b5271f..b37db48d4 100644 --- a/.github/mergify.yml +++ b/.github/mergify.yml @@ -7,7 +7,7 @@ pull_request_rules: - status-success=Test Successful - status-success=Docker Test Successful - status-success=Windows Test Successful - - status-success=Travis CI - Pull Request +# - status-success=Travis CI - Pull Request - status-success=continuous-integration/appveyor/pr actions: merge: From 4ed79ea79c71ba97726f95c06bdac8df3018cfb9 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 12 Dec 2020 10:31:55 +1100 Subject: [PATCH 073/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index b05fa78df..e009c9508 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,18 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Moved warning to end of execution #4965 + [radarhere] + +- Removed unused fromstring and tostring C methods #5026 + [radarhere] + +- init() if one of the formats is unrecognised #5037 + [radarhere] + +- Moved string_dimension CVE image to pillow-depends #4993 + [radarhere] + - Support raw rgba8888 for DDS #4760 [qiankanglai] From a666c91e10d3d4922b2eefe3c31dbeb970baa8d6 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 12 Dec 2020 14:12:30 +1100 Subject: [PATCH 074/186] Allow putpalette to accept 1024 integers to include alpha values --- Tests/test_image_putpalette.py | 21 +++++++++++++++++++-- src/PIL/Image.py | 26 ++++++++++++++++++-------- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/Tests/test_image_putpalette.py b/Tests/test_image_putpalette.py index 32f8de2c0..5a9df11b1 100644 --- a/Tests/test_image_putpalette.py +++ b/Tests/test_image_putpalette.py @@ -1,8 +1,8 @@ import pytest -from PIL import ImagePalette +from PIL import Image, ImagePalette -from .helper import hopper +from .helper import assert_image_equal, hopper def test_putpalette(): @@ -39,3 +39,20 @@ def test_imagepalette(): im.putpalette(ImagePalette.random()) im.putpalette(ImagePalette.sepia()) im.putpalette(ImagePalette.wedge()) + + +def test_putpalette_with_alpha_values(): + with Image.open("Tests/images/transparent.gif") as im: + expected = im.convert("RGBA") + + palette = im.getpalette() + transparency = im.info.pop("transparency") + + palette_with_alpha_values = [] + for i in range(256): + color = palette[i * 3 : i * 3 + 3] + alpha = 0 if i == transparency else 255 + palette_with_alpha_values += color + [alpha] + im.putpalette(palette_with_alpha_values, "RGBA") + + assert_image_equal(im.convert("RGBA"), expected) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index ae2559d11..55861a75a 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -815,9 +815,15 @@ class Image: """ if self.im and self.palette and self.palette.dirty: # realize palette - self.im.putpalette(*self.palette.getdata()) + mode, arr = self.palette.getdata() + if mode == "RGBA": + mode = "RGB" + self.info["transparency"] = arr[3::4] + arr = bytes( + value for (index, value) in enumerate(arr) if index % 4 != 3 + ) + self.im.putpalette(mode, arr) self.palette.dirty = 0 - self.palette.mode = "RGB" self.palette.rawmode = None if "transparency" in self.info: if isinstance(self.info["transparency"], int): @@ -825,6 +831,8 @@ class Image: else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" + else: + self.palette.mode = "RGB" if self.im: if cffi and USE_CFFI_ACCESS: @@ -1672,12 +1680,14 @@ class Image: def putpalette(self, data, rawmode="RGB"): """ - Attaches a palette to this image. The image must be a "P", - "PA", "L" or "LA" image, and the palette sequence must contain - 768 integer values, where each group of three values represent - the red, green, and blue values for the corresponding pixel - index. Instead of an integer sequence, you can use an 8-bit - string. + Attaches a palette to this image. The image must be a "P", "PA", "L" + or "LA" image. + + The palette sequence must contain either 768 integer values, or 1024 + integer values if alpha is included. Each group of values represents + the red, green, blue (and alpha if included) values for the + corresponding pixel index. Instead of an integer sequence, you can use + an 8-bit string. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. From ff0ad9af3445346d385da76e7c3acc881ce55336 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 12 Dec 2020 23:36:57 +1100 Subject: [PATCH 075/186] Do not catch a ValueError only to raise another --- src/PIL/Image.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index ae2559d11..a4e6f3682 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1626,7 +1626,7 @@ class Image: self.im = im self.pyaccess = None self.mode = self.im.mode - except (KeyError, ValueError) as e: + except KeyError as e: raise ValueError("illegal image mode") from e if self.mode in ("LA", "PA"): From 989c9b303a253a9c864e8053a53752dbd3f47918 Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 4 Nov 2020 00:38:28 +0000 Subject: [PATCH 076/186] xfail failing libtiff tests on big-endian (cherry picked from commit 25ce233edf732edb5660f877365379377a64f136) --- Tests/test_file_libtiff.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index da955b3de..7d3e10c24 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -16,6 +16,7 @@ from .helper import ( assert_image_similar, assert_image_similar_tofile, hopper, + is_big_endian, skip_unless_feature, ) @@ -813,11 +814,13 @@ class TestFileLibTiff(LibTiffTestCase): with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/pil_sample_cmyk.jpg", 0.5) + @pytest.mark.xfail(is_big_endian(), reason="Fails on big-endian") def test_strip_ycbcr_jpeg_2x2_sampling(self): infile = "Tests/images/tiff_strip_ycbcr_jpeg_2x2_sampling.tif" with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/flower.jpg", 0.5) + @pytest.mark.xfail(is_big_endian(), reason="Fails on big-endian") def test_strip_ycbcr_jpeg_1x1_sampling(self): infile = "Tests/images/tiff_strip_ycbcr_jpeg_1x1_sampling.tif" with Image.open(infile) as im: @@ -828,16 +831,19 @@ class TestFileLibTiff(LibTiffTestCase): with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/pil_sample_cmyk.jpg", 0.5) + @pytest.mark.xfail(is_big_endian(), reason="Fails on big-endian") def test_tiled_ycbcr_jpeg_1x1_sampling(self): infile = "Tests/images/tiff_tiled_ycbcr_jpeg_1x1_sampling.tif" with Image.open(infile) as im: assert_image_equal_tofile(im, "Tests/images/flower2.jpg") + @pytest.mark.xfail(is_big_endian(), reason="Fails on big-endian") def test_tiled_ycbcr_jpeg_2x2_sampling(self): infile = "Tests/images/tiff_tiled_ycbcr_jpeg_2x2_sampling.tif" with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/flower.jpg", 0.5) + @pytest.mark.xfail(is_big_endian(), reason="Fails on big-endian") def test_old_style_jpeg(self): infile = "Tests/images/old-style-jpeg-compression.tif" with Image.open(infile) as im: From a3ab868b0f4d1d147030b4eead32a046ed48bf72 Mon Sep 17 00:00:00 2001 From: nulano Date: Wed, 4 Nov 2020 00:58:06 +0000 Subject: [PATCH 077/186] xfail tests failing on ppc64le on GHA (cherry picked from commit 9c7fb5bd14c3064fede96131a0f7f67abf26a4e7) --- Tests/helper.py | 6 ++++++ Tests/test_image_quantize.py | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Tests/helper.py b/Tests/helper.py index 3da2571f2..d76389621 100644 --- a/Tests/helper.py +++ b/Tests/helper.py @@ -278,6 +278,12 @@ def is_big_endian(): return sys.byteorder == "big" +def is_ppc64le(): + import platform + + return platform.machine() == "ppc64le" + + def is_win32(): return sys.platform.startswith("win32") diff --git a/Tests/test_image_quantize.py b/Tests/test_image_quantize.py index 921c39e3f..af4172c88 100644 --- a/Tests/test_image_quantize.py +++ b/Tests/test_image_quantize.py @@ -2,7 +2,7 @@ import pytest from PIL import Image -from .helper import assert_image, assert_image_similar, hopper +from .helper import assert_image, assert_image_similar, hopper, is_ppc64le def test_sanity(): @@ -17,6 +17,7 @@ def test_sanity(): assert_image_similar(converted.convert("RGB"), image, 60) +@pytest.mark.xfail(is_ppc64le(), reason="failing on ppc64le on GHA") def test_libimagequant_quantize(): image = hopper() try: From 903ec9723d425daba09eeaacdb0fea7427cea35c Mon Sep 17 00:00:00 2001 From: nulano Date: Fri, 11 Dec 2020 20:41:02 +0100 Subject: [PATCH 078/186] move tests for arm64v8, ppc64le, s390x from Travis CI to GHA using Docker and aptman/qus --- .github/workflows/test-docker.yml | 17 +++++++++++++++++ .travis.yml | 29 ----------------------------- 2 files changed, 17 insertions(+), 29 deletions(-) delete mode 100644 .travis.yml diff --git a/.github/workflows/test-docker.yml b/.github/workflows/test-docker.yml index f6814f932..eb173c359 100644 --- a/.github/workflows/test-docker.yml +++ b/.github/workflows/test-docker.yml @@ -10,6 +10,11 @@ jobs: fail-fast: false matrix: docker: [ + # Run slower jobs first to give them a headstart and reduce waiting time + ubuntu-20.04-focal-arm64v8, + ubuntu-20.04-focal-ppc64le, + ubuntu-20.04-focal-s390x, + # Then run the remainder alpine, amazon-2-amd64, arch, @@ -22,6 +27,13 @@ jobs: ubuntu-20.04-focal-amd64, ] dockerTag: [master] + include: + - docker: "ubuntu-20.04-focal-arm64v8" + qemu-arch: "aarch64" + - docker: "ubuntu-20.04-focal-ppc64le" + qemu-arch: "ppc64le" + - docker: "ubuntu-20.04-focal-s390x" + qemu-arch: "s390x" name: ${{ matrix.docker }} @@ -31,6 +43,11 @@ jobs: - name: Build system information run: python .github/workflows/system-info.py + - name: Set up QEMU + if: "matrix.qemu-arch" + run: | + docker run --rm --privileged aptman/qus -s -- -p ${{ matrix.qemu-arch }} + - name: Docker pull run: | docker pull pythonpillow/${{ matrix.docker }}:${{ matrix.dockerTag }} diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index e239ed496..000000000 --- a/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ -dist: xenial -language: python -cache: pip - -notifications: - irc: "chat.freenode.net#pil" - -matrix: - fast_finish: true - include: - - python: "3.6" - arch: arm64 - - python: "3.7" - arch: ppc64le - - python: "3.8" - arch: s390x - -install: - - | - .ci/install.sh; - -script: - - | - .ci/build.sh - .ci/test.sh - -after_success: - - | - .ci/after_success.sh From db35e6404e6a3bcd19f530af73c41c422d054c0f Mon Sep 17 00:00:00 2001 From: nulano Date: Fri, 11 Dec 2020 21:06:24 +0100 Subject: [PATCH 079/186] remove FreeType<2.7 metrics in test_imagefont --- Tests/test_imagefont.py | 64 +++++++++++------------------------------ 1 file changed, 17 insertions(+), 47 deletions(-) diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py index 06ed42658..0f44b2e0c 100644 --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -32,36 +32,6 @@ pytestmark = skip_unless_feature("freetype2") class TestImageFont: LAYOUT_ENGINE = ImageFont.LAYOUT_BASIC - # Freetype has different metrics depending on the version. - # (and, other things, but first things first) - METRICS = { - (">=2.7",): {"multiline": 6.2, "textsize": 2.5, "getlength": (36, 21, 24, 33)}, - "Default": {"multiline": 0.5, "textsize": 0.5, "getlength": (36, 24, 24, 33)}, - } - - @classmethod - def setup_class(self): - freetype = parse_version(features.version_module("freetype2")) - - self.metrics = self.METRICS["Default"] - for conditions, metrics in self.METRICS.items(): - if not isinstance(conditions, tuple): - continue - - for condition in conditions: - version = parse_version(re.sub("[<=>]", "", condition)) - if (condition.startswith(">=") and freetype >= version) or ( - condition.startswith("<") and freetype < version - ): - # Condition was met - continue - - # Condition failed - break - else: - # All conditions were met - self.metrics = metrics - def get_font(self): return ImageFont.truetype( FONT_PATH, FONT_SIZE, layout_engine=self.LAYOUT_ENGINE @@ -177,24 +147,24 @@ class TestImageFont: with Image.open(target) as target_img: # Epsilon ~.5 fails with FreeType 2.7 - assert_image_similar(im, target_img, self.metrics["textsize"]) + assert_image_similar(im, target_img, 2.5) @pytest.mark.parametrize( - "text, mode, font, size, length_basic_index, length_raqm", + "text, mode, font, size, length_basic, length_raqm", ( # basic test - ("text", "L", "FreeMono.ttf", 15, 0, 36), - ("text", "1", "FreeMono.ttf", 15, 0, 36), + ("text", "L", "FreeMono.ttf", 15, 36, 36), + ("text", "1", "FreeMono.ttf", 15, 36, 36), # issue 4177 - ("rrr", "L", "DejaVuSans.ttf", 18, 1, 22.21875), - ("rrr", "1", "DejaVuSans.ttf", 18, 2, 22.21875), + ("rrr", "L", "DejaVuSans.ttf", 18, 21, 22.21875), + ("rrr", "1", "DejaVuSans.ttf", 18, 24, 22.21875), # test 'l' not including extra margin # using exact value 2047 / 64 for raqm, checked with debugger - ("ill", "L", "OpenSansCondensed-LightItalic.ttf", 63, 3, 31.984375), - ("ill", "1", "OpenSansCondensed-LightItalic.ttf", 63, 3, 31.984375), + ("ill", "L", "OpenSansCondensed-LightItalic.ttf", 63, 33, 31.984375), + ("ill", "1", "OpenSansCondensed-LightItalic.ttf", 63, 33, 31.984375), ), ) - def test_getlength(self, text, mode, font, size, length_basic_index, length_raqm): + def test_getlength(self, text, mode, font, size, length_basic, length_raqm): f = ImageFont.truetype( "Tests/fonts/" + font, size, layout_engine=self.LAYOUT_ENGINE ) @@ -204,7 +174,7 @@ class TestImageFont: if self.LAYOUT_ENGINE == ImageFont.LAYOUT_BASIC: length = d.textlength(text, f) - assert length == self.metrics["getlength"][length_basic_index] + assert length == length_basic else: # disable kerning, kerning metrics changed length = d.textlength(text, f, features=["-kern"]) @@ -227,7 +197,7 @@ class TestImageFont: # some versions of freetype have different horizontal spacing. # setting a tight epsilon, I'm showing the original test failure # at epsilon = ~38. - assert_image_similar(im, target_img, self.metrics["multiline"]) + assert_image_similar(im, target_img, 6.2) def test_render_multiline_text(self): ttf = self.get_font() @@ -242,7 +212,7 @@ class TestImageFont: with Image.open(target) as target_img: # Epsilon ~.5 fails with FreeType 2.7 - assert_image_similar(im, target_img, self.metrics["multiline"]) + assert_image_similar(im, target_img, 6.2) # Test that text() can pass on additional arguments # to multiline_text() @@ -261,7 +231,7 @@ class TestImageFont: with Image.open(target) as target_img: # Epsilon ~.5 fails with FreeType 2.7 - assert_image_similar(im, target_img, self.metrics["multiline"]) + assert_image_similar(im, target_img, 6.2) def test_unknown_align(self): im = Image.new(mode="RGB", size=(300, 100)) @@ -319,7 +289,7 @@ class TestImageFont: with Image.open(target) as target_img: # Epsilon ~.5 fails with FreeType 2.7 - assert_image_similar(im, target_img, self.metrics["multiline"]) + assert_image_similar(im, target_img, 6.2) def test_rotated_transposed_font(self): img_grey = Image.new("L", (100, 100)) @@ -906,7 +876,7 @@ class TestImageFont: d.text((10, 10), txt, font=ttf, fill="#fa6", embedded_color=True) with Image.open("Tests/images/standard_embedded.png") as expected: - assert_image_similar(im, expected, max(self.metrics["multiline"], 3)) + assert_image_similar(im, expected, 6.2) @skip_unless_feature_version("freetype2", "2.5.0") def test_cbdt(self): @@ -923,7 +893,7 @@ class TestImageFont: d.text((10, 10), "\U0001f469", embedded_color=True, font=font) with Image.open("Tests/images/cbdt_notocoloremoji.png") as expected: - assert_image_similar(im, expected, self.metrics["multiline"]) + assert_image_similar(im, expected, 6.2) except IOError as e: assert str(e) in ("unimplemented feature", "unknown file format") pytest.skip("freetype compiled without libpng or unsupported") @@ -943,7 +913,7 @@ class TestImageFont: d.text((10, 10), "\U0001f469", "black", font=font) with Image.open("Tests/images/cbdt_notocoloremoji_mask.png") as expected: - assert_image_similar(im, expected, self.metrics["multiline"]) + assert_image_similar(im, expected, 6.2) except IOError as e: assert str(e) in ("unimplemented feature", "unknown file format") pytest.skip("freetype compiled without libpng or unsupported") From 27bf17009c74b739d6b0ab4a68ac8d02e8bc76aa Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Wed, 16 Dec 2020 18:21:37 +0200 Subject: [PATCH 080/186] Deprecate FreeType 2.7, to be removed in Pillow 9 (2022-01-02) --- Tests/test_imagefont.py | 12 ++++++++++ docs/deprecations.rst | 14 ++++++++++++ docs/releasenotes/8.1.0.rst | 45 +++++++++++++++++++++++++++++++++++++ docs/releasenotes/index.rst | 1 + src/PIL/ImageFont.py | 14 +++++++++++- 5 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 docs/releasenotes/8.1.0.rst diff --git a/Tests/test_imagefont.py b/Tests/test_imagefont.py index 06ed42658..264c97e48 100644 --- a/Tests/test_imagefont.py +++ b/Tests/test_imagefont.py @@ -998,3 +998,15 @@ def test_render_mono_size(): draw.text((10, 10), "r" * 10, "black", ttf) assert_image_equal_tofile(im, "Tests/images/text_mono.gif") + + +def test_freetype_deprecation(monkeypatch): + # Arrange: mock features.version_module to return fake FreeType version + def fake_version_module(module): + return "2.7" + + monkeypatch.setattr(features, "version_module", fake_version_module) + + # Act / Assert + with pytest.warns(DeprecationWarning): + ImageFont.truetype(FONT_PATH, FONT_SIZE) diff --git a/docs/deprecations.rst b/docs/deprecations.rst index 07d845dd6..36f74a64f 100644 --- a/docs/deprecations.rst +++ b/docs/deprecations.rst @@ -12,6 +12,20 @@ Deprecated features Below are features which are considered deprecated. Where appropriate, a ``DeprecationWarning`` is issued. +FreeType 2.7 +~~~~~~~~~~~~ + +.. deprecated:: 8.1.0 + +Support for FreeType 2.7 is deprecated and will be removed in Pillow 9.0.0 (2022-01-02), +when FreeType 2.8 will be the minimum supported. + +We recommend upgrading to at least FreeType `2.10.4`_, which fixed a severe +vulnerability introduced in FreeType 2.6 (CVE-2020-15999_). + +.. _2.10.4: https://sourceforge.net/projects/freetype/files/freetype2/2.10.4/ +.. _CVE-2020-15999: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-15999 + Image.show command parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst new file mode 100644 index 000000000..819bb30e0 --- /dev/null +++ b/docs/releasenotes/8.1.0.rst @@ -0,0 +1,45 @@ +8.1.0 +----- + +Deprecations +============ + +FreeType 2.7 +^^^^^^^^^^^^ + +Support for FreeType 2.7 is deprecated and will be removed in Pillow 9.0.0 (2022-01-02), +when FreeType 2.8 will be the minimum supported. + +We recommend upgrading to at least FreeType `2.10.4`_, which fixed a severe +vulnerability introduced in FreeType 2.6 (:cve:`CVE-2020-15999`). + +.. _2.10.4: https://sourceforge.net/projects/freetype/files/freetype2/2.10.4/ + +API Changes +=========== + +TODO +^^^^ + +TODO + +API Additions +============= + +TODO +^^^^ + +TODO + +Security +======== + +TODO + +Other Changes +============= + +TODO +^^^^ + +TODO diff --git a/docs/releasenotes/index.rst b/docs/releasenotes/index.rst index 5c74bed9b..18d2d9576 100644 --- a/docs/releasenotes/index.rst +++ b/docs/releasenotes/index.rst @@ -13,6 +13,7 @@ expected to be backported to earlier versions. .. toctree:: :maxdepth: 2 + 8.1.0 8.0.1 8.0.0 7.2.0 diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py index 3a8a309c6..78f8d8cde 100644 --- a/src/PIL/ImageFont.py +++ b/src/PIL/ImageFont.py @@ -28,9 +28,12 @@ import base64 import os import sys +import warnings from io import BytesIO -from . import Image +from packaging.version import parse as parse_version + +from . import Image, features from ._util import isDirectory, isPath LAYOUT_BASIC = 0 @@ -164,6 +167,15 @@ class FreeTypeFont: self.index = index self.encoding = encoding + freetype_version = parse_version(features.version_module("freetype2")) + if freetype_version < parse_version("2.8"): + warnings.warn( + "Support for FreeType 2.7 is deprecated and will be removed in Pillow " + "9 (2022-01-02). Please upgrade to FreeType 2.8 or newer, preferably " + "FreeType 2.10.4 which fixes CVE-2020-15999.", + DeprecationWarning, + ) + if layout_engine not in (LAYOUT_BASIC, LAYOUT_RAQM): layout_engine = LAYOUT_BASIC if core.HAVE_RAQM: From d093b7141f1f25f0857ce6846344cfd83c029d8b Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 17 Dec 2020 06:17:59 +0200 Subject: [PATCH 081/186] Update Makefile docs command for Python 3 --- Makefile | 2 +- docs/Makefile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 99232cac9..8892d4390 100644 --- a/Makefile +++ b/Makefile @@ -33,7 +33,7 @@ doccheck: .PHONY: docserve docserve: - cd docs/_build/html && python3 -mSimpleHTTPServer 2> /dev/null& + cd docs/_build/html && python3 -m http.server 2> /dev/null& .PHONY: help help: diff --git a/docs/Makefile b/docs/Makefile index d7c20bca4..686f0119e 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -156,4 +156,4 @@ livehtml: html livereload $(BUILDDIR)/html -p 33233 serve: - cd $(BUILDDIR)/html; python -m SimpleHTTPServer + cd $(BUILDDIR)/html; python3 -m http.server From f0c0a0a1f48bfb0e97504f75f66b5c518c85c778 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 17 Dec 2020 06:46:51 +0200 Subject: [PATCH 082/186] Autolink CVEs with sphinx-issues --- .github/workflows/test.yml | 2 +- docs/conf.py | 1 + docs/deprecations.rst | 3 +-- docs/releasenotes/3.1.1.rst | 24 ++++++++++++++---------- docs/releasenotes/3.1.2.rst | 6 ++++-- docs/releasenotes/6.2.0.rst | 6 +++--- docs/releasenotes/6.2.2.rst | 13 +++++++------ docs/releasenotes/7.1.0.rst | 10 +++++----- docs/releasenotes/8.0.1.rst | 5 +---- requirements.txt | 1 + 10 files changed, 38 insertions(+), 33 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 51ce9d085..ada367131 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -103,7 +103,7 @@ jobs: - name: Docs if: startsWith(matrix.os, 'ubuntu') && matrix.python-version == 3.9 run: | - python3 -m pip install sphinx-removed-in sphinx-rtd-theme + python3 -m pip install sphinx-issues sphinx-removed-in sphinx-rtd-theme make doccheck - name: After success diff --git a/docs/conf.py b/docs/conf.py index a8f101141..7a117a271 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -32,6 +32,7 @@ extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", + "sphinx_issues", "sphinx_removed_in", ] diff --git a/docs/deprecations.rst b/docs/deprecations.rst index 36f74a64f..44aa2a795 100644 --- a/docs/deprecations.rst +++ b/docs/deprecations.rst @@ -21,10 +21,9 @@ Support for FreeType 2.7 is deprecated and will be removed in Pillow 9.0.0 (2022 when FreeType 2.8 will be the minimum supported. We recommend upgrading to at least FreeType `2.10.4`_, which fixed a severe -vulnerability introduced in FreeType 2.6 (CVE-2020-15999_). +vulnerability introduced in FreeType 2.6 (:cve:`CVE-2020-15999`). .. _2.10.4: https://sourceforge.net/projects/freetype/files/freetype2/2.10.4/ -.. _CVE-2020-15999: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-15999 Image.show command parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/releasenotes/3.1.1.rst b/docs/releasenotes/3.1.1.rst index 8c32a43e7..38118ea39 100644 --- a/docs/releasenotes/3.1.1.rst +++ b/docs/releasenotes/3.1.1.rst @@ -6,7 +6,7 @@ CVE-2016-0740 -- Buffer overflow in TiffDecode.c ------------------------------------------------ Pillow 3.1.0 and earlier when linked against libtiff >= 4.0.0 on x64 -may overflow a buffer when reading a specially crafted tiff file. +may overflow a buffer when reading a specially crafted tiff file (:cve:`CVE-2016-0740`). Specifically, libtiff >= 4.0.0 changed the return type of ``TIFFScanlineSize`` from ``int32`` to machine dependent @@ -24,9 +24,11 @@ CVE-2016-0775 -- Buffer overflow in FliDecode.c ----------------------------------------------- In all versions of Pillow, dating back at least to the last PIL 1.1.7 -release, FliDecode.c has a buffer overflow error. +release, FliDecode.c has a buffer overflow error (:cve:`CVE-2016-0775`). -Around line 192:: +Around line 192: + +.. code-block:: c case 16: /* COPY chunk */ @@ -45,13 +47,13 @@ is a set of row pointers to segments of memory that are the size of the row. At the max ``y``, this will write the contents of the line off the end of the memory buffer, causing a segfault. -This issue was found by Alyssa Besseling at Atlassian +This issue was found by Alyssa Besseling at Atlassian. CVE-2016-2533 -- Buffer overflow in PcdDecode.c ----------------------------------------------- In all versions of Pillow, dating back at least to the last PIL 1.1.7 -release, ``PcdDecode.c`` has a buffer overflow error. +release, ``PcdDecode.c`` has a buffer overflow error (:cve:`CVE-2016-2533`). The ``state.buffer`` for ``PcdDecode.c`` is allocated based on a 3 bytes per pixel sizing, where ``PcdDecode.c`` wrote into the buffer @@ -63,14 +65,16 @@ Integer overflow in Resample.c ------------------------------ If a large value was passed into the new size for an image, it is -possible to overflow an int32 value passed into malloc. +possible to overflow an ``int32`` value passed into malloc. - kk = malloc(xsize * kmax * sizeof(float)); - ... - xbounds = malloc(xsize * 2 * sizeof(int)); +.. code-block:: c + + kk = malloc(xsize * kmax * sizeof(float)); + ... + xbounds = malloc(xsize * 2 * sizeof(int)); ``xsize`` is trusted user input. These multiplications can overflow, -leading the malloc'd buffer to be undersized. These allocations are +leading the ``malloc``'d buffer to be undersized. These allocations are followed by a loop that writes out of bounds. This can lead to corruption on the heap of the Python process with attacker controlled float data. diff --git a/docs/releasenotes/3.1.2.rst b/docs/releasenotes/3.1.2.rst index ddb6a2ada..b5f7cfe99 100644 --- a/docs/releasenotes/3.1.2.rst +++ b/docs/releasenotes/3.1.2.rst @@ -7,9 +7,11 @@ CVE-2016-3076 -- Buffer overflow in Jpeg2KEncode.c Pillow between 2.5.0 and 3.1.1 may overflow a buffer when writing large Jpeg2000 files, allowing for code execution or other memory -corruption. +corruption (:cve:`CVE-2016-3076`). -This occurs specifically in the function ``j2k_encode_entry``, at the line:: +This occurs specifically in the function ``j2k_encode_entry``, at the line: + +.. code-block:: c state->buffer = malloc (tile_width * tile_height * components * prec / 8); diff --git a/docs/releasenotes/6.2.0.rst b/docs/releasenotes/6.2.0.rst index faf84e6bd..1bc82b72f 100644 --- a/docs/releasenotes/6.2.0.rst +++ b/docs/releasenotes/6.2.0.rst @@ -73,7 +73,7 @@ Security ======== This release catches several buffer overruns, as well as addressing -CVE-2019-16865. The CVE is regarding DOS problems, such as consuming large +:cve:`CVE-2019-16865`. The CVE is regarding DOS problems, such as consuming large amounts of memory, or taking a large amount of time to process an image. In RawDecode.c, an error is now thrown if skip is calculated to be less than @@ -103,7 +103,7 @@ instead. Flags for libwebp in wheels ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -When building libwebp for inclusion in wheels, Pillow now adds the -O3 and --DNDEBUG CFLAGS. These flags would be used by default if building libwebp +When building libwebp for inclusion in wheels, Pillow now adds the ``-O3`` and +``-DNDEBUG`` CFLAGS. These flags would be used by default if building libwebp without debugging, and using them fixes a significant decrease in speed when a wheel-installed copy of Pillow performs libwebp operations. diff --git a/docs/releasenotes/6.2.2.rst b/docs/releasenotes/6.2.2.rst index a138c7d60..79d4b88aa 100644 --- a/docs/releasenotes/6.2.2.rst +++ b/docs/releasenotes/6.2.2.rst @@ -6,12 +6,13 @@ Security This release addresses several security problems. -CVE-2019-19911 is regarding FPX images. If an image reports that it has a large number -of bands, a large amount of resources will be used when trying to process the +:cve:`CVE-2019-19911` is regarding FPX images. If an image reports that it has a large +number of bands, a large amount of resources will be used when trying to process the image. This is fixed by limiting the number of bands to those usable by Pillow. -Buffer overruns were found when processing an SGI (CVE-2020-5311), PCX (CVE-2020-5312) -or FLI image (CVE-2020-5313). Checks have been added to prevent this. +Buffer overruns were found when processing an SGI (:cve:`CVE-2020-5311`), +PCX (:cve:`CVE-2020-5312`) or FLI image (:cve:`CVE-2020-5313`). Checks have been added +to prevent this. -CVE-2020-5310: Overflow checks have been added when calculating the size of a memory -block to be reallocated in the processing of a TIFF image. +:cve:`CVE-2020-5310`: Overflow checks have been added when calculating the size of a +memory block to be reallocated in the processing of a TIFF image. diff --git a/docs/releasenotes/7.1.0.rst b/docs/releasenotes/7.1.0.rst index 35e5c4464..fd3627e3c 100644 --- a/docs/releasenotes/7.1.0.rst +++ b/docs/releasenotes/7.1.0.rst @@ -74,11 +74,11 @@ Security This release includes security fixes. -* CVE-2020-10177 Fix multiple OOB reads in FLI decoding -* CVE-2020-10378 Fix bounds overflow in PCX decoding -* CVE-2020-10379 Fix two buffer overflows in TIFF decoding -* CVE-2020-10994 Fix bounds overflow in JPEG 2000 decoding -* CVE-2020-11538 Fix buffer overflow in SGI-RLE decoding +* :cve:`CVE-2020-10177` Fix multiple OOB reads in FLI decoding +* :cve:`CVE-2020-10378` Fix bounds overflow in PCX decoding +* :cve:`CVE-2020-10379` Fix two buffer overflows in TIFF decoding +* :cve:`CVE-2020-10994` Fix bounds overflow in JPEG 2000 decoding +* :cve:`CVE-2020-11538` Fix buffer overflow in SGI-RLE decoding Other Changes ============= diff --git a/docs/releasenotes/8.0.1.rst b/docs/releasenotes/8.0.1.rst index e50596e5c..3584a5d72 100644 --- a/docs/releasenotes/8.0.1.rst +++ b/docs/releasenotes/8.0.1.rst @@ -4,13 +4,11 @@ Security ======== -Update FreeType used in binary wheels to `2.10.4`_ to fix CVE-2020-15999_: +Update FreeType used in binary wheels to `2.10.4`_ to fix :cve:`CVE-2020-15999`: - A heap buffer overflow has been found in the handling of embedded PNG bitmaps, introduced in FreeType version 2.6. - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-15999 - If you use option ``FT_CONFIG_OPTION_USE_PNG`` you should upgrade immediately. We strongly recommend updating to Pillow 8.0.1 if you are using Pillow 8.0.0, which improved support for bitmap fonts. @@ -22,4 +20,3 @@ Pillow 8.0.0 and earlier are potentially vulnerable releases, including the last to support Python 2.7, namely Pillow 6.2.2. .. _2.10.4: https://sourceforge.net/projects/freetype/files/freetype2/2.10.4/ -.. _CVE-2020-15999: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-15999 diff --git a/requirements.txt b/requirements.txt index 9758f91fd..da5752cfd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,5 +10,6 @@ pyroma pytest pytest-cov sphinx>=2.4 +sphinx-issues sphinx-removed-in sphinx-rtd-theme From cfc45ab9c352e6cd43c9fa8d56e7b100084052b7 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 17 Dec 2020 06:49:13 +0200 Subject: [PATCH 083/186] Autolink PEP --- docs/releasenotes/6.2.0.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/releasenotes/6.2.0.rst b/docs/releasenotes/6.2.0.rst index 1bc82b72f..20a009cc1 100644 --- a/docs/releasenotes/6.2.0.rst +++ b/docs/releasenotes/6.2.0.rst @@ -96,7 +96,7 @@ Other Changes Removed bdist_wininst .exe installers ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -.exe installers fell out of favour with PEP 527, and will be deprecated in +.exe installers fell out of favour with :pep:`527`, and will be deprecated in Python 3.8. Pillow will no longer be distributing them. Wheels should be used instead. From 5c600adf4191e864568c1988cca4b045c7d05435 Mon Sep 17 00:00:00 2001 From: nulano Date: Thu, 17 Dec 2020 16:23:12 +0100 Subject: [PATCH 084/186] gha: add PyPy3.7 --- .github/workflows/test-windows.yml | 6 ++++-- .github/workflows/test.yml | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test-windows.yml b/.github/workflows/test-windows.yml index 91d41fdb0..562b2b7b4 100644 --- a/.github/workflows/test-windows.yml +++ b/.github/workflows/test-windows.yml @@ -8,7 +8,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.6", "3.7", "3.8", "3.9", "3.10-dev", "pypy3"] + python-version: ["pypy-3.6", "pypy-3.7", "3.6", "3.7", "3.8", "3.9", "3.10-dev"] architecture: ["x86", "x64"] include: - architecture: "x86" @@ -19,7 +19,9 @@ jobs: platform-msbuild: "x64" exclude: # PyPy does not support 64-bit on Windows - - python-version: "pypy3" + - python-version: "pypy-3.6" + architecture: "x64" + - python-version: "pypy-3.7" architecture: "x64" timeout-minutes: 30 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 51ce9d085..305ad7ba8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,7 +13,8 @@ jobs: "macOS-latest", ] python-version: [ - "pypy3", + "pypy-3.7", + "pypy-3.6", "3.10-dev", "3.9", "3.8", From 043d8dac0b5259d73036f8f49aecfafc439f6244 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 18 Dec 2020 23:42:16 +1100 Subject: [PATCH 085/186] Do not require packaging just for a DeprecationWarning --- src/PIL/ImageFont.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py index 78f8d8cde..c48d89835 100644 --- a/src/PIL/ImageFont.py +++ b/src/PIL/ImageFont.py @@ -31,8 +31,6 @@ import sys import warnings from io import BytesIO -from packaging.version import parse as parse_version - from . import Image, features from ._util import isDirectory, isPath @@ -167,14 +165,20 @@ class FreeTypeFont: self.index = index self.encoding = encoding - freetype_version = parse_version(features.version_module("freetype2")) - if freetype_version < parse_version("2.8"): - warnings.warn( - "Support for FreeType 2.7 is deprecated and will be removed in Pillow " - "9 (2022-01-02). Please upgrade to FreeType 2.8 or newer, preferably " - "FreeType 2.10.4 which fixes CVE-2020-15999.", - DeprecationWarning, - ) + try: + from packaging.version import parse as parse_version + except ImportError: + pass + else: + freetype_version = parse_version(features.version_module("freetype2")) + if freetype_version < parse_version("2.8"): + warnings.warn( + "Support for FreeType 2.7 is deprecated and will be removed" + " in Pillow 9 (2022-01-02). Please upgrade to FreeType 2.8 " + "or newer, preferably FreeType 2.10.4 which fixes " + "CVE-2020-15999.", + DeprecationWarning, + ) if layout_engine not in (LAYOUT_BASIC, LAYOUT_RAQM): layout_engine = LAYOUT_BASIC From 2b319f2ce45586aeb5cbfd7ed16d81c3b62bf0a4 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Fri, 18 Dec 2020 11:12:04 +0200 Subject: [PATCH 086/186] Simplify: remove class --- Tests/test_imagepath.py | 118 ++++++++++++++++++++-------------------- 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/Tests/test_imagepath.py b/Tests/test_imagepath.py index 7cc89ae39..01862f750 100644 --- a/Tests/test_imagepath.py +++ b/Tests/test_imagepath.py @@ -6,75 +6,75 @@ import pytest from PIL import Image, ImagePath -class TestImagePath: - def test_path(self): +def test_path(): - p = ImagePath.Path(list(range(10))) + p = ImagePath.Path(list(range(10))) - # sequence interface - assert len(p) == 5 - assert p[0] == (0.0, 1.0) - assert p[-1] == (8.0, 9.0) - assert list(p[:1]) == [(0.0, 1.0)] - with pytest.raises(TypeError) as cm: - p["foo"] - assert str(cm.value) == "Path indices must be integers, not str" - assert list(p) == [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0), (6.0, 7.0), (8.0, 9.0)] + # sequence interface + assert len(p) == 5 + assert p[0] == (0.0, 1.0) + assert p[-1] == (8.0, 9.0) + assert list(p[:1]) == [(0.0, 1.0)] + with pytest.raises(TypeError) as cm: + p["foo"] + assert str(cm.value) == "Path indices must be integers, not str" + assert list(p) == [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0), (6.0, 7.0), (8.0, 9.0)] - # method sanity check - assert p.tolist() == [ - (0.0, 1.0), - (2.0, 3.0), - (4.0, 5.0), - (6.0, 7.0), - (8.0, 9.0), - ] - assert p.tolist(1) == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] + # method sanity check + assert p.tolist() == [ + (0.0, 1.0), + (2.0, 3.0), + (4.0, 5.0), + (6.0, 7.0), + (8.0, 9.0), + ] + assert p.tolist(1) == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] - assert p.getbbox() == (0.0, 1.0, 8.0, 9.0) + assert p.getbbox() == (0.0, 1.0, 8.0, 9.0) - assert p.compact(5) == 2 - assert list(p) == [(0.0, 1.0), (4.0, 5.0), (8.0, 9.0)] + assert p.compact(5) == 2 + assert list(p) == [(0.0, 1.0), (4.0, 5.0), (8.0, 9.0)] - p.transform((1, 0, 1, 0, 1, 1)) - assert list(p) == [(1.0, 2.0), (5.0, 6.0), (9.0, 10.0)] + p.transform((1, 0, 1, 0, 1, 1)) + assert list(p) == [(1.0, 2.0), (5.0, 6.0), (9.0, 10.0)] - # alternative constructors - p = ImagePath.Path([0, 1]) - assert list(p) == [(0.0, 1.0)] - p = ImagePath.Path([0.0, 1.0]) - assert list(p) == [(0.0, 1.0)] - p = ImagePath.Path([0, 1]) - assert list(p) == [(0.0, 1.0)] - p = ImagePath.Path([(0, 1)]) - assert list(p) == [(0.0, 1.0)] - p = ImagePath.Path(p) - assert list(p) == [(0.0, 1.0)] - p = ImagePath.Path(p.tolist(0)) - assert list(p) == [(0.0, 1.0)] - p = ImagePath.Path(p.tolist(1)) - assert list(p) == [(0.0, 1.0)] - p = ImagePath.Path(array.array("f", [0, 1])) - assert list(p) == [(0.0, 1.0)] + # alternative constructors + p = ImagePath.Path([0, 1]) + assert list(p) == [(0.0, 1.0)] + p = ImagePath.Path([0.0, 1.0]) + assert list(p) == [(0.0, 1.0)] + p = ImagePath.Path([0, 1]) + assert list(p) == [(0.0, 1.0)] + p = ImagePath.Path([(0, 1)]) + assert list(p) == [(0.0, 1.0)] + p = ImagePath.Path(p) + assert list(p) == [(0.0, 1.0)] + p = ImagePath.Path(p.tolist(0)) + assert list(p) == [(0.0, 1.0)] + p = ImagePath.Path(p.tolist(1)) + assert list(p) == [(0.0, 1.0)] + p = ImagePath.Path(array.array("f", [0, 1])) + assert list(p) == [(0.0, 1.0)] - arr = array.array("f", [0, 1]) - if hasattr(arr, "tobytes"): - p = ImagePath.Path(arr.tobytes()) - else: - p = ImagePath.Path(arr.tostring()) - assert list(p) == [(0.0, 1.0)] + arr = array.array("f", [0, 1]) + if hasattr(arr, "tobytes"): + p = ImagePath.Path(arr.tobytes()) + else: + p = ImagePath.Path(arr.tostring()) + assert list(p) == [(0.0, 1.0)] - def test_overflow_segfault(self): - # Some Pythons fail getting the argument as an integer, and it falls - # through to the sequence. Seeing this on 32-bit Windows. - with pytest.raises((TypeError, MemoryError)): - # post patch, this fails with a memory error - x = evil() - # This fails due to the invalid malloc above, - # and segfaults - for i in range(200000): - x[i] = b"0" * 16 +def test_overflow_segfault(): + # Some Pythons fail getting the argument as an integer, and it falls + # through to the sequence. Seeing this on 32-bit Windows. + with pytest.raises((TypeError, MemoryError)): + # post patch, this fails with a memory error + x = evil() + + # This fails due to the invalid malloc above, + # and segfaults + for i in range(200000): + x[i] = b"0" * 16 class evil: From ceaed2e058c8239237fe1ae1920d30f277a804f8 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Fri, 18 Dec 2020 22:09:44 +0200 Subject: [PATCH 087/186] Add tests for ImagePath.Path --- Tests/test_imagepath.py | 101 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/Tests/test_imagepath.py b/Tests/test_imagepath.py index 01862f750..0835fdb43 100644 --- a/Tests/test_imagepath.py +++ b/Tests/test_imagepath.py @@ -1,4 +1,5 @@ import array +import math import struct import pytest @@ -64,6 +65,106 @@ def test_path(): assert list(p) == [(0.0, 1.0)] +def test_invalid_coords(): + # Arrange + coords = ["a", "b"] + + # Act / Assert + with pytest.raises(SystemError): + ImagePath.Path(coords) + + +def test_path_odd_number_of_coordinates(): + # Arrange + coords = [0] + + # Act / Assert + with pytest.raises(ValueError) as e: + ImagePath.Path(coords) + + assert str(e.value) == "wrong number of coordinates" + + +@pytest.mark.parametrize( + "coords, expected", + [ + ([0, 1, 2, 3], (0.0, 1.0, 2.0, 3.0)), + ([3, 2, 1, 0], (1.0, 0.0, 3.0, 2.0)), + ], +) +def test_getbbox(coords, expected): + # Arrange + p = ImagePath.Path(coords) + + # Act / Assert + assert p.getbbox() == expected + + +def test_getbbox_no_args(): + # Arrange + p = ImagePath.Path([0, 1, 2, 3]) + + # Act / Assert + with pytest.raises(TypeError): + p.getbbox(1) + + +@pytest.mark.parametrize( + "coords, expected", + [ + (0, []), + (list(range(6)), [(0.0, 3.0), (4.0, 9.0), (8.0, 15.0)]), + ], +) +def test_map(coords, expected): + # Arrange + p = ImagePath.Path(coords) + + # Act + # Modifies the path in-place + p.map(lambda x, y: (x * 2, y * 3)) + + # Assert + assert list(p) == expected + + +def test_transform(): + # Arrange + p = ImagePath.Path([0, 1, 2, 3]) + theta = math.pi / 15 + + # Act + # Affine transform, in-place + p.transform( + (math.cos(theta), math.sin(theta), 20, -math.sin(theta), math.cos(theta), 20), + ) + + # Assert + assert p.tolist() == [ + (20.20791169081776, 20.978147600733806), + (22.58003027392089, 22.518619420565898), + ] + + +def test_transform_with_wrap(): + # Arrange + p = ImagePath.Path([0, 1, 2, 3]) + theta = math.pi / 15 + + # Act + # Affine transform, in-place, with wrap parameter + p.transform( + (math.cos(theta), math.sin(theta), 20, -math.sin(theta), math.cos(theta), 20), + 1.0, + ) + + # Assert + assert p.tolist() == [ + (0.20791169081775962, 20.978147600733806), + (0.5800302739208902, 22.518619420565898), + ] + + def test_overflow_segfault(): # Some Pythons fail getting the argument as an integer, and it falls # through to the sequence. Seeing this on 32-bit Windows. From 162fbc679bca8c65bf575758e7f5c5880457611f Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 18 Dec 2020 23:28:57 +1100 Subject: [PATCH 088/186] Added packaging --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index 9758f91fd..89db88ad4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,6 +6,7 @@ jarn.viewdoc olefile pycodestyle pyflakes +packaging pyroma pytest pytest-cov From d3702fd6143d3739e6d7725ca8cf82650e048942 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Sat, 21 Nov 2020 13:43:44 +0200 Subject: [PATCH 089/186] Remove unused Travis CI config --- .ci/after_success.sh | 6 ------ .ci/install.sh | 6 +----- .ci/test.sh | 5 ----- depends/diffcover-install.sh | 8 -------- depends/diffcover-run.sh | 5 ----- requirements.txt | 2 -- 6 files changed, 1 insertion(+), 31 deletions(-) delete mode 100755 depends/diffcover-install.sh delete mode 100755 depends/diffcover-run.sh diff --git a/.ci/after_success.sh b/.ci/after_success.sh index 762670f10..01889607b 100755 --- a/.ci/after_success.sh +++ b/.ci/after_success.sh @@ -11,9 +11,3 @@ fi if [[ $TRAVIS ]]; then codecov --flags TravisCI fi - -if [ "$TRAVIS_PYTHON_VERSION" == "3.9" ]; then - # Coverage and quality reports on just the latest diff. - depends/diffcover-install.sh - depends/diffcover-run.sh -fi diff --git a/.ci/install.sh b/.ci/install.sh index db259bdca..3e1d64e34 100755 --- a/.ci/install.sh +++ b/.ci/install.sh @@ -34,10 +34,9 @@ python3 -m pip install test-image-results # TODO Remove condition when numpy supports 3.10 if ! [ "$GHA_PYTHON_VERSION" == "3.10-dev" ]; then python3 -m pip install numpy ; fi -# TODO Remove when 3.8 / 3.9 / PyPy3 includes setuptools 49.3.2+: +# TODO Remove when 3.8 / 3.9 includes setuptools 49.3.2+: if [ "$GHA_PYTHON_VERSION" == "3.8" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi if [ "$GHA_PYTHON_VERSION" == "3.9" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi -if [ "$TRAVIS_PYTHON_VERSION" == "pypy3.6-7.3.1" ]; then python3 -m pip install -U "setuptools>=49.3.2" ; fi # PyQt5 doesn't support PyPy3 # Wheel doesn't yet support 3.10 @@ -48,9 +47,6 @@ if [[ $GHA_PYTHON_VERSION == 3.* && $GHA_PYTHON_VERSION != "3.10-dev" ]]; then python3 -m pip install pyqt5 fi -# docs only on Python 3.9 -if [ "$TRAVIS_PYTHON_VERSION" == "3.9" ]; then python3 -m pip install -r requirements.txt ; fi - # webp pushd depends && ./install_webp.sh && popd diff --git a/.ci/test.sh b/.ci/test.sh index 1396445e0..5a19ec9b4 100755 --- a/.ci/test.sh +++ b/.ci/test.sh @@ -3,8 +3,3 @@ set -e python -bb -m pytest -v -x -W always --cov PIL --cov Tests --cov-report term Tests - -# Docs -if [ "$TRAVIS_PYTHON_VERSION" == "3.9" ] && [ "$TRAVIS_CPU_ARCH" == "amd64" ]; then - make doccheck -fi diff --git a/depends/diffcover-install.sh b/depends/diffcover-install.sh deleted file mode 100755 index 18be4f9f9..000000000 --- a/depends/diffcover-install.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash -# Fetch the remote master branch before running diff-cover on Travis CI. -# https://github.com/Bachmann1234/diff-cover#troubleshooting -git fetch origin master:refs/remotes/origin/master - -# CFLAGS=-O0 means build with no optimisation. -# Makes build much quicker for lxml and other dependencies. -time CFLAGS=-O0 python3 -m pip install diff_cover diff --git a/depends/diffcover-run.sh b/depends/diffcover-run.sh deleted file mode 100755 index b007494e9..000000000 --- a/depends/diffcover-run.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash -coverage xml -diff-cover coverage.xml -diff-quality --violation=pyflakes -diff-quality --violation=pycodestyle diff --git a/requirements.txt b/requirements.txt index 9758f91fd..ea57e863b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,8 +4,6 @@ check-manifest coverage jarn.viewdoc olefile -pycodestyle -pyflakes pyroma pytest pytest-cov From 9e21ef7338cdf5e09aab3dcadea80988863c931d Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Mon, 14 Dec 2020 20:35:04 +0200 Subject: [PATCH 090/186] Remove old Travis CI config --- .ci/after_success.sh | 4 ---- .ci/install.sh | 2 -- .github/CONTRIBUTING.md | 4 ++-- .github/mergify.yml | 1 - README.md | 15 ++++++--------- RELEASING.md | 4 ++-- Tests/bench_cffi_access.py | 2 +- depends/README.rst | 4 ++-- docs/about.rst | 6 +++--- docs/index.rst | 20 ++++++++------------ 10 files changed, 24 insertions(+), 38 deletions(-) diff --git a/.ci/after_success.sh b/.ci/after_success.sh index 01889607b..ff91b481e 100755 --- a/.ci/after_success.sh +++ b/.ci/after_success.sh @@ -7,7 +7,3 @@ if [[ $MATRIX_DOCKER ]]; then else coverage xml fi - -if [[ $TRAVIS ]]; then - codecov --flags TravisCI -fi diff --git a/.ci/install.sh b/.ci/install.sh index 3e1d64e34..9372d0c51 100755 --- a/.ci/install.sh +++ b/.ci/install.sh @@ -21,8 +21,6 @@ sudo apt-get -qq install libfreetype6-dev liblcms2-dev python3-tk\ ghostscript libffi-dev libjpeg-turbo-progs libopenjp2-7-dev\ cmake imagemagick libharfbuzz-dev libfribidi-dev -if [[ $TRAVIS_CPU_ARCH == "s390x" ]]; then sudo chown $USER ~/.cache/pip/wheels ; fi - python3 -m pip install --upgrade pip PYTHONOPTIMIZE=0 python3 -m pip install cffi python3 -m pip install coverage diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index a65487d5e..e20296da5 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -9,7 +9,7 @@ Please send a pull request to the master branch. Please include [documentation]( - Fork the Pillow repository. - Create a branch from master. - Develop bug fixes, features, tests, etc. -- Run the test suite. You can enable [Travis CI](https://travis-ci.com/account/repositories) and [AppVeyor](https://ci.appveyor.com/projects/new) on your repo to catch test failures prior to the pull request, and [Codecov](https://codecov.io/gh) to see if the changed code is covered by tests. +- Run the test suite. You can enable [GitHub Actions](http://github.com/MY-USERNAME/Pillow/actions) and [AppVeyor](https://ci.appveyor.com/projects/new) on your repo to catch test failures prior to the pull request, and [Codecov](https://codecov.io/gh) to see if the changed code is covered by tests. - Create a pull request to pull the changes from your branch to the Pillow master. ### Guidelines @@ -17,7 +17,7 @@ Please send a pull request to the master branch. Please include [documentation]( - Separate code commits from reformatting commits. - Provide tests for any newly added code. - Follow PEP 8. -- When committing only documentation changes please include `[ci skip]` in the commit message to avoid running tests on Travis CI and AppVeyor. +- When committing only documentation changes please include `[ci skip]` in the commit message to avoid running tests on AppVeyor. ## Reporting Issues diff --git a/.github/mergify.yml b/.github/mergify.yml index b37db48d4..4b8b113d3 100644 --- a/.github/mergify.yml +++ b/.github/mergify.yml @@ -7,7 +7,6 @@ pull_request_rules: - status-success=Test Successful - status-success=Docker Test Successful - status-success=Windows Test Successful -# - status-success=Travis CI - Pull Request - status-success=continuous-integration/appveyor/pr actions: merge: diff --git a/README.md b/README.md index 6c323413d..0408f4c28 100644 --- a/README.md +++ b/README.md @@ -24,15 +24,6 @@ As of 2019, Pillow development is tests - Travis CI build status (Linux) - Travis CI build status (macOS) - AppVeyor CI build status (Windows) GitHub Actions build status (Lint) @@ -45,6 +36,12 @@ As of 2019, Pillow development is GitHub Actions build status (Test Docker) + AppVeyor CI build status (Windows) + Travis CI build status (macOS) Code coverage diff --git a/RELEASING.md b/RELEASING.md index 5e00e5724..b3845d090 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -6,7 +6,7 @@ Released quarterly on January 2nd, April 1st, July 1st and October 15th. * [ ] Open a release ticket e.g. https://github.com/python-pillow/Pillow/issues/3154 * [ ] Develop and prepare release in `master` branch. -* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), [Travis CI](https://travis-ci.com/github/python-pillow/Pillow) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in `master` branch. +* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in `master` branch. * [ ] Check that all of the wheel builds [Pillow Wheel Builder](https://github.com/python-pillow/pillow-wheels) pass the tests in Travis CI. * [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), update version identifier in `src/PIL/_version.py` * [ ] Update `CHANGES.rst`. @@ -41,7 +41,7 @@ Released as needed for security, installation or critical bug fixes. -* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions), [Travis CI](https://travis-ci.com/github/python-pillow/Pillow) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in release branch e.g. `5.2.x`. +* [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in release branch e.g. `5.2.x`. * [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), update version identifier in `src/PIL/_version.py` * [ ] Run pre-release check via `make release-test`. * [ ] Create tag for release e.g.: diff --git a/Tests/bench_cffi_access.py b/Tests/bench_cffi_access.py index f9edcf09a..87cad699d 100644 --- a/Tests/bench_cffi_access.py +++ b/Tests/bench_cffi_access.py @@ -4,7 +4,7 @@ from PIL import PyAccess from .helper import hopper -# Not running this test by default. No DOS against Travis CI. +# Not running this test by default. No DOS against CI. def iterate_get(size, access): diff --git a/depends/README.rst b/depends/README.rst index ce88fa47b..b69c9dcbf 100644 --- a/depends/README.rst +++ b/depends/README.rst @@ -3,7 +3,7 @@ Depends ``install_openjpeg.sh``, ``install_webp.sh``, ``install_imagequant.sh``, ``install_raqm.sh`` and ``install_raqm_cmake.sh`` can be used to download, -build & install non-packaged dependencies; useful for testing with Travis CI. +build & install non-packaged dependencies; useful for testing on CI. ``install_extra_test_images.sh`` can be used to install additional test images -that are used for Travis CI and AppVeyor. +that are used by CI. diff --git a/docs/about.rst b/docs/about.rst index acd361fa8..51b583ea0 100644 --- a/docs/about.rst +++ b/docs/about.rst @@ -6,13 +6,13 @@ Goals The fork author's goal is to foster and support active development of PIL through: -- Continuous integration testing via `Travis CI`_, `AppVeyor`_ and `GitHub Actions`_ +- Continuous integration testing via `GitHub Actions`_, `AppVeyor`_ and `Travis CI`_ - Publicized development activity on `GitHub`_ - Regular releases to the `Python Package Index`_ -.. _Travis CI: https://travis-ci.com/github/python-pillow/Pillow -.. _AppVeyor: https://ci.appveyor.com/project/Python-pillow/pillow .. _GitHub Actions: https://github.com/python-pillow/Pillow/actions +.. _AppVeyor: https://ci.appveyor.com/project/Python-pillow/pillow +.. _Travis CI: https://travis-ci.com/github/python-pillow/pillow-wheels .. _GitHub: https://github.com/python-pillow/Pillow .. _Python Package Index: https://pypi.org/project/Pillow/ diff --git a/docs/index.rst b/docs/index.rst index eafcb1fec..d2aca4bc4 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -9,18 +9,6 @@ Pillow for enterprise is available via the Tidelift Subscription. `Learn more Date: Fri, 18 Dec 2020 18:51:13 +1100 Subject: [PATCH 091/186] GitHub Actions have been added to wheels [ci skip] --- RELEASING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASING.md b/RELEASING.md index b3845d090..db7b22445 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -7,7 +7,7 @@ Released quarterly on January 2nd, April 1st, July 1st and October 15th. * [ ] Open a release ticket e.g. https://github.com/python-pillow/Pillow/issues/3154 * [ ] Develop and prepare release in `master` branch. * [ ] Check [GitHub Actions](https://github.com/python-pillow/Pillow/actions) and [AppVeyor](https://ci.appveyor.com/project/python-pillow/Pillow) to confirm passing tests in `master` branch. -* [ ] Check that all of the wheel builds [Pillow Wheel Builder](https://github.com/python-pillow/pillow-wheels) pass the tests in Travis CI. +* [ ] Check that all of the wheel builds [Pillow Wheel Builder](https://github.com/python-pillow/pillow-wheels) pass the tests in Travis CI and GitHub Actions. * [ ] In compliance with [PEP 440](https://www.python.org/dev/peps/pep-0440/), update version identifier in `src/PIL/_version.py` * [ ] Update `CHANGES.rst`. * [ ] Run pre-release check via `make release-test` in a freshly cloned repo. From b0af0d4076a47ae9612c0d8e946e9ae14e9c4aef Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 18 Dec 2020 19:27:22 +1100 Subject: [PATCH 092/186] Travis CI is no longer used --- Tests/helper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/helper.py b/Tests/helper.py index d76389621..be3bdb76f 100644 --- a/Tests/helper.py +++ b/Tests/helper.py @@ -270,7 +270,7 @@ def on_github_actions(): def on_ci(): - # GitHub Actions, Travis and AppVeyor have "CI" + # GitHub Actions and AppVeyor have "CI" return "CI" in os.environ From 924b1496c3618f91aeb9875f7294fb526f8c4d6f Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Fri, 18 Dec 2020 12:37:24 +0200 Subject: [PATCH 093/186] Show example link instead of hiding inside hyperlink Co-authored-by: Andrew Murray <3112309+radarhere@users.noreply.github.com> --- .github/CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index e20296da5..563fcda6a 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -9,7 +9,7 @@ Please send a pull request to the master branch. Please include [documentation]( - Fork the Pillow repository. - Create a branch from master. - Develop bug fixes, features, tests, etc. -- Run the test suite. You can enable [GitHub Actions](http://github.com/MY-USERNAME/Pillow/actions) and [AppVeyor](https://ci.appveyor.com/projects/new) on your repo to catch test failures prior to the pull request, and [Codecov](https://codecov.io/gh) to see if the changed code is covered by tests. +- Run the test suite. You can enable GitHub Actions (https://github.com/MY-USERNAME/Pillow/actions) and [AppVeyor](https://ci.appveyor.com/projects/new) on your repo to catch test failures prior to the pull request, and [Codecov](https://codecov.io/gh) to see if the changed code is covered by tests. - Create a pull request to pull the changes from your branch to the Pillow master. ### Guidelines From 7673cb7549e5071d39e76419204c56b0f07199bb Mon Sep 17 00:00:00 2001 From: Christoph Gohlke Date: Sat, 19 Dec 2020 14:57:55 -0800 Subject: [PATCH 094/186] Fix dereferencing potential null pointer --- src/_imaging.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/_imaging.c b/src/_imaging.c index 3635d2afa..53a03fc88 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -3180,6 +3180,10 @@ _draw_polygon(ImagingDrawObject* self, PyObject* args) /* Copy list of vertices to array */ ixy = (int*) calloc(n, 2 * sizeof(int)); + if (ixy == NULL) { + free(xy); + return NULL; + } for (i = 0; i < n; i++) { ixy[i+i] = (int) xy[i+i]; From c1adae6f7010c514331f1ca0f589f96ead3e04fa Mon Sep 17 00:00:00 2001 From: Christoph Gohlke Date: Sat, 19 Dec 2020 15:07:51 -0800 Subject: [PATCH 095/186] Remove duplicate code --- src/_imagingcms.c | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/_imagingcms.c b/src/_imagingcms.c index 5693ccbab..491866f74 100644 --- a/src/_imagingcms.c +++ b/src/_imagingcms.c @@ -1147,10 +1147,6 @@ cms_profile_getattr_media_white_point_temperature(CmsProfileObject *self, void* } XYZ = (cmsCIEXYZ*) cmsReadTag(self->profile, info); - if (!XYZ) { - Py_INCREF(Py_None); - return Py_None; - } if (XYZ == NULL || XYZ->X == 0) { Py_INCREF(Py_None); return Py_None; @@ -1499,8 +1495,6 @@ setup_module(PyObject* m) { PyObject *v; int vn; - d = PyModule_GetDict(m); - CmsProfile_Type.tp_new = PyType_GenericNew; /* Ready object types */ From 2f48b036aded11467fcef1b9d22f14748f1b8d88 Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Sat, 19 Dec 2020 15:10:47 -0800 Subject: [PATCH 096/186] =?UTF-8?q?Update=20isort=20URL:=20timothycrosley/?= =?UTF-8?q?isort=20=E2=86=92=20PyCQA/isort?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 459251d77..8d38375f0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -8,7 +8,7 @@ repos: files: \.py$ types: [] - - repo: https://github.com/timothycrosley/isort + - repo: https://github.com/PyCQA/isort rev: 377d260ffa6f746693f97b46d95025afc4bd8275 # frozen: 5.4.2 hooks: - id: isort From fd4b0609efbbc5d2135c1169fda2567bc6c90899 Mon Sep 17 00:00:00 2001 From: Christoph Gohlke Date: Sat, 19 Dec 2020 15:58:25 -0800 Subject: [PATCH 097/186] Fix dereferencing of potential null pointers --- src/libImaging/Histo.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/libImaging/Histo.c b/src/libImaging/Histo.c index 050c2840f..66d696a2a 100644 --- a/src/libImaging/Histo.c +++ b/src/libImaging/Histo.c @@ -29,10 +29,12 @@ void ImagingHistogramDelete(ImagingHistogram h) { - if (h->histogram) { - free(h->histogram); + if (h) { + if (h->histogram) { + free(h->histogram); + } + free(h); } - free(h); } ImagingHistogram @@ -42,11 +44,18 @@ ImagingHistogramNew(Imaging im) /* Create histogram descriptor */ h = calloc(1, sizeof(struct ImagingHistogramInstance)); + if (h == NULL) { + return NULL; + } strncpy(h->mode, im->mode, IMAGING_MODE_LENGTH-1); h->mode[IMAGING_MODE_LENGTH-1] = 0; h->bands = im->bands; h->histogram = calloc(im->pixelsize, 256 * sizeof(long)); + if (h->histogram == NULL) { + free(h); + return NULL; + } return h; } @@ -75,6 +84,9 @@ ImagingGetHistogram(Imaging im, Imaging imMask, void* minmax) } h = ImagingHistogramNew(im); + if (h == NULL) { + return NULL; + } if (imMask) { /* mask */ From 5474b2c7d46543e918adeeeddbef4374eb5102fe Mon Sep 17 00:00:00 2001 From: Jon Dufresne Date: Sat, 19 Dec 2020 17:55:54 -0800 Subject: [PATCH 098/186] Update some doc code blocks to the 'pycon' lexer These code blocks represent Python console sessions, not Python source code. The pycon lexer understands the ">>>" prompt and output (e.g. a traceback). --- docs/releasenotes/7.1.1.rst | 2 +- docs/releasenotes/7.1.2.rst | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/releasenotes/7.1.1.rst b/docs/releasenotes/7.1.1.rst index 4c33adf8e..2169e6a05 100644 --- a/docs/releasenotes/7.1.1.rst +++ b/docs/releasenotes/7.1.1.rst @@ -7,7 +7,7 @@ Fix regression seeking PNG files This fixes a regression introduced in 7.1.0 when adding support for APNG files when calling ``seek`` and ``tell``: -.. code-block:: python +.. code-block:: pycon >>> from PIL import Image >>> with Image.open("Tests/images/hopper.png") as im: diff --git a/docs/releasenotes/7.1.2.rst b/docs/releasenotes/7.1.2.rst index c9d0d54eb..b12d84e33 100644 --- a/docs/releasenotes/7.1.2.rst +++ b/docs/releasenotes/7.1.2.rst @@ -9,7 +9,7 @@ This fixes a regression introduced in 7.1.0 when adding support for APNG files. When calling ``seek(n)`` on a regular PNG where ``n > 0``, it failed to raise an ``EOFError`` as it should have done, resulting in: -.. code-block:: python +.. code-block:: pycon AttributeError: 'NoneType' object has no attribute 'read' From 75542fea6da91154f39971b32f08d3ac5b389c90 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 20 Dec 2020 13:00:10 +1100 Subject: [PATCH 099/186] Replaced PyErr_NoMemory with ImagingError_MemoryError --- src/_imaging.c | 6 +++--- src/decode.c | 6 +++--- src/encode.c | 16 ++++++++-------- src/path.c | 6 +++--- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/_imaging.c b/src/_imaging.c index 3635d2afa..d81191b97 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -377,7 +377,7 @@ getlist(PyObject* arg, Py_ssize_t* length, const char* wrong_length, int type) calloc checks for overflow */ list = calloc(n, type & 0xff); if ( ! list) { - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } seq = PySequence_Fast(arg, must_be_sequence); @@ -789,7 +789,7 @@ _prepare_lut_table(PyObject* table, Py_ssize_t table_size) if (free_table_data) { free(table_data); } - return (INT16*) PyErr_NoMemory(); + return (INT16*) ImagingError_MemoryError(); } for (i = 0; i < table_size; i++) { @@ -2234,7 +2234,7 @@ _getprojection(ImagingObject* self, PyObject* args) if (xprofile == NULL || yprofile == NULL) { free(xprofile); free(yprofile); - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } ImagingGetProjection(self->image, (unsigned char *)xprofile, (unsigned char *)yprofile); diff --git a/src/decode.c b/src/decode.c index 0ce381aa1..5c57fea5d 100644 --- a/src/decode.c +++ b/src/decode.c @@ -80,7 +80,7 @@ PyImaging_DecoderNew(int contextsize) context = (void*) calloc(1, contextsize); if (!context) { Py_DECREF(decoder); - (void) PyErr_NoMemory(); + (void) ImagingError_MemoryError(); return NULL; } } else { @@ -204,14 +204,14 @@ _setimage(ImagingDecoderObject* decoder, PyObject* args) if (state->bits > 0) { if (!state->bytes) { if (state->xsize > ((INT_MAX / state->bits)-7)){ - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } state->bytes = (state->bits * state->xsize+7)/8; } /* malloc check ok, overflow checked above */ state->buffer = (UINT8*) malloc(state->bytes); if (!state->buffer) { - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } } diff --git a/src/encode.c b/src/encode.c index 41f28722c..d3e15fcd2 100644 --- a/src/encode.c +++ b/src/encode.c @@ -72,7 +72,7 @@ PyImaging_EncoderNew(int contextsize) context = (void*) calloc(1, contextsize); if (!context) { Py_DECREF(encoder); - (void) PyErr_NoMemory(); + (void) ImagingError_MemoryError(); return NULL; } } else { @@ -194,7 +194,7 @@ _encode_to_file(ImagingEncoderObject* encoder, PyObject* args) /* malloc check ok, either constant int, or checked by PyArg_ParseTuple */ buf = (UINT8*) malloc(bufsize); if (!buf) { - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } ImagingSectionEnter(&cookie); @@ -271,13 +271,13 @@ _setimage(ImagingEncoderObject* encoder, PyObject* args) /* Allocate memory buffer (if bits field is set) */ if (state->bits > 0) { if (state->xsize > ((INT_MAX / state->bits)-7)) { - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } state->bytes = (state->bits * state->xsize+7)/8; /* malloc check ok, overflow checked above */ state->buffer = (UINT8*) malloc(state->bytes); if (!state->buffer) { - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } } @@ -604,7 +604,7 @@ PyImaging_ZipEncoderNew(PyObject* self, PyObject* args) /* malloc check ok, size comes from PyArg_ParseTuple */ char* p = malloc(dictionary_size); if (!p) { - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } memcpy(p, dictionary, dictionary_size); dictionary = p; @@ -1005,7 +1005,7 @@ static unsigned int* get_qtables_arrays(PyObject* qtables, int* qtablesLen) { qarrays = (unsigned int*) malloc(num_tables * DCTSIZE2 * sizeof(unsigned int)); if (!qarrays) { Py_DECREF(tables); - PyErr_NoMemory(); + ImagingError_MemoryError(); return NULL; } for (i = 0; i < num_tables; i++) { @@ -1091,7 +1091,7 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args) /* malloc check ok, length is from python parsearg */ char* p = malloc(extra_size); // Freed in JpegEncode, Case 5 if (!p) { - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } memcpy(p, extra, extra_size); extra = p; @@ -1106,7 +1106,7 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args) if (extra) { free(extra); } - return PyErr_NoMemory(); + return ImagingError_MemoryError(); } memcpy(pp, rawExif, rawExifLen); rawExif = pp; diff --git a/src/path.c b/src/path.c index 8eba81aa4..fb72d1a68 100644 --- a/src/path.c +++ b/src/path.c @@ -53,16 +53,16 @@ alloc_array(Py_ssize_t count) { double* xy; if (count < 0) { - PyErr_NoMemory(); + ImagingError_MemoryError(); return NULL; } if ((unsigned long long)count > (SIZE_MAX / (2 * sizeof(double))) - 1 ) { - PyErr_NoMemory(); + ImagingError_MemoryError(); return NULL; } xy = malloc(2 * count * sizeof(double) + 1); if (!xy) { - PyErr_NoMemory(); + ImagingError_MemoryError(); } return xy; } From b7fb39fff817d25739aa4ef1ba5b2c10089858ae Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 20 Dec 2020 12:28:52 +1100 Subject: [PATCH 100/186] Use ImagingError_MemoryError NULL return value --- src/_imaging.c | 6 ++---- src/encode.c | 3 +-- src/path.c | 6 ++---- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/_imaging.c b/src/_imaging.c index d81191b97..d4d392d9b 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -2711,8 +2711,7 @@ _font_getmask(ImagingFontObject* self, PyObject* args) im = ImagingNew(self->bitmap->mode, textwidth(self, text), self->ysize); if (!im) { free(text); - ImagingError_MemoryError(); - return NULL; + return ImagingError_MemoryError(); } b = 0; @@ -3933,8 +3932,7 @@ _set_blocks_max(PyObject* self, PyObject* args) if ( ! ImagingMemorySetBlocksMax(&ImagingDefaultArena, blocks_max)) { - ImagingError_MemoryError(); - return NULL; + return ImagingError_MemoryError(); } Py_INCREF(Py_None); diff --git a/src/encode.c b/src/encode.c index d3e15fcd2..57ce42734 100644 --- a/src/encode.c +++ b/src/encode.c @@ -1005,8 +1005,7 @@ static unsigned int* get_qtables_arrays(PyObject* qtables, int* qtablesLen) { qarrays = (unsigned int*) malloc(num_tables * DCTSIZE2 * sizeof(unsigned int)); if (!qarrays) { Py_DECREF(tables); - ImagingError_MemoryError(); - return NULL; + return ImagingError_MemoryError(); } for (i = 0; i < num_tables; i++) { table = PySequence_Fast_GET_ITEM(tables, i); diff --git a/src/path.c b/src/path.c index fb72d1a68..62e7e15b5 100644 --- a/src/path.c +++ b/src/path.c @@ -53,12 +53,10 @@ alloc_array(Py_ssize_t count) { double* xy; if (count < 0) { - ImagingError_MemoryError(); - return NULL; + return ImagingError_MemoryError(); } if ((unsigned long long)count > (SIZE_MAX / (2 * sizeof(double))) - 1 ) { - ImagingError_MemoryError(); - return NULL; + return ImagingError_MemoryError(); } xy = malloc(2 * count * sizeof(double) + 1); if (!xy) { From 15dd7aef9f0e585d8cbcb36c4ff42cf7d996d529 Mon Sep 17 00:00:00 2001 From: Christoph Gohlke Date: Sat, 19 Dec 2020 19:35:21 -0800 Subject: [PATCH 101/186] Return ImagingError_MemoryError --- src/libImaging/Histo.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libImaging/Histo.c b/src/libImaging/Histo.c index 66d696a2a..5ef72e6d3 100644 --- a/src/libImaging/Histo.c +++ b/src/libImaging/Histo.c @@ -54,7 +54,7 @@ ImagingHistogramNew(Imaging im) h->histogram = calloc(im->pixelsize, 256 * sizeof(long)); if (h->histogram == NULL) { free(h); - return NULL; + return (ImagingHistogram) ImagingError_MemoryError(); } return h; From fd14616dbbe12f477bcd695552659aad949b56eb Mon Sep 17 00:00:00 2001 From: Christoph Gohlke Date: Sat, 19 Dec 2020 19:37:05 -0800 Subject: [PATCH 102/186] Return ImagingError_MemoryError --- src/libImaging/Histo.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libImaging/Histo.c b/src/libImaging/Histo.c index 5ef72e6d3..923fa28d5 100644 --- a/src/libImaging/Histo.c +++ b/src/libImaging/Histo.c @@ -45,7 +45,7 @@ ImagingHistogramNew(Imaging im) /* Create histogram descriptor */ h = calloc(1, sizeof(struct ImagingHistogramInstance)); if (h == NULL) { - return NULL; + return (ImagingHistogram) ImagingError_MemoryError(); } strncpy(h->mode, im->mode, IMAGING_MODE_LENGTH-1); h->mode[IMAGING_MODE_LENGTH-1] = 0; From d1e706d75641b6900a632801f58e6db8400be9d5 Mon Sep 17 00:00:00 2001 From: Christoph Gohlke Date: Sat, 19 Dec 2020 19:42:29 -0800 Subject: [PATCH 103/186] return ImagingError_MemoryError --- src/_imaging.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/_imaging.c b/src/_imaging.c index 53a03fc88..ca4c017d5 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -3182,7 +3182,7 @@ _draw_polygon(ImagingDrawObject* self, PyObject* args) ixy = (int*) calloc(n, 2 * sizeof(int)); if (ixy == NULL) { free(xy); - return NULL; + return ImagingError_MemoryError(); } for (i = 0; i < n; i++) { From 889409ded385b40187af7e6aa5c9018e0ef63b70 Mon Sep 17 00:00:00 2001 From: Hollow Man Date: Sun, 20 Dec 2020 22:31:25 +0800 Subject: [PATCH 104/186] =?UTF-8?q?Fix=20use=20of=C2=A0a=C2=A0versus=C2=A0?= =?UTF-8?q?an=20in=20ImageCms.rst?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit an color -> a color --- docs/reference/ImageCms.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/ImageCms.rst b/docs/reference/ImageCms.rst index 8fed4d092..f938e63a0 100644 --- a/docs/reference/ImageCms.rst +++ b/docs/reference/ImageCms.rst @@ -200,7 +200,7 @@ can be easily displayed in a chromaticity diagram, for example). The chromatic adaption matrix converts a color measured using the actual illumination conditions and relative to the actual adopted - white, to an color relative to the PCS adopted white, with + white, to a color relative to the PCS adopted white, with complete adaptation from the actual adopted white chromaticity to the PCS adopted white chromaticity (see 9.2.15 of ICC.1:2010). From 0a1dcfc55a0f1f94115a5708c51867268b9636b7 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 21 Dec 2020 09:10:19 +1100 Subject: [PATCH 105/186] Fix 3rd level menu item background-color in dark mode [ci skip] --- docs/resources/css/dark.css | 1 + docs/resources/css/light.css | 1 + docs/resources/js/script.js | 1 - 3 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/resources/css/dark.css b/docs/resources/css/dark.css index 2ed958429..cc213d674 100644 --- a/docs/resources/css/dark.css +++ b/docs/resources/css/dark.css @@ -1196,6 +1196,7 @@ color: rgb(166, 158, 146); } + .wy-menu-vertical li.toctree-l2.current a, .wy-menu-vertical li.toctree-l3.current a { background-color: #363636; } diff --git a/docs/resources/css/light.css b/docs/resources/css/light.css index ae3debc91..04edd7b16 100644 --- a/docs/resources/css/light.css +++ b/docs/resources/css/light.css @@ -1,5 +1,6 @@ @media (prefers-color-scheme: light) { + .wy-menu-vertical li.toctree-l2.current a, .wy-menu-vertical li.toctree-l3.current a { background-color: #c9c9c9; } diff --git a/docs/resources/js/script.js b/docs/resources/js/script.js index d58571d6d..5cb6494ea 100644 --- a/docs/resources/js/script.js +++ b/docs/resources/js/script.js @@ -24,7 +24,6 @@ jQuery(document).ready(function ($) { var $upperA = $sidebarItem.parent().children('a'); var $upperAParent = $upperA.parent(); if ($upperAParent.hasClass('toctree-l2')) { - $a.css('background-color', '#c9c9c9'); $a.css('padding-left', '4em'); } else if ($upperAParent.hasClass('toctree-l3')) { if (!$upperA.find('.toctree-expand').length) { From c44457a627f4aa698827a8349659588c47b907a6 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 21 Dec 2020 17:14:52 +1100 Subject: [PATCH 106/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index e009c9508..8898ae10d 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,9 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Deprecate FreeType 2.7 #5098 + [hugovk, radarhere] + - Moved warning to end of execution #4965 [radarhere] From 967d214a5cdfce36e3fab7ea6e3298749faec424 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 21 Dec 2020 17:45:43 +1100 Subject: [PATCH 107/186] Added versioning documentation [ci skip] --- RELEASING.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/RELEASING.md b/RELEASING.md index db7b22445..4368792e6 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,3 +1,28 @@ +# Versioning + +Pillow follows Semantic Versioning. From https://semver.org/: + +> Given a version number MAJOR.MINOR.PATCH, increment the: +> 1. MAJOR version when you make incompatible API changes, +> 2. MINOR version when you add functionality in a backwards compatible manner, and +> 3. PATCH version when you make backwards compatible bug fixes. + +Quarterly releases (referred to as "Main Release" in the checklist below) bump at +least the MINOR version, as new functionality has likely been added in the prior three +months. + +A quarterly release bumps the MAJOR version when make incompatible API changes are +made, such as removing deprecated APIs or dropping an EOL Python version. In practice, +these occur every 12-18 months, guided by Python's EOL schedule, and any APIs that have +been deprecated for at least a year are removed at the same time. + +PATCH versions ("Point Release" or "Embargoed Release" in the checklist below) are for +security, installation or critical bug fixes. These are less common as it is preferred +to stick to quarterly releases. + +Between quarterly releases, ".dev0" is appended to the version, indicating that this is +not a formally released copy. + # Release Checklist ## Main Release From 35834535cbf9c42f7dc454e86f6a0056d74e8e00 Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Mon, 21 Dec 2020 19:17:31 +1100 Subject: [PATCH 108/186] Fixed wording [ci skip] Co-authored-by: Hugo van Kemenade --- RELEASING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASING.md b/RELEASING.md index 4368792e6..01faa76ec 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -11,7 +11,7 @@ Quarterly releases (referred to as "Main Release" in the checklist below) bump a least the MINOR version, as new functionality has likely been added in the prior three months. -A quarterly release bumps the MAJOR version when make incompatible API changes are +A quarterly release bumps the MAJOR version when incompatible API changes are made, such as removing deprecated APIs or dropping an EOL Python version. In practice, these occur every 12-18 months, guided by Python's EOL schedule, and any APIs that have been deprecated for at least a year are removed at the same time. From cf26a10f32e82eee3a7220d4b289a3dd4d9907bb Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Mon, 21 Dec 2020 19:17:50 +1100 Subject: [PATCH 109/186] Added link [ci skip] Co-authored-by: Hugo van Kemenade --- RELEASING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASING.md b/RELEASING.md index 01faa76ec..9aac638c4 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -13,7 +13,7 @@ months. A quarterly release bumps the MAJOR version when incompatible API changes are made, such as removing deprecated APIs or dropping an EOL Python version. In practice, -these occur every 12-18 months, guided by Python's EOL schedule, and any APIs that have +these occur every 12-18 months, guided by [Python's EOL schedule](https://devguide.python.org/#status-of-python-branches), and any APIs that have been deprecated for at least a year are removed at the same time. PATCH versions ("Point Release" or "Embargoed Release" in the checklist below) are for From a0f8004aa6230830a0801357367df4493e96d250 Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Mon, 21 Dec 2020 19:48:53 +1100 Subject: [PATCH 110/186] Specify branch [ci skip] --- RELEASING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASING.md b/RELEASING.md index 9aac638c4..5fe5a9b72 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -20,7 +20,7 @@ PATCH versions ("Point Release" or "Embargoed Release" in the checklist below) a security, installation or critical bug fixes. These are less common as it is preferred to stick to quarterly releases. -Between quarterly releases, ".dev0" is appended to the version, indicating that this is +Between quarterly releases, ".dev0" is appended to the `master` branch, indicating that this is not a formally released copy. # Release Checklist From d13a3ce7bfb836559830ae7d160c69690eec2d0f Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 21 Dec 2020 20:45:59 +1100 Subject: [PATCH 111/186] Moved "Versioning" into "Release Notes" --- RELEASING.md | 28 +++------------------------- docs/releasenotes/index.rst | 4 +++- docs/releasenotes/versioning.rst | 30 ++++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 26 deletions(-) create mode 100644 docs/releasenotes/versioning.rst diff --git a/RELEASING.md b/RELEASING.md index 5fe5a9b72..eb69f2699 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,30 +1,8 @@ -# Versioning - -Pillow follows Semantic Versioning. From https://semver.org/: - -> Given a version number MAJOR.MINOR.PATCH, increment the: -> 1. MAJOR version when you make incompatible API changes, -> 2. MINOR version when you add functionality in a backwards compatible manner, and -> 3. PATCH version when you make backwards compatible bug fixes. - -Quarterly releases (referred to as "Main Release" in the checklist below) bump at -least the MINOR version, as new functionality has likely been added in the prior three -months. - -A quarterly release bumps the MAJOR version when incompatible API changes are -made, such as removing deprecated APIs or dropping an EOL Python version. In practice, -these occur every 12-18 months, guided by [Python's EOL schedule](https://devguide.python.org/#status-of-python-branches), and any APIs that have -been deprecated for at least a year are removed at the same time. - -PATCH versions ("Point Release" or "Embargoed Release" in the checklist below) are for -security, installation or critical bug fixes. These are less common as it is preferred -to stick to quarterly releases. - -Between quarterly releases, ".dev0" is appended to the `master` branch, indicating that this is -not a formally released copy. - # Release Checklist +See https://pillow.readthedocs.io/en/stable/releasenotes/versioning.html for +information about how the version numbers line up with releases. + ## Main Release Released quarterly on January 2nd, April 1st, July 1st and October 15th. diff --git a/docs/releasenotes/index.rst b/docs/releasenotes/index.rst index 18d2d9576..cd73de814 100644 --- a/docs/releasenotes/index.rst +++ b/docs/releasenotes/index.rst @@ -3,7 +3,8 @@ Release Notes Pillow is released quarterly on January 2nd, April 1st, July 1st and October 15th. Patch releases are created if the latest release contains severe bugs, or if security -fixes are put together before a scheduled release. +fixes are put together before a scheduled release. See :ref:`versioning` for more +information. Please use the latest version of Pillow. Functionality and security fixes should not be expected to be backported to earlier versions. @@ -48,3 +49,4 @@ expected to be backported to earlier versions. 3.0.0 2.8.0 2.7.0 + versioning diff --git a/docs/releasenotes/versioning.rst b/docs/releasenotes/versioning.rst new file mode 100644 index 000000000..c69139600 --- /dev/null +++ b/docs/releasenotes/versioning.rst @@ -0,0 +1,30 @@ +.. _versioning: + +Versioning +========== + +Pillow follows Semantic Versioning. From https://semver.org/: + + Given a version number MAJOR.MINOR.PATCH, increment the: + + 1. MAJOR version when you make incompatible API changes, + 2. MINOR version when you add functionality in a backwards compatible manner, and + 3. PATCH version when you make backwards compatible bug fixes. + +Quarterly releases ("`Main Release `_") +bump at least the MINOR version, as new functionality has likely been added in the +prior three months. + +A quarterly release bumps the MAJOR version when incompatible API changes are +made, such as removing deprecated APIs or dropping an EOL Python version. In practice, +these occur every 12-18 months, guided by +`Python's EOL schedule `_, and +any APIs that have been deprecated for at least a year are removed at the same time. + +PATCH versions ("`Point Release `_" +or "`Embargoed Release `_") +are for security, installation or critical bug fixes. These are less common as it is +preferred to stick to quarterly releases. + +Between quarterly releases, ".dev0" is appended to the "master" branch, indicating that +this is not a formally released copy. From 47085d405756f80f3ec2c7841e30e90a3ba9c9cc Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Mon, 21 Dec 2020 12:30:26 +0200 Subject: [PATCH 112/186] Keep example consistent Co-authored-by: Andrew Murray <3112309+radarhere@users.noreply.github.com> --- RELEASING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASING.md b/RELEASING.md index ea6642ef4..a3653f5be 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -64,7 +64,7 @@ Released as needed for security, installation or critical bug fixes. * [ ] Check and upload all binaries and source distributions e.g.: ```bash twine check dist/* - twine upload dist/Pillow-5.2.0* + twine upload dist/Pillow-5.2.1* ``` * [ ] Publish the [release on GitHub](https://github.com/python-pillow/Pillow/releases) From 1777aada93f00aa09c906eb40e0c8bdfef6e0839 Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Tue, 22 Dec 2020 07:38:56 +1100 Subject: [PATCH 113/186] Reformatted link [ci skip] Co-authored-by: Hugo van Kemenade --- docs/releasenotes/versioning.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/releasenotes/versioning.rst b/docs/releasenotes/versioning.rst index c69139600..1653bff3c 100644 --- a/docs/releasenotes/versioning.rst +++ b/docs/releasenotes/versioning.rst @@ -3,7 +3,7 @@ Versioning ========== -Pillow follows Semantic Versioning. From https://semver.org/: +Pillow follows [Semantic Versioning](https://semver.org/): Given a version number MAJOR.MINOR.PATCH, increment the: From 8794610c76f0ac040c9ac4d298aca7a65a70713a Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 22 Dec 2020 11:38:02 +1100 Subject: [PATCH 114/186] Block TIFFTAG_SUBIFD --- Tests/test_file_tiff.py | 10 +++++++++- src/PIL/TiffImagePlugin.py | 3 +++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py index f644ef887..bb1bbda3e 100644 --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -4,7 +4,7 @@ from io import BytesIO import pytest from PIL import Image, TiffImagePlugin -from PIL.TiffImagePlugin import RESOLUTION_UNIT, X_RESOLUTION, Y_RESOLUTION +from PIL.TiffImagePlugin import RESOLUTION_UNIT, SUBIFD, X_RESOLUTION, Y_RESOLUTION from .helper import ( assert_image_equal, @@ -161,6 +161,14 @@ class TestFileTiff: reloaded.load() assert (round(dpi), round(dpi)) == reloaded.info["dpi"] + def test_subifd(self, tmp_path): + outfile = str(tmp_path / "temp.tif") + with Image.open("Tests/images/g4_orientation_6.tif") as im: + im.tag_v2[SUBIFD] = 10000 + + # Should not segfault + im.save(outfile) + def test_save_setting_missing_resolution(self): b = BytesIO() Image.open("Tests/images/10ct_32bit_128.tiff").save( diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index bbfd28cc2..5480fcd85 100644 --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -89,6 +89,7 @@ ARTIST = 315 PREDICTOR = 317 COLORMAP = 320 TILEOFFSETS = 324 +SUBIFD = 330 EXTRASAMPLES = 338 SAMPLEFORMAT = 339 JPEGTABLES = 347 @@ -1559,12 +1560,14 @@ def _save(im, fp, filename): # The other tags expect arrays with a certain length (fixed or depending on # BITSPERSAMPLE, etc), passing arrays with a different length will result in # segfaults. Block these tags until we add extra validation. + # SUBIFD may also cause a segfault. blocklist = [ REFERENCEBLACKWHITE, SAMPLEFORMAT, STRIPBYTECOUNTS, STRIPOFFSETS, TRANSFERFUNCTION, + SUBIFD, ] atts = {} From 26e592961707b84111315e4a08f4d382289647bb Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 22 Dec 2020 16:06:44 +1100 Subject: [PATCH 115/186] Fixed comparison between int and unsigned long --- src/_imaging.c | 2 +- src/libImaging/Draw.c | 6 +++--- src/libImaging/RankFilter.c | 2 +- src/libImaging/Resample.c | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/_imaging.c b/src/_imaging.c index 0b0cfe3f8..0f8c9d61f 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -3928,7 +3928,7 @@ _set_blocks_max(PyObject* self, PyObject* args) "blocks_max should be greater than 0"); return NULL; } - else if ( blocks_max > SIZE_MAX/sizeof(ImagingDefaultArena.blocks_pool[0])) { + else if ( (unsigned long)blocks_max > SIZE_MAX/sizeof(ImagingDefaultArena.blocks_pool[0])) { PyErr_SetString(PyExc_ValueError, "blocks_max is too large"); return NULL; diff --git a/src/libImaging/Draw.c b/src/libImaging/Draw.c index a2b2b10f3..339e1cd35 100644 --- a/src/libImaging/Draw.c +++ b/src/libImaging/Draw.c @@ -1115,7 +1115,7 @@ int clip_tree_do_clip(clip_node* root, int32_t x0, int32_t y, int32_t x1, event_ if ((root->type == CT_OR && ( (t->type == 1 && (tail == NULL || tail->type == -1)) || (t->type == -1 && k1 == 0 && k2 == 0) - )) || + )) || (root->type == CT_AND && ( (t->type == 1 && (tail == NULL || tail->type == -1) && k1 > 0 && k2 > 0) || (t->type == -1 && tail != NULL && tail->type == 1 && (k1 == 0 || k2 == 0)) @@ -1359,7 +1359,7 @@ void pie_init(clip_ellipse_state* s, int32_t a, int32_t b, int32_t w, float al, rc->a = yr; rc->b = -xr; rc->c = 0; - + s->root = s->nodes + s->node_count++; s->root->l = lc; s->root->r = rc; @@ -1630,7 +1630,7 @@ allocate(ImagingOutline outline, int extra) /* malloc check ok, uses calloc for overflow */ e = calloc(outline->size, sizeof(Edge)); } else { - if (outline->size > INT_MAX / sizeof(Edge)) { + if (outline->size > INT_MAX / (int)sizeof(Edge)) { return NULL; } /* malloc check ok, overflow checked above */ diff --git a/src/libImaging/RankFilter.c b/src/libImaging/RankFilter.c index e4f2679b2..897e4d7b6 100644 --- a/src/libImaging/RankFilter.c +++ b/src/libImaging/RankFilter.c @@ -72,7 +72,7 @@ ImagingRankFilter(Imaging im, int size, int rank) /* malloc check ok, for overflow in the define below */ if (size > INT_MAX / size || - size > INT_MAX / (size * sizeof(FLOAT32))) { + size > INT_MAX / (size * (int)sizeof(FLOAT32))) { return (Imaging) ImagingError_ValueError("filter size too large"); } diff --git a/src/libImaging/Resample.c b/src/libImaging/Resample.c index ec35303d8..b12e023f8 100644 --- a/src/libImaging/Resample.c +++ b/src/libImaging/Resample.c @@ -208,7 +208,7 @@ precompute_coeffs(int inSize, float in0, float in1, int outSize, ksize = (int) ceil(support) * 2 + 1; // check for overflow - if (outSize > INT_MAX / (ksize * sizeof(double))) { + if (outSize > INT_MAX / (ksize * (int)sizeof(double))) { ImagingError_MemoryError(); return 0; } From 36dc83e3ac2437b34253bdc66f2bffa4362e2537 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 22 Dec 2020 16:07:32 +1100 Subject: [PATCH 116/186] Fixed comparison between unsigned int and int --- src/libImaging/Jpeg2KDecode.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/libImaging/Jpeg2KDecode.c b/src/libImaging/Jpeg2KDecode.c index b08e607a7..8cce5454f 100644 --- a/src/libImaging/Jpeg2KDecode.c +++ b/src/libImaging/Jpeg2KDecode.c @@ -742,10 +742,12 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) swapped), bail. */ if (tile_info.x0 >= tile_info.x1 || tile_info.y0 >= tile_info.y1 - || tile_info.x0 < (OPJ_INT32)image->x0 - || tile_info.y0 < (OPJ_INT32)image->y0 - || tile_info.x1 - image->x0 > im->xsize - || tile_info.y1 - image->y0 > im->ysize) { + || tile_info.x0 < 0 + || tile_info.y0 < 0 + || (OPJ_UINT32)tile_info.x0 < image->x0 + || (OPJ_UINT32)tile_info.y0 < image->y0 + || (OPJ_INT32)(tile_info.x1 - image->x0) > im->xsize + || (OPJ_INT32)(tile_info.y1 - image->y0) > im->ysize) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; goto quick_exit; From 9940c84b085dc8674e6da09a1ad9c693ba5c3409 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 23 Dec 2020 13:22:53 +1100 Subject: [PATCH 117/186] Use previous disposal method in load_end --- Tests/images/dispose_none_load_end.gif | Bin 0 -> 24601 bytes Tests/images/dispose_none_load_end_second.gif | Bin 0 -> 17208 bytes Tests/test_file_gif.py | 14 ++++++++++++++ src/PIL/GifImagePlugin.py | 3 ++- 4 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 Tests/images/dispose_none_load_end.gif create mode 100644 Tests/images/dispose_none_load_end_second.gif diff --git a/Tests/images/dispose_none_load_end.gif b/Tests/images/dispose_none_load_end.gif new file mode 100644 index 0000000000000000000000000000000000000000..3c94eb1b6e006508839ce1827a239058fe9ac82a GIT binary patch literal 24601 zcmeFZ^t5G=UDv%ewKb$=><57yAQl5$US1~f^PAS2`uTkq z5NM*OpKNaSpoyaKX!1x;-xcr>*kWUQ_RMf|WBvK;^URzyclTM&c+RFqA-z03?_qBO zg66(H&%>#yDMrQyJw5KbTpes|DJgX9>Obq)RH+K&g zSBRvfgv4B;gAg;bU%svmT@an=plNotlz*=Oi=?Fa`ID*C)a-07?kaE;ZdTUrXV0em z2np8KT0d-kI6OZ5N=MJdH5VN%Wo30f^R(_~bF)N{M1H>7n3oqr1%ru6t%gR0bgXo3 zEn~j4^zrdJHFeg@_V(f7lf13Gt;3DTo=9Ha9GN^BJ-uuTi}^=Gk2*Sj$;quGC8^YS zd*^+~OL2EEFF&`icoFvSVI>z=jJ!N2=a!UIFB{u0tzfM(s1_scW<+b`iO+->+g$;vxTsViv9>;VF-_iYfSSC zRN&cTVNpDB*AK+8vrnX0092GIuigK17PqN zwHk`MBH8q z_`F9v>DSyaeqR@cnyV&?kdgRIIxW>xWm=i^`W$PztWtQTI%8}7`mEPf$S*z(zj*rL zxm`~JlWuF>$7a`=+M5hF^3zoCa0pRN)z3b^Hu_1ZWuz6?5{7~iFzdB7Ece9W>6-RN z#k09#*mR%hwKuJgGnm#Xd_WC$U8d5^(Cqf{^i&LRBL( zO2gkJ31G+x^G}`{L{?(n%iLxf+=qO?o(sB zuCokul9c!(T2U2fcuJ;B_~sl|&SaS~!3DtUXQD*b;zkC5rXyQEhX#3ss+Y?WQctzoZSp?=nDx&9WM*}=;IuuBK z4V<%LU_(7G44+2Kb8DZqH;$a!q;QZY{Lx)3Nt}5{uH;N8)vJISqa}_vGDkOb2 zuADn8Yl9iwrq4WO#85Q1vC^y?*`Tg|eK+cOs7n~zX)&T$4a+$Fnq_QF62?GJ@=WK# ztH8tEo!?UXOWm=D)W&d?6exCzi15-va5VnSdq#^>>mkwj*!a@him}Wm`%46qKhRq& zXGdQ@G~d}{R>(AU;7XHgSW%>dK*2vyBzEBPCRmbj#xO{! z$Po`pgqSofem|fOUkpCp02O0}D%PJQP&Kom#t0;#4wSs$f|IdC*#alOsJ(64{kPx0 zxKDG()-8z~%g+Sxu|sRZS!yPoH68jA<&rRTGvPNOA(@ZMMO#vAUARd#E)LJ>0$iuc z)L|BWIFLthvSD=#W5V!A67dr={y^YXD)ULgF*O1wyqfj~J(bk-ATEP9a48XZ$ruu_ zJyT=;()Q*&4@t}x)&Aw@-(=9$kB#4&U=PoZnEI2pC&NFJg&g@I_kBoIh(mt+bC5#! zi_qa%1oZM+r07I(=%6}}xe)X%l~Zqr>tqrMsUI%!(PVLn4b}s)!8F#F-3i%j$w_TT zkeKPtN7p>&JL1Kw#vjYy)ln5kXoi=l5irW=AhyZw-IV`)(AUcQ$xRWz@`(`&5>}FVC{z3(o^!lX@sDP zwjCji(hc1@?Ce>|Mn0q)MH^#�jzID@z$pEiT}EESp<693mhmWmb04u*bhJJD)VlLB6+B0!3H8#zB|7298maV2 z1CcuQgAU3z^E3~gwp03`j|1j)>FF2A*Ww{3DpN`k*hI`~c}B}BF+?OfsxVefNCH(V zBP$a1nJnd-$Qxc&&w&(TM}fyJ*Ie{)a|A!GYwZ&PC^fu}sUGbKJyti&gG(%WvuY!^ zs@^!h8=ie8mAXIlkqDfwC_fB6rA?nK=feAX`tE4{8@+Mq8tMsfyPlmzt5&biZ=)H^ zcWqvIcM=x+uW3QvK1e;sez2Ard;eMJ$8RDoNfq|Vg2~&YmVUVR0?6Y402zfVYalN- zw5&X+G+m)zq>+3Uorkx^re;BAeeXMrY%qO@+#nMA%mm@pr0|N zYt$*t&9i{7@9J+2Jh}NgfDEsL4B=Cb4mwy*%^T|7Dxi_?l}&1l!cMFZb(CEgNG$@Q zgaL90BX&6Y6(i2$JYJ3+mYx`57L@?4?Igf&9o)7hzN`H(-2ETZ#daJ+>GVxbyfn`k zNBk&yNe`w5b&}Zf;ZvBjpLe(?o+ySviTDC|rosSxb++Oot?){N$IK6gwF)2U{QZ@}aAD=9x_Und+dP zNF(Yp+m?=T9Jq1b-ymm#avI9eoZB(du2a>$ry296%c(|Hzd-6vlblK_w*vP!KdhU9 zQ3g;lOd8kqS6SOi>cm)-@yagUSYmxQmR2iDG|jpVzcroi4& zHi}vy|JrNlk#ZZr3rrA?$LUf}=wcy~+0 zg%AS80Q_(PBtXHX%S3*Ke_(R=u(z}Wnx2(rLa{rXLw-L0gMXf=7?qP@CB8hmRFV-!ULVA%RDJ%fnRsrP`T1{95VmY`r^0GgU@qI*)Z;)V`}_lP9$c zEdNFZwM%Vq{7^w4cMogsx`p-fpom^ie?Xq@%V(e4zvELD59ESZ@6i^Oj~HsIvnP&% z|Hf!Ni25)#D&A0!vDiK4yX(97dc(VERh z>B@69@CW}y60jK9w2_hoyssbWTKL3rN9H{l?M#Jk^tU5ey37y~+jN75t5 zMRdV+wwup-%n2SSy$Y*$UuhkfWEda=F6e!mjYo>l|`c{TtWFLVko( zrSalZuH{45%pyr_QFF#d7Rum!n1RMjU1cFGJ6BTjG)|i~xM&^avQ6*sCKv^+-{$j2 zZnHJlpSygvdO=DOb{RBcEEoHdQD%CQF6JtU+~gyCj!wbkRfsZW3Ev)PBv6t+kGpFZ z81?0D2=j&hC-zF%}f#L8^bovV3F-h!ar>s&ln z!MH^5!qJn!YNTHKpKzG0l~yLHUu!Hm+G8I~W7EtKa6918X2oN>hEl3D9{v^NM3yL?8vP<8cug6b6a5|`2 zT9T<|@ra#VTf?XE#wW!kQf#Qr(S>}mK^jQ7-Xn}-!ZsyEl|VF#xcrv8)#L2@bkf-r z;baFT@lYZ+jHLhW_fzq$$x_WQ>U0EoB^icU9;ubdPKpH&?;z^&TgRuqI+Hzl zR3+-@bkdAN1M5Mbg9XNSA#ReuJL&;x$PW^Km$3qwz@H%gxqS`R@uur=X&x?~ZfE1a z&N|IN`@m+IS2YO;2d|%_pBMKDA+lfO;Sc~xpCQJS*Zg$ii$ zz__U1?xg_$H8kQqEAQ(o5Xm!HW5C1{U4HR8LE`EAx+>B%R&&qjY+6w^HJ)5f8zF4Z zPp`(V6JfL@z;v=U%!Wjfuq4-64CUy*52w0;PxDhbE`sYSZ{H`BX<8e~;}UxX7vWbR{;3isW3ROkL=o$PK~%Ugh)%fsU@9G??#S`U=eVY~Mb-*riJ6C4CHL5k|#x z?rD}gJq`Okk+F-}{CP2!^fStbE@N`{0stnfYg_CUsgzr0RR+%?NtbV8n5=((r*Rmp zL%%7dZFe}?j~=N&p7^ZvQLW{RRWQo`LYkBF!vOaH8`vdI`rL08*$*yjmQzY)ji5-3e(4a?)?R0R$QVU*jwXW29uZ+UP>a%aBv&gyvm{g=DOFfco&yGZ-0hQ+WB_&J{*NaYFK zjT3s)lk)YQoZY~9%IB*}3HAKyRc&E!&vl<)E{gf260f&U;hJ5u?{2x9$mRK7$V?WX zw@&x!OQ401|4Gu&SQ1v12NLNH>O>0jOwyB)7#iURxWp|K+8cU#Vcf=*X6+fyy1BwP z69%2Q^z{qe2(iT?-R49D%u&#Xhd3j7#G2{5Mzt-fGsNHLm@HqW*oNbq6G%UD(|i?5?kiEp$e3beGk4Z=Zy}F z@EGQuc_y?J-C{UwM}&oR2|1-SQKTFT;-3JwnMzF}t>*l@^s3>bYG>kvBUGQvzpV9x z!0gT<(><&`kwT`|?3(aNOU>t|;ZRL@-H7PYh?1cR@wVHv+C&+_$diZrP($@=_OI^| zl~TvfL+$7D;S}%73uJKZ-;M>@fmb*N15m*ktCzAt{)g&lYwFoe65Ed9?4H2lo3CLz zgYm&X{=z?h@jq&hewJIdPp6F_(=US-z5BYikm#Yx(@cDoEpXSZ5TR5~jj@2#OO5ijOW405% zNi{6mvA!>9-I;f`L$u?Td|>>;=%_wNlR>}T@XDwX%*Ur1&QiDb*)mGdiF~E*L9S1S zW4}}Y$Bg(_>m+#7npLAoV{ZV~4z>Em$j-M9v7aA&3#&k?lAv~o8C?TWACy5z-{KgA zfJV?@I1I`yrdHIGK>jByZ*c6%wQwjMo7>>0A|8KNRZFqFbB3v)jl2h%wXZAU@61?d9C z7MpGNr&kU8($Vg>KDI4o4kDV*XZRV;36#kZOT9lC7oJKAl1h&Jiom8dsE*?r#RO4+ z^9c7VXM04jHB<@|k4Kqhd-JsfdiX`W5439EcQZ12d(IE?Km3!VLb^GA9U(`q=8K^h zFmPEc4E5+Uw_Ae?I+oMclCXL}RuzrI?KcBdhL$1>w) zxiN4fG`wM#Gu(RIWvWg_m)3xgFKbAS1ABqc8ilk+Z**rRmdn?gSvn@?Bvdmw%6!GJ=L70bTqwYH)ISq4- zf!YuNHT071I+B-Qy_?d+5EXN zyzfx*K|r~cv~34*!<~uHh&-Bv%cn%@evxU!Czq~zjYrKklNW`{3Y0?;pWfmkRpyQbF}v~ zK_ax-6&XQRU{>AmW2?Ifho!@bRxO!6Ub(rZuf(M+Ueaso3~PS}+9td#WHUOFraUQ6 z)52)ntWj@$tqf>0g!$Pb7lk* (|jNAX~?Dh+tFAmb#({7^s(B z&`-435#KE-@g{_6Nk@}Tj)8uF$0+9RmQSztW7((F0(lZ1AIdai4@Sw~?`XWl?v4_) zK-3KhD1>(N#jq0NS+xW$CmN;Xp7^ZY zKXMI3JbVrN{;4@tM0vDE1oQP%XR1=?<;D5$-?%4+OUMXp^)|YOfzc=GL}N*`jkv>4 zt^!00tWV@IeNUP6pZ0n`h&|teSCH)&-iqC9Gw$B>Z7LdP(Zwe6h#L2#jLMNVn1 z_@BEwf8n23Z1_Z|Carxop8G$MmRQacab(OmgmATD-CW}Dy}Sk4!CeC5h0$YH#a>+k z(A}3w}@W3Ra(M^TEjvRd;wQhxTq1y{4dQ0%e5FD0_(?r*8J4iak2bek@;y zRwMw^4DJ(Y#~Y!~(m2hw5~%u8G|)89Y_P zI5s+nCQz|ULAoB%*aPRLf8ihd{w$eH7yayMwFkZsuNtxkh!-Sl|Px2GyOm)U@Lp!IFv#m^E;e8Rxj_Gmi+ z92vj$KfmhJNLz}9koHdiMU+%l%^dkhe$FGgqPO4c$)v+sZ@n${6_-_pk}#7y@u}5M z;CWx=?cyAr2Lg%^?NX}yAy;L`fp?t5!VgA-ehJ@J~+UBFohK{|hm!sgZ zFNlq^x40gsjIe_~qTO_iBS#?#3rw>pFEW*iLLdJA^<(oxXHgjD5(7ZAbU9R_(jwW^ zw5%ncO~l8N)EF}al$Itczdov--zs&ydNKI0U2+ttf9YGjzW1HBND|C^1d{+t-%amH zR}Z>*Gscv7ypT+_g{Qz&xLfP@KugVk`Jbm2^|o8$yHOvW&q@~3GE^~3TzCE5Zoy#p z@ENUE?b{B)N>PqA*BGV{0TIsCr-2)QNcr4L6c_q#)4d9zVmPWt9f&x zST&JZpMIgum)qp2?c-Or3fi@1r+&(x`s6*VThr#oUQ6vsu)KZvd(u;bl;%)tA3zt% z$P-SMsj?hA|4aW`9Dnor*B}1p7qRz3{NdJ2(c)66?VHeAo55TbyD!up90!{uNHzcu z#j%kNw|m;ve4FU)!-jPSTU2m%`AIqy-lLvGYkaZ#AN|X6dQCfvSJzg0YI=Pnx8>_t z)>?Pv7;spZzNF0tqN9QC4b8Pf=6+?Tj*I9~s8XZl1GjFi( zOX0MB|CjzH@olpg#6PPkPt9LGA?OH#jTUHj3&%@*Y7PG3mxPPgs|*O(*10Ap2B&KW z^caEq7a^Zn+S!MXhqot7)Kj@`{>A^~{tQ^{{pQQhj9+CL(_N5NEgV4 z@nagh#23I}tKVZ9To|Z-iB=o=uCmOxxPNH!`u0ep8hB8W!LLBs@{a6WQ}a1?Nlo6O$G*#7vf|Kjo?Kp6Hy#)S5SY@0>|| zpKH23^UO<5vW?=^K(bt;@?^{sx1{F@Hm*TIi1gQXSH)DUBV{_k==r!K^G|R>{+rB8 z_fZVA{h2J!SLAUBjV~MT>|H9HpB!w?{Dpsxa=oN|p-bQ{t;Q>DUG9w`;+{wQ#=%Mn z;=w)DAQ?AL3NS$G@I-{s@*w|%BjP4zAVtU^(&AaO5`|AlTYKIdOmW)))W3cnol=1O zk80QrS>Gcb3FQdMYhF4;#D%x~e3pECvwJ&&IjW7>yBr5eWgr{ad4beB9|4b#&p7R2 zFg$nKEe9jt6)YUW?91ch-!wjUU6FV+k`HKo9r|LP7Giw9OONLWGVqvhKsIw38NpZe zQFgF(^>`0WLy)2SRkf0PH2|W*nY<+lX7`A{z z&QWc@PeK}rPwp#HZShmMq&u3BLG}S$w6r%K^tY=Kc`q$l^as5W+=U;po zs=FYgtNqEr(uAvN>;vk6RSSp0TMEkqCapjL)mJcHJdW`|gmUS+N&p};&=DllKcI2V zc~&cc;K1;w=llz=#eNX~cz=2G5VN7+)Z??#^9db3 z(+ccZJU!YT57JuS!}3WVj!twOTbP(@#mN$LUPWS`=H9}DUS3?l&bfUMT@g4WYN^W@k&f&sf_`7MUmd!wRmpKFm2~*yl9wBnoE_o4+nZt1N^@<; zXk`rN7T#H;fAITfS58@JN`v}o)!+P2GT+@l_{Zef%nkP8nN2V{+<&!S8ayNKJ~d&- zmK%C2eQrN=^R6~5+C{#isGW#cEKzxw!4Vsq$Px4KMR0%AP}6OqQt5;`0fWe}9AU@t zx-0(YiBcr7U`W6gAA>>J7avDe9Azo*q|C^kTmp}XwG(`*uQQLo6otl~9f1g1uH>w6 zi=ws&p*V1|-<8gHJwp*Rs`{(ZBYuuOiiWdwF z-b;%`xs#djmFQ_d=nq(1N?YyD74~?)a)ft$_3~AFNRv18(@a|0`4T}t>$+Z&yy}-A zqb4%S=HttBq! zod)2V-2aspB;WQkk(%Ro8od?_kv!CV8w23-!mxELTU>`3WlY|4(6{nn*#58o2Xhd> zfK}yG!64;1Hz#61O3dizb8?_QGFv4Vh}d3e?@yd?e88a`krhRWDg(-Iw)u9an>y1X zYy4)_EUw95n%qDCum8ugVyTTj(5LJARUdX)kLS-jeh#JRO0=;qr> z1Zs&lN}xT^S%Ma~o??|~vFnFg7iBj;{g3}AdN0(e2h%3M#(lOR?dxDuC^);4mgYE| zC9JKT5j8)_jSuXH-V;O^GDqT5&Cfpn5TmSKhyX6fs%|Y_K0H4?-rHPU{2%^DVZG5F z%#PlYo(s|?oBh;iq_4 z0*y@OdVT9_R2V*LHOJP8C?(Fq%c*Bxza@A7<^KtTp_~!a;Pb%x5W8WjyaKAyFc6$a zt(kU%y&U-SLHqOlska({9%b|&Zk|=p)F~|5OCv59row`AAn0YnuKkp zMJvrt8JyT3{^#HLr)SzO8*`Fw(BI;pd$0y+(Ir8Qp|F;#Z{xSrn3ZW3w1PpUW4l z#|p+EKy6OS4g;4GhLxq zAp3B>1@cteaQ3|IOf~sEx1q(>$#7ZDoRw@qLr_FcUnaN2ta7HW5awob0FGXsorr!S z7J-iR#qWRkAH^i;#+AM#24QbIXgWP#R#R6`9tfhr;Unync z&VsJ~*_YBj4r+lX<+|pPFc<+fVWC`AUj(_q{|o=~kN*cprmG2!WXopRc5gsiB=l*d zFj;2h&#rVudT?@OJ9MoKWzsW_i`vx!&$oe?#89Pk<^(wjR4Ur99+81tGIMsy^l@jmHzcF z{PS8SeE)X1@~Z$dD|uvSeP6kWK%r8Yt-A@qSMYK4<(hUfJ)_g0h#ffBt5s1gvc2Me zK6l2l+`4>lcD(axv$VGxB<`vK0pk^V7DY}j1>OoH*2Ea%BIE-TN47rt$ztEME;Lk= z0s)*8@cMBKWpEjm>ecvhj)3~t+qLpuD2#Z!S_C6vREj;J?H*biY~oICEMe%5(8u@U zjjaTqU-C(Tz+ha+^N~ONk8NiJ5&u1bk4-KUrPx3>7K~18T-y!}kd%;#C{~Rd^u?lGARjQAGrzW(zgzfhL37;Ud zeA^A^6bUiN|NOdHhI5UWaat7Kwax|MLI*gMT(gwBxbytSa?0yCC_pBa_lj@9Ww%Hm^2CTYnW+Da)i0g(xZ8sM3e$ z_5(Qz1%LcMoA2Kg1m5{*b8eYd>Fr=ki>+0>jm`@G>=`pNW4 zgi!!kr~Tvqd3gWV-ts^$$p3_Zv9p*I(~lu!!vJA=`Lm_iYYa+j{0v zz{99%wd~Mn6a)v1=G^EbaWXbDTG|FXwkUF;!poX}@XyE-{nxEKpW6HvH+t2z;RI+p zxRPdh&<}qzS`iUDbOas+YZht=x>WSX|NI~RXN1M@ZO3U?A(H3E?e3`PUpOla4R&2o z@uaMFyb!V&Jnp~z&y!2aQFv5BPIHsXs&QnT^jPR<0ywA6c{ChCkVDRiK>8T>ZZCrT z&-G_cAE(#<N5}+-)7v_yZb5Ow+K+G zJj>nNMPPpinBPX*8dnF>*mV_0;}gOEEI@0AjE0jD7pul{sYHiEV1!`mv+H7k8(MDCzQ*zRzZ+v%l34RcT|ZU_ zCTI0y`u~3F3XuH|znyvmYXnUK;td}J7==Xb%-L$~+-Eqr#A?+>%4+KvO(NH?S*oju zp7tcS8QMJH$HW=PZ@;*+`Q`I(kl%h0DWZ&>FMC(Q9m#$W30_~@(xXL&QTS|XoH~dz zV;DWsRbrYf-QEbCG`YaZ>e1d`{T+3#KiK+{=-K@uoDoddT)(=ft=S!L=nyNBW-s~I zs}b;RyIfXlN5v(%$-WQ~fk4rn|ElkD#i)iku_6N)rIAmKBVq6BtQs$oW-IfNxPsN^ zC(7$}`7GN`dNZZY`B((3ZRbxt{#D=Ey#{fQbf5tau4{sf$Ob?}A3MlcTv0X+uF9zU ztkHIz3ptw_xN)SpRdHYx7;t?&{>yKJ_1$}f9<3dEi4m6=gm^r}J3+~7!$sAP);eY> zB&Of#x!b>q0U%Nj=)5<`m@SRKfzxq2cBmkU(dP6*|3qs#QfA;G`&Uk0t%# zC7#IJca_eTlYd~AcNMLnB>1s9)XdWdeV81eR4w9j2SQyHcDViFW!T^P{vJsh__)>h zV{yAK5O7OOSKRN8=qsld!Iy8*a|9t#IE&%*P##w#43|y9=N&%iRNEaekJ;BOl*}y9}Etn4bSGfLc6f zCYH$tm=<0TysHQhtJG)DFwn=d04{I#<{7Vo^_@Z}79BYU4HyNjNxu|)DwrVI<3y@a zbrf)@SJ53mGizXa>;s2VQl>q*i8@$o5AX(SV^|pQaSN=xpKl6yl zaZ>~9W=PUNn>T^W5CdiId<=)S38!fG2eUUisB`Fav##M2`TeDvvYKnL5R2(cg&0Q5 z1E=9^!CU=>bmH8cT;M#!^fhFeW=qGc8jzpd86;Z-ElBGP`Q|G<3!qsHlL%zU5ip#I zo5mb;T1|`M+*$P77<;S~%lxOmqsHIFp*sQ#?-VP!r@<~<@?edoP$_j8OVU%@q(aPj z7#neRbUZl2E^Nq*3|WIGT6H5CFN!!VGpK^}O2#iUo=t|AI-D8C@M>hCDkNM!^4joT)iXdE|d1Qp0^ z5j=C~qu0l7b+XMo#`XGv`J#fWrd{*N*xup+4pF?yrNA9SGQUI z@i$6=`u<%QoLmzd$E!cp!xUudA~wbXPay~eog$)=436}*kt|*rjuoR%m}l{hH(#DoHBNqKDX9EsHW zk20FmF=dR(A@_!wSwSNN!-3HM>iZ*z62^5bDk4>o!9+o?gU?T4$3EeOHc+DKigGU=XhDaytCY|{+i2-LUUL|8cJ0UIvzpS zQk$rEPXzXSDbeYBJ30!kk-1&*U5|h2 zyPbEfDtL*N!(=>~oyzLgM!bF4hM^`rrZ_s+(_C2IO1SO|4l;fFuy^98%#UJZTzm;H zy{D@F(pz#K9iG{x!3H8Sv3=w+_pj=~8(w(lX$&FJ1fVPjAP;Es0N6E5B zeJ&8h=a2AhP*oCgox(@p;u6b5tSm@3dgOFS_$;+F+N%!#5B?dB=cZ+Aa1DzTEyi z@=tvyFOA>os-Gp}S1w?6&AAxK%W(9ajsmo`OQ3q`$m?%?VBSZmy}DK|S9Eq_^~MSm z8~h|a+ms9LF-ZG}4ZikWE&}^oulhSW+J3C|uY-3IQKT5v^;#f-t8Pg8CKxGDEl_Ue zNZUnX=na{tA0GxHKA%$78Zvske{kx@iW^(VASJml7v?w#Lv;o%wEfsx{8xQPtbI(z zrT3_e61WDH<`6a@ml4l@c(T8vN~%=^$|$g*^~Z8WPG3q+YbN4-kFnDC*9pMbNqKv= z86WlIm?`6U%^3~NDE+IxtA7@MHK5`&kc5r!N_%dmeG>Fh(y_l4xHvoN`ngTap%tjO z^ZEYfc$Lw^vo=zW!CYY)={3)`#^wH1A}L9|O2Xa6KmDy63s?I7;KmG*BE+@HwGVO;Y{R++8@*6L{x$YxzJk^6_*H~V{k>-$&ur(GGD zY+6Y;o9`u_Po}uhtEv%$T&MGm)=g+r*&w*y`WO zzAYzc1+f`Sk6e{c36}ESN3A}YkMU*Lm@xdY_qV_CKm4|<&)Ai6s+Nf3IuxX)|G-*FQD0sxQ0=06o0!+vSvmqN}{>CJlqj|^Pp2ax0+^N2+l1JYyhbI2+Z>4lI zsnAWt`G|~AVcjK!1nz3RV#gD-vhr|i_mN8lrGJRcQp5c~ z)i2Wy!PoWxK>#+-})N8i7c52mC7$C*PxeuJ-yQv=^uKz9JE zL%Ad(BnoGM(A)?AWe3~yU~rt5h7PKi47`$Q)wm+#G2z^jB&qsoj&|Z2p^V0if}qo-4Cq(DLMm8|gmF&{$hW zuK=$T0_pJ%K?Va_#YV_NC&+Khh5psw!2oLuSMH0app|uOvrmpn@P_CVNGb@w`1%k3;uNpXE|!FdKz-EjO~Z?F(A36iSD740o=N7RZGWD_r$=JT~t}E%)M4(Y|sl z)__J5kwbq95dhfSA#pfsme(BW@lqhLHav zlGb=dErCkVwl~k$fr^mUtPs56$_I&PU-jXoiLJ|n{T(=YGXw_8qXNsv21>J-jJX;J1?HZ=@sH)9%Xs!hHBb-jah)!IjSUwu zJa&H%*?2=ty8eg_cmW}#yJq;3;7f<^(&RDtV#*9jMaYx~pvz}0_B`@0{Bzac`tXd1 zicjPLE(^12VetCc1c9BGE-H9u6WjIu(nm3_gdFuo(3U7qbMYHi$4yGCtju75&@ZrL?tl-DgCgW5?}-V9Y?P?cVFM^|Hnx746#yqQnwwRIm#S3xRF7GcS0! zfeml+(r6}O$@gL{d1(vKgkr#PR6oRb$B?ATm7K&>g{82lrU(Rs{>B_(RjvwfD}wsI zEB}D77EIj@_m_B|qd3~ZMZ`B?xph08b`Enfkfg#WV^f&fhoa;V&AoCBu z-CjyW`^<47MHxFr`cP}s-~MTrnEEuplR%Eby3hRK#AcNYh4qm9{RXyA$*s=vkW0w4 ztZ15DR|L%^=YRR_K~gH5L>gge#tQg-hYBz-?G4Av){(a-=;!c}4$PnzM+*xf>RH`?CIS_O^u%>@oL$iQi@{oJWN}2o9Ra(}Fd;RYnC1*|aSCf1i`^;Mm{% zkh*Avql^JwT7V&sR=y5D{!YKP64j$TTm3jsx^be-d0H)wwA(l;PHh@EXZZX39+hTl z+msBVaICllWpSKGcu>-~^vIH`3Ccx!dF%eQkFfv;=woV##w8&K`&*OU1=Vqst-)=w z)UB>`y%xDc|EX#so+7f^GSRwZT4-7>KGAVX^78-~07PQr6%)`6!oO>HFFix>rW(s{r{ZkEF9- z=R4YJEU67DQl70#m+mTTXAHG~PvT)!gd9Wg$lH7)Hxl7)nC`?Y{--1O0O;D;f{?mKqEr)RjcAj-HLK9L$&sIWiZ_n37v zQP*XRBSV5;Gl2iG+ID|4e}1D5>zhV5y#yhx38UObpDqIQuYv z>@nBq94m8I19${q?*@J4qrVcUnxY79+4o`E8htsmEWUwpt&s2#vqO`*Gvk5$k7LoM z3h2nDt4=1k%dJh$tg3bTBlGr+7K$I&?ZEz!%L~^Og!24U7%o!R1^h+}U{6BHlUR)W z*o=GSza}px`>}V$|46xHQTIb4@J=)iR-&KN4pTKbz3>2=hvY0pU8o6=-SqJcwD%kk z_Q~`yM&LEX<9_6d5(M4JO&U)PiwrX&9t2gw0f4u;RcNx+E~mlLp-(8!`NkvZdrYqa zSV>*c013Os_wc4a?@ayUCYCdjl?;PJA>?_oZ^tD(jz9!1iM}1g1)J@`Ce+u=3j537 z!iB+Q#!Z_78vy8IyfL*k=?(9RK7kfNmzm1PtXBbc)jp&AN>T11{#K%G-_<%Ok*zOVbbKD+Ms>m?4lN2s^F3XK?n?9l%&-$AVJb<1Tz1QHyWLfcMOb6_E62E7#L zE7nG|MHc5~)a>6O3nu4njw#rKaV|&ti#VAEE-t>*JGhhHXEz;R9y+8S-34WKs~_zc zbAR4wlY_CH+dKp%!CocKmI5+j zsZ^2_>2fc!7#j-|U_AKoJvU5ATuhte~+V05RFNy~V*){)U5z zi^l~^d`7u~Tv=dJm}6F+J5E{FcW?dhS={_X*=?axP+6ZQ22E?`qn0c(MT(!qMs%N( zh^+njACzUZFMaDUGM9zDItf6J@XOihA~gcmj}*!MbFOsS2c;S**k>kV;ok<0Je93C zDF;Xz&<~D3{(zbB{(EjRC9Qrr=T{aD-1Fp;WsbRB<0>U$aDGzHNYC9A#i98{0qD@S6y?;_9FT9E&kM?}U|~B~7CMu%8l;3> zFznxTk$t6erE9C#0Lrf16kzMW=CF#mqC$1n=tZ79gL zN2hbs+^g+=8hrxp4H1AFdn#`PD#*>u?}Z%($X_cesG9yCR|m73outw9O%O+tnz3cH zM{#-CjqUrcEU=WGm∈DH5&QVP{Jmmr5@4v2IHy1EmM8JLthv5y%6ORE*lmK*V@$ zOQ*xncLN`H#OT8<+WJP%+rqG1bCpPl77&hzr0xlaGGT~G9j6nW05E;q8YW%u&_w`# z4+6g+5Oy!1t#g7rR$GNynz~XH0;T*>5@z<&$ZH0C5v}OEv!=j(_s1JCdkF}h?7;Mh6aN_;I102r< zB;iUf&#Jpu5t(De$g0iXr%a*C9|e#1AKX(HBUjng{DeuIk@ua(GE&3M4P&C#*A^op zTWcts@%h*@v$|rw6`RZA>3o2#EG)YI!J7hP=kZ9;y5%Py)Dgh92D@%IzX=`9%W%j- z$xeChwJve;RbdXB<4-*`@W16y>Zwg`!&X{^8}Fq}7{*LoNdQ(5o=^R-m}y*2XDLYM zTj+d#bN@Hl!K(EbNRU!)f7LBOLZUry6HnJj99XB9tZW^skVZ^~+pxEasMd0wNn*AJ zOo3}2b#9m0fNw?3LtZ=;IA*ID6KNAKXuczGOJV=S^<5QthL%@~{G}l5dK>ri^qyut zdPz#e?5G|qGpL>%|1>M%b>^_ziEwi5zJ^5EvK=w60*X(Cb3yY^&GD-2t*>k=lz*z& ztYo3%KFPNo2DYH~xXz@nkO%C3ET`j@q_KGCyn4WT3Vodfz&%hsd-a0jFU?NatCqWt$NtqZVIJSM z?z&3w%@#`)ifTyz&eUrXKOXq`BTpM?HCiCzz(kNm>0U9-iqTT-^ap;kbl^8L?hAj< zDOcDvoa@h#nSwI08ZX6JZz*PX<)!B0*B%&KcXeU%(XNU6RU^vi$~U!?tiRy1SN9*w z)aj6S-Z}4kr!8ZmKD4Z$eb z;goCSYSdoez#4urZvJ@!*ES{R_kVQa<~|2YPgD{3oKQ{1T44>T@63DWGZFktX`>=j zCCA-mjex6O9OpMUf$dPW6P*79aaIA}abaYi98yst3=~`T_EPCygKO+F-3L%sY>l;~ zA3mdkuC#Gf#bvL0FAhqHpc?$B3Gf{{iP0~gcfENeADSJg=eGph5IwWC%oi5!@?4I^ z$rYb3SzPps)~i3*w&GP= zJYNg|GHvq4Tn(kG0W9P~lv6=K`xdXbEx}Wu{(-l5&-D1@2ehcQ`xGgCdHo9b&9W2@ zl6WE?abw!d6SY0@z}fWg^RccU33H(Upg;N+Wp9(T!qj~C>9<<@s3#30#TmPKZu;v# zQ}pU`)z(&h!T{ZepajiGmEnwB&s;L`s}p((#C|j203m4TLEF*hVvU$18%7r~fZt=`Dv~yt#EF~bR4(8WL9^xWhH43R@j3&I!lo68z_66SIV$UMJg6;E>90gydrTK z=taQyulTG%Pcv#J+Ptw5&nS>h_Y!^kZ@y7ftCsFrzq=m9R#mOKn;dB&L>dIL5H6`h zmV9`0VP)|R7bvlqTQc5H-asS~9Y9H=ao=8C(tLTiUrT|yz9o**g{abqCi$5ky67vJ zN@!G#s_jR>QP5VQXD|ZU@O$HxEek)?qMKNL1Er^$_4ix)A@qwJ#k9QGZ&ppXI(m+r zK;E}7S00Gy3NLboK`6P1n4`#i(T4?eoX|WJsfhKKDkRtur)f)Iqt17ZU<9PF-=DrE z5eXi+Lmxu#$X4X`*0`Mv^Himcd#|fUMYiI(o~QrL39t7MdM>QBS09?F&jfct`<~j1 zu>M0iTe~y2G1p6Xq+#wRM`e8*s`24bQ&)io44*;Mf<)!pBwc_N@wxKAZ)VU}5Qqrz zVerwh52`d3z6aA>VO<#nG;Uq|3=W_z?NXbQyB_A0mU`#Wks5m0hPpra%??C5M+X~Z zXR<#%Brm-NEZfWnDEbZ7+wQD430QC!TD?_OHb?Z|zZ%eS{4EM1CuvlT;+g_g3J1)E zlJ;i;ksr(eH>-%A(7QH$_jt$NOQR2z%LqQrvR~AZ&`gT;IAuY=l&o`>rmdY}WTXSt z9$*_&62R_e~e)w}4TwSpDh_5>sPS|a3jOY~pF9&0+(Xh&i}!d!2&+DQT&&UJ6T znl}v?9Deyd3biOeNAPJG2#tIM&gJrJMMDcv*dX_-&SXcLz2S*+)N+S!cX}Ec__M}^ z5Uyh|c3bf}%@r$rW$zkIQX5lk>7x<6^GaoW3i1_*BtDjVo-eOx_fJIgl{(5r=uS#! z>i$I3gA$h5Tar%6M@!HfBbBcUUy1XL>T0jMT#Syp%Zz5Y{)_C87xk{p%;a3`@ooz2 zC}^SO2f|y`?ua#FgG6#voN%Gc@rZm3kOL_${reY5OEu3|B7nwHA^=m3OgSB*2L>H-m^N7ENWP}H8`!bo3{5$F%OaCLQ9%^hrOR%yFkn+7W@~DF zc#ykga8&c$IMeWPrDc@As5|6jVAeT1!qE>F*+7&w4LnFSN2kbSOy=6DE4flx`rb|c zTam$^wv*CSbIFqKSa>H96aAl?nWqg2P;KI>Q4(>cJ4;iJ z<;lj}#W~G7)PYtzB`A zP%+czNm0h0jRCjg!X&YZM7o67Z}wY@*W+PTIoqc1eNf?ZS%j*Vngi>j?grnHR@T3t z1Ks_!>liiW1h_I;Fmf#|4Y7+03DNi9Q5~R?8+O4!c+NbQ+DMGe&p9X}u6xlkL{ue$ z?$yZi6lY34^6fye%I09II$X?mTn2K7DocfuDmD}j-2*&R{!4`$`Ns84@R`2igt<5& zi&|)W7dlT4`}J7MBC5amI+acG|$kR*aZL+nx!-noHFH71&p@~S`g58k}`&#mYz zgT59sr%LUk$We~q;bRDSo{R*3*BG*jJB{Zk z0*g_Rc!Z=S2j`*8xaPquLiy%XQt;dHZ=UjHfGvfPE~9~|39ycX4txA~)Y<;!{b=g1I>)1zn2dYak`bxguTr6GP}-zRkW`6QHrJuh8KZpfSLA6e?l`rW~X=->8kw zmV)o0t6Bm}7SMMo;mTyncXiS8QKZa4YBrEK5oiUfnqb412Iu>s8~H|JR#M+gZ=DJm z1GYM>zJyMqPNw`P;=^%bZ5fz~!T**wq+r&yYy7`DOEmfxYS(N7Y8Jq^uD^N6pcDg% zC3=geNr08yjBud(JpXf`+*?DeA~>PCr^bOJHnw-K@pV(N-{Z|AP?**DRGhmdc@hFi zD#Ic=zXj?a7mIutis7vl z6&C)00|P~9w}xJT6&yucAS*JV4H1K7xq8<_;P;S93p#i(CAZK;b)HubeKmf183IQ5 zzI6H=^_3mg-0>P%O%CnMkLq}1`tp{}9pHu&d@k;Ue_Jvw3Kjpk6rcZamC?Ek^&Q3` z4+c^%kKZ*$AC$!MUCU0HbjNCe}bK3&LQXtmr@c2tF$ zL-WQSfx7S>?Cq7sibV+?O!9#@4G+peO<=YF&Q-+_+DVlyyS3q6(zd7PWG}{26~ZJE z#rD%?Sh#Cxps{vraxKNJ!n|72mG3;c!FRlr7Qpp%8Tlk*PlIf+HWAtE*@(8gyrS<0 z>Ha7SwIF!Y7F?w`8AQl>>Gl-$-~DeKQVIXz#SQ{~S1^(JO}nObQdU3Dde%_IPes)- zAZhBH8+CpAul!HcOa2OR9M6bw&%7P0f*Wvc0c+vRPRfyVh(wron;rPU^>SPP`{o~; zjvblmIJ|9%QV+46>B$<2jq9XvP-=HbuNG6C%28^lz1L1irf{IvSXJdkh14W){*&>( zS56l0PJg~*NdkOYl`sz}B52e+2QGy^`ho)M0SdgLosfn9EE^}( zZ%n$QpZ)|Xr0KDmg?~L2*FQf|Pa8-EYe-dIj^$MqBd3DVl$|-EAWr*+e3P54G-eRHM$nTR=3YrtJLzB+-||>#AdBE6#S!0*3cJ%}@cpaN&xpE| z4aCCmLp%MP*r3c_o_$<{==9>uIK^>YJn$-#MuQj=x5V^3jR46i$MBp>{0w zn#x_MX!+f8_v9QdP{Vzy0=$ZGQa%IrBWY;Q#X-3m2uglmzoJ_)}}J00Wjl9}kl z`%8iiTy|vLL%J--Z15f3`CH<}^-s)e_0%oy{^x1>Ck+2I{G|IU|MO!j7P9ky0NStG AyZ`_I literal 0 HcmV?d00001 diff --git a/Tests/images/dispose_none_load_end_second.gif b/Tests/images/dispose_none_load_end_second.gif new file mode 100644 index 0000000000000000000000000000000000000000..5d8462cebb84b5658c81977a0148cb4a7e29b0c4 GIT binary patch literal 17208 zcmY+LbzD>b|F^fXjWJ@3jsb(w-5~;_8z~8;1q4J&L_m~{?r!N&N?Hj~N2f}tAQmkM zDyg8z?!)IB_xI;t{Nv91apHZR=Xzc*eM3EE71vQv9w?p+Iz2s25)-p}XcZK+EiT^1 z!7e%+j%m*L~{S|CxNtyR*bz{GFdkD9uD zXvlYedU_gzX)!Sox+&Pp$CsAIj>9Fz#m&sm&wc&+^39w2FJDfA0=ly#Bpy6SeDNZ+ z8-s~&j32hXILgk>n#CF(el9=%dYF*V$d{3%q!xjD0{QuDBcmhj-`eBiaPvY!1A>C# zii!#f^T}?K+}uG$#zyR+>{g>zxw%R=@^3s!Nm*Dpnodv8%@q`S0Q`y&FK>TS({vCG z_3G;5xsAE~!~L)99D;)Lv9U^*E}hIaH2!RFR|r)oD$;pz{W@n2r=?}Ro?eY|ymEa# zrbt=&@NkWVC8x8ydwl$;V54ATe?592T0|sIr9j2RB-hSvp>V9QxA&K->T*hoR-K<; z!CXO_k56^=iJje}$UArL3kt@aKQAD#p`l|y7em8!85u{%uMg^L z9(Xl%Stqjvs@oLtOoOndteZSB=fPtVd)`@OxtKaUR$4UcDMzl%H; zX@Ek%Cnm+v!fb8FTf+8vr^#jM3h{N77lkTmoB;s!0yvi#RARTFHx+5pY7tSjqvm4ICNsLNp%?P@s zCj5hkM@_w1PA-8bo5%15Z)R6{0{d5@uB5Qq#C2Lb=io(VjH3?fru z3|h+jq7jUu4x=p<1M&1Yqhf=ITv36auQ z#)}Qx@4vXGToY>_G~QQO=8Gv_W`UEQR~clBI*xbL%|0-%GWsjTKU;be*5>mfeAR%6 zWbWB!GY-+uZ{J4HD{D1BeBTK>bvHU_Zug_x$(aH=%~(3Fq*xyA zyMyNl(tV2`RM;`)rfcT86!Kn}jvzu_no%-K_F%n*_E2MyVFJC33wEiPhMmTQ0Fs6c z)p>mG1+`X@nxlLgJ$+Xw2GgQM5Tq&4O0-FLz*>@htL0#u;H0j6YsJB<{i{sA*FpP6dQ8oLxB=hBmGA)nU`$C^V=IdlX$gv*^jpWcCW-!~D_Ps5M` zx|xJS4~>XX+}{>}Q`V2v5z`g!J-WKfH=M$u6tumudxcNw_6!v1zEREVA9-568@Gv^ zRFd^@+jQCYq%@W;QaH-PLvw?JheO4m~v zzwINL)zK^=t0r;#n0w&cliT*I?S1#EH%4g@DaV6P9md-%?T^) z9xgS__s-GJhkc#?K@l}Z%TX-+2Dj7?soy-fP}hU>I+v%S?Jv!TwQ6ggmS`i z!i^O;rY1^J{^r5~L`2tB_-RY{*P$%wnbVtxznOjQTCa@dDcokce(BMKwM&Aw77X6a zR-1`!b#(wey?y+(iq+&JooCoz&m;#dLG;}**MqOOM5w&%mEbfBR&NCt zmqk_?<}2Rexasqz!M-!(FNfk5FPpVX%N_{vtT?QLK12p-nhEp+ycE*{!11#6}AzcBQ6PdV+ zq6ZtT6{4PHny(u(m5GcGFn8?`Q&dm^uPHDULsww*dNRVBTy*XZQlb8Jopr;dryLg- zvg8n>Tt~>Cz};alh{c2XjZw5q_gBYj@MI#KR*eoLtec6+?)Orp!UpHKSo~HJjT4r^D%WLjC=vmNO z=r+jR{griuFKYws z9<1D(-ZMI{ctuKw@33cF;UeN-$l%J(G&&+qf4+5#{>I28ox=5ymYB^KFU8cFUD$sL zWfkJ%W-z)%o}}7H(-QSqj*DNd>&X`zEZwRM8DU!LjS+u)mI;l%?;7pAR|n!jVEZ7E zQI7{489v=iABOHJ*>;Jq@#!R>2gZ}!R!6bQLt49T!!?)AcZH;0NMxz0W{$FaVD1b8f;P48t923%Y&8@fMsf{y^<1zR!o#`BQxNUGwSDryyV zwNa-b+@KFXuTycF+CY_EEGalTI5g;Ug^36>Gap9M$>i4xWfj;AIaPIQ74bCd0LkPs z=PEFfCuy6;9_KxuiBuG8A>&ACj`@n}2U->gh4RrIFlo0<>v z2w}_WOf*h6DVF*HFUG#jimBYRq2dD+>PBxu>U5L**gce#$Z*4`D2txuR2C7DhH&lw zQY-D^LL$Hz1+|31eY%%;(_r299W^es&IK^le^?^2Qtxw^@W-GLicM*1%e z=c?xWee5wYOVq^QcjyX2C&2`jl=aXSMe^(x+tH8$R@YPAyz_-Y9uxU8SKs!kv~_4v z1ToR8{T@X_9#COa`qLcaxtebUXQ&Nl0WYn970+Az@sxTd1&G~@Xs2Bacg%^^%S1yq zdLx%u;JnAcsNpS~EiE5os3MK<0l!C9bJ#3~Y%u1LF1oja5SWPhI6i81C*+RUsDgk) zBrO>fMm1>Ln3)-!DxVluu~GJ){8KrUOjj1hW>tZElFlQR;67I|P#^+4z{*REEQKI-bXiem#qt_%m;z34e)g9P`6(L+E4dH&)YyB3%J z7~&0C<<~Bn#i4bE65Kh$({7d`EK^nbQVMmtXDh5W{uNDxF&cHPk}dJidXIe?AGbo> z^fjBrA;RW66?GP9F|i$8Vb7Z9%!H!(UYC{VC<cx#e!w z4Ao+g;ZwMfE6Xe@?KS(D^b2u9}wl zX@7#b+mG+gl;iuvcAA4sr^|V%>1`U#tta}aKZB2UQ9ASi>#>!Q$A>?@eEzIKiiA)y zh|2#Fu6(89Tbf{{!vy(#m=9RlOr@=jqFHFE$a>%=mc)#+ZJbYP z8A=)wwn+iDo~uqV;GG{5AAtNb^YGd)$xprEzh2U|5uu67Z15}QdX*^QOJJ7SN`cMY z5>>4(vpndhq(DxN+Ry?hvN4SJ-7D1 zfBU1fv)CWcNXZSOfHRNFNc+D$(Iaet*Dacz)JVPC=Rv>;cco9<*>}ijj<0g!R1Ua% zeLldAB0`hXEQRydvbr*e{B!@u51vI0A_WzTd?>x^zw%F400N%KD9}$4u*-*H*mr;y zPHzu%`t!WakPc&58%OfYK2c8#A_L_Tqhx3--$0uRG)}O9U#!yf$Fe^Fr>Z6?2+T5ugX!eP1&en;w z_&HKMbLi-rJvUu_54roXKEn+Hx|8EBIWJ_jgs_(P7%xJ!^Oz1%(NMEY?xD=*qf8st z*@C0!`-OFr@_4&vcq?_>Y(LpW+*ljGrxZz3BLih{FUNaA3JpmcW#hTxmwO_pwpDLlp+tb?7QMNjXqEiIoYpCd^oZfE(vBk-32&=W4fcG+vcA zf9YIsOK4QyP_~f5YfZ*XEZMZ=TnW;;*1R0_M3U?G?{80V0gH4o)VJ8KP)+0xrL@wt z>j!y_5mHc>bbT_4X;vxsHwL%9`o&@-a$YE%hX(RyP5?n1H2G?-|NCI2+W8 zX&xNZXdi8b4-!!>ZQy7?(PBV_43Z9#v`3=}49r(znJwJ%YLA=N4eJb7-<+=_s;kL+ zRl%pWtg-4(A+QZ*<(V1^4Su;^5-7oAl0*li<;G;U7{lTm#a)TYDQ0Q%-a!tN=uwku zjZ6l_F{|aOL6(4NsZOD6jXVdFJaeL}E+em>)L@24emjP}bV*(q#9>_vq3vDZQYIy{ zK0}BVvm_Im3xs9J#tA0{@^!k@I@Zb&u`Dbclx-UHCD*~_^f9=tpkBw$mx+vk?(Na^OWLt4~N`Irew0vbLblHV`>X3n=-%2BYvrs{1Mtsp?^LOB2$>y`hu=PrlsS{{p8owyaUv9e z?TdnwMJjbDXn2tjZnFXq6pXZ?%acBS5QrN|X2;&>AJ3f>DzH z%|8xdeDd7ADk{K<&V;;uXj?nwp$}v>Q6^!$e*`%E#>-jb=4T)x`eF6oWT{B?zrTO} zn4sKQP5}jpftnJeGaOo(#gcS|^(FOaz`k9?-RW8bT~j7fz{)}T|H(h(>eM}#1SfF5 zlp{B}q+Zygr1NT&|ZZ%8b8gmZTgA0WCV) zHamfPm2m`zn4mSj#mky{lgaQGMPTwEFn{ig)SxF~3dMo@-~73g zW>dgg|4_PfT8bb~YSJpJE>W)_^8fOmqh{vkGTUiP1qPYR=nz#|hAmR&$4pm$Y5TAE zwra!d?X;=OhA2=1J^b$L+6uS@mAZgYM|oCL+yyU86kI^7W+R(JL3y-5(KH!KecHuz znV6m*$88tpZBBaBFxSM&WOdo`On9RPJd@!?v2LF`Bg2Q z8lQq1ankpV^N|@iTbHX;$u)EZa@Rf;cT=mHwa`>Y!%ZDiXEBxyPA`@yD;WTO!AVJ8b*5DzlXXy8a_u>C~M?uoeeF1)@oyAAK(^ZrkM2`npCdR+5X~ ztXesc27C^eAs_m7ksCxWD4ybujRr`Lf^}2l?%*0Di;PEJrQ!ZqHABRagP28>QBUv} zap5I~CJv-cBVpcR%DRt<$vE%M4&)z_Gf$ZQqHUFeSmI-9w|tv~QUnmwPM_eUMpxk4 z%bLq`-yM5zGJ42n54`6*AIiu6d*H`hG`gT^@%RwPqb9RY$kWN+5Y};j*k5zz$->Yz#6h%d$QCgiXV|o^feHQDP zCu2pdBt72_5Vg&djLu0F-rnQq$}Hb3H4)vdxFiWP%9p)9e!%>?773t~x#)bjQ*U@j zwm@=mfdF|pOXAv3@r4ebxhB&b?+Zm;fwa@KOq=PQKnC5pv-0aKgTfgF9pXMSpEE0N zT&W(60W#?QF@p!umpbgJS-iG<2jU*Xs4EW*JrUs|#luX| zQvJ?i@sCmftT~QRsHsB#NeJb_?s83q0~A0@78=q^CIyiToi~1b|EqemvpjMwKh6`6 zmGi{X%(stD@o5wJo`&66JH2<}-x9p>nFssCpbErv0&y*QfQ@F6cPKaIgfoj)O0p%OR{m+GhFH{X&uk_~t24iybOWZV#gX)~|3 zS<%*&1aO3R-1yz`kx0Qf*qiYabpjCBuzFD zxz@JxF4yglZ|}Qr{c>`I7D3HfB%<1`qL_q}%kl3h!2JZUr}(!P9@ym$!ExYY7cPBC z-lH5Z!g;XG&gc!QRvxOWIKGPr8hvfoF)k1WoXp$P2U3?4wxlpTE%*jJES zDCYjIquWilwFJErE5=GpA;>-GKT%DRubZhk%Rd1Bv93>LEOzp+Fe zUmU39hZt{J8jgEWtYn>ugA)l&rFiU;x!c)jF2J85Vv6tHSSgsSoz^gRu{n1bbAO7_hxFszq;3C}Z zBWhnCSnP{}TBv3!2iAy^F&c3g`#tyZTnXp1{IfoxWL-<5zjWY56S!WYrzS;sBmrK3 zTFP2(AANPAK==~N5U~1vhm%vs3(A<~D8*uY>B(SMpir?b@8N}i@t=`W$3G$8KR%6| zYx1Ii@2$PKVov0J3E)bHd7l=OOnFdJB@~-kHlm^cd1L$LR%Ni~=}`VLDv&nmgFqY|=R zq`&~=9|a$Y=yHj->#zXci_90*p1`}6D{j&&_y|3_`%TWTP#(<}Q_jrG2dsnq>3{Q2 zXH%sB-5>%BP~aH1RUmj*gtoeg*+kvM0pB5T8j&=v{pFe@bymyuA9SKPuc%YGz2qZ|h*IWzp7 zXu6~N>-(qY(I~0A5x=A#44NbaxTyU({6_U`wrSAE-A?RyUs-4dLtw`Zo zU)05$UzJs6Dh8y5%>k0Rb1jA)A$@l#vBL`$gUiMQ8_nK|91M^dQ zxh1@PyGPhA(w25Kni5}cI-MalC-&r)v&b25=??DzMKd&-4AE*v!RyS|M=fNXB^?T~ ze8+W#J<97RkA|VZXW5gOSUR=j;7xnc--DNRg%~(M&C>-c{Y~1}-RzEbZx5t@=KOr3 z2W+=q)7+?E=kbV+k<^69R~7pC>LuYfx8_>)BZ=64V#sII;=oAq2{D9{u4AhL_&odd z!&xLlqwHCf$eY1=BwmaT&P)bfblJ$O9IrUvUxc`vplRPBINd{ApR+tw0h`Vdv8v!J zQVhFi^AHzM4SIU+=DKpA>;u-A+XgNJM9|w;( z9{G3wRbuqWr$Ekq!CNf=#3SVdfM%~b?SY1NuUS#MiO1J3tKyG*Rim-PNzCtT*k*}7 zbKHCh;vBW=N_&`as9&LoRbOy%Hg;)(;B@mGb1kV`>tBQyUv!W*`#`nU>0=+m zeI;ABkzv`!pFG;$L0c~~1z!*>$WhchX1!gzK>vk{>|PRgego?ZUI(Fj#kgZZbX5A%#uMhAEksMC4-;H)<6gs(c9yAntHBq;WCvvcT?>+t{zrD5Vda}pLk1{7fw zdVg2m&3?I14)k9Fq6aWuo|vwu*w>@uvur~`2spV z{VZ{n;Vgj=W}7y5rQsRrb1Ffh`+7q9X*X4ZPIgHfJX7Ub@eC3^2f{N|NnYl{ZfkYS zrc4N`1ayUiN>C-#WVCWoY`(>f*=xh~?KUxp(Yzdw9ZwR}GJZWBJG><6)T{9Ge$~u! zpMrW77NgSU=a_~u+mN|$OK^-o>%X|=wrK?+Fwqvy*@}U*DIntuJ1&l9LdZbdw&Au} z+7a1yb++mHpMUs|ah0ZlRVJGa$1#@QQ>%M*tv`1nOE)@dW2WlbVk|)8m=`+z)6JVO zD&VWarm7<(eBwbuE&bBssoKdejamaS_hG}dlPv_EEf;|$NYNvLr9*cX0si0O(kg$S zLgu{FGnsMsbpvoJrwTVOo^%<4CL83*hcS2<<%-!qKF>Z3hT-H=<=fhpNks16(4}O0 z$zlkMBa|yans~9@!+0>mz7^segE*pNViZ`-9?!$f)|KQ|qF5f$wHE3{a5RY!kpSXO9(55J~&NSR|PW3>2A-*iUuMBe@T z=lItz)J_?R2&Lw*)=7l3-BC}GZv#*YO%T(VF3DE%0~9Na5kIDstsc$fH!eC)wZ{&y z{j{knThiD$hJ=Dn{Lz)3Cot z#m4zo_lY8AF;jyID8)~_JyeO@M6>t%R?!g zs&{Er+E&MM#4bNeQE6X4<3HcUOfT`Fs~H8d1izJiebadP$z592|DS*S7G`3YjHF#a zIl6<%obhc}@lje@|J#45I~MT?nlKsup;YfZ+FhNvr;)Dy^!MR*jZBanDC)$(JN#Ye zkHN8GV7r~7Fi0N-iDxysZa*8Jpw)T|nD>a6%I? z-E6wh1m4wwgiO7n2>MD*Dw4(-|M^eXLr*-edB4J2n zqDK6uh~N9vQ^1z-`G5HjOjbp}6Vgo~#+`-6x&VJ1jprttPbLY=eCR^YFkNxS;nYb1 z*+2cy`Y-4H6p`fYBi@M^7mE+GGWllC;B41sNE-pm@FIu~wJ zf@eGQ7n^HxdLH!`=`zL+C>lD#tggB;P&)O=MXQG&z!7TUi(E#fHG$ZvdD87nPirTzPJr~hCuH;v;!zh zmd6V_(}Vy*J{*SZk3EY$&D@l9jV&{yh)5h0=p14{-9S)zw=hzi4b3J}%;;(rh@BWHyGvClRa590!sl9*-O zsx314AoBr#I`jRVpGSfzSb zR%$dgZ*IL&a38ajbWr)RCJ5YRRhhYLy7K5s-fzygfBje*$=4{md*=^XCzMU^jHZ!6 z)Ci354no!K#AQ)LyOBcG*zS`H`)mc!f3duKD3>#wn0>PtA0v%l8)HZpbUkd?YiHNja#R@EM{%|BdZK#Q<9fGm@Tk;0e4t zGjPVGlTDzf6RuipSjfYDl#alW!|f@6sc_V))H*%oDC(J;`VVw6Qs&y|yVnVak)o-2 zny?d4aOG&O7%OiaNQ+6{zR<4*0pmzI_5S?w>62eS76+2aD5-u5aESg44=?Eyp&H`Y z({e?h;28UdIgMsO-q(bZzy+n_w`-wz0)gQR$|0sDJsb+<=wr>bk@R4Uybr$?3|+|} zK>xQEOnWIcSjW9FN9KAF0Kb$EH!56>6qx1+^J6t6ApfX8Kwxz=@p%DDe1k0jTtSOj zJY=fCYfo!5+CTDJTX?f&+v3C?c9e}9>A|RMgzo3zC`(-PhFcoU=Ok5)^M->L-_QN{ zEHemnTO$I{=wOU8zQH1T;L2zw4;lY2wsR&n4Ye2XY`UAwR(b%-;O$y1f~;CcqnrTf zWPVw*$w!zQ)S7J!P%sxSdWH-EvO^a_rjg0jX>fd>kIBp6kL}0bH@DwC^8fP5@ks_W z^HfKcQF!DS<2|!lE=MzQ+t^Wb@`vp3UCNW=!}O(e7#uGpm$9=2>W={)jhBIoAX<+2 zgek$dwO+f4MTQ*4Y8ERNFREGijM-f90$h}EmYjeh$e?C4s6X8{f*Iszuc&Rh!+t))N|2P5^Z2u~h#+Dmfod{hi zrIh>Blmc{q$X2@T`I{SCzx+STK!I~dG63SBfwD-eOCO;1$hrsATC9vQvJ@Gc`YeS3 zU1+6#x}-wg&?8E6{bh5*{4^pg602-l=lMP@>O=R93gt)J6b(LBOzxWagba0_qNG7U zMYE$3o8d%<_oZf_w4_c0|HFT>QBs529RB`0CsE)f)N^N)3!W4M)V0?_$6Z?8sestS zg!#x9mun@SA01F#iOX&CF6b=QuV0VjpT`KjtCN(dMBwZl?80QwrZyM49 z^|7?HOCL1B0U7%9ps)eZFhT$yBUhII;!)?YZ_Sdp*GM7OX#MbOG(F7pj9>oxum6*` zT?+>C<-o!Eg(CTaqot)^lz{p5{O<0PAdmSLU_GpgA6!k`#832G$eSd?M3}^vm+UPr zL~uOE=8T$apPMD{U>oGS1#;XJ0XSiYY$}n85kB+A;FcL&{-#3ddDmTj95vTDpRmRu?RW#03#GLx z$GA0=!Ue%rpA2K-WTE`E^`1K32T``?!$ha1fDfCBBf7@XJc+mh*8lN;EV&f0rbQU< zo^XYOs|9xAw&QtsqQ@-bANi_ohyHm?j&|tY2JREAW^&#Q8X7jdj=)D1Du$Pv2+whA zHLDcPd-b-c_+lf1=#Pciua@W7XYZp8AKZtEgF=`J)KfVQ8-Vyz-UAt?v$|@a#i9G|T51STQHPR0xyB#St-fnj4T{NT zpk@GIsorWln2{8kvIVq~y_zR=*FgpRhV}gSX^QG?siw5>;USx2*_7P9#$OUnq(R0- zB@W2*ccI5d0RQ<1mNrpJIjxN^sZKS0B!;XG_8#S1eK9LlyK@TVu-z{{d?^!_Ph?9U0XwbDIA9vadz|wKfb^j*%Eqce_%={BfA{?;3 zu@C_g-1{;;cQlfjda_J|#}xM1{af}SmCJZeGUtx$hvr}aQiT0o19t?j#Bm4A?0B1( zn=duQ(ea2*(MuZV1@!{#_(5RRFa@PxvHhMu|5%pbg-VmUAOYiSz7N|}(7pjR)NK|C z@`9WT^tqDy@fla(VR7S1Yg2WD(-Q7`fuM<1km$$tHjnDeiLPMVrY9#L1ZT~wICH}+ zgFTP&91KHX?e#>t?}Le)cg#j7u3h<26~5MQI##pDywu+uv^FDM!;wLWB3M(8B+n7Y z^TaOD?`usze_5&#{qO!u*H~N51qD5ia-o^000SlijxRM}4GD+JdB&x>0s=$Hxnwv$ zf?*te!+cs=XZEqn?_g$878mD$jY2-qC-8g^&if?P`TqKtVY5>P7XQ(AltRANloPMG z2NM2Q?*tMx2LMbCfQ;S2QINhEap0GX?V*Ig0IY4NJZ5Q93HtUF-2mJU0sLb0+Q<<>CopG%jc;h&>E zpjCgSNwIc7M*CVrlCeHY*1=nzRkRpocHdPniP||Ps23E^_@PSw2}S&SF7sZyz!)kw zv)E&$|N1|LH@=MXA!!M12?u<_x6eLNJYFTBx#2VjopR%Ry6sgR#Wj(62i;MvLpWS}_00@NAwfgVn|LZ?Hf1n|>Jy_uu#%h0mMsrR0f^DO1gW$N?lABoV- zmk-`|{`hcqbRO0y=<(hfB)*syIJ(_4fLwo>>SIsVOao}bP}0MBC-FF8Fydt~xw3kr z?0A1;w!!(;zxuD|lvs&O1X^n^nV$EdCWbJMp-q`td?zbtQu=5&cd&w*JBa@dlDYm> zqI$)5e9!)-RqX{{;HcJn+5DKxk6$;$Q;c+RDgjzaYu~!*z1;I9K>_P2Y~`Boio?-* z3mVmixso0WuYvz&QDasks(`2s9M2(MYQL^0*D~VJWw6Fa;xh35(fIdZ^W}ThjPH{* zs=sE1470qtGjNn6&KQ0_UoQ$uvwO6O%tG9hn9&V&a3 z62u!O%tnG~#q6`drDIok2bDPm7kY+qX2rA|O2usQ?xW8$&iIe_9{+fbsBN3?rmTPn zvr=QGIdRET=^DSmd^z)?&=hEY9fpwp0l0>ec|C|lH}2PA{0^@NT;KQ*XfJhU)n2_m z5Xb07d3=2JU;S6x^{t=(_&+_c0E*}&Mj`2)p@0DnD&~(6dP#>+?&ZOxFWm@yln&_H z+jR@UrG8yCKwCbE8n{BSF?IRzpo;54aIP?!Y}4-d?YF}A{D1h*yNl8;=0GD5x7erT zvcVz*3R>OIlk?|xaUv*y?o+U7UC&Tp*f;3fNLx`Y-nnk(d#3#;XukeO`x%V$Ag|9h z`;*mAPk#UUKmN}WUPF|vp0q>HH|Ph3Oty!juMomGDRjc_Bk%?wZTJhhO^ARIMmhLz z6ovj2yimw%2BY*{=OypN>EXdKmL3M6i!_9h>4LwKPiXtuP2AJ|T_rC9uDE zrXc<2I&ESY|9W@8pT|yWn2{!`bAhZsJ_fFs9Xw=Ob9U*Areal$U<-5`N@iCghZGm& zAeq^OZ6Bvpa3+S`b8NJLg5)=_{095VKy~x@`Za?NK^cE15NrF@xpqhY4^)8vv;T7+ z6&kQKkjScZ7ZVnA#(yrPA+>`yXTXNLxSE+>5YScp-g(&9ewEf2hLuT&CW81O838{& zE#!rP9bPv#*E>HAmsBj?LG8qlh!i8lKk?EP{joHh=OPd?m4k^)Vn)>Mt3!3H7?D^D z9V1v=CclgWh``{H1N`#FUfcD!$tz%k`QF6YbrwxPnWA3g^U}DeQ}-tM2Hz&!N2ur= z*W8!>=l}T6NeT^bA38h<|J!pBU1Q}th^5Dh#x1b93nK7XJu+Qfcd%8&wH;sf?5jM$ z5|{W$EZpY}*wj;wS{^a6L$4RIVhPl&f352vkHl`2sSBCWRC-FhOq>?_Z7!B0LZn0i z)^%9w`UER4AH&}#|L(v3oC5hL;3KHNS2-G>5pF|nOk$7u!dw68MJ#+VaG%%GE*t9} zfLy;S2Am*&?!?3G_swOL&gMyH2W?eM&yzB&P!|9f=vdY=-uX@FUl)GIa*cnuguv!A zl16u>_ZuwjK!M>WS`C^Zcib z;TZt(k5-CsAm30D3mJ@90f7rCxHayk;62@AxYguM3=55;;Z8?%7`$Gx4Tk1pk1M&W zHFgm03p|iG&Hkctrl<%3!y@Y}sZ0C@#R+F>oFC`1c~!_2Z4AR}DD5!`=w~j3c}iq- z*4vhxyHSkUbP=IvLU21cMuWjo@s!W?3f`?Ofw}MAhBFx*`2Uyx$a;(=ITfSnmq1@$ z0`>8@B`r+M2H)m2B`q-5@V1#rc#72Ez~bKF1)E}_)$ZVY?Pt!I!%OkV{FwvxLQ^q| zutz(c?(T|V5fkSg%Lg|1D}CZ>B6MrhRa);7LmSRZ8}ajNHmm3ZpMWk@v-gy6E+n?y zxU%@$zd%~j?IY0**Q6)64R_X@wc}B|dO6COZo0|nnzOcw45+0%nvb_Cc#BJXgubm> zwpjLwZBW)uYxX(@#9k39+5K?bF=%xp0p zC698q#IJTD8X2jVs6p*je63q8Arg5?{+}H(|E!x<M&e&q#+ z!9Kr0tgL?dZ{ceU4-GrK#&ha6SWNFpyG~1c-BbAcQ37)C)qT$Cs>OYO+M>Re*Tjfp zI=fHR7b0WT1pU2FPj)>Mo>kz9GuwgL8_tpB|KtD2v#kSG<2OET5-WhQoB&(SYpy9i z&K9d3XMN`Xz(NSV*LHXZsF>L*$9(x3*CCvHtDEm?OmrDJFB(WtfJj!Qg430*^BH{O zYI4CFXG30AB`RBO=K{69AfL-}^(Qf_!YA&v`#04N$xgm6Ga%B8nQG^MFEvR#-TZI< zVQCyC5-7eg@F<_ne*szTaH@PUcWt78+3VA!y{4opsyD(eNbfb$VS@#6`RO7&5hSUI zV0^0+o5~cwx8dD}eN{zW>HtkX6em`w0EE`giSViC=Gj~X{^>y4)|{%>XLVp1O1Ay+ z0{} z6k~E3X&SJo<_ZyaTZJt*Q@R$SY~qnE;6HbGziIM#AM%YF zsoOaDsLgGN81gL~FtfkrLV&6+6KCr;e%3@ud48}1tgfRSzz+5uT4Qz}>~)!bw}16j zjge`QbrOvFW(xeE{_N-Z z|3xKeiYmu&P~%_x=Pdtx>_+=o>tqW8W@~fCo4dNLY%)n+d%P}Mc_PSzFU!p&4Ll4& ziJW9^a)?2!0`S+a5s)g4?aUj!T3=VQptv2xWa@G{w9LO|Y+IL;GI87ITDAk$xT`F< zrO{XbG{*y!KaE$KW`g z)?vWF$J;P{e4jDKcy!5atLxL2bkeo z9go7Nuz__Oy%^eKjJyl>f$fIuFawJ?a3_yt4qT@DrqcWOctvwmV|QgN|6lW88zQaK?yzUMd@^Tv zuMyyU?(_s#3VKaR7&7Qxou^QKR4ny3&=N30l>|&2*>&u@=usH?M%YaU3r?m7^Vf9< z2c}-2($P@viWmdqfq@#I88LH0=}QP~{^lk~zILiYQ^K`%uqkS$2AFnX*9O43KQNEk z)#Jy-1}_|5mQ)BhWc%Da;Q!pB zG%k=v3!C#Q|1+PlL28N$3Yjdl4OJf=Xpj8Y{MVD8-#&C(xmArB0WDKROIV*Cs5@wT zETJd^XjzXBwr1x@4e@trdv_j!>{2FU0N02Ky@ah1p2R@4q)u71-MQh_#bNvJ;A{uPEW#OKC<0?c*^zv{h#0I z3~W5)RN$dqjee0V2O0MeVO0dk2?tZLZn6yp(4yEhDictjiOe@`bx6i=B8Bc3`rNMJ z_zP5`I?5Qm;(}3>sP$chVa655GDs>3d*I;tn;@=B!SOPA(ypzqD}c7QNnLsm z|HS~j@aP&3Z-%NRFNhpLhI2a{1uPGx^8Dh8gTpLzi6Ng0zAf8`#rWZfIr%MWj_r7 z)m$oCF7klJfh;#Gxq|2QCOZwJN!(Waw(!`0rOA{k1%-RY$=vGZ0aKB6=UYrRH;aw~ zDyqWD<)@7XtJPLd&^m!ekONIwMPS5lcgeyilQ+doEY>jZWbyQ+a3ZwK*IV(Xu5Q zqHo`>+5-#}oY@8bOV1oTg|aguZ|$zXdGhc6>*WM6oq;S$;`dvnpixqUxD8@$CAH2J z?abtsupwj+QKoBL3IQ-%$Ivi+n@6Fc{hHxsA{K7d@kdm99;7km=&DCSs!dCST zV{J7P`O?OsfN!6o&Xd|Wn4l@C)eTICn}DMF&qz+zf9Buw)wN~a<})F%x87<&gH%t= z02lt=Y=dvJ2KRT5y_T!52!IPPR$|=wule^g|Je!T+Eo%nT2FDMe2^ED`LnroW#p{? zGU=8j_#2!rFkFe@ehLWu2OOq7X`AxI$OV|M@@sXF`dG9;EvJ0LkgE AS^xk5 literal 0 HcmV?d00001 diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py index 90943ac8f..833294d81 100644 --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -307,6 +307,20 @@ def test_dispose_none(): pass +def test_dispose_none_load_end(): + # Test image created with: + # + # im = Image.open("transparent.gif") + # im_rotated = im.rotate(180) + # im.save("dispose_none_load_end.gif", + # save_all=True, append_images=[im_rotated], disposal=[1,2]) + with Image.open("Tests/images/dispose_none_load_end.gif") as img: + img.seek(1) + + with Image.open("Tests/images/dispose_none_load_end_second.gif") as expected: + assert_image_equal(img, expected) + + def test_dispose_background(): with Image.open("Tests/images/dispose_bgnd.gif") as img: try: diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py index 4ca5a697e..95e300bd7 100644 --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -301,13 +301,14 @@ class GifImageFile(ImageFile.ImageFile): # if the disposal method is 'do not dispose', transparent # pixels should show the content of the previous frame - if self._prev_im and self.disposal_method == 1: + if self._prev_im and self._prev_disposal_method == 1: # we do this by pasting the updated area onto the previous # frame which we then use as the current image content updated = self._crop(self.im, self.dispose_extent) self._prev_im.paste(updated, self.dispose_extent, updated.convert("RGBA")) self.im = self._prev_im self._prev_im = self.im.copy() + self._prev_disposal_method = self.disposal_method def _close__fp(self): try: From 5e4e0fa6ee67fd55105fc94c7cf96256ef543a6e Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 24 Dec 2020 09:55:22 +1100 Subject: [PATCH 118/186] Use disposal settings from previous frame --- .../images/apng/dispose_op_previous_frame.png | Bin 0 -> 582 bytes Tests/test_file_apng.py | 25 ++++ src/PIL/PngImagePlugin.py | 117 +++++++++--------- 3 files changed, 83 insertions(+), 59 deletions(-) create mode 100644 Tests/images/apng/dispose_op_previous_frame.png diff --git a/Tests/images/apng/dispose_op_previous_frame.png b/Tests/images/apng/dispose_op_previous_frame.png new file mode 100644 index 0000000000000000000000000000000000000000..14168da8992ee8bed51ce4e33348f2a84175c128 GIT binary patch literal 582 zcmeAS@N?(olHy`uVBq!ia0vp^4M6O`!3HERU8}DLQXGlNAwEEw8HgFqz1?*HNJ*tZ z#6Us~KPBV0OZD|r8tHFX(pgoFE|Rqz3L`s!c}FvdGqIutC_d3y%bLaw!z?{QEGv_Sa6$Y}J!PC{xWt~$(69D#V Bs7L?+ literal 0 HcmV?d00001 diff --git a/Tests/test_file_apng.py b/Tests/test_file_apng.py index 2d50748bd..97e2a150e 100644 --- a/Tests/test_file_apng.py +++ b/Tests/test_file_apng.py @@ -105,6 +105,31 @@ def test_apng_dispose_region(): assert im.getpixel((64, 32)) == (0, 255, 0, 255) +def test_apng_dispose_op_previous_frame(): + # Test that the dispose settings being used are from the previous frame + # + # Image created with: + # red = Image.new("RGBA", (128, 64), (255, 0, 0, 255)) + # green = red.copy() + # green.paste(Image.new("RGBA", (64, 32), (0, 255, 0, 255))) + # blue = red.copy() + # blue.paste(Image.new("RGBA", (64, 32), (0, 255, 0, 255)), (64, 32)) + # + # red.save( + # "Tests/images/apng/dispose_op_previous_frame.png", + # save_all=True, + # append_images=[green, blue], + # disposal=[ + # PngImagePlugin.APNG_DISPOSE_OP_NONE, + # PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS, + # PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS + # ], + # ) + with Image.open("Tests/images/apng/dispose_op_previous_frame.png") as im: + im.seek(im.n_frames - 1) + assert im.getpixel((0, 0)) == (255, 0, 0, 255) + + def test_apng_dispose_op_background_p_mode(): with Image.open("Tests/images/apng/dispose_op_background_p_mode.png") as im: im.seek(1) diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py index 6af41af6e..590a39017 100644 --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -803,60 +803,76 @@ class PngImageFile(ImageFile.ImageFile): self.blend_op = self.info.get("blend") self.dispose_extent = self.info.get("bbox") self.__frame = 0 - return else: if frame != self.__frame + 1: raise ValueError(f"cannot seek to frame {frame}") - # ensure previous frame was loaded - self.load() + # ensure previous frame was loaded + self.load() - self.fp = self.__fp + if self.dispose: + self.im.paste(self.dispose, self.dispose_extent) + self._prev_im = self.im.copy() - # advance to the next frame - if self.__prepare_idat: - ImageFile._safe_read(self.fp, self.__prepare_idat) - self.__prepare_idat = 0 - frame_start = False - while True: - self.fp.read(4) # CRC + self.fp = self.__fp - try: - cid, pos, length = self.png.read() - except (struct.error, SyntaxError): - break + # advance to the next frame + if self.__prepare_idat: + ImageFile._safe_read(self.fp, self.__prepare_idat) + self.__prepare_idat = 0 + frame_start = False + while True: + self.fp.read(4) # CRC - if cid == b"IEND": - raise EOFError("No more images in APNG file") - if cid == b"fcTL": - if frame_start: - # there must be at least one fdAT chunk between fcTL chunks - raise SyntaxError("APNG missing frame data") - frame_start = True + try: + cid, pos, length = self.png.read() + except (struct.error, SyntaxError): + break - try: - self.png.call(cid, pos, length) - except UnicodeDecodeError: - break - except EOFError: - if cid == b"fdAT": - length -= 4 + if cid == b"IEND": + raise EOFError("No more images in APNG file") + if cid == b"fcTL": if frame_start: - self.__prepare_idat = length - break - ImageFile._safe_read(self.fp, length) - except AttributeError: - logger.debug("%r %s %s (unknown)", cid, pos, length) - ImageFile._safe_read(self.fp, length) + # there must be at least one fdAT chunk between fcTL chunks + raise SyntaxError("APNG missing frame data") + frame_start = True - self.__frame = frame - self.tile = self.png.im_tile - self.dispose_op = self.info.get("disposal") - self.blend_op = self.info.get("blend") - self.dispose_extent = self.info.get("bbox") + try: + self.png.call(cid, pos, length) + except UnicodeDecodeError: + break + except EOFError: + if cid == b"fdAT": + length -= 4 + if frame_start: + self.__prepare_idat = length + break + ImageFile._safe_read(self.fp, length) + except AttributeError: + logger.debug("%r %s %s (unknown)", cid, pos, length) + ImageFile._safe_read(self.fp, length) - if not self.tile: - raise EOFError + self.__frame = frame + self.tile = self.png.im_tile + self.dispose_op = self.info.get("disposal") + self.blend_op = self.info.get("blend") + self.dispose_extent = self.info.get("bbox") + + if not self.tile: + raise EOFError + + # setup frame disposal (actual disposal done when needed in the next _seek()) + if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS: + self.dispose_op = APNG_DISPOSE_OP_BACKGROUND + + if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS: + self.dispose = self._prev_im.copy() + self.dispose = self._crop(self.dispose, self.dispose_extent) + elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND: + self.dispose = Image.core.fill(self.mode, self.size) + self.dispose = self._crop(self.dispose, self.dispose_extent) + else: + self.dispose = None def tell(self): return self.__frame @@ -939,19 +955,6 @@ class PngImageFile(ImageFile.ImageFile): self.png.close() self.png = None else: - # setup frame disposal (actual disposal done when needed in _seek()) - if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS: - self.dispose_op = APNG_DISPOSE_OP_BACKGROUND - - if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS: - dispose = self._prev_im.copy() - dispose = self._crop(dispose, self.dispose_extent) - elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND: - dispose = Image.core.fill(self.im.mode, self.size) - dispose = self._crop(dispose, self.dispose_extent) - else: - dispose = None - if self._prev_im and self.blend_op == APNG_BLEND_OP_OVER: updated = self._crop(self.im, self.dispose_extent) self._prev_im.paste( @@ -960,10 +963,6 @@ class PngImageFile(ImageFile.ImageFile): self.im = self._prev_im if self.pyaccess: self.pyaccess = None - self._prev_im = self.im.copy() - - if dispose: - self._prev_im.paste(dispose, self.dispose_extent) def _getexif(self): if "exif" not in self.info: From 8eaf9e7cb7d8c8cc33941f6f07a568d3537b49bb Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 24 Dec 2020 10:47:06 +1100 Subject: [PATCH 119/186] Fixed warning assigning to "unsigned char *" from "char *" --- src/_imagingft.c | 2 +- src/libImaging/GetBBox.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/_imagingft.c b/src/_imagingft.c index 62db561ea..183cfb23e 100644 --- a/src/_imagingft.c +++ b/src/_imagingft.c @@ -1084,7 +1084,7 @@ font_render(FontObject* self, PyObject* args) if (color) { /* target[RGB] returns the color, target[A] returns the mask */ /* target bands get split again in ImageDraw.text */ - target = im->image[yy] + xx * 4; + target = (unsigned char*)im->image[yy] + xx * 4; } else { target = im->image8[yy] + xx; } diff --git a/src/libImaging/GetBBox.c b/src/libImaging/GetBBox.c index 9a8ae1f32..8db78c2e2 100644 --- a/src/libImaging/GetBBox.c +++ b/src/libImaging/GetBBox.c @@ -198,7 +198,7 @@ ImagingGetExtrema(Imaging im, void *extrema) imin = imax = v; for (y = 0; y < im->ysize; y++) { for (x = 0; x < im->xsize; x++) { - pixel = im->image[y] + x * sizeof(v); + pixel = (UINT8*)im->image[y] + x * sizeof(v); #ifdef WORDS_BIGENDIAN v = pixel[0] + (pixel[1] << 8); #else From 46f7b4a439819d45ab727ec87384d5d651ae26bc Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Thu, 24 Dec 2020 10:50:43 +1100 Subject: [PATCH 120/186] Updated test name and text --- Tests/test_file_ico.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/test_file_ico.py b/Tests/test_file_ico.py index a5f728c42..34fb42abf 100644 --- a/Tests/test_file_ico.py +++ b/Tests/test_file_ico.py @@ -85,8 +85,8 @@ def test_only_save_relevant_sizes(tmp_path): assert im_saved.info["sizes"] == {(16, 16), (24, 24), (32, 32), (48, 48)} -def test_only_save_append_images(tmp_path): - """append_images should work to provide alternative sizes""" +def test_save_append_images(tmp_path): + # append_images should be used for scaled down versions of the image im = hopper("RGBA") provided_im = Image.new("RGBA", (32, 32), (255, 0, 0)) outfile = str(tmp_path / "temp_saved_multi_icon.ico") From 645b10612f351fa0dd24a11c9528c66f4440ad12 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 24 Dec 2020 10:51:49 +1100 Subject: [PATCH 121/186] Updated harfbuzz to 2.7.3 --- winbuild/build_prepare.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/winbuild/build_prepare.py b/winbuild/build_prepare.py index 178194ffe..fd80ecf65 100644 --- a/winbuild/build_prepare.py +++ b/winbuild/build_prepare.py @@ -275,9 +275,9 @@ deps = { "libs": [r"*.lib"], }, "harfbuzz": { - "url": "https://github.com/harfbuzz/harfbuzz/archive/2.7.2.zip", - "filename": "harfbuzz-2.7.2.zip", - "dir": "harfbuzz-2.7.2", + "url": "https://github.com/harfbuzz/harfbuzz/archive/2.7.3.zip", + "filename": "harfbuzz-2.7.3.zip", + "dir": "harfbuzz-2.7.3", "build": [ cmd_cmake("-DHB_HAVE_FREETYPE:BOOL=TRUE"), cmd_nmake(target="clean"), From ff9715f079428b3f62b864d472f21fd33e367d94 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 24 Dec 2020 11:17:43 +1100 Subject: [PATCH 122/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 8898ae10d..59ceb82b8 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,15 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Added append_images support for ICO #4568 + [ziplantil, radarhere] + +- Block TIFFTAG_SUBIFD #5120 + [radarhere] + +- Fixed dereferencing potential null pointer #5108 + [cgohlke] + - Deprecate FreeType 2.7 #5098 [hugovk, radarhere] From 2899ca03878665a7c64f394df1e6bd0427e937fc Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 24 Dec 2020 13:13:44 +1100 Subject: [PATCH 123/186] Added release notes for #4568 [ci skip] --- docs/releasenotes/8.1.0.rst | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index 819bb30e0..7af2e79f1 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -26,10 +26,15 @@ TODO API Additions ============= -TODO -^^^^ +Append images to ICO +^^^^^^^^^^^^^^^^^^^^ -TODO +When saving an ICO image, the file may contain versions of the image at different +sizes. By default, Pillow will scale down the main image to create these copies. + +With this release, a list of images can be provided to the ``append_images`` parameter +when saving, to replace the scaled down versions. This is the same functionality that +already exists for the ICNS format. Security ======== From 26b91815916e1ab25facb4cca199896267b4ff90 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 24 Dec 2020 17:11:49 +1100 Subject: [PATCH 124/186] Updated macOS tested Pillow versions [ci skip] --- docs/installation.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/installation.rst b/docs/installation.rst index 849cd02e9..2f97d9f39 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -465,7 +465,9 @@ These platforms have been reported to work at the versions mentioned. +----------------------------------+------------------------------+--------------------------------+-----------------------+ |**Operating system** |**Tested Python versions** |**Latest tested Pillow version**|**Tested processors** | +----------------------------------+------------------------------+--------------------------------+-----------------------+ -| macOS 11.0 Big Sur | 3.6, 3.7, 3.8, 3.9 | 8.0.1 |x86-64 | +| macOS 11.0 Big Sur | 3.8, 3.9 | 8.0.1 |arm | +| +------------------------------+--------------------------------+-----------------------+ +| | 3.6, 3.7, 3.8, 3.9 | 8.0.1 |x86-64 | +----------------------------------+------------------------------+--------------------------------+-----------------------+ | macOS 10.15 Catalina | 3.6, 3.7, 3.8, 3.9 | 8.0.1 |x86-64 | | +------------------------------+--------------------------------+ + From e9fa245b696a11fecf0123ffcc92d66dbfcf908e Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 25 Dec 2020 18:08:48 +1100 Subject: [PATCH 125/186] Documented the addition of PyPy3.7 wheels [ci skip] --- docs/releasenotes/8.1.0.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index 7af2e79f1..2284b22a5 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -44,7 +44,7 @@ TODO Other Changes ============= -TODO -^^^^ +PyPy wheels +^^^^^^^^^^^ -TODO +Wheels have been added for PyPy 3.7. From 51b813792493818202645f6b064551f15a17610c Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Sat, 26 Dec 2020 21:49:40 +1100 Subject: [PATCH 126/186] Changed style for consistency --- src/libImaging/Histo.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libImaging/Histo.c b/src/libImaging/Histo.c index 923fa28d5..512e57a98 100644 --- a/src/libImaging/Histo.c +++ b/src/libImaging/Histo.c @@ -44,7 +44,7 @@ ImagingHistogramNew(Imaging im) /* Create histogram descriptor */ h = calloc(1, sizeof(struct ImagingHistogramInstance)); - if (h == NULL) { + if (!h) { return (ImagingHistogram) ImagingError_MemoryError(); } strncpy(h->mode, im->mode, IMAGING_MODE_LENGTH-1); @@ -52,7 +52,7 @@ ImagingHistogramNew(Imaging im) h->bands = im->bands; h->histogram = calloc(im->pixelsize, 256 * sizeof(long)); - if (h->histogram == NULL) { + if (!h->histogram) { free(h); return (ImagingHistogram) ImagingError_MemoryError(); } @@ -84,7 +84,7 @@ ImagingGetHistogram(Imaging im, Imaging imMask, void* minmax) } h = ImagingHistogramNew(im); - if (h == NULL) { + if (!h) { return NULL; } From b48cfa747cecd02ee4d76d12f7bbf64e186982af Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 27 Dec 2020 12:29:43 +1100 Subject: [PATCH 127/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 59ceb82b8..6b733cac4 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -11,8 +11,8 @@ Changelog (Pillow) - Block TIFFTAG_SUBIFD #5120 [radarhere] -- Fixed dereferencing potential null pointer #5108 - [cgohlke] +- Fixed dereferencing potential null pointers #5108, #5111 + [cgohlke, radarhere] - Deprecate FreeType 2.7 #5098 [hugovk, radarhere] From 6ee74e1f1897b2ed38c90767ec81328b3a205ac0 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 27 Dec 2020 12:48:29 +1100 Subject: [PATCH 128/186] Document limited number of characters [ci skip] --- docs/reference/ImageFont.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/ImageFont.rst b/docs/reference/ImageFont.rst index dbab0f395..813d325e0 100644 --- a/docs/reference/ImageFont.rst +++ b/docs/reference/ImageFont.rst @@ -8,7 +8,7 @@ The :py:mod:`~PIL.ImageFont` module defines a class with the same name. Instance this class store bitmap fonts, and are used with the :py:meth:`PIL.ImageDraw.ImageDraw.text` method. -PIL uses its own font file format to store bitmap fonts. You can use +PIL uses its own font file format to store bitmap fonts, limited to 256 characters. You can use `pilfont.py `_ from `pillow-scripts `_ to convert BDF and PCF font descriptors (X window font formats) to this format. From bea3745a743edec788e3607cf1f365a494d47af9 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 27 Dec 2020 13:19:07 +1100 Subject: [PATCH 129/186] Updated harfbuzz to 2.7.4 --- winbuild/build_prepare.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/winbuild/build_prepare.py b/winbuild/build_prepare.py index fd80ecf65..324f91cd9 100644 --- a/winbuild/build_prepare.py +++ b/winbuild/build_prepare.py @@ -275,9 +275,9 @@ deps = { "libs": [r"*.lib"], }, "harfbuzz": { - "url": "https://github.com/harfbuzz/harfbuzz/archive/2.7.3.zip", - "filename": "harfbuzz-2.7.3.zip", - "dir": "harfbuzz-2.7.3", + "url": "https://github.com/harfbuzz/harfbuzz/archive/2.7.4.zip", + "filename": "harfbuzz-2.7.4.zip", + "dir": "harfbuzz-2.7.4", "build": [ cmd_cmake("-DHB_HAVE_FREETYPE:BOOL=TRUE"), cmd_nmake(target="clean"), From fdce8453645c95c347660887077de87fa6650571 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 27 Dec 2020 15:36:16 +1100 Subject: [PATCH 130/186] Added exception explaining that _repr_png_ saves to PNG --- Tests/test_file_png.py | 6 ++++++ src/PIL/Image.py | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py index 80305c7b4..9028aaf23 100644 --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -537,6 +537,12 @@ class TestFilePng: assert repr_png.format == "PNG" assert_image_equal(im, repr_png) + def test_repr_png_error(self): + im = hopper("F") + + with pytest.raises(ValueError): + im._repr_png_() + def test_chunk_order(self, tmp_path): with Image.open("Tests/images/icc_profile.png") as im: test_file = str(tmp_path / "temp.png") diff --git a/src/PIL/Image.py b/src/PIL/Image.py index ae2559d11..e9d4e4f29 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -670,7 +670,10 @@ class Image: :returns: png version of the image as bytes """ b = io.BytesIO() - self.save(b, "PNG") + try: + self.save(b, "PNG") + except Exception as e: + raise ValueError("Could not save to PNG for display") from e return b.getvalue() @property From 00df94bb7819c6b26aa53cd6ece701725d7e6809 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 27 Dec 2020 16:16:55 +1100 Subject: [PATCH 131/186] Removed unused variable --- src/_imagingft.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/_imagingft.c b/src/_imagingft.c index 183cfb23e..5566ee3da 100644 --- a/src/_imagingft.c +++ b/src/_imagingft.c @@ -877,7 +877,6 @@ font_render(FontObject* self, PyObject* args) unsigned char convert_scale; /* scale factor for non-8bpp bitmaps */ Imaging im; Py_ssize_t id; - int horizontal_dir; /* is primary axis horizontal? */ int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */ int color = 0; /* is FT_LOAD_COLOR enabled? */ int stroke_width = 0; @@ -897,8 +896,6 @@ font_render(FontObject* self, PyObject* args) return NULL; } - horizontal_dir = dir && strcmp(dir, "ttb") == 0 ? 0 : 1; - mask = mode && strcmp(mode, "1") == 0; color = mode && strcmp(mode, "RGBA") == 0; From d96945b7c8e4287fb5dc3330ee0ba980642eae87 Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Sat, 26 Dec 2020 19:07:16 +0100 Subject: [PATCH 132/186] Fix Out of bounds read when saving GIF of xsize=1 --- Tests/test_file_gif.py | 8 ++++---- src/libImaging/GifEncode.c | 7 +++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py index 90943ac8f..198e1b162 100644 --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -74,10 +74,10 @@ def test_optimize(): im.save(test_file, "GIF", optimize=optimize) return len(test_file.getvalue()) - assert test_grayscale(0) == 800 - assert test_grayscale(1) == 44 - assert test_bilevel(0) == 800 - assert test_bilevel(1) == 800 + assert test_grayscale(0) == 799 + assert test_grayscale(1) == 43 + assert test_bilevel(0) == 799 + assert test_bilevel(1) == 799 def test_optimize_correctness(): diff --git a/src/libImaging/GifEncode.c b/src/libImaging/GifEncode.c index e9c6c3149..9f22add24 100644 --- a/src/libImaging/GifEncode.c +++ b/src/libImaging/GifEncode.c @@ -233,6 +233,13 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) } } + /* Potential special case for xsize==1 */ + if (state->x < state->xsize) { + this = state->buffer[state->x++]; + } else { + EMIT_RUN(label0); + break; + } this = state->buffer[state->x++]; From a39d7c4fcf2f114c643112506a412cf195da0535 Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Sun, 27 Dec 2020 17:04:45 +0100 Subject: [PATCH 133/186] Fix OOB Read in tif_dirinfo.c ==3330== at 0xBD4110C: _TIFFSetupFields (tif_dirinfo.c:327) Passing in a stack allocated array is going to fail, as a reference is retained to the name and used later when flushing the Tiff to the file. --- src/libImaging/TiffDecode.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c index bdb524bec..f33cbc6bd 100644 --- a/src/libImaging/TiffDecode.c +++ b/src/libImaging/TiffDecode.c @@ -573,7 +573,6 @@ int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { int ImagingLibTiffMergeFieldInfo(ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length){ // Refer to libtiff docs (http://www.simplesystems.org/libtiff/addingtags.html) TIFFSTATE *clientstate = (TIFFSTATE *)state->context; - char field_name[10]; uint32 n; int status = 0; @@ -586,7 +585,7 @@ int ImagingLibTiffMergeFieldInfo(ImagingCodecState state, TIFFDataType field_typ int passcount = 0; TIFFFieldInfo info[] = { - { key, readcount, writecount, field_type, FIELD_CUSTOM, 1, passcount, field_name } + { key, readcount, writecount, field_type, FIELD_CUSTOM, 1, passcount, "CustomField" } }; if (is_var_length) { From c68ddcf87d3efe0fe2dd98ae5c0f9f22ab613251 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 29 Dec 2020 10:44:32 +1100 Subject: [PATCH 134/186] Updated openjpeg to 2.4.0 --- depends/install_openjpeg.sh | 2 +- docs/installation.rst | 2 +- winbuild/build_prepare.py | 10 +++++----- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/depends/install_openjpeg.sh b/depends/install_openjpeg.sh index a93498282..7321b80f0 100755 --- a/depends/install_openjpeg.sh +++ b/depends/install_openjpeg.sh @@ -1,7 +1,7 @@ #!/bin/bash # install openjpeg -archive=openjpeg-2.3.1 +archive=openjpeg-2.4.0 ./download-and-extract.sh $archive https://raw.githubusercontent.com/python-pillow/pillow-depends/master/$archive.tar.gz diff --git a/docs/installation.rst b/docs/installation.rst index 2f97d9f39..b358c18c4 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -171,7 +171,7 @@ Many of Pillow's features require external libraries: * **openjpeg** provides JPEG 2000 functionality. - * Pillow has been tested with openjpeg **2.0.0**, **2.1.0** and **2.3.1**. + * Pillow has been tested with openjpeg **2.0.0**, **2.1.0**, **2.3.1** and **2.4.0**. * Pillow does **not** support the earlier **1.5** series which ships with Debian Jessie. diff --git a/winbuild/build_prepare.py b/winbuild/build_prepare.py index 324f91cd9..fb52cb4ce 100644 --- a/winbuild/build_prepare.py +++ b/winbuild/build_prepare.py @@ -242,15 +242,15 @@ deps = { "libs": [r"Lib\MS\*.lib"], }, "openjpeg": { - "url": "https://github.com/uclouvain/openjpeg/archive/v2.3.1.tar.gz", - "filename": "openjpeg-2.3.1.tar.gz", - "dir": "openjpeg-2.3.1", + "url": "https://github.com/uclouvain/openjpeg/archive/v2.4.0.tar.gz", + "filename": "openjpeg-2.4.0.tar.gz", + "dir": "openjpeg-2.4.0", "build": [ cmd_cmake(("-DBUILD_THIRDPARTY:BOOL=OFF", "-DBUILD_SHARED_LIBS:BOOL=OFF")), cmd_nmake(target="clean"), cmd_nmake(target="openjp2"), - cmd_mkdir(r"{inc_dir}\openjpeg-2.3.1"), - cmd_copy(r"src\lib\openjp2\*.h", r"{inc_dir}\openjpeg-2.3.1"), + cmd_mkdir(r"{inc_dir}\openjpeg-2.4.0"), + cmd_copy(r"src\lib\openjp2\*.h", r"{inc_dir}\openjpeg-2.4.0"), ], "libs": [r"bin\*.lib"], }, From 8f1111472b8ab40dfe1b7397e3295f7518b6faf8 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 29 Dec 2020 11:32:10 +1100 Subject: [PATCH 135/186] OpenJPEG has been updated in pillow-wheels [ci skip] --- docs/releasenotes/8.1.0.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index 2284b22a5..f4eeabdeb 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -39,7 +39,8 @@ already exists for the ICNS format. Security ======== -TODO +OpenJPEG in the macOS and Linux wheels has been updated from 2.3.1 to 2.4.0, resolving +security problems present in the earlier version of that dependency. Other Changes ============= From 387ac3d7048c8acfa70db2f87a18b93b89b1bf12 Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Tue, 29 Dec 2020 19:08:04 +1100 Subject: [PATCH 136/186] Simplified wording [ci skip] Co-authored-by: Hugo van Kemenade --- docs/releasenotes/8.1.0.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index f4eeabdeb..976fa482a 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -39,8 +39,7 @@ already exists for the ICNS format. Security ======== -OpenJPEG in the macOS and Linux wheels has been updated from 2.3.1 to 2.4.0, resolving -security problems present in the earlier version of that dependency. +OpenJPEG in the macOS and Linux wheels has been updated from 2.3.1 to 2.4.0, including security fixes. Other Changes ============= From 28fbc6bcd0623813f03970ebc13fd358ad51b361 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 29 Dec 2020 20:03:45 +1100 Subject: [PATCH 137/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 6b733cac4..00014753b 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,9 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Fix OOB Read when writing TIFF with custom Metadata #5148 + [wiredfool] + - Added append_images support for ICO #4568 [ziplantil, radarhere] From 1892b2339f3d20cf4c8c92ec8fb1f1663e37cb3a Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 29 Dec 2020 21:20:26 +1100 Subject: [PATCH 138/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 00014753b..12e01ca35 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,9 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Allow putpalette to accept 1024 integers to include alpha values #5089 + [radarhere] + - Fix OOB Read when writing TIFF with custom Metadata #5148 [wiredfool] From 143a77d8e219274bece890be08f6ba104c15e47e Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 29 Dec 2020 21:29:22 +1100 Subject: [PATCH 139/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 12e01ca35..691a7a220 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,9 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Use previous disposal method in GIF load_end #5125 + [radarhere] + - Allow putpalette to accept 1024 integers to include alpha values #5089 [radarhere] From 8dd5913428d96cc454d152e9431fa150d1952960 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 30 Dec 2020 11:34:46 +1100 Subject: [PATCH 140/186] Updated libtiff to 4.2.0 --- winbuild/build_prepare.py | 6 +++--- winbuild/tiff.opt | 4 ++++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/winbuild/build_prepare.py b/winbuild/build_prepare.py index fb52cb4ce..2531d5504 100644 --- a/winbuild/build_prepare.py +++ b/winbuild/build_prepare.py @@ -141,9 +141,9 @@ deps = { "libs": [r"*.lib"], }, "libtiff": { - "url": "https://download.osgeo.org/libtiff/tiff-4.1.0.tar.gz", - "filename": "tiff-4.1.0.tar.gz", - "dir": "tiff-4.1.0", + "url": "https://download.osgeo.org/libtiff/tiff-4.2.0.tar.gz", + "filename": "tiff-4.2.0.tar.gz", + "dir": "tiff-4.2.0", "build": [ cmd_copy(r"{winbuild_dir}\tiff.opt", "nmake.opt"), cmd_nmake("makefile.vc", "clean"), diff --git a/winbuild/tiff.opt b/winbuild/tiff.opt index 16acabc26..d82c51678 100644 --- a/winbuild/tiff.opt +++ b/winbuild/tiff.opt @@ -66,6 +66,10 @@ ZIP_SUPPORT = 1 ZLIB_INCLUDE = -I$(INCLIB) ZLIB_LIB = $(INCLIB)/zlib.lib +# Indicate if the compiler provides strtoll/strtoull (default 1) +# Users of MSVC++ 14.0 ("Visual Studio 2015") and later should set this to 1 +HAVE_STRTOLL = 1 + # # Uncomment and edit following lines to enable ISO JBIG support # From 6b21a96578442cb0a4a806eb0b7f9de6682fcd04 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 30 Dec 2020 11:57:05 +1100 Subject: [PATCH 141/186] Changed readcount so that _TIFFSetGetType can identify the type --- src/libImaging/TiffDecode.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c index f33cbc6bd..d86a42915 100644 --- a/src/libImaging/TiffDecode.c +++ b/src/libImaging/TiffDecode.c @@ -378,7 +378,7 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ TIFFClose(tiff); return -1; } - + state->bytes = row_byte_size * tile_length; if (TIFFTileSize(tiff) > state->bytes) { @@ -578,7 +578,7 @@ int ImagingLibTiffMergeFieldInfo(ImagingCodecState state, TIFFDataType field_typ // custom fields added with ImagingLibTiffMergeFieldInfo are only used for // decoding, ignore readcount; - int readcount = 0; + int readcount = 1; // we support writing a single value, or a variable number of values int writecount = 1; // whether the first value should encode the number of values. From 4056bf529e12744d50f9eeb19b48bb75e7789d2e Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 30 Dec 2020 12:43:13 +1100 Subject: [PATCH 142/186] Document #5148 [ci skip] --- docs/releasenotes/8.1.0.rst | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index 976fa482a..79ed507f4 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -39,7 +39,14 @@ already exists for the ICNS format. Security ======== -OpenJPEG in the macOS and Linux wheels has been updated from 2.3.1 to 2.4.0, including security fixes. +An out-of-bounds read when saving TIFFs with custom metadata through libtiff has been +fixed. + +Dependencies +^^^^^^^^^^^^ + +OpenJPEG in the macOS and Linux wheels has been updated from 2.3.1 to 2.4.0, including +security fixes. Other Changes ============= From 3757b8c7485f9d804f4a96772384543b4fe59121 Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 8 May 2020 19:48:02 +0300 Subject: [PATCH 143/186] remove extra i8 calls where input is proved bytes[] or int --- src/PIL/BmpImagePlugin.py | 3 +-- src/PIL/CurImagePlugin.py | 3 +-- src/PIL/FliImagePlugin.py | 11 +++++------ src/PIL/FpxImagePlugin.py | 5 ++--- src/PIL/GdImageFile.py | 3 +-- src/PIL/GifImagePlugin.py | 29 ++++++++++++++--------------- src/PIL/GribStubImagePlugin.py | 3 +-- src/PIL/IcnsImagePlugin.py | 3 +-- src/PIL/IcoImagePlugin.py | 9 ++++----- src/PIL/ImImagePlugin.py | 7 +++---- src/PIL/Image.py | 4 ++-- src/PIL/IptcImagePlugin.py | 6 +++--- src/PIL/JpegImagePlugin.py | 19 +++++++++---------- src/PIL/MspImagePlugin.py | 3 +-- src/PIL/PcdImagePlugin.py | 3 +-- src/PIL/PcxImagePlugin.py | 11 +++++------ src/PIL/PngImagePlugin.py | 25 ++++++++++++------------- src/PIL/SgiImagePlugin.py | 5 ++--- src/PIL/TgaImagePlugin.py | 11 +++++------ src/PIL/TiffImagePlugin.py | 4 ++-- src/PIL/XVThumbImagePlugin.py | 4 ++-- src/PIL/XpmImagePlugin.py | 4 ++-- 22 files changed, 79 insertions(+), 96 deletions(-) diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py index 1bcbe93b2..fa096b89b 100644 --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -25,7 +25,6 @@ from . import Image, ImageFile, ImagePalette -from ._binary import i8 from ._binary import i16le as i16 from ._binary import i32le as i32 from ._binary import o8 @@ -97,7 +96,7 @@ class BmpImageFile(ImageFile.ImageFile): # --------------------------------------------- Windows Bitmap v2 to v5 # v3, OS/2 v2, v4, v5 elif file_info["header_size"] in (40, 64, 108, 124): - file_info["y_flip"] = i8(header_data[7]) == 0xFF + file_info["y_flip"] = header_data[7] == 0xFF file_info["direction"] = 1 if file_info["y_flip"] else -1 file_info["width"] = i32(header_data[0:4]) file_info["height"] = ( diff --git a/src/PIL/CurImagePlugin.py b/src/PIL/CurImagePlugin.py index 35123f789..8451fe90f 100644 --- a/src/PIL/CurImagePlugin.py +++ b/src/PIL/CurImagePlugin.py @@ -16,7 +16,6 @@ # See the README file for information on usage and redistribution. # from . import BmpImagePlugin, Image -from ._binary import i8 from ._binary import i16le as i16 from ._binary import i32le as i32 @@ -52,7 +51,7 @@ class CurImageFile(BmpImagePlugin.BmpImageFile): s = self.fp.read(16) if not m: m = s - elif i8(s[0]) > i8(m[0]) and i8(s[1]) > i8(m[1]): + elif s[0] > m[0] and s[1] > m[1]: m = s if not m: raise TypeError("No cursors were found") diff --git a/src/PIL/FliImagePlugin.py b/src/PIL/FliImagePlugin.py index 3c88d53af..5a3247024 100644 --- a/src/PIL/FliImagePlugin.py +++ b/src/PIL/FliImagePlugin.py @@ -17,7 +17,6 @@ from . import Image, ImageFile, ImagePalette -from ._binary import i8 from ._binary import i16le as i16 from ._binary import i32le as i32 from ._binary import o8 @@ -102,15 +101,15 @@ class FliImageFile(ImageFile.ImageFile): i = 0 for e in range(i16(self.fp.read(2))): s = self.fp.read(2) - i = i + i8(s[0]) - n = i8(s[1]) + i = i + s[0] + n = s[1] if n == 0: n = 256 s = self.fp.read(n * 3) for n in range(0, len(s), 3): - r = i8(s[n]) << shift - g = i8(s[n + 1]) << shift - b = i8(s[n + 2]) << shift + r = s[n] << shift + g = s[n + 1] << shift + b = s[n + 2] << shift palette[i] = (r, g, b) i += 1 diff --git a/src/PIL/FpxImagePlugin.py b/src/PIL/FpxImagePlugin.py index 14070eebf..5e385469f 100644 --- a/src/PIL/FpxImagePlugin.py +++ b/src/PIL/FpxImagePlugin.py @@ -17,7 +17,6 @@ import olefile from . import Image, ImageFile -from ._binary import i8 from ._binary import i32le as i32 # we map from colour field tuples to (mode, rawmode) descriptors @@ -181,8 +180,8 @@ class FpxImageFile(ImageFile.ImageFile): elif compression == 2: - internal_color_conversion = i8(s[14]) - jpeg_tables = i8(s[15]) + internal_color_conversion = s[14] + jpeg_tables = s[15] rawmode = self.rawmode if internal_color_conversion: diff --git a/src/PIL/GdImageFile.py b/src/PIL/GdImageFile.py index 8561f7b74..986dd063e 100644 --- a/src/PIL/GdImageFile.py +++ b/src/PIL/GdImageFile.py @@ -28,7 +28,6 @@ from . import ImageFile, ImagePalette, UnidentifiedImageError -from ._binary import i8 from ._binary import i16be as i16 from ._binary import i32be as i32 @@ -55,7 +54,7 @@ class GdImageFile(ImageFile.ImageFile): self.mode = "L" # FIXME: "P" self._size = i16(s[2:4]), i16(s[4:6]) - trueColor = i8(s[6]) + trueColor = s[6] trueColorOffset = 2 if trueColor else 0 # transparency index diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py index 95e300bd7..1873e441f 100644 --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -30,7 +30,6 @@ import os import subprocess from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence -from ._binary import i8 from ._binary import i16le as i16 from ._binary import o8 from ._binary import o16le as o16 @@ -58,8 +57,8 @@ class GifImageFile(ImageFile.ImageFile): def data(self): s = self.fp.read(1) - if s and i8(s): - return self.fp.read(i8(s)) + if s and s[0]: + return self.fp.read(s[0]) return None def _open(self): @@ -72,16 +71,16 @@ class GifImageFile(ImageFile.ImageFile): self.info["version"] = s[:6] self._size = i16(s[6:]), i16(s[8:]) self.tile = [] - flags = i8(s[10]) + flags = s[10] bits = (flags & 7) + 1 if flags & 128: # get global palette - self.info["background"] = i8(s[11]) + self.info["background"] = s[11] # check if palette contains colour indices p = self.fp.read(3 << bits) for i in range(0, len(p), 3): - if not (i // 3 == i8(p[i]) == i8(p[i + 1]) == i8(p[i + 2])): + if not (i // 3 == p[i] == p[i + 1] == p[i + 2]): p = ImagePalette.raw("RGB", p) self.global_palette = self.palette = p break @@ -187,13 +186,13 @@ class GifImageFile(ImageFile.ImageFile): # s = self.fp.read(1) block = self.data() - if i8(s) == 249: + if s[0] == 249: # # graphic control extension # - flags = i8(block[0]) + flags = block[0] if flags & 1: - info["transparency"] = i8(block[3]) + info["transparency"] = block[3] info["duration"] = i16(block[1:3]) * 10 # disposal method - find the value of bits 4 - 6 @@ -205,7 +204,7 @@ class GifImageFile(ImageFile.ImageFile): # correct, but it seems to prevent the last # frame from looking odd for some animations self.disposal_method = dispose_bits - elif i8(s) == 254: + elif s[0] == 254: # # comment extension # @@ -216,14 +215,14 @@ class GifImageFile(ImageFile.ImageFile): info["comment"] = block block = self.data() continue - elif i8(s) == 255: + elif s[0] == 255: # # application extension # info["extension"] = block, self.fp.tell() if block[:11] == b"NETSCAPE2.0": block = self.data() - if len(block) >= 3 and i8(block[0]) == 1: + if len(block) >= 3 and block[0] == 1: info["loop"] = i16(block[1:3]) while self.data(): pass @@ -240,7 +239,7 @@ class GifImageFile(ImageFile.ImageFile): if x1 > self.size[0] or y1 > self.size[1]: self._size = max(x1, self.size[0]), max(y1, self.size[1]) self.dispose_extent = x0, y0, x1, y1 - flags = i8(s[8]) + flags = s[8] interlace = (flags & 64) != 0 @@ -249,7 +248,7 @@ class GifImageFile(ImageFile.ImageFile): self.palette = ImagePalette.raw("RGB", self.fp.read(3 << bits)) # image data - bits = i8(self.fp.read(1)) + bits = self.fp.read(1)[0] self.__offset = self.fp.tell() self.tile = [ ("gif", (x0, y0, x1, y1), self.__offset, (bits, interlace)) @@ -258,7 +257,7 @@ class GifImageFile(ImageFile.ImageFile): else: pass - # raise OSError, "illegal GIF tag `%x`" % i8(s) + # raise OSError, "illegal GIF tag `%x`" % s[0] try: if self.disposal_method < 2: diff --git a/src/PIL/GribStubImagePlugin.py b/src/PIL/GribStubImagePlugin.py index 515c272f7..b9bdd16e3 100644 --- a/src/PIL/GribStubImagePlugin.py +++ b/src/PIL/GribStubImagePlugin.py @@ -10,7 +10,6 @@ # from . import Image, ImageFile -from ._binary import i8 _handler = None @@ -30,7 +29,7 @@ def register_handler(handler): def _accept(prefix): - return prefix[0:4] == b"GRIB" and i8(prefix[7]) == 1 + return prefix[0:4] == b"GRIB" and prefix[7] == 1 class GribStubImageFile(ImageFile.StubImageFile): diff --git a/src/PIL/IcnsImagePlugin.py b/src/PIL/IcnsImagePlugin.py index b9b1ae007..2a63d75cb 100644 --- a/src/PIL/IcnsImagePlugin.py +++ b/src/PIL/IcnsImagePlugin.py @@ -24,7 +24,6 @@ import sys import tempfile from PIL import Image, ImageFile, PngImagePlugin, features -from PIL._binary import i8 enable_jpeg2k = features.check_codec("jpg_2000") if enable_jpeg2k: @@ -70,7 +69,7 @@ def read_32(fobj, start_length, size): byte = fobj.read(1) if not byte: break - byte = i8(byte) + byte = byte[0] if byte & 0x80: blocksize = byte - 125 byte = fobj.read(1) diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py index 8b456d502..7dff008ed 100644 --- a/src/PIL/IcoImagePlugin.py +++ b/src/PIL/IcoImagePlugin.py @@ -28,7 +28,6 @@ from io import BytesIO from math import ceil, log from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin -from ._binary import i8 from ._binary import i16le as i16 from ._binary import i32le as i32 @@ -110,10 +109,10 @@ class IcoFile: s = buf.read(16) icon_header = { - "width": i8(s[0]), - "height": i8(s[1]), - "nb_color": i8(s[2]), # No. of colors in image (0 if >=8bpp) - "reserved": i8(s[3]), + "width": s[0], + "height": s[1], + "nb_color": s[2], # No. of colors in image (0 if >=8bpp) + "reserved": s[3], "planes": i16(s[4:]), "bpp": i16(s[6:]), "size": i32(s[8:]), diff --git a/src/PIL/ImImagePlugin.py b/src/PIL/ImImagePlugin.py index 8ef474171..1dfc808c4 100644 --- a/src/PIL/ImImagePlugin.py +++ b/src/PIL/ImImagePlugin.py @@ -30,7 +30,6 @@ import os import re from . import Image, ImageFile, ImagePalette -from ._binary import i8 # -------------------------------------------------------------------- # Standard tags @@ -223,14 +222,14 @@ class ImImageFile(ImageFile.ImageFile): linear = 1 # linear greyscale palette for i in range(256): if palette[i] == palette[i + 256] == palette[i + 512]: - if i8(palette[i]) != i: + if palette[i] != i: linear = 0 else: greyscale = 0 if self.mode in ["L", "LA", "P", "PA"]: if greyscale: if not linear: - self.lut = [i8(c) for c in palette[:256]] + self.lut = list(palette[:256]) else: if self.mode in ["L", "P"]: self.mode = self.rawmode = "P" @@ -240,7 +239,7 @@ class ImImageFile(ImageFile.ImageFile): self.palette = ImagePalette.raw("RGB;L", palette) elif self.mode == "RGB": if not greyscale or not linear: - self.lut = [i8(c) for c in palette] + self.lut = list(palette) self.frame = 0 diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 1b4efdc4f..815c0f659 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -50,7 +50,7 @@ from . import ( _plugins, _raise_version_warning, ) -from ._binary import i8, i32le +from ._binary import i32le from ._util import deferred_error, isPath if sys.version_info >= (3, 7): @@ -1378,7 +1378,7 @@ class Image: self.load() x, y = self.im.getprojection() - return [i8(c) for c in x], [i8(c) for c in y] + return list(x), list(y) def histogram(self, mask=None, extrema=None): """ diff --git a/src/PIL/IptcImagePlugin.py b/src/PIL/IptcImagePlugin.py index f407b7e5f..932601adc 100644 --- a/src/PIL/IptcImagePlugin.py +++ b/src/PIL/IptcImagePlugin.py @@ -62,14 +62,14 @@ class IptcImageFile(ImageFile.ImageFile): if not len(s): return None, 0 - tag = i8(s[1]), i8(s[2]) + tag = s[1], s[2] # syntax - if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9: + if s[0] != 0x1C or tag[0] < 1 or tag[0] > 9: raise SyntaxError("invalid IPTC/NAA file") # field size - size = i8(s[3]) + size = s[3] if size > 132: raise OSError("illegal field length in IPTC/NAA file") elif size == 128: diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py index 29bc61aa8..be917e01e 100644 --- a/src/PIL/JpegImagePlugin.py +++ b/src/PIL/JpegImagePlugin.py @@ -41,7 +41,6 @@ import tempfile import warnings from . import Image, ImageFile, TiffImagePlugin -from ._binary import i8 from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 @@ -75,7 +74,7 @@ def APP(self, marker): self.info["jfif_version"] = divmod(version, 256) # extract JFIF properties try: - jfif_unit = i8(s[7]) + jfif_unit = s[7] jfif_density = i16(s, 8), i16(s, 10) except Exception: pass @@ -115,7 +114,7 @@ def APP(self, marker): code = i16(s, offset) offset += 2 # resource name (usually empty) - name_len = i8(s[offset]) + name_len = s[offset] # name = s[offset+1:offset+1+name_len] offset += 1 + name_len offset += offset & 1 # align @@ -140,7 +139,7 @@ def APP(self, marker): self.info["adobe"] = i16(s, 5) # extract Adobe custom properties try: - adobe_transform = i8(s[1]) + adobe_transform = s[1] except Exception: pass else: @@ -197,11 +196,11 @@ def SOF(self, marker): s = ImageFile._safe_read(self.fp, n) self._size = i16(s[3:]), i16(s[1:]) - self.bits = i8(s[0]) + self.bits = s[0] if self.bits != 8: raise SyntaxError(f"cannot handle {self.bits}-bit layers") - self.layers = i8(s[5]) + self.layers = s[5] if self.layers == 1: self.mode = "L" elif self.layers == 3: @@ -217,7 +216,7 @@ def SOF(self, marker): if self.icclist: # fixup icc profile self.icclist.sort() # sort by sequence number - if i8(self.icclist[0][13]) == len(self.icclist): + if self.icclist[0][13] == len(self.icclist): profile = [] for p in self.icclist: profile.append(p[14:]) @@ -230,7 +229,7 @@ def SOF(self, marker): for i in range(6, len(s), 3): t = s[i : i + 3] # 4-tuples: id, vsamp, hsamp, qtable - self.layer.append((t[0], i8(t[1]) // 16, i8(t[1]) & 15, i8(t[2]))) + self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2])) def DQT(self, marker): @@ -244,7 +243,7 @@ def DQT(self, marker): n = i16(self.fp.read(2)) - 2 s = ImageFile._safe_read(self.fp, n) while len(s): - v = i8(s[0]) + v = s[0] precision = 1 if (v // 16 == 0) else 2 # in bytes qt_length = 1 + precision * 64 if len(s) < qt_length: @@ -362,7 +361,7 @@ class JpegImageFile(ImageFile.ImageFile): while True: - i = i8(s) + i = s[0] if i == 0xFF: s = s + self.fp.read(1) i = i16(s) diff --git a/src/PIL/MspImagePlugin.py b/src/PIL/MspImagePlugin.py index 9dd6e9f32..95190a944 100644 --- a/src/PIL/MspImagePlugin.py +++ b/src/PIL/MspImagePlugin.py @@ -27,7 +27,6 @@ import io import struct from . import Image, ImageFile -from ._binary import i8 from ._binary import i16le as i16 from ._binary import o16le as o16 @@ -133,7 +132,7 @@ class MspDecoder(ImageFile.PyDecoder): ) idx = 0 while idx < rowlen: - runtype = i8(row[idx]) + runtype = row[idx] idx += 1 if runtype == 0: (runcount, runval) = struct.unpack_from("Bc", row, idx) diff --git a/src/PIL/PcdImagePlugin.py b/src/PIL/PcdImagePlugin.py index 625f55646..38caf5c63 100644 --- a/src/PIL/PcdImagePlugin.py +++ b/src/PIL/PcdImagePlugin.py @@ -16,7 +16,6 @@ from . import Image, ImageFile -from ._binary import i8 ## # Image plugin for PhotoCD images. This plugin only reads the 768x512 @@ -38,7 +37,7 @@ class PcdImageFile(ImageFile.ImageFile): if s[:4] != b"PCD_": raise SyntaxError("not a PCD file") - orientation = i8(s[1538]) & 3 + orientation = s[1538] & 3 self.tile_post_rotate = None if orientation == 1: self.tile_post_rotate = 90 diff --git a/src/PIL/PcxImagePlugin.py b/src/PIL/PcxImagePlugin.py index 767f9945a..b337b7dde 100644 --- a/src/PIL/PcxImagePlugin.py +++ b/src/PIL/PcxImagePlugin.py @@ -29,7 +29,6 @@ import io import logging from . import Image, ImageFile, ImagePalette -from ._binary import i8 from ._binary import i16le as i16 from ._binary import o8 from ._binary import o16le as o16 @@ -38,7 +37,7 @@ logger = logging.getLogger(__name__) def _accept(prefix): - return i8(prefix[0]) == 10 and i8(prefix[1]) in [0, 2, 3, 5] + return prefix[0] == 10 and prefix[1] in [0, 2, 3, 5] ## @@ -64,9 +63,9 @@ class PcxImageFile(ImageFile.ImageFile): logger.debug("BBox: %s %s %s %s", *bbox) # format - version = i8(s[1]) - bits = i8(s[3]) - planes = i8(s[65]) + version = s[1] + bits = s[3] + planes = s[65] stride = i16(s, 66) logger.debug( "PCX version %s, bits %s, planes %s, stride %s", @@ -91,7 +90,7 @@ class PcxImageFile(ImageFile.ImageFile): # FIXME: hey, this doesn't work with the incremental loader !!! self.fp.seek(-769, io.SEEK_END) s = self.fp.read(769) - if len(s) == 769 and i8(s[0]) == 12: + if len(s) == 769 and s[0] == 12: # check if the palette is linear greyscale for i in range(256): if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3: diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py index 6af41af6e..fd7ef712f 100644 --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -39,7 +39,6 @@ import warnings import zlib from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence -from ._binary import i8 from ._binary import i16be as i16 from ._binary import i32be as i32 from ._binary import o8 @@ -193,7 +192,7 @@ class ChunkStream: # Skip CRC checks for ancillary chunks if allowed to load truncated # images # 5th byte of first char is 1 [specs, section 5.4] - if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1): + if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1): self.crc_skip(cid, data) return @@ -390,8 +389,8 @@ class PngStream(ChunkStream): # Compressed profile n bytes (zlib with deflate compression) i = s.find(b"\0") logger.debug("iCCP profile name %r", s[:i]) - logger.debug("Compression method %s", i8(s[i])) - comp_method = i8(s[i]) + logger.debug("Compression method %s", s[i]) + comp_method = s[i] if comp_method != 0: raise SyntaxError(f"Unknown compression method {comp_method} in iCCP chunk") try: @@ -412,12 +411,12 @@ class PngStream(ChunkStream): s = ImageFile._safe_read(self.fp, length) self.im_size = i32(s), i32(s[4:]) try: - self.im_mode, self.im_rawmode = _MODES[(i8(s[8]), i8(s[9]))] + self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])] except Exception: pass - if i8(s[12]): + if s[12]: self.im_info["interlace"] = 1 - if i8(s[11]): + if s[11]: raise SyntaxError("unknown filter category") return s @@ -491,7 +490,7 @@ class PngStream(ChunkStream): # 3 absolute colorimetric s = ImageFile._safe_read(self.fp, length) - self.im_info["srgb"] = i8(s) + self.im_info["srgb"] = s[0] return s def chunk_pHYs(self, pos, length): @@ -499,7 +498,7 @@ class PngStream(ChunkStream): # pixels per unit s = ImageFile._safe_read(self.fp, length) px, py = i32(s), i32(s[4:]) - unit = i8(s[8]) + unit = s[8] if unit == 1: # meter dpi = int(px * 0.0254 + 0.5), int(py * 0.0254 + 0.5) self.im_info["dpi"] = dpi @@ -537,7 +536,7 @@ class PngStream(ChunkStream): k = s v = b"" if v: - comp_method = i8(v[0]) + comp_method = v[0] else: comp_method = 0 if comp_method != 0: @@ -571,7 +570,7 @@ class PngStream(ChunkStream): return s if len(r) < 2: return s - cf, cm, r = i8(r[0]), i8(r[1]), r[2:] + cf, cm, r = r[0], r[1], r[2:] try: lang, tk, v = r.split(b"\0", 2) except ValueError: @@ -641,8 +640,8 @@ class PngStream(ChunkStream): if delay_den == 0: delay_den = 100 self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000 - self.im_info["disposal"] = i8(s[24]) - self.im_info["blend"] = i8(s[25]) + self.im_info["disposal"] = s[24] + self.im_info["blend"] = s[25] return s def chunk_fdAT(self, pos, length): diff --git a/src/PIL/SgiImagePlugin.py b/src/PIL/SgiImagePlugin.py index f878fefa9..58a62fa5d 100644 --- a/src/PIL/SgiImagePlugin.py +++ b/src/PIL/SgiImagePlugin.py @@ -26,7 +26,6 @@ import os import struct from . import Image, ImageFile -from ._binary import i8 from ._binary import i16be as i16 from ._binary import o8 @@ -64,10 +63,10 @@ class SgiImageFile(ImageFile.ImageFile): raise ValueError("Not an SGI image file") # compression : verbatim or RLE - compression = i8(s[2]) + compression = s[2] # bpc : 1 or 2 bytes (8bits or 16bits) - bpc = i8(s[3]) + bpc = s[3] # dimension : 1, 2 or 3 (depending on xsize, ysize and zsize) dimension = i16(s[4:]) diff --git a/src/PIL/TgaImagePlugin.py b/src/PIL/TgaImagePlugin.py index 69b3e0678..2ebe5d349 100644 --- a/src/PIL/TgaImagePlugin.py +++ b/src/PIL/TgaImagePlugin.py @@ -20,7 +20,6 @@ import warnings from . import Image, ImageFile, ImagePalette -from ._binary import i8 from ._binary import i16le as i16 from ._binary import o8 from ._binary import o16le as o16 @@ -56,14 +55,14 @@ class TgaImageFile(ImageFile.ImageFile): # process header s = self.fp.read(18) - id_len = i8(s[0]) + id_len = s[0] - colormaptype = i8(s[1]) - imagetype = i8(s[2]) + colormaptype = s[1] + imagetype = s[2] - depth = i8(s[16]) + depth = s[16] - flags = i8(s[17]) + flags = s[17] self._size = i16(s[12:]), i16(s[14:]) diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index 5480fcd85..0b70ce382 100644 --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -49,7 +49,7 @@ from fractions import Fraction from numbers import Number, Rational from . import Image, ImageFile, ImagePalette, TiffTags -from ._binary import i8, o8 +from ._binary import o8 from .TiffTags import TYPES logger = logging.getLogger(__name__) @@ -1518,7 +1518,7 @@ def _save(im, fp, filename): if im.mode in ["P", "PA"]: lut = im.im.getpalette("RGB", "RGB;L") - ifd[COLORMAP] = tuple(i8(v) * 256 for v in lut) + ifd[COLORMAP] = tuple(v * 256 for v in lut) # data orientation stride = len(bits) * ((im.size[0] * bits[0] + 7) // 8) ifd[ROWSPERSTRIP] = im.size[1] diff --git a/src/PIL/XVThumbImagePlugin.py b/src/PIL/XVThumbImagePlugin.py index c0d8db09a..4efedb77e 100644 --- a/src/PIL/XVThumbImagePlugin.py +++ b/src/PIL/XVThumbImagePlugin.py @@ -18,7 +18,7 @@ # from . import Image, ImageFile, ImagePalette -from ._binary import i8, o8 +from ._binary import o8 _MAGIC = b"P7 332" @@ -59,7 +59,7 @@ class XVThumbImageFile(ImageFile.ImageFile): s = self.fp.readline() if not s: raise SyntaxError("Unexpected EOF reading XV thumbnail file") - if i8(s[0]) != 35: # ie. when not a comment: '#' + if s[0] != 35: # ie. when not a comment: '#' break # parse header line (already read) diff --git a/src/PIL/XpmImagePlugin.py b/src/PIL/XpmImagePlugin.py index d8bd00a1b..ebd65ba58 100644 --- a/src/PIL/XpmImagePlugin.py +++ b/src/PIL/XpmImagePlugin.py @@ -18,7 +18,7 @@ import re from . import Image, ImageFile, ImagePalette -from ._binary import i8, o8 +from ._binary import o8 # XPM header xpm_head = re.compile(b'"([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)') @@ -72,7 +72,7 @@ class XpmImageFile(ImageFile.ImageFile): elif s[-1:] in b"\r\n": s = s[:-1] - c = i8(s[1]) + c = s[1] s = s[2:-2].split() for i in range(0, len(s), 2): From 1ff61bcaa6f67072a0397ea03b99ff91cb81b2e5 Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 8 May 2020 21:11:58 +0300 Subject: [PATCH 144/186] use offset for all binary input functions instead of slicing --- src/PIL/BmpImagePlugin.py | 34 +++++++++++++++++----------------- src/PIL/CurImagePlugin.py | 4 ++-- src/PIL/EpsImagePlugin.py | 6 +++--- src/PIL/FliImagePlugin.py | 20 ++++++++++---------- src/PIL/GbrImagePlugin.py | 2 +- src/PIL/GdImageFile.py | 6 +++--- src/PIL/GifImagePlugin.py | 10 +++++----- src/PIL/IcoImagePlugin.py | 10 +++++----- src/PIL/Image.py | 2 +- src/PIL/IptcImagePlugin.py | 2 +- src/PIL/JpegImagePlugin.py | 10 +++++----- src/PIL/MspImagePlugin.py | 4 ++-- src/PIL/PixarImagePlugin.py | 4 ++-- src/PIL/PngImagePlugin.py | 14 +++++++------- src/PIL/PsdImagePlugin.py | 12 ++++++------ src/PIL/SgiImagePlugin.py | 8 ++++---- src/PIL/SunImagePlugin.py | 12 ++++++------ src/PIL/TgaImagePlugin.py | 4 ++-- 18 files changed, 82 insertions(+), 82 deletions(-) diff --git a/src/PIL/BmpImagePlugin.py b/src/PIL/BmpImagePlugin.py index fa096b89b..98685be0b 100644 --- a/src/PIL/BmpImagePlugin.py +++ b/src/PIL/BmpImagePlugin.py @@ -51,7 +51,7 @@ def _accept(prefix): def _dib_accept(prefix): - return i32(prefix[:4]) in [12, 40, 64, 108, 124] + return i32(prefix) in [12, 40, 64, 108, 124] # ============================================================================= @@ -86,10 +86,10 @@ class BmpImageFile(ImageFile.ImageFile): # -------------------------------------------------- IBM OS/2 Bitmap v1 # ----- This format has different offsets because of width/height types if file_info["header_size"] == 12: - file_info["width"] = i16(header_data[0:2]) - file_info["height"] = i16(header_data[2:4]) - file_info["planes"] = i16(header_data[4:6]) - file_info["bits"] = i16(header_data[6:8]) + file_info["width"] = i16(header_data, 0) + file_info["height"] = i16(header_data, 2) + file_info["planes"] = i16(header_data, 4) + file_info["bits"] = i16(header_data, 6) file_info["compression"] = self.RAW file_info["palette_padding"] = 3 @@ -98,22 +98,22 @@ class BmpImageFile(ImageFile.ImageFile): elif file_info["header_size"] in (40, 64, 108, 124): file_info["y_flip"] = header_data[7] == 0xFF file_info["direction"] = 1 if file_info["y_flip"] else -1 - file_info["width"] = i32(header_data[0:4]) + file_info["width"] = i32(header_data, 0) file_info["height"] = ( - i32(header_data[4:8]) + i32(header_data, 4) if not file_info["y_flip"] - else 2 ** 32 - i32(header_data[4:8]) + else 2 ** 32 - i32(header_data, 4) ) - file_info["planes"] = i16(header_data[8:10]) - file_info["bits"] = i16(header_data[10:12]) - file_info["compression"] = i32(header_data[12:16]) + file_info["planes"] = i16(header_data, 8) + file_info["bits"] = i16(header_data, 10) + file_info["compression"] = i32(header_data, 12) # byte size of pixel data - file_info["data_size"] = i32(header_data[16:20]) + file_info["data_size"] = i32(header_data, 16) file_info["pixels_per_meter"] = ( - i32(header_data[20:24]), - i32(header_data[24:28]), + i32(header_data, 20), + i32(header_data, 24), ) - file_info["colors"] = i32(header_data[28:32]) + file_info["colors"] = i32(header_data, 28) file_info["palette_padding"] = 4 self.info["dpi"] = tuple( int(x / 39.3701 + 0.5) for x in file_info["pixels_per_meter"] @@ -123,7 +123,7 @@ class BmpImageFile(ImageFile.ImageFile): for idx, mask in enumerate( ["r_mask", "g_mask", "b_mask", "a_mask"] ): - file_info[mask] = i32(header_data[36 + idx * 4 : 40 + idx * 4]) + file_info[mask] = i32(header_data, 36 + idx * 4) else: # 40 byte headers only have the three components in the # bitfields masks, ref: @@ -266,7 +266,7 @@ class BmpImageFile(ImageFile.ImageFile): if not _accept(head_data): raise SyntaxError("Not a BMP file") # read the start position of the BMP image data (u32) - offset = i32(head_data[10:14]) + offset = i32(head_data, 10) # load bitmap information (offset=raster info) self._bitmap(offset=offset) diff --git a/src/PIL/CurImagePlugin.py b/src/PIL/CurImagePlugin.py index 8451fe90f..42af5cafc 100644 --- a/src/PIL/CurImagePlugin.py +++ b/src/PIL/CurImagePlugin.py @@ -47,7 +47,7 @@ class CurImageFile(BmpImagePlugin.BmpImageFile): # pick the largest cursor in the file m = b"" - for i in range(i16(s[4:])): + for i in range(i16(s, 4)): s = self.fp.read(16) if not m: m = s @@ -57,7 +57,7 @@ class CurImageFile(BmpImagePlugin.BmpImageFile): raise TypeError("No cursors were found") # load as bitmap - self._bitmap(i32(m[12:]) + offset) + self._bitmap(i32(m, 12) + offset) # patch up the bitmap height self._size = self.size[0], self.size[1] // 2 diff --git a/src/PIL/EpsImagePlugin.py b/src/PIL/EpsImagePlugin.py index ec2329c7e..dc61f48ed 100644 --- a/src/PIL/EpsImagePlugin.py +++ b/src/PIL/EpsImagePlugin.py @@ -312,14 +312,14 @@ class EpsImageFile(ImageFile.ImageFile): fp.seek(0, io.SEEK_END) length = fp.tell() offset = 0 - elif i32(s[0:4]) == 0xC6D3D0C5: + elif i32(s, 0) == 0xC6D3D0C5: # FIX for: Some EPS file not handled correctly / issue #302 # EPS can contain binary data # or start directly with latin coding # more info see: # https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf - offset = i32(s[4:8]) - length = i32(s[8:12]) + offset = i32(s, 4) + length = i32(s, 8) else: raise SyntaxError("not an EPS file") diff --git a/src/PIL/FliImagePlugin.py b/src/PIL/FliImagePlugin.py index 5a3247024..f2d4857f7 100644 --- a/src/PIL/FliImagePlugin.py +++ b/src/PIL/FliImagePlugin.py @@ -26,7 +26,7 @@ from ._binary import o8 def _accept(prefix): - return len(prefix) >= 6 and i16(prefix[4:6]) in [0xAF11, 0xAF12] + return len(prefix) >= 6 and i16(prefix, 4) in [0xAF11, 0xAF12] ## @@ -46,22 +46,22 @@ class FliImageFile(ImageFile.ImageFile): s = self.fp.read(128) if not ( _accept(s) - and i16(s[14:16]) in [0, 3] # flags + and i16(s, 14) in [0, 3] # flags and s[20:22] == b"\x00\x00" # reserved ): raise SyntaxError("not an FLI/FLC file") # frames - self.n_frames = i16(s[6:8]) + self.n_frames = i16(s, 6) self.is_animated = self.n_frames > 1 # image characteristics self.mode = "P" - self._size = i16(s[8:10]), i16(s[10:12]) + self._size = i16(s, 8), i16(s, 10) # animation speed - duration = i32(s[16:20]) - magic = i16(s[4:6]) + duration = i32(s, 16) + magic = i16(s, 4) if magic == 0xAF11: duration = (duration * 1000) // 70 self.info["duration"] = duration @@ -73,17 +73,17 @@ class FliImageFile(ImageFile.ImageFile): self.__offset = 128 - if i16(s[4:6]) == 0xF100: + if i16(s, 4) == 0xF100: # prefix chunk; ignore it self.__offset = self.__offset + i32(s) s = self.fp.read(16) - if i16(s[4:6]) == 0xF1FA: + if i16(s, 4) == 0xF1FA: # look for palette chunk s = self.fp.read(6) - if i16(s[4:6]) == 11: + if i16(s, 4) == 11: self._palette(palette, 2) - elif i16(s[4:6]) == 4: + elif i16(s, 4) == 4: self._palette(palette, 0) palette = [o8(r) + o8(g) + o8(b) for (r, g, b) in palette] diff --git a/src/PIL/GbrImagePlugin.py b/src/PIL/GbrImagePlugin.py index 5e447b411..0f230602d 100644 --- a/src/PIL/GbrImagePlugin.py +++ b/src/PIL/GbrImagePlugin.py @@ -29,7 +29,7 @@ from ._binary import i32be as i32 def _accept(prefix): - return len(prefix) >= 8 and i32(prefix[:4]) >= 20 and i32(prefix[4:8]) in (1, 2) + return len(prefix) >= 8 and i32(prefix, 0) >= 20 and i32(prefix, 4) in (1, 2) ## diff --git a/src/PIL/GdImageFile.py b/src/PIL/GdImageFile.py index 986dd063e..9c34adaa6 100644 --- a/src/PIL/GdImageFile.py +++ b/src/PIL/GdImageFile.py @@ -48,17 +48,17 @@ class GdImageFile(ImageFile.ImageFile): # Header s = self.fp.read(1037) - if not i16(s[:2]) in [65534, 65535]: + if not i16(s) in [65534, 65535]: raise SyntaxError("Not a valid GD 2.x .gd file") self.mode = "L" # FIXME: "P" - self._size = i16(s[2:4]), i16(s[4:6]) + self._size = i16(s, 2), i16(s, 4) trueColor = s[6] trueColorOffset = 2 if trueColor else 0 # transparency index - tindex = i32(s[7 + trueColorOffset : 7 + trueColorOffset + 4]) + tindex = i32(s, 7 + trueColorOffset) if tindex < 256: self.info["transparency"] = tindex diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py index 1873e441f..7c083bd8b 100644 --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -69,7 +69,7 @@ class GifImageFile(ImageFile.ImageFile): raise SyntaxError("not a GIF file") self.info["version"] = s[:6] - self._size = i16(s[6:]), i16(s[8:]) + self._size = i16(s, 6), i16(s, 8) self.tile = [] flags = s[10] bits = (flags & 7) + 1 @@ -193,7 +193,7 @@ class GifImageFile(ImageFile.ImageFile): flags = block[0] if flags & 1: info["transparency"] = block[3] - info["duration"] = i16(block[1:3]) * 10 + info["duration"] = i16(block, 1) * 10 # disposal method - find the value of bits 4 - 6 dispose_bits = 0b00011100 & flags @@ -223,7 +223,7 @@ class GifImageFile(ImageFile.ImageFile): if block[:11] == b"NETSCAPE2.0": block = self.data() if len(block) >= 3 and block[0] == 1: - info["loop"] = i16(block[1:3]) + info["loop"] = i16(block, 1) while self.data(): pass @@ -234,8 +234,8 @@ class GifImageFile(ImageFile.ImageFile): s = self.fp.read(9) # extent - x0, y0 = i16(s[0:]), i16(s[2:]) - x1, y1 = x0 + i16(s[4:]), y0 + i16(s[6:]) + x0, y0 = i16(s, 0), i16(s, 2) + x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6) if x1 > self.size[0] or y1 > self.size[1]: self._size = max(x1, self.size[0]), max(y1, self.size[1]) self.dispose_extent = x0, y0, x1, y1 diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py index 7dff008ed..e1bfa7a59 100644 --- a/src/PIL/IcoImagePlugin.py +++ b/src/PIL/IcoImagePlugin.py @@ -102,7 +102,7 @@ class IcoFile: self.entry = [] # Number of items in file - self.nb_items = i16(s[4:]) + self.nb_items = i16(s, 4) # Get headers for each item for i in range(self.nb_items): @@ -113,10 +113,10 @@ class IcoFile: "height": s[1], "nb_color": s[2], # No. of colors in image (0 if >=8bpp) "reserved": s[3], - "planes": i16(s[4:]), - "bpp": i16(s[6:]), - "size": i32(s[8:]), - "offset": i32(s[12:]), + "planes": i16(s, 4), + "bpp": i16(s, 6), + "size": i32(s, 8), + "offset": i32(s, 12), } # See Wikipedia diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 815c0f659..e2540a2b2 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -3374,7 +3374,7 @@ class Exif(MutableMapping): if self[0x927C][:8] == b"FUJIFILM": exif_data = self[0x927C] - ifd_offset = i32le(exif_data[8:12]) + ifd_offset = i32le(exif_data, 8) ifd_data = exif_data[ifd_offset:] makernote = {} diff --git a/src/PIL/IptcImagePlugin.py b/src/PIL/IptcImagePlugin.py index 932601adc..0bbe50668 100644 --- a/src/PIL/IptcImagePlugin.py +++ b/src/PIL/IptcImagePlugin.py @@ -77,7 +77,7 @@ class IptcImageFile(ImageFile.ImageFile): elif size > 128: size = i(self.fp.read(size - 128)) else: - size = i16(s[3:]) + size = i16(s, 3) return tag, size diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py index be917e01e..054495e6f 100644 --- a/src/PIL/JpegImagePlugin.py +++ b/src/PIL/JpegImagePlugin.py @@ -124,10 +124,10 @@ def APP(self, marker): data = s[offset : offset + size] if code == 0x03ED: # ResolutionInfo data = { - "XResolution": i32(data[:4]) / 65536, - "DisplayedUnitsX": i16(data[4:8]), - "YResolution": i32(data[8:12]) / 65536, - "DisplayedUnitsY": i16(data[12:]), + "XResolution": i32(data, 0) / 65536, + "DisplayedUnitsX": i16(data, 4), + "YResolution": i32(data, 8) / 65536, + "DisplayedUnitsY": i16(data, 12), } photoshop[code] = data offset += size @@ -194,7 +194,7 @@ def SOF(self, marker): n = i16(self.fp.read(2)) - 2 s = ImageFile._safe_read(self.fp, n) - self._size = i16(s[3:]), i16(s[1:]) + self._size = i16(s, 3), i16(s, 1) self.bits = s[0] if self.bits != 8: diff --git a/src/PIL/MspImagePlugin.py b/src/PIL/MspImagePlugin.py index 95190a944..e1fdc1fdf 100644 --- a/src/PIL/MspImagePlugin.py +++ b/src/PIL/MspImagePlugin.py @@ -58,12 +58,12 @@ class MspImageFile(ImageFile.ImageFile): # Header checksum checksum = 0 for i in range(0, 32, 2): - checksum = checksum ^ i16(s[i : i + 2]) + checksum = checksum ^ i16(s, i) if checksum != 0: raise SyntaxError("bad MSP checksum") self.mode = "1" - self._size = i16(s[4:]), i16(s[6:]) + self._size = i16(s, 4), i16(s, 6) if s[:4] == b"DanM": self.tile = [("raw", (0, 0) + self.size, 32, ("1", 0, 1))] diff --git a/src/PIL/PixarImagePlugin.py b/src/PIL/PixarImagePlugin.py index 91f0314b5..c4860b6c4 100644 --- a/src/PIL/PixarImagePlugin.py +++ b/src/PIL/PixarImagePlugin.py @@ -49,10 +49,10 @@ class PixarImageFile(ImageFile.ImageFile): # read rest of header s = s + self.fp.read(508) - self._size = i16(s[418:420]), i16(s[416:418]) + self._size = i16(s, 418), i16(s, 416) # get channel/depth descriptions - mode = i16(s[424:426]), i16(s[426:428]) + mode = i16(s, 424), i16(s, 426) if mode == (14, 2): self.mode = "RGB" diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py index fd7ef712f..10e6010eb 100644 --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -409,7 +409,7 @@ class PngStream(ChunkStream): # image header s = ImageFile._safe_read(self.fp, length) - self.im_size = i32(s), i32(s[4:]) + self.im_size = i32(s, 0), i32(s, 4) try: self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])] except Exception: @@ -464,7 +464,7 @@ class PngStream(ChunkStream): elif self.im_mode in ("1", "L", "I"): self.im_info["transparency"] = i16(s) elif self.im_mode == "RGB": - self.im_info["transparency"] = i16(s), i16(s[2:]), i16(s[4:]) + self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4) return s def chunk_gAMA(self, pos, length): @@ -497,7 +497,7 @@ class PngStream(ChunkStream): # pixels per unit s = ImageFile._safe_read(self.fp, length) - px, py = i32(s), i32(s[4:]) + px, py = i32(s, 0), i32(s, 4) unit = s[8] if unit == 1: # meter dpi = int(px * 0.0254 + 0.5), int(py * 0.0254 + 0.5) @@ -618,7 +618,7 @@ class PngStream(ChunkStream): warnings.warn("Invalid APNG, will use default PNG image if possible") return s self.im_n_frames = n_frames - self.im_info["loop"] = i32(s[4:]) + self.im_info["loop"] = i32(s, 4) self.im_custom_mimetype = "image/apng" return s @@ -630,13 +630,13 @@ class PngStream(ChunkStream): ): raise SyntaxError("APNG contains frame sequence errors") self._seq_num = seq - width, height = i32(s[4:]), i32(s[8:]) - px, py = i32(s[12:]), i32(s[16:]) + width, height = i32(s, 4), i32(s, 8) + px, py = i32(s, 12), i32(s, 16) im_w, im_h = self.im_size if px + width > im_w or py + height > im_h: raise SyntaxError("APNG contains invalid frames") self.im_info["bbox"] = (px, py, px + width, py + height) - delay_num, delay_den = i16(s[20:]), i16(s[22:]) + delay_num, delay_den = i16(s, 20), i16(s, 22) if delay_den == 0: delay_den = 100 self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000 diff --git a/src/PIL/PsdImagePlugin.py b/src/PIL/PsdImagePlugin.py index 8d1dbf2b2..d3799edc3 100644 --- a/src/PIL/PsdImagePlugin.py +++ b/src/PIL/PsdImagePlugin.py @@ -63,12 +63,12 @@ class PsdImageFile(ImageFile.ImageFile): # header s = read(26) - if not _accept(s) or i16(s[4:]) != 1: + if not _accept(s) or i16(s, 4) != 1: raise SyntaxError("not a PSD file") - psd_bits = i16(s[22:]) - psd_channels = i16(s[12:]) - psd_mode = i16(s[24:]) + psd_bits = i16(s, 22) + psd_channels = i16(s, 12) + psd_mode = i16(s, 24) mode, channels = MODES[(psd_mode, psd_bits)] @@ -76,7 +76,7 @@ class PsdImageFile(ImageFile.ImageFile): raise OSError("not enough channels") self.mode = mode - self._size = i32(s[18:]), i32(s[14:]) + self._size = i32(s, 18), i32(s, 14) # # color mode data @@ -291,7 +291,7 @@ def _maketile(file, mode, bbox, channels): layer += ";I" tile.append(("packbits", bbox, offset, layer)) for y in range(ysize): - offset = offset + i16(bytecount[i : i + 2]) + offset = offset + i16(bytecount, i) i += 2 file.seek(offset) diff --git a/src/PIL/SgiImagePlugin.py b/src/PIL/SgiImagePlugin.py index 58a62fa5d..d0f7c9993 100644 --- a/src/PIL/SgiImagePlugin.py +++ b/src/PIL/SgiImagePlugin.py @@ -69,16 +69,16 @@ class SgiImageFile(ImageFile.ImageFile): bpc = s[3] # dimension : 1, 2 or 3 (depending on xsize, ysize and zsize) - dimension = i16(s[4:]) + dimension = i16(s, 4) # xsize : width - xsize = i16(s[6:]) + xsize = i16(s, 6) # ysize : height - ysize = i16(s[8:]) + ysize = i16(s, 8) # zsize : channels count - zsize = i16(s[10:]) + zsize = i16(s, 10) # layout layout = bpc, dimension, zsize diff --git a/src/PIL/SunImagePlugin.py b/src/PIL/SunImagePlugin.py index d99884293..c03759a01 100644 --- a/src/PIL/SunImagePlugin.py +++ b/src/PIL/SunImagePlugin.py @@ -58,13 +58,13 @@ class SunImageFile(ImageFile.ImageFile): offset = 32 - self._size = i32(s[4:8]), i32(s[8:12]) + self._size = i32(s, 4), i32(s, 8) - depth = i32(s[12:16]) - # data_length = i32(s[16:20]) # unreliable, ignore. - file_type = i32(s[20:24]) - palette_type = i32(s[24:28]) # 0: None, 1: RGB, 2: Raw/arbitrary - palette_length = i32(s[28:32]) + depth = i32(s, 12) + # data_length = i32(s, 16) # unreliable, ignore. + file_type = i32(s, 20) + palette_type = i32(s, 24) # 0: None, 1: RGB, 2: Raw/arbitrary + palette_length = i32(s, 28) if depth == 1: self.mode, rawmode = "1", "1;I" diff --git a/src/PIL/TgaImagePlugin.py b/src/PIL/TgaImagePlugin.py index 2ebe5d349..2b936d687 100644 --- a/src/PIL/TgaImagePlugin.py +++ b/src/PIL/TgaImagePlugin.py @@ -64,7 +64,7 @@ class TgaImageFile(ImageFile.ImageFile): flags = s[17] - self._size = i16(s[12:]), i16(s[14:]) + self._size = i16(s, 12), i16(s, 14) # validate header fields if ( @@ -110,7 +110,7 @@ class TgaImageFile(ImageFile.ImageFile): if colormaptype: # read palette - start, size, mapdepth = i16(s[3:]), i16(s[5:]), i16(s[7:]) + start, size, mapdepth = i16(s, 3), i16(s, 5), i16(s, 7) if mapdepth == 16: self.palette = ImagePalette.raw( "BGR;16", b"\0" * 2 * start + self.fp.read(2 * size) From 250e42f7f864401b87a378771e4b2fa0d6cccafe Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Wed, 30 Dec 2020 11:07:58 +0100 Subject: [PATCH 145/186] Bad Rebase --- src/libImaging/GifEncode.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/libImaging/GifEncode.c b/src/libImaging/GifEncode.c index 9f22add24..a0fef9933 100644 --- a/src/libImaging/GifEncode.c +++ b/src/libImaging/GifEncode.c @@ -241,8 +241,6 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) break; } - this = state->buffer[state->x++]; - if (this == context->last) { context->count++; } else { From e126001e627345abc6515cc49d7ca6f801a2c759 Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Wed, 30 Dec 2020 11:25:34 +0100 Subject: [PATCH 146/186] Help as default goal --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 6430c9776..3febff602 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.DEFAULT_GOAL := release-test +.DEFAULT_GOAL := help .PHONY: clean clean: From dae30d86016dfd3ed69d344809346d63b3039591 Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Wed, 30 Dec 2020 11:26:32 +0100 Subject: [PATCH 147/186] Removed co target -- Artifact of previous code review process --- Makefile | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Makefile b/Makefile index 3febff602..031b1de0d 100644 --- a/Makefile +++ b/Makefile @@ -7,13 +7,6 @@ clean: rm -r build || true find . -name __pycache__ | xargs rm -r || true -BRANCHES=`git branch -a | grep -v HEAD | grep -v master | grep remote` -.PHONY: co -co: - -for i in $(BRANCHES) ; do \ - git checkout -t $$i ; \ - done - .PHONY: coverage coverage: pytest -qq From 85649e299d3faa7d45523d180b0939f960f6c4f7 Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Wed, 30 Dec 2020 11:51:04 +0100 Subject: [PATCH 148/186] Makefile: Lint target --- Makefile | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Makefile b/Makefile index 031b1de0d..ab64730a2 100644 --- a/Makefile +++ b/Makefile @@ -102,3 +102,9 @@ test: .PHONY: readme readme: python3 setup.py --long-description | markdown2 > .long-description.html && open .long-description.html + + +.PHONY: lint +lint: + tox --help > /dev/null || pip install tox + tox -e lint From 737205c67f0c70ac4a83555afe0dfc16201f68cb Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 31 Dec 2020 09:35:35 +1100 Subject: [PATCH 149/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 691a7a220..796ed156b 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,9 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Added exception explaining that _repr_png_ saves to PNG #5139 + [radarhere] + - Use previous disposal method in GIF load_end #5125 [radarhere] From 77b16efba3aaf0758fd1a43aa6aea517509e88f3 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 31 Dec 2020 16:25:46 +1100 Subject: [PATCH 150/186] Corrected argument --- Tests/test_decompression_bomb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/test_decompression_bomb.py b/Tests/test_decompression_bomb.py index 132269933..7671cdc09 100644 --- a/Tests/test_decompression_bomb.py +++ b/Tests/test_decompression_bomb.py @@ -11,7 +11,7 @@ ORIGINAL_LIMIT = Image.MAX_IMAGE_PIXELS class TestDecompressionBomb: @classmethod - def teardown_class(self): + def teardown_class(cls): Image.MAX_IMAGE_PIXELS = ORIGINAL_LIMIT def test_no_warning_small_file(self): From 1af26f3159739fca2a54338a60c3c2c07e23b619 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 31 Dec 2020 18:28:01 +1100 Subject: [PATCH 151/186] Revert "skip wheels on 3.10-dev due to wheel#354" This reverts commit bdcc48f0a2d5af58155c6e10a127536d4ac79374. --- .github/workflows/test-windows.yml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test-windows.yml b/.github/workflows/test-windows.yml index 562b2b7b4..db1675135 100644 --- a/.github/workflows/test-windows.yml +++ b/.github/workflows/test-windows.yml @@ -197,16 +197,14 @@ jobs: - name: Build wheel id: wheel - # Skip wheels on 3.10 due to https://github.com/pypa/wheel/issues/354 - if: "github.event_name == 'push' && !contains(matrix.python-version, '3.10')" + if: "github.event_name == 'push'" run: | for /f "tokens=3 delims=/" %%a in ("${{ github.ref }}") do echo ::set-output name=dist::dist-%%a winbuild\\build\\build_pillow.cmd --disable-imagequant bdist_wheel shell: cmd - uses: actions/upload-artifact@v2 - # Skip wheels on 3.10 due to https://github.com/pypa/wheel/issues/354 - if: "github.event_name == 'push' && !contains(matrix.python-version, '3.10')" + if: "github.event_name == 'push'" with: name: ${{ steps.wheel.outputs.dist }} path: dist\*.whl From 48eb46ece6e4ce088ac0e328d2ea264123eec832 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 1 Jan 2021 00:05:47 +1100 Subject: [PATCH 152/186] Updated copyright year --- LICENSE | 2 +- docs/COPYING | 2 +- docs/conf.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/LICENSE b/LICENSE index eb9c41f56..1197291bc 100644 --- a/LICENSE +++ b/LICENSE @@ -5,7 +5,7 @@ The Python Imaging Library (PIL) is Pillow is the friendly PIL fork. It is - Copyright © 2010-2020 by Alex Clark and contributors + Copyright © 2010-2021 by Alex Clark and contributors Like PIL, Pillow is licensed under the open source HPND License: diff --git a/docs/COPYING b/docs/COPYING index ec2a5d8cb..f2466d659 100644 --- a/docs/COPYING +++ b/docs/COPYING @@ -5,7 +5,7 @@ The Python Imaging Library (PIL) is Pillow is the friendly PIL fork. It is - Copyright © 2010-2020 by Alex Clark and contributors + Copyright © 2010-2021 by Alex Clark and contributors Like PIL, Pillow is licensed under the open source PIL Software License: diff --git a/docs/conf.py b/docs/conf.py index 4e14a6fd0..4fb9d1f8f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -51,7 +51,7 @@ master_doc = "index" # General information about the project. project = "Pillow (PIL Fork)" -copyright = "1995-2011 Fredrik Lundh, 2010-2020 Alex Clark and Contributors" +copyright = "1995-2011 Fredrik Lundh, 2010-2021 Alex Clark and Contributors" author = "Fredrik Lundh, Alex Clark and Contributors" # The version info for the project you're documenting, acts as replacement for From 4ba769f99e4b7493d457b562096dfe8e896b5468 Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Thu, 31 Dec 2020 16:38:41 +0100 Subject: [PATCH 153/186] documentation --- Makefile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index ab64730a2..8dd35ec5c 100644 --- a/Makefile +++ b/Makefile @@ -40,7 +40,9 @@ help: @echo " install make and install" @echo " install-coverage make and install with C coverage" @echo " install-req install documentation and test dependencies" - @echo " install-venv install in virtualenv" + @echo " install-venv (deprecated) install in virtualenv" + @echo " lint run the lint checks" + @echo " lint-fix run black to (mostly) fix lint issues." @echo " release-test run code and package tests before release" @echo " test run tests on installed pillow" @echo " upload build and upload sdists to PyPI" From 35c396c1e6298ab1fdfdd31f502419916a4acebc Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Thu, 31 Dec 2020 16:38:57 +0100 Subject: [PATCH 154/186] the other pip invocation --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 8dd35ec5c..322b5bc43 100644 --- a/Makefile +++ b/Makefile @@ -108,5 +108,5 @@ readme: .PHONY: lint lint: - tox --help > /dev/null || pip install tox + tox --help > /dev/null || python3 -m pip install tox tox -e lint From 31b6e80f6efb33a2aa541872a728b212d33ea2fc Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Thu, 31 Dec 2020 16:39:10 +0100 Subject: [PATCH 155/186] lint-fix target, currently including black --- Makefile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Makefile b/Makefile index 322b5bc43..0ed453705 100644 --- a/Makefile +++ b/Makefile @@ -110,3 +110,7 @@ readme: lint: tox --help > /dev/null || python3 -m pip install tox tox -e lint + +.PHONY: lint-fix +lint-fix: + black --target-version py36 . From d7350bd4039f6482b1bcce4b8a05fcf4b6a750cf Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 1 Jan 2021 09:06:32 +1100 Subject: [PATCH 156/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 796ed156b..8cedc7415 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,9 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Use disposal settings from previous frame in APNG #5126 + [radarhere] + - Added exception explaining that _repr_png_ saves to PNG #5139 [radarhere] From 62693b7c54d0cae1bcd67affe2bf3e2829783a63 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 1 Jan 2021 11:33:20 +1100 Subject: [PATCH 157/186] Moved QApplication into one test --- Tests/test_imageqt.py | 21 ---------- Tests/test_qt_image_fromqpixmap.py | 15 ------- Tests/test_qt_image_qapplication.py | 63 +++++++++++++++++++++++++++++ Tests/test_qt_image_toqimage.py | 33 --------------- Tests/test_qt_image_toqpixmap.py | 20 --------- 5 files changed, 63 insertions(+), 89 deletions(-) delete mode 100644 Tests/test_qt_image_fromqpixmap.py create mode 100644 Tests/test_qt_image_qapplication.py delete mode 100644 Tests/test_qt_image_toqpixmap.py diff --git a/Tests/test_imageqt.py b/Tests/test_imageqt.py index c39bb0a06..7a6e1354f 100644 --- a/Tests/test_imageqt.py +++ b/Tests/test_imageqt.py @@ -8,27 +8,6 @@ if ImageQt.qt_is_installed: from PIL.ImageQt import qRgba -@pytest.mark.skipif(not ImageQt.qt_is_installed, reason="Qt bindings are not installed") -class PillowQPixmapTestCase: - @classmethod - def setup_class(self): - try: - if ImageQt.qt_version == "5": - from PyQt5.QtGui import QGuiApplication - elif ImageQt.qt_version == "side2": - from PySide2.QtGui import QGuiApplication - except ImportError: - pytest.skip("QGuiApplication not installed") - return - - self.app = QGuiApplication([]) - - @classmethod - def teardown_class(self): - self.app.quit() - self.app = None - - @pytest.mark.skipif(not ImageQt.qt_is_installed, reason="Qt bindings are not installed") def test_rgb(): # from https://doc.qt.io/archives/qt-4.8/qcolor.html diff --git a/Tests/test_qt_image_fromqpixmap.py b/Tests/test_qt_image_fromqpixmap.py deleted file mode 100644 index cb1b385ec..000000000 --- a/Tests/test_qt_image_fromqpixmap.py +++ /dev/null @@ -1,15 +0,0 @@ -from PIL import ImageQt - -from .helper import assert_image_equal, hopper -from .test_imageqt import PillowQPixmapTestCase - - -class TestFromQPixmap(PillowQPixmapTestCase): - def roundtrip(self, expected): - result = ImageQt.fromqpixmap(ImageQt.toqpixmap(expected)) - # Qt saves all pixmaps as rgb - assert_image_equal(result, expected.convert("RGB")) - - def test_sanity(self): - for mode in ("1", "RGB", "RGBA", "L", "P"): - self.roundtrip(hopper(mode)) diff --git a/Tests/test_qt_image_qapplication.py b/Tests/test_qt_image_qapplication.py new file mode 100644 index 000000000..ef1ff5901 --- /dev/null +++ b/Tests/test_qt_image_qapplication.py @@ -0,0 +1,63 @@ +import pytest + +from PIL import ImageQt + +from .helper import assert_image_equal, hopper + +if ImageQt.qt_is_installed: + from PIL.ImageQt import QPixmap + + if ImageQt.qt_version == "5": + from PyQt5 import QtGui + from PyQt5.QtWidgets import QApplication, QHBoxLayout, QLabel, QWidget + elif ImageQt.qt_version == "side2": + from PySide2 import QtGui + from PySide2.QtWidgets import QApplication, QHBoxLayout, QLabel, QWidget + + class Example(QWidget): + def __init__(self): + super().__init__() + + img = hopper().resize((1000, 1000)) + + qimage = ImageQt.ImageQt(img) + + pixmap1 = QtGui.QPixmap.fromImage(qimage) + + QHBoxLayout(self) # hbox + + lbl = QLabel(self) + # Segfault in the problem + lbl.setPixmap(pixmap1.copy()) + + +def roundtrip(expected): + result = ImageQt.fromqpixmap(ImageQt.toqpixmap(expected)) + # Qt saves all pixmaps as rgb + assert_image_equal(result, expected.convert("RGB")) + + +@pytest.mark.skipif(not ImageQt.qt_is_installed, reason="Qt bindings are not installed") +def test_sanity(tmp_path): + # Segfault test + app = QApplication([]) + ex = Example() + assert app # Silence warning + assert ex # Silence warning + + for mode in ("1", "RGB", "RGBA", "L", "P"): + # to QPixmap + data = ImageQt.toqpixmap(hopper(mode)) + + assert isinstance(data, QPixmap) + assert not data.isNull() + + # Test saving the file + tempfile = str(tmp_path / f"temp_{mode}.png") + data.save(tempfile) + + # from QPixmap + roundtrip(hopper(mode)) + + app.quit() + app = None diff --git a/Tests/test_qt_image_toqimage.py b/Tests/test_qt_image_toqimage.py index 8d599f9bf..1a2bfd71e 100644 --- a/Tests/test_qt_image_toqimage.py +++ b/Tests/test_qt_image_toqimage.py @@ -11,13 +11,6 @@ pytestmark = pytest.mark.skipif( if ImageQt.qt_is_installed: from PIL.ImageQt import QImage - try: - from PyQt5 import QtGui - from PyQt5.QtWidgets import QApplication, QHBoxLayout, QLabel, QWidget - except (ImportError, RuntimeError): - from PySide2 import QtGui - from PySide2.QtWidgets import QApplication, QHBoxLayout, QLabel, QWidget - def test_sanity(tmp_path): for mode in ("RGB", "RGBA", "L", "P", "1"): @@ -49,29 +42,3 @@ def test_sanity(tmp_path): # Check that it actually worked. with Image.open(tempfile) as reloaded: assert_image_equal(reloaded, src) - - -def test_segfault(): - app = QApplication([]) - ex = Example() - assert app # Silence warning - assert ex # Silence warning - - -if ImageQt.qt_is_installed: - - class Example(QWidget): - def __init__(self): - super().__init__() - - img = hopper().resize((1000, 1000)) - - qimage = ImageQt.ImageQt(img) - - pixmap1 = QtGui.QPixmap.fromImage(qimage) - - QHBoxLayout(self) # hbox - - lbl = QLabel(self) - # Segfault in the problem - lbl.setPixmap(pixmap1.copy()) diff --git a/Tests/test_qt_image_toqpixmap.py b/Tests/test_qt_image_toqpixmap.py deleted file mode 100644 index f38cc7f13..000000000 --- a/Tests/test_qt_image_toqpixmap.py +++ /dev/null @@ -1,20 +0,0 @@ -from PIL import ImageQt - -from .helper import hopper -from .test_imageqt import PillowQPixmapTestCase - -if ImageQt.qt_is_installed: - from PIL.ImageQt import QPixmap - - -class TestToQPixmap(PillowQPixmapTestCase): - def test_sanity(self, tmp_path): - for mode in ("1", "RGB", "RGBA", "L", "P"): - data = ImageQt.toqpixmap(hopper(mode)) - - assert isinstance(data, QPixmap) - assert not data.isNull() - - # Test saving the file - tempfile = str(tmp_path / f"temp_{mode}.png") - data.save(tempfile) From 78a051470cbed0f4d6e7a938f7cfeec691a66e07 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 1 Jan 2021 15:54:53 +1100 Subject: [PATCH 158/186] Added isort to lint-fix --- Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index 0ed453705..36338b2e1 100644 --- a/Makefile +++ b/Makefile @@ -114,3 +114,4 @@ lint: .PHONY: lint-fix lint-fix: black --target-version py36 . + isort . From 4f28ed3956a8104a7e36e7f0fe2b74d034d4a4aa Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 1 Jan 2021 23:32:46 +1100 Subject: [PATCH 159/186] Changed tabs to spaces for consistency --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 36338b2e1..af1c12039 100644 --- a/Makefile +++ b/Makefile @@ -41,8 +41,8 @@ help: @echo " install-coverage make and install with C coverage" @echo " install-req install documentation and test dependencies" @echo " install-venv (deprecated) install in virtualenv" - @echo " lint run the lint checks" - @echo " lint-fix run black to (mostly) fix lint issues." + @echo " lint run the lint checks" + @echo " lint-fix run black to (mostly) fix lint issues." @echo " release-test run code and package tests before release" @echo " test run tests on installed pillow" @echo " upload build and upload sdists to PyPI" From 4e3dc9a06b4459b444af44a234ff37434ed1253f Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Mon, 28 Dec 2020 12:58:08 +0200 Subject: [PATCH 160/186] Add support for PySide6 --- Tests/test_imageqt.py | 4 +++- Tests/test_qt_image_qapplication.py | 5 ++++- src/PIL/ImageQt.py | 11 +++++++++-- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/Tests/test_imageqt.py b/Tests/test_imageqt.py index 7a6e1354f..cf4aba982 100644 --- a/Tests/test_imageqt.py +++ b/Tests/test_imageqt.py @@ -14,7 +14,9 @@ def test_rgb(): # typedef QRgb # An ARGB quadruplet on the format #AARRGGBB, # equivalent to an unsigned int. - if ImageQt.qt_version == "5": + if ImageQt.qt_version == "side6": + from PySide6.QtGui import qRgb + elif ImageQt.qt_version == "5": from PyQt5.QtGui import qRgb elif ImageQt.qt_version == "side2": from PySide2.QtGui import qRgb diff --git a/Tests/test_qt_image_qapplication.py b/Tests/test_qt_image_qapplication.py index ef1ff5901..8d76eca3c 100644 --- a/Tests/test_qt_image_qapplication.py +++ b/Tests/test_qt_image_qapplication.py @@ -7,7 +7,10 @@ from .helper import assert_image_equal, hopper if ImageQt.qt_is_installed: from PIL.ImageQt import QPixmap - if ImageQt.qt_version == "5": + if ImageQt.qt_version == "side6": + from PySide6 import QtGui + from PySide6.QtWidgets import QApplication, QHBoxLayout, QLabel, QWidget + elif ImageQt.qt_version == "5": from PyQt5 import QtGui from PyQt5.QtWidgets import QApplication, QHBoxLayout, QLabel, QWidget elif ImageQt.qt_version == "side2": diff --git a/src/PIL/ImageQt.py b/src/PIL/ImageQt.py index 91be53488..64f07be11 100644 --- a/src/PIL/ImageQt.py +++ b/src/PIL/ImageQt.py @@ -22,13 +22,20 @@ from io import BytesIO from . import Image from ._util import isPath -qt_versions = [["5", "PyQt5"], ["side2", "PySide2"]] +qt_versions = [ + ["side6", "PySide6"], + ["5", "PyQt5"], + ["side2", "PySide2"], +] # If a version has already been imported, attempt it first qt_versions.sort(key=lambda qt_version: qt_version[1] in sys.modules, reverse=True) for qt_version, qt_module in qt_versions: try: - if qt_module == "PyQt5": + if qt_module == "PySide6": + from PySide6.QtCore import QBuffer, QIODevice + from PySide6.QtGui import QImage, QPixmap, qRgba + elif qt_module == "PyQt5": from PyQt5.QtCore import QBuffer, QIODevice from PyQt5.QtGui import QImage, QPixmap, qRgba elif qt_module == "PySide2": From effa65cb386638aa064ad92b17c9e91449fd461a Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Mon, 28 Dec 2020 13:04:25 +0200 Subject: [PATCH 161/186] Refactor --- Tests/test_qt_image_qapplication.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Tests/test_qt_image_qapplication.py b/Tests/test_qt_image_qapplication.py index 8d76eca3c..06bd27c00 100644 --- a/Tests/test_qt_image_qapplication.py +++ b/Tests/test_qt_image_qapplication.py @@ -8,13 +8,10 @@ if ImageQt.qt_is_installed: from PIL.ImageQt import QPixmap if ImageQt.qt_version == "side6": - from PySide6 import QtGui from PySide6.QtWidgets import QApplication, QHBoxLayout, QLabel, QWidget elif ImageQt.qt_version == "5": - from PyQt5 import QtGui from PyQt5.QtWidgets import QApplication, QHBoxLayout, QLabel, QWidget elif ImageQt.qt_version == "side2": - from PySide2 import QtGui from PySide2.QtWidgets import QApplication, QHBoxLayout, QLabel, QWidget class Example(QWidget): @@ -25,7 +22,7 @@ if ImageQt.qt_is_installed: qimage = ImageQt.ImageQt(img) - pixmap1 = QtGui.QPixmap.fromImage(qimage) + pixmap1 = ImageQt.QPixmap.fromImage(qimage) QHBoxLayout(self) # hbox From 8e948d066a36f53f31b34bbaf4199443dbfa489b Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 09:34:31 +1100 Subject: [PATCH 162/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 8cedc7415..3573d934f 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,9 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Add support for PySide6 #5161 + [hugovk] + - Use disposal settings from previous frame in APNG #5126 [radarhere] From 3808aee4e6d019def83132d9ab3e1514738273a4 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 09:39:04 +1100 Subject: [PATCH 163/186] Document #5161 [ci skip] --- docs/releasenotes/8.1.0.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index 79ed507f4..b52d9f883 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -55,3 +55,9 @@ PyPy wheels ^^^^^^^^^^^ Wheels have been added for PyPy 3.7. + +PySide6 +^^^^^^^ + +Support has been added for PySide6. If it is installed, it will be used instead of +PyQt5 or PySide2, since it is based on a newer Qt. From 6f3670df4d27f54f2bd66f9b1f2a98e59b46bf1d Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Sat, 2 Jan 2021 09:46:03 +1100 Subject: [PATCH 164/186] Updated description --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index af1c12039..dae26bbee 100644 --- a/Makefile +++ b/Makefile @@ -42,7 +42,7 @@ help: @echo " install-req install documentation and test dependencies" @echo " install-venv (deprecated) install in virtualenv" @echo " lint run the lint checks" - @echo " lint-fix run black to (mostly) fix lint issues." + @echo " lint-fix run black and isort to (mostly) fix lint issues." @echo " release-test run code and package tests before release" @echo " test run tests on installed pillow" @echo " upload build and upload sdists to PyPI" From 852503a4a3a7d47266c6a8b69e741136b47d76e8 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 11:00:33 +1100 Subject: [PATCH 165/186] Document #5159 [ci skip] --- docs/releasenotes/8.1.0.rst | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index b52d9f883..f89693677 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -15,6 +15,11 @@ vulnerability introduced in FreeType 2.6 (:cve:`CVE-2020-15999`). .. _2.10.4: https://sourceforge.net/projects/freetype/files/freetype2/2.10.4/ +Makefile +^^^^^^^^ + +The 'install-venv' target has been deprecated. + API Changes =========== @@ -51,6 +56,11 @@ security fixes. Other Changes ============= +Makefile +^^^^^^^^ + +The 'co' target has been removed. + PyPy wheels ^^^^^^^^^^^ From 01cad6bcad622cb853a58642b12facfe6dc86362 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 11:24:20 +1100 Subject: [PATCH 166/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 3573d934f..346cfd2a9 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,9 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Makefile updates #5159 + [wiredfool, radarhere] + - Add support for PySide6 #5161 [hugovk] From 527409053fb9d4732166e50b1624d9385230e859 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 19:39:42 +1100 Subject: [PATCH 167/186] Added deprecation message for install-venv --- Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index dae26bbee..53eaa0566 100644 --- a/Makefile +++ b/Makefile @@ -76,6 +76,7 @@ install-req: .PHONY: install-venv install-venv: + echo "'install-venv' is deprecated and will be removed in a future Pillow release" virtualenv . bin/pip install -r requirements.txt From e6ef8a6c0916807bd10d6a089ca95b70e03d538c Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 19:58:03 +1100 Subject: [PATCH 168/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 346cfd2a9..7a21cf440 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,9 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Fix OOB Read when saving GIF of xsize=1 #5149 + [wiredfool] + - Makefile updates #5159 [wiredfool, radarhere] From 6ffa37b85bc46133ac3c176253e36bff9c6c7272 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 19:59:29 +1100 Subject: [PATCH 169/186] Document #5149 [ci skip] --- docs/releasenotes/8.1.0.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index b52d9f883..37571d731 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -40,7 +40,7 @@ Security ======== An out-of-bounds read when saving TIFFs with custom metadata through libtiff has been -fixed. +fixed, as well as when saving a GIF of 1px width. Dependencies ^^^^^^^^^^^^ From 7e95c63fa7f503f185d3d9eb16b9cee1e54d1e46 Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Thu, 29 Oct 2020 23:07:15 +0000 Subject: [PATCH 170/186] Fix for SGI Decode buffer overrun CVE-2020-35655 * Independently found by a contributor and sent to Tidelift, and by Google's OSS Fuzz. --- ...7f2244da6d0ae297ee0754a424213444e92778.sgi | Bin 0 -> 6973 bytes Tests/images/ossfuzz-5730089102868480.sgi | Bin 0 -> 530 bytes Tests/test_sgi_crash.py | 8 +++++- src/libImaging/SgiRleDecode.c | 23 ++++++++++++------ 4 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi create mode 100644 Tests/images/ossfuzz-5730089102868480.sgi diff --git a/Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi b/Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi new file mode 100644 index 0000000000000000000000000000000000000000..74396935b9a5df427fdcc80c5d884e0196f6caf0 GIT binary patch literal 6973 zcmeI0e^6G}na4l(_qq4I_bwXKxW*WUl9XCw(NaS-H4Y`w7*cIY3`;30MPn!-#IVG; zl%@0?N{u>7S*ylaLJ854#9RI~)^6DQ~flo{5&u)T66OghU?uv&MEwCyZzUo8n za`^focvK$W=3Mw@6MQEIc5H<2b;0+iLVXTAcNmVyd`kti&w^i$z^k3`t9}@o10%=a zUCA?%iRNrXi|It0k%bl?gLca$v}8FNDNE4OYSHdbKwI05mS2PR*nYI~HneT;q3y{= ztLsNQT!GfI60IW{t!FXXzy`FDI<%|9=vET?lxp-F#?fbQKwoeX{R=thD|*ng63{mk zq8A-PFB?SP=A-YKh5pQJ^#6`WKRy+`V-&ro7k!`^eWV`!>Rt?UD@IHi#>~wa2?ZEQ z8!(pSV5DVXWQcNCVHAo=M3pkGmbDtOIh2RdT#V6Pj&W)`#u;CpOR#P^iuJi1tUJoE?oGm49gmg266^8pSQUL()ibf4UW3(8 zfb~KNR>wxH(^*)93$ZTySbvy`ZI@$DX~CX(68jU4*z?P%@LjVUHwZzngzdfPHH#KJqvK|E5`Y%*shD>Jd}=8^d3%0InK9+ah{li zQYgHsW4?7Wbwf;(j^-H@O%$B^~$fG2Hu- zakH~c4s#@k+ix9f{|`^B$b;XOBqcSQV-@4|br z5bx#Xc&Fp>UN`ZE&f<+Un~g& zl4cS~k0p|oLL@hjNPZQOqGLo#28l%9A+k*o`L9_-o=PI}%t|89l@dA9NaXkkk&|B6_)Nmt7YXMT5Z*dMxHy|I^(Df)XA^#@ zobdi$!t7aux#@&?n+OYc5EhF{qJ-t^2`d*6ZW|^1ZVlm{g@pTC2V5M!sB}hPb3qbJVf}?6~eBogx!+AcNO7lhY8Qr5uTG+Z=@0qO5VX!gl|gTH}gfu z2#1tNY=^{d=pDjeFA;4Qogo~Sy$;LXhUMPQPZQ;cBLsT!4dl^X)?GT+Me0z>)Gt5hXTkB!*Tu5z$yEEWR??A>rSX~V3 zWv(C={=EcBdLSzHPYC>}8iu_K;puWXa0(9J49^Q#`bh{Uo1tqf^h*4*HE`aB%XM(I z08Pt5^LC(JGmdt{ZnRGbD4Mq%ZBahj9Y@ht#-n9QzfQ)5GXEdxXceVsJ5QoLH6QIj zD_T<#TH7)-ITu=A8ro0^+LdEy|0m?pO-H|0piW#Y`dk4-iv;#8twjIw74$Vr(DS3{ zn_AJMGTtd`PsO1h6kv2j0MSnsdZ&P-zE1R^M)WJS=;OOER3*l=QjA!EJah6flGkIT zuEAI-5GX4XV}k&pB2ife#@1|%-MJWb0)^xp8!ZBpIw~-FsxSujVF#;74uRi=I@KJ%xbKEX~de*gLU&%ta*E}KA(?uR}0pvDAw01u?ml2ePbN!iBzoJ zGJZzJjU8A&>B8!4!+NbAYgjOAjDqsL+rZ+F5Op& zy;^|NgCp3Fj$wb}3ih|Vv3KsnesU#t-C690h1k#U#cmtLeo6dam9;Yi*uw&zF5iiL zwGc;% z0fA}1p1}D{G0v5KoH2?22Z3Vbp{!*ndB3Vq;MLSp)O7;1uJ1v`3hcT`K-MS4=9VaG zp6IjHsLu_c7B`?$7o+YHkhP*4bzd{;D>bOKvi^YRp*qx~ZK%gbP-OzwD#}n>1*Cm< zA!?7<)|8;0mG}+ff3zOeD!wO&P_N{o`UI4{F&%ZW2{rl->irsAPe9nT5!@T&a1(lP z=cnKBfR{tMUEK4u| literal 0 HcmV?d00001 diff --git a/Tests/images/ossfuzz-5730089102868480.sgi b/Tests/images/ossfuzz-5730089102868480.sgi new file mode 100644 index 0000000000000000000000000000000000000000..a92c1ed019bf1505edc5cc7444f72bd89f7105b7 GIT binary patch literal 530 zcmbV}JxT;Y5QX0x1_l2X!3#{Vk%1bUmuz`gUnXQAvCj}~ z7>4_*w5lQ8R_)W3#s6Qn?)|gR$6YB~%3<#QnCan5OLprB9k|!1GG*%B<)Kn9rCeY5 lRXC<*?69+uJ>aQ&fSW~xI==&kzK^d-^5=gx6Y-&T?Hdo^jb8u& literal 0 HcmV?d00001 diff --git a/Tests/test_sgi_crash.py b/Tests/test_sgi_crash.py index 2b671244a..6626f55f7 100644 --- a/Tests/test_sgi_crash.py +++ b/Tests/test_sgi_crash.py @@ -6,7 +6,13 @@ from PIL import Image @pytest.mark.parametrize( "test_file", - ["Tests/images/sgi_overrun_expandrowF04.bin", "Tests/images/sgi_crash.bin"], + [ + "Tests/images/sgi_overrun_expandrowF04.bin", + "Tests/images/sgi_crash.bin", + "Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi", + "Tests/images/ossfuzz-5730089102868480.sgi", + + ], ) def test_crashes(test_file): with open(test_file, "rb") as f: diff --git a/src/libImaging/SgiRleDecode.c b/src/libImaging/SgiRleDecode.c index a03ecd456..46a917923 100644 --- a/src/libImaging/SgiRleDecode.c +++ b/src/libImaging/SgiRleDecode.c @@ -112,11 +112,27 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, int err = 0; int status; + /* size check */ + if (im->xsize > INT_MAX / im->bands || + im->ysize > INT_MAX / im->bands) { + return IMAGING_CODEC_MEMORY; + } + /* Get all data from File descriptor */ c = (SGISTATE*)state->context; _imaging_seek_pyFd(state->fd, 0L, SEEK_END); c->bufsize = _imaging_tell_pyFd(state->fd); c->bufsize -= SGI_HEADER_SIZE; + + c->tablen = im->bands * im->ysize; + /* below, we populate the starttab and lentab into the bufsize, + each with 4 bytes per element of tablen + Check here before we allocate any memory + */ + if (c->bufsize < 8*c->tablen) { + return IMAGING_CODEC_MEMORY; + } + ptr = malloc(sizeof(UINT8) * c->bufsize); if (!ptr) { return IMAGING_CODEC_MEMORY; @@ -134,18 +150,11 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, state->ystep = 1; } - if (im->xsize > INT_MAX / im->bands || - im->ysize > INT_MAX / im->bands) { - err = IMAGING_CODEC_MEMORY; - goto sgi_finish_decode; - } - /* Allocate memory for RLE tables and rows */ free(state->buffer); state->buffer = NULL; /* malloc overflow check above */ state->buffer = calloc(im->xsize * im->bands, sizeof(UINT8) * 2); - c->tablen = im->bands * im->ysize; c->starttab = calloc(c->tablen, sizeof(UINT32)); c->lengthtab = calloc(c->tablen, sizeof(UINT32)); if (!state->buffer || From 9a2c9f722f78773e608d44710873437baf3f17d1 Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Fri, 30 Oct 2020 09:57:23 +0000 Subject: [PATCH 171/186] Make the SGI code return -1 as an error flag, error in state --- src/libImaging/SgiRleDecode.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/libImaging/SgiRleDecode.c b/src/libImaging/SgiRleDecode.c index 46a917923..9a8814b50 100644 --- a/src/libImaging/SgiRleDecode.c +++ b/src/libImaging/SgiRleDecode.c @@ -115,7 +115,8 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, /* size check */ if (im->xsize > INT_MAX / im->bands || im->ysize > INT_MAX / im->bands) { - return IMAGING_CODEC_MEMORY; + state->errcode = IMAGING_CODEC_MEMORY; + return -1; } /* Get all data from File descriptor */ @@ -130,12 +131,14 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, Check here before we allocate any memory */ if (c->bufsize < 8*c->tablen) { - return IMAGING_CODEC_MEMORY; + state->errcode = IMAGING_CODEC_OVERRUN; + return -1; } ptr = malloc(sizeof(UINT8) * c->bufsize); if (!ptr) { - return IMAGING_CODEC_MEMORY; + state->errcode = IMAGING_CODEC_MEMORY; + return -1; } _imaging_seek_pyFd(state->fd, SGI_HEADER_SIZE, SEEK_SET); _imaging_read_pyFd(state->fd, (char*)ptr, c->bufsize); @@ -185,7 +188,7 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, if (c->rleoffset + c->rlelength > c->bufsize) { state->errcode = IMAGING_CODEC_OVERRUN; - return -1; + goto sgi_finish_decode; } /* row decompression */ @@ -197,7 +200,7 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, } if (status == -1) { state->errcode = IMAGING_CODEC_OVERRUN; - return -1; + goto sgi_finish_decode; } else if (status == 1) { goto sgi_finish_decode; } @@ -218,7 +221,8 @@ sgi_finish_decode: ; free(c->lengthtab); free(ptr); if (err != 0){ - return err; + state->errcode=err; + return -1; } return state->count - c->bufsize; } From 1cbb12fb6e44da0d6d6d58254d0d96930d04af5e Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 20:19:26 +1100 Subject: [PATCH 172/186] Lint fix --- Tests/test_sgi_crash.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Tests/test_sgi_crash.py b/Tests/test_sgi_crash.py index 6626f55f7..ac304aab4 100644 --- a/Tests/test_sgi_crash.py +++ b/Tests/test_sgi_crash.py @@ -11,7 +11,6 @@ from PIL import Image "Tests/images/sgi_crash.bin", "Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi", "Tests/images/ossfuzz-5730089102868480.sgi", - ], ) def test_crashes(test_file): From eb8c1206d6b170d4e798a00db7432e023853da5c Mon Sep 17 00:00:00 2001 From: wiredfool Date: Sun, 1 Nov 2020 14:16:38 +0000 Subject: [PATCH 173/186] Fix CVE-2020-35654 - OOB Write in TiffDecode.c * In some circumstances with some versions of libtiff (4.1.0+), there could be a 4 byte out of bound write when decoding a YCbCr tiff. * The Pillow code dates to 6.0.0 * Found and reported through Tidelift --- Tests/images/crash-2020-10-test.tif | Bin 0 -> 4883 bytes Tests/test_tiff_crashes.py | 7 +- src/libImaging/TiffDecode.c | 286 +++++++++++++++++----------- 3 files changed, 185 insertions(+), 108 deletions(-) create mode 100644 Tests/images/crash-2020-10-test.tif diff --git a/Tests/images/crash-2020-10-test.tif b/Tests/images/crash-2020-10-test.tif new file mode 100644 index 0000000000000000000000000000000000000000..958cdde22098ae65a82e671407f170ef75e34a1f GIT binary patch literal 4883 zcmeHKU2GIp6h3!$x-M;jwk&O|O9s$m#tJfoVVWf+wliKAaz3DL z^_15Db50FKdLu|=+eD)S*U4kH2@kKzBiEbDVY2P(T}rDm(pq^aZUOgY%L$s%t+xf8m2zOyS;uA{V(FvKrE?EgNalcZzcY)9bytoJ zL*L#Gu^aX&n|bvbVAJ2XF92MJ>z>CLE9sI_DXqA}q23?$_(NyK8zIyWTY+qZJuC5kSJzke zq;3B(d7BF(h}hV1>BoZ~*!eOV6PDv2?V#yCQg|fgvFqrT!{v4zlL@OdQbSWD8jr^x zT$^ZXwKiF?&=rcyRG5{HgQD8B>jTG=#}6G% z9c-)b*n4D8f1u~F#{->5hWZ07p_b-nBN5A}^q7>cigc`4^~Ccf^?k2h@NeGp(M|g* zdFC58)Pu6Q8GIZmZZ4Q(m<=HVrUL$LHDVJhG$_AH1%C~{U{Wcj30$*EYHY5tAZC?g zKCT{}c1wv|Whu5`U1mE?tDo5lrMLEUZ8Hk(#7|JoTtZjC(GE7ZX5CsMo-MnB;$DNq z1?J+O#LUg%-BAw(Fqh)p3#dogkHq#0<2>jb4_5sWOw#dSe%*ON z4$*Sqm0Qqz$t#<0c@Wm)Id2;QnpsXXW;f$J4M z0UT8LQ{dGS8&uUqv^G;B9kdI0ox(%Fjo@KNy#l-*bjE4mCWTJ{hZKGbI1C-iz;g~b z0ynLeZn>67Vm;+!Q|n z{#D^GfPV+(L)tj--ORMJ@)_f95cD5G_h%iaRN$l*1lBop59jOudb@ySy4SdOYd+}c z+}<$)L%BJ~j|mPSccm&)r$KHMJ)MIC-Kn7gaN(TzWZy7a?!wNJ{5E*`Dr_f`Hgm}v zyrjdnO_<<5Kzu^63Lz-RLr2u?QMdPgz%W4W(k*F1pYz#+Rnxn1B$cALRC7?$A zBc*{&Lwlb~c5m4hIDTjlUs1SgtKXkW9ZiPA!^6X&;i#n>G#AK>@55rL?JRg9QmxRD Yp?%?KB9RD3tgvM@W8LOsFC^Oj1mik+wEzGB literal 0 HcmV?d00001 diff --git a/Tests/test_tiff_crashes.py b/Tests/test_tiff_crashes.py index 9c293e014..d0de4b305 100644 --- a/Tests/test_tiff_crashes.py +++ b/Tests/test_tiff_crashes.py @@ -19,7 +19,12 @@ from .helper import on_ci @pytest.mark.parametrize( - "test_file", ["Tests/images/crash_1.tif", "Tests/images/crash_2.tif"] + "test_file", + [ + "Tests/images/crash_1.tif", + "Tests/images/crash_2.tif", + "Tests/images/crash-2020-10-test.tif", + ], ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") @pytest.mark.filterwarnings("ignore:Metadata warning") diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c index d86a42915..2684b9e28 100644 --- a/src/libImaging/TiffDecode.c +++ b/src/libImaging/TiffDecode.c @@ -238,54 +238,181 @@ int ReadTile(TIFF* tiff, UINT32 col, UINT32 row, UINT32* buffer) { return 0; } -int ReadStrip(TIFF* tiff, UINT32 row, UINT32* buffer) { - uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR - TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); - +int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { // To avoid dealing with YCbCr subsampling, let libtiff handle it - if (photometric == PHOTOMETRIC_YCBCR) { - TIFFRGBAImage img; - char emsg[1024] = ""; - UINT32 rows_per_strip, rows_to_read; - int ok; + // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle + // all of the conversion. Metadata read from the TIFFRGBAImage could + // be different from the metadata that the base tiff returns. + INT32 strip_row; + UINT8 *new_data; + UINT32 rows_per_strip, row_byte_size, rows_to_read; + int ret; + TIFFRGBAImage img; + char emsg[1024] = ""; + int ok; - TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); - if ((row % rows_per_strip) != 0) { - TRACE(("Row passed to ReadStrip() must be first in a strip.")); - return -1; - } - - if (TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg)) { - TRACE(("Initialized RGBAImage\n")); - - img.req_orientation = ORIENTATION_TOPLEFT; - img.row_offset = row; - img.col_offset = 0; - - rows_to_read = min(rows_per_strip, img.height - row); - - TRACE(("rows to read: %d\n", rows_to_read)); - ok = TIFFRGBAImageGet(&img, buffer, img.width, rows_to_read); - - TIFFRGBAImageEnd(&img); - } else { - ok = 0; - } - - if (ok == 0) { - TRACE(("Decode Error, row %d; msg: %s\n", row, emsg)); - return -1; - } - - return 0; + ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); + if (ret != 1) { + rows_per_strip = state->ysize; } + TRACE(("RowsPerStrip: %u \n", rows_per_strip)); - if (TIFFReadEncodedStrip(tiff, TIFFComputeStrip(tiff, row, 0), (tdata_t)buffer, -1) == -1) { - TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, row, 0))); + if (!(TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg))) { + TRACE(("Decode error, msg: %s", emsg)); + state->errcode = IMAGING_CODEC_BROKEN; + TIFFClose(tiff); return -1; } + img.req_orientation = ORIENTATION_TOPLEFT; + img.col_offset = 0; + + if (state->xsize != img.width || state->ysize != img.height) { + TRACE(("Inconsistent Image Error: %d =? %d, %d =? %d", + state->xsize, img.width, state->ysize, img.height)); + state->errcode = IMAGING_CODEC_BROKEN; + TIFFRGBAImageEnd(&img); + TIFFClose(tiff); + return -1; + } + + /* overflow check for row byte size */ + if (INT_MAX / 4 < img.width) { + state->errcode = IMAGING_CODEC_MEMORY; + TIFFRGBAImageEnd(&img); + TIFFClose(tiff); + return -1; + } + + // TiffRGBAImages are 32bits/pixel. + row_byte_size = img.width * 4; + + /* overflow check for realloc */ + if (INT_MAX / row_byte_size < rows_per_strip) { + state->errcode = IMAGING_CODEC_MEMORY; + TIFFRGBAImageEnd(&img); + TIFFClose(tiff); + return -1; + } + + state->bytes = rows_per_strip * row_byte_size; + + TRACE(("StripSize: %d \n", state->bytes)); + + /* realloc to fit whole strip */ + /* malloc check above */ + new_data = realloc (state->buffer, state->bytes); + if (!new_data) { + state->errcode = IMAGING_CODEC_MEMORY; + TIFFRGBAImageEnd(&img); + TIFFClose(tiff); + return -1; + } + + state->buffer = new_data; + + for (; state->y < state->ysize; state->y += rows_per_strip) { + img.row_offset = state->y; + rows_to_read = min(rows_per_strip, img.height - state->y); + + if (TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read) == -1) { + TRACE(("Decode Error, y: %d\n", state->y )); + state->errcode = IMAGING_CODEC_BROKEN; + TIFFRGBAImageEnd(&img); + TIFFClose(tiff); + return -1; + } + + TRACE(("Decoded strip for row %d \n", state->y)); + + // iterate over each row in the strip and stuff data into image + for (strip_row = 0; strip_row < min((INT32) rows_per_strip, state->ysize - state->y); strip_row++) { + TRACE(("Writing data into line %d ; \n", state->y + strip_row)); + + // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); + // TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); + + state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] + + state->xoff * im->pixelsize, + state->buffer + strip_row * row_byte_size, + state->xsize); + } + } + TIFFRGBAImageEnd(&img); + return 0; +} + +int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { + INT32 strip_row; + UINT8 *new_data; + UINT32 rows_per_strip, row_byte_size; + int ret; + + ret = TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); + if (ret != 1) { + rows_per_strip = state->ysize; + } + TRACE(("RowsPerStrip: %u \n", rows_per_strip)); + + // We could use TIFFStripSize, but for YCbCr data it returns subsampled data size + row_byte_size = (state->xsize * state->bits + 7) / 8; + + /* overflow check for realloc */ + if (INT_MAX / row_byte_size < rows_per_strip) { + state->errcode = IMAGING_CODEC_MEMORY; + TIFFClose(tiff); + return -1; + } + + state->bytes = rows_per_strip * row_byte_size; + + TRACE(("StripSize: %d \n", state->bytes)); + + if (TIFFStripSize(tiff) > state->bytes) { + // If the strip size as expected by LibTiff isn't what we're expecting, abort. + // man: TIFFStripSize returns the equivalent size for a strip of data as it would be returned in a + // call to TIFFReadEncodedStrip ... + + state->errcode = IMAGING_CODEC_MEMORY; + TIFFClose(tiff); + return -1; + } + + /* realloc to fit whole strip */ + /* malloc check above */ + new_data = realloc (state->buffer, state->bytes); + if (!new_data) { + state->errcode = IMAGING_CODEC_MEMORY; + TIFFClose(tiff); + return -1; + } + + state->buffer = new_data; + + for (; state->y < state->ysize; state->y += rows_per_strip) { + if (TIFFReadEncodedStrip(tiff, TIFFComputeStrip(tiff, state->y, 0), (tdata_t)state->buffer, -1) == -1) { + TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, state->y, 0))); + state->errcode = IMAGING_CODEC_BROKEN; + TIFFClose(tiff); + return -1; + } + + TRACE(("Decoded strip for row %d \n", state->y)); + + // iterate over each row in the strip and stuff data into image + for (strip_row = 0; strip_row < min((INT32) rows_per_strip, state->ysize - state->y); strip_row++) { + TRACE(("Writing data into line %d ; \n", state->y + strip_row)); + + // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); + // TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); + + state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] + + state->xoff * im->pixelsize, + state->buffer + strip_row * row_byte_size, + state->xsize); + } + } return 0; } @@ -294,6 +421,9 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ char *filename = "tempfile.tif"; char *mode = "r"; TIFF *tiff; + uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR + int isYCbCr = 0; + int ret; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ @@ -354,6 +484,10 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ } } + + TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); + isYCbCr = photometric == PHOTOMETRIC_YCBCR; + if (TIFFIsTiled(tiff)) { INT32 x, y, tile_y; UINT32 tile_width, tile_length, current_tile_width, row_byte_size; @@ -429,75 +563,13 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ } } } else { - INT32 strip_row; - UINT8 *new_data; - UINT32 rows_per_strip, row_byte_size; - int ret; - - ret = TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); - if (ret != 1) { - rows_per_strip = state->ysize; + if (!isYCbCr) { + ret = _decodeStrip(im, state, tiff); } - TRACE(("RowsPerStrip: %u \n", rows_per_strip)); - - // We could use TIFFStripSize, but for YCbCr data it returns subsampled data size - row_byte_size = (state->xsize * state->bits + 7) / 8; - - /* overflow check for realloc */ - if (INT_MAX / row_byte_size < rows_per_strip) { - state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); - return -1; - } - - state->bytes = rows_per_strip * row_byte_size; - - TRACE(("StripSize: %d \n", state->bytes)); - - if (TIFFStripSize(tiff) > state->bytes) { - // If the strip size as expected by LibTiff isn't what we're expecting, abort. - // man: TIFFStripSize returns the equivalent size for a strip of data as it would be returned in a - // call to TIFFReadEncodedStrip ... - - state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); - return -1; - } - - /* realloc to fit whole strip */ - /* malloc check above */ - new_data = realloc (state->buffer, state->bytes); - if (!new_data) { - state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); - return -1; - } - - state->buffer = new_data; - - for (; state->y < state->ysize; state->y += rows_per_strip) { - if (ReadStrip(tiff, state->y, (UINT32 *)state->buffer) == -1) { - TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, state->y, 0))); - state->errcode = IMAGING_CODEC_BROKEN; - TIFFClose(tiff); - return -1; - } - - TRACE(("Decoded strip for row %d \n", state->y)); - - // iterate over each row in the strip and stuff data into image - for (strip_row = 0; strip_row < min((INT32) rows_per_strip, state->ysize - state->y); strip_row++) { - TRACE(("Writing data into line %d ; \n", state->y + strip_row)); - - // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); - // TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); - - state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] + - state->xoff * im->pixelsize, - state->buffer + strip_row * row_byte_size, - state->xsize); - } + else { + ret = _decodeStripYCbCr(im, state, tiff); } + if (ret == -1) { return ret; } } TIFFClose(tiff); From 45a62e91b1f72e79989a7919af97b062dc8dfaf4 Mon Sep 17 00:00:00 2001 From: wiredfool Date: Sun, 1 Nov 2020 16:25:31 +0000 Subject: [PATCH 174/186] Rework ReadTile * Don't malloc for the swap line, just shuffle backwards * Ensure that im->pixelsize is sanity checked * Ensure that we're using the right size for the buffer from TiffReadRGBATile --- src/libImaging/TiffDecode.c | 164 ++++++++++++++---------------------- 1 file changed, 61 insertions(+), 103 deletions(-) diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c index 2684b9e28..5cbbe7380 100644 --- a/src/libImaging/TiffDecode.c +++ b/src/libImaging/TiffDecode.c @@ -181,63 +181,6 @@ int ImagingLibTiffInit(ImagingCodecState state, int fp, uint32 offset) { } -int ReadTile(TIFF* tiff, UINT32 col, UINT32 row, UINT32* buffer) { - uint16 photometric = 0; - - TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); - - // To avoid dealing with YCbCr subsampling, let libtiff handle it - if (photometric == PHOTOMETRIC_YCBCR) { - UINT32 tile_width, tile_height, swap_line_size, i_row; - UINT32* swap_line; - - TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); - TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_height); - - swap_line_size = tile_width * sizeof(UINT32); - if (tile_width != swap_line_size / sizeof(UINT32)) { - return -1; - } - - /* Read the tile into an RGBA array */ - if (!TIFFReadRGBATile(tiff, col, row, buffer)) { - return -1; - } - - swap_line = (UINT32*)malloc(swap_line_size); - if (swap_line == NULL) { - return -1; - } - /* - * For some reason the TIFFReadRGBATile() function chooses the - * lower left corner as the origin. Vertically mirror scanlines. - */ - for(i_row = 0; i_row < tile_height / 2; i_row++) { - UINT32 *top_line, *bottom_line; - - top_line = buffer + tile_width * i_row; - bottom_line = buffer + tile_width * (tile_height - i_row - 1); - - memcpy(swap_line, top_line, 4*tile_width); - memcpy(top_line, bottom_line, 4*tile_width); - memcpy(bottom_line, swap_line, 4*tile_width); - } - - free(swap_line); - - return 0; - } - - if (TIFFReadTile(tiff, (tdata_t)buffer, col, row, 0, 0) == -1) { - TRACE(("Decode Error, Tile at %dx%d\n", col, row)); - return -1; - } - - TRACE(("Successfully read tile at %dx%d; \n\n", col, row)); - - return 0; -} - int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { // To avoid dealing with YCbCr subsampling, let libtiff handle it // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle @@ -250,7 +193,6 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { int ret; TIFFRGBAImage img; char emsg[1024] = ""; - int ok; ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); if (ret != 1) { @@ -261,7 +203,7 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { if (!(TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg))) { TRACE(("Decode error, msg: %s", emsg)); state->errcode = IMAGING_CODEC_BROKEN; - TIFFClose(tiff); + // nothing to clean up, just return return -1; } @@ -272,17 +214,13 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { TRACE(("Inconsistent Image Error: %d =? %d, %d =? %d", state->xsize, img.width, state->ysize, img.height)); state->errcode = IMAGING_CODEC_BROKEN; - TIFFRGBAImageEnd(&img); - TIFFClose(tiff); - return -1; + goto decodeycbcr_err; } /* overflow check for row byte size */ if (INT_MAX / 4 < img.width) { state->errcode = IMAGING_CODEC_MEMORY; - TIFFRGBAImageEnd(&img); - TIFFClose(tiff); - return -1; + goto decodeycbcr_err; } // TiffRGBAImages are 32bits/pixel. @@ -291,9 +229,7 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { /* overflow check for realloc */ if (INT_MAX / row_byte_size < rows_per_strip) { state->errcode = IMAGING_CODEC_MEMORY; - TIFFRGBAImageEnd(&img); - TIFFClose(tiff); - return -1; + goto decodeycbcr_err; } state->bytes = rows_per_strip * row_byte_size; @@ -305,9 +241,7 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; - TIFFRGBAImageEnd(&img); - TIFFClose(tiff); - return -1; + goto decodeycbcr_err; } state->buffer = new_data; @@ -319,9 +253,7 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { if (TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read) == -1) { TRACE(("Decode Error, y: %d\n", state->y )); state->errcode = IMAGING_CODEC_BROKEN; - TIFFRGBAImageEnd(&img); - TIFFClose(tiff); - return -1; + goto decodeycbcr_err; } TRACE(("Decoded strip for row %d \n", state->y)); @@ -339,7 +271,12 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { state->xsize); } } - TIFFRGBAImageEnd(&img); + + decodeycbcr_err: + TIFFRGBAImageEnd(&img); + if (state->errcode != 0) { + return -1; + } return 0; } @@ -361,7 +298,6 @@ int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { /* overflow check for realloc */ if (INT_MAX / row_byte_size < rows_per_strip) { state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); return -1; } @@ -375,7 +311,6 @@ int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { // call to TIFFReadEncodedStrip ... state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); return -1; } @@ -384,7 +319,6 @@ int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); return -1; } @@ -394,7 +328,6 @@ int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { if (TIFFReadEncodedStrip(tiff, TIFFComputeStrip(tiff, state->y, 0), (tdata_t)state->buffer, -1) == -1) { TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, state->y, 0))); state->errcode = IMAGING_CODEC_BROKEN; - TIFFClose(tiff); return -1; } @@ -423,7 +356,6 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ TIFF *tiff; uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR int isYCbCr = 0; - int ret; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ @@ -480,7 +412,7 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv){ TRACE(("error in TIFFSetSubDirectory")); - return -1; + goto decode_err; } } @@ -490,7 +422,7 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ if (TIFFIsTiled(tiff)) { INT32 x, y, tile_y; - UINT32 tile_width, tile_length, current_tile_width, row_byte_size; + UINT32 tile_width, tile_length, current_tile_length, current_line, current_tile_width, row_byte_size; UINT8 *new_data; TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); @@ -499,18 +431,26 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ /* overflow check for row_byte_size calculation */ if ((UINT32) INT_MAX / state->bits < tile_width) { state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); - return -1; + goto decode_err; } - // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size - row_byte_size = (tile_width * state->bits + 7) / 8; + + if (isYCbCr) { + row_byte_size = tile_width * 4; + /* sanity check, we use this value in shuffle below */ + if (im->pixelsize != 4) { + state->errcode = IMAGING_CODEC_BROKEN; + goto decode_err; + } + } else { + // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size + row_byte_size = (tile_width * state->bits + 7) / 8; + } /* overflow check for realloc */ if (INT_MAX / row_byte_size < tile_length) { state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); - return -1; + goto decode_err; } state->bytes = row_byte_size * tile_length; @@ -518,8 +458,7 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ if (TIFFTileSize(tiff) > state->bytes) { // If the strip size as expected by LibTiff isn't what we're expecting, abort. state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); - return -1; + goto decode_err; } /* realloc to fit whole tile */ @@ -527,8 +466,7 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; - TIFFClose(tiff); - return -1; + goto decode_err; } state->buffer = new_data; @@ -537,26 +475,46 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ for (y = state->yoff; y < state->ysize; y += tile_length) { for (x = state->xoff; x < state->xsize; x += tile_width) { - if (ReadTile(tiff, x, y, (UINT32*) state->buffer) == -1) { - TRACE(("Decode Error, Tile at %dx%d\n", x, y)); - state->errcode = IMAGING_CODEC_BROKEN; - TIFFClose(tiff); - return -1; + if (isYCbCr) { + /* To avoid dealing with YCbCr subsampling, let libtiff handle it */ + if (!TIFFReadRGBATile(tiff, x, y, (UINT32 *)state->buffer)) { + TRACE(("Decode Error, Tile at %dx%d\n", x, y)); + state->errcode = IMAGING_CODEC_BROKEN; + goto decode_err; + } + } else { + if (TIFFReadTile(tiff, (tdata_t)state->buffer, x, y, 0, 0) == -1) { + TRACE(("Decode Error, Tile at %dx%d\n", x, y)); + state->errcode = IMAGING_CODEC_BROKEN; + goto decode_err; + } } TRACE(("Read tile at %dx%d; \n\n", x, y)); current_tile_width = min((INT32) tile_width, state->xsize - x); - + current_tile_length = min((INT32) tile_length, state->ysize - y); // iterate over each line in the tile and stuff data into image - for (tile_y = 0; tile_y < min((INT32) tile_length, state->ysize - y); tile_y++) { + for (tile_y = 0; tile_y < current_tile_length; tile_y++) { TRACE(("Writing tile data at %dx%d using tile_width: %d; \n", tile_y + y, x, current_tile_width)); // UINT8 * bbb = state->buffer + tile_y * row_byte_size; // TRACE(("chars: %x%x%x%x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); + /* + * For some reason the TIFFReadRGBATile() function + * chooses the lower left corner as the origin. + * Vertically mirror by shuffling the scanlines + * backwards + */ + if (isYCbCr) { + current_line = tile_length - tile_y - 1; + } else { + current_line = tile_y; + } + state->shuffle((UINT8*) im->image[tile_y + y] + x * im->pixelsize, - state->buffer + tile_y * row_byte_size, + state->buffer + current_line * row_byte_size, current_tile_width ); } @@ -564,14 +522,14 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ } } else { if (!isYCbCr) { - ret = _decodeStrip(im, state, tiff); + _decodeStrip(im, state, tiff); } else { - ret = _decodeStripYCbCr(im, state, tiff); + _decodeStripYCbCr(im, state, tiff); } - if (ret == -1) { return ret; } } + decode_err: TIFFClose(tiff); TRACE(("Done Decoding, Returning \n")); // Returning -1 here to force ImageFile.load to break, rather than From 2f409261eb1228e166868f8f0b5da5cda52e55bf Mon Sep 17 00:00:00 2001 From: Eric Soroos Date: Thu, 17 Dec 2020 00:17:53 +0100 Subject: [PATCH 175/186] Fix for CVE CVE-2020-35655 - Read Overflow in PCX Decoding. * Don't trust the image to specify a buffer size --- Tests/images/ossfuzz-4836216264589312.pcx | Bin 0 -> 129 bytes Tests/test_image.py | 27 ++++++++++++---------- src/PIL/PcxImagePlugin.py | 9 ++++++-- 3 files changed, 22 insertions(+), 14 deletions(-) create mode 100644 Tests/images/ossfuzz-4836216264589312.pcx diff --git a/Tests/images/ossfuzz-4836216264589312.pcx b/Tests/images/ossfuzz-4836216264589312.pcx new file mode 100644 index 0000000000000000000000000000000000000000..fdde9716a0cbd84900f9499c2f8c6d13067d456a GIT binary patch literal 129 wcmd;LP+(+WP*4Ej|6rg11t1QLjY`90z%&y`Cj@}_2tCMbm "7.0.0" - def test_overrun(self): - """For overrun completeness, test as: - valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c - """ - for file in [ + @pytest.mark.parametrize("path", [ "fli_overrun.bin", "sgi_overrun.bin", "sgi_overrun_expandrow.bin", "sgi_overrun_expandrow2.bin", "pcx_overrun.bin", "pcx_overrun2.bin", + "ossfuzz-4836216264589312.pcx", "01r_00.pcx", - ]: - with Image.open(os.path.join("Tests/images", file)) as im: - try: - im.load() - assert False - except OSError as e: - assert str(e) == "buffer overrun when reading image file" + ]) + def test_overrun(self, path): + """For overrun completeness, test as: + valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c + """ + with Image.open(os.path.join("Tests/images", path)) as im: + try: + im.load() + assert False + except OSError as e: + assert (str(e) == "buffer overrun when reading image file" or + "image file is truncated" in str(e)) + def test_fli_overrun2(self): with Image.open("Tests/images/fli_overrun2.bin") as im: try: im.seek(1) diff --git a/src/PIL/PcxImagePlugin.py b/src/PIL/PcxImagePlugin.py index b337b7dde..a24d44b42 100644 --- a/src/PIL/PcxImagePlugin.py +++ b/src/PIL/PcxImagePlugin.py @@ -66,13 +66,13 @@ class PcxImageFile(ImageFile.ImageFile): version = s[1] bits = s[3] planes = s[65] - stride = i16(s, 66) + ignored_stride = i16(s, 66) logger.debug( "PCX version %s, bits %s, planes %s, stride %s", version, bits, planes, - stride, + ignored_stride, ) self.info["dpi"] = i16(s, 12), i16(s, 14) @@ -110,6 +110,11 @@ class PcxImageFile(ImageFile.ImageFile): self.mode = mode self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] + # don't trust the passed in stride. Calculate for ourselves. + # CVE-2020-35655 + stride = (self._size[0] * bits + 7) // 8 + stride += stride % 2 + bbox = (0, 0) + self.size logger.debug("size: %sx%s", *self.size) From 903c67353da1dc3a59d5367338e76101a9cfb4b1 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 20:41:17 +1100 Subject: [PATCH 176/186] Lint fix --- Tests/test_image.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Tests/test_image.py b/Tests/test_image.py index d91f1c263..f2a1917e8 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -775,7 +775,9 @@ class TestImage: with pytest.warns(DeprecationWarning): assert test_module.PILLOW_VERSION > "7.0.0" - @pytest.mark.parametrize("path", [ + @pytest.mark.parametrize( + "path", + [ "fli_overrun.bin", "sgi_overrun.bin", "sgi_overrun_expandrow.bin", @@ -784,7 +786,8 @@ class TestImage: "pcx_overrun2.bin", "ossfuzz-4836216264589312.pcx", "01r_00.pcx", - ]) + ], + ) def test_overrun(self, path): """For overrun completeness, test as: valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c @@ -794,8 +797,10 @@ class TestImage: im.load() assert False except OSError as e: - assert (str(e) == "buffer overrun when reading image file" or - "image file is truncated" in str(e)) + buffer_overrun = str(e) == "buffer overrun when reading image file" + truncated = "image file is truncated" in str(e) + + assert buffer_overrun or truncated def test_fli_overrun2(self): with Image.open("Tests/images/fli_overrun2.bin") as im: From 95f99d52c404dc467388bee351c41de15895cf55 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 21:27:50 +1100 Subject: [PATCH 177/186] Document CVE fixes [ci skip] --- CHANGES.rst | 9 +++++++++ docs/releasenotes/8.1.0.rst | 33 +++++++++++++++++++++++---------- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 7a21cf440..668aaa7c5 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,15 @@ Changelog (Pillow) 8.1.0 (unreleased) ------------------ +- Fix TIFF OOB Write error. CVE-2020-35654 #5175 + [wiredfool] + +- Fix for Read Overflow in PCX Decoding. CVE-2020-35653 #5174 + [wiredfool, radarhere] + +- Fix for SGI Decode buffer overrun. CVE-2020-35655 #5173 + [wiredfool, radarhere] + - Fix OOB Read when saving GIF of xsize=1 #5149 [wiredfool] diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index da5f95405..84ec8ae76 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -20,14 +20,6 @@ Makefile The 'install-venv' target has been deprecated. -API Changes -=========== - -TODO -^^^^ - -TODO - API Additions ============= @@ -44,8 +36,29 @@ already exists for the ICNS format. Security ======== -An out-of-bounds read when saving TIFFs with custom metadata through libtiff has been -fixed, as well as when saving a GIF of 1px width. +This release includes security fixes. + +* An out-of-bounds read when saving TIFFs with custom metadata through libtiff +* An out-of-bounds read when saving a GIF of 1px width +* :cve:`CVE-2020-35653` Buffer Read Overrun in PCX Decoding. + +The PCX Image decoder used the reported image stride to calculate the row buffer, +rather than calculating it from the image size. This issue dates back to the PIL fork. +Thanks to Google's OSS-Fuzz project for finding this. + +* :cve:`CVE-2020-35654` Fix TIFF OOB Write error + +OOB Write in TiffDecode.c when reading corrupt YCbCr files in some LibTiff versions +(4.1.0/Ubuntu 20.04, but not 4.0.9/Ubuntu 18.04). In some cases libtiff's +interpretation of the file is different when reading in RGBA mode, leading to an Out of +bounds write in TiffDecode.c. This potentially affects Pillow versions from 6.0.0 to +8.0.1, depending on the version of LibTiff. This was reported through Tidelift. + +* :cve:`CVE-2020-35655` Fix for SGI Decode buffer overrun + +4 Byte Read Overflow in SGIRleDecode.c, where the code was not correctly checking the +offsets and length tables. Independently reported through Tidelift and Google's OSS-Fuzz. +This vulnerability covers Pillow versions 4.3.0->8.0.1. Dependencies ^^^^^^^^^^^^ From d88fdcda0699c647ba7a0befca97f08134fe6627 Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Sat, 2 Jan 2021 22:00:35 +1100 Subject: [PATCH 178/186] Updated capitalisation [ci skip] Co-authored-by: Hugo van Kemenade --- docs/releasenotes/8.1.0.rst | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index 84ec8ae76..78c3e914a 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -38,25 +38,25 @@ Security This release includes security fixes. -* An out-of-bounds read when saving TIFFs with custom metadata through libtiff +* An out-of-bounds read when saving TIFFs with custom metadata through LibTIFF * An out-of-bounds read when saving a GIF of 1px width -* :cve:`CVE-2020-35653` Buffer Read Overrun in PCX Decoding. +* :cve:`CVE-2020-35653` Buffer read overrun in PCX decoding -The PCX Image decoder used the reported image stride to calculate the row buffer, +The PCX image decoder used the reported image stride to calculate the row buffer, rather than calculating it from the image size. This issue dates back to the PIL fork. Thanks to Google's OSS-Fuzz project for finding this. * :cve:`CVE-2020-35654` Fix TIFF OOB Write error -OOB Write in TiffDecode.c when reading corrupt YCbCr files in some LibTiff versions -(4.1.0/Ubuntu 20.04, but not 4.0.9/Ubuntu 18.04). In some cases libtiff's +OOB Write in TiffDecode.c when reading corrupt YCbCr files in some LibTIFF versions +(4.1.0/Ubuntu 20.04, but not 4.0.9/Ubuntu 18.04). In some cases LibTIFF's interpretation of the file is different when reading in RGBA mode, leading to an Out of bounds write in TiffDecode.c. This potentially affects Pillow versions from 6.0.0 to -8.0.1, depending on the version of LibTiff. This was reported through Tidelift. +8.0.1, depending on the version of LibTIFF. This was reported through Tidelift. * :cve:`CVE-2020-35655` Fix for SGI Decode buffer overrun -4 Byte Read Overflow in SGIRleDecode.c, where the code was not correctly checking the +4 byte read overflow in SGIRleDecode.c, where the code was not correctly checking the offsets and length tables. Independently reported through Tidelift and Google's OSS-Fuzz. This vulnerability covers Pillow versions 4.3.0->8.0.1. From 2711549503be2f665888c405eabaa9e8786d5ece Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 22:07:03 +1100 Subject: [PATCH 179/186] Link to TideLift [ci skip] --- docs/releasenotes/8.1.0.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index 78c3e914a..e5228ac8c 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -52,13 +52,15 @@ OOB Write in TiffDecode.c when reading corrupt YCbCr files in some LibTIFF versi (4.1.0/Ubuntu 20.04, but not 4.0.9/Ubuntu 18.04). In some cases LibTIFF's interpretation of the file is different when reading in RGBA mode, leading to an Out of bounds write in TiffDecode.c. This potentially affects Pillow versions from 6.0.0 to -8.0.1, depending on the version of LibTIFF. This was reported through Tidelift. +8.0.1, depending on the version of LibTIFF. This was reported through `Tidelift`_. * :cve:`CVE-2020-35655` Fix for SGI Decode buffer overrun 4 byte read overflow in SGIRleDecode.c, where the code was not correctly checking the -offsets and length tables. Independently reported through Tidelift and Google's OSS-Fuzz. -This vulnerability covers Pillow versions 4.3.0->8.0.1. +offsets and length tables. Independently reported through `Tidelift`_ and Google's +OSS-Fuzz. This vulnerability covers Pillow versions 4.3.0->8.0.1. + +.. _Tidelift: https://tidelift.com/subscription/pkg/pypi-pillow?utm_source=pillow&utm_medium=referral&utm_campaign=docs Dependencies ^^^^^^^^^^^^ From cd316feead0bba5f2e949a9cd4991ca7fe1d0615 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 22:09:07 +1100 Subject: [PATCH 180/186] Link to OSS-Fuzz [ci skip] --- docs/releasenotes/8.1.0.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/releasenotes/8.1.0.rst b/docs/releasenotes/8.1.0.rst index e5228ac8c..90847af81 100644 --- a/docs/releasenotes/8.1.0.rst +++ b/docs/releasenotes/8.1.0.rst @@ -44,7 +44,7 @@ This release includes security fixes. The PCX image decoder used the reported image stride to calculate the row buffer, rather than calculating it from the image size. This issue dates back to the PIL fork. -Thanks to Google's OSS-Fuzz project for finding this. +Thanks to Google's `OSS-Fuzz`_ project for finding this. * :cve:`CVE-2020-35654` Fix TIFF OOB Write error @@ -58,9 +58,10 @@ bounds write in TiffDecode.c. This potentially affects Pillow versions from 6.0. 4 byte read overflow in SGIRleDecode.c, where the code was not correctly checking the offsets and length tables. Independently reported through `Tidelift`_ and Google's -OSS-Fuzz. This vulnerability covers Pillow versions 4.3.0->8.0.1. +`OSS-Fuzz`_. This vulnerability covers Pillow versions 4.3.0->8.0.1. .. _Tidelift: https://tidelift.com/subscription/pkg/pypi-pillow?utm_source=pillow&utm_medium=referral&utm_campaign=docs +.. _OSS-Fuzz: https://github.com/google/oss-fuzz Dependencies ^^^^^^^^^^^^ From a99128052c472ed94f60b2b13548c0ee6dbf3c7d Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 22:38:16 +1100 Subject: [PATCH 181/186] Update CHANGES.rst [ci skip] --- CHANGES.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGES.rst b/CHANGES.rst index 668aaa7c5..6296c09c7 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -2,7 +2,7 @@ Changelog (Pillow) ================== -8.1.0 (unreleased) +8.1.0 (2020-01-02) ------------------ - Fix TIFF OOB Write error. CVE-2020-35654 #5175 From fcc42e0d344146ee9d265d1f43c094ce5a0ec4cf Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 2 Jan 2021 22:39:02 +1100 Subject: [PATCH 182/186] 8.1.0 version bump --- src/PIL/_version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PIL/_version.py b/src/PIL/_version.py index 4fcb50190..8877e09d2 100644 --- a/src/PIL/_version.py +++ b/src/PIL/_version.py @@ -1,2 +1,2 @@ # Master version for Pillow -__version__ = "8.1.0.dev0" +__version__ = "8.1.0" From 56e7d1fd9bd5754f3a0c8e3909fd217cd16c3058 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 3 Jan 2021 07:14:59 +1100 Subject: [PATCH 183/186] 8.2.0.dev0 version bump --- src/PIL/_version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PIL/_version.py b/src/PIL/_version.py index 8877e09d2..20e8754a4 100644 --- a/src/PIL/_version.py +++ b/src/PIL/_version.py @@ -1,2 +1,2 @@ # Master version for Pillow -__version__ = "8.1.0" +__version__ = "8.2.0.dev0" From 5d968accf5db5d45fceeb68b9cbc4af44be0f6b4 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 9 Jul 2020 15:32:14 +0300 Subject: [PATCH 184/186] Add clang-format style that approximates Python's PEP 7 from pganssle/zoneinfo --- .clang-format | 18 ++++++++++++++++++ MANIFEST.in | 1 + 2 files changed, 19 insertions(+) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..e7fc90e37 --- /dev/null +++ b/.clang-format @@ -0,0 +1,18 @@ +# A clang-format style that approximates Python's PEP 7 +# Useful for IDE integration +BasedOnStyle: Google +AlwaysBreakAfterReturnType: All +AllowShortIfStatementsOnASingleLine: false +AlignAfterOpenBracket: Align +BreakBeforeBraces: Stroustrup +ColumnLimit: 79 +DerivePointerAlignment: false +IndentWidth: 4 +Language: Cpp +PointerAlignment: Right +ReflowComments: true +SortIncludes: false +SpaceBeforeParens: ControlStatements +SpacesInParentheses: false +TabWidth: 4 +UseTab: Never diff --git a/MANIFEST.in b/MANIFEST.in index f5d367fdd..e9aaa8318 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -18,6 +18,7 @@ graft docs # build/src control detritus exclude .appveyor.yml +exclude .clang-format exclude .coveragerc exclude .editorconfig exclude .readthedocs.yml From e2d00f8cf88e2f0d6c8597cff24433876eb29471 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 9 Jul 2020 15:59:18 +0300 Subject: [PATCH 185/186] Adjust clang-format style --- .clang-format | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.clang-format b/.clang-format index e7fc90e37..be32e6d1a 100644 --- a/.clang-format +++ b/.clang-format @@ -3,9 +3,11 @@ BasedOnStyle: Google AlwaysBreakAfterReturnType: All AllowShortIfStatementsOnASingleLine: false -AlignAfterOpenBracket: Align -BreakBeforeBraces: Stroustrup -ColumnLimit: 79 +AlignAfterOpenBracket: AlwaysBreak +BinPackArguments: false +BinPackParameters: false +BreakBeforeBraces: Attach +ColumnLimit: 88 DerivePointerAlignment: false IndentWidth: 4 Language: Cpp From 46b7e86bab79450ec0a2866c6c0c679afb659d17 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 3 Jan 2021 14:17:51 +1100 Subject: [PATCH 186/186] Format with ClangFormat --- src/Tk/_tkmini.h | 54 +- src/Tk/tkImaging.c | 194 +- src/_imaging.c | 2949 +++++++++++++++---------------- src/_imagingcms.c | 1065 +++++------ src/_imagingft.c | 985 ++++++----- src/_imagingmath.c | 149 +- src/_imagingmorph.c | 157 +- src/_imagingtk.c | 33 +- src/_webp.c | 645 ++++--- src/decode.c | 465 +++-- src/display.c | 564 +++--- src/encode.c | 645 +++---- src/libImaging/Access.c | 136 +- src/libImaging/AlphaComposite.c | 47 +- src/libImaging/Bands.c | 130 +- src/libImaging/BcnDecode.c | 438 +++-- src/libImaging/Bit.h | 3 +- src/libImaging/BitDecode.c | 42 +- src/libImaging/Blend.c | 37 +- src/libImaging/BoxBlur.c | 169 +- src/libImaging/Chops.c | 161 +- src/libImaging/ColorLUT.c | 135 +- src/libImaging/Convert.c | 993 +++++------ src/libImaging/ConvertYCbCr.c | 620 ++++--- src/libImaging/Copy.c | 13 +- src/libImaging/Crop.c | 9 +- src/libImaging/Dib.c | 134 +- src/libImaging/Draw.c | 1342 +++++++------- src/libImaging/Effects.c | 82 +- src/libImaging/EpsEncode.c | 24 +- src/libImaging/Except.c | 26 +- src/libImaging/File.c | 23 +- src/libImaging/Fill.c | 21 +- src/libImaging/Filter.c | 332 ++-- src/libImaging/FliDecode.c | 75 +- src/libImaging/Geometry.c | 935 +++++----- src/libImaging/GetBBox.c | 278 ++- src/libImaging/Gif.h | 21 +- src/libImaging/GifDecode.c | 106 +- src/libImaging/GifEncode.c | 189 +- src/libImaging/HexDecode.c | 25 +- src/libImaging/Histo.c | 47 +- src/libImaging/ImDib.h | 23 +- src/libImaging/ImPlatform.h | 11 +- src/libImaging/Imaging.h | 803 +++++---- src/libImaging/ImagingUtils.h | 47 +- src/libImaging/Jpeg.h | 22 +- src/libImaging/Jpeg2K.h | 33 +- src/libImaging/Jpeg2KDecode.c | 474 ++--- src/libImaging/Jpeg2KEncode.c | 182 +- src/libImaging/JpegDecode.c | 283 ++- src/libImaging/JpegEncode.c | 126 +- src/libImaging/Matrix.c | 33 +- src/libImaging/ModeFilter.c | 14 +- src/libImaging/Negative.c | 8 +- src/libImaging/Offset.c | 21 +- src/libImaging/Pack.c | 473 +++-- src/libImaging/PackDecode.c | 33 +- src/libImaging/Palette.c | 139 +- src/libImaging/Paste.c | 346 ++-- src/libImaging/PcdDecode.c | 27 +- src/libImaging/PcxDecode.c | 34 +- src/libImaging/PcxEncode.c | 216 ++- src/libImaging/Point.c | 205 +-- src/libImaging/Quant.c | 2527 +++++++++++++------------- src/libImaging/QuantHash.c | 515 +++--- src/libImaging/QuantHash.h | 51 +- src/libImaging/QuantHeap.c | 224 +-- src/libImaging/QuantHeap.h | 16 +- src/libImaging/QuantOctree.c | 760 ++++---- src/libImaging/QuantOctree.h | 9 +- src/libImaging/QuantPngQuant.c | 47 +- src/libImaging/QuantPngQuant.h | 4 +- src/libImaging/QuantTypes.h | 14 +- src/libImaging/RankFilter.c | 132 +- src/libImaging/Raw.h | 1 - src/libImaging/RawDecode.c | 24 +- src/libImaging/RawEncode.c | 19 +- src/libImaging/Reduce.c | 1405 ++++++++------- src/libImaging/Resample.c | 452 +++-- src/libImaging/Sgi.h | 1 - src/libImaging/SgiRleDecode.c | 93 +- src/libImaging/Storage.c | 163 +- src/libImaging/SunRleDecode.c | 28 +- src/libImaging/TgaRleDecode.c | 29 +- src/libImaging/TgaRleEncode.c | 21 +- src/libImaging/TiffDecode.c | 470 +++-- src/libImaging/TiffDecode.h | 32 +- src/libImaging/Unpack.c | 1248 +++++++------ src/libImaging/UnpackYCC.c | 223 +-- src/libImaging/UnsharpMask.c | 39 +- src/libImaging/XbmDecode.c | 25 +- src/libImaging/XbmEncode.c | 51 +- src/libImaging/ZipCodecs.h | 28 +- src/libImaging/ZipDecode.c | 207 ++- src/libImaging/ZipEncode.c | 412 +++-- src/libImaging/codec_fd.c | 19 +- src/libImaging/raqm.h | 58 +- src/map.c | 182 +- src/outline.c | 112 +- src/path.c | 294 ++- 101 files changed, 14097 insertions(+), 13889 deletions(-) diff --git a/src/Tk/_tkmini.h b/src/Tk/_tkmini.h index adc470532..b6945eb1a 100644 --- a/src/Tk/_tkmini.h +++ b/src/Tk/_tkmini.h @@ -79,18 +79,20 @@ typedef struct Tcl_Interp Tcl_Interp; typedef struct Tcl_Command_ *Tcl_Command; typedef void *ClientData; -typedef int (Tcl_CmdProc) (ClientData clientData, Tcl_Interp - *interp, int argc, const char *argv[]); -typedef void (Tcl_CmdDeleteProc) (ClientData clientData); +typedef int(Tcl_CmdProc)( + ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]); +typedef void(Tcl_CmdDeleteProc)(ClientData clientData); /* Typedefs derived from function signatures in Tcl header */ /* Tcl_CreateCommand */ -typedef Tcl_Command (*Tcl_CreateCommand_t)(Tcl_Interp *interp, - const char *cmdName, Tcl_CmdProc *proc, - ClientData clientData, - Tcl_CmdDeleteProc *deleteProc); +typedef Tcl_Command (*Tcl_CreateCommand_t)( + Tcl_Interp *interp, + const char *cmdName, + Tcl_CmdProc *proc, + ClientData clientData, + Tcl_CmdDeleteProc *deleteProc); /* Tcl_AppendResult */ -typedef void (*Tcl_AppendResult_t) (Tcl_Interp *interp, ...); +typedef void (*Tcl_AppendResult_t)(Tcl_Interp *interp, ...); /* Tk header excerpts */ @@ -107,8 +109,7 @@ typedef struct Tk_Window_ *Tk_Window; typedef void *Tk_PhotoHandle; -typedef struct Tk_PhotoImageBlock -{ +typedef struct Tk_PhotoImageBlock { unsigned char *pixelPtr; int width; int height; @@ -119,23 +120,30 @@ typedef struct Tk_PhotoImageBlock /* Typedefs derived from function signatures in Tk header */ /* Tk_PhotoPutBlock for Tk <= 8.4 */ -typedef void (*Tk_PhotoPutBlock_84_t) (Tk_PhotoHandle handle, - Tk_PhotoImageBlock *blockPtr, int x, int y, - int width, int height, int compRule); +typedef void (*Tk_PhotoPutBlock_84_t)( + Tk_PhotoHandle handle, + Tk_PhotoImageBlock *blockPtr, + int x, + int y, + int width, + int height, + int compRule); /* Tk_PhotoPutBlock for Tk >= 8.5 */ -typedef int (*Tk_PhotoPutBlock_85_t) (Tcl_Interp * interp, - Tk_PhotoHandle handle, - Tk_PhotoImageBlock * blockPtr, int x, int y, - int width, int height, int compRule); +typedef int (*Tk_PhotoPutBlock_85_t)( + Tcl_Interp *interp, + Tk_PhotoHandle handle, + Tk_PhotoImageBlock *blockPtr, + int x, + int y, + int width, + int height, + int compRule); /* Tk_PhotoSetSize for Tk <= 8.4 */ -typedef void (*Tk_PhotoSetSize_84_t) (Tk_PhotoHandle handle, - int width, int height); +typedef void (*Tk_PhotoSetSize_84_t)(Tk_PhotoHandle handle, int width, int height); /* Tk_FindPhoto */ -typedef Tk_PhotoHandle (*Tk_FindPhoto_t) (Tcl_Interp *interp, - const char *imageName); +typedef Tk_PhotoHandle (*Tk_FindPhoto_t)(Tcl_Interp *interp, const char *imageName); /* Tk_PhotoGetImage */ -typedef int (*Tk_PhotoGetImage_t) (Tk_PhotoHandle handle, - Tk_PhotoImageBlock * blockPtr); +typedef int (*Tk_PhotoGetImage_t)(Tk_PhotoHandle handle, Tk_PhotoImageBlock *blockPtr); /* * end block for C++ diff --git a/src/Tk/tkImaging.c b/src/Tk/tkImaging.c index 5df3abb72..1c6c5f34a 100644 --- a/src/Tk/tkImaging.c +++ b/src/Tk/tkImaging.c @@ -58,8 +58,7 @@ static Tk_PhotoSetSize_84_t TK_PHOTO_SET_SIZE_84; static Tk_PhotoPutBlock_85_t TK_PHOTO_PUT_BLOCK_85; static Imaging -ImagingFind(const char* name) -{ +ImagingFind(const char *name) { Py_ssize_t id; /* FIXME: use CObject instead? */ @@ -72,41 +71,37 @@ ImagingFind(const char* name) return NULL; } - return (Imaging) id; + return (Imaging)id; } - static int -PyImagingPhotoPut(ClientData clientdata, Tcl_Interp* interp, - int argc, const char **argv) -{ +PyImagingPhotoPut( + ClientData clientdata, Tcl_Interp *interp, int argc, const char **argv) { Imaging im; Tk_PhotoHandle photo; Tk_PhotoImageBlock block; if (argc != 3) { - TCL_APPEND_RESULT(interp, "usage: ", argv[0], - " destPhoto srcImage", (char *) NULL); + TCL_APPEND_RESULT( + interp, "usage: ", argv[0], " destPhoto srcImage", (char *)NULL); return TCL_ERROR; } /* get Tcl PhotoImage handle */ photo = TK_FIND_PHOTO(interp, argv[1]); if (photo == NULL) { - TCL_APPEND_RESULT( - interp, "destination photo must exist", (char *) NULL - ); + TCL_APPEND_RESULT(interp, "destination photo must exist", (char *)NULL); return TCL_ERROR; } /* get PIL Image handle */ im = ImagingFind(argv[2]); if (!im) { - TCL_APPEND_RESULT(interp, "bad name", (char*) NULL); + TCL_APPEND_RESULT(interp, "bad name", (char *)NULL); return TCL_ERROR; } if (!im->block) { - TCL_APPEND_RESULT(interp, "bad display memory", (char*) NULL); + TCL_APPEND_RESULT(interp, "bad display memory", (char *)NULL); return TCL_ERROR; } @@ -126,18 +121,18 @@ PyImagingPhotoPut(ClientData clientdata, Tcl_Interp* interp, block.offset[3] = 0; /* no alpha */ } } else { - TCL_APPEND_RESULT(interp, "Bad mode", (char*) NULL); + TCL_APPEND_RESULT(interp, "Bad mode", (char *)NULL); return TCL_ERROR; } block.width = im->xsize; block.height = im->ysize; block.pitch = im->linesize; - block.pixelPtr = (unsigned char*) im->block; + block.pixelPtr = (unsigned char *)im->block; if (TK_LT_85) { /* Tk 8.4 */ - TK_PHOTO_PUT_BLOCK_84(photo, &block, 0, 0, block.width, block.height, - TK_PHOTO_COMPOSITE_SET); + TK_PHOTO_PUT_BLOCK_84( + photo, &block, 0, 0, block.width, block.height, TK_PHOTO_COMPOSITE_SET); if (strcmp(im->mode, "RGBA") == 0) { /* Tk workaround: we need apply ToggleComplexAlphaIfNeeded */ /* (fixed in Tk 8.5a3) */ @@ -145,50 +140,54 @@ PyImagingPhotoPut(ClientData clientdata, Tcl_Interp* interp, } } else { /* Tk >=8.5 */ - TK_PHOTO_PUT_BLOCK_85(interp, photo, &block, 0, 0, block.width, - block.height, TK_PHOTO_COMPOSITE_SET); + TK_PHOTO_PUT_BLOCK_85( + interp, + photo, + &block, + 0, + 0, + block.width, + block.height, + TK_PHOTO_COMPOSITE_SET); } return TCL_OK; } static int -PyImagingPhotoGet(ClientData clientdata, Tcl_Interp* interp, - int argc, const char **argv) -{ +PyImagingPhotoGet( + ClientData clientdata, Tcl_Interp *interp, int argc, const char **argv) { Imaging im; Tk_PhotoHandle photo; Tk_PhotoImageBlock block; int x, y, z; if (argc != 3) { - TCL_APPEND_RESULT(interp, "usage: ", argv[0], - " srcPhoto destImage", (char *) NULL); + TCL_APPEND_RESULT( + interp, "usage: ", argv[0], " srcPhoto destImage", (char *)NULL); return TCL_ERROR; } /* get Tcl PhotoImage handle */ photo = TK_FIND_PHOTO(interp, argv[1]); if (photo == NULL) { - TCL_APPEND_RESULT( - interp, "source photo must exist", (char *) NULL - ); + TCL_APPEND_RESULT(interp, "source photo must exist", (char *)NULL); return TCL_ERROR; } /* get PIL Image handle */ im = ImagingFind(argv[2]); if (!im) { - TCL_APPEND_RESULT(interp, "bad name", (char*) NULL); + TCL_APPEND_RESULT(interp, "bad name", (char *)NULL); return TCL_ERROR; } TK_PHOTO_GET_IMAGE(photo, &block); for (y = 0; y < block.height; y++) { - UINT8* out = (UINT8*)im->image32[y]; + UINT8 *out = (UINT8 *)im->image32[y]; for (x = 0; x < block.pitch; x += block.pixelSize) { - for (z=0; z < block.pixelSize; z++) { + for (z = 0; z < block.pixelSize; z++) { int offset = block.offset[z]; out[x + offset] = block.pixelPtr[y * block.pitch + x + offset]; } @@ -198,14 +197,20 @@ PyImagingPhotoGet(ClientData clientdata, Tcl_Interp* interp, return TCL_OK; } - void -TkImaging_Init(Tcl_Interp* interp) -{ - TCL_CREATE_COMMAND(interp, "PyImagingPhoto", PyImagingPhotoPut, - (ClientData) 0, (Tcl_CmdDeleteProc*) NULL); - TCL_CREATE_COMMAND(interp, "PyImagingPhotoGet", PyImagingPhotoGet, - (ClientData) 0, (Tcl_CmdDeleteProc*) NULL); +TkImaging_Init(Tcl_Interp *interp) { + TCL_CREATE_COMMAND( + interp, + "PyImagingPhoto", + PyImagingPhotoPut, + (ClientData)0, + (Tcl_CmdDeleteProc *)NULL); + TCL_CREATE_COMMAND( + interp, + "PyImagingPhotoGet", + PyImagingPhotoGet, + (ClientData)0, + (Tcl_CmdDeleteProc *)NULL); } /* @@ -230,13 +235,13 @@ TkImaging_Init(Tcl_Interp* interp) #define TKINTER_PKG "tkinter" -FARPROC _dfunc(HMODULE lib_handle, const char *func_name) -{ +FARPROC +_dfunc(HMODULE lib_handle, const char *func_name) { /* * Load function `func_name` from `lib_handle`. * Set Python exception if we can't find `func_name` in `lib_handle`. * Returns function pointer or NULL if not present. - */ + */ char message[100]; @@ -248,24 +253,26 @@ FARPROC _dfunc(HMODULE lib_handle, const char *func_name) return func; } -int get_tcl(HMODULE hMod) -{ +int +get_tcl(HMODULE hMod) { /* * Try to fill Tcl global vars with function pointers. Return 0 for no * functions found, 1 for all functions found, -1 for some but not all * functions found. */ - if ((TCL_CREATE_COMMAND = (Tcl_CreateCommand_t) - GetProcAddress(hMod, "Tcl_CreateCommand")) == NULL) { + if ((TCL_CREATE_COMMAND = + (Tcl_CreateCommand_t)GetProcAddress(hMod, "Tcl_CreateCommand")) == NULL) { return 0; /* Maybe not Tcl module */ } - return ((TCL_APPEND_RESULT = (Tcl_AppendResult_t) _dfunc(hMod, - "Tcl_AppendResult")) == NULL) ? -1 : 1; + return ((TCL_APPEND_RESULT = + (Tcl_AppendResult_t)_dfunc(hMod, "Tcl_AppendResult")) == NULL) + ? -1 + : 1; } -int get_tk(HMODULE hMod) -{ +int +get_tk(HMODULE hMod) { /* * Try to fill Tk global vars with function pointers. Return 0 for no * functions found, 1 for all functions found, -1 for some but not all @@ -273,26 +280,31 @@ int get_tk(HMODULE hMod) */ FARPROC func = GetProcAddress(hMod, "Tk_PhotoPutBlock"); - if (func == NULL) { /* Maybe not Tk module */ + if (func == NULL) { /* Maybe not Tk module */ return 0; } - if ((TK_PHOTO_GET_IMAGE = (Tk_PhotoGetImage_t) - _dfunc(hMod, "Tk_PhotoGetImage")) == NULL) { return -1; }; - if ((TK_FIND_PHOTO = (Tk_FindPhoto_t) - _dfunc(hMod, "Tk_FindPhoto")) == NULL) { return -1; }; + if ((TK_PHOTO_GET_IMAGE = (Tk_PhotoGetImage_t)_dfunc(hMod, "Tk_PhotoGetImage")) == + NULL) { + return -1; + }; + if ((TK_FIND_PHOTO = (Tk_FindPhoto_t)_dfunc(hMod, "Tk_FindPhoto")) == NULL) { + return -1; + }; TK_LT_85 = GetProcAddress(hMod, "Tk_PhotoPutBlock_Panic") == NULL; /* Tk_PhotoPutBlock_Panic defined as of 8.5.0 */ if (TK_LT_85) { - TK_PHOTO_PUT_BLOCK_84 = (Tk_PhotoPutBlock_84_t) func; - return ((TK_PHOTO_SET_SIZE_84 = (Tk_PhotoSetSize_84_t) - _dfunc(hMod, "Tk_PhotoSetSize")) == NULL) ? -1 : 1; + TK_PHOTO_PUT_BLOCK_84 = (Tk_PhotoPutBlock_84_t)func; + return ((TK_PHOTO_SET_SIZE_84 = + (Tk_PhotoSetSize_84_t)_dfunc(hMod, "Tk_PhotoSetSize")) == NULL) + ? -1 + : 1; } - TK_PHOTO_PUT_BLOCK_85 = (Tk_PhotoPutBlock_85_t) func; + TK_PHOTO_PUT_BLOCK_85 = (Tk_PhotoPutBlock_85_t)func; return 1; } -int load_tkinter_funcs(void) -{ +int +load_tkinter_funcs(void) { /* * Load Tcl and Tk functions by searching all modules in current process. * Return 0 for success, non-zero for failure. @@ -344,7 +356,7 @@ int load_tkinter_funcs(void) return 1; } -#else /* not Windows */ +#else /* not Windows */ /* * On Unix, we can get the Tcl and Tk symbols from the tkinter module, because @@ -353,9 +365,9 @@ int load_tkinter_funcs(void) */ /* From module __file__ attribute to char *string for dlopen. */ -char *fname2char(PyObject *fname) -{ - PyObject* bytes; +char * +fname2char(PyObject *fname) { + PyObject *bytes; bytes = PyUnicode_EncodeFSDefault(fname); if (bytes == NULL) { return NULL; @@ -365,15 +377,15 @@ char *fname2char(PyObject *fname) #include -void *_dfunc(void *lib_handle, const char *func_name) -{ +void * +_dfunc(void *lib_handle, const char *func_name) { /* * Load function `func_name` from `lib_handle`. * Set Python exception if we can't find `func_name` in `lib_handle`. * Returns function pointer or NULL if not present. */ - void* func; + void *func; /* Reset errors. */ dlerror(); func = dlsym(lib_handle, func_name); @@ -384,35 +396,44 @@ void *_dfunc(void *lib_handle, const char *func_name) return func; } -int _func_loader(void *lib) -{ +int +_func_loader(void *lib) { /* * Fill global function pointers from dynamic lib. * Return 1 if any pointer is NULL, 0 otherwise. */ - if ((TCL_CREATE_COMMAND = (Tcl_CreateCommand_t) - _dfunc(lib, "Tcl_CreateCommand")) == NULL) { return 1; } - if ((TCL_APPEND_RESULT = (Tcl_AppendResult_t) _dfunc(lib, - "Tcl_AppendResult")) == NULL) { return 1; } - if ((TK_PHOTO_GET_IMAGE = (Tk_PhotoGetImage_t) - _dfunc(lib, "Tk_PhotoGetImage")) == NULL) { return 1; } - if ((TK_FIND_PHOTO = (Tk_FindPhoto_t) - _dfunc(lib, "Tk_FindPhoto")) == NULL) { return 1; } + if ((TCL_CREATE_COMMAND = (Tcl_CreateCommand_t)_dfunc(lib, "Tcl_CreateCommand")) == + NULL) { + return 1; + } + if ((TCL_APPEND_RESULT = (Tcl_AppendResult_t)_dfunc(lib, "Tcl_AppendResult")) == + NULL) { + return 1; + } + if ((TK_PHOTO_GET_IMAGE = (Tk_PhotoGetImage_t)_dfunc(lib, "Tk_PhotoGetImage")) == + NULL) { + return 1; + } + if ((TK_FIND_PHOTO = (Tk_FindPhoto_t)_dfunc(lib, "Tk_FindPhoto")) == NULL) { + return 1; + } /* Tk_PhotoPutBlock_Panic defined as of 8.5.0 */ TK_LT_85 = (dlsym(lib, "Tk_PhotoPutBlock_Panic") == NULL); if (TK_LT_85) { - return (((TK_PHOTO_PUT_BLOCK_84 = (Tk_PhotoPutBlock_84_t) - _dfunc(lib, "Tk_PhotoPutBlock")) == NULL) || - ((TK_PHOTO_SET_SIZE_84 = (Tk_PhotoSetSize_84_t) - _dfunc(lib, "Tk_PhotoSetSize")) == NULL)); + return ( + ((TK_PHOTO_PUT_BLOCK_84 = + (Tk_PhotoPutBlock_84_t)_dfunc(lib, "Tk_PhotoPutBlock")) == NULL) || + ((TK_PHOTO_SET_SIZE_84 = + (Tk_PhotoSetSize_84_t)_dfunc(lib, "Tk_PhotoSetSize")) == NULL)); } - return ((TK_PHOTO_PUT_BLOCK_85 = (Tk_PhotoPutBlock_85_t) - _dfunc(lib, "Tk_PhotoPutBlock")) == NULL); + return ( + (TK_PHOTO_PUT_BLOCK_85 = + (Tk_PhotoPutBlock_85_t)_dfunc(lib, "Tk_PhotoPutBlock")) == NULL); } -int load_tkinter_funcs(void) -{ +int +load_tkinter_funcs(void) { /* * Load tkinter global funcs from tkinter compiled module. * Return 0 for success, non-zero for failure. @@ -447,8 +468,7 @@ int load_tkinter_funcs(void) } tkinter_lib = dlopen(tkinter_libname, RTLD_LAZY); if (tkinter_lib == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "Cannot dlopen tkinter module file"); + PyErr_SetString(PyExc_RuntimeError, "Cannot dlopen tkinter module file"); goto exit; } ret = _func_loader(tkinter_lib); diff --git a/src/_imaging.c b/src/_imaging.c index 0f8c9d61f..a8741f6ad 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -94,31 +94,30 @@ #include /* Configuration stuff. Feel free to undef things you don't need. */ -#define WITH_IMAGECHOPS /* ImageChops support */ -#define WITH_IMAGEDRAW /* ImageDraw support */ -#define WITH_MAPPING /* use memory mapping to read some file formats */ -#define WITH_IMAGEPATH /* ImagePath stuff */ -#define WITH_ARROW /* arrow graphics stuff (experimental) */ -#define WITH_EFFECTS /* special effects */ -#define WITH_QUANTIZE /* quantization support */ -#define WITH_RANKFILTER /* rank filter */ -#define WITH_MODEFILTER /* mode filter */ -#define WITH_THREADING /* "friendly" threading support */ +#define WITH_IMAGECHOPS /* ImageChops support */ +#define WITH_IMAGEDRAW /* ImageDraw support */ +#define WITH_MAPPING /* use memory mapping to read some file formats */ +#define WITH_IMAGEPATH /* ImagePath stuff */ +#define WITH_ARROW /* arrow graphics stuff (experimental) */ +#define WITH_EFFECTS /* special effects */ +#define WITH_QUANTIZE /* quantization support */ +#define WITH_RANKFILTER /* rank filter */ +#define WITH_MODEFILTER /* mode filter */ +#define WITH_THREADING /* "friendly" threading support */ #define WITH_UNSHARPMASK /* Kevin Cazabon's unsharpmask module */ -#undef VERBOSE +#undef VERBOSE -#define B16(p, i) ((((int)p[(i)]) << 8) + p[(i)+1]) -#define L16(p, i) ((((int)p[(i)+1]) << 8) + p[(i)]) -#define S16(v) ((v) < 32768 ? (v) : ((v) - 65536)) +#define B16(p, i) ((((int)p[(i)]) << 8) + p[(i) + 1]) +#define L16(p, i) ((((int)p[(i) + 1]) << 8) + p[(i)]) +#define S16(v) ((v) < 32768 ? (v) : ((v)-65536)) /* -------------------------------------------------------------------- */ /* OBJECT ADMINISTRATION */ /* -------------------------------------------------------------------- */ typedef struct { - PyObject_HEAD - Imaging image; + PyObject_HEAD Imaging image; ImagingAccess access; } ImagingObject; @@ -126,8 +125,7 @@ static PyTypeObject Imaging_Type; #ifdef WITH_IMAGEDRAW -typedef struct -{ +typedef struct { /* to write a character, cut out sxy from glyph data, place at current position plus dxy, and advance by (dx, dy) */ int dx, dy; @@ -136,8 +134,7 @@ typedef struct } Glyph; typedef struct { - PyObject_HEAD - ImagingObject* ref; + PyObject_HEAD ImagingObject *ref; Imaging bitmap; int ysize; int baseline; @@ -147,8 +144,7 @@ typedef struct { static PyTypeObject ImagingFont_Type; typedef struct { - PyObject_HEAD - ImagingObject* image; + PyObject_HEAD ImagingObject *image; UINT8 ink[4]; int blend; } ImagingDrawObject; @@ -158,17 +154,15 @@ static PyTypeObject ImagingDraw_Type; #endif typedef struct { - PyObject_HEAD - ImagingObject* image; + PyObject_HEAD ImagingObject *image; int readonly; } PixelAccessObject; static PyTypeObject PixelAccess_Type; -PyObject* -PyImagingNew(Imaging imOut) -{ - ImagingObject* imagep; +PyObject * +PyImagingNew(Imaging imOut) { + ImagingObject *imagep; if (!imOut) { return NULL; @@ -187,13 +181,11 @@ PyImagingNew(Imaging imOut) imagep->image = imOut; imagep->access = ImagingAccessNew(imOut); - return (PyObject*) imagep; + return (PyObject *)imagep; } static void -_dealloc(ImagingObject* imagep) -{ - +_dealloc(ImagingObject *imagep) { #ifdef VERBOSE printf("imaging %p deleted\n", imagep); #endif @@ -207,8 +199,8 @@ _dealloc(ImagingObject* imagep) #define PyImaging_Check(op) (Py_TYPE(op) == &Imaging_Type) -Imaging PyImaging_AsImaging(PyObject *op) -{ +Imaging +PyImaging_AsImaging(PyObject *op) { if (!PyImaging_Check(op)) { PyErr_BadInternalCall(); return NULL; @@ -217,22 +209,21 @@ Imaging PyImaging_AsImaging(PyObject *op) return ((ImagingObject *)op)->image; } - /* -------------------------------------------------------------------- */ /* THREAD HANDLING */ /* -------------------------------------------------------------------- */ -void ImagingSectionEnter(ImagingSectionCookie* cookie) -{ +void +ImagingSectionEnter(ImagingSectionCookie *cookie) { #ifdef WITH_THREADING - *cookie = (PyThreadState *) PyEval_SaveThread(); + *cookie = (PyThreadState *)PyEval_SaveThread(); #endif } -void ImagingSectionLeave(ImagingSectionCookie* cookie) -{ +void +ImagingSectionLeave(ImagingSectionCookie *cookie) { #ifdef WITH_THREADING - PyEval_RestoreThread((PyThreadState*) *cookie); + PyEval_RestoreThread((PyThreadState *)*cookie); #endif } @@ -241,13 +232,13 @@ void ImagingSectionLeave(ImagingSectionCookie* cookie) /* -------------------------------------------------------------------- */ /* Python compatibility API */ -int PyImaging_CheckBuffer(PyObject* buffer) -{ +int +PyImaging_CheckBuffer(PyObject *buffer) { return PyObject_CheckBuffer(buffer); } -int PyImaging_GetBuffer(PyObject* buffer, Py_buffer *view) -{ +int +PyImaging_GetBuffer(PyObject *buffer, Py_buffer *view) { /* must call check_buffer first! */ return PyObject_GetBuffer(buffer, view, PyBUF_SIMPLE); } @@ -257,58 +248,50 @@ int PyImaging_GetBuffer(PyObject* buffer, Py_buffer *view) /* -------------------------------------------------------------------- */ /* error messages */ -static const char* must_be_sequence = "argument must be a sequence"; -static const char* must_be_two_coordinates = - "coordinate list must contain exactly 2 coordinates"; -static const char* wrong_mode = "unrecognized image mode"; -static const char* wrong_raw_mode = "unrecognized raw mode"; -static const char* outside_image = "image index out of range"; -static const char* outside_palette = "palette index out of range"; -static const char* wrong_palette_size = "invalid palette size"; -static const char* no_palette = "image has no palette"; -static const char* readonly = "image is readonly"; +static const char *must_be_sequence = "argument must be a sequence"; +static const char *must_be_two_coordinates = + "coordinate list must contain exactly 2 coordinates"; +static const char *wrong_mode = "unrecognized image mode"; +static const char *wrong_raw_mode = "unrecognized raw mode"; +static const char *outside_image = "image index out of range"; +static const char *outside_palette = "palette index out of range"; +static const char *wrong_palette_size = "invalid palette size"; +static const char *no_palette = "image has no palette"; +static const char *readonly = "image is readonly"; /* static const char* no_content = "image has no content"; */ void * -ImagingError_OSError(void) -{ +ImagingError_OSError(void) { PyErr_SetString(PyExc_OSError, "error when accessing file"); return NULL; } void * -ImagingError_MemoryError(void) -{ +ImagingError_MemoryError(void) { return PyErr_NoMemory(); } void * -ImagingError_Mismatch(void) -{ +ImagingError_Mismatch(void) { PyErr_SetString(PyExc_ValueError, "images do not match"); return NULL; } void * -ImagingError_ModeError(void) -{ +ImagingError_ModeError(void) { PyErr_SetString(PyExc_ValueError, "image has wrong mode"); return NULL; } void * -ImagingError_ValueError(const char *message) -{ +ImagingError_ValueError(const char *message) { PyErr_SetString( - PyExc_ValueError, - (message) ? (char*) message : "unrecognized argument value" - ); + PyExc_ValueError, (message) ? (char *)message : "unrecognized argument value"); return NULL; } void -ImagingError_Clear(void) -{ +ImagingError_Clear(void) { PyErr_Clear(); } @@ -317,8 +300,7 @@ ImagingError_Clear(void) /* -------------------------------------------------------------------- */ static int -getbands(const char* mode) -{ +getbands(const char *mode) { Imaging im; int bands; @@ -335,15 +317,14 @@ getbands(const char* mode) return bands; } -#define TYPE_UINT8 (0x100|sizeof(UINT8)) -#define TYPE_INT32 (0x200|sizeof(INT32)) -#define TYPE_FLOAT16 (0x500|sizeof(FLOAT16)) -#define TYPE_FLOAT32 (0x300|sizeof(FLOAT32)) -#define TYPE_DOUBLE (0x400|sizeof(double)) +#define TYPE_UINT8 (0x100 | sizeof(UINT8)) +#define TYPE_INT32 (0x200 | sizeof(INT32)) +#define TYPE_FLOAT16 (0x500 | sizeof(FLOAT16)) +#define TYPE_FLOAT32 (0x300 | sizeof(FLOAT32)) +#define TYPE_DOUBLE (0x400 | sizeof(double)) -static void* -getlist(PyObject* arg, Py_ssize_t* length, const char* wrong_length, int type) -{ +static void * +getlist(PyObject *arg, Py_ssize_t *length, const char *wrong_length, int type) { /* - allocates and returns a c array of the items in the python sequence arg. - the size of the returned array is in length @@ -358,11 +339,11 @@ getlist(PyObject* arg, Py_ssize_t* length, const char* wrong_length, int type) int itemp; double dtemp; FLOAT32 ftemp; - UINT8* list; - PyObject* seq; - PyObject* op; + UINT8 *list; + PyObject *seq; + PyObject *op; - if ( ! PySequence_Check(arg)) { + if (!PySequence_Check(arg)) { PyErr_SetString(PyExc_TypeError, must_be_sequence); return NULL; } @@ -376,12 +357,12 @@ getlist(PyObject* arg, Py_ssize_t* length, const char* wrong_length, int type) /* malloc check ok, type & ff is just a sizeof(something) calloc checks for overflow */ list = calloc(n, type & 0xff); - if ( ! list) { + if (!list) { return ImagingError_MemoryError(); } seq = PySequence_Fast(arg, must_be_sequence); - if ( ! seq) { + if (!seq) { free(list); return NULL; } @@ -391,22 +372,22 @@ getlist(PyObject* arg, Py_ssize_t* length, const char* wrong_length, int type) // DRY, branch prediction is going to work _really_ well // on this switch. And 3 fewer loops to copy/paste. switch (type) { - case TYPE_UINT8: - itemp = PyLong_AsLong(op); - list[i] = CLIP8(itemp); - break; - case TYPE_INT32: - itemp = PyLong_AsLong(op); - memcpy(list + i * sizeof(INT32), &itemp, sizeof(itemp)); - break; - case TYPE_FLOAT32: - ftemp = (FLOAT32)PyFloat_AsDouble(op); - memcpy(list + i * sizeof(ftemp), &ftemp, sizeof(ftemp)); - break; - case TYPE_DOUBLE: - dtemp = PyFloat_AsDouble(op); - memcpy(list + i * sizeof(dtemp), &dtemp, sizeof(dtemp)); - break; + case TYPE_UINT8: + itemp = PyLong_AsLong(op); + list[i] = CLIP8(itemp); + break; + case TYPE_INT32: + itemp = PyLong_AsLong(op); + memcpy(list + i * sizeof(INT32), &itemp, sizeof(itemp)); + break; + case TYPE_FLOAT32: + ftemp = (FLOAT32)PyFloat_AsDouble(op); + memcpy(list + i * sizeof(ftemp), &ftemp, sizeof(ftemp)); + break; + case TYPE_DOUBLE: + dtemp = PyFloat_AsDouble(op); + memcpy(list + i * sizeof(dtemp), &dtemp, sizeof(dtemp)); + break; } } @@ -431,31 +412,30 @@ float16tofloat32(const FLOAT16 in) { UINT32 t3; FLOAT32 out[1] = {0}; - t1 = in & 0x7fff; // Non-sign bits - t2 = in & 0x8000; // Sign bit - t3 = in & 0x7c00; // Exponent + t1 = in & 0x7fff; // Non-sign bits + t2 = in & 0x8000; // Sign bit + t3 = in & 0x7c00; // Exponent - t1 <<= 13; // Align mantissa on MSB - t2 <<= 16; // Shift sign bit into position + t1 <<= 13; // Align mantissa on MSB + t2 <<= 16; // Shift sign bit into position - t1 += 0x38000000; // Adjust bias + t1 += 0x38000000; // Adjust bias - t1 = (t3 == 0 ? 0 : t1); // Denormals-as-zero + t1 = (t3 == 0 ? 0 : t1); // Denormals-as-zero - t1 |= t2; // Re-insert sign bit + t1 |= t2; // Re-insert sign bit memcpy(out, &t1, 4); return out[0]; } -static inline PyObject* -getpixel(Imaging im, ImagingAccess access, int x, int y) -{ +static inline PyObject * +getpixel(Imaging im, ImagingAccess access, int x, int y) { union { - UINT8 b[4]; - UINT16 h; - INT32 i; - FLOAT32 f; + UINT8 b[4]; + UINT16 h; + INT32 i; + FLOAT32 f; } pixel; if (x < 0) { @@ -473,27 +453,28 @@ getpixel(Imaging im, ImagingAccess access, int x, int y) access->get_pixel(im, x, y, &pixel); switch (im->type) { - case IMAGING_TYPE_UINT8: - switch (im->bands) { - case 1: - return PyLong_FromLong(pixel.b[0]); - case 2: - return Py_BuildValue("BB", pixel.b[0], pixel.b[1]); - case 3: - return Py_BuildValue("BBB", pixel.b[0], pixel.b[1], pixel.b[2]); - case 4: - return Py_BuildValue("BBBB", pixel.b[0], pixel.b[1], pixel.b[2], pixel.b[3]); - } - break; - case IMAGING_TYPE_INT32: - return PyLong_FromLong(pixel.i); - case IMAGING_TYPE_FLOAT32: - return PyFloat_FromDouble(pixel.f); - case IMAGING_TYPE_SPECIAL: - if (strncmp(im->mode, "I;16", 4) == 0) { - return PyLong_FromLong(pixel.h); - } - break; + case IMAGING_TYPE_UINT8: + switch (im->bands) { + case 1: + return PyLong_FromLong(pixel.b[0]); + case 2: + return Py_BuildValue("BB", pixel.b[0], pixel.b[1]); + case 3: + return Py_BuildValue("BBB", pixel.b[0], pixel.b[1], pixel.b[2]); + case 4: + return Py_BuildValue( + "BBBB", pixel.b[0], pixel.b[1], pixel.b[2], pixel.b[3]); + } + break; + case IMAGING_TYPE_INT32: + return PyLong_FromLong(pixel.i); + case IMAGING_TYPE_FLOAT32: + return PyFloat_FromDouble(pixel.f); + case IMAGING_TYPE_SPECIAL: + if (strncmp(im->mode, "I;16", 4) == 0) { + return PyLong_FromLong(pixel.h); + } + break; } /* unknown type */ @@ -501,11 +482,10 @@ getpixel(Imaging im, ImagingAccess access, int x, int y) return Py_None; } -static char* -getink(PyObject* color, Imaging im, char* ink) -{ - int g=0, b=0, a=0; - double f=0; +static char * +getink(PyObject *color, Imaging im, char *ink) { + int g = 0, b = 0, a = 0; + double f = 0; /* Windows 64 bit longs are 32 bits, and 0xFFFFFFFF (white) is a python long (not int) that raises an overflow error when trying to return it into a 32 bit C long @@ -521,8 +501,7 @@ getink(PyObject* color, Imaging im, char* ink) if (PyTuple_Check(color) && PyTuple_Size(color) == 1) { color = PyTuple_GetItem(color, 0); } - if (im->type == IMAGING_TYPE_UINT8 || - im->type == IMAGING_TYPE_INT32 || + if (im->type == IMAGING_TYPE_UINT8 || im->type == IMAGING_TYPE_INT32 || im->type == IMAGING_TYPE_SPECIAL) { if (PyLong_Check(color)) { r = PyLong_AsLongLong(color); @@ -536,70 +515,71 @@ getink(PyObject* color, Imaging im, char* ink) return NULL; } } else { - PyErr_SetString(PyExc_TypeError, "color must be int or single-element tuple"); + PyErr_SetString( + PyExc_TypeError, "color must be int or single-element tuple"); return NULL; } } switch (im->type) { - case IMAGING_TYPE_UINT8: - /* unsigned integer */ - if (im->bands == 1) { - /* unsigned integer, single layer */ - if (rIsInt != 1) { - if (!PyArg_ParseTuple(color, "L", &r)) { - return NULL; + case IMAGING_TYPE_UINT8: + /* unsigned integer */ + if (im->bands == 1) { + /* unsigned integer, single layer */ + if (rIsInt != 1) { + if (!PyArg_ParseTuple(color, "L", &r)) { + return NULL; + } } - } - ink[0] = (char) CLIP8(r); - ink[1] = ink[2] = ink[3] = 0; - } else { - a = 255; - if (rIsInt) { - /* compatibility: ABGR */ - a = (UINT8) (r >> 24); - b = (UINT8) (r >> 16); - g = (UINT8) (r >> 8); - r = (UINT8) r; + ink[0] = (char)CLIP8(r); + ink[1] = ink[2] = ink[3] = 0; } else { - if (im->bands == 2) { - if (!PyArg_ParseTuple(color, "L|i", &r, &a)) { - return NULL; - } - g = b = r; + a = 255; + if (rIsInt) { + /* compatibility: ABGR */ + a = (UINT8)(r >> 24); + b = (UINT8)(r >> 16); + g = (UINT8)(r >> 8); + r = (UINT8)r; } else { - if (!PyArg_ParseTuple(color, "Lii|i", &r, &g, &b, &a)) { - return NULL; + if (im->bands == 2) { + if (!PyArg_ParseTuple(color, "L|i", &r, &a)) { + return NULL; + } + g = b = r; + } else { + if (!PyArg_ParseTuple(color, "Lii|i", &r, &g, &b, &a)) { + return NULL; + } } } + ink[0] = (char)CLIP8(r); + ink[1] = (char)CLIP8(g); + ink[2] = (char)CLIP8(b); + ink[3] = (char)CLIP8(a); } - ink[0] = (char) CLIP8(r); - ink[1] = (char) CLIP8(g); - ink[2] = (char) CLIP8(b); - ink[3] = (char) CLIP8(a); - } - return ink; - case IMAGING_TYPE_INT32: - /* signed integer */ - itmp = r; - memcpy(ink, &itmp, sizeof(itmp)); - return ink; - case IMAGING_TYPE_FLOAT32: - /* floating point */ - f = PyFloat_AsDouble(color); - if (f == -1.0 && PyErr_Occurred()) { - return NULL; - } - ftmp = f; - memcpy(ink, &ftmp, sizeof(ftmp)); - return ink; - case IMAGING_TYPE_SPECIAL: - if (strncmp(im->mode, "I;16", 4) == 0) { - ink[0] = (UINT8) r; - ink[1] = (UINT8) (r >> 8); - ink[2] = ink[3] = 0; return ink; - } + case IMAGING_TYPE_INT32: + /* signed integer */ + itmp = r; + memcpy(ink, &itmp, sizeof(itmp)); + return ink; + case IMAGING_TYPE_FLOAT32: + /* floating point */ + f = PyFloat_AsDouble(color); + if (f == -1.0 && PyErr_Occurred()) { + return NULL; + } + ftmp = f; + memcpy(ink, &ftmp, sizeof(ftmp)); + return ink; + case IMAGING_TYPE_SPECIAL: + if (strncmp(im->mode, "I;16", 4) == 0) { + ink[0] = (UINT8)r; + ink[1] = (UINT8)(r >> 8); + ink[2] = ink[3] = 0; + return ink; + } } PyErr_SetString(PyExc_ValueError, wrong_mode); @@ -610,12 +590,11 @@ getink(PyObject* color, Imaging im, char* ink) /* FACTORIES */ /* -------------------------------------------------------------------- */ -static PyObject* -_fill(PyObject* self, PyObject* args) -{ - char* mode; +static PyObject * +_fill(PyObject *self, PyObject *args) { + char *mode; int xsize, ysize; - PyObject* color; + PyObject *color; char buffer[4]; Imaging im; @@ -639,16 +618,14 @@ _fill(PyObject* self, PyObject* args) } } - - (void) ImagingFill(im, buffer); + (void)ImagingFill(im, buffer); return PyImagingNew(im); } -static PyObject* -_new(PyObject* self, PyObject* args) -{ - char* mode; +static PyObject * +_new(PyObject *self, PyObject *args) { + char *mode; int xsize, ysize; if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize)) { @@ -658,10 +635,9 @@ _new(PyObject* self, PyObject* args) return PyImagingNew(ImagingNew(mode, xsize, ysize)); } -static PyObject* -_new_block(PyObject* self, PyObject* args) -{ - char* mode; +static PyObject * +_new_block(PyObject *self, PyObject *args) { + char *mode; int xsize, ysize; if (!PyArg_ParseTuple(args, "s(ii)", &mode, &xsize, &ysize)) { @@ -671,10 +647,9 @@ _new_block(PyObject* self, PyObject* args) return PyImagingNew(ImagingNewBlock(mode, xsize, ysize)); } -static PyObject* -_linear_gradient(PyObject* self, PyObject* args) -{ - char* mode; +static PyObject * +_linear_gradient(PyObject *self, PyObject *args) { + char *mode; if (!PyArg_ParseTuple(args, "s", &mode)) { return NULL; @@ -683,10 +658,9 @@ _linear_gradient(PyObject* self, PyObject* args) return PyImagingNew(ImagingFillLinearGradient(mode)); } -static PyObject* -_radial_gradient(PyObject* self, PyObject* args) -{ - char* mode; +static PyObject * +_radial_gradient(PyObject *self, PyObject *args) { + char *mode; if (!PyArg_ParseTuple(args, "s", &mode)) { return NULL; @@ -695,64 +669,57 @@ _radial_gradient(PyObject* self, PyObject* args) return PyImagingNew(ImagingFillRadialGradient(mode)); } -static PyObject* -_alpha_composite(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep1; - ImagingObject* imagep2; +static PyObject * +_alpha_composite(ImagingObject *self, PyObject *args) { + ImagingObject *imagep1; + ImagingObject *imagep2; - if (!PyArg_ParseTuple(args, "O!O!", - &Imaging_Type, &imagep1, - &Imaging_Type, &imagep2)) { + if (!PyArg_ParseTuple( + args, "O!O!", &Imaging_Type, &imagep1, &Imaging_Type, &imagep2)) { return NULL; } return PyImagingNew(ImagingAlphaComposite(imagep1->image, imagep2->image)); } -static PyObject* -_blend(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep1; - ImagingObject* imagep2; +static PyObject * +_blend(ImagingObject *self, PyObject *args) { + ImagingObject *imagep1; + ImagingObject *imagep2; double alpha; alpha = 0.5; - if (!PyArg_ParseTuple(args, "O!O!|d", - &Imaging_Type, &imagep1, - &Imaging_Type, &imagep2, - &alpha)) { + if (!PyArg_ParseTuple( + args, "O!O!|d", &Imaging_Type, &imagep1, &Imaging_Type, &imagep2, &alpha)) { return NULL; } - return PyImagingNew(ImagingBlend(imagep1->image, imagep2->image, - (float) alpha)); + return PyImagingNew(ImagingBlend(imagep1->image, imagep2->image, (float)alpha)); } /* -------------------------------------------------------------------- */ /* METHODS */ /* -------------------------------------------------------------------- */ -static INT16* -_prepare_lut_table(PyObject* table, Py_ssize_t table_size) -{ +static INT16 * +_prepare_lut_table(PyObject *table, Py_ssize_t table_size) { int i; Py_buffer buffer_info; INT32 data_type = TYPE_FLOAT32; float item = 0; - void* table_data = NULL; - int free_table_data = 0; - INT16* prepared; + void *table_data = NULL; + int free_table_data = 0; + INT16 *prepared; - /* NOTE: This value should be the same as in ColorLUT.c */ - #define PRECISION_BITS (16 - 8 - 2) +/* NOTE: This value should be the same as in ColorLUT.c */ +#define PRECISION_BITS (16 - 8 - 2) - const char* wrong_size = ("The table should have table_channels * " - "size1D * size2D * size3D float items."); + const char *wrong_size = + ("The table should have table_channels * " + "size1D * size2D * size3D float items."); if (PyObject_CheckBuffer(table)) { - if ( ! PyObject_GetBuffer(table, &buffer_info, - PyBUF_CONTIG_RO | PyBUF_FORMAT)) { + if (!PyObject_GetBuffer(table, &buffer_info, PyBUF_CONTIG_RO | PyBUF_FORMAT)) { if (buffer_info.ndim == 1 && buffer_info.shape[0] == table_size) { if (strlen(buffer_info.format) == 1) { switch (buffer_info.format[0]) { @@ -775,21 +742,21 @@ _prepare_lut_table(PyObject* table, Py_ssize_t table_size) } } - if ( ! table_data) { + if (!table_data) { free_table_data = 1; table_data = getlist(table, &table_size, wrong_size, TYPE_FLOAT32); - if ( ! table_data) { + if (!table_data) { return NULL; } } /* malloc check ok, max is 2 * 4 * 65**3 = 2197000 */ - prepared = (INT16*) malloc(sizeof(INT16) * table_size); - if ( ! prepared) { + prepared = (INT16 *)malloc(sizeof(INT16) * table_size); + if (!prepared) { if (free_table_data) { free(table_data); } - return (INT16*) ImagingError_MemoryError(); + return (INT16 *)ImagingError_MemoryError(); } for (i = 0; i < table_size; i++) { @@ -797,15 +764,16 @@ _prepare_lut_table(PyObject* table, Py_ssize_t table_size) double dtmp; switch (data_type) { case TYPE_FLOAT16: - memcpy(&htmp, ((char*) table_data) + i * sizeof(htmp), sizeof(htmp)); + memcpy(&htmp, ((char *)table_data) + i * sizeof(htmp), sizeof(htmp)); item = float16tofloat32(htmp); break; case TYPE_FLOAT32: - memcpy(&item, ((char*) table_data) + i * sizeof(FLOAT32), sizeof(FLOAT32)); + memcpy( + &item, ((char *)table_data) + i * sizeof(FLOAT32), sizeof(FLOAT32)); break; case TYPE_DOUBLE: - memcpy(&dtmp, ((char*) table_data) + i * sizeof(dtmp), sizeof(dtmp)); - item = (FLOAT32) dtmp; + memcpy(&dtmp, ((char *)table_data) + i * sizeof(dtmp), sizeof(dtmp)); + item = (FLOAT32)dtmp; break; } /* Max value for INT16 */ @@ -825,69 +793,75 @@ _prepare_lut_table(PyObject* table, Py_ssize_t table_size) } } - #undef PRECISION_BITS +#undef PRECISION_BITS if (free_table_data) { free(table_data); } return prepared; } - -static PyObject* -_color_lut_3d(ImagingObject* self, PyObject* args) -{ - char* mode; +static PyObject * +_color_lut_3d(ImagingObject *self, PyObject *args) { + char *mode; int filter; int table_channels; int size1D, size2D, size3D; - PyObject* table; + PyObject *table; - INT16* prepared_table; + INT16 *prepared_table; Imaging imOut; - if ( ! PyArg_ParseTuple(args, "siiiiiO:color_lut_3d", &mode, &filter, - &table_channels, &size1D, &size2D, &size3D, - &table)) { + if (!PyArg_ParseTuple( + args, + "siiiiiO:color_lut_3d", + &mode, + &filter, + &table_channels, + &size1D, + &size2D, + &size3D, + &table)) { return NULL; } /* actually, it is trilinear */ if (filter != IMAGING_TRANSFORM_BILINEAR) { - PyErr_SetString(PyExc_ValueError, - "Only LINEAR filter is supported."); + PyErr_SetString(PyExc_ValueError, "Only LINEAR filter is supported."); return NULL; } if (1 > table_channels || table_channels > 4) { - PyErr_SetString(PyExc_ValueError, - "table_channels should be from 1 to 4"); + PyErr_SetString(PyExc_ValueError, "table_channels should be from 1 to 4"); return NULL; } - if (2 > size1D || size1D > 65 || - 2 > size2D || size2D > 65 || - 2 > size3D || size3D > 65 - ) { - PyErr_SetString(PyExc_ValueError, - "Table size in any dimension should be from 2 to 65"); + if (2 > size1D || size1D > 65 || 2 > size2D || size2D > 65 || 2 > size3D || + size3D > 65) { + PyErr_SetString( + PyExc_ValueError, "Table size in any dimension should be from 2 to 65"); return NULL; } - prepared_table = _prepare_lut_table( - table, table_channels * size1D * size2D * size3D); - if ( ! prepared_table) { + prepared_table = + _prepare_lut_table(table, table_channels * size1D * size2D * size3D); + if (!prepared_table) { return NULL; } imOut = ImagingNewDirty(mode, self->image->xsize, self->image->ysize); - if ( ! imOut) { + if (!imOut) { free(prepared_table); return NULL; } - if ( ! ImagingColorLUT3D_linear(imOut, self->image, - table_channels, size1D, size2D, size3D, - prepared_table)) { + if (!ImagingColorLUT3D_linear( + imOut, + self->image, + table_channels, + size1D, + size2D, + size3D, + prepared_table)) { free(prepared_table); ImagingDelete(imOut); return NULL; @@ -898,10 +872,9 @@ _color_lut_3d(ImagingObject* self, PyObject* args) return PyImagingNew(imOut); } -static PyObject* -_convert(ImagingObject* self, PyObject* args) -{ - char* mode; +static PyObject * +_convert(ImagingObject *self, PyObject *args) { + char *mode; int dither = 0; ImagingObject *paletteimage = NULL; @@ -911,7 +884,8 @@ _convert(ImagingObject* self, PyObject* args) if (paletteimage != NULL) { if (!PyImaging_Check(paletteimage)) { PyObject_Print((PyObject *)paletteimage, stderr, 0); - PyErr_SetString(PyExc_ValueError, "palette argument must be image with mode 'P'"); + PyErr_SetString( + PyExc_ValueError, "palette argument must be image with mode 'P'"); return NULL; } if (paletteimage->image->palette == NULL) { @@ -920,17 +894,16 @@ _convert(ImagingObject* self, PyObject* args) } } - return PyImagingNew(ImagingConvert(self->image, mode, paletteimage ? paletteimage->image->palette : NULL, dither)); + return PyImagingNew(ImagingConvert( + self->image, mode, paletteimage ? paletteimage->image->palette : NULL, dither)); } -static PyObject* -_convert2(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep1; - ImagingObject* imagep2; - if (!PyArg_ParseTuple(args, "O!O!", - &Imaging_Type, &imagep1, - &Imaging_Type, &imagep2)) { +static PyObject * +_convert2(ImagingObject *self, PyObject *args) { + ImagingObject *imagep1; + ImagingObject *imagep2; + if (!PyArg_ParseTuple( + args, "O!O!", &Imaging_Type, &imagep1, &Imaging_Type, &imagep2)) { return NULL; } @@ -942,17 +915,28 @@ _convert2(ImagingObject* self, PyObject* args) return Py_None; } -static PyObject* -_convert_matrix(ImagingObject* self, PyObject* args) -{ - char* mode; +static PyObject * +_convert_matrix(ImagingObject *self, PyObject *args) { + char *mode; float m[12]; - if (!PyArg_ParseTuple(args, "s(ffff)", &mode, m+0, m+1, m+2, m+3)) { + if (!PyArg_ParseTuple(args, "s(ffff)", &mode, m + 0, m + 1, m + 2, m + 3)) { PyErr_Clear(); - if (!PyArg_ParseTuple(args, "s(ffffffffffff)", &mode, - m+0, m+1, m+2, m+3, - m+4, m+5, m+6, m+7, - m+8, m+9, m+10, m+11)){ + if (!PyArg_ParseTuple( + args, + "s(ffffffffffff)", + &mode, + m + 0, + m + 1, + m + 2, + m + 3, + m + 4, + m + 5, + m + 6, + m + 7, + m + 8, + m + 9, + m + 10, + m + 11)) { return NULL; } } @@ -960,11 +944,10 @@ _convert_matrix(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingConvertMatrix(self->image, mode, m)); } -static PyObject* -_convert_transparent(ImagingObject* self, PyObject* args) -{ - char* mode; - int r,g,b; +static PyObject * +_convert_transparent(ImagingObject *self, PyObject *args) { + char *mode; + int r, g, b; if (PyArg_ParseTuple(args, "s(iii)", &mode, &r, &g, &b)) { return PyImagingNew(ImagingConvertTransparent(self->image, mode, r, g, b)); } @@ -975,9 +958,8 @@ _convert_transparent(ImagingObject* self, PyObject* args) return NULL; } -static PyObject* -_copy(ImagingObject* self, PyObject* args) -{ +static PyObject * +_copy(ImagingObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "")) { return NULL; } @@ -985,9 +967,8 @@ _copy(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingCopy(self->image)); } -static PyObject* -_crop(ImagingObject* self, PyObject* args) -{ +static PyObject * +_crop(ImagingObject *self, PyObject *args) { int x0, y0, x1, y1; if (!PyArg_ParseTuple(args, "(iiii)", &x0, &y0, &x1, &y1)) { return NULL; @@ -996,9 +977,8 @@ _crop(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingCrop(self->image, x0, y0, x1, y1)); } -static PyObject* -_expand_image(ImagingObject* self, PyObject* args) -{ +static PyObject * +_expand_image(ImagingObject *self, PyObject *args) { int x, y; int mode = 0; if (!PyArg_ParseTuple(args, "ii|i", &x, &y, &mode)) { @@ -1008,18 +988,17 @@ _expand_image(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingExpand(self->image, x, y, mode)); } -static PyObject* -_filter(ImagingObject* self, PyObject* args) -{ - PyObject* imOut; +static PyObject * +_filter(ImagingObject *self, PyObject *args) { + PyObject *imOut; Py_ssize_t kernelsize; - FLOAT32* kerneldata; + FLOAT32 *kerneldata; int xsize, ysize, i; float divisor, offset; - PyObject* kernel = NULL; - if (!PyArg_ParseTuple(args, "(ii)ffO", &xsize, &ysize, - &divisor, &offset, &kernel)) { + PyObject *kernel = NULL; + if (!PyArg_ParseTuple( + args, "(ii)ffO", &xsize, &ysize, &divisor, &offset, &kernel)) { return NULL; } @@ -1028,7 +1007,7 @@ _filter(ImagingObject* self, PyObject* args) if (!kerneldata) { return NULL; } - if (kernelsize != (Py_ssize_t) xsize * (Py_ssize_t) ysize) { + if (kernelsize != (Py_ssize_t)xsize * (Py_ssize_t)ysize) { free(kerneldata); return ImagingError_ValueError("bad kernel size"); } @@ -1037,9 +1016,7 @@ _filter(ImagingObject* self, PyObject* args) kerneldata[i] /= divisor; } - imOut = PyImagingNew( - ImagingFilter(self->image, xsize, ysize, kerneldata, offset) - ); + imOut = PyImagingNew(ImagingFilter(self->image, xsize, ysize, kerneldata, offset)); free(kerneldata); @@ -1047,9 +1024,8 @@ _filter(ImagingObject* self, PyObject* args) } #ifdef WITH_UNSHARPMASK -static PyObject* -_gaussian_blur(ImagingObject* self, PyObject* args) -{ +static PyObject * +_gaussian_blur(ImagingObject *self, PyObject *args) { Imaging imIn; Imaging imOut; @@ -1074,16 +1050,15 @@ _gaussian_blur(ImagingObject* self, PyObject* args) } #endif -static PyObject* -_getpalette(ImagingObject* self, PyObject* args) -{ - PyObject* palette; +static PyObject * +_getpalette(ImagingObject *self, PyObject *args) { + PyObject *palette; int palettesize = 256; int bits; ImagingShuffler pack; - char* mode = "RGB"; - char* rawmode = "RGB"; + char *mode = "RGB"; + char *rawmode = "RGB"; if (!PyArg_ParseTuple(args, "|ss", &mode, &rawmode)) { return NULL; } @@ -1104,27 +1079,25 @@ _getpalette(ImagingObject* self, PyObject* args) return NULL; } - pack((UINT8*) PyBytes_AsString(palette), - self->image->palette->palette, palettesize); + pack( + (UINT8 *)PyBytes_AsString(palette), self->image->palette->palette, palettesize); return palette; } -static PyObject* -_getpalettemode(ImagingObject* self, PyObject* args) -{ +static PyObject * +_getpalettemode(ImagingObject *self, PyObject *args) { if (!self->image->palette) { - PyErr_SetString(PyExc_ValueError, no_palette); - return NULL; + PyErr_SetString(PyExc_ValueError, no_palette); + return NULL; } return PyUnicode_FromString(self->image->palette->mode); } static inline int -_getxy(PyObject* xy, int* x, int *y) -{ - PyObject* value; +_getxy(PyObject *xy, int *x, int *y) { + PyObject *value; if (!PyTuple_Check(xy) || PyTuple_GET_SIZE(xy) != 2) { goto badarg; @@ -1134,7 +1107,7 @@ _getxy(PyObject* xy, int* x, int *y) if (PyLong_Check(value)) { *x = PyLong_AS_LONG(value); } else if (PyFloat_Check(value)) { - *x = (int) PyFloat_AS_DOUBLE(value); + *x = (int)PyFloat_AS_DOUBLE(value); } else { goto badval; } @@ -1143,39 +1116,29 @@ _getxy(PyObject* xy, int* x, int *y) if (PyLong_Check(value)) { *y = PyLong_AS_LONG(value); } else if (PyFloat_Check(value)) { - *y = (int) PyFloat_AS_DOUBLE(value); + *y = (int)PyFloat_AS_DOUBLE(value); } else { goto badval; } return 0; - badarg: - PyErr_SetString( - PyExc_TypeError, - "argument must be sequence of length 2" - ); +badarg: + PyErr_SetString(PyExc_TypeError, "argument must be sequence of length 2"); return -1; - badval: - PyErr_SetString( - PyExc_TypeError, - "an integer is required" - ); +badval: + PyErr_SetString(PyExc_TypeError, "an integer is required"); return -1; } -static PyObject* -_getpixel(ImagingObject* self, PyObject* args) -{ - PyObject* xy; +static PyObject * +_getpixel(ImagingObject *self, PyObject *args) { + PyObject *xy; int x, y; if (PyTuple_GET_SIZE(args) != 1) { - PyErr_SetString( - PyExc_TypeError, - "argument 1 must be sequence of length 2" - ); + PyErr_SetString(PyExc_TypeError, "argument 1 must be sequence of length 2"); return NULL; } @@ -1199,38 +1162,37 @@ union hist_extrema { FLOAT32 f[2]; }; -static union hist_extrema* -parse_histogram_extremap(ImagingObject* self, PyObject* extremap, - union hist_extrema* ep) -{ +static union hist_extrema * +parse_histogram_extremap( + ImagingObject *self, PyObject *extremap, union hist_extrema *ep) { int i0, i1; double f0, f1; if (extremap) { switch (self->image->type) { - case IMAGING_TYPE_UINT8: - if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1)) { + case IMAGING_TYPE_UINT8: + if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1)) { + return NULL; + } + ep->u[0] = CLIP8(i0); + ep->u[1] = CLIP8(i1); + break; + case IMAGING_TYPE_INT32: + if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1)) { + return NULL; + } + ep->i[0] = i0; + ep->i[1] = i1; + break; + case IMAGING_TYPE_FLOAT32: + if (!PyArg_ParseTuple(extremap, "dd", &f0, &f1)) { + return NULL; + } + ep->f[0] = (FLOAT32)f0; + ep->f[1] = (FLOAT32)f1; + break; + default: return NULL; - } - ep->u[0] = CLIP8(i0); - ep->u[1] = CLIP8(i1); - break; - case IMAGING_TYPE_INT32: - if (!PyArg_ParseTuple(extremap, "ii", &i0, &i1)) { - return NULL; - } - ep->i[0] = i0; - ep->i[1] = i1; - break; - case IMAGING_TYPE_FLOAT32: - if (!PyArg_ParseTuple(extremap, "dd", &f0, &f1)) { - return NULL; - } - ep->f[0] = (FLOAT32) f0; - ep->f[1] = (FLOAT32) f1; - break; - default: - return NULL; } } else { return NULL; @@ -1238,17 +1200,16 @@ parse_histogram_extremap(ImagingObject* self, PyObject* extremap, return ep; } -static PyObject* -_histogram(ImagingObject* self, PyObject* args) -{ +static PyObject * +_histogram(ImagingObject *self, PyObject *args) { ImagingHistogram h; - PyObject* list; + PyObject *list; int i; union hist_extrema extrema; - union hist_extrema* ep; + union hist_extrema *ep; - PyObject* extremap = NULL; - ImagingObject* maskp = NULL; + PyObject *extremap = NULL; + ImagingObject *maskp = NULL; if (!PyArg_ParseTuple(args, "|OO!", &extremap, &Imaging_Type, &maskp)) { return NULL; } @@ -1264,7 +1225,7 @@ _histogram(ImagingObject* self, PyObject* args) /* Build an integer list containing the histogram */ list = PyList_New(h->bands * 256); for (i = 0; i < h->bands * 256; i++) { - PyObject* item; + PyObject *item; item = PyLong_FromLong(h->histogram[i]); if (item == NULL) { Py_DECREF(list); @@ -1280,18 +1241,17 @@ _histogram(ImagingObject* self, PyObject* args) return list; } -static PyObject* -_entropy(ImagingObject* self, PyObject* args) -{ +static PyObject * +_entropy(ImagingObject *self, PyObject *args) { ImagingHistogram h; int idx, length; long sum; double entropy, fsum, p; union hist_extrema extrema; - union hist_extrema* ep; + union hist_extrema *ep; - PyObject* extremap = NULL; - ImagingObject* maskp = NULL; + PyObject *extremap = NULL; + ImagingObject *maskp = NULL; if (!PyArg_ParseTuple(args, "|OO!", &extremap, &Imaging_Type, &maskp)) { return NULL; } @@ -1330,9 +1290,8 @@ _entropy(ImagingObject* self, PyObject* args) } #ifdef WITH_MODEFILTER -static PyObject* -_modefilter(ImagingObject* self, PyObject* args) -{ +static PyObject * +_modefilter(ImagingObject *self, PyObject *args) { int size; if (!PyArg_ParseTuple(args, "i", &size)) { return NULL; @@ -1342,9 +1301,8 @@ _modefilter(ImagingObject* self, PyObject* args) } #endif -static PyObject* -_offset(ImagingObject* self, PyObject* args) -{ +static PyObject * +_offset(ImagingObject *self, PyObject *args) { int xoffset, yoffset; if (!PyArg_ParseTuple(args, "ii", &xoffset, &yoffset)) { return NULL; @@ -1353,38 +1311,35 @@ _offset(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingOffset(self->image, xoffset, yoffset)); } -static PyObject* -_paste(ImagingObject* self, PyObject* args) -{ +static PyObject * +_paste(ImagingObject *self, PyObject *args) { int status; char ink[4]; - PyObject* source; + PyObject *source; int x0, y0, x1, y1; - ImagingObject* maskp = NULL; - if (!PyArg_ParseTuple(args, "O(iiii)|O!", - &source, - &x0, &y0, &x1, &y1, - &Imaging_Type, &maskp)) { + ImagingObject *maskp = NULL; + if (!PyArg_ParseTuple( + args, "O(iiii)|O!", &source, &x0, &y0, &x1, &y1, &Imaging_Type, &maskp)) { return NULL; } if (PyImaging_Check(source)) { status = ImagingPaste( - self->image, PyImaging_AsImaging(source), + self->image, + PyImaging_AsImaging(source), (maskp) ? maskp->image : NULL, - x0, y0, x1, y1 - ); + x0, + y0, + x1, + y1); } else { if (!getink(source, self->image, ink)) { return NULL; } status = ImagingFill2( - self->image, ink, - (maskp) ? maskp->image : NULL, - x0, y0, x1, y1 - ); + self->image, ink, (maskp) ? maskp->image : NULL, x0, y0, x1, y1); } if (status < 0) { @@ -1395,23 +1350,22 @@ _paste(ImagingObject* self, PyObject* args) return Py_None; } -static PyObject* -_point(ImagingObject* self, PyObject* args) -{ - static const char* wrong_number = "wrong number of lut entries"; +static PyObject * +_point(ImagingObject *self, PyObject *args) { + static const char *wrong_number = "wrong number of lut entries"; Py_ssize_t n; int i, bands; Imaging im; - PyObject* list; - char* mode; + PyObject *list; + char *mode; if (!PyArg_ParseTuple(args, "Oz", &list, &mode)) { return NULL; } if (mode && !strcmp(mode, "F")) { - FLOAT32* data; + FLOAT32 *data; /* map from 8-bit data to floating point */ n = 256; @@ -1419,11 +1373,11 @@ _point(ImagingObject* self, PyObject* args) if (!data) { return NULL; } - im = ImagingPoint(self->image, mode, (void*) data); + im = ImagingPoint(self->image, mode, (void *)data); free(data); } else if (!strcmp(self->image->mode, "I") && mode && !strcmp(mode, "L")) { - UINT8* data; + UINT8 *data; /* map from 16-bit subset of 32-bit data to 8-bit */ /* FIXME: support arbitrary number of entries (requires API change) */ @@ -1432,11 +1386,11 @@ _point(ImagingObject* self, PyObject* args) if (!data) { return NULL; } - im = ImagingPoint(self->image, mode, (void*) data); + im = ImagingPoint(self->image, mode, (void *)data); free(data); } else { - INT32* data; + INT32 *data; UINT8 lut[1024]; if (mode) { @@ -1456,23 +1410,23 @@ _point(ImagingObject* self, PyObject* args) } if (mode && !strcmp(mode, "I")) { - im = ImagingPoint(self->image, mode, (void*) data); + im = ImagingPoint(self->image, mode, (void *)data); } else if (mode && bands > 1) { for (i = 0; i < 256; i++) { - lut[i*4] = CLIP8(data[i]); - lut[i*4+1] = CLIP8(data[i+256]); - lut[i*4+2] = CLIP8(data[i+512]); + lut[i * 4] = CLIP8(data[i]); + lut[i * 4 + 1] = CLIP8(data[i + 256]); + lut[i * 4 + 2] = CLIP8(data[i + 512]); if (n > 768) { - lut[i*4+3] = CLIP8(data[i+768]); + lut[i * 4 + 3] = CLIP8(data[i + 768]); } } - im = ImagingPoint(self->image, mode, (void*) lut); + im = ImagingPoint(self->image, mode, (void *)lut); } else { /* map individual bands */ for (i = 0; i < n; i++) { lut[i] = CLIP8(data[i]); } - im = ImagingPoint(self->image, mode, (void*) lut); + im = ImagingPoint(self->image, mode, (void *)lut); } free(data); } @@ -1480,9 +1434,8 @@ _point(ImagingObject* self, PyObject* args) return PyImagingNew(im); } -static PyObject* -_point_transform(ImagingObject* self, PyObject* args) -{ +static PyObject * +_point_transform(ImagingObject *self, PyObject *args) { double scale = 1.0; double offset = 0.0; if (!PyArg_ParseTuple(args, "|dd", &scale, &offset)) { @@ -1492,16 +1445,15 @@ _point_transform(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingPointTransform(self->image, scale, offset)); } -static PyObject* -_putdata(ImagingObject* self, PyObject* args) -{ +static PyObject * +_putdata(ImagingObject *self, PyObject *args) { Imaging image; // i & n are # pixels, require py_ssize_t. x can be as large as n. y, just because. Py_ssize_t n, i, x, y; - PyObject* data; - PyObject* seq = NULL; - PyObject* op; + PyObject *data; + PyObject *seq = NULL; + PyObject *op; double scale = 1.0; double offset = 0.0; @@ -1524,54 +1476,54 @@ _putdata(ImagingObject* self, PyObject* args) if (image->image8) { if (PyBytes_Check(data)) { - unsigned char* p; - p = (unsigned char*) PyBytes_AS_STRING(data); + unsigned char *p; + p = (unsigned char *)PyBytes_AS_STRING(data); if (scale == 1.0 && offset == 0.0) { /* Plain string data */ for (i = y = 0; i < n; i += image->xsize, y++) { x = n - i; - if (x > (int) image->xsize) { + if (x > (int)image->xsize) { x = image->xsize; } - memcpy(image->image8[y], p+i, x); + memcpy(image->image8[y], p + i, x); } } else { /* Scaled and clipped string data */ for (i = x = y = 0; i < n; i++) { - image->image8[y][x] = CLIP8((int) (p[i] * scale + offset)); - if (++x >= (int) image->xsize) { + image->image8[y][x] = CLIP8((int)(p[i] * scale + offset)); + if (++x >= (int)image->xsize) { x = 0, y++; } } } } else { - seq = PySequence_Fast(data, must_be_sequence); - if (!seq) { - PyErr_SetString(PyExc_TypeError, must_be_sequence); - return NULL; - } - if (scale == 1.0 && offset == 0.0) { - /* Clipped data */ - for (i = x = y = 0; i < n; i++) { - op = PySequence_Fast_GET_ITEM(seq, i); - image->image8[y][x] = (UINT8) CLIP8(PyLong_AsLong(op)); - if (++x >= (int) image->xsize){ - x = 0, y++; - } - } + seq = PySequence_Fast(data, must_be_sequence); + if (!seq) { + PyErr_SetString(PyExc_TypeError, must_be_sequence); + return NULL; + } + if (scale == 1.0 && offset == 0.0) { + /* Clipped data */ + for (i = x = y = 0; i < n; i++) { + op = PySequence_Fast_GET_ITEM(seq, i); + image->image8[y][x] = (UINT8)CLIP8(PyLong_AsLong(op)); + if (++x >= (int)image->xsize) { + x = 0, y++; + } + } } else { - /* Scaled and clipped data */ - for (i = x = y = 0; i < n; i++) { - PyObject *op = PySequence_Fast_GET_ITEM(seq, i); - image->image8[y][x] = CLIP8( - (int) (PyFloat_AsDouble(op) * scale + offset)); - if (++x >= (int) image->xsize){ - x = 0, y++; - } - } - } - PyErr_Clear(); /* Avoid weird exceptions */ + /* Scaled and clipped data */ + for (i = x = y = 0; i < n; i++) { + PyObject *op = PySequence_Fast_GET_ITEM(seq, i); + image->image8[y][x] = + CLIP8((int)(PyFloat_AsDouble(op) * scale + offset)); + if (++x >= (int)image->xsize) { + x = 0, y++; + } + } + } + PyErr_Clear(); /* Avoid weird exceptions */ } } else { /* 32-bit images */ @@ -1581,50 +1533,50 @@ _putdata(ImagingObject* self, PyObject* args) return NULL; } switch (image->type) { - case IMAGING_TYPE_INT32: - for (i = x = y = 0; i < n; i++) { - op = PySequence_Fast_GET_ITEM(seq, i); - IMAGING_PIXEL_INT32(image, x, y) = - (INT32) (PyFloat_AsDouble(op) * scale + offset); - if (++x >= (int) image->xsize){ - x = 0, y++; + case IMAGING_TYPE_INT32: + for (i = x = y = 0; i < n; i++) { + op = PySequence_Fast_GET_ITEM(seq, i); + IMAGING_PIXEL_INT32(image, x, y) = + (INT32)(PyFloat_AsDouble(op) * scale + offset); + if (++x >= (int)image->xsize) { + x = 0, y++; + } } - } - PyErr_Clear(); /* Avoid weird exceptions */ - break; - case IMAGING_TYPE_FLOAT32: - for (i = x = y = 0; i < n; i++) { - op = PySequence_Fast_GET_ITEM(seq, i); - IMAGING_PIXEL_FLOAT32(image, x, y) = - (FLOAT32) (PyFloat_AsDouble(op) * scale + offset); - if (++x >= (int) image->xsize){ - x = 0, y++; + PyErr_Clear(); /* Avoid weird exceptions */ + break; + case IMAGING_TYPE_FLOAT32: + for (i = x = y = 0; i < n; i++) { + op = PySequence_Fast_GET_ITEM(seq, i); + IMAGING_PIXEL_FLOAT32(image, x, y) = + (FLOAT32)(PyFloat_AsDouble(op) * scale + offset); + if (++x >= (int)image->xsize) { + x = 0, y++; + } } - } - PyErr_Clear(); /* Avoid weird exceptions */ - break; - default: - for (i = x = y = 0; i < n; i++) { - union { - char ink[4]; - INT32 inkint; - } u; + PyErr_Clear(); /* Avoid weird exceptions */ + break; + default: + for (i = x = y = 0; i < n; i++) { + union { + char ink[4]; + INT32 inkint; + } u; - u.inkint = 0; + u.inkint = 0; - op = PySequence_Fast_GET_ITEM(seq, i); - if (!op || !getink(op, image, u.ink)) { - Py_DECREF(seq); - return NULL; + op = PySequence_Fast_GET_ITEM(seq, i); + if (!op || !getink(op, image, u.ink)) { + Py_DECREF(seq); + return NULL; + } + /* FIXME: what about scale and offset? */ + image->image32[y][x] = u.inkint; + if (++x >= (int)image->xsize) { + x = 0, y++; + } } - /* FIXME: what about scale and offset? */ - image->image32[y][x] = u.inkint; - if (++x >= (int) image->xsize){ - x = 0, y++; - } - } - PyErr_Clear(); /* Avoid weird exceptions */ - break; + PyErr_Clear(); /* Avoid weird exceptions */ + break; } } @@ -1636,9 +1588,8 @@ _putdata(ImagingObject* self, PyObject* args) #ifdef WITH_QUANTIZE -static PyObject* -_quantize(ImagingObject* self, PyObject* args) -{ +static PyObject * +_quantize(ImagingObject *self, PyObject *args) { int colours = 256; int method = 0; int kmeans = 0; @@ -1648,23 +1599,20 @@ _quantize(ImagingObject* self, PyObject* args) if (!self->image->xsize || !self->image->ysize) { /* no content; return an empty image */ - return PyImagingNew( - ImagingNew("P", self->image->xsize, self->image->ysize) - ); + return PyImagingNew(ImagingNew("P", self->image->xsize, self->image->ysize)); } return PyImagingNew(ImagingQuantize(self->image, colours, method, kmeans)); } #endif -static PyObject* -_putpalette(ImagingObject* self, PyObject* args) -{ +static PyObject * +_putpalette(ImagingObject *self, PyObject *args) { ImagingShuffler unpack; int bits; - char* rawmode; - UINT8* palette; + char *rawmode; + UINT8 *palette; Py_ssize_t palettesize; if (!PyArg_ParseTuple(args, "sy#", &rawmode, &palette, &palettesize)) { return NULL; @@ -1682,7 +1630,7 @@ _putpalette(ImagingObject* self, PyObject* args) return NULL; } - if ( palettesize * 8 / bits > 256) { + if (palettesize * 8 / bits > 256) { PyErr_SetString(PyExc_ValueError, wrong_palette_size); return NULL; } @@ -1699,9 +1647,8 @@ _putpalette(ImagingObject* self, PyObject* args) return Py_None; } -static PyObject* -_putpalettealpha(ImagingObject* self, PyObject* args) -{ +static PyObject * +_putpalettealpha(ImagingObject *self, PyObject *args) { int index; int alpha = 0; if (!PyArg_ParseTuple(args, "i|i", &index, &alpha)) { @@ -1719,15 +1666,14 @@ _putpalettealpha(ImagingObject* self, PyObject* args) } strcpy(self->image->palette->mode, "RGBA"); - self->image->palette->palette[index*4+3] = (UINT8) alpha; + self->image->palette->palette[index * 4 + 3] = (UINT8)alpha; Py_INCREF(Py_None); return Py_None; } -static PyObject* -_putpalettealphas(ImagingObject* self, PyObject* args) -{ +static PyObject * +_putpalettealphas(ImagingObject *self, PyObject *args) { int i; UINT8 *values; Py_ssize_t length; @@ -1740,28 +1686,27 @@ _putpalettealphas(ImagingObject* self, PyObject* args) return NULL; } - if (length > 256) { + if (length > 256) { PyErr_SetString(PyExc_ValueError, outside_palette); return NULL; } strcpy(self->image->palette->mode, "RGBA"); - for (i=0; iimage->palette->palette[i*4+3] = (UINT8) values[i]; + for (i = 0; i < length; i++) { + self->image->palette->palette[i * 4 + 3] = (UINT8)values[i]; } Py_INCREF(Py_None); return Py_None; } -static PyObject* -_putpixel(ImagingObject* self, PyObject* args) -{ +static PyObject * +_putpixel(ImagingObject *self, PyObject *args) { Imaging im; char ink[4]; int x, y; - PyObject* color; + PyObject *color; if (!PyArg_ParseTuple(args, "(ii)O", &x, &y, &color)) { return NULL; } @@ -1793,9 +1738,8 @@ _putpixel(ImagingObject* self, PyObject* args) } #ifdef WITH_RANKFILTER -static PyObject* -_rankfilter(ImagingObject* self, PyObject* args) -{ +static PyObject * +_rankfilter(ImagingObject *self, PyObject *args) { int size, rank; if (!PyArg_ParseTuple(args, "ii", &size, &rank)) { return NULL; @@ -1805,9 +1749,8 @@ _rankfilter(ImagingObject* self, PyObject* args) } #endif -static PyObject* -_resize(ImagingObject* self, PyObject* args) -{ +static PyObject * +_resize(ImagingObject *self, PyObject *args) { Imaging imIn; Imaging imOut; @@ -1819,8 +1762,16 @@ _resize(ImagingObject* self, PyObject* args) box[2] = imIn->xsize; box[3] = imIn->ysize; - if (!PyArg_ParseTuple(args, "(ii)|i(ffff)", &xsize, &ysize, &filter, - &box[0], &box[1], &box[2], &box[3])) { + if (!PyArg_ParseTuple( + args, + "(ii)|i(ffff)", + &xsize, + &ysize, + &filter, + &box[0], + &box[1], + &box[2], + &box[3])) { return NULL; } @@ -1841,36 +1792,31 @@ _resize(ImagingObject* self, PyObject* args) } // If box's coordinates are int and box size matches requested size - if (box[0] - (int) box[0] == 0 && box[2] - box[0] == xsize - && box[1] - (int) box[1] == 0 && box[3] - box[1] == ysize) { + if (box[0] - (int)box[0] == 0 && box[2] - box[0] == xsize && + box[1] - (int)box[1] == 0 && box[3] - box[1] == ysize) { imOut = ImagingCrop(imIn, box[0], box[1], box[2], box[3]); - } - else if (filter == IMAGING_TRANSFORM_NEAREST) { + } else if (filter == IMAGING_TRANSFORM_NEAREST) { double a[6]; memset(a, 0, sizeof a); - a[0] = (double) (box[2] - box[0]) / xsize; - a[4] = (double) (box[3] - box[1]) / ysize; + a[0] = (double)(box[2] - box[0]) / xsize; + a[4] = (double)(box[3] - box[1]) / ysize; a[2] = box[0]; a[5] = box[1]; imOut = ImagingNewDirty(imIn->mode, xsize, ysize); imOut = ImagingTransform( - imOut, imIn, IMAGING_TRANSFORM_AFFINE, - 0, 0, xsize, ysize, - a, filter, 1); - } - else { + imOut, imIn, IMAGING_TRANSFORM_AFFINE, 0, 0, xsize, ysize, a, filter, 1); + } else { imOut = ImagingResample(imIn, xsize, ysize, filter, box); } return PyImagingNew(imOut); } -static PyObject* -_reduce(ImagingObject* self, PyObject* args) -{ +static PyObject * +_reduce(ImagingObject *self, PyObject *args) { Imaging imIn; Imaging imOut; @@ -1881,8 +1827,15 @@ _reduce(ImagingObject* self, PyObject* args) box[2] = imIn->xsize; box[3] = imIn->ysize; - if (!PyArg_ParseTuple(args, "(ii)|(iiii)", &xscale, &yscale, - &box[0], &box[1], &box[2], &box[3])) { + if (!PyArg_ParseTuple( + args, + "(ii)|(iiii)", + &xscale, + &yscale, + &box[0], + &box[1], + &box[2], + &box[3])) { return NULL; } @@ -1914,18 +1867,16 @@ _reduce(ImagingObject* self, PyObject* args) return PyImagingNew(imOut); } - -#define IS_RGB(mode)\ +#define IS_RGB(mode) \ (!strcmp(mode, "RGB") || !strcmp(mode, "RGBA") || !strcmp(mode, "RGBX")) -static PyObject* -im_setmode(ImagingObject* self, PyObject* args) -{ +static PyObject * +im_setmode(ImagingObject *self, PyObject *args) { /* attempt to modify the mode of an image in place */ Imaging im; - char* mode; + char *mode; Py_ssize_t modelen; if (!PyArg_ParseTuple(args, "s#:setmode", &mode, &modelen)) { return NULL; @@ -1942,7 +1893,7 @@ im_setmode(ImagingObject* self, PyObject* args) strcpy(im->mode, mode); im->bands = modelen; if (!strcmp(mode, "RGBA")) { - (void) ImagingFillBand(im, 3, 255); + (void)ImagingFillBand(im, 3, 255); } } else { /* trying doing an in-place conversion */ @@ -1960,42 +1911,48 @@ im_setmode(ImagingObject* self, PyObject* args) return Py_None; } - -static PyObject* -_transform2(ImagingObject* self, PyObject* args) -{ - static const char* wrong_number = "wrong number of matrix entries"; +static PyObject * +_transform2(ImagingObject *self, PyObject *args) { + static const char *wrong_number = "wrong number of matrix entries"; Imaging imOut; Py_ssize_t n; double *a; - ImagingObject* imagep; + ImagingObject *imagep; int x0, y0, x1, y1; int method; - PyObject* data; + PyObject *data; int filter = IMAGING_TRANSFORM_NEAREST; int fill = 1; - if (!PyArg_ParseTuple(args, "(iiii)O!iO|ii", - &x0, &y0, &x1, &y1, - &Imaging_Type, &imagep, - &method, &data, - &filter, &fill)) { + if (!PyArg_ParseTuple( + args, + "(iiii)O!iO|ii", + &x0, + &y0, + &x1, + &y1, + &Imaging_Type, + &imagep, + &method, + &data, + &filter, + &fill)) { return NULL; } switch (method) { - case IMAGING_TRANSFORM_AFFINE: - n = 6; - break; - case IMAGING_TRANSFORM_PERSPECTIVE: - n = 8; - break; - case IMAGING_TRANSFORM_QUAD: - n = 8; - break; - default: - n = -1; /* force error */ + case IMAGING_TRANSFORM_AFFINE: + n = 6; + break; + case IMAGING_TRANSFORM_PERSPECTIVE: + n = 8; + break; + case IMAGING_TRANSFORM_QUAD: + n = 8; + break; + default: + n = -1; /* force error */ } a = getlist(data, &n, wrong_number, TYPE_DOUBLE); @@ -2004,8 +1961,7 @@ _transform2(ImagingObject* self, PyObject* args) } imOut = ImagingTransform( - self->image, imagep->image, method, - x0, y0, x1, y1, a, filter, fill); + self->image, imagep->image, method, x0, y0, x1, y1, a, filter, fill); free(a); @@ -2017,9 +1973,8 @@ _transform2(ImagingObject* self, PyObject* args) return Py_None; } -static PyObject* -_transpose(ImagingObject* self, PyObject* args) -{ +static PyObject * +_transpose(ImagingObject *self, PyObject *args) { Imaging imIn; Imaging imOut; @@ -2031,45 +1986,45 @@ _transpose(ImagingObject* self, PyObject* args) imIn = self->image; switch (op) { - case 0: /* flip left right */ - case 1: /* flip top bottom */ - case 3: /* rotate 180 */ - imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize); - break; - case 2: /* rotate 90 */ - case 4: /* rotate 270 */ - case 5: /* transpose */ - case 6: /* transverse */ - imOut = ImagingNewDirty(imIn->mode, imIn->ysize, imIn->xsize); - break; - default: - PyErr_SetString(PyExc_ValueError, "No such transpose operation"); - return NULL; + case 0: /* flip left right */ + case 1: /* flip top bottom */ + case 3: /* rotate 180 */ + imOut = ImagingNewDirty(imIn->mode, imIn->xsize, imIn->ysize); + break; + case 2: /* rotate 90 */ + case 4: /* rotate 270 */ + case 5: /* transpose */ + case 6: /* transverse */ + imOut = ImagingNewDirty(imIn->mode, imIn->ysize, imIn->xsize); + break; + default: + PyErr_SetString(PyExc_ValueError, "No such transpose operation"); + return NULL; } if (imOut) { switch (op) { - case 0: - (void) ImagingFlipLeftRight(imOut, imIn); - break; - case 1: - (void) ImagingFlipTopBottom(imOut, imIn); - break; - case 2: - (void) ImagingRotate90(imOut, imIn); - break; - case 3: - (void) ImagingRotate180(imOut, imIn); - break; - case 4: - (void) ImagingRotate270(imOut, imIn); - break; - case 5: - (void) ImagingTranspose(imOut, imIn); - break; - case 6: - (void) ImagingTransverse(imOut, imIn); - break; + case 0: + (void)ImagingFlipLeftRight(imOut, imIn); + break; + case 1: + (void)ImagingFlipTopBottom(imOut, imIn); + break; + case 2: + (void)ImagingRotate90(imOut, imIn); + break; + case 3: + (void)ImagingRotate180(imOut, imIn); + break; + case 4: + (void)ImagingRotate270(imOut, imIn); + break; + case 5: + (void)ImagingTranspose(imOut, imIn); + break; + case 6: + (void)ImagingTransverse(imOut, imIn); + break; } } @@ -2077,9 +2032,8 @@ _transpose(ImagingObject* self, PyObject* args) } #ifdef WITH_UNSHARPMASK -static PyObject* -_unsharp_mask(ImagingObject* self, PyObject* args) -{ +static PyObject * +_unsharp_mask(ImagingObject *self, PyObject *args) { Imaging imIn; Imaging imOut; @@ -2103,9 +2057,8 @@ _unsharp_mask(ImagingObject* self, PyObject* args) } #endif -static PyObject* -_box_blur(ImagingObject* self, PyObject* args) -{ +static PyObject * +_box_blur(ImagingObject *self, PyObject *args) { Imaging imIn; Imaging imOut; @@ -2131,15 +2084,13 @@ _box_blur(ImagingObject* self, PyObject* args) /* -------------------------------------------------------------------- */ -static PyObject* -_isblock(ImagingObject* self, PyObject* args) -{ +static PyObject * +_isblock(ImagingObject *self, PyObject *args) { return PyBool_FromLong(self->image->block != NULL); } -static PyObject* -_getbbox(ImagingObject* self, PyObject* args) -{ +static PyObject * +_getbbox(ImagingObject *self, PyObject *args) { int bbox[4]; if (!ImagingGetBBox(self->image, bbox)) { Py_INCREF(Py_None); @@ -2149,12 +2100,11 @@ _getbbox(ImagingObject* self, PyObject* args) return Py_BuildValue("iiii", bbox[0], bbox[1], bbox[2], bbox[3]); } -static PyObject* -_getcolors(ImagingObject* self, PyObject* args) -{ - ImagingColorItem* items; +static PyObject * +_getcolors(ImagingObject *self, PyObject *args) { + ImagingColorItem *items; int i, colors; - PyObject* out; + PyObject *out; int maxcolors = 256; if (!PyArg_ParseTuple(args, "i:getcolors", &maxcolors)) { @@ -2172,10 +2122,9 @@ _getcolors(ImagingObject* self, PyObject* args) } else { out = PyList_New(colors); for (i = 0; i < colors; i++) { - ImagingColorItem* v = &items[i]; - PyObject* item = Py_BuildValue( - "iN", v->count, getpixel(self->image, self->access, v->x, v->y) - ); + ImagingColorItem *v = &items[i]; + PyObject *item = Py_BuildValue( + "iN", v->count, getpixel(self->image, self->access, v->x, v->y)); PyList_SetItem(out, i, item); } } @@ -2185,9 +2134,8 @@ _getcolors(ImagingObject* self, PyObject* args) return out; } -static PyObject* -_getextrema(ImagingObject* self, PyObject* args) -{ +static PyObject * +_getextrema(ImagingObject *self, PyObject *args) { union { UINT8 u[2]; INT32 i[2]; @@ -2203,16 +2151,16 @@ _getextrema(ImagingObject* self, PyObject* args) if (status) { switch (self->image->type) { - case IMAGING_TYPE_UINT8: - return Py_BuildValue("BB", extrema.u[0], extrema.u[1]); - case IMAGING_TYPE_INT32: - return Py_BuildValue("ii", extrema.i[0], extrema.i[1]); - case IMAGING_TYPE_FLOAT32: - return Py_BuildValue("dd", extrema.f[0], extrema.f[1]); - case IMAGING_TYPE_SPECIAL: - if (strcmp(self->image->mode, "I;16") == 0) { - return Py_BuildValue("HH", extrema.s[0], extrema.s[1]); - } + case IMAGING_TYPE_UINT8: + return Py_BuildValue("BB", extrema.u[0], extrema.u[1]); + case IMAGING_TYPE_INT32: + return Py_BuildValue("ii", extrema.i[0], extrema.i[1]); + case IMAGING_TYPE_FLOAT32: + return Py_BuildValue("dd", extrema.f[0], extrema.f[1]); + case IMAGING_TYPE_SPECIAL: + if (strcmp(self->image->mode, "I;16") == 0) { + return Py_BuildValue("HH", extrema.s[0], extrema.s[1]); + } } } @@ -2220,12 +2168,11 @@ _getextrema(ImagingObject* self, PyObject* args) return Py_None; } -static PyObject* -_getprojection(ImagingObject* self, PyObject* args) -{ - unsigned char* xprofile; - unsigned char* yprofile; - PyObject* result; +static PyObject * +_getprojection(ImagingObject *self, PyObject *args) { + unsigned char *xprofile; + unsigned char *yprofile; + PyObject *result; /* malloc check ok */ xprofile = malloc(self->image->xsize); @@ -2237,11 +2184,15 @@ _getprojection(ImagingObject* self, PyObject* args) return ImagingError_MemoryError(); } - ImagingGetProjection(self->image, (unsigned char *)xprofile, (unsigned char *)yprofile); + ImagingGetProjection( + self->image, (unsigned char *)xprofile, (unsigned char *)yprofile); - result = Py_BuildValue("y#y#", - xprofile, (Py_ssize_t)self->image->xsize, - yprofile, (Py_ssize_t)self->image->ysize); + result = Py_BuildValue( + "y#y#", + xprofile, + (Py_ssize_t)self->image->xsize, + yprofile, + (Py_ssize_t)self->image->ysize); free(xprofile); free(yprofile); @@ -2251,9 +2202,8 @@ _getprojection(ImagingObject* self, PyObject* args) /* -------------------------------------------------------------------- */ -static PyObject* -_getband(ImagingObject* self, PyObject* args) -{ +static PyObject * +_getband(ImagingObject *self, PyObject *args) { int band; if (!PyArg_ParseTuple(args, "i", &band)) { @@ -2263,9 +2213,8 @@ _getband(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingGetBand(self->image, band)); } -static PyObject* -_fillband(ImagingObject* self, PyObject* args) -{ +static PyObject * +_fillband(ImagingObject *self, PyObject *args) { int band; int color; @@ -2281,14 +2230,11 @@ _fillband(ImagingObject* self, PyObject* args) return Py_None; } -static PyObject* -_putband(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_putband(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; int band; - if (!PyArg_ParseTuple(args, "O!i", - &Imaging_Type, &imagep, - &band)) { + if (!PyArg_ParseTuple(args, "O!i", &Imaging_Type, &imagep, &band)) { return NULL; } @@ -2300,19 +2246,27 @@ _putband(ImagingObject* self, PyObject* args) return Py_None; } -static PyObject* -_merge(PyObject* self, PyObject* args) -{ - char* mode; +static PyObject * +_merge(PyObject *self, PyObject *args) { + char *mode; ImagingObject *band0 = NULL; ImagingObject *band1 = NULL; ImagingObject *band2 = NULL; ImagingObject *band3 = NULL; Imaging bands[4] = {NULL, NULL, NULL, NULL}; - if (!PyArg_ParseTuple(args, "sO!|O!O!O!", &mode, - &Imaging_Type, &band0, &Imaging_Type, &band1, - &Imaging_Type, &band2, &Imaging_Type, &band3)) { + if (!PyArg_ParseTuple( + args, + "sO!|O!O!O!", + &mode, + &Imaging_Type, + &band0, + &Imaging_Type, + &band1, + &Imaging_Type, + &band2, + &Imaging_Type, + &band3)) { return NULL; } @@ -2332,23 +2286,22 @@ _merge(PyObject* self, PyObject* args) return PyImagingNew(ImagingMerge(mode, bands)); } -static PyObject* -_split(ImagingObject* self, PyObject* args) -{ +static PyObject * +_split(ImagingObject *self, PyObject *args) { int fails = 0; Py_ssize_t i; - PyObject* list; - PyObject* imaging_object; + PyObject *list; + PyObject *imaging_object; Imaging bands[4] = {NULL, NULL, NULL, NULL}; - if ( ! ImagingSplit(self->image, bands)) { + if (!ImagingSplit(self->image, bands)) { return NULL; } list = PyTuple_New(self->image->bands); for (i = 0; i < self->image->bands; i++) { imaging_object = PyImagingNew(bands[i]); - if ( ! imaging_object) { + if (!imaging_object) { fails += 1; } PyTuple_SET_ITEM(list, i, imaging_object); @@ -2364,16 +2317,14 @@ _split(ImagingObject* self, PyObject* args) #ifdef WITH_IMAGECHOPS -static PyObject* -_chop_invert(ImagingObject* self, PyObject* args) -{ +static PyObject * +_chop_invert(ImagingObject *self, PyObject *args) { return PyImagingNew(ImagingNegative(self->image)); } -static PyObject* -_chop_lighter(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_lighter(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2382,10 +2333,9 @@ _chop_lighter(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopLighter(self->image, imagep->image)); } -static PyObject* -_chop_darker(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_darker(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2394,10 +2344,9 @@ _chop_darker(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopDarker(self->image, imagep->image)); } -static PyObject* -_chop_difference(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_difference(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2406,10 +2355,9 @@ _chop_difference(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopDifference(self->image, imagep->image)); } -static PyObject* -_chop_multiply(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_multiply(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2418,10 +2366,9 @@ _chop_multiply(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopMultiply(self->image, imagep->image)); } -static PyObject* -_chop_screen(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_screen(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2430,48 +2377,41 @@ _chop_screen(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopScreen(self->image, imagep->image)); } -static PyObject* -_chop_add(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_add(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; float scale; int offset; scale = 1.0; offset = 0; - if (!PyArg_ParseTuple(args, "O!|fi", &Imaging_Type, &imagep, - &scale, &offset)) { + if (!PyArg_ParseTuple(args, "O!|fi", &Imaging_Type, &imagep, &scale, &offset)) { return NULL; } - return PyImagingNew(ImagingChopAdd(self->image, imagep->image, - scale, offset)); + return PyImagingNew(ImagingChopAdd(self->image, imagep->image, scale, offset)); } -static PyObject* -_chop_subtract(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_subtract(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; float scale; int offset; scale = 1.0; offset = 0; - if (!PyArg_ParseTuple(args, "O!|fi", &Imaging_Type, &imagep, - &scale, &offset)) { + if (!PyArg_ParseTuple(args, "O!|fi", &Imaging_Type, &imagep, &scale, &offset)) { return NULL; } - return PyImagingNew(ImagingChopSubtract(self->image, imagep->image, - scale, offset)); + return PyImagingNew(ImagingChopSubtract(self->image, imagep->image, scale, offset)); } -static PyObject* -_chop_and(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_and(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2480,10 +2420,9 @@ _chop_and(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopAnd(self->image, imagep->image)); } -static PyObject* -_chop_or(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_or(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2492,10 +2431,9 @@ _chop_or(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopOr(self->image, imagep->image)); } -static PyObject* -_chop_xor(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_xor(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2504,10 +2442,9 @@ _chop_xor(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopXor(self->image, imagep->image)); } -static PyObject* -_chop_add_modulo(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_add_modulo(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2516,10 +2453,9 @@ _chop_add_modulo(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopAddModulo(self->image, imagep->image)); } -static PyObject* -_chop_subtract_modulo(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_subtract_modulo(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2528,10 +2464,9 @@ _chop_subtract_modulo(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopSubtractModulo(self->image, imagep->image)); } -static PyObject* -_chop_soft_light(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_soft_light(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2540,10 +2475,9 @@ _chop_soft_light(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopSoftLight(self->image, imagep->image)); } -static PyObject* -_chop_hard_light(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_hard_light(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2552,10 +2486,9 @@ _chop_hard_light(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingChopHardLight(self->image, imagep->image)); } -static PyObject* -_chop_overlay(ImagingObject* self, PyObject* args) -{ - ImagingObject* imagep; +static PyObject * +_chop_overlay(ImagingObject *self, PyObject *args) { + ImagingObject *imagep; if (!PyArg_ParseTuple(args, "O!", &Imaging_Type, &imagep)) { return NULL; @@ -2565,24 +2498,21 @@ _chop_overlay(ImagingObject* self, PyObject* args) } #endif - /* -------------------------------------------------------------------- */ #ifdef WITH_IMAGEDRAW -static PyObject* -_font_new(PyObject* self_, PyObject* args) -{ +static PyObject * +_font_new(PyObject *self_, PyObject *args) { ImagingFontObject *self; int i, y0, y1; - static const char* wrong_length = "descriptor table has wrong size"; + static const char *wrong_length = "descriptor table has wrong size"; - ImagingObject* imagep; - unsigned char* glyphdata; + ImagingObject *imagep; + unsigned char *glyphdata; Py_ssize_t glyphdata_length; - if (!PyArg_ParseTuple(args, "O!y#", - &Imaging_Type, &imagep, - &glyphdata, &glyphdata_length)) { + if (!PyArg_ParseTuple( + args, "O!y#", &Imaging_Type, &imagep, &glyphdata, &glyphdata_length)) { return NULL; } @@ -2629,19 +2559,17 @@ _font_new(PyObject* self_, PyObject* args) Py_INCREF(imagep); self->ref = imagep; - return (PyObject*) self; + return (PyObject *)self; } static void -_font_dealloc(ImagingFontObject* self) -{ +_font_dealloc(ImagingFontObject *self) { Py_XDECREF(self->ref); PyObject_Del(self); } static inline int -textwidth(ImagingFontObject* self, const unsigned char* text) -{ +textwidth(ImagingFontObject *self, const unsigned char *text) { int xsize; for (xsize = 0; *text; text++) { @@ -2651,16 +2579,17 @@ textwidth(ImagingFontObject* self, const unsigned char* text) return xsize; } -void _font_text_asBytes(PyObject* encoded_string, unsigned char** text){ +void +_font_text_asBytes(PyObject *encoded_string, unsigned char **text) { /* Allocates *text, returns a 'new reference'. Caller is required to free */ - PyObject* bytes = NULL; + PyObject *bytes = NULL; Py_ssize_t len = 0; char *buffer; *text = NULL; - if (PyUnicode_CheckExact(encoded_string)){ + if (PyUnicode_CheckExact(encoded_string)) { bytes = PyUnicode_AsLatin1String(encoded_string); if (!bytes) { return; @@ -2670,7 +2599,7 @@ void _font_text_asBytes(PyObject* encoded_string, unsigned char** text){ PyBytes_AsStringAndSize(encoded_string, &buffer, &len); } - *text = calloc(len+1,1); + *text = calloc(len + 1, 1); if (*text) { memcpy(*text, buffer, len); } else { @@ -2683,23 +2612,21 @@ void _font_text_asBytes(PyObject* encoded_string, unsigned char** text){ return; } - -static PyObject* -_font_getmask(ImagingFontObject* self, PyObject* args) -{ +static PyObject * +_font_getmask(ImagingFontObject *self, PyObject *args) { Imaging im; Imaging bitmap; int x, b; - int i=0; + int i = 0; int status; - Glyph* glyph; + Glyph *glyph; - PyObject* encoded_string; + PyObject *encoded_string; - unsigned char* text; - char* mode = ""; + unsigned char *text; + char *mode = ""; - if (!PyArg_ParseTuple(args, "O|s:getmask", &encoded_string, &mode)){ + if (!PyArg_ParseTuple(args, "O|s:getmask", &encoded_string, &mode)) { return NULL; } @@ -2715,22 +2642,24 @@ _font_getmask(ImagingFontObject* self, PyObject* args) } b = 0; - (void) ImagingFill(im, &b); + (void)ImagingFill(im, &b); b = self->baseline; for (x = 0; text[i]; i++) { glyph = &self->glyphs[text[i]]; - bitmap = ImagingCrop( - self->bitmap, - glyph->sx0, glyph->sy0, glyph->sx1, glyph->sy1 - ); + bitmap = + ImagingCrop(self->bitmap, glyph->sx0, glyph->sy0, glyph->sx1, glyph->sy1); if (!bitmap) { goto failed; } status = ImagingPaste( - im, bitmap, NULL, - glyph->dx0+x, glyph->dy0+b, glyph->dx1+x, glyph->dy1+b - ); + im, + bitmap, + NULL, + glyph->dx0 + x, + glyph->dy0 + b, + glyph->dx1 + x, + glyph->dy1 + b); ImagingDelete(bitmap); if (status < 0) { goto failed; @@ -2741,18 +2670,17 @@ _font_getmask(ImagingFontObject* self, PyObject* args) free(text); return PyImagingNew(im); - failed: +failed: free(text); ImagingDelete(im); Py_RETURN_NONE; } -static PyObject* -_font_getsize(ImagingFontObject* self, PyObject* args) -{ - unsigned char* text; - PyObject* encoded_string; - PyObject* val; +static PyObject * +_font_getsize(ImagingFontObject *self, PyObject *args) { + unsigned char *text; + PyObject *encoded_string; + PyObject *val; if (!PyArg_ParseTuple(args, "O:getsize", &encoded_string)) { return NULL; @@ -2776,12 +2704,11 @@ static struct PyMethodDef _font_methods[] = { /* -------------------------------------------------------------------- */ -static PyObject* -_draw_new(PyObject* self_, PyObject* args) -{ +static PyObject * +_draw_new(PyObject *self_, PyObject *args) { ImagingDrawObject *self; - ImagingObject* imagep; + ImagingObject *imagep; int blend = 0; if (!PyArg_ParseTuple(args, "O!|i", &Imaging_Type, &imagep, &blend)) { return NULL; @@ -2800,41 +2727,39 @@ _draw_new(PyObject* self_, PyObject* args) self->blend = blend; - return (PyObject*) self; + return (PyObject *)self; } static void -_draw_dealloc(ImagingDrawObject* self) -{ +_draw_dealloc(ImagingDrawObject *self) { Py_XDECREF(self->image); PyObject_Del(self); } -extern Py_ssize_t PyPath_Flatten(PyObject* data, double **xy); +extern Py_ssize_t +PyPath_Flatten(PyObject *data, double **xy); -static PyObject* -_draw_ink(ImagingDrawObject* self, PyObject* args) -{ +static PyObject * +_draw_ink(ImagingDrawObject *self, PyObject *args) { INT32 ink = 0; - PyObject* color; + PyObject *color; if (!PyArg_ParseTuple(args, "O", &color)) { return NULL; } - if (!getink(color, self->image->image, (char*) &ink)) { + if (!getink(color, self->image->image, (char *)&ink)) { return NULL; } - return PyLong_FromLong((int) ink); + return PyLong_FromLong((int)ink); } -static PyObject* -_draw_arc(ImagingDrawObject* self, PyObject* args) -{ - double* xy; +static PyObject * +_draw_arc(ImagingDrawObject *self, PyObject *args) { + double *xy; Py_ssize_t n; - PyObject* data; + PyObject *data; int ink; int width = 0; float start, end; @@ -2852,11 +2777,17 @@ _draw_arc(ImagingDrawObject* self, PyObject* args) return NULL; } - n = ImagingDrawArc(self->image->image, - (int) xy[0], (int) xy[1], - (int) xy[2], (int) xy[3], - start, end, &ink, width, self->blend - ); + n = ImagingDrawArc( + self->image->image, + (int)xy[0], + (int)xy[1], + (int)xy[2], + (int)xy[3], + start, + end, + &ink, + width, + self->blend); free(xy); @@ -2868,14 +2799,13 @@ _draw_arc(ImagingDrawObject* self, PyObject* args) return Py_None; } -static PyObject* -_draw_bitmap(ImagingDrawObject* self, PyObject* args) -{ +static PyObject * +_draw_bitmap(ImagingDrawObject *self, PyObject *args) { double *xy; Py_ssize_t n; PyObject *data; - ImagingObject* bitmap; + ImagingObject *bitmap; int ink; if (!PyArg_ParseTuple(args, "OO!i", &data, &Imaging_Type, &bitmap, &ink)) { return NULL; @@ -2886,17 +2816,14 @@ _draw_bitmap(ImagingDrawObject* self, PyObject* args) return NULL; } if (n != 1) { - PyErr_SetString(PyExc_TypeError, - "coordinate list must contain exactly 1 coordinate" - ); + PyErr_SetString( + PyExc_TypeError, "coordinate list must contain exactly 1 coordinate"); free(xy); return NULL; } n = ImagingDrawBitmap( - self->image->image, (int) xy[0], (int) xy[1], bitmap->image, - &ink, self->blend - ); + self->image->image, (int)xy[0], (int)xy[1], bitmap->image, &ink, self->blend); free(xy); @@ -2908,216 +2835,12 @@ _draw_bitmap(ImagingDrawObject* self, PyObject* args) return Py_None; } -static PyObject* -_draw_chord(ImagingDrawObject* self, PyObject* args) -{ - double* xy; - Py_ssize_t n; - - PyObject* data; - int ink, fill; - int width = 0; - float start, end; - if (!PyArg_ParseTuple(args, "Offii|i", - &data, &start, &end, &ink, &fill, &width)) { - return NULL; - } - - n = PyPath_Flatten(data, &xy); - if (n < 0) { - return NULL; - } - if (n != 2) { - PyErr_SetString(PyExc_TypeError, must_be_two_coordinates); - free(xy); - return NULL; - } - - n = ImagingDrawChord(self->image->image, - (int) xy[0], (int) xy[1], - (int) xy[2], (int) xy[3], - start, end, &ink, fill, width, self->blend - ); - - free(xy); - - if (n < 0) { - return NULL; - } - - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject* -_draw_ellipse(ImagingDrawObject* self, PyObject* args) -{ - double* xy; - Py_ssize_t n; - - PyObject* data; - int ink; - int fill = 0; - int width = 0; - if (!PyArg_ParseTuple(args, "Oi|ii", &data, &ink, &fill, &width)) { - return NULL; - } - - n = PyPath_Flatten(data, &xy); - if (n < 0) { - return NULL; - } - if (n != 2) { - PyErr_SetString(PyExc_TypeError, must_be_two_coordinates); - free(xy); - return NULL; - } - - n = ImagingDrawEllipse(self->image->image, - (int) xy[0], (int) xy[1], - (int) xy[2], (int) xy[3], - &ink, fill, width, self->blend - ); - - free(xy); - - if (n < 0) { - return NULL; - } - - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject* -_draw_lines(ImagingDrawObject* self, PyObject* args) -{ +static PyObject * +_draw_chord(ImagingDrawObject *self, PyObject *args) { double *xy; - Py_ssize_t i, n; + Py_ssize_t n; PyObject *data; - int ink; - int width = 0; - if (!PyArg_ParseTuple(args, "Oi|i", &data, &ink, &width)) { - return NULL; - } - - n = PyPath_Flatten(data, &xy); - if (n < 0) { - return NULL; - } - - if (width <= 1) { - double *p = NULL; - for (i = 0; i < n-1; i++) { - p = &xy[i+i]; - if (ImagingDrawLine( - self->image->image, - (int) p[0], (int) p[1], (int) p[2], (int) p[3], - &ink, self->blend) < 0) { - free(xy); - return NULL; - } - } - if (p) {/* draw last point */ - ImagingDrawPoint( - self->image->image, - (int) p[2], (int) p[3], - &ink, self->blend - ); - } - } else { - for (i = 0; i < n-1; i++) { - double *p = &xy[i+i]; - if (ImagingDrawWideLine( - self->image->image, - (int) p[0], (int) p[1], (int) p[2], (int) p[3], - &ink, width, self->blend) < 0) { - free(xy); - return NULL; - } - } - } - - free(xy); - - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject* -_draw_points(ImagingDrawObject* self, PyObject* args) -{ - double *xy; - Py_ssize_t i, n; - - PyObject *data; - int ink; - if (!PyArg_ParseTuple(args, "Oi", &data, &ink)) { - return NULL; - } - - n = PyPath_Flatten(data, &xy); - if (n < 0) { - return NULL; - } - - for (i = 0; i < n; i++) { - double *p = &xy[i+i]; - if (ImagingDrawPoint(self->image->image, (int) p[0], (int) p[1], - &ink, self->blend) < 0) { - free(xy); - return NULL; - } - } - - free(xy); - - Py_INCREF(Py_None); - return Py_None; -} - -#ifdef WITH_ARROW - -/* from outline.c */ -extern ImagingOutline PyOutline_AsOutline(PyObject* outline); - -static PyObject* -_draw_outline(ImagingDrawObject* self, PyObject* args) -{ - ImagingOutline outline; - - PyObject* outline_; - int ink; - int fill = 0; - if (!PyArg_ParseTuple(args, "Oi|i", &outline_, &ink, &fill)) { - return NULL; - } - - outline = PyOutline_AsOutline(outline_); - if (!outline) { - PyErr_SetString(PyExc_TypeError, "expected outline object"); - return NULL; - } - - if (ImagingDrawOutline(self->image->image, outline, - &ink, fill, self->blend) < 0) { - return NULL; - } - - Py_INCREF(Py_None); - return Py_None; -} - -#endif - -static PyObject* -_draw_pieslice(ImagingDrawObject* self, PyObject* args) -{ - double* xy; - Py_ssize_t n; - - PyObject* data; int ink, fill; int width = 0; float start, end; @@ -3135,11 +2858,18 @@ _draw_pieslice(ImagingDrawObject* self, PyObject* args) return NULL; } - n = ImagingDrawPieslice(self->image->image, - (int) xy[0], (int) xy[1], - (int) xy[2], (int) xy[3], - start, end, &ink, fill, width, self->blend - ); + n = ImagingDrawChord( + self->image->image, + (int)xy[0], + (int)xy[1], + (int)xy[2], + (int)xy[3], + start, + end, + &ink, + fill, + width, + self->blend); free(xy); @@ -3151,65 +2881,12 @@ _draw_pieslice(ImagingDrawObject* self, PyObject* args) return Py_None; } -static PyObject* -_draw_polygon(ImagingDrawObject* self, PyObject* args) -{ +static PyObject * +_draw_ellipse(ImagingDrawObject *self, PyObject *args) { double *xy; - int *ixy; - Py_ssize_t n, i; - - PyObject* data; - int ink; - int fill = 0; - if (!PyArg_ParseTuple(args, "Oi|i", &data, &ink, &fill)) { - return NULL; - } - - n = PyPath_Flatten(data, &xy); - if (n < 0) { - return NULL; - } - if (n < 2) { - PyErr_SetString(PyExc_TypeError, - "coordinate list must contain at least 2 coordinates" - ); - free(xy); - return NULL; - } - - /* Copy list of vertices to array */ - ixy = (int*) calloc(n, 2 * sizeof(int)); - if (ixy == NULL) { - free(xy); - return ImagingError_MemoryError(); - } - - for (i = 0; i < n; i++) { - ixy[i+i] = (int) xy[i+i]; - ixy[i+i+1] = (int) xy[i+i+1]; - } - - free(xy); - - if (ImagingDrawPolygon(self->image->image, n, ixy, - &ink, fill, self->blend) < 0) { - free(ixy); - return NULL; - } - - free(ixy); - - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject* -_draw_rectangle(ImagingDrawObject* self, PyObject* args) -{ - double* xy; Py_ssize_t n; - PyObject* data; + PyObject *data; int ink; int fill = 0; int width = 0; @@ -3227,11 +2904,280 @@ _draw_rectangle(ImagingDrawObject* self, PyObject* args) return NULL; } - n = ImagingDrawRectangle(self->image->image, - (int) xy[0], (int) xy[1], - (int) xy[2], (int) xy[3], - &ink, fill, width, self->blend - ); + n = ImagingDrawEllipse( + self->image->image, + (int)xy[0], + (int)xy[1], + (int)xy[2], + (int)xy[3], + &ink, + fill, + width, + self->blend); + + free(xy); + + if (n < 0) { + return NULL; + } + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +_draw_lines(ImagingDrawObject *self, PyObject *args) { + double *xy; + Py_ssize_t i, n; + + PyObject *data; + int ink; + int width = 0; + if (!PyArg_ParseTuple(args, "Oi|i", &data, &ink, &width)) { + return NULL; + } + + n = PyPath_Flatten(data, &xy); + if (n < 0) { + return NULL; + } + + if (width <= 1) { + double *p = NULL; + for (i = 0; i < n - 1; i++) { + p = &xy[i + i]; + if (ImagingDrawLine( + self->image->image, + (int)p[0], + (int)p[1], + (int)p[2], + (int)p[3], + &ink, + self->blend) < 0) { + free(xy); + return NULL; + } + } + if (p) { /* draw last point */ + ImagingDrawPoint( + self->image->image, (int)p[2], (int)p[3], &ink, self->blend); + } + } else { + for (i = 0; i < n - 1; i++) { + double *p = &xy[i + i]; + if (ImagingDrawWideLine( + self->image->image, + (int)p[0], + (int)p[1], + (int)p[2], + (int)p[3], + &ink, + width, + self->blend) < 0) { + free(xy); + return NULL; + } + } + } + + free(xy); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +_draw_points(ImagingDrawObject *self, PyObject *args) { + double *xy; + Py_ssize_t i, n; + + PyObject *data; + int ink; + if (!PyArg_ParseTuple(args, "Oi", &data, &ink)) { + return NULL; + } + + n = PyPath_Flatten(data, &xy); + if (n < 0) { + return NULL; + } + + for (i = 0; i < n; i++) { + double *p = &xy[i + i]; + if (ImagingDrawPoint( + self->image->image, (int)p[0], (int)p[1], &ink, self->blend) < 0) { + free(xy); + return NULL; + } + } + + free(xy); + + Py_INCREF(Py_None); + return Py_None; +} + +#ifdef WITH_ARROW + +/* from outline.c */ +extern ImagingOutline +PyOutline_AsOutline(PyObject *outline); + +static PyObject * +_draw_outline(ImagingDrawObject *self, PyObject *args) { + ImagingOutline outline; + + PyObject *outline_; + int ink; + int fill = 0; + if (!PyArg_ParseTuple(args, "Oi|i", &outline_, &ink, &fill)) { + return NULL; + } + + outline = PyOutline_AsOutline(outline_); + if (!outline) { + PyErr_SetString(PyExc_TypeError, "expected outline object"); + return NULL; + } + + if (ImagingDrawOutline(self->image->image, outline, &ink, fill, self->blend) < 0) { + return NULL; + } + + Py_INCREF(Py_None); + return Py_None; +} + +#endif + +static PyObject * +_draw_pieslice(ImagingDrawObject *self, PyObject *args) { + double *xy; + Py_ssize_t n; + + PyObject *data; + int ink, fill; + int width = 0; + float start, end; + if (!PyArg_ParseTuple(args, "Offii|i", &data, &start, &end, &ink, &fill, &width)) { + return NULL; + } + + n = PyPath_Flatten(data, &xy); + if (n < 0) { + return NULL; + } + if (n != 2) { + PyErr_SetString(PyExc_TypeError, must_be_two_coordinates); + free(xy); + return NULL; + } + + n = ImagingDrawPieslice( + self->image->image, + (int)xy[0], + (int)xy[1], + (int)xy[2], + (int)xy[3], + start, + end, + &ink, + fill, + width, + self->blend); + + free(xy); + + if (n < 0) { + return NULL; + } + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +_draw_polygon(ImagingDrawObject *self, PyObject *args) { + double *xy; + int *ixy; + Py_ssize_t n, i; + + PyObject *data; + int ink; + int fill = 0; + if (!PyArg_ParseTuple(args, "Oi|i", &data, &ink, &fill)) { + return NULL; + } + + n = PyPath_Flatten(data, &xy); + if (n < 0) { + return NULL; + } + if (n < 2) { + PyErr_SetString( + PyExc_TypeError, "coordinate list must contain at least 2 coordinates"); + free(xy); + return NULL; + } + + /* Copy list of vertices to array */ + ixy = (int *)calloc(n, 2 * sizeof(int)); + if (ixy == NULL) { + free(xy); + return ImagingError_MemoryError(); + } + + for (i = 0; i < n; i++) { + ixy[i + i] = (int)xy[i + i]; + ixy[i + i + 1] = (int)xy[i + i + 1]; + } + + free(xy); + + if (ImagingDrawPolygon(self->image->image, n, ixy, &ink, fill, self->blend) < 0) { + free(ixy); + return NULL; + } + + free(ixy); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +_draw_rectangle(ImagingDrawObject *self, PyObject *args) { + double *xy; + Py_ssize_t n; + + PyObject *data; + int ink; + int fill = 0; + int width = 0; + if (!PyArg_ParseTuple(args, "Oi|ii", &data, &ink, &fill, &width)) { + return NULL; + } + + n = PyPath_Flatten(data, &xy); + if (n < 0) { + return NULL; + } + if (n != 2) { + PyErr_SetString(PyExc_TypeError, must_be_two_coordinates); + free(xy); + return NULL; + } + + n = ImagingDrawRectangle( + self->image->image, + (int)xy[0], + (int)xy[1], + (int)xy[2], + (int)xy[3], + &ink, + fill, + width, + self->blend); free(xy); @@ -3265,10 +3211,8 @@ static struct PyMethodDef _draw_methods[] = { #endif - -static PyObject* -pixel_access_new(ImagingObject* imagep, PyObject* args) -{ +static PyObject * +pixel_access_new(ImagingObject *imagep, PyObject *args) { PixelAccessObject *self; int readonly = 0; @@ -3287,19 +3231,17 @@ pixel_access_new(ImagingObject* imagep, PyObject* args) self->readonly = readonly; - return (PyObject*) self; + return (PyObject *)self; } static void -pixel_access_dealloc(PixelAccessObject* self) -{ +pixel_access_dealloc(PixelAccessObject *self) { Py_XDECREF(self->image); PyObject_Del(self); } static PyObject * -pixel_access_getitem(PixelAccessObject *self, PyObject *xy) -{ +pixel_access_getitem(PixelAccessObject *self, PyObject *xy) { int x, y; if (_getxy(xy, &x, &y)) { return NULL; @@ -3309,14 +3251,13 @@ pixel_access_getitem(PixelAccessObject *self, PyObject *xy) } static int -pixel_access_setitem(PixelAccessObject *self, PyObject *xy, PyObject *color) -{ +pixel_access_setitem(PixelAccessObject *self, PyObject *xy, PyObject *color) { Imaging im = self->image->image; char ink[4]; int x, y; if (self->readonly) { - (void) ImagingError_ValueError(readonly); + (void)ImagingError_ValueError(readonly); return -1; } @@ -3336,7 +3277,7 @@ pixel_access_setitem(PixelAccessObject *self, PyObject *xy, PyObject *color) return -1; } - if (!color) {/* FIXME: raise exception? */ + if (!color) { /* FIXME: raise exception? */ return 0; } @@ -3355,29 +3296,36 @@ pixel_access_setitem(PixelAccessObject *self, PyObject *xy, PyObject *color) #ifdef WITH_EFFECTS -static PyObject* -_effect_mandelbrot(ImagingObject* self, PyObject* args) -{ +static PyObject * +_effect_mandelbrot(ImagingObject *self, PyObject *args) { int xsize = 512; int ysize = 512; double extent[4]; int quality = 100; - extent[0] = -3; extent[1] = -2.5; - extent[2] = 2; extent[3] = 2.5; + extent[0] = -3; + extent[1] = -2.5; + extent[2] = 2; + extent[3] = 2.5; - if (!PyArg_ParseTuple(args, "|(ii)(dddd)i", &xsize, &ysize, - &extent[0], &extent[1], &extent[2], &extent[3], - &quality)) { + if (!PyArg_ParseTuple( + args, + "|(ii)(dddd)i", + &xsize, + &ysize, + &extent[0], + &extent[1], + &extent[2], + &extent[3], + &quality)) { return NULL; } return PyImagingNew(ImagingEffectMandelbrot(xsize, ysize, extent, quality)); } -static PyObject* -_effect_noise(ImagingObject* self, PyObject* args) -{ +static PyObject * +_effect_noise(ImagingObject *self, PyObject *args) { int xsize, ysize; float sigma = 128; if (!PyArg_ParseTuple(args, "(ii)|f", &xsize, &ysize, &sigma)) { @@ -3387,9 +3335,8 @@ _effect_noise(ImagingObject* self, PyObject* args) return PyImagingNew(ImagingEffectNoise(xsize, ysize, sigma)); } -static PyObject* -_effect_spread(ImagingObject* self, PyObject* args) -{ +static PyObject * +_effect_spread(ImagingObject *self, PyObject *args) { int dist; if (!PyArg_ParseTuple(args, "i", &dist)) { @@ -3405,30 +3352,33 @@ _effect_spread(ImagingObject* self, PyObject* args) /* UTILITIES */ /* -------------------------------------------------------------------- */ - -static PyObject* -_getcodecstatus(PyObject* self, PyObject* args) -{ +static PyObject * +_getcodecstatus(PyObject *self, PyObject *args) { int status; - char* msg; + char *msg; if (!PyArg_ParseTuple(args, "i", &status)) { return NULL; } switch (status) { - case IMAGING_CODEC_OVERRUN: - msg = "buffer overrun"; break; - case IMAGING_CODEC_BROKEN: - msg = "broken data stream"; break; - case IMAGING_CODEC_UNKNOWN: - msg = "unrecognized data stream contents"; break; - case IMAGING_CODEC_CONFIG: - msg = "codec configuration error"; break; - case IMAGING_CODEC_MEMORY: - msg = "out of memory"; break; - default: - Py_RETURN_NONE; + case IMAGING_CODEC_OVERRUN: + msg = "buffer overrun"; + break; + case IMAGING_CODEC_BROKEN: + msg = "broken data stream"; + break; + case IMAGING_CODEC_UNKNOWN: + msg = "unrecognized data stream contents"; + break; + case IMAGING_CODEC_CONFIG: + msg = "codec configuration error"; + break; + case IMAGING_CODEC_MEMORY: + msg = "out of memory"; + break; + default: + Py_RETURN_NONE; } return PyUnicode_FromString(msg); @@ -3438,11 +3388,9 @@ _getcodecstatus(PyObject* self, PyObject* args) /* DEBUGGING HELPERS */ /* -------------------------------------------------------------------- */ - -static PyObject* -_save_ppm(ImagingObject* self, PyObject* args) -{ - char* filename; +static PyObject * +_save_ppm(ImagingObject *self, PyObject *args) { + char *filename; if (!PyArg_ParseTuple(args, "s", &filename)) { return NULL; @@ -3456,7 +3404,6 @@ _save_ppm(ImagingObject* self, PyObject* args) return Py_None; } - /* -------------------------------------------------------------------- */ /* methods */ @@ -3562,73 +3509,65 @@ static struct PyMethodDef methods[] = { {NULL, NULL} /* sentinel */ }; - /* attributes */ -static PyObject* -_getattr_mode(ImagingObject* self, void* closure) -{ +static PyObject * +_getattr_mode(ImagingObject *self, void *closure) { return PyUnicode_FromString(self->image->mode); } -static PyObject* -_getattr_size(ImagingObject* self, void* closure) -{ +static PyObject * +_getattr_size(ImagingObject *self, void *closure) { return Py_BuildValue("ii", self->image->xsize, self->image->ysize); } -static PyObject* -_getattr_bands(ImagingObject* self, void* closure) -{ +static PyObject * +_getattr_bands(ImagingObject *self, void *closure) { return PyLong_FromLong(self->image->bands); } -static PyObject* -_getattr_id(ImagingObject* self, void* closure) -{ - return PyLong_FromSsize_t((Py_ssize_t) self->image); +static PyObject * +_getattr_id(ImagingObject *self, void *closure) { + return PyLong_FromSsize_t((Py_ssize_t)self->image); } -static PyObject* -_getattr_ptr(ImagingObject* self, void* closure) -{ +static PyObject * +_getattr_ptr(ImagingObject *self, void *closure) { return PyCapsule_New(self->image, IMAGING_MAGIC, NULL); } -static PyObject* -_getattr_unsafe_ptrs(ImagingObject* self, void* closure) -{ - return Py_BuildValue("(sn)(sn)(sn)", - "image8", self->image->image8, - "image32", self->image->image32, - "image", self->image->image - ); +static PyObject * +_getattr_unsafe_ptrs(ImagingObject *self, void *closure) { + return Py_BuildValue( + "(sn)(sn)(sn)", + "image8", + self->image->image8, + "image32", + self->image->image32, + "image", + self->image->image); }; - static struct PyGetSetDef getsetters[] = { - { "mode", (getter) _getattr_mode }, - { "size", (getter) _getattr_size }, - { "bands", (getter) _getattr_bands }, - { "id", (getter) _getattr_id }, - { "ptr", (getter) _getattr_ptr }, - { "unsafe_ptrs", (getter) _getattr_unsafe_ptrs }, - { NULL } -}; + {"mode", (getter)_getattr_mode}, + {"size", (getter)_getattr_size}, + {"bands", (getter)_getattr_bands}, + {"id", (getter)_getattr_id}, + {"ptr", (getter)_getattr_ptr}, + {"unsafe_ptrs", (getter)_getattr_unsafe_ptrs}, + {NULL}}; /* basic sequence semantics */ static Py_ssize_t -image_length(ImagingObject *self) -{ +image_length(ImagingObject *self) { Imaging im = self->image; - return (Py_ssize_t) im->xsize * im->ysize; + return (Py_ssize_t)im->xsize * im->ysize; } static PyObject * -image_item(ImagingObject *self, Py_ssize_t i) -{ +image_item(ImagingObject *self, Py_ssize_t i) { int x, y; Imaging im = self->image; @@ -3643,154 +3582,150 @@ image_item(ImagingObject *self, Py_ssize_t i) } static PySequenceMethods image_as_sequence = { - (lenfunc) image_length, /*sq_length*/ - (binaryfunc) NULL, /*sq_concat*/ - (ssizeargfunc) NULL, /*sq_repeat*/ - (ssizeargfunc) image_item, /*sq_item*/ - (ssizessizeargfunc) NULL, /*sq_slice*/ - (ssizeobjargproc) NULL, /*sq_ass_item*/ - (ssizessizeobjargproc) NULL, /*sq_ass_slice*/ + (lenfunc)image_length, /*sq_length*/ + (binaryfunc)NULL, /*sq_concat*/ + (ssizeargfunc)NULL, /*sq_repeat*/ + (ssizeargfunc)image_item, /*sq_item*/ + (ssizessizeargfunc)NULL, /*sq_slice*/ + (ssizeobjargproc)NULL, /*sq_ass_item*/ + (ssizessizeobjargproc)NULL, /*sq_ass_slice*/ }; - /* type description */ static PyTypeObject Imaging_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "ImagingCore", /*tp_name*/ - sizeof(ImagingObject), /*tp_size*/ - 0, /*tp_itemsize*/ + PyVarObject_HEAD_INIT(NULL, 0) "ImagingCore", /*tp_name*/ + sizeof(ImagingObject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - (destructor)_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - &image_as_sequence, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - methods, /*tp_methods*/ - 0, /*tp_members*/ - getsetters, /*tp_getset*/ + (destructor)_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + &image_as_sequence, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + methods, /*tp_methods*/ + 0, /*tp_members*/ + getsetters, /*tp_getset*/ }; #ifdef WITH_IMAGEDRAW static PyTypeObject ImagingFont_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "ImagingFont", /*tp_name*/ - sizeof(ImagingFontObject), /*tp_size*/ - 0, /*tp_itemsize*/ + PyVarObject_HEAD_INIT(NULL, 0) "ImagingFont", /*tp_name*/ + sizeof(ImagingFontObject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - (destructor)_font_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - _font_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ + (destructor)_font_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + _font_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ }; static PyTypeObject ImagingDraw_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "ImagingDraw", /*tp_name*/ - sizeof(ImagingDrawObject), /*tp_size*/ - 0, /*tp_itemsize*/ + PyVarObject_HEAD_INIT(NULL, 0) "ImagingDraw", /*tp_name*/ + sizeof(ImagingDrawObject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - (destructor)_draw_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - _draw_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ + (destructor)_draw_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + _draw_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ }; #endif static PyMappingMethods pixel_access_as_mapping = { - (lenfunc) NULL, /*mp_length*/ - (binaryfunc) pixel_access_getitem, /*mp_subscript*/ - (objobjargproc) pixel_access_setitem, /*mp_ass_subscript*/ + (lenfunc)NULL, /*mp_length*/ + (binaryfunc)pixel_access_getitem, /*mp_subscript*/ + (objobjargproc)pixel_access_setitem, /*mp_ass_subscript*/ }; /* type description */ static PyTypeObject PixelAccess_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "PixelAccess", sizeof(PixelAccessObject), 0, + PyVarObject_HEAD_INIT(NULL, 0) "PixelAccess", + sizeof(PixelAccessObject), + 0, /* methods */ (destructor)pixel_access_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - &pixel_access_as_mapping, /*tp_as_mapping */ - 0 /*tp_hash*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + &pixel_access_as_mapping, /*tp_as_mapping */ + 0 /*tp_hash*/ }; /* -------------------------------------------------------------------- */ -static PyObject* -_get_stats(PyObject* self, PyObject* args) -{ - PyObject* d; +static PyObject * +_get_stats(PyObject *self, PyObject *args) { + PyObject *d; ImagingMemoryArena arena = &ImagingDefaultArena; if (!PyArg_ParseTuple(args, ":get_stats")) { @@ -3798,27 +3733,23 @@ _get_stats(PyObject* self, PyObject* args) } d = PyDict_New(); - if ( ! d) { + if (!d) { return NULL; } - PyDict_SetItemString(d, "new_count", - PyLong_FromLong(arena->stats_new_count)); - PyDict_SetItemString(d, "allocated_blocks", - PyLong_FromLong(arena->stats_allocated_blocks)); - PyDict_SetItemString(d, "reused_blocks", - PyLong_FromLong(arena->stats_reused_blocks)); - PyDict_SetItemString(d, "reallocated_blocks", - PyLong_FromLong(arena->stats_reallocated_blocks)); - PyDict_SetItemString(d, "freed_blocks", - PyLong_FromLong(arena->stats_freed_blocks)); - PyDict_SetItemString(d, "blocks_cached", - PyLong_FromLong(arena->blocks_cached)); + PyDict_SetItemString(d, "new_count", PyLong_FromLong(arena->stats_new_count)); + PyDict_SetItemString( + d, "allocated_blocks", PyLong_FromLong(arena->stats_allocated_blocks)); + PyDict_SetItemString( + d, "reused_blocks", PyLong_FromLong(arena->stats_reused_blocks)); + PyDict_SetItemString( + d, "reallocated_blocks", PyLong_FromLong(arena->stats_reallocated_blocks)); + PyDict_SetItemString(d, "freed_blocks", PyLong_FromLong(arena->stats_freed_blocks)); + PyDict_SetItemString(d, "blocks_cached", PyLong_FromLong(arena->blocks_cached)); return d; } -static PyObject* -_reset_stats(PyObject* self, PyObject* args) -{ +static PyObject * +_reset_stats(PyObject *self, PyObject *args) { ImagingMemoryArena arena = &ImagingDefaultArena; if (!PyArg_ParseTuple(args, ":reset_stats")) { @@ -3835,9 +3766,8 @@ _reset_stats(PyObject* self, PyObject* args) return Py_None; } -static PyObject* -_get_alignment(PyObject* self, PyObject* args) -{ +static PyObject * +_get_alignment(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":get_alignment")) { return NULL; } @@ -3845,9 +3775,8 @@ _get_alignment(PyObject* self, PyObject* args) return PyLong_FromLong(ImagingDefaultArena.alignment); } -static PyObject* -_get_block_size(PyObject* self, PyObject* args) -{ +static PyObject * +_get_block_size(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":get_block_size")) { return NULL; } @@ -3855,9 +3784,8 @@ _get_block_size(PyObject* self, PyObject* args) return PyLong_FromLong(ImagingDefaultArena.block_size); } -static PyObject* -_get_blocks_max(PyObject* self, PyObject* args) -{ +static PyObject * +_get_blocks_max(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":get_blocks_max")) { return NULL; } @@ -3865,9 +3793,8 @@ _get_blocks_max(PyObject* self, PyObject* args) return PyLong_FromLong(ImagingDefaultArena.blocks_max); } -static PyObject* -_set_alignment(PyObject* self, PyObject* args) -{ +static PyObject * +_set_alignment(PyObject *self, PyObject *args) { int alignment; if (!PyArg_ParseTuple(args, "i:set_alignment", &alignment)) { return NULL; @@ -3889,23 +3816,20 @@ _set_alignment(PyObject* self, PyObject* args) return Py_None; } -static PyObject* -_set_block_size(PyObject* self, PyObject* args) -{ +static PyObject * +_set_block_size(PyObject *self, PyObject *args) { int block_size; if (!PyArg_ParseTuple(args, "i:set_block_size", &block_size)) { return NULL; } if (block_size <= 0) { - PyErr_SetString(PyExc_ValueError, - "block_size should be greater than 0"); + PyErr_SetString(PyExc_ValueError, "block_size should be greater than 0"); return NULL; } if (block_size & 0xfff) { - PyErr_SetString(PyExc_ValueError, - "block_size should be multiple of 4096"); + PyErr_SetString(PyExc_ValueError, "block_size should be multiple of 4096"); return NULL; } @@ -3915,27 +3839,24 @@ _set_block_size(PyObject* self, PyObject* args) return Py_None; } -static PyObject* -_set_blocks_max(PyObject* self, PyObject* args) -{ +static PyObject * +_set_blocks_max(PyObject *self, PyObject *args) { int blocks_max; if (!PyArg_ParseTuple(args, "i:set_blocks_max", &blocks_max)) { return NULL; } if (blocks_max < 0) { - PyErr_SetString(PyExc_ValueError, - "blocks_max should be greater than 0"); + PyErr_SetString(PyExc_ValueError, "blocks_max should be greater than 0"); return NULL; - } - else if ( (unsigned long)blocks_max > SIZE_MAX/sizeof(ImagingDefaultArena.blocks_pool[0])) { - PyErr_SetString(PyExc_ValueError, - "blocks_max is too large"); + } else if ( + (unsigned long)blocks_max > + SIZE_MAX / sizeof(ImagingDefaultArena.blocks_pool[0])) { + PyErr_SetString(PyExc_ValueError, "blocks_max is too large"); return NULL; } - - if ( ! ImagingMemorySetBlocksMax(&ImagingDefaultArena, blocks_max)) { + if (!ImagingMemorySetBlocksMax(&ImagingDefaultArena, blocks_max)) { return ImagingError_MemoryError(); } @@ -3943,9 +3864,8 @@ _set_blocks_max(PyObject* self, PyObject* args) return Py_None; } -static PyObject* -_clear_cache(PyObject* self, PyObject* args) -{ +static PyObject * +_clear_cache(PyObject *self, PyObject *args) { int i = 0; if (!PyArg_ParseTuple(args, "|i:clear_cache", &i)) { @@ -3964,59 +3884,99 @@ _clear_cache(PyObject* self, PyObject* args) pluggable codecs, but not before PIL 1.2 */ /* Decoders (in decode.c) */ -extern PyObject* PyImaging_BcnDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_BitDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_FliDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_GifDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_HexDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_JpegDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_Jpeg2KDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_LibTiffDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_PackbitsDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_PcdDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_PcxDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_RawDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_SgiRleDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_SunRleDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_TgaRleDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_XbmDecoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_ZipDecoderNew(PyObject* self, PyObject* args); +extern PyObject * +PyImaging_BcnDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_BitDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_FliDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_GifDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_HexDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_JpegDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_Jpeg2KDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_LibTiffDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_PackbitsDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_PcdDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_PcxDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_RawDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_SgiRleDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_SunRleDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_TgaRleDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_XbmDecoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_ZipDecoderNew(PyObject *self, PyObject *args); /* Encoders (in encode.c) */ -extern PyObject* PyImaging_EpsEncoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_GifEncoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_JpegEncoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_Jpeg2KEncoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_PcxEncoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_RawEncoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_TgaRleEncoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_XbmEncoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_ZipEncoderNew(PyObject* self, PyObject* args); -extern PyObject* PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args); +extern PyObject * +PyImaging_EpsEncoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_GifEncoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_JpegEncoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_Jpeg2KEncoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_PcxEncoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_RawEncoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_TgaRleEncoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_XbmEncoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_ZipEncoderNew(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args); /* Display support etc (in display.c) */ #ifdef _WIN32 -extern PyObject* PyImaging_CreateWindowWin32(PyObject* self, PyObject* args); -extern PyObject* PyImaging_DisplayWin32(PyObject* self, PyObject* args); -extern PyObject* PyImaging_DisplayModeWin32(PyObject* self, PyObject* args); -extern PyObject* PyImaging_GrabScreenWin32(PyObject* self, PyObject* args); -extern PyObject* PyImaging_GrabClipboardWin32(PyObject* self, PyObject* args); -extern PyObject* PyImaging_ListWindowsWin32(PyObject* self, PyObject* args); -extern PyObject* PyImaging_EventLoopWin32(PyObject* self, PyObject* args); -extern PyObject* PyImaging_DrawWmf(PyObject* self, PyObject* args); +extern PyObject * +PyImaging_CreateWindowWin32(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_DisplayWin32(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_DisplayModeWin32(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_GrabScreenWin32(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_GrabClipboardWin32(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_ListWindowsWin32(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_EventLoopWin32(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_DrawWmf(PyObject *self, PyObject *args); #endif #ifdef HAVE_XCB -extern PyObject* PyImaging_GrabScreenX11(PyObject* self, PyObject* args); +extern PyObject * +PyImaging_GrabScreenX11(PyObject *self, PyObject *args); #endif /* Experimental path stuff (in path.c) */ -extern PyObject* PyPath_Create(ImagingObject* self, PyObject* args); +extern PyObject * +PyPath_Create(ImagingObject *self, PyObject *args); /* Experimental outline stuff (in outline.c) */ -extern PyObject* PyOutline_Create(ImagingObject* self, PyObject* args); +extern PyObject * +PyOutline_Create(ImagingObject *self, PyObject *args); -extern PyObject* PyImaging_Mapper(PyObject* self, PyObject* args); -extern PyObject* PyImaging_MapBuffer(PyObject* self, PyObject* args); +extern PyObject * +PyImaging_Mapper(PyObject *self, PyObject *args); +extern PyObject * +PyImaging_MapBuffer(PyObject *self, PyObject *args); static PyMethodDef functions[] = { @@ -4068,7 +4028,7 @@ static PyMethodDef functions[] = { {"zip_encoder", (PyCFunction)PyImaging_ZipEncoderNew, 1}, #endif - /* Memory mapping */ +/* Memory mapping */ #ifdef WITH_MAPPING #ifdef _WIN32 {"map", (PyCFunction)PyImaging_Mapper, 1}, @@ -4076,7 +4036,7 @@ static PyMethodDef functions[] = { {"map_buffer", (PyCFunction)PyImaging_MapBuffer, 1}, #endif - /* Display support */ +/* Display support */ #ifdef _WIN32 {"display", (PyCFunction)PyImaging_DisplayWin32, 1}, {"display_mode", (PyCFunction)PyImaging_DisplayModeWin32, 1}, @@ -4094,7 +4054,7 @@ static PyMethodDef functions[] = { /* Utilities */ {"getcodecstatus", (PyCFunction)_getcodecstatus, 1}, - /* Special effects (experimental) */ +/* Special effects (experimental) */ #ifdef WITH_EFFECTS {"effect_mandelbrot", (PyCFunction)_effect_mandelbrot, 1}, {"effect_noise", (PyCFunction)_effect_noise, 1}, @@ -4103,18 +4063,18 @@ static PyMethodDef functions[] = { {"wedge", (PyCFunction)_linear_gradient, 1}, /* Compatibility */ #endif - /* Drawing support stuff */ +/* Drawing support stuff */ #ifdef WITH_IMAGEDRAW {"font", (PyCFunction)_font_new, 1}, {"draw", (PyCFunction)_draw_new, 1}, #endif - /* Experimental path stuff */ +/* Experimental path stuff */ #ifdef WITH_IMAGEPATH {"path", (PyCFunction)PyPath_Create, 1}, #endif - /* Experimental arrow graphics stuff */ +/* Experimental arrow graphics stuff */ #ifdef WITH_ARROW {"outline", (PyCFunction)PyOutline_Create, 1}, #endif @@ -4134,9 +4094,9 @@ static PyMethodDef functions[] = { }; static int -setup_module(PyObject* m) { - PyObject* d = PyModule_GetDict(m); - const char* version = (char*)PILLOW_VERSION; +setup_module(PyObject *m) { + PyObject *d = PyModule_GetDict(m); + const char *version = (char *)PILLOW_VERSION; /* Ready object types */ if (PyType_Ready(&Imaging_Type) < 0) { @@ -4159,26 +4119,29 @@ setup_module(PyObject* m) { ImagingAccessInit(); #ifdef HAVE_LIBJPEG - { - extern const char* ImagingJpegVersion(void); - PyDict_SetItemString(d, "jpeglib_version", PyUnicode_FromString(ImagingJpegVersion())); - } + { + extern const char *ImagingJpegVersion(void); + PyDict_SetItemString( + d, "jpeglib_version", PyUnicode_FromString(ImagingJpegVersion())); + } #endif #ifdef HAVE_OPENJPEG - { - extern const char *ImagingJpeg2KVersion(void); - PyDict_SetItemString(d, "jp2klib_version", PyUnicode_FromString(ImagingJpeg2KVersion())); - } + { + extern const char *ImagingJpeg2KVersion(void); + PyDict_SetItemString( + d, "jp2klib_version", PyUnicode_FromString(ImagingJpeg2KVersion())); + } #endif #ifdef LIBJPEG_TURBO_VERSION PyModule_AddObject(m, "HAVE_LIBJPEGTURBO", Py_True); - #define tostr1(a) #a - #define tostr(a) tostr1(a) - PyDict_SetItemString(d, "libjpeg_turbo_version", PyUnicode_FromString(tostr(LIBJPEG_TURBO_VERSION))); - #undef tostr - #undef tostr1 +#define tostr1(a) #a +#define tostr(a) tostr1(a) + PyDict_SetItemString( + d, "libjpeg_turbo_version", PyUnicode_FromString(tostr(LIBJPEG_TURBO_VERSION))); +#undef tostr +#undef tostr1 #else PyModule_AddObject(m, "HAVE_LIBJPEGTURBO", Py_False); #endif @@ -4186,40 +4149,44 @@ setup_module(PyObject* m) { #ifdef HAVE_LIBIMAGEQUANT PyModule_AddObject(m, "HAVE_LIBIMAGEQUANT", Py_True); { - extern const char* ImagingImageQuantVersion(void); - PyDict_SetItemString(d, "imagequant_version", PyUnicode_FromString(ImagingImageQuantVersion())); + extern const char *ImagingImageQuantVersion(void); + PyDict_SetItemString( + d, "imagequant_version", PyUnicode_FromString(ImagingImageQuantVersion())); } #else PyModule_AddObject(m, "HAVE_LIBIMAGEQUANT", Py_False); #endif #ifdef HAVE_LIBZ - /* zip encoding strategies */ - PyModule_AddIntConstant(m, "DEFAULT_STRATEGY", Z_DEFAULT_STRATEGY); - PyModule_AddIntConstant(m, "FILTERED", Z_FILTERED); - PyModule_AddIntConstant(m, "HUFFMAN_ONLY", Z_HUFFMAN_ONLY); - PyModule_AddIntConstant(m, "RLE", Z_RLE); - PyModule_AddIntConstant(m, "FIXED", Z_FIXED); - { - extern const char* ImagingZipVersion(void); - PyDict_SetItemString(d, "zlib_version", PyUnicode_FromString(ImagingZipVersion())); - } + /* zip encoding strategies */ + PyModule_AddIntConstant(m, "DEFAULT_STRATEGY", Z_DEFAULT_STRATEGY); + PyModule_AddIntConstant(m, "FILTERED", Z_FILTERED); + PyModule_AddIntConstant(m, "HUFFMAN_ONLY", Z_HUFFMAN_ONLY); + PyModule_AddIntConstant(m, "RLE", Z_RLE); + PyModule_AddIntConstant(m, "FIXED", Z_FIXED); + { + extern const char *ImagingZipVersion(void); + PyDict_SetItemString( + d, "zlib_version", PyUnicode_FromString(ImagingZipVersion())); + } #endif #ifdef HAVE_LIBTIFF - { - extern const char * ImagingTiffVersion(void); - PyDict_SetItemString(d, "libtiff_version", PyUnicode_FromString(ImagingTiffVersion())); + { + extern const char *ImagingTiffVersion(void); + PyDict_SetItemString( + d, "libtiff_version", PyUnicode_FromString(ImagingTiffVersion())); - // Test for libtiff 4.0 or later, excluding libtiff 3.9.6 and 3.9.7 - PyObject* support_custom_tags; -#if TIFFLIB_VERSION >= 20111221 && TIFFLIB_VERSION != 20120218 && TIFFLIB_VERSION != 20120922 - support_custom_tags = Py_True; + // Test for libtiff 4.0 or later, excluding libtiff 3.9.6 and 3.9.7 + PyObject *support_custom_tags; +#if TIFFLIB_VERSION >= 20111221 && TIFFLIB_VERSION != 20120218 && \ + TIFFLIB_VERSION != 20120922 + support_custom_tags = Py_True; #else - support_custom_tags = Py_False; + support_custom_tags = Py_False; #endif - PyDict_SetItemString(d, "libtiff_support_custom_tags", support_custom_tags); - } + PyDict_SetItemString(d, "libtiff_support_custom_tags", support_custom_tags); + } #endif #ifdef HAVE_XCB @@ -4235,14 +4202,14 @@ setup_module(PyObject* m) { PyMODINIT_FUNC PyInit__imaging(void) { - PyObject* m; + PyObject *m; static PyModuleDef module_def = { PyModuleDef_HEAD_INIT, - "_imaging", /* m_name */ - NULL, /* m_doc */ - -1, /* m_size */ - functions, /* m_methods */ + "_imaging", /* m_name */ + NULL, /* m_doc */ + -1, /* m_size */ + functions, /* m_methods */ }; m = PyModule_Create(&module_def); diff --git a/src/_imagingcms.c b/src/_imagingcms.c index 491866f74..314150420 100644 --- a/src/_imagingcms.c +++ b/src/_imagingcms.c @@ -17,7 +17,8 @@ * March 2009, for distribution under the standard PIL license */ -#define COPYRIGHTINFO "\ +#define COPYRIGHTINFO \ + "\ pyCMS\n\ a Python / PIL interface to the littleCMS ICC Color Management System\n\ Copyright (C) 2002-2003 Kevin Cazabon\n\ @@ -26,7 +27,7 @@ http://www.cazabon.com\n\ " #define PY_SSIZE_T_CLEAN -#include "Python.h" // Include before wchar.h so _GNU_SOURCE is set +#include "Python.h" // Include before wchar.h so _GNU_SOURCE is set #include "wchar.h" #include "datetime.h" @@ -41,10 +42,11 @@ http://www.cazabon.com\n\ 1.0.0 pil Integrating littleCMS2 0.1.0 pil integration & refactoring 0.0.2 alpha: Minor updates, added interfaces to littleCMS features, Jan 6, 2003 - - fixed some memory holes in how transforms/profiles were created and passed back to Python - due to improper destructor setup for PyCObjects + - fixed some memory holes in how transforms/profiles were created and passed back to + Python due to improper destructor setup for PyCObjects - added buildProofTransformFromOpenProfiles() function - - eliminated some code redundancy, centralizing several common tasks with internal functions + - eliminated some code redundancy, centralizing several common tasks with internal + functions 0.0.1 alpha: First public release Dec 26, 2002 @@ -74,18 +76,16 @@ http://www.cazabon.com\n\ /* a profile represents the ICC characteristics for a specific device */ typedef struct { - PyObject_HEAD - cmsHPROFILE profile; + PyObject_HEAD cmsHPROFILE profile; } CmsProfileObject; static PyTypeObject CmsProfile_Type; #define CmsProfile_Check(op) (Py_TYPE(op) == &CmsProfile_Type) -static PyObject* -cms_profile_new(cmsHPROFILE profile) -{ - CmsProfileObject* self; +static PyObject * +cms_profile_new(cmsHPROFILE profile) { + CmsProfileObject *self; self = PyObject_New(CmsProfileObject, &CmsProfile_Type); if (!self) { @@ -94,15 +94,14 @@ cms_profile_new(cmsHPROFILE profile) self->profile = profile; - return (PyObject*) self; + return (PyObject *)self; } -static PyObject* -cms_profile_open(PyObject* self, PyObject* args) -{ +static PyObject * +cms_profile_open(PyObject *self, PyObject *args) { cmsHPROFILE hProfile; - char* sProfile; + char *sProfile; if (!PyArg_ParseTuple(args, "s:profile_open", &sProfile)) { return NULL; } @@ -116,12 +115,11 @@ cms_profile_open(PyObject* self, PyObject* args) return cms_profile_new(hProfile); } -static PyObject* -cms_profile_fromstring(PyObject* self, PyObject* args) -{ +static PyObject * +cms_profile_fromstring(PyObject *self, PyObject *args) { cmsHPROFILE hProfile; - char* pProfile; + char *pProfile; Py_ssize_t nProfile; if (!PyArg_ParseTuple(args, "y#:profile_frombytes", &pProfile, &nProfile)) { return NULL; @@ -136,28 +134,27 @@ cms_profile_fromstring(PyObject* self, PyObject* args) return cms_profile_new(hProfile); } -static PyObject* -cms_profile_tobytes(PyObject* self, PyObject* args) -{ - char *pProfile =NULL; +static PyObject * +cms_profile_tobytes(PyObject *self, PyObject *args) { + char *pProfile = NULL; cmsUInt32Number nProfile; - PyObject* CmsProfile; + PyObject *CmsProfile; cmsHPROFILE *profile; - PyObject* ret; - if (!PyArg_ParseTuple(args, "O", &CmsProfile)){ + PyObject *ret; + if (!PyArg_ParseTuple(args, "O", &CmsProfile)) { return NULL; } - profile = ((CmsProfileObject*)CmsProfile)->profile; + profile = ((CmsProfileObject *)CmsProfile)->profile; if (!cmsSaveProfileToMem(profile, pProfile, &nProfile)) { PyErr_SetString(PyExc_OSError, "Could not determine profile size"); return NULL; } - pProfile = (char*)malloc(nProfile); + pProfile = (char *)malloc(nProfile); if (!pProfile) { PyErr_SetString(PyExc_OSError, "Out of Memory"); return NULL; @@ -176,17 +173,15 @@ cms_profile_tobytes(PyObject* self, PyObject* args) } static void -cms_profile_dealloc(CmsProfileObject* self) -{ - (void) cmsCloseProfile(self->profile); +cms_profile_dealloc(CmsProfileObject *self) { + (void)cmsCloseProfile(self->profile); PyObject_Del(self); } /* a transform represents the mapping between two profiles */ typedef struct { - PyObject_HEAD - char mode_in[8]; + PyObject_HEAD char mode_in[8]; char mode_out[8]; cmsHTRANSFORM transform; } CmsTransformObject; @@ -195,10 +190,9 @@ static PyTypeObject CmsTransform_Type; #define CmsTransform_Check(op) (Py_TYPE(op) == &CmsTransform_Type) -static PyObject* -cms_transform_new(cmsHTRANSFORM transform, char* mode_in, char* mode_out) -{ - CmsTransformObject* self; +static PyObject * +cms_transform_new(cmsHTRANSFORM transform, char *mode_in, char *mode_out) { + CmsTransformObject *self; self = PyObject_New(CmsTransformObject, &CmsTransform_Type); if (!self) { @@ -210,12 +204,11 @@ cms_transform_new(cmsHTRANSFORM transform, char* mode_in, char* mode_out) strcpy(self->mode_in, mode_in); strcpy(self->mode_out, mode_out); - return (PyObject*) self; + return (PyObject *)self; } static void -cms_transform_dealloc(CmsTransformObject* self) -{ +cms_transform_dealloc(CmsTransformObject *self) { cmsDeleteTransform(self->transform); PyObject_Del(self); } @@ -224,41 +217,30 @@ cms_transform_dealloc(CmsTransformObject* self) /* internal functions */ static cmsUInt32Number -findLCMStype(char* PILmode) -{ +findLCMStype(char *PILmode) { if (strcmp(PILmode, "RGB") == 0) { return TYPE_RGBA_8; - } - else if (strcmp(PILmode, "RGBA") == 0) { + } else if (strcmp(PILmode, "RGBA") == 0) { return TYPE_RGBA_8; - } - else if (strcmp(PILmode, "RGBX") == 0) { + } else if (strcmp(PILmode, "RGBX") == 0) { return TYPE_RGBA_8; - } - else if (strcmp(PILmode, "RGBA;16B") == 0) { + } else if (strcmp(PILmode, "RGBA;16B") == 0) { return TYPE_RGBA_16; - } - else if (strcmp(PILmode, "CMYK") == 0) { + } else if (strcmp(PILmode, "CMYK") == 0) { return TYPE_CMYK_8; - } - else if (strcmp(PILmode, "L") == 0) { + } else if (strcmp(PILmode, "L") == 0) { return TYPE_GRAY_8; - } - else if (strcmp(PILmode, "L;16") == 0) { + } else if (strcmp(PILmode, "L;16") == 0) { return TYPE_GRAY_16; - } - else if (strcmp(PILmode, "L;16B") == 0) { + } else if (strcmp(PILmode, "L;16B") == 0) { return TYPE_GRAY_16_SE; - } - else if (strcmp(PILmode, "YCCA") == 0) { + } else if (strcmp(PILmode, "YCCA") == 0) { return TYPE_YCbCr_8; - } - else if (strcmp(PILmode, "YCC") == 0) { + } else if (strcmp(PILmode, "YCC") == 0) { return TYPE_YCbCr_8; - } - else if (strcmp(PILmode, "LAB") == 0) { + } else if (strcmp(PILmode, "LAB") == 0) { // LabX equivalent like ALab, but not reversed -- no #define in lcms2 - return (COLORSPACE_SH(PT_LabV2)|CHANNELS_SH(3)|BYTES_SH(1)|EXTRA_SH(1)); + return (COLORSPACE_SH(PT_LabV2) | CHANNELS_SH(3) | BYTES_SH(1) | EXTRA_SH(1)); } else { @@ -270,8 +252,7 @@ findLCMStype(char* PILmode) #define Cms_Min(a, b) ((a) < (b) ? (a) : (b)) static int -pyCMSgetAuxChannelChannel (cmsUInt32Number format, int auxChannelNdx) -{ +pyCMSgetAuxChannelChannel(cmsUInt32Number format, int auxChannelNdx) { int numColors = T_CHANNELS(format); int numExtras = T_EXTRA(format); @@ -282,28 +263,24 @@ pyCMSgetAuxChannelChannel (cmsUInt32Number format, int auxChannelNdx) } else { return numExtras - 2 - auxChannelNdx; } - } - else if (T_SWAPFIRST(format)) { + } else if (T_SWAPFIRST(format)) { // in order, after color channels, but last extra is shifted to first if (auxChannelNdx == numExtras - 1) { return 0; } else { return numColors + 1 + auxChannelNdx; } - } - else if (T_DOSWAP(format)) { + } else if (T_DOSWAP(format)) { // reverse order, before anything return numExtras - 1 - auxChannelNdx; - } - else { + } else { // in order, after color channels return numColors + auxChannelNdx; } } static void -pyCMScopyAux (cmsHTRANSFORM hTransform, Imaging imDst, const Imaging imSrc) -{ +pyCMScopyAux(cmsHTRANSFORM hTransform, Imaging imDst, const Imaging imSrc) { cmsUInt32Number dstLCMSFormat; cmsUInt32Number srcLCMSFormat; int numSrcExtras; @@ -331,11 +308,11 @@ pyCMScopyAux (cmsHTRANSFORM hTransform, Imaging imDst, const Imaging imSrc) // copy only if channel format is identical, except OPTIMIZED is ignored as it // does not affect the aux channel - if (T_FLOAT(dstLCMSFormat) != T_FLOAT(srcLCMSFormat) - || T_FLAVOR(dstLCMSFormat) != T_FLAVOR(srcLCMSFormat) - || T_ENDIAN16(dstLCMSFormat) != T_ENDIAN16(srcLCMSFormat) - || T_BYTES(dstLCMSFormat) != T_BYTES(srcLCMSFormat)) { - return; + if (T_FLOAT(dstLCMSFormat) != T_FLOAT(srcLCMSFormat) || + T_FLAVOR(dstLCMSFormat) != T_FLAVOR(srcLCMSFormat) || + T_ENDIAN16(dstLCMSFormat) != T_ENDIAN16(srcLCMSFormat) || + T_BYTES(dstLCMSFormat) != T_BYTES(srcLCMSFormat)) { + return; } numSrcExtras = T_EXTRA(srcLCMSFormat); @@ -354,19 +331,21 @@ pyCMScopyAux (cmsHTRANSFORM hTransform, Imaging imDst, const Imaging imSrc) for (y = 0; y < ySize; y++) { int x; - char* pDstExtras = imDst->image[y] + dstChannel * channelSize; - const char* pSrcExtras = imSrc->image[y] + srcChannel * channelSize; + char *pDstExtras = imDst->image[y] + dstChannel * channelSize; + const char *pSrcExtras = imSrc->image[y] + srcChannel * channelSize; for (x = 0; x < xSize; x++) { - memcpy(pDstExtras + x * dstChunkSize, pSrcExtras + x * srcChunkSize, channelSize); + memcpy( + pDstExtras + x * dstChunkSize, + pSrcExtras + x * srcChunkSize, + channelSize); } } } } static int -pyCMSdoTransform(Imaging im, Imaging imOut, cmsHTRANSFORM hTransform) -{ +pyCMSdoTransform(Imaging im, Imaging imOut, cmsHTRANSFORM hTransform) { int i; if (im->xsize > imOut->xsize || im->ysize > imOut->ysize) { @@ -375,8 +354,8 @@ pyCMSdoTransform(Imaging im, Imaging imOut, cmsHTRANSFORM hTransform) Py_BEGIN_ALLOW_THREADS - // transform color channels only - for (i = 0; i < im->ysize; i++) { + // transform color channels only + for (i = 0; i < im->ysize; i++) { cmsDoTransform(hTransform, im->image[i], imOut->image[i], im->xsize); } @@ -391,26 +370,33 @@ pyCMSdoTransform(Imaging im, Imaging imOut, cmsHTRANSFORM hTransform) Py_END_ALLOW_THREADS - return 0; + return 0; } static cmsHTRANSFORM -_buildTransform(cmsHPROFILE hInputProfile, cmsHPROFILE hOutputProfile, char *sInMode, char *sOutMode, int iRenderingIntent, cmsUInt32Number cmsFLAGS) -{ +_buildTransform( + cmsHPROFILE hInputProfile, + cmsHPROFILE hOutputProfile, + char *sInMode, + char *sOutMode, + int iRenderingIntent, + cmsUInt32Number cmsFLAGS) { cmsHTRANSFORM hTransform; Py_BEGIN_ALLOW_THREADS - /* create the transform */ - hTransform = cmsCreateTransform(hInputProfile, - findLCMStype(sInMode), - hOutputProfile, - findLCMStype(sOutMode), - iRenderingIntent, cmsFLAGS); + /* create the transform */ + hTransform = cmsCreateTransform( + hInputProfile, + findLCMStype(sInMode), + hOutputProfile, + findLCMStype(sOutMode), + iRenderingIntent, + cmsFLAGS); Py_END_ALLOW_THREADS - if (!hTransform) { + if (!hTransform) { PyErr_SetString(PyExc_ValueError, "cannot build transform"); } @@ -418,25 +404,33 @@ _buildTransform(cmsHPROFILE hInputProfile, cmsHPROFILE hOutputProfile, char *sIn } static cmsHTRANSFORM -_buildProofTransform(cmsHPROFILE hInputProfile, cmsHPROFILE hOutputProfile, cmsHPROFILE hProofProfile, char *sInMode, char *sOutMode, int iRenderingIntent, int iProofIntent, cmsUInt32Number cmsFLAGS) -{ +_buildProofTransform( + cmsHPROFILE hInputProfile, + cmsHPROFILE hOutputProfile, + cmsHPROFILE hProofProfile, + char *sInMode, + char *sOutMode, + int iRenderingIntent, + int iProofIntent, + cmsUInt32Number cmsFLAGS) { cmsHTRANSFORM hTransform; Py_BEGIN_ALLOW_THREADS - /* create the transform */ - hTransform = cmsCreateProofingTransform(hInputProfile, - findLCMStype(sInMode), - hOutputProfile, - findLCMStype(sOutMode), - hProofProfile, - iRenderingIntent, - iProofIntent, - cmsFLAGS); + /* create the transform */ + hTransform = cmsCreateProofingTransform( + hInputProfile, + findLCMStype(sInMode), + hOutputProfile, + findLCMStype(sOutMode), + hProofProfile, + iRenderingIntent, + iProofIntent, + cmsFLAGS); Py_END_ALLOW_THREADS - if (!hTransform) { + if (!hTransform) { PyErr_SetString(PyExc_ValueError, "cannot build proof transform"); } @@ -457,11 +451,27 @@ buildTransform(PyObject *self, PyObject *args) { cmsHTRANSFORM transform = NULL; - if (!PyArg_ParseTuple(args, "O!O!ss|ii:buildTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &sInMode, &sOutMode, &iRenderingIntent, &cmsFLAGS)) { + if (!PyArg_ParseTuple( + args, + "O!O!ss|ii:buildTransform", + &CmsProfile_Type, + &pInputProfile, + &CmsProfile_Type, + &pOutputProfile, + &sInMode, + &sOutMode, + &iRenderingIntent, + &cmsFLAGS)) { return NULL; } - transform = _buildTransform(pInputProfile->profile, pOutputProfile->profile, sInMode, sOutMode, iRenderingIntent, cmsFLAGS); + transform = _buildTransform( + pInputProfile->profile, + pOutputProfile->profile, + sInMode, + sOutMode, + iRenderingIntent, + cmsFLAGS); if (!transform) { return NULL; @@ -471,8 +481,7 @@ buildTransform(PyObject *self, PyObject *args) { } static PyObject * -buildProofTransform(PyObject *self, PyObject *args) -{ +buildProofTransform(PyObject *self, PyObject *args) { CmsProfileObject *pInputProfile; CmsProfileObject *pOutputProfile; CmsProfileObject *pProofProfile; @@ -484,23 +493,42 @@ buildProofTransform(PyObject *self, PyObject *args) cmsHTRANSFORM transform = NULL; - if (!PyArg_ParseTuple(args, "O!O!O!ss|iii:buildProofTransform", &CmsProfile_Type, &pInputProfile, &CmsProfile_Type, &pOutputProfile, &CmsProfile_Type, &pProofProfile, &sInMode, &sOutMode, &iRenderingIntent, &iProofIntent, &cmsFLAGS)) { + if (!PyArg_ParseTuple( + args, + "O!O!O!ss|iii:buildProofTransform", + &CmsProfile_Type, + &pInputProfile, + &CmsProfile_Type, + &pOutputProfile, + &CmsProfile_Type, + &pProofProfile, + &sInMode, + &sOutMode, + &iRenderingIntent, + &iProofIntent, + &cmsFLAGS)) { return NULL; } - transform = _buildProofTransform(pInputProfile->profile, pOutputProfile->profile, pProofProfile->profile, sInMode, sOutMode, iRenderingIntent, iProofIntent, cmsFLAGS); + transform = _buildProofTransform( + pInputProfile->profile, + pOutputProfile->profile, + pProofProfile->profile, + sInMode, + sOutMode, + iRenderingIntent, + iProofIntent, + cmsFLAGS); if (!transform) { return NULL; } return cms_transform_new(transform, sInMode, sOutMode); - } static PyObject * -cms_transform_apply(CmsTransformObject *self, PyObject *args) -{ +cms_transform_apply(CmsTransformObject *self, PyObject *args) { Py_ssize_t idIn; Py_ssize_t idOut; Imaging im; @@ -512,8 +540,8 @@ cms_transform_apply(CmsTransformObject *self, PyObject *args) return NULL; } - im = (Imaging) idIn; - imOut = (Imaging) idOut; + im = (Imaging)idIn; + imOut = (Imaging)idOut; result = pyCMSdoTransform(im, imOut, self->transform); @@ -524,8 +552,7 @@ cms_transform_apply(CmsTransformObject *self, PyObject *args) /* Python-Callable On-The-Fly profile creation functions */ static PyObject * -createProfile(PyObject *self, PyObject *args) -{ +createProfile(PyObject *self, PyObject *args) { char *sColorSpace; cmsHPROFILE hProfile; cmsFloat64Number dColorTemp = 0.0; @@ -540,21 +567,21 @@ createProfile(PyObject *self, PyObject *args) if (dColorTemp > 0.0) { result = cmsWhitePointFromTemp(&whitePoint, dColorTemp); if (!result) { - PyErr_SetString(PyExc_ValueError, "ERROR: Could not calculate white point from color temperature provided, must be float in degrees Kelvin"); + PyErr_SetString( + PyExc_ValueError, + "ERROR: Could not calculate white point from color temperature " + "provided, must be float in degrees Kelvin"); return NULL; } hProfile = cmsCreateLab2Profile(&whitePoint); } else { hProfile = cmsCreateLab2Profile(NULL); } - } - else if (strcmp(sColorSpace, "XYZ") == 0) { + } else if (strcmp(sColorSpace, "XYZ") == 0) { hProfile = cmsCreateXYZProfile(); - } - else if (strcmp(sColorSpace, "sRGB") == 0) { + } else if (strcmp(sColorSpace, "sRGB") == 0) { hProfile = cmsCreate_sRGBProfile(); - } - else { + } else { hProfile = NULL; } @@ -570,8 +597,7 @@ createProfile(PyObject *self, PyObject *args) /* profile methods */ static PyObject * -cms_profile_is_intent_supported(CmsProfileObject *self, PyObject *args) -{ +cms_profile_is_intent_supported(CmsProfileObject *self, PyObject *args) { cmsBool result; int intent; @@ -582,7 +608,8 @@ cms_profile_is_intent_supported(CmsProfileObject *self, PyObject *args) result = cmsIsIntentSupported(self->profile, intent, direction); - /* printf("cmsIsIntentSupported(%p, %d, %d) => %d\n", self->profile, intent, direction, result); */ + /* printf("cmsIsIntentSupported(%p, %d, %d) => %d\n", self->profile, intent, + * direction, result); */ return PyLong_FromLong(result != 0); } @@ -596,30 +623,30 @@ cms_profile_is_intent_supported(CmsProfileObject *self, PyObject *args) #endif static PyObject * -cms_get_display_profile_win32(PyObject* self, PyObject* args) -{ +cms_get_display_profile_win32(PyObject *self, PyObject *args) { char filename[MAX_PATH]; cmsUInt32Number filename_size; BOOL ok; HANDLE handle = 0; int is_dc = 0; - if (!PyArg_ParseTuple(args, "|" F_HANDLE "i:get_display_profile", &handle, &is_dc)) { + if (!PyArg_ParseTuple( + args, "|" F_HANDLE "i:get_display_profile", &handle, &is_dc)) { return NULL; } filename_size = sizeof(filename); if (is_dc) { - ok = GetICMProfile((HDC) handle, &filename_size, filename); + ok = GetICMProfile((HDC)handle, &filename_size, filename); } else { - HDC dc = GetDC((HWND) handle); + HDC dc = GetDC((HWND)handle); ok = GetICMProfile(dc, &filename_size, filename); - ReleaseDC((HWND) handle, dc); + ReleaseDC((HWND)handle, dc); } if (ok) { - return PyUnicode_FromStringAndSize(filename, filename_size-1); + return PyUnicode_FromStringAndSize(filename, filename_size - 1); } Py_INCREF(Py_None); @@ -630,9 +657,8 @@ cms_get_display_profile_win32(PyObject* self, PyObject* args) /* -------------------------------------------------------------------- */ /* Helper functions. */ -static PyObject* -_profile_read_mlu(CmsProfileObject* self, cmsTagSignature info) -{ +static PyObject * +_profile_read_mlu(CmsProfileObject *self, cmsTagSignature info) { PyObject *uni; char *lc = "en"; char *cc = cmsNoCountry; @@ -673,26 +699,22 @@ _profile_read_mlu(CmsProfileObject* self, cmsTagSignature info) return uni; } - -static PyObject* -_profile_read_int_as_string(cmsUInt32Number nr) -{ - PyObject* ret; +static PyObject * +_profile_read_int_as_string(cmsUInt32Number nr) { + PyObject *ret; char buf[5]; - buf[0] = (char) ((nr >> 24) & 0xff); - buf[1] = (char) ((nr >> 16) & 0xff); - buf[2] = (char) ((nr >> 8) & 0xff); - buf[3] = (char) (nr & 0xff); + buf[0] = (char)((nr >> 24) & 0xff); + buf[1] = (char)((nr >> 16) & 0xff); + buf[2] = (char)((nr >> 8) & 0xff); + buf[3] = (char)(nr & 0xff); buf[4] = 0; ret = PyUnicode_DecodeASCII(buf, 4, NULL); return ret; } - -static PyObject* -_profile_read_signature(CmsProfileObject* self, cmsTagSignature info) -{ +static PyObject * +_profile_read_signature(CmsProfileObject *self, cmsTagSignature info) { unsigned int *sig; if (!cmsIsTag(self->profile, info)) { @@ -700,7 +722,7 @@ _profile_read_signature(CmsProfileObject* self, cmsTagSignature info) return Py_None; } - sig = (unsigned int *) cmsReadTag(self->profile, info); + sig = (unsigned int *)cmsReadTag(self->profile, info); if (!sig) { Py_INCREF(Py_None); return Py_None; @@ -709,42 +731,53 @@ _profile_read_signature(CmsProfileObject* self, cmsTagSignature info) return _profile_read_int_as_string(*sig); } -static PyObject* -_xyz_py(cmsCIEXYZ* XYZ) -{ +static PyObject * +_xyz_py(cmsCIEXYZ *XYZ) { cmsCIExyY xyY; cmsXYZ2xyY(&xyY, XYZ); - return Py_BuildValue("((d,d,d),(d,d,d))", XYZ->X, XYZ->Y, XYZ->Z, xyY.x, xyY.y, xyY.Y); + return Py_BuildValue( + "((d,d,d),(d,d,d))", XYZ->X, XYZ->Y, XYZ->Z, xyY.x, xyY.y, xyY.Y); } -static PyObject* -_xyz3_py(cmsCIEXYZ* XYZ) -{ +static PyObject * +_xyz3_py(cmsCIEXYZ *XYZ) { cmsCIExyY xyY[3]; cmsXYZ2xyY(&xyY[0], &XYZ[0]); cmsXYZ2xyY(&xyY[1], &XYZ[1]); cmsXYZ2xyY(&xyY[2], &XYZ[2]); - return Py_BuildValue("(((d,d,d),(d,d,d),(d,d,d)),((d,d,d),(d,d,d),(d,d,d)))", - XYZ[0].X, XYZ[0].Y, XYZ[0].Z, - XYZ[1].X, XYZ[1].Y, XYZ[1].Z, - XYZ[2].X, XYZ[2].Y, XYZ[2].Z, - xyY[0].x, xyY[0].y, xyY[0].Y, - xyY[1].x, xyY[1].y, xyY[1].Y, - xyY[2].x, xyY[2].y, xyY[2].Y); + return Py_BuildValue( + "(((d,d,d),(d,d,d),(d,d,d)),((d,d,d),(d,d,d),(d,d,d)))", + XYZ[0].X, + XYZ[0].Y, + XYZ[0].Z, + XYZ[1].X, + XYZ[1].Y, + XYZ[1].Z, + XYZ[2].X, + XYZ[2].Y, + XYZ[2].Z, + xyY[0].x, + xyY[0].y, + xyY[0].Y, + xyY[1].x, + xyY[1].y, + xyY[1].Y, + xyY[2].x, + xyY[2].y, + xyY[2].Y); } -static PyObject* -_profile_read_ciexyz(CmsProfileObject* self, cmsTagSignature info, int multi) -{ - cmsCIEXYZ* XYZ; +static PyObject * +_profile_read_ciexyz(CmsProfileObject *self, cmsTagSignature info, int multi) { + cmsCIEXYZ *XYZ; if (!cmsIsTag(self->profile, info)) { Py_INCREF(Py_None); return Py_None; } - XYZ = (cmsCIEXYZ*) cmsReadTag(self->profile, info); + XYZ = (cmsCIEXYZ *)cmsReadTag(self->profile, info); if (!XYZ) { Py_INCREF(Py_None); return Py_None; @@ -756,17 +789,16 @@ _profile_read_ciexyz(CmsProfileObject* self, cmsTagSignature info, int multi) } } -static PyObject* -_profile_read_ciexyy_triple(CmsProfileObject* self, cmsTagSignature info) -{ - cmsCIExyYTRIPLE* triple; +static PyObject * +_profile_read_ciexyy_triple(CmsProfileObject *self, cmsTagSignature info) { + cmsCIExyYTRIPLE *triple; if (!cmsIsTag(self->profile, info)) { Py_INCREF(Py_None); return Py_None; } - triple = (cmsCIExyYTRIPLE*) cmsReadTag(self->profile, info); + triple = (cmsCIExyYTRIPLE *)cmsReadTag(self->profile, info); if (!triple) { Py_INCREF(Py_None); return Py_None; @@ -774,26 +806,32 @@ _profile_read_ciexyy_triple(CmsProfileObject* self, cmsTagSignature info) /* Note: lcms does all the heavy lifting and error checking (nr of channels == 3). */ - return Py_BuildValue("((d,d,d),(d,d,d),(d,d,d)),", - triple->Red.x, triple->Red.y, triple->Red.Y, - triple->Green.x, triple->Green.y, triple->Green.Y, - triple->Blue.x, triple->Blue.y, triple->Blue.Y); + return Py_BuildValue( + "((d,d,d),(d,d,d),(d,d,d)),", + triple->Red.x, + triple->Red.y, + triple->Red.Y, + triple->Green.x, + triple->Green.y, + triple->Green.Y, + triple->Blue.x, + triple->Blue.y, + triple->Blue.Y); } -static PyObject* -_profile_read_named_color_list(CmsProfileObject* self, cmsTagSignature info) -{ - cmsNAMEDCOLORLIST* ncl; +static PyObject * +_profile_read_named_color_list(CmsProfileObject *self, cmsTagSignature info) { + cmsNAMEDCOLORLIST *ncl; int i, n; char name[cmsMAX_PATH]; - PyObject* result; + PyObject *result; if (!cmsIsTag(self->profile, info)) { Py_INCREF(Py_None); return Py_None; } - ncl = (cmsNAMEDCOLORLIST*) cmsReadTag(self->profile, info); + ncl = (cmsNAMEDCOLORLIST *)cmsReadTag(self->profile, info); if (ncl == NULL) { Py_INCREF(Py_None); return Py_None; @@ -807,7 +845,7 @@ _profile_read_named_color_list(CmsProfileObject* self, cmsTagSignature info) } for (i = 0; i < n; i++) { - PyObject* str; + PyObject *str; cmsNamedColorInfo(ncl, i, name, NULL, NULL, NULL, NULL); str = PyUnicode_FromString(name); if (str == NULL) { @@ -821,9 +859,9 @@ _profile_read_named_color_list(CmsProfileObject* self, cmsTagSignature info) return result; } -static cmsBool _calculate_rgb_primaries(CmsProfileObject* self, cmsCIEXYZTRIPLE* result) -{ - double input[3][3] = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; +static cmsBool +_calculate_rgb_primaries(CmsProfileObject *self, cmsCIEXYZTRIPLE *result) { + double input[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; cmsHPROFILE hXYZ; cmsHTRANSFORM hTransform; @@ -836,36 +874,41 @@ static cmsBool _calculate_rgb_primaries(CmsProfileObject* self, cmsCIEXYZTRIPLE* } // transform from our profile to XYZ using doubles for highest precision - hTransform = cmsCreateTransform(self->profile, TYPE_RGB_DBL, - hXYZ, TYPE_XYZ_DBL, - INTENT_RELATIVE_COLORIMETRIC, - cmsFLAGS_NOCACHE | cmsFLAGS_NOOPTIMIZE); + hTransform = cmsCreateTransform( + self->profile, + TYPE_RGB_DBL, + hXYZ, + TYPE_XYZ_DBL, + INTENT_RELATIVE_COLORIMETRIC, + cmsFLAGS_NOCACHE | cmsFLAGS_NOOPTIMIZE); cmsCloseProfile(hXYZ); if (hTransform == NULL) { return 0; } - cmsDoTransform(hTransform, (void*) input, result, 3); + cmsDoTransform(hTransform, (void *)input, result, 3); cmsDeleteTransform(hTransform); return 1; } -static cmsBool _check_intent(int clut, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number UsedDirection) -{ +static cmsBool +_check_intent( + int clut, + cmsHPROFILE hProfile, + cmsUInt32Number Intent, + cmsUInt32Number UsedDirection) { if (clut) { return cmsIsCLUT(hProfile, Intent, UsedDirection); - } - else { + } else { return cmsIsIntentSupported(hProfile, Intent, UsedDirection); } } #define INTENTS 200 -static PyObject* -_is_intent_supported(CmsProfileObject* self, int clut) -{ - PyObject* result; +static PyObject * +_is_intent_supported(CmsProfileObject *self, int clut) { + PyObject *result; int n; int i; cmsUInt32Number intent_ids[INTENTS]; @@ -877,26 +920,28 @@ _is_intent_supported(CmsProfileObject* self, int clut) return Py_None; } - - n = cmsGetSupportedIntents(INTENTS, - intent_ids, - intent_descs); + n = cmsGetSupportedIntents(INTENTS, intent_ids, intent_descs); for (i = 0; i < n; i++) { - int intent = (int) intent_ids[i]; - PyObject* id; - PyObject* entry; + int intent = (int)intent_ids[i]; + PyObject *id; + PyObject *entry; - /* Only valid for ICC Intents (otherwise we read invalid memory in lcms cmsio1.c). */ - if (!(intent == INTENT_PERCEPTUAL || intent == INTENT_RELATIVE_COLORIMETRIC - || intent == INTENT_SATURATION || intent == INTENT_ABSOLUTE_COLORIMETRIC)) { + /* Only valid for ICC Intents (otherwise we read invalid memory in lcms + * cmsio1.c). */ + if (!(intent == INTENT_PERCEPTUAL || intent == INTENT_RELATIVE_COLORIMETRIC || + intent == INTENT_SATURATION || intent == INTENT_ABSOLUTE_COLORIMETRIC)) { continue; } - id = PyLong_FromLong((long) intent); - entry = Py_BuildValue("(OOO)", - _check_intent(clut, self->profile, intent, LCMS_USED_AS_INPUT) ? Py_True : Py_False, - _check_intent(clut, self->profile, intent, LCMS_USED_AS_OUTPUT) ? Py_True : Py_False, - _check_intent(clut, self->profile, intent, LCMS_USED_AS_PROOF) ? Py_True : Py_False); + id = PyLong_FromLong((long)intent); + entry = Py_BuildValue( + "(OOO)", + _check_intent(clut, self->profile, intent, LCMS_USED_AS_INPUT) ? Py_True + : Py_False, + _check_intent(clut, self->profile, intent, LCMS_USED_AS_OUTPUT) ? Py_True + : Py_False, + _check_intent(clut, self->profile, intent, LCMS_USED_AS_PROOF) ? Py_True + : Py_False); if (id == NULL || entry == NULL) { Py_XDECREF(id); Py_XDECREF(entry); @@ -924,185 +969,161 @@ static PyMethodDef pyCMSdll_methods[] = { {"buildProofTransform", buildProofTransform, 1}, {"createProfile", createProfile, 1}, - /* platform specific tools */ +/* platform specific tools */ #ifdef _WIN32 {"get_display_profile_win32", cms_get_display_profile_win32, 1}, #endif - {NULL, NULL} -}; + {NULL, NULL}}; static struct PyMethodDef cms_profile_methods[] = { - {"is_intent_supported", (PyCFunction) cms_profile_is_intent_supported, 1}, + {"is_intent_supported", (PyCFunction)cms_profile_is_intent_supported, 1}, {NULL, NULL} /* sentinel */ }; -static PyObject* -cms_profile_getattr_rendering_intent(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_rendering_intent(CmsProfileObject *self, void *closure) { return PyLong_FromLong(cmsGetHeaderRenderingIntent(self->profile)); } /* New-style unicode interfaces. */ -static PyObject* -cms_profile_getattr_copyright(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_copyright(CmsProfileObject *self, void *closure) { return _profile_read_mlu(self, cmsSigCopyrightTag); } -static PyObject* -cms_profile_getattr_target(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_target(CmsProfileObject *self, void *closure) { return _profile_read_mlu(self, cmsSigCharTargetTag); } -static PyObject* -cms_profile_getattr_manufacturer(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_manufacturer(CmsProfileObject *self, void *closure) { return _profile_read_mlu(self, cmsSigDeviceMfgDescTag); } -static PyObject* -cms_profile_getattr_model(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_model(CmsProfileObject *self, void *closure) { return _profile_read_mlu(self, cmsSigDeviceModelDescTag); } -static PyObject* -cms_profile_getattr_profile_description(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_profile_description(CmsProfileObject *self, void *closure) { return _profile_read_mlu(self, cmsSigProfileDescriptionTag); } -static PyObject* -cms_profile_getattr_screening_description(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_screening_description(CmsProfileObject *self, void *closure) { return _profile_read_mlu(self, cmsSigScreeningDescTag); } -static PyObject* -cms_profile_getattr_viewing_condition(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_viewing_condition(CmsProfileObject *self, void *closure) { return _profile_read_mlu(self, cmsSigViewingCondDescTag); } -static PyObject* -cms_profile_getattr_creation_date(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_creation_date(CmsProfileObject *self, void *closure) { cmsBool result; struct tm ct; result = cmsGetHeaderCreationDateTime(self->profile, &ct); - if (! result) { + if (!result) { Py_INCREF(Py_None); return Py_None; } - return PyDateTime_FromDateAndTime(1900 + ct.tm_year, ct.tm_mon, ct.tm_mday, - ct.tm_hour, ct.tm_min, ct.tm_sec, 0); + return PyDateTime_FromDateAndTime( + 1900 + ct.tm_year, ct.tm_mon, ct.tm_mday, ct.tm_hour, ct.tm_min, ct.tm_sec, 0); } -static PyObject* -cms_profile_getattr_version(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_version(CmsProfileObject *self, void *closure) { cmsFloat64Number version = cmsGetProfileVersion(self->profile); return PyFloat_FromDouble(version); } -static PyObject* -cms_profile_getattr_icc_version(CmsProfileObject* self, void* closure) -{ - return PyLong_FromLong((long) cmsGetEncodedICCversion(self->profile)); +static PyObject * +cms_profile_getattr_icc_version(CmsProfileObject *self, void *closure) { + return PyLong_FromLong((long)cmsGetEncodedICCversion(self->profile)); } -static PyObject* -cms_profile_getattr_attributes(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_attributes(CmsProfileObject *self, void *closure) { cmsUInt64Number attr; cmsGetHeaderAttributes(self->profile, &attr); /* This works just as well on Windows (LLP64), 32-bit Linux (ILP32) and 64-bit Linux (LP64) systems. */ - return PyLong_FromUnsignedLongLong((unsigned long long) attr); + return PyLong_FromUnsignedLongLong((unsigned long long)attr); } -static PyObject* -cms_profile_getattr_header_flags(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_header_flags(CmsProfileObject *self, void *closure) { cmsUInt32Number flags = cmsGetHeaderFlags(self->profile); return PyLong_FromLong(flags); } -static PyObject* -cms_profile_getattr_header_manufacturer(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_header_manufacturer(CmsProfileObject *self, void *closure) { return _profile_read_int_as_string(cmsGetHeaderManufacturer(self->profile)); } -static PyObject* -cms_profile_getattr_header_model(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_header_model(CmsProfileObject *self, void *closure) { return _profile_read_int_as_string(cmsGetHeaderModel(self->profile)); } -static PyObject* -cms_profile_getattr_device_class(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_device_class(CmsProfileObject *self, void *closure) { return _profile_read_int_as_string(cmsGetDeviceClass(self->profile)); } -static PyObject* -cms_profile_getattr_connection_space(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_connection_space(CmsProfileObject *self, void *closure) { return _profile_read_int_as_string(cmsGetPCS(self->profile)); } -static PyObject* -cms_profile_getattr_xcolor_space(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_xcolor_space(CmsProfileObject *self, void *closure) { return _profile_read_int_as_string(cmsGetColorSpace(self->profile)); } -static PyObject* -cms_profile_getattr_profile_id(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_profile_id(CmsProfileObject *self, void *closure) { cmsUInt8Number id[16]; cmsGetHeaderProfileID(self->profile, id); - return PyBytes_FromStringAndSize((char *) id, 16); + return PyBytes_FromStringAndSize((char *)id, 16); } -static PyObject* -cms_profile_getattr_is_matrix_shaper(CmsProfileObject* self, void* closure) -{ - return PyBool_FromLong((long) cmsIsMatrixShaper(self->profile)); +static PyObject * +cms_profile_getattr_is_matrix_shaper(CmsProfileObject *self, void *closure) { + return PyBool_FromLong((long)cmsIsMatrixShaper(self->profile)); } -static PyObject* -cms_profile_getattr_technology(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_technology(CmsProfileObject *self, void *closure) { return _profile_read_signature(self, cmsSigTechnologyTag); } -static PyObject* -cms_profile_getattr_colorimetric_intent(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_colorimetric_intent(CmsProfileObject *self, void *closure) { return _profile_read_signature(self, cmsSigColorimetricIntentImageStateTag); } -static PyObject* -cms_profile_getattr_perceptual_rendering_intent_gamut(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_perceptual_rendering_intent_gamut( + CmsProfileObject *self, void *closure) { return _profile_read_signature(self, cmsSigPerceptualRenderingIntentGamutTag); } -static PyObject* -cms_profile_getattr_saturation_rendering_intent_gamut(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_saturation_rendering_intent_gamut( + CmsProfileObject *self, void *closure) { return _profile_read_signature(self, cmsSigSaturationRenderingIntentGamutTag); } -static PyObject* -cms_profile_getattr_red_colorant(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_red_colorant(CmsProfileObject *self, void *closure) { if (!cmsIsMatrixShaper(self->profile)) { Py_INCREF(Py_None); return Py_None; @@ -1110,10 +1131,8 @@ cms_profile_getattr_red_colorant(CmsProfileObject* self, void* closure) return _profile_read_ciexyz(self, cmsSigRedColorantTag, 0); } - -static PyObject* -cms_profile_getattr_green_colorant(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_green_colorant(CmsProfileObject *self, void *closure) { if (!cmsIsMatrixShaper(self->profile)) { Py_INCREF(Py_None); return Py_None; @@ -1121,10 +1140,8 @@ cms_profile_getattr_green_colorant(CmsProfileObject* self, void* closure) return _profile_read_ciexyz(self, cmsSigGreenColorantTag, 0); } - -static PyObject* -cms_profile_getattr_blue_colorant(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_blue_colorant(CmsProfileObject *self, void *closure) { if (!cmsIsMatrixShaper(self->profile)) { Py_INCREF(Py_None); return Py_None; @@ -1132,10 +1149,10 @@ cms_profile_getattr_blue_colorant(CmsProfileObject* self, void* closure) return _profile_read_ciexyz(self, cmsSigBlueColorantTag, 0); } -static PyObject* -cms_profile_getattr_media_white_point_temperature(CmsProfileObject *self, void* closure) -{ - cmsCIEXYZ* XYZ; +static PyObject * +cms_profile_getattr_media_white_point_temperature( + CmsProfileObject *self, void *closure) { + cmsCIEXYZ *XYZ; cmsCIExyY xyY; cmsFloat64Number tempK; cmsTagSignature info = cmsSigMediaWhitePointTag; @@ -1146,7 +1163,7 @@ cms_profile_getattr_media_white_point_temperature(CmsProfileObject *self, void* return Py_None; } - XYZ = (cmsCIEXYZ*) cmsReadTag(self->profile, info); + XYZ = (cmsCIEXYZ *)cmsReadTag(self->profile, info); if (XYZ == NULL || XYZ->X == 0) { Py_INCREF(Py_None); return Py_None; @@ -1161,47 +1178,40 @@ cms_profile_getattr_media_white_point_temperature(CmsProfileObject *self, void* return PyFloat_FromDouble(tempK); } -static PyObject* -cms_profile_getattr_media_white_point(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_media_white_point(CmsProfileObject *self, void *closure) { return _profile_read_ciexyz(self, cmsSigMediaWhitePointTag, 0); } - -static PyObject* -cms_profile_getattr_media_black_point(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_media_black_point(CmsProfileObject *self, void *closure) { return _profile_read_ciexyz(self, cmsSigMediaBlackPointTag, 0); } -static PyObject* -cms_profile_getattr_luminance(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_luminance(CmsProfileObject *self, void *closure) { return _profile_read_ciexyz(self, cmsSigLuminanceTag, 0); } -static PyObject* -cms_profile_getattr_chromatic_adaptation(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_chromatic_adaptation(CmsProfileObject *self, void *closure) { return _profile_read_ciexyz(self, cmsSigChromaticAdaptationTag, 1); } -static PyObject* -cms_profile_getattr_chromaticity(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_chromaticity(CmsProfileObject *self, void *closure) { return _profile_read_ciexyy_triple(self, cmsSigChromaticityTag); } -static PyObject* -cms_profile_getattr_red_primary(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_red_primary(CmsProfileObject *self, void *closure) { cmsBool result = 0; cmsCIEXYZTRIPLE primaries; if (cmsIsMatrixShaper(self->profile)) { result = _calculate_rgb_primaries(self, &primaries); } - if (! result) { + if (!result) { Py_INCREF(Py_None); return Py_None; } @@ -1209,16 +1219,15 @@ cms_profile_getattr_red_primary(CmsProfileObject* self, void* closure) return _xyz_py(&primaries.Red); } -static PyObject* -cms_profile_getattr_green_primary(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_green_primary(CmsProfileObject *self, void *closure) { cmsBool result = 0; cmsCIEXYZTRIPLE primaries; if (cmsIsMatrixShaper(self->profile)) { result = _calculate_rgb_primaries(self, &primaries); } - if (! result) { + if (!result) { Py_INCREF(Py_None); return Py_None; } @@ -1226,16 +1235,15 @@ cms_profile_getattr_green_primary(CmsProfileObject* self, void* closure) return _xyz_py(&primaries.Green); } -static PyObject* -cms_profile_getattr_blue_primary(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_blue_primary(CmsProfileObject *self, void *closure) { cmsBool result = 0; cmsCIEXYZTRIPLE primaries; if (cmsIsMatrixShaper(self->profile)) { result = _calculate_rgb_primaries(self, &primaries); } - if (! result) { + if (!result) { Py_INCREF(Py_None); return Py_None; } @@ -1243,61 +1251,55 @@ cms_profile_getattr_blue_primary(CmsProfileObject* self, void* closure) return _xyz_py(&primaries.Blue); } -static PyObject* -cms_profile_getattr_colorant_table(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_colorant_table(CmsProfileObject *self, void *closure) { return _profile_read_named_color_list(self, cmsSigColorantTableTag); } -static PyObject* -cms_profile_getattr_colorant_table_out(CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_colorant_table_out(CmsProfileObject *self, void *closure) { return _profile_read_named_color_list(self, cmsSigColorantTableOutTag); } -static PyObject* -cms_profile_getattr_is_intent_supported (CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_is_intent_supported(CmsProfileObject *self, void *closure) { return _is_intent_supported(self, 0); } -static PyObject* -cms_profile_getattr_is_clut (CmsProfileObject* self, void* closure) -{ +static PyObject * +cms_profile_getattr_is_clut(CmsProfileObject *self, void *closure) { return _is_intent_supported(self, 1); } -static const char* -_illu_map(int i) -{ - switch(i) { - case 0: - return "unknown"; - case 1: - return "D50"; - case 2: - return "D65"; - case 3: - return "D93"; - case 4: - return "F2"; - case 5: - return "D55"; - case 6: - return "A"; - case 7: - return "E"; - case 8: - return "F8"; - default: - return NULL; +static const char * +_illu_map(int i) { + switch (i) { + case 0: + return "unknown"; + case 1: + return "D50"; + case 2: + return "D65"; + case 3: + return "D93"; + case 4: + return "F2"; + case 5: + return "D55"; + case 6: + return "A"; + case 7: + return "E"; + case 8: + return "F8"; + default: + return NULL; } } -static PyObject* -cms_profile_getattr_icc_measurement_condition (CmsProfileObject* self, void* closure) -{ - cmsICCMeasurementConditions* mc; +static PyObject * +cms_profile_getattr_icc_measurement_condition(CmsProfileObject *self, void *closure) { + cmsICCMeasurementConditions *mc; cmsTagSignature info = cmsSigMeasurementTag; const char *geo; @@ -1306,7 +1308,7 @@ cms_profile_getattr_icc_measurement_condition (CmsProfileObject* self, void* clo return Py_None; } - mc = (cmsICCMeasurementConditions*) cmsReadTag(self->profile, info); + mc = (cmsICCMeasurementConditions *)cmsReadTag(self->profile, info); if (!mc) { Py_INCREF(Py_None); return Py_None; @@ -1320,18 +1322,25 @@ cms_profile_getattr_icc_measurement_condition (CmsProfileObject* self, void* clo geo = "unknown"; } - return Py_BuildValue("{s:i,s:(ddd),s:s,s:d,s:s}", - "observer", mc->Observer, - "backing", mc->Backing.X, mc->Backing.Y, mc->Backing.Z, - "geo", geo, - "flare", mc->Flare, - "illuminant_type", _illu_map(mc->IlluminantType)); + return Py_BuildValue( + "{s:i,s:(ddd),s:s,s:d,s:s}", + "observer", + mc->Observer, + "backing", + mc->Backing.X, + mc->Backing.Y, + mc->Backing.Z, + "geo", + geo, + "flare", + mc->Flare, + "illuminant_type", + _illu_map(mc->IlluminantType)); } -static PyObject* -cms_profile_getattr_icc_viewing_condition (CmsProfileObject* self, void* closure) -{ - cmsICCViewingConditions* vc; +static PyObject * +cms_profile_getattr_icc_viewing_condition(CmsProfileObject *self, void *closure) { + cmsICCViewingConditions *vc; cmsTagSignature info = cmsSigViewingConditionsTag; if (!cmsIsTag(self->profile, info)) { @@ -1339,158 +1348,164 @@ cms_profile_getattr_icc_viewing_condition (CmsProfileObject* self, void* closure return Py_None; } - vc = (cmsICCViewingConditions*) cmsReadTag(self->profile, info); + vc = (cmsICCViewingConditions *)cmsReadTag(self->profile, info); if (!vc) { Py_INCREF(Py_None); return Py_None; } - return Py_BuildValue("{s:(ddd),s:(ddd),s:s}", - "illuminant", vc->IlluminantXYZ.X, vc->IlluminantXYZ.Y, vc->IlluminantXYZ.Z, - "surround", vc->SurroundXYZ.X, vc->SurroundXYZ.Y, vc->SurroundXYZ.Z, - "illuminant_type", _illu_map(vc->IlluminantType)); + return Py_BuildValue( + "{s:(ddd),s:(ddd),s:s}", + "illuminant", + vc->IlluminantXYZ.X, + vc->IlluminantXYZ.Y, + vc->IlluminantXYZ.Z, + "surround", + vc->SurroundXYZ.X, + vc->SurroundXYZ.Y, + vc->SurroundXYZ.Z, + "illuminant_type", + _illu_map(vc->IlluminantType)); } - static struct PyGetSetDef cms_profile_getsetters[] = { /* New style interfaces. */ - { "rendering_intent", (getter) cms_profile_getattr_rendering_intent }, - { "creation_date", (getter) cms_profile_getattr_creation_date }, - { "copyright", (getter) cms_profile_getattr_copyright }, - { "target", (getter) cms_profile_getattr_target }, - { "manufacturer", (getter) cms_profile_getattr_manufacturer }, - { "model", (getter) cms_profile_getattr_model }, - { "profile_description", (getter) cms_profile_getattr_profile_description }, - { "screening_description", (getter) cms_profile_getattr_screening_description }, - { "viewing_condition", (getter) cms_profile_getattr_viewing_condition }, - { "version", (getter) cms_profile_getattr_version }, - { "icc_version", (getter) cms_profile_getattr_icc_version }, - { "attributes", (getter) cms_profile_getattr_attributes }, - { "header_flags", (getter) cms_profile_getattr_header_flags }, - { "header_manufacturer", (getter) cms_profile_getattr_header_manufacturer }, - { "header_model", (getter) cms_profile_getattr_header_model }, - { "device_class", (getter) cms_profile_getattr_device_class }, - { "connection_space", (getter) cms_profile_getattr_connection_space }, - { "xcolor_space", (getter) cms_profile_getattr_xcolor_space }, - { "profile_id", (getter) cms_profile_getattr_profile_id }, - { "is_matrix_shaper", (getter) cms_profile_getattr_is_matrix_shaper }, - { "technology", (getter) cms_profile_getattr_technology }, - { "colorimetric_intent", (getter) cms_profile_getattr_colorimetric_intent }, - { "perceptual_rendering_intent_gamut", (getter) cms_profile_getattr_perceptual_rendering_intent_gamut }, - { "saturation_rendering_intent_gamut", (getter) cms_profile_getattr_saturation_rendering_intent_gamut }, - { "red_colorant", (getter) cms_profile_getattr_red_colorant }, - { "green_colorant", (getter) cms_profile_getattr_green_colorant }, - { "blue_colorant", (getter) cms_profile_getattr_blue_colorant }, - { "red_primary", (getter) cms_profile_getattr_red_primary }, - { "green_primary", (getter) cms_profile_getattr_green_primary }, - { "blue_primary", (getter) cms_profile_getattr_blue_primary }, - { "media_white_point_temperature", (getter) cms_profile_getattr_media_white_point_temperature }, - { "media_white_point", (getter) cms_profile_getattr_media_white_point }, - { "media_black_point", (getter) cms_profile_getattr_media_black_point }, - { "luminance", (getter) cms_profile_getattr_luminance }, - { "chromatic_adaptation", (getter) cms_profile_getattr_chromatic_adaptation }, - { "chromaticity", (getter) cms_profile_getattr_chromaticity }, - { "colorant_table", (getter) cms_profile_getattr_colorant_table }, - { "colorant_table_out", (getter) cms_profile_getattr_colorant_table_out }, - { "intent_supported", (getter) cms_profile_getattr_is_intent_supported }, - { "clut", (getter) cms_profile_getattr_is_clut }, - { "icc_measurement_condition", (getter) cms_profile_getattr_icc_measurement_condition }, - { "icc_viewing_condition", (getter) cms_profile_getattr_icc_viewing_condition }, - - { NULL } -}; + {"rendering_intent", (getter)cms_profile_getattr_rendering_intent}, + {"creation_date", (getter)cms_profile_getattr_creation_date}, + {"copyright", (getter)cms_profile_getattr_copyright}, + {"target", (getter)cms_profile_getattr_target}, + {"manufacturer", (getter)cms_profile_getattr_manufacturer}, + {"model", (getter)cms_profile_getattr_model}, + {"profile_description", (getter)cms_profile_getattr_profile_description}, + {"screening_description", (getter)cms_profile_getattr_screening_description}, + {"viewing_condition", (getter)cms_profile_getattr_viewing_condition}, + {"version", (getter)cms_profile_getattr_version}, + {"icc_version", (getter)cms_profile_getattr_icc_version}, + {"attributes", (getter)cms_profile_getattr_attributes}, + {"header_flags", (getter)cms_profile_getattr_header_flags}, + {"header_manufacturer", (getter)cms_profile_getattr_header_manufacturer}, + {"header_model", (getter)cms_profile_getattr_header_model}, + {"device_class", (getter)cms_profile_getattr_device_class}, + {"connection_space", (getter)cms_profile_getattr_connection_space}, + {"xcolor_space", (getter)cms_profile_getattr_xcolor_space}, + {"profile_id", (getter)cms_profile_getattr_profile_id}, + {"is_matrix_shaper", (getter)cms_profile_getattr_is_matrix_shaper}, + {"technology", (getter)cms_profile_getattr_technology}, + {"colorimetric_intent", (getter)cms_profile_getattr_colorimetric_intent}, + {"perceptual_rendering_intent_gamut", + (getter)cms_profile_getattr_perceptual_rendering_intent_gamut}, + {"saturation_rendering_intent_gamut", + (getter)cms_profile_getattr_saturation_rendering_intent_gamut}, + {"red_colorant", (getter)cms_profile_getattr_red_colorant}, + {"green_colorant", (getter)cms_profile_getattr_green_colorant}, + {"blue_colorant", (getter)cms_profile_getattr_blue_colorant}, + {"red_primary", (getter)cms_profile_getattr_red_primary}, + {"green_primary", (getter)cms_profile_getattr_green_primary}, + {"blue_primary", (getter)cms_profile_getattr_blue_primary}, + {"media_white_point_temperature", + (getter)cms_profile_getattr_media_white_point_temperature}, + {"media_white_point", (getter)cms_profile_getattr_media_white_point}, + {"media_black_point", (getter)cms_profile_getattr_media_black_point}, + {"luminance", (getter)cms_profile_getattr_luminance}, + {"chromatic_adaptation", (getter)cms_profile_getattr_chromatic_adaptation}, + {"chromaticity", (getter)cms_profile_getattr_chromaticity}, + {"colorant_table", (getter)cms_profile_getattr_colorant_table}, + {"colorant_table_out", (getter)cms_profile_getattr_colorant_table_out}, + {"intent_supported", (getter)cms_profile_getattr_is_intent_supported}, + {"clut", (getter)cms_profile_getattr_is_clut}, + {"icc_measurement_condition", + (getter)cms_profile_getattr_icc_measurement_condition}, + {"icc_viewing_condition", (getter)cms_profile_getattr_icc_viewing_condition}, + {NULL}}; static PyTypeObject CmsProfile_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "PIL._imagingcms.CmsProfile", /*tp_name */ - sizeof(CmsProfileObject), 0,/*tp_basicsize, tp_itemsize */ + PyVarObject_HEAD_INIT(NULL, 0) "PIL._imagingcms.CmsProfile", /*tp_name */ + sizeof(CmsProfileObject), + 0, /*tp_basicsize, tp_itemsize */ /* methods */ - (destructor) cms_profile_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - cms_profile_methods, /*tp_methods*/ - 0, /*tp_members*/ - cms_profile_getsetters, /*tp_getset*/ + (destructor)cms_profile_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + cms_profile_methods, /*tp_methods*/ + 0, /*tp_members*/ + cms_profile_getsetters, /*tp_getset*/ }; static struct PyMethodDef cms_transform_methods[] = { - {"apply", (PyCFunction) cms_transform_apply, 1}, - {NULL, NULL} /* sentinel */ + {"apply", (PyCFunction)cms_transform_apply, 1}, {NULL, NULL} /* sentinel */ }; -static PyObject* -cms_transform_getattr_inputMode(CmsTransformObject* self, void* closure) -{ +static PyObject * +cms_transform_getattr_inputMode(CmsTransformObject *self, void *closure) { return PyUnicode_FromString(self->mode_in); } -static PyObject* -cms_transform_getattr_outputMode(CmsTransformObject* self, void* closure) -{ +static PyObject * +cms_transform_getattr_outputMode(CmsTransformObject *self, void *closure) { return PyUnicode_FromString(self->mode_out); } static struct PyGetSetDef cms_transform_getsetters[] = { - { "inputMode", (getter) cms_transform_getattr_inputMode }, - { "outputMode", (getter) cms_transform_getattr_outputMode }, - { NULL } -}; + {"inputMode", (getter)cms_transform_getattr_inputMode}, + {"outputMode", (getter)cms_transform_getattr_outputMode}, + {NULL}}; static PyTypeObject CmsTransform_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "CmsTransform", sizeof(CmsTransformObject), 0, + PyVarObject_HEAD_INIT(NULL, 0) "CmsTransform", + sizeof(CmsTransformObject), + 0, /* methods */ - (destructor) cms_transform_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - cms_transform_methods, /*tp_methods*/ - 0, /*tp_members*/ - cms_transform_getsetters, /*tp_getset*/ + (destructor)cms_transform_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + cms_transform_methods, /*tp_methods*/ + 0, /*tp_members*/ + cms_transform_getsetters, /*tp_getset*/ }; static int -setup_module(PyObject* m) { +setup_module(PyObject *m) { PyObject *d; PyObject *v; int vn; @@ -1524,14 +1539,14 @@ setup_module(PyObject* m) { PyMODINIT_FUNC PyInit__imagingcms(void) { - PyObject* m; + PyObject *m; static PyModuleDef module_def = { PyModuleDef_HEAD_INIT, - "_imagingcms", /* m_name */ - NULL, /* m_doc */ - -1, /* m_size */ - pyCMSdll_methods, /* m_methods */ + "_imagingcms", /* m_name */ + NULL, /* m_doc */ + -1, /* m_size */ + pyCMSdll_methods, /* m_methods */ }; m = PyModule_Create(&module_def); diff --git a/src/_imagingft.c b/src/_imagingft.c index 5566ee3da..d73c6c2d5 100644 --- a/src/_imagingft.c +++ b/src/_imagingft.c @@ -40,7 +40,7 @@ #endif #if !defined(FT_LOAD_TARGET_MONO) -#define FT_LOAD_TARGET_MONO FT_LOAD_MONOCHROME +#define FT_LOAD_TARGET_MONO FT_LOAD_MONOCHROME #endif /* -------------------------------------------------------------------- */ @@ -49,73 +49,61 @@ #undef FTERRORS_H #undef __FTERRORS_H__ -#define FT_ERRORDEF( e, v, s ) { e, s }, -#define FT_ERROR_START_LIST { -#define FT_ERROR_END_LIST { 0, 0 } }; +#define FT_ERRORDEF(e, v, s) {e, s}, +#define FT_ERROR_START_LIST { +#define FT_ERROR_END_LIST \ + { 0, 0 } \ + } \ + ; #include "libImaging/raqm.h" #define LAYOUT_FALLBACK 0 #define LAYOUT_RAQM 1 -typedef struct -{ - int index, x_offset, x_advance, y_offset, y_advance; - unsigned int cluster; +typedef struct { + int index, x_offset, x_advance, y_offset, y_advance; + unsigned int cluster; } GlyphInfo; struct { int code; - const char* message; + const char *message; } ft_errors[] = #include FT_ERRORS_H -/* -------------------------------------------------------------------- */ -/* font objects */ + /* -------------------------------------------------------------------- */ + /* font objects */ -static FT_Library library; + static FT_Library library; typedef struct { - PyObject_HEAD - FT_Face face; + PyObject_HEAD FT_Face face; unsigned char *font_bytes; int layout_engine; } FontObject; static PyTypeObject Font_Type; -typedef const char* (*t_raqm_version_string) (void); -typedef bool (*t_raqm_version_atleast)(unsigned int major, - unsigned int minor, - unsigned int micro); -typedef raqm_t* (*t_raqm_create)(void); -typedef int (*t_raqm_set_text)(raqm_t *rq, - const uint32_t *text, - size_t len); -typedef bool (*t_raqm_set_text_utf8) (raqm_t *rq, - const char *text, - size_t len); -typedef bool (*t_raqm_set_par_direction) (raqm_t *rq, - raqm_direction_t dir); -typedef bool (*t_raqm_set_language) (raqm_t *rq, - const char *lang, - size_t start, - size_t len); -typedef bool (*t_raqm_add_font_feature) (raqm_t *rq, - const char *feature, - int len); -typedef bool (*t_raqm_set_freetype_face) (raqm_t *rq, - FT_Face face); -typedef bool (*t_raqm_layout) (raqm_t *rq); -typedef raqm_glyph_t* (*t_raqm_get_glyphs) (raqm_t *rq, - size_t *length); -typedef raqm_glyph_t_01* (*t_raqm_get_glyphs_01) (raqm_t *rq, - size_t *length); -typedef void (*t_raqm_destroy) (raqm_t *rq); +typedef const char *(*t_raqm_version_string)(void); +typedef bool (*t_raqm_version_atleast)( + unsigned int major, unsigned int minor, unsigned int micro); +typedef raqm_t *(*t_raqm_create)(void); +typedef int (*t_raqm_set_text)(raqm_t *rq, const uint32_t *text, size_t len); +typedef bool (*t_raqm_set_text_utf8)(raqm_t *rq, const char *text, size_t len); +typedef bool (*t_raqm_set_par_direction)(raqm_t *rq, raqm_direction_t dir); +typedef bool (*t_raqm_set_language)( + raqm_t *rq, const char *lang, size_t start, size_t len); +typedef bool (*t_raqm_add_font_feature)(raqm_t *rq, const char *feature, int len); +typedef bool (*t_raqm_set_freetype_face)(raqm_t *rq, FT_Face face); +typedef bool (*t_raqm_layout)(raqm_t *rq); +typedef raqm_glyph_t *(*t_raqm_get_glyphs)(raqm_t *rq, size_t *length); +typedef raqm_glyph_t_01 *(*t_raqm_get_glyphs_01)(raqm_t *rq, size_t *length); +typedef void (*t_raqm_destroy)(raqm_t *rq); typedef struct { - void* raqm; + void *raqm; int version; t_raqm_version_string version_string; t_raqm_version_atleast version_atleast; @@ -134,13 +122,11 @@ typedef struct { static p_raqm_func p_raqm; - /* round a 26.6 pixel coordinate to the nearest integer */ -#define PIXEL(x) ((((x)+32) & -64)>>6) +#define PIXEL(x) ((((x) + 32) & -64) >> 6) -static PyObject* -geterror(int code) -{ +static PyObject * +geterror(int code) { int i; for (i = 0; ft_errors[i].message; i++) { @@ -155,8 +141,7 @@ geterror(int code) } static int -setraqm(void) -{ +setraqm(void) { /* set the static function pointers for dynamic raqm linking */ p_raqm.raqm = NULL; @@ -179,68 +164,72 @@ setraqm(void) } #ifndef _WIN32 - p_raqm.version_string = (t_raqm_version_string)dlsym(p_raqm.raqm, "raqm_version_string"); - p_raqm.version_atleast = (t_raqm_version_atleast)dlsym(p_raqm.raqm, "raqm_version_atleast"); + p_raqm.version_string = + (t_raqm_version_string)dlsym(p_raqm.raqm, "raqm_version_string"); + p_raqm.version_atleast = + (t_raqm_version_atleast)dlsym(p_raqm.raqm, "raqm_version_atleast"); p_raqm.create = (t_raqm_create)dlsym(p_raqm.raqm, "raqm_create"); p_raqm.set_text = (t_raqm_set_text)dlsym(p_raqm.raqm, "raqm_set_text"); - p_raqm.set_text_utf8 = (t_raqm_set_text_utf8)dlsym(p_raqm.raqm, "raqm_set_text_utf8"); - p_raqm.set_par_direction = (t_raqm_set_par_direction)dlsym(p_raqm.raqm, "raqm_set_par_direction"); + p_raqm.set_text_utf8 = + (t_raqm_set_text_utf8)dlsym(p_raqm.raqm, "raqm_set_text_utf8"); + p_raqm.set_par_direction = + (t_raqm_set_par_direction)dlsym(p_raqm.raqm, "raqm_set_par_direction"); p_raqm.set_language = (t_raqm_set_language)dlsym(p_raqm.raqm, "raqm_set_language"); - p_raqm.add_font_feature = (t_raqm_add_font_feature)dlsym(p_raqm.raqm, "raqm_add_font_feature"); - p_raqm.set_freetype_face = (t_raqm_set_freetype_face)dlsym(p_raqm.raqm, "raqm_set_freetype_face"); + p_raqm.add_font_feature = + (t_raqm_add_font_feature)dlsym(p_raqm.raqm, "raqm_add_font_feature"); + p_raqm.set_freetype_face = + (t_raqm_set_freetype_face)dlsym(p_raqm.raqm, "raqm_set_freetype_face"); p_raqm.layout = (t_raqm_layout)dlsym(p_raqm.raqm, "raqm_layout"); p_raqm.destroy = (t_raqm_destroy)dlsym(p_raqm.raqm, "raqm_destroy"); - if(dlsym(p_raqm.raqm, "raqm_index_to_position")) { + if (dlsym(p_raqm.raqm, "raqm_index_to_position")) { p_raqm.get_glyphs = (t_raqm_get_glyphs)dlsym(p_raqm.raqm, "raqm_get_glyphs"); p_raqm.version = 2; } else { p_raqm.version = 1; - p_raqm.get_glyphs_01 = (t_raqm_get_glyphs_01)dlsym(p_raqm.raqm, "raqm_get_glyphs"); + p_raqm.get_glyphs_01 = + (t_raqm_get_glyphs_01)dlsym(p_raqm.raqm, "raqm_get_glyphs"); } if (dlerror() || - !(p_raqm.create && - p_raqm.set_text && - p_raqm.set_text_utf8 && - p_raqm.set_par_direction && - p_raqm.set_language && - p_raqm.add_font_feature && - p_raqm.set_freetype_face && - p_raqm.layout && - (p_raqm.get_glyphs || p_raqm.get_glyphs_01) && - p_raqm.destroy)) { + !(p_raqm.create && p_raqm.set_text && p_raqm.set_text_utf8 && + p_raqm.set_par_direction && p_raqm.set_language && p_raqm.add_font_feature && + p_raqm.set_freetype_face && p_raqm.layout && + (p_raqm.get_glyphs || p_raqm.get_glyphs_01) && p_raqm.destroy)) { dlclose(p_raqm.raqm); p_raqm.raqm = NULL; return 2; } #else - p_raqm.version_string = (t_raqm_version_string)GetProcAddress(p_raqm.raqm, "raqm_version_string"); - p_raqm.version_atleast = (t_raqm_version_atleast)GetProcAddress(p_raqm.raqm, "raqm_version_atleast"); + p_raqm.version_string = + (t_raqm_version_string)GetProcAddress(p_raqm.raqm, "raqm_version_string"); + p_raqm.version_atleast = + (t_raqm_version_atleast)GetProcAddress(p_raqm.raqm, "raqm_version_atleast"); p_raqm.create = (t_raqm_create)GetProcAddress(p_raqm.raqm, "raqm_create"); p_raqm.set_text = (t_raqm_set_text)GetProcAddress(p_raqm.raqm, "raqm_set_text"); - p_raqm.set_text_utf8 = (t_raqm_set_text_utf8)GetProcAddress(p_raqm.raqm, "raqm_set_text_utf8"); - p_raqm.set_par_direction = (t_raqm_set_par_direction)GetProcAddress(p_raqm.raqm, "raqm_set_par_direction"); - p_raqm.set_language = (t_raqm_set_language)GetProcAddress(p_raqm.raqm, "raqm_set_language"); - p_raqm.add_font_feature = (t_raqm_add_font_feature)GetProcAddress(p_raqm.raqm, "raqm_add_font_feature"); - p_raqm.set_freetype_face = (t_raqm_set_freetype_face)GetProcAddress(p_raqm.raqm, "raqm_set_freetype_face"); + p_raqm.set_text_utf8 = + (t_raqm_set_text_utf8)GetProcAddress(p_raqm.raqm, "raqm_set_text_utf8"); + p_raqm.set_par_direction = + (t_raqm_set_par_direction)GetProcAddress(p_raqm.raqm, "raqm_set_par_direction"); + p_raqm.set_language = + (t_raqm_set_language)GetProcAddress(p_raqm.raqm, "raqm_set_language"); + p_raqm.add_font_feature = + (t_raqm_add_font_feature)GetProcAddress(p_raqm.raqm, "raqm_add_font_feature"); + p_raqm.set_freetype_face = + (t_raqm_set_freetype_face)GetProcAddress(p_raqm.raqm, "raqm_set_freetype_face"); p_raqm.layout = (t_raqm_layout)GetProcAddress(p_raqm.raqm, "raqm_layout"); p_raqm.destroy = (t_raqm_destroy)GetProcAddress(p_raqm.raqm, "raqm_destroy"); - if(GetProcAddress(p_raqm.raqm, "raqm_index_to_position")) { - p_raqm.get_glyphs = (t_raqm_get_glyphs)GetProcAddress(p_raqm.raqm, "raqm_get_glyphs"); + if (GetProcAddress(p_raqm.raqm, "raqm_index_to_position")) { + p_raqm.get_glyphs = + (t_raqm_get_glyphs)GetProcAddress(p_raqm.raqm, "raqm_get_glyphs"); p_raqm.version = 2; } else { p_raqm.version = 1; - p_raqm.get_glyphs_01 = (t_raqm_get_glyphs_01)GetProcAddress(p_raqm.raqm, "raqm_get_glyphs"); + p_raqm.get_glyphs_01 = + (t_raqm_get_glyphs_01)GetProcAddress(p_raqm.raqm, "raqm_get_glyphs"); } - if (!(p_raqm.create && - p_raqm.set_text && - p_raqm.set_text_utf8 && - p_raqm.set_par_direction && - p_raqm.set_language && - p_raqm.add_font_feature && - p_raqm.set_freetype_face && - p_raqm.layout && - (p_raqm.get_glyphs || p_raqm.get_glyphs_01) && - p_raqm.destroy)) { + if (!(p_raqm.create && p_raqm.set_text && p_raqm.set_text_utf8 && + p_raqm.set_par_direction && p_raqm.set_language && p_raqm.add_font_feature && + p_raqm.set_freetype_face && p_raqm.layout && + (p_raqm.get_glyphs || p_raqm.get_glyphs_01) && p_raqm.destroy)) { FreeLibrary(p_raqm.raqm); p_raqm.raqm = NULL; return 2; @@ -250,38 +239,41 @@ setraqm(void) return 0; } -static PyObject* -getfont(PyObject* self_, PyObject* args, PyObject* kw) -{ +static PyObject * +getfont(PyObject *self_, PyObject *args, PyObject *kw) { /* create a font object from a file name and a size (in pixels) */ - FontObject* self; + FontObject *self; int error = 0; - char* filename = NULL; + char *filename = NULL; Py_ssize_t size; Py_ssize_t index = 0; Py_ssize_t layout_engine = 0; - unsigned char* encoding; - unsigned char* font_bytes; + unsigned char *encoding; + unsigned char *font_bytes; Py_ssize_t font_bytes_size = 0; - static char* kwlist[] = { - "filename", "size", "index", "encoding", "font_bytes", - "layout_engine", NULL - }; + static char *kwlist[] = { + "filename", "size", "index", "encoding", "font_bytes", "layout_engine", NULL}; if (!library) { - PyErr_SetString( - PyExc_OSError, - "failed to initialize FreeType library" - ); + PyErr_SetString(PyExc_OSError, "failed to initialize FreeType library"); return NULL; } - if (!PyArg_ParseTupleAndKeywords(args, kw, "etn|nsy#n", kwlist, - Py_FileSystemDefaultEncoding, &filename, - &size, &index, &encoding, &font_bytes, - &font_bytes_size, &layout_engine)) { + if (!PyArg_ParseTupleAndKeywords( + args, + kw, + "etn|nsy#n", + kwlist, + Py_FileSystemDefaultEncoding, + &filename, + &size, + &index, + &encoding, + &font_bytes, + &font_bytes_size, + &layout_engine)) { return NULL; } @@ -304,12 +296,16 @@ getfont(PyObject* self_, PyObject* args, PyObject* kw) /* Don't free this before FT_Done_Face */ self->font_bytes = PyMem_Malloc(font_bytes_size); if (!self->font_bytes) { - error = 65; // Out of Memory in Freetype. + error = 65; // Out of Memory in Freetype. } if (!error) { memcpy(self->font_bytes, font_bytes, (size_t)font_bytes_size); - error = FT_New_Memory_Face(library, (FT_Byte*)self->font_bytes, - font_bytes_size, index, &self->face); + error = FT_New_Memory_Face( + library, + (FT_Byte *)self->font_bytes, + font_bytes_size, + index, + &self->face); } } @@ -317,14 +313,13 @@ getfont(PyObject* self_, PyObject* args, PyObject* kw) error = FT_Set_Pixel_Sizes(self->face, 0, size); } - if (!error && encoding && strlen((char*) encoding) == 4) { - FT_Encoding encoding_tag = FT_MAKE_TAG( - encoding[0], encoding[1], encoding[2], encoding[3] - ); + if (!error && encoding && strlen((char *)encoding) == 4) { + FT_Encoding encoding_tag = + FT_MAKE_TAG(encoding[0], encoding[1], encoding[2], encoding[3]); error = FT_Select_Charmap(self->face, encoding_tag); } if (filename) { - PyMem_Free(filename); + PyMem_Free(filename); } if (error) { @@ -336,12 +331,11 @@ getfont(PyObject* self_, PyObject* args, PyObject* kw) return geterror(error); } - return (PyObject*) self; + return (PyObject *)self; } static int -font_getchar(PyObject* string, int index, FT_ULong* char_out) -{ +font_getchar(PyObject *string, int index, FT_ULong *char_out) { if (PyUnicode_Check(string)) { if (index >= PyUnicode_GET_LENGTH(string)) { return 0; @@ -353,9 +347,15 @@ font_getchar(PyObject* string, int index, FT_ULong* char_out) } static size_t -text_layout_raqm(PyObject* string, FontObject* self, const char* dir, PyObject *features, - const char* lang, GlyphInfo **glyph_info, int mask, int color) -{ +text_layout_raqm( + PyObject *string, + FontObject *self, + const char *dir, + PyObject *features, + const char *lang, + GlyphInfo **glyph_info, + int mask, + int color) { size_t i = 0, count = 0, start = 0; raqm_t *rq; raqm_glyph_t *glyphs = NULL; @@ -388,8 +388,7 @@ text_layout_raqm(PyObject* string, FontObject* self, const char* dir, PyObject * goto failed; } } - } - else { + } else { PyErr_SetString(PyExc_TypeError, "expected string"); goto failed; } @@ -403,11 +402,14 @@ text_layout_raqm(PyObject* string, FontObject* self, const char* dir, PyObject * } else if (strcmp(dir, "ttb") == 0) { direction = RAQM_DIRECTION_TTB; if (p_raqm.version_atleast == NULL || !(*p_raqm.version_atleast)(0, 7, 0)) { - PyErr_SetString(PyExc_ValueError, "libraqm 0.7 or greater required for 'ttb' direction"); + PyErr_SetString( + PyExc_ValueError, + "libraqm 0.7 or greater required for 'ttb' direction"); goto failed; } } else { - PyErr_SetString(PyExc_ValueError, "direction must be either 'rtl', 'ltr' or 'ttb'"); + PyErr_SetString( + PyExc_ValueError, "direction must be either 'rtl', 'ltr' or 'ttb'"); goto failed; } } @@ -510,9 +512,15 @@ failed: } static size_t -text_layout_fallback(PyObject* string, FontObject* self, const char* dir, PyObject *features, - const char* lang, GlyphInfo **glyph_info, int mask, int color) -{ +text_layout_fallback( + PyObject *string, + FontObject *self, + const char *dir, + PyObject *features, + const char *lang, + GlyphInfo **glyph_info, + int mask, + int color) { int error, load_flags; FT_ULong ch; Py_ssize_t count; @@ -522,7 +530,10 @@ text_layout_fallback(PyObject* string, FontObject* self, const char* dir, PyObje int i; if (features != Py_None || dir != NULL || lang != NULL) { - PyErr_SetString(PyExc_KeyError, "setting text direction, language or font features is not supported without libraqm"); + PyErr_SetString( + PyExc_KeyError, + "setting text direction, language or font features is not supported " + "without libraqm"); } if (!PyUnicode_Check(string)) { PyErr_SetString(PyExc_TypeError, "expected string"); @@ -531,7 +542,7 @@ text_layout_fallback(PyObject* string, FontObject* self, const char* dir, PyObje count = 0; while (font_getchar(string, count, &ch)) { - count++; + count++; } if (count == 0) { return 0; @@ -560,14 +571,18 @@ text_layout_fallback(PyObject* string, FontObject* self, const char* dir, PyObje return 0; } glyph = self->face->glyph; - (*glyph_info)[i].x_offset=0; - (*glyph_info)[i].y_offset=0; + (*glyph_info)[i].x_offset = 0; + (*glyph_info)[i].y_offset = 0; if (kerning && last_index && (*glyph_info)[i].index) { FT_Vector delta; - if (FT_Get_Kerning(self->face, last_index, (*glyph_info)[i].index, - ft_kerning_default,&delta) == 0) { - (*glyph_info)[i-1].x_advance += PIXEL(delta.x); - (*glyph_info)[i-1].y_advance += PIXEL(delta.y); + if (FT_Get_Kerning( + self->face, + last_index, + (*glyph_info)[i].index, + ft_kerning_default, + &delta) == 0) { + (*glyph_info)[i - 1].x_advance += PIXEL(delta.x); + (*glyph_info)[i - 1].y_advance += PIXEL(delta.y); } } @@ -581,28 +596,35 @@ text_layout_fallback(PyObject* string, FontObject* self, const char* dir, PyObje } static size_t -text_layout(PyObject* string, FontObject* self, const char* dir, PyObject *features, - const char* lang, GlyphInfo **glyph_info, int mask, int color) -{ +text_layout( + PyObject *string, + FontObject *self, + const char *dir, + PyObject *features, + const char *lang, + GlyphInfo **glyph_info, + int mask, + int color) { size_t count; if (p_raqm.raqm && self->layout_engine == LAYOUT_RAQM) { - count = text_layout_raqm(string, self, dir, features, lang, glyph_info, mask, color); + count = text_layout_raqm( + string, self, dir, features, lang, glyph_info, mask, color); } else { - count = text_layout_fallback(string, self, dir, features, lang, glyph_info, mask, color); + count = text_layout_fallback( + string, self, dir, features, lang, glyph_info, mask, color); } return count; } -static PyObject* -font_getlength(FontObject* self, PyObject* args) -{ - int length; /* length along primary axis, in 26.6 precision */ +static PyObject * +font_getlength(FontObject *self, PyObject *args) { + int length; /* length along primary axis, in 26.6 precision */ GlyphInfo *glyph_info = NULL; /* computed text layout */ - size_t i, count; /* glyph_info index and length */ - int horizontal_dir; /* is primary axis horizontal? */ - int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */ - int color = 0; /* is FT_LOAD_COLOR enabled? */ + size_t i, count; /* glyph_info index and length */ + int horizontal_dir; /* is primary axis horizontal? */ + int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */ + int color = 0; /* is FT_LOAD_COLOR enabled? */ const char *mode = NULL; const char *dir = NULL; const char *lang = NULL; @@ -611,7 +633,8 @@ font_getlength(FontObject* self, PyObject* args) /* calculate size and bearing for a given string */ - if (!PyArg_ParseTuple(args, "O|zzOz:getlength", &string, &mode, &dir, &features, &lang)) { + if (!PyArg_ParseTuple( + args, "O|zzOz:getlength", &string, &mode, &dir, &features, &lang)) { return NULL; } @@ -642,24 +665,23 @@ font_getlength(FontObject* self, PyObject* args) return PyLong_FromLong(length); } -static PyObject* -font_getsize(FontObject* self, PyObject* args) -{ +static PyObject * +font_getsize(FontObject *self, PyObject *args) { int position; /* pen position along primary axis, in 26.6 precision */ int advanced; /* pen position along primary axis, in pixels */ - int px, py; /* position of current glyph, in pixels */ + int px, py; /* position of current glyph, in pixels */ int x_min, x_max, y_min, y_max; /* text bounding box, in pixels */ - int x_anchor, y_anchor; /* offset of point drawn at (0, 0), in pixels */ - int load_flags; /* FreeType load_flags parameter */ + int x_anchor, y_anchor; /* offset of point drawn at (0, 0), in pixels */ + int load_flags; /* FreeType load_flags parameter */ int error; FT_Face face; FT_Glyph glyph; - FT_BBox bbox; /* glyph bounding box */ + FT_BBox bbox; /* glyph bounding box */ GlyphInfo *glyph_info = NULL; /* computed text layout */ - size_t i, count; /* glyph_info index and length */ - int horizontal_dir; /* is primary axis horizontal? */ - int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */ - int color = 0; /* is FT_LOAD_COLOR enabled? */ + size_t i, count; /* glyph_info index and length */ + int horizontal_dir; /* is primary axis horizontal? */ + int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */ + int color = 0; /* is FT_LOAD_COLOR enabled? */ const char *mode = NULL; const char *dir = NULL; const char *lang = NULL; @@ -669,7 +691,8 @@ font_getsize(FontObject* self, PyObject* args) /* calculate size and bearing for a given string */ - if (!PyArg_ParseTuple(args, "O|zzOzz:getsize", &string, &mode, &dir, &features, &lang, &anchor)) { + if (!PyArg_ParseTuple( + args, "O|zzOzz:getsize", &string, &mode, &dir, &features, &lang, &anchor)) { return NULL; } @@ -771,95 +794,98 @@ font_getsize(FontObject* self, PyObject* args) if (face) { if (horizontal_dir) { switch (anchor[0]) { - case 'l': // left - x_anchor = 0; - break; - case 'm': // middle (left + right) / 2 - x_anchor = PIXEL(position / 2); - break; - case 'r': // right - x_anchor = PIXEL(position); - break; - case 's': // vertical baseline - default: - goto bad_anchor; + case 'l': // left + x_anchor = 0; + break; + case 'm': // middle (left + right) / 2 + x_anchor = PIXEL(position / 2); + break; + case 'r': // right + x_anchor = PIXEL(position); + break; + case 's': // vertical baseline + default: + goto bad_anchor; } switch (anchor[1]) { - case 'a': // ascender - y_anchor = PIXEL(self->face->size->metrics.ascender); - break; - case 't': // top - y_anchor = y_max; - break; - case 'm': // middle (ascender + descender) / 2 - y_anchor = PIXEL((self->face->size->metrics.ascender + self->face->size->metrics.descender) / 2); - break; - case 's': // horizontal baseline - y_anchor = 0; - break; - case 'b': // bottom - y_anchor = y_min; - break; - case 'd': // descender - y_anchor = PIXEL(self->face->size->metrics.descender); - break; - default: - goto bad_anchor; + case 'a': // ascender + y_anchor = PIXEL(self->face->size->metrics.ascender); + break; + case 't': // top + y_anchor = y_max; + break; + case 'm': // middle (ascender + descender) / 2 + y_anchor = PIXEL( + (self->face->size->metrics.ascender + + self->face->size->metrics.descender) / + 2); + break; + case 's': // horizontal baseline + y_anchor = 0; + break; + case 'b': // bottom + y_anchor = y_min; + break; + case 'd': // descender + y_anchor = PIXEL(self->face->size->metrics.descender); + break; + default: + goto bad_anchor; } } else { switch (anchor[0]) { - case 'l': // left - x_anchor = x_min; - break; - case 'm': // middle (left + right) / 2 - x_anchor = (x_min + x_max) / 2; - break; - case 'r': // right - x_anchor = x_max; - break; - case 's': // vertical baseline - x_anchor = 0; - break; - default: - goto bad_anchor; + case 'l': // left + x_anchor = x_min; + break; + case 'm': // middle (left + right) / 2 + x_anchor = (x_min + x_max) / 2; + break; + case 'r': // right + x_anchor = x_max; + break; + case 's': // vertical baseline + x_anchor = 0; + break; + default: + goto bad_anchor; } switch (anchor[1]) { - case 't': // top - y_anchor = 0; - break; - case 'm': // middle (top + bottom) / 2 - y_anchor = PIXEL(position / 2); - break; - case 'b': // bottom - y_anchor = PIXEL(position); - break; - case 'a': // ascender - case 's': // horizontal baseline - case 'd': // descender - default: - goto bad_anchor; + case 't': // top + y_anchor = 0; + break; + case 'm': // middle (top + bottom) / 2 + y_anchor = PIXEL(position / 2); + break; + case 'b': // bottom + y_anchor = PIXEL(position); + break; + case 'a': // ascender + case 's': // horizontal baseline + case 'd': // descender + default: + goto bad_anchor; } } } return Py_BuildValue( "(ii)(ii)", - (x_max - x_min), (y_max - y_min), - (-x_anchor + x_min), -(-y_anchor + y_max) - ); + (x_max - x_min), + (y_max - y_min), + (-x_anchor + x_min), + -(-y_anchor + y_max)); bad_anchor: PyErr_Format(PyExc_ValueError, "bad anchor specified: %s", anchor); return NULL; } -static PyObject* -font_render(FontObject* self, PyObject* args) -{ - int x, y; /* pen position, in 26.6 precision */ - int px, py; /* position of current glyph, in pixels */ +static PyObject * +font_render(FontObject *self, PyObject *args) { + int x, y; /* pen position, in 26.6 precision */ + int px, py; /* position of current glyph, in pixels */ int x_min, y_max; /* text offset in 26.6 precision */ - int load_flags; /* FreeType load_flags parameter */ + int load_flags; /* FreeType load_flags parameter */ int error; FT_Glyph glyph; FT_GlyphSlot glyph_slot; @@ -868,16 +894,16 @@ font_render(FontObject* self, PyObject* args) FT_BitmapGlyph bitmap_glyph; FT_Stroker stroker = NULL; int bitmap_converted_ready = 0; /* has bitmap_converted been initialized */ - GlyphInfo *glyph_info = NULL; /* computed text layout */ - size_t i, count; /* glyph_info index and length */ - int xx, yy; /* pixel offset of current glyph bitmap */ - int x0, x1; /* horizontal bounds of glyph bitmap to copy */ - unsigned int bitmap_y; /* glyph bitmap y index */ - unsigned char *source; /* glyph bitmap source buffer */ - unsigned char convert_scale; /* scale factor for non-8bpp bitmaps */ + GlyphInfo *glyph_info = NULL; /* computed text layout */ + size_t i, count; /* glyph_info index and length */ + int xx, yy; /* pixel offset of current glyph bitmap */ + int x0, x1; /* horizontal bounds of glyph bitmap to copy */ + unsigned int bitmap_y; /* glyph bitmap y index */ + unsigned char *source; /* glyph bitmap source buffer */ + unsigned char convert_scale; /* scale factor for non-8bpp bitmaps */ Imaging im; Py_ssize_t id; - int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */ + int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */ int color = 0; /* is FT_LOAD_COLOR enabled? */ int stroke_width = 0; PY_LONG_LONG foreground_ink_long = 0; @@ -886,13 +912,22 @@ font_render(FontObject* self, PyObject* args) const char *dir = NULL; const char *lang = NULL; PyObject *features = Py_None; - PyObject* string; + PyObject *string; /* render string into given buffer (the buffer *must* have the right size, or this will crash) */ - if (!PyArg_ParseTuple(args, "On|zzOziL:render", &string, &id, &mode, &dir, &features, &lang, - &stroke_width, &foreground_ink_long)) { + if (!PyArg_ParseTuple( + args, + "On|zzOziL:render", + &string, + &id, + &mode, + &dir, + &features, + &lang, + &stroke_width, + &foreground_ink_long)) { return NULL; } @@ -904,11 +939,12 @@ font_render(FontObject* self, PyObject* args) #ifdef FT_COLOR_H if (color) { FT_Color foreground_color; - FT_Byte* ink = (FT_Byte*)&foreground_ink; + FT_Byte *ink = (FT_Byte *)&foreground_ink; foreground_color.red = ink[0]; foreground_color.green = ink[1]; foreground_color.blue = ink[2]; - foreground_color.alpha = (FT_Byte) 255; /* ink alpha is handled in ImageDraw.text */ + foreground_color.alpha = + (FT_Byte)255; /* ink alpha is handled in ImageDraw.text */ FT_Palette_Set_Foreground_Color(self->face, foreground_color); } #endif @@ -927,10 +963,15 @@ font_render(FontObject* self, PyObject* args) return geterror(error); } - FT_Stroker_Set(stroker, (FT_Fixed)stroke_width*64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); + FT_Stroker_Set( + stroker, + (FT_Fixed)stroke_width * 64, + FT_STROKER_LINECAP_ROUND, + FT_STROKER_LINEJOIN_ROUND, + 0); } - im = (Imaging) id; + im = (Imaging)id; load_flags = FT_LOAD_DEFAULT; if (mask) { load_flags |= FT_LOAD_TARGET_MONO; @@ -950,7 +991,8 @@ font_render(FontObject* self, PyObject* args) px = PIXEL(x + glyph_info[i].x_offset); py = PIXEL(y + glyph_info[i].y_offset); - error = FT_Load_Glyph(self->face, glyph_info[i].index, load_flags | FT_LOAD_RENDER); + error = + FT_Load_Glyph(self->face, glyph_info[i].index, load_flags | FT_LOAD_RENDER); if (error) { return geterror(error); } @@ -1030,9 +1072,7 @@ font_render(FontObject* self, PyObject* args) case FT_PIXEL_MODE_GRAY2: case FT_PIXEL_MODE_GRAY4: if (!bitmap_converted_ready) { - -#if FREETYPE_MAJOR > 2 ||\ - (FREETYPE_MAJOR == 2 && FREETYPE_MINOR > 6) +#if FREETYPE_MAJOR > 2 || (FREETYPE_MAJOR == 2 && FREETYPE_MINOR > 6) FT_Bitmap_Init(&bitmap_converted); #else FT_Bitmap_New(&bitmap_converted); @@ -1070,18 +1110,18 @@ font_render(FontObject* self, PyObject* args) x1 = im->xsize - xx; } - source = (unsigned char*) bitmap.buffer; + source = (unsigned char *)bitmap.buffer; for (bitmap_y = 0; bitmap_y < bitmap.rows; bitmap_y++, yy++) { /* clip glyph bitmap height to target image bounds */ if (yy >= 0 && yy < im->ysize) { /* blend this glyph into the buffer */ int k; unsigned char v; - unsigned char* target; + unsigned char *target; if (color) { /* target[RGB] returns the color, target[A] returns the mask */ /* target bands get split again in ImageDraw.text */ - target = (unsigned char*)im->image[yy] + xx * 4; + target = (unsigned char *)im->image[yy] + xx * 4; } else { target = im->image8[yy] + xx; } @@ -1091,17 +1131,20 @@ font_render(FontObject* self, PyObject* args) for (k = x0; k < x1; k++) { if (target[k * 4 + 3] < source[k * 4 + 3]) { /* unpremultiply BGRa to RGBA */ - target[k * 4 + 0] = CLIP8((255 * (int)source[k * 4 + 2]) / source[k * 4 + 3]); - target[k * 4 + 1] = CLIP8((255 * (int)source[k * 4 + 1]) / source[k * 4 + 3]); - target[k * 4 + 2] = CLIP8((255 * (int)source[k * 4 + 0]) / source[k * 4 + 3]); + target[k * 4 + 0] = CLIP8( + (255 * (int)source[k * 4 + 2]) / source[k * 4 + 3]); + target[k * 4 + 1] = CLIP8( + (255 * (int)source[k * 4 + 1]) / source[k * 4 + 3]); + target[k * 4 + 2] = CLIP8( + (255 * (int)source[k * 4 + 0]) / source[k * 4 + 3]); target[k * 4 + 3] = source[k * 4 + 3]; } } } else #endif - if (bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) { + if (bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) { if (color) { - unsigned char* ink = (unsigned char*)&foreground_ink; + unsigned char *ink = (unsigned char *)&foreground_ink; for (k = x0; k < x1; k++) { v = source[k] * convert_scale; if (target[k * 4 + 3] < v) { @@ -1152,173 +1195,166 @@ glyph_error: return NULL; } -#if FREETYPE_MAJOR > 2 ||\ - (FREETYPE_MAJOR == 2 && FREETYPE_MINOR > 9) ||\ +#if FREETYPE_MAJOR > 2 || (FREETYPE_MAJOR == 2 && FREETYPE_MINOR > 9) || \ (FREETYPE_MAJOR == 2 && FREETYPE_MINOR == 9 && FREETYPE_PATCH == 1) - static PyObject* - font_getvarnames(FontObject* self) - { - int error; - FT_UInt i, j, num_namedstyles, name_count; - FT_MM_Var *master; - FT_SfntName name; - PyObject *list_names, *list_name; +static PyObject * +font_getvarnames(FontObject *self) { + int error; + FT_UInt i, j, num_namedstyles, name_count; + FT_MM_Var *master; + FT_SfntName name; + PyObject *list_names, *list_name; - error = FT_Get_MM_Var(self->face, &master); + error = FT_Get_MM_Var(self->face, &master); + if (error) { + return geterror(error); + } + + num_namedstyles = master->num_namedstyles; + list_names = PyList_New(num_namedstyles); + + name_count = FT_Get_Sfnt_Name_Count(self->face); + for (i = 0; i < name_count; i++) { + error = FT_Get_Sfnt_Name(self->face, i, &name); if (error) { return geterror(error); } - num_namedstyles = master->num_namedstyles; - list_names = PyList_New(num_namedstyles); + for (j = 0; j < num_namedstyles; j++) { + if (PyList_GetItem(list_names, j) != NULL) { + continue; + } - name_count = FT_Get_Sfnt_Name_Count(self->face); - for (i = 0; i < name_count; i++) { - error = FT_Get_Sfnt_Name(self->face, i, &name); + if (master->namedstyle[j].strid == name.name_id) { + list_name = Py_BuildValue("y#", name.string, name.string_len); + PyList_SetItem(list_names, j, list_name); + break; + } + } + } + + FT_Done_MM_Var(library, master); + + return list_names; +} + +static PyObject * +font_getvaraxes(FontObject *self) { + int error; + FT_UInt i, j, num_axis, name_count; + FT_MM_Var *master; + FT_Var_Axis axis; + FT_SfntName name; + PyObject *list_axes, *list_axis, *axis_name; + error = FT_Get_MM_Var(self->face, &master); + if (error) { + return geterror(error); + } + + num_axis = master->num_axis; + name_count = FT_Get_Sfnt_Name_Count(self->face); + + list_axes = PyList_New(num_axis); + for (i = 0; i < num_axis; i++) { + axis = master->axis[i]; + + list_axis = PyDict_New(); + PyDict_SetItemString( + list_axis, "minimum", PyLong_FromLong(axis.minimum / 65536)); + PyDict_SetItemString(list_axis, "default", PyLong_FromLong(axis.def / 65536)); + PyDict_SetItemString( + list_axis, "maximum", PyLong_FromLong(axis.maximum / 65536)); + + for (j = 0; j < name_count; j++) { + error = FT_Get_Sfnt_Name(self->face, j, &name); if (error) { return geterror(error); } - for (j = 0; j < num_namedstyles; j++) { - if (PyList_GetItem(list_names, j) != NULL) { - continue; - } - - if (master->namedstyle[j].strid == name.name_id) { - list_name = Py_BuildValue("y#", name.string, name.string_len); - PyList_SetItem(list_names, j, list_name); - break; - } + if (name.name_id == axis.strid) { + axis_name = Py_BuildValue("y#", name.string, name.string_len); + PyDict_SetItemString(list_axis, "name", axis_name); + break; } } - FT_Done_MM_Var(library, master); - - return list_names; + PyList_SetItem(list_axes, i, list_axis); } - static PyObject* - font_getvaraxes(FontObject* self) - { - int error; - FT_UInt i, j, num_axis, name_count; - FT_MM_Var* master; - FT_Var_Axis axis; - FT_SfntName name; - PyObject *list_axes, *list_axis, *axis_name; - error = FT_Get_MM_Var(self->face, &master); - if (error) { - return geterror(error); - } + FT_Done_MM_Var(library, master); - num_axis = master->num_axis; - name_count = FT_Get_Sfnt_Name_Count(self->face); + return list_axes; +} - list_axes = PyList_New(num_axis); - for (i = 0; i < num_axis; i++) { - axis = master->axis[i]; +static PyObject * +font_setvarname(FontObject *self, PyObject *args) { + int error; - list_axis = PyDict_New(); - PyDict_SetItemString(list_axis, "minimum", - PyLong_FromLong(axis.minimum / 65536)); - PyDict_SetItemString(list_axis, "default", - PyLong_FromLong(axis.def / 65536)); - PyDict_SetItemString(list_axis, "maximum", - PyLong_FromLong(axis.maximum / 65536)); - - for (j = 0; j < name_count; j++) { - error = FT_Get_Sfnt_Name(self->face, j, &name); - if (error) { - return geterror(error); - } - - if (name.name_id == axis.strid) { - axis_name = Py_BuildValue("y#", name.string, name.string_len); - PyDict_SetItemString(list_axis, "name", axis_name); - break; - } - } - - PyList_SetItem(list_axes, i, list_axis); - } - - FT_Done_MM_Var(library, master); - - return list_axes; + int instance_index; + if (!PyArg_ParseTuple(args, "i", &instance_index)) { + return NULL; } - static PyObject* - font_setvarname(FontObject* self, PyObject* args) - { - int error; + error = FT_Set_Named_Instance(self->face, instance_index); + if (error) { + return geterror(error); + } - int instance_index; - if (!PyArg_ParseTuple(args, "i", &instance_index)) { + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +font_setvaraxes(FontObject *self, PyObject *args) { + int error; + + PyObject *axes, *item; + Py_ssize_t i, num_coords; + FT_Fixed *coords; + FT_Fixed coord; + if (!PyArg_ParseTuple(args, "O", &axes)) { + return NULL; + } + + if (!PyList_Check(axes)) { + PyErr_SetString(PyExc_TypeError, "argument must be a list"); + return NULL; + } + + num_coords = PyObject_Length(axes); + coords = malloc(2 * sizeof(coords)); + if (coords == NULL) { + return PyErr_NoMemory(); + } + for (i = 0; i < num_coords; i++) { + item = PyList_GET_ITEM(axes, i); + if (PyFloat_Check(item)) { + coord = PyFloat_AS_DOUBLE(item); + } else if (PyLong_Check(item)) { + coord = (float)PyLong_AS_LONG(item); + } else if (PyNumber_Check(item)) { + coord = PyFloat_AsDouble(item); + } else { + free(coords); + PyErr_SetString(PyExc_TypeError, "list must contain numbers"); return NULL; } - - error = FT_Set_Named_Instance(self->face, instance_index); - if (error) { - return geterror(error); - } - - Py_INCREF(Py_None); - return Py_None; + coords[i] = coord * 65536; } - static PyObject* - font_setvaraxes(FontObject* self, PyObject* args) - { - int error; - - PyObject *axes, *item; - Py_ssize_t i, num_coords; - FT_Fixed *coords; - FT_Fixed coord; - if (!PyArg_ParseTuple(args, "O", &axes)) { - return NULL; - } - - if (!PyList_Check(axes)) { - PyErr_SetString(PyExc_TypeError, "argument must be a list"); - return NULL; - } - - num_coords = PyObject_Length(axes); - coords = malloc(2 * sizeof(coords)); - if (coords == NULL) { - return PyErr_NoMemory(); - } - for (i = 0; i < num_coords; i++) { - item = PyList_GET_ITEM(axes, i); - if (PyFloat_Check(item)) { - coord = PyFloat_AS_DOUBLE(item); - } else if (PyLong_Check(item)) { - coord = (float) PyLong_AS_LONG(item); - } else if (PyNumber_Check(item)) { - coord = PyFloat_AsDouble(item); - } else { - free(coords); - PyErr_SetString(PyExc_TypeError, "list must contain numbers"); - return NULL; - } - coords[i] = coord * 65536; - } - - error = FT_Set_Var_Design_Coordinates(self->face, num_coords, coords); - free(coords); - if (error) { - return geterror(error); - } - - Py_INCREF(Py_None); - return Py_None; + error = FT_Set_Var_Design_Coordinates(self->face, num_coords, coords); + free(coords); + if (error) { + return geterror(error); } + + Py_INCREF(Py_None); + return Py_None; +} #endif static void -font_dealloc(FontObject* self) -{ +font_dealloc(FontObject *self) { if (self->face) { FT_Done_Face(self->face); } @@ -1329,128 +1365,115 @@ font_dealloc(FontObject* self) } static PyMethodDef font_methods[] = { - {"render", (PyCFunction) font_render, METH_VARARGS}, - {"getsize", (PyCFunction) font_getsize, METH_VARARGS}, - {"getlength", (PyCFunction) font_getlength, METH_VARARGS}, -#if FREETYPE_MAJOR > 2 ||\ - (FREETYPE_MAJOR == 2 && FREETYPE_MINOR > 9) ||\ + {"render", (PyCFunction)font_render, METH_VARARGS}, + {"getsize", (PyCFunction)font_getsize, METH_VARARGS}, + {"getlength", (PyCFunction)font_getlength, METH_VARARGS}, +#if FREETYPE_MAJOR > 2 || (FREETYPE_MAJOR == 2 && FREETYPE_MINOR > 9) || \ (FREETYPE_MAJOR == 2 && FREETYPE_MINOR == 9 && FREETYPE_PATCH == 1) - {"getvarnames", (PyCFunction) font_getvarnames, METH_NOARGS }, - {"getvaraxes", (PyCFunction) font_getvaraxes, METH_NOARGS }, - {"setvarname", (PyCFunction) font_setvarname, METH_VARARGS}, - {"setvaraxes", (PyCFunction) font_setvaraxes, METH_VARARGS}, + {"getvarnames", (PyCFunction)font_getvarnames, METH_NOARGS}, + {"getvaraxes", (PyCFunction)font_getvaraxes, METH_NOARGS}, + {"setvarname", (PyCFunction)font_setvarname, METH_VARARGS}, + {"setvaraxes", (PyCFunction)font_setvaraxes, METH_VARARGS}, #endif - {NULL, NULL} -}; + {NULL, NULL}}; -static PyObject* -font_getattr_family(FontObject* self, void* closure) -{ +static PyObject * +font_getattr_family(FontObject *self, void *closure) { if (self->face->family_name) { return PyUnicode_FromString(self->face->family_name); } Py_RETURN_NONE; } -static PyObject* -font_getattr_style(FontObject* self, void* closure) -{ +static PyObject * +font_getattr_style(FontObject *self, void *closure) { if (self->face->style_name) { return PyUnicode_FromString(self->face->style_name); } Py_RETURN_NONE; } -static PyObject* -font_getattr_ascent(FontObject* self, void* closure) -{ +static PyObject * +font_getattr_ascent(FontObject *self, void *closure) { return PyLong_FromLong(PIXEL(self->face->size->metrics.ascender)); } -static PyObject* -font_getattr_descent(FontObject* self, void* closure) -{ +static PyObject * +font_getattr_descent(FontObject *self, void *closure) { return PyLong_FromLong(-PIXEL(self->face->size->metrics.descender)); } -static PyObject* -font_getattr_height(FontObject* self, void* closure) -{ +static PyObject * +font_getattr_height(FontObject *self, void *closure) { return PyLong_FromLong(PIXEL(self->face->size->metrics.height)); } -static PyObject* -font_getattr_x_ppem(FontObject* self, void* closure) -{ +static PyObject * +font_getattr_x_ppem(FontObject *self, void *closure) { return PyLong_FromLong(self->face->size->metrics.x_ppem); } -static PyObject* -font_getattr_y_ppem(FontObject* self, void* closure) -{ +static PyObject * +font_getattr_y_ppem(FontObject *self, void *closure) { return PyLong_FromLong(self->face->size->metrics.y_ppem); } - -static PyObject* -font_getattr_glyphs(FontObject* self, void* closure) -{ +static PyObject * +font_getattr_glyphs(FontObject *self, void *closure) { return PyLong_FromLong(self->face->num_glyphs); } static struct PyGetSetDef font_getsetters[] = { - { "family", (getter) font_getattr_family }, - { "style", (getter) font_getattr_style }, - { "ascent", (getter) font_getattr_ascent }, - { "descent", (getter) font_getattr_descent }, - { "height", (getter) font_getattr_height }, - { "x_ppem", (getter) font_getattr_x_ppem }, - { "y_ppem", (getter) font_getattr_y_ppem }, - { "glyphs", (getter) font_getattr_glyphs }, - { NULL } -}; + {"family", (getter)font_getattr_family}, + {"style", (getter)font_getattr_style}, + {"ascent", (getter)font_getattr_ascent}, + {"descent", (getter)font_getattr_descent}, + {"height", (getter)font_getattr_height}, + {"x_ppem", (getter)font_getattr_x_ppem}, + {"y_ppem", (getter)font_getattr_y_ppem}, + {"glyphs", (getter)font_getattr_glyphs}, + {NULL}}; static PyTypeObject Font_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "Font", sizeof(FontObject), 0, + PyVarObject_HEAD_INIT(NULL, 0) "Font", + sizeof(FontObject), + 0, /* methods */ (destructor)font_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - font_methods, /*tp_methods*/ - 0, /*tp_members*/ - font_getsetters, /*tp_getset*/ + 0, /* tp_print */ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + font_methods, /*tp_methods*/ + 0, /*tp_members*/ + font_getsetters, /*tp_getset*/ }; static PyMethodDef _functions[] = { - {"getfont", (PyCFunction) getfont, METH_VARARGS|METH_KEYWORDS}, - {NULL, NULL} -}; + {"getfont", (PyCFunction)getfont, METH_VARARGS | METH_KEYWORDS}, {NULL, NULL}}; static int -setup_module(PyObject* m) { - PyObject* d; - PyObject* v; +setup_module(PyObject *m) { + PyObject *d; + PyObject *v; int major, minor, patch; d = PyModule_GetDict(m); @@ -1467,12 +1490,12 @@ setup_module(PyObject* m) { v = PyUnicode_FromFormat("%d.%d.%d", major, minor, patch); PyDict_SetItemString(d, "freetype2_version", v); - setraqm(); v = PyBool_FromLong(!!p_raqm.raqm); PyDict_SetItemString(d, "HAVE_RAQM", v); if (p_raqm.version_string) { - PyDict_SetItemString(d, "raqm_version", PyUnicode_FromString(p_raqm.version_string())); + PyDict_SetItemString( + d, "raqm_version", PyUnicode_FromString(p_raqm.version_string())); } return 0; @@ -1480,14 +1503,14 @@ setup_module(PyObject* m) { PyMODINIT_FUNC PyInit__imagingft(void) { - PyObject* m; + PyObject *m; static PyModuleDef module_def = { PyModuleDef_HEAD_INIT, - "_imagingft", /* m_name */ - NULL, /* m_doc */ - -1, /* m_size */ - _functions, /* m_methods */ + "_imagingft", /* m_name */ + NULL, /* m_doc */ + -1, /* m_size */ + _functions, /* m_methods */ }; m = PyModule_Create(&module_def); diff --git a/src/_imagingmath.c b/src/_imagingmath.c index b99356d14..067c165b2 100644 --- a/src/_imagingmath.c +++ b/src/_imagingmath.c @@ -23,50 +23,51 @@ #define MAX_INT32 2147483647.0 #define MIN_INT32 -2147483648.0 -#define UNOP(name, op, type)\ -void name(Imaging out, Imaging im1)\ -{\ - int x, y;\ - for (y = 0; y < out->ysize; y++) {\ - type* p0 = (type*) out->image[y];\ - type* p1 = (type*) im1->image[y];\ - for (x = 0; x < out->xsize; x++) {\ - *p0 = op(type, *p1);\ - p0++; p1++;\ - }\ - }\ -} +#define UNOP(name, op, type) \ + void name(Imaging out, Imaging im1) { \ + int x, y; \ + for (y = 0; y < out->ysize; y++) { \ + type *p0 = (type *)out->image[y]; \ + type *p1 = (type *)im1->image[y]; \ + for (x = 0; x < out->xsize; x++) { \ + *p0 = op(type, *p1); \ + p0++; \ + p1++; \ + } \ + } \ + } -#define BINOP(name, op, type)\ -void name(Imaging out, Imaging im1, Imaging im2)\ -{\ - int x, y;\ - for (y = 0; y < out->ysize; y++) {\ - type* p0 = (type*) out->image[y];\ - type* p1 = (type*) im1->image[y];\ - type* p2 = (type*) im2->image[y];\ - for (x = 0; x < out->xsize; x++) {\ - *p0 = op(type, *p1, *p2);\ - p0++; p1++; p2++;\ - }\ - }\ -} +#define BINOP(name, op, type) \ + void name(Imaging out, Imaging im1, Imaging im2) { \ + int x, y; \ + for (y = 0; y < out->ysize; y++) { \ + type *p0 = (type *)out->image[y]; \ + type *p1 = (type *)im1->image[y]; \ + type *p2 = (type *)im2->image[y]; \ + for (x = 0; x < out->xsize; x++) { \ + *p0 = op(type, *p1, *p2); \ + p0++; \ + p1++; \ + p2++; \ + } \ + } \ + } #define NEG(type, v1) -(v1) #define INVERT(type, v1) ~(v1) -#define ADD(type, v1, v2) (v1)+(v2) -#define SUB(type, v1, v2) (v1)-(v2) -#define MUL(type, v1, v2) (v1)*(v2) +#define ADD(type, v1, v2) (v1) + (v2) +#define SUB(type, v1, v2) (v1) - (v2) +#define MUL(type, v1, v2) (v1) * (v2) -#define MIN(type, v1, v2) ((v1)<(v2))?(v1):(v2) -#define MAX(type, v1, v2) ((v1)>(v2))?(v1):(v2) +#define MIN(type, v1, v2) ((v1) < (v2)) ? (v1) : (v2) +#define MAX(type, v1, v2) ((v1) > (v2)) ? (v1) : (v2) -#define AND(type, v1, v2) (v1)&(v2) -#define OR(type, v1, v2) (v1)|(v2) -#define XOR(type, v1, v2) (v1)^(v2) -#define LSHIFT(type, v1, v2) (v1)<<(v2) -#define RSHIFT(type, v1, v2) (v1)>>(v2) +#define AND(type, v1, v2) (v1) & (v2) +#define OR(type, v1, v2) (v1) | (v2) +#define XOR(type, v1, v2) (v1) ^ (v2) +#define LSHIFT(type, v1, v2) (v1) << (v2) +#define RSHIFT(type, v1, v2) (v1) >> (v2) #define ABS_I(type, v1) abs((v1)) #define ABS_F(type, v1) fabs((v1)) @@ -79,14 +80,14 @@ void name(Imaging out, Imaging im1, Imaging im2)\ * PyFPE_END_PROTECT(result) */ -#define DIV_I(type, v1, v2) ((v2)!=0)?(v1)/(v2):0 -#define DIV_F(type, v1, v2) ((v2)!=0.0F)?(v1)/(v2):0.0F +#define DIV_I(type, v1, v2) ((v2) != 0) ? (v1) / (v2) : 0 +#define DIV_F(type, v1, v2) ((v2) != 0.0F) ? (v1) / (v2) : 0.0F -#define MOD_I(type, v1, v2) ((v2)!=0)?(v1)%(v2):0 -#define MOD_F(type, v1, v2) ((v2)!=0.0F)?fmod((v1),(v2)):0.0F +#define MOD_I(type, v1, v2) ((v2) != 0) ? (v1) % (v2) : 0 +#define MOD_F(type, v1, v2) ((v2) != 0.0F) ? fmod((v1), (v2)) : 0.0F -static int powi(int x, int y) -{ +static int +powi(int x, int y) { double v = pow(x, y) + 0.5; if (errno == EDOM) { return 0; @@ -96,21 +97,21 @@ static int powi(int x, int y) } else if (v > MAX_INT32) { v = MAX_INT32; } - return (int) v; + return (int)v; } #define POW_I(type, v1, v2) powi(v1, v2) #define POW_F(type, v1, v2) powf(v1, v2) /* FIXME: EDOM handling */ -#define DIFF_I(type, v1, v2) abs((v1)-(v2)) -#define DIFF_F(type, v1, v2) fabs((v1)-(v2)) +#define DIFF_I(type, v1, v2) abs((v1) - (v2)) +#define DIFF_F(type, v1, v2) fabs((v1) - (v2)) -#define EQ(type, v1, v2) (v1)==(v2) -#define NE(type, v1, v2) (v1)!=(v2) -#define LT(type, v1, v2) (v1)<(v2) -#define LE(type, v1, v2) (v1)<=(v2) -#define GT(type, v1, v2) (v1)>(v2) -#define GE(type, v1, v2) (v1)>=(v2) +#define EQ(type, v1, v2) (v1) == (v2) +#define NE(type, v1, v2) (v1) != (v2) +#define LT(type, v1, v2) (v1) < (v2) +#define LE(type, v1, v2) (v1) <= (v2) +#define GT(type, v1, v2) (v1) > (v2) +#define GE(type, v1, v2) (v1) >= (v2) UNOP(abs_I, ABS_I, INT32) UNOP(neg_I, NEG, INT32) @@ -162,8 +163,7 @@ BINOP(gt_F, GT, FLOAT32) BINOP(ge_F, GE, FLOAT32) static PyObject * -_unop(PyObject* self, PyObject* args) -{ +_unop(PyObject *self, PyObject *args) { Imaging out; Imaging im1; void (*unop)(Imaging, Imaging); @@ -173,10 +173,10 @@ _unop(PyObject* self, PyObject* args) return NULL; } - out = (Imaging) i0; - im1 = (Imaging) i1; + out = (Imaging)i0; + im1 = (Imaging)i1; - unop = (void*) op; + unop = (void *)op; unop(out, im1); @@ -185,8 +185,7 @@ _unop(PyObject* self, PyObject* args) } static PyObject * -_binop(PyObject* self, PyObject* args) -{ +_binop(PyObject *self, PyObject *args) { Imaging out; Imaging im1; Imaging im2; @@ -197,11 +196,11 @@ _binop(PyObject* self, PyObject* args) return NULL; } - out = (Imaging) i0; - im1 = (Imaging) i1; - im2 = (Imaging) i2; + out = (Imaging)i0; + im1 = (Imaging)i1; + im2 = (Imaging)i2; - binop = (void*) op; + binop = (void *)op; binop(out, im1, im2); @@ -210,15 +209,11 @@ _binop(PyObject* self, PyObject* args) } static PyMethodDef _functions[] = { - {"unop", _unop, 1}, - {"binop", _binop, 1}, - {NULL, NULL} -}; + {"unop", _unop, 1}, {"binop", _binop, 1}, {NULL, NULL}}; static void -install(PyObject *d, char* name, void* value) -{ - PyObject *v = PyLong_FromSsize_t((Py_ssize_t) value); +install(PyObject *d, char *name, void *value) { + PyObject *v = PyLong_FromSsize_t((Py_ssize_t)value); if (!v || PyDict_SetItemString(d, name, v)) { PyErr_Clear(); } @@ -226,8 +221,8 @@ install(PyObject *d, char* name, void* value) } static int -setup_module(PyObject* m) { - PyObject* d = PyModule_GetDict(m); +setup_module(PyObject *m) { + PyObject *d = PyModule_GetDict(m); install(d, "abs_I", abs_I); install(d, "neg_I", neg_I); @@ -279,14 +274,14 @@ setup_module(PyObject* m) { PyMODINIT_FUNC PyInit__imagingmath(void) { - PyObject* m; + PyObject *m; static PyModuleDef module_def = { PyModuleDef_HEAD_INIT, - "_imagingmath", /* m_name */ - NULL, /* m_doc */ - -1, /* m_size */ - _functions, /* m_methods */ + "_imagingmath", /* m_name */ + NULL, /* m_doc */ + -1, /* m_size */ + _functions, /* m_methods */ }; m = PyModule_Create(&module_def); diff --git a/src/_imagingmorph.c b/src/_imagingmorph.c index 0fe54ab77..c0644b616 100644 --- a/src/_imagingmorph.c +++ b/src/_imagingmorph.c @@ -14,7 +14,7 @@ #include "Python.h" #include "libImaging/Imaging.h" -#define LUT_SIZE (1<<9) +#define LUT_SIZE (1 << 9) /* Apply a morphologic LUT to a binary image. Outputs a a new binary image. @@ -27,9 +27,8 @@ Returns number of changed pixels. */ -static PyObject* -apply(PyObject *self, PyObject* args) -{ +static PyObject * +apply(PyObject *self, PyObject *args) { const char *lut; PyObject *py_lut; Py_ssize_t lut_len, i0, i1; @@ -58,18 +57,16 @@ apply(PyObject *self, PyObject* args) lut = PyBytes_AsString(py_lut); - imgin = (Imaging) i0; - imgout = (Imaging) i1; + imgin = (Imaging)i0; + imgout = (Imaging)i1; width = imgin->xsize; height = imgin->ysize; - if (imgin->type != IMAGING_TYPE_UINT8 || - imgin->bands != 1) { + if (imgin->type != IMAGING_TYPE_UINT8 || imgin->bands != 1) { PyErr_SetString(PyExc_RuntimeError, "Unsupported image type"); return NULL; } - if (imgout->type != IMAGING_TYPE_UINT8 || - imgout->bands != 1) { + if (imgout->type != IMAGING_TYPE_UINT8 || imgout->bands != 1) { PyErr_SetString(PyExc_RuntimeError, "Unsupported image type"); return NULL; } @@ -77,52 +74,46 @@ apply(PyObject *self, PyObject* args) inrows = imgin->image8; outrows = imgout->image8; - for (row_idx=0; row_idx < height; row_idx++) { + for (row_idx = 0; row_idx < height; row_idx++) { UINT8 *outrow = outrows[row_idx]; UINT8 *inrow = inrows[row_idx]; UINT8 *prow, *nrow; /* Previous and next row */ /* zero boundary conditions. TBD support other modes */ - outrow[0] = outrow[width-1] = 0; - if (row_idx==0 || row_idx == height-1) { - for(col_idx=0; col_idxtype != IMAGING_TYPE_UINT8 || - imgin->bands != 1) { + if (imgin->type != IMAGING_TYPE_UINT8 || imgin->bands != 1) { PyErr_SetString(PyExc_RuntimeError, "Unsupported image type"); return NULL; } @@ -177,39 +166,33 @@ match(PyObject *self, PyObject* args) width = imgin->xsize; height = imgin->ysize; - for (row_idx=1; row_idx < height-1; row_idx++) { + for (row_idx = 1; row_idx < height - 1; row_idx++) { UINT8 *inrow = inrows[row_idx]; UINT8 *prow, *nrow; - prow = inrows[row_idx-1]; - nrow = inrows[row_idx+1]; + prow = inrows[row_idx - 1]; + nrow = inrows[row_idx + 1]; - for (col_idx=1; col_idximage8; width = img->xsize; height = img->ysize; - for (row_idx=0; row_idx < height; row_idx++) { + for (row_idx = 0; row_idx < height; row_idx++) { UINT8 *row = rows[row_idx]; - for (col_idx=0; col_idxinterp; } @@ -69,10 +68,10 @@ PyMODINIT_FUNC PyInit__imagingtk(void) { static PyModuleDef module_def = { PyModuleDef_HEAD_INIT, - "_imagingtk", /* m_name */ - NULL, /* m_doc */ - -1, /* m_size */ - functions, /* m_methods */ + "_imagingtk", /* m_name */ + NULL, /* m_doc */ + -1, /* m_size */ + functions, /* m_methods */ }; PyObject *m; m = PyModule_Create(&module_def); diff --git a/src/_webp.c b/src/_webp.c index 6c6ca2aa6..c7875fa36 100644 --- a/src/_webp.c +++ b/src/_webp.c @@ -21,12 +21,14 @@ #endif -void ImagingSectionEnter(ImagingSectionCookie* cookie) { - *cookie = (PyThreadState *) PyEval_SaveThread(); +void +ImagingSectionEnter(ImagingSectionCookie *cookie) { + *cookie = (PyThreadState *)PyEval_SaveThread(); } -void ImagingSectionLeave(ImagingSectionCookie* cookie) { - PyEval_RestoreThread((PyThreadState*) *cookie); +void +ImagingSectionLeave(ImagingSectionCookie *cookie) { + PyEval_RestoreThread((PyThreadState *)*cookie); } /* -------------------------------------------------------------------- */ @@ -35,12 +37,15 @@ void ImagingSectionLeave(ImagingSectionCookie* cookie) { #ifdef HAVE_WEBPMUX -static const char* const kErrorMessages[-WEBP_MUX_NOT_ENOUGH_DATA + 1] = { - "WEBP_MUX_NOT_FOUND", "WEBP_MUX_INVALID_ARGUMENT", "WEBP_MUX_BAD_DATA", - "WEBP_MUX_MEMORY_ERROR", "WEBP_MUX_NOT_ENOUGH_DATA" -}; +static const char *const kErrorMessages[-WEBP_MUX_NOT_ENOUGH_DATA + 1] = { + "WEBP_MUX_NOT_FOUND", + "WEBP_MUX_INVALID_ARGUMENT", + "WEBP_MUX_BAD_DATA", + "WEBP_MUX_MEMORY_ERROR", + "WEBP_MUX_NOT_ENOUGH_DATA"}; -PyObject* HandleMuxError(WebPMuxError err, char* chunk) { +PyObject * +HandleMuxError(WebPMuxError err, char *chunk) { char message[100]; int message_len; assert(err <= WEBP_MUX_NOT_FOUND && err >= WEBP_MUX_NOT_ENOUGH_DATA); @@ -52,9 +57,11 @@ PyObject* HandleMuxError(WebPMuxError err, char* chunk) { // Create the error message if (chunk == NULL) { - message_len = sprintf(message, "could not assemble chunks: %s", kErrorMessages[-err]); + message_len = + sprintf(message, "could not assemble chunks: %s", kErrorMessages[-err]); } else { - message_len = sprintf(message, "could not set %.4s chunk: %s", chunk, kErrorMessages[-err]); + message_len = sprintf( + message, "could not set %.4s chunk: %s", chunk, kErrorMessages[-err]); } if (message_len < 0) { PyErr_SetString(PyExc_RuntimeError, "failed to construct error message"); @@ -90,8 +97,7 @@ PyObject* HandleMuxError(WebPMuxError err, char* chunk) { // Encoder type typedef struct { - PyObject_HEAD - WebPAnimEncoder* enc; + PyObject_HEAD WebPAnimEncoder *enc; WebPPicture frame; } WebPAnimEncoderObject; @@ -99,18 +105,17 @@ static PyTypeObject WebPAnimEncoder_Type; // Decoder type typedef struct { - PyObject_HEAD - WebPAnimDecoder* dec; + PyObject_HEAD WebPAnimDecoder *dec; WebPAnimInfo info; WebPData data; - char* mode; + char *mode; } WebPAnimDecoderObject; static PyTypeObject WebPAnimDecoder_Type; // Encoder functions -PyObject* _anim_encoder_new(PyObject* self, PyObject* args) -{ +PyObject * +_anim_encoder_new(PyObject *self, PyObject *args) { int width, height; uint32_t bgcolor; int loop_count; @@ -119,12 +124,21 @@ PyObject* _anim_encoder_new(PyObject* self, PyObject* args) int allow_mixed; int verbose; WebPAnimEncoderOptions enc_options; - WebPAnimEncoderObject* encp = NULL; - WebPAnimEncoder* enc = NULL; + WebPAnimEncoderObject *encp = NULL; + WebPAnimEncoder *enc = NULL; - if (!PyArg_ParseTuple(args, "iiIiiiiii", - &width, &height, &bgcolor, &loop_count, &minimize_size, - &kmin, &kmax, &allow_mixed, &verbose)) { + if (!PyArg_ParseTuple( + args, + "iiIiiiiii", + &width, + &height, + &bgcolor, + &loop_count, + &minimize_size, + &kmin, + &kmax, + &allow_mixed, + &verbose)) { return NULL; } @@ -154,7 +168,7 @@ PyObject* _anim_encoder_new(PyObject* self, PyObject* args) enc = WebPAnimEncoderNew(width, height, &enc_options); if (enc) { encp->enc = enc; - return (PyObject*) encp; + return (PyObject *)encp; } WebPPictureFree(&(encp->frame)); } @@ -164,33 +178,42 @@ PyObject* _anim_encoder_new(PyObject* self, PyObject* args) return NULL; } -PyObject* _anim_encoder_dealloc(PyObject* self) -{ - WebPAnimEncoderObject* encp = (WebPAnimEncoderObject*)self; +PyObject * +_anim_encoder_dealloc(PyObject *self) { + WebPAnimEncoderObject *encp = (WebPAnimEncoderObject *)self; WebPPictureFree(&(encp->frame)); WebPAnimEncoderDelete(encp->enc); Py_RETURN_NONE; } -PyObject* _anim_encoder_add(PyObject* self, PyObject* args) -{ - uint8_t* rgb; +PyObject * +_anim_encoder_add(PyObject *self, PyObject *args) { + uint8_t *rgb; Py_ssize_t size; int timestamp; int width; int height; - char* mode; + char *mode; int lossless; float quality_factor; int method; WebPConfig config; - WebPAnimEncoderObject* encp = (WebPAnimEncoderObject*)self; - WebPAnimEncoder* enc = encp->enc; - WebPPicture* frame = &(encp->frame); + WebPAnimEncoderObject *encp = (WebPAnimEncoderObject *)self; + WebPAnimEncoder *enc = encp->enc; + WebPPicture *frame = &(encp->frame); - if (!PyArg_ParseTuple(args, "z#iiisifi", - (char**)&rgb, &size, ×tamp, &width, &height, &mode, - &lossless, &quality_factor, &method)) { + if (!PyArg_ParseTuple( + args, + "z#iiisifi", + (char **)&rgb, + &size, + ×tamp, + &width, + &height, + &mode, + &lossless, + &quality_factor, + &method)) { return NULL; } @@ -218,10 +241,10 @@ PyObject* _anim_encoder_add(PyObject* self, PyObject* args) // Populate the frame with raw bytes passed to us frame->width = width; frame->height = height; - frame->use_argb = 1; // Don't convert RGB pixels to YUV - if (strcmp(mode, "RGBA")==0) { + frame->use_argb = 1; // Don't convert RGB pixels to YUV + if (strcmp(mode, "RGBA") == 0) { WebPPictureImportRGBA(frame, rgb, 4 * width); - } else if (strcmp(mode, "RGBX")==0) { + } else if (strcmp(mode, "RGBX") == 0) { WebPPictureImportRGBX(frame, rgb, 4 * width); } else { WebPPictureImportRGB(frame, rgb, 3 * width); @@ -236,22 +259,29 @@ PyObject* _anim_encoder_add(PyObject* self, PyObject* args) Py_RETURN_NONE; } -PyObject* _anim_encoder_assemble(PyObject* self, PyObject* args) -{ - uint8_t* icc_bytes; - uint8_t* exif_bytes; - uint8_t* xmp_bytes; +PyObject * +_anim_encoder_assemble(PyObject *self, PyObject *args) { + uint8_t *icc_bytes; + uint8_t *exif_bytes; + uint8_t *xmp_bytes; Py_ssize_t icc_size; Py_ssize_t exif_size; Py_ssize_t xmp_size; WebPData webp_data; - WebPAnimEncoderObject* encp = (WebPAnimEncoderObject*)self; - WebPAnimEncoder* enc = encp->enc; - WebPMux* mux = NULL; - PyObject* ret = NULL; + WebPAnimEncoderObject *encp = (WebPAnimEncoderObject *)self; + WebPAnimEncoder *enc = encp->enc; + WebPMux *mux = NULL; + PyObject *ret = NULL; - if (!PyArg_ParseTuple(args, "s#s#s#", - &icc_bytes, &icc_size, &exif_bytes, &exif_size, &xmp_bytes, &xmp_size)) { + if (!PyArg_ParseTuple( + args, + "s#s#s#", + &icc_bytes, + &icc_size, + &exif_bytes, + &exif_size, + &xmp_bytes, + &xmp_size)) { return NULL; } @@ -270,9 +300,9 @@ PyObject* _anim_encoder_assemble(PyObject* self, PyObject* args) int i_icc_size = (int)icc_size; int i_exif_size = (int)exif_size; int i_xmp_size = (int)xmp_size; - WebPData icc_profile = { icc_bytes, i_icc_size }; - WebPData exif = { exif_bytes, i_exif_size }; - WebPData xmp = { xmp_bytes, i_xmp_size }; + WebPData icc_profile = {icc_bytes, i_icc_size}; + WebPData exif = {exif_bytes, i_exif_size}; + WebPData xmp = {xmp_bytes, i_xmp_size}; mux = WebPMuxCreate(&webp_data, 1); if (mux == NULL) { @@ -312,7 +342,7 @@ PyObject* _anim_encoder_assemble(PyObject* self, PyObject* args) } // Convert to Python bytes - ret = PyBytes_FromStringAndSize((char*)webp_data.bytes, webp_data.size); + ret = PyBytes_FromStringAndSize((char *)webp_data.bytes, webp_data.size); WebPDataClear(&webp_data); // If we had to re-mux, we should free it now that we're done with it @@ -324,21 +354,21 @@ PyObject* _anim_encoder_assemble(PyObject* self, PyObject* args) } // Decoder functions -PyObject* _anim_decoder_new(PyObject* self, PyObject* args) -{ +PyObject * +_anim_decoder_new(PyObject *self, PyObject *args) { PyBytesObject *webp_string; const uint8_t *webp; Py_ssize_t size; WebPData webp_src; - char* mode; + char *mode; WebPDecoderConfig config; - WebPAnimDecoderObject* decp = NULL; - WebPAnimDecoder* dec = NULL; + WebPAnimDecoderObject *decp = NULL; + WebPAnimDecoder *dec = NULL; if (!PyArg_ParseTuple(args, "S", &webp_string)) { return NULL; } - PyBytes_AsStringAndSize((PyObject *)webp_string, (char**)&webp, &size); + PyBytes_AsStringAndSize((PyObject *)webp_string, (char **)&webp, &size); webp_src.bytes = webp; webp_src.size = size; @@ -359,7 +389,7 @@ PyObject* _anim_decoder_new(PyObject* self, PyObject* args) if (dec) { if (WebPAnimDecoderGetInfo(dec, &(decp->info))) { decp->dec = dec; - return (PyObject*)decp; + return (PyObject *)decp; } } } @@ -369,33 +399,34 @@ PyObject* _anim_decoder_new(PyObject* self, PyObject* args) return NULL; } -PyObject* _anim_decoder_dealloc(PyObject* self) -{ - WebPAnimDecoderObject* decp = (WebPAnimDecoderObject *)self; +PyObject * +_anim_decoder_dealloc(PyObject *self) { + WebPAnimDecoderObject *decp = (WebPAnimDecoderObject *)self; WebPDataClear(&(decp->data)); WebPAnimDecoderDelete(decp->dec); Py_RETURN_NONE; } -PyObject* _anim_decoder_get_info(PyObject* self) -{ - WebPAnimDecoderObject* decp = (WebPAnimDecoderObject *)self; - WebPAnimInfo* info = &(decp->info); +PyObject * +_anim_decoder_get_info(PyObject *self) { + WebPAnimDecoderObject *decp = (WebPAnimDecoderObject *)self; + WebPAnimInfo *info = &(decp->info); - return Py_BuildValue("IIIIIs", - info->canvas_width, info->canvas_height, + return Py_BuildValue( + "IIIIIs", + info->canvas_width, + info->canvas_height, info->loop_count, info->bgcolor, info->frame_count, - decp->mode - ); + decp->mode); } -PyObject* _anim_decoder_get_chunk(PyObject* self, PyObject* args) -{ - char* mode; - WebPAnimDecoderObject* decp = (WebPAnimDecoderObject *)self; - const WebPDemuxer* demux; +PyObject * +_anim_decoder_get_chunk(PyObject *self, PyObject *args) { + char *mode; + WebPAnimDecoderObject *decp = (WebPAnimDecoderObject *)self; + const WebPDemuxer *demux; WebPChunkIterator iter; PyObject *ret; @@ -408,27 +439,27 @@ PyObject* _anim_decoder_get_chunk(PyObject* self, PyObject* args) Py_RETURN_NONE; } - ret = PyBytes_FromStringAndSize((const char*)iter.chunk.bytes, iter.chunk.size); + ret = PyBytes_FromStringAndSize((const char *)iter.chunk.bytes, iter.chunk.size); WebPDemuxReleaseChunkIterator(&iter); return ret; } -PyObject* _anim_decoder_get_next(PyObject* self) -{ - uint8_t* buf; +PyObject * +_anim_decoder_get_next(PyObject *self) { + uint8_t *buf; int timestamp; - PyObject* bytes; - PyObject* ret; - WebPAnimDecoderObject* decp = (WebPAnimDecoderObject*)self; + PyObject *bytes; + PyObject *ret; + WebPAnimDecoderObject *decp = (WebPAnimDecoderObject *)self; if (!WebPAnimDecoderGetNext(decp->dec, &buf, ×tamp)) { PyErr_SetString(PyExc_OSError, "failed to read next frame"); return NULL; } - bytes = PyBytes_FromStringAndSize((char *)buf, - decp->info.canvas_width * 4 * decp->info.canvas_height); + bytes = PyBytes_FromStringAndSize( + (char *)buf, decp->info.canvas_width * 4 * decp->info.canvas_height); ret = Py_BuildValue("Si", bytes, timestamp); @@ -436,9 +467,9 @@ PyObject* _anim_decoder_get_next(PyObject* self) return ret; } -PyObject* _anim_decoder_reset(PyObject* self) -{ - WebPAnimDecoderObject* decp = (WebPAnimDecoderObject *)self; +PyObject * +_anim_decoder_reset(PyObject *self) { + WebPAnimDecoderObject *decp = (WebPAnimDecoderObject *)self; WebPAnimDecoderReset(decp->dec); Py_RETURN_NONE; } @@ -456,37 +487,36 @@ static struct PyMethodDef _anim_encoder_methods[] = { // WebPAnimDecoder type definition static PyTypeObject WebPAnimEncoder_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "WebPAnimEncoder", /*tp_name */ - sizeof(WebPAnimEncoderObject), /*tp_size */ - 0, /*tp_itemsize */ + PyVarObject_HEAD_INIT(NULL, 0) "WebPAnimEncoder", /*tp_name */ + sizeof(WebPAnimEncoderObject), /*tp_size */ + 0, /*tp_itemsize */ /* methods */ (destructor)_anim_encoder_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - _anim_encoder_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + _anim_encoder_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ }; // WebPAnimDecoder methods @@ -500,37 +530,36 @@ static struct PyMethodDef _anim_decoder_methods[] = { // WebPAnimDecoder type definition static PyTypeObject WebPAnimDecoder_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "WebPAnimDecoder", /*tp_name */ - sizeof(WebPAnimDecoderObject), /*tp_size */ - 0, /*tp_itemsize */ + PyVarObject_HEAD_INIT(NULL, 0) "WebPAnimDecoder", /*tp_name */ + sizeof(WebPAnimDecoderObject), /*tp_size */ + 0, /*tp_itemsize */ /* methods */ (destructor)_anim_decoder_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - _anim_decoder_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + _anim_decoder_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ }; #endif @@ -539,19 +568,19 @@ static PyTypeObject WebPAnimDecoder_Type = { /* Legacy WebP Support */ /* -------------------------------------------------------------------- */ -PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args) -{ +PyObject * +WebPEncode_wrapper(PyObject *self, PyObject *args) { int width; int height; int lossless; float quality_factor; int method; - uint8_t* rgb; - uint8_t* icc_bytes; - uint8_t* exif_bytes; - uint8_t* xmp_bytes; - uint8_t* output; - char* mode; + uint8_t *rgb; + uint8_t *icc_bytes; + uint8_t *exif_bytes; + uint8_t *xmp_bytes; + uint8_t *output; + char *mode; Py_ssize_t size; Py_ssize_t icc_size; Py_ssize_t exif_size; @@ -565,9 +594,23 @@ PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args) WebPMemoryWriter writer; WebPPicture pic; - if (!PyArg_ParseTuple(args, "y#iiifss#is#s#", - (char**)&rgb, &size, &width, &height, &lossless, &quality_factor, &mode, - &icc_bytes, &icc_size, &method, &exif_bytes, &exif_size, &xmp_bytes, &xmp_size)) { + if (!PyArg_ParseTuple( + args, + "y#iiifss#is#s#", + (char **)&rgb, + &size, + &width, + &height, + &lossless, + &quality_factor, + &mode, + &icc_bytes, + &icc_size, + &method, + &exif_bytes, + &exif_size, + &xmp_bytes, + &xmp_size)) { return NULL; } @@ -602,7 +645,7 @@ PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args) } pic.width = width; pic.height = height; - pic.use_argb = 1; // Don't convert RGB pixels to YUV + pic.use_argb = 1; // Don't convert RGB pixels to YUV if (rgba_mode) { WebPPictureImportRGBA(&pic, rgb, channels * width); @@ -628,98 +671,100 @@ PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args) #ifndef HAVE_WEBPMUX if (ret_size > 0) { - PyObject *ret = PyBytes_FromStringAndSize((char*)output, ret_size); + PyObject *ret = PyBytes_FromStringAndSize((char *)output, ret_size); free(output); return ret; } #else { - /* I want to truncate the *_size items that get passed into WebP - data. Pypy2.1.0 had some issues where the Py_ssize_t items had - data in the upper byte. (Not sure why, it shouldn't have been there) - */ - int i_icc_size = (int)icc_size; - int i_exif_size = (int)exif_size; - int i_xmp_size = (int)xmp_size; - WebPData output_data = {0}; - WebPData image = { output, ret_size }; - WebPData icc_profile = { icc_bytes, i_icc_size }; - WebPData exif = { exif_bytes, i_exif_size }; - WebPData xmp = { xmp_bytes, i_xmp_size }; - WebPMuxError err; - int dbg = 0; + /* I want to truncate the *_size items that get passed into WebP + data. Pypy2.1.0 had some issues where the Py_ssize_t items had + data in the upper byte. (Not sure why, it shouldn't have been there) + */ + int i_icc_size = (int)icc_size; + int i_exif_size = (int)exif_size; + int i_xmp_size = (int)xmp_size; + WebPData output_data = {0}; + WebPData image = {output, ret_size}; + WebPData icc_profile = {icc_bytes, i_icc_size}; + WebPData exif = {exif_bytes, i_exif_size}; + WebPData xmp = {xmp_bytes, i_xmp_size}; + WebPMuxError err; + int dbg = 0; - int copy_data = 0; // value 1 indicates given data WILL be copied to the mux - // and value 0 indicates data will NOT be copied. + int copy_data = 0; // value 1 indicates given data WILL be copied to the mux + // and value 0 indicates data will NOT be copied. - WebPMux* mux = WebPMuxNew(); - WebPMuxSetImage(mux, &image, copy_data); + WebPMux *mux = WebPMuxNew(); + WebPMuxSetImage(mux, &image, copy_data); - if (dbg) { - /* was getting %ld icc_size == 0, icc_size>0 was true */ - fprintf(stderr, "icc size %d, %d \n", i_icc_size, i_icc_size > 0); - } - - if (i_icc_size > 0) { if (dbg) { - fprintf(stderr, "Adding ICC Profile\n"); + /* was getting %ld icc_size == 0, icc_size>0 was true */ + fprintf(stderr, "icc size %d, %d \n", i_icc_size, i_icc_size > 0); + } + + if (i_icc_size > 0) { + if (dbg) { + fprintf(stderr, "Adding ICC Profile\n"); + } + err = WebPMuxSetChunk(mux, "ICCP", &icc_profile, copy_data); + if (err != WEBP_MUX_OK) { + return HandleMuxError(err, "ICCP"); + } } - err = WebPMuxSetChunk(mux, "ICCP", &icc_profile, copy_data); - if (err != WEBP_MUX_OK) { - return HandleMuxError(err, "ICCP"); - } - } - if (dbg) { - fprintf(stderr, "exif size %d \n", i_exif_size); - } - if (i_exif_size > 0) { if (dbg) { - fprintf(stderr, "Adding Exif Data\n"); + fprintf(stderr, "exif size %d \n", i_exif_size); } - err = WebPMuxSetChunk(mux, "EXIF", &exif, copy_data); - if (err != WEBP_MUX_OK) { - return HandleMuxError(err, "EXIF"); + if (i_exif_size > 0) { + if (dbg) { + fprintf(stderr, "Adding Exif Data\n"); + } + err = WebPMuxSetChunk(mux, "EXIF", &exif, copy_data); + if (err != WEBP_MUX_OK) { + return HandleMuxError(err, "EXIF"); + } } - } - if (dbg) { - fprintf(stderr, "xmp size %d \n", i_xmp_size); - } - if (i_xmp_size > 0) { - if (dbg){ - fprintf(stderr, "Adding XMP Data\n"); + if (dbg) { + fprintf(stderr, "xmp size %d \n", i_xmp_size); } - err = WebPMuxSetChunk(mux, "XMP ", &xmp, copy_data); - if (err != WEBP_MUX_OK) { - return HandleMuxError(err, "XMP "); + if (i_xmp_size > 0) { + if (dbg) { + fprintf(stderr, "Adding XMP Data\n"); + } + err = WebPMuxSetChunk(mux, "XMP ", &xmp, copy_data); + if (err != WEBP_MUX_OK) { + return HandleMuxError(err, "XMP "); + } } - } - WebPMuxAssemble(mux, &output_data); - WebPMuxDelete(mux); - free(output); + WebPMuxAssemble(mux, &output_data); + WebPMuxDelete(mux); + free(output); - ret_size = output_data.size; - if (ret_size > 0) { - PyObject *ret = PyBytes_FromStringAndSize((char*)output_data.bytes, ret_size); - WebPDataClear(&output_data); - return ret; - } + ret_size = output_data.size; + if (ret_size > 0) { + PyObject *ret = + PyBytes_FromStringAndSize((char *)output_data.bytes, ret_size); + WebPDataClear(&output_data); + return ret; + } } #endif Py_RETURN_NONE; } -PyObject* WebPDecode_wrapper(PyObject* self, PyObject* args) -{ - PyBytesObject* webp_string; - const uint8_t* webp; +PyObject * +WebPDecode_wrapper(PyObject *self, PyObject *args) { + PyBytesObject *webp_string; + const uint8_t *webp; Py_ssize_t size; - PyObject *ret = Py_None, *bytes = NULL, *pymode = NULL, *icc_profile = NULL, *exif = NULL; + PyObject *ret = Py_None, *bytes = NULL, *pymode = NULL, *icc_profile = NULL, + *exif = NULL; WebPDecoderConfig config; VP8StatusCode vp8_status_code = VP8_STATUS_OK; - char* mode = "RGB"; + char *mode = "RGB"; if (!PyArg_ParseTuple(args, "S", &webp_string)) { return NULL; @@ -729,7 +774,7 @@ PyObject* WebPDecode_wrapper(PyObject* self, PyObject* args) Py_RETURN_NONE; } - PyBytes_AsStringAndSize((PyObject*) webp_string, (char**)&webp, &size); + PyBytes_AsStringAndSize((PyObject *)webp_string, (char **)&webp, &size); vp8_status_code = WebPGetFeatures(webp, size, &config.input); if (vp8_status_code == VP8_STATUS_OK) { @@ -743,39 +788,40 @@ PyObject* WebPDecode_wrapper(PyObject* self, PyObject* args) #ifndef HAVE_WEBPMUX vp8_status_code = WebPDecode(webp, size, &config); #else - { - int copy_data = 0; - WebPData data = { webp, size }; - WebPMuxFrameInfo image; - WebPData icc_profile_data = {0}; - WebPData exif_data = {0}; - - WebPMux* mux = WebPMuxCreate(&data, copy_data); - if (NULL == mux) { - goto end; - } - - if (WEBP_MUX_OK != WebPMuxGetFrame(mux, 1, &image)) { + int copy_data = 0; + WebPData data = {webp, size}; + WebPMuxFrameInfo image; + WebPData icc_profile_data = {0}; + WebPData exif_data = {0}; + + WebPMux *mux = WebPMuxCreate(&data, copy_data); + if (NULL == mux) { + goto end; + } + + if (WEBP_MUX_OK != WebPMuxGetFrame(mux, 1, &image)) { + WebPMuxDelete(mux); + goto end; + } + + webp = image.bitstream.bytes; + size = image.bitstream.size; + + vp8_status_code = WebPDecode(webp, size, &config); + + if (WEBP_MUX_OK == WebPMuxGetChunk(mux, "ICCP", &icc_profile_data)) { + icc_profile = PyBytes_FromStringAndSize( + (const char *)icc_profile_data.bytes, icc_profile_data.size); + } + + if (WEBP_MUX_OK == WebPMuxGetChunk(mux, "EXIF", &exif_data)) { + exif = PyBytes_FromStringAndSize( + (const char *)exif_data.bytes, exif_data.size); + } + + WebPDataClear(&image.bitstream); WebPMuxDelete(mux); - goto end; - } - - webp = image.bitstream.bytes; - size = image.bitstream.size; - - vp8_status_code = WebPDecode(webp, size, &config); - - if (WEBP_MUX_OK == WebPMuxGetChunk(mux, "ICCP", &icc_profile_data)) { - icc_profile = PyBytes_FromStringAndSize((const char*)icc_profile_data.bytes, icc_profile_data.size); - } - - if (WEBP_MUX_OK == WebPMuxGetChunk(mux, "EXIF", &exif_data)) { - exif = PyBytes_FromStringAndSize((const char*)exif_data.bytes, exif_data.size); - } - - WebPDataClear(&image.bitstream); - WebPMuxDelete(mux); } #endif } @@ -785,20 +831,24 @@ PyObject* WebPDecode_wrapper(PyObject* self, PyObject* args) } if (config.output.colorspace < MODE_YUV) { - bytes = PyBytes_FromStringAndSize((char*)config.output.u.RGBA.rgba, - config.output.u.RGBA.size); + bytes = PyBytes_FromStringAndSize( + (char *)config.output.u.RGBA.rgba, config.output.u.RGBA.size); } else { // Skipping YUV for now. Need Test Images. // UNDONE -- unclear if we'll ever get here if we set mode_rgb* - bytes = PyBytes_FromStringAndSize((char*)config.output.u.YUVA.y, - config.output.u.YUVA.y_size); + bytes = PyBytes_FromStringAndSize( + (char *)config.output.u.YUVA.y, config.output.u.YUVA.y_size); } pymode = PyUnicode_FromString(mode); - ret = Py_BuildValue("SiiSSS", bytes, config.output.width, - config.output.height, pymode, - NULL == icc_profile ? Py_None : icc_profile, - NULL == exif ? Py_None : exif); + ret = Py_BuildValue( + "SiiSSS", + bytes, + config.output.width, + config.output.height, + pymode, + NULL == icc_profile ? Py_None : icc_profile, + NULL == exif ? Py_None : exif); end: WebPFreeDecBuffer(&config.output); @@ -817,17 +867,22 @@ end: // Return the decoder's version number, packed in hexadecimal using 8bits for // each of major/minor/revision. E.g: v2.5.7 is 0x020507. -PyObject* WebPDecoderVersion_wrapper() { +PyObject * +WebPDecoderVersion_wrapper() { return Py_BuildValue("i", WebPGetDecoderVersion()); } // Version as string -const char* -WebPDecoderVersion_str(void) -{ +const char * +WebPDecoderVersion_str(void) { static char version[20]; int version_number = WebPGetDecoderVersion(); - sprintf(version, "%d.%d.%d", version_number >> 16, (version_number >> 8) % 0x100, version_number % 0x100); + sprintf( + version, + "%d.%d.%d", + version_number >> 16, + (version_number >> 8) % 0x100, + version_number % 0x100); return version; } @@ -835,11 +890,13 @@ WebPDecoderVersion_str(void) * The version of webp that ships with (0.1.3) Ubuntu 12.04 doesn't handle alpha well. * Files that are valid with 0.3 are reported as being invalid. */ -int WebPDecoderBuggyAlpha(void) { - return WebPGetDecoderVersion()==0x0103; +int +WebPDecoderBuggyAlpha(void) { + return WebPGetDecoderVersion() == 0x0103; } -PyObject* WebPDecoderBuggyAlpha_wrapper() { +PyObject * +WebPDecoderBuggyAlpha_wrapper() { return Py_BuildValue("i", WebPDecoderBuggyAlpha()); } @@ -847,8 +904,7 @@ PyObject* WebPDecoderBuggyAlpha_wrapper() { /* Module Setup */ /* -------------------------------------------------------------------- */ -static PyMethodDef webpMethods[] = -{ +static PyMethodDef webpMethods[] = { #ifdef HAVE_WEBPANIM {"WebPAnimDecoder", _anim_decoder_new, METH_VARARGS, "WebPAnimDecoder"}, {"WebPAnimEncoder", _anim_encoder_new, METH_VARARGS, "WebPAnimEncoder"}, @@ -856,11 +912,14 @@ static PyMethodDef webpMethods[] = {"WebPEncode", WebPEncode_wrapper, METH_VARARGS, "WebPEncode"}, {"WebPDecode", WebPDecode_wrapper, METH_VARARGS, "WebPDecode"}, {"WebPDecoderVersion", WebPDecoderVersion_wrapper, METH_NOARGS, "WebPVersion"}, - {"WebPDecoderBuggyAlpha", WebPDecoderBuggyAlpha_wrapper, METH_NOARGS, "WebPDecoderBuggyAlpha"}, - {NULL, NULL} -}; + {"WebPDecoderBuggyAlpha", + WebPDecoderBuggyAlpha_wrapper, + METH_NOARGS, + "WebPDecoderBuggyAlpha"}, + {NULL, NULL}}; -void addMuxFlagToModule(PyObject* m) { +void +addMuxFlagToModule(PyObject *m) { #ifdef HAVE_WEBPMUX PyModule_AddObject(m, "HAVE_WEBPMUX", Py_True); #else @@ -868,7 +927,8 @@ void addMuxFlagToModule(PyObject* m) { #endif } -void addAnimFlagToModule(PyObject* m) { +void +addAnimFlagToModule(PyObject *m) { #ifdef HAVE_WEBPANIM PyModule_AddObject(m, "HAVE_WEBPANIM", Py_True); #else @@ -876,18 +936,21 @@ void addAnimFlagToModule(PyObject* m) { #endif } -void addTransparencyFlagToModule(PyObject* m) { - PyModule_AddObject(m, "HAVE_TRANSPARENCY", - PyBool_FromLong(!WebPDecoderBuggyAlpha())); +void +addTransparencyFlagToModule(PyObject *m) { + PyModule_AddObject( + m, "HAVE_TRANSPARENCY", PyBool_FromLong(!WebPDecoderBuggyAlpha())); } -static int setup_module(PyObject* m) { - PyObject* d = PyModule_GetDict(m); +static int +setup_module(PyObject *m) { + PyObject *d = PyModule_GetDict(m); addMuxFlagToModule(m); addAnimFlagToModule(m); addTransparencyFlagToModule(m); - PyDict_SetItemString(d, "webpdecoder_version", PyUnicode_FromString(WebPDecoderVersion_str())); + PyDict_SetItemString( + d, "webpdecoder_version", PyUnicode_FromString(WebPDecoderVersion_str())); #ifdef HAVE_WEBPANIM /* Ready object types */ @@ -901,14 +964,14 @@ static int setup_module(PyObject* m) { PyMODINIT_FUNC PyInit__webp(void) { - PyObject* m; + PyObject *m; static PyModuleDef module_def = { PyModuleDef_HEAD_INIT, - "_webp", /* m_name */ - NULL, /* m_doc */ - -1, /* m_size */ - webpMethods, /* m_methods */ + "_webp", /* m_name */ + NULL, /* m_doc */ + -1, /* m_size */ + webpMethods, /* m_methods */ }; m = PyModule_Create(&module_def); diff --git a/src/decode.c b/src/decode.c index 5c57fea5d..5d64bd0b9 100644 --- a/src/decode.c +++ b/src/decode.c @@ -39,31 +39,28 @@ #include "libImaging/Bit.h" #include "libImaging/Sgi.h" - /* -------------------------------------------------------------------- */ /* Common */ /* -------------------------------------------------------------------- */ typedef struct { - PyObject_HEAD - int (*decode)(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); + PyObject_HEAD int (*decode)( + Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); int (*cleanup)(ImagingCodecState state); struct ImagingCodecStateInstance state; Imaging im; - PyObject* lock; + PyObject *lock; int pulls_fd; } ImagingDecoderObject; static PyTypeObject ImagingDecoderType; -static ImagingDecoderObject* -PyImaging_DecoderNew(int contextsize) -{ +static ImagingDecoderObject * +PyImaging_DecoderNew(int contextsize) { ImagingDecoderObject *decoder; void *context; - if(PyType_Ready(&ImagingDecoderType) < 0) { + if (PyType_Ready(&ImagingDecoderType) < 0) { return NULL; } @@ -77,10 +74,10 @@ PyImaging_DecoderNew(int contextsize) /* Allocate decoder context */ if (contextsize > 0) { - context = (void*) calloc(1, contextsize); + context = (void *)calloc(1, contextsize); if (!context) { Py_DECREF(decoder); - (void) ImagingError_MemoryError(); + (void)ImagingError_MemoryError(); return NULL; } } else { @@ -105,8 +102,7 @@ PyImaging_DecoderNew(int contextsize) } static void -_dealloc(ImagingDecoderObject* decoder) -{ +_dealloc(ImagingDecoderObject *decoder) { if (decoder->cleanup) { decoder->cleanup(&decoder->state); } @@ -117,10 +113,9 @@ _dealloc(ImagingDecoderObject* decoder) PyObject_Del(decoder); } -static PyObject* -_decode(ImagingDecoderObject* decoder, PyObject* args) -{ - UINT8* buffer; +static PyObject * +_decode(ImagingDecoderObject *decoder, PyObject *args) { + UINT8 *buffer; Py_ssize_t bufsize; int status; ImagingSectionCookie cookie; @@ -142,26 +137,23 @@ _decode(ImagingDecoderObject* decoder, PyObject* args) return Py_BuildValue("ii", status, decoder->state.errcode); } -static PyObject* -_decode_cleanup(ImagingDecoderObject* decoder, PyObject* args) -{ +static PyObject * +_decode_cleanup(ImagingDecoderObject *decoder, PyObject *args) { int status = 0; - if (decoder->cleanup){ + if (decoder->cleanup) { status = decoder->cleanup(&decoder->state); } return Py_BuildValue("i", status); } +extern Imaging +PyImaging_AsImaging(PyObject *op); - -extern Imaging PyImaging_AsImaging(PyObject *op); - -static PyObject* -_setimage(ImagingDecoderObject* decoder, PyObject* args) -{ - PyObject* op; +static PyObject * +_setimage(ImagingDecoderObject *decoder, PyObject *args) { + PyObject *op; Imaging im; ImagingCodecState state; int x0, y0, x1, y1; @@ -192,10 +184,8 @@ _setimage(ImagingDecoderObject* decoder, PyObject* args) state->ysize = y1 - y0; } - if (state->xsize <= 0 || - state->xsize + state->xoff > (int) im->xsize || - state->ysize <= 0 || - state->ysize + state->yoff > (int) im->ysize) { + if (state->xsize <= 0 || state->xsize + state->xoff > (int)im->xsize || + state->ysize <= 0 || state->ysize + state->yoff > (int)im->ysize) { PyErr_SetString(PyExc_ValueError, "tile cannot extend outside image"); return NULL; } @@ -203,13 +193,13 @@ _setimage(ImagingDecoderObject* decoder, PyObject* args) /* Allocate memory buffer (if bits field is set) */ if (state->bits > 0) { if (!state->bytes) { - if (state->xsize > ((INT_MAX / state->bits)-7)){ + if (state->xsize > ((INT_MAX / state->bits) - 7)) { return ImagingError_MemoryError(); } - state->bytes = (state->bits * state->xsize+7)/8; + state->bytes = (state->bits * state->xsize + 7) / 8; } /* malloc check ok, overflow checked above */ - state->buffer = (UINT8*) malloc(state->bytes); + state->buffer = (UINT8 *)malloc(state->bytes); if (!state->buffer) { return ImagingError_MemoryError(); } @@ -225,10 +215,9 @@ _setimage(ImagingDecoderObject* decoder, PyObject* args) return Py_None; } -static PyObject* -_setfd(ImagingDecoderObject* decoder, PyObject* args) -{ - PyObject* fd; +static PyObject * +_setfd(ImagingDecoderObject *decoder, PyObject *args) { + PyObject *fd; ImagingCodecState state; if (!PyArg_ParseTuple(args, "O", &fd)) { @@ -244,10 +233,8 @@ _setfd(ImagingDecoderObject* decoder, PyObject* args) return Py_None; } - static PyObject * -_get_pulls_fd(ImagingDecoderObject *decoder) -{ +_get_pulls_fd(ImagingDecoderObject *decoder) { return PyBool_FromLong(decoder->pulls_fd); } @@ -260,52 +247,51 @@ static struct PyMethodDef methods[] = { }; static struct PyGetSetDef getseters[] = { - {"pulls_fd", (getter)_get_pulls_fd, NULL, + {"pulls_fd", + (getter)_get_pulls_fd, + NULL, "True if this decoder expects to pull from self.fd itself.", NULL}, {NULL, NULL, NULL, NULL, NULL} /* sentinel */ }; static PyTypeObject ImagingDecoderType = { - PyVarObject_HEAD_INIT(NULL, 0) - "ImagingDecoder", /*tp_name*/ - sizeof(ImagingDecoderObject), /*tp_size*/ - 0, /*tp_itemsize*/ + PyVarObject_HEAD_INIT(NULL, 0) "ImagingDecoder", /*tp_name*/ + sizeof(ImagingDecoderObject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - (destructor)_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - methods, /*tp_methods*/ - 0, /*tp_members*/ - getseters, /*tp_getset*/ + (destructor)_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + methods, /*tp_methods*/ + 0, /*tp_members*/ + getseters, /*tp_getset*/ }; /* -------------------------------------------------------------------- */ int -get_unpacker(ImagingDecoderObject* decoder, const char* mode, - const char* rawmode) -{ +get_unpacker(ImagingDecoderObject *decoder, const char *mode, const char *rawmode) { int bits; ImagingShuffler unpack; @@ -322,24 +308,21 @@ get_unpacker(ImagingDecoderObject* decoder, const char* mode, return 0; } - /* -------------------------------------------------------------------- */ /* BIT (packed fields) */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_BitDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_BitDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - int bits = 8; - int pad = 8; - int fill = 0; - int sign = 0; + char *mode; + int bits = 8; + int pad = 8; + int fill = 0; + int sign = 0; int ystep = 1; - if (!PyArg_ParseTuple(args, "s|iiiii", &mode, &bits, &pad, &fill, - &sign, &ystep)) { + if (!PyArg_ParseTuple(args, "s|iiiii", &mode, &bits, &pad, &fill, &sign, &ystep)) { return NULL; } @@ -357,26 +340,24 @@ PyImaging_BitDecoderNew(PyObject* self, PyObject* args) decoder->state.ystep = ystep; - ((BITSTATE*)decoder->state.context)->bits = bits; - ((BITSTATE*)decoder->state.context)->pad = pad; - ((BITSTATE*)decoder->state.context)->fill = fill; - ((BITSTATE*)decoder->state.context)->sign = sign; + ((BITSTATE *)decoder->state.context)->bits = bits; + ((BITSTATE *)decoder->state.context)->pad = pad; + ((BITSTATE *)decoder->state.context)->fill = fill; + ((BITSTATE *)decoder->state.context)->sign = sign; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* BCn: GPU block-compressed texture formats */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_BcnDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_BcnDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* actual; + char *mode; + char *actual; int n = 0; int ystep = 1; if (!PyArg_ParseTuple(args, "s|ii", &mode, &n, &ystep)) { @@ -384,20 +365,23 @@ PyImaging_BcnDecoderNew(PyObject* self, PyObject* args) } switch (n) { - case 1: /* BC1: 565 color, 1-bit alpha */ - case 2: /* BC2: 565 color, 4-bit alpha */ - case 3: /* BC3: 565 color, 2-endpoint 8-bit interpolated alpha */ - case 5: /* BC5: 2-channel 8-bit via 2 BC3 alpha blocks */ - case 7: /* BC7: 4-channel 8-bit via everything */ - actual = "RGBA"; break; - case 4: /* BC4: 1-channel 8-bit via 1 BC3 alpha block */ - actual = "L"; break; - case 6: /* BC6: 3-channel 16-bit float */ - /* TODO: support 4-channel floating point images */ - actual = "RGBAF"; break; - default: - PyErr_SetString(PyExc_ValueError, "block compression type unknown"); - return NULL; + case 1: /* BC1: 565 color, 1-bit alpha */ + case 2: /* BC2: 565 color, 4-bit alpha */ + case 3: /* BC3: 565 color, 2-endpoint 8-bit interpolated alpha */ + case 5: /* BC5: 2-channel 8-bit via 2 BC3 alpha blocks */ + case 7: /* BC7: 4-channel 8-bit via everything */ + actual = "RGBA"; + break; + case 4: /* BC4: 1-channel 8-bit via 1 BC3 alpha block */ + actual = "L"; + break; + case 6: /* BC6: 3-channel 16-bit float */ + /* TODO: support 4-channel floating point images */ + actual = "RGBAF"; + break; + default: + PyErr_SetString(PyExc_ValueError, "block compression type unknown"); + return NULL; } if (strcmp(mode, actual) != 0) { @@ -414,18 +398,16 @@ PyImaging_BcnDecoderNew(PyObject* self, PyObject* args) decoder->state.state = n; decoder->state.ystep = ystep; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* FLI */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_FliDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_FliDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; decoder = PyImaging_DecoderNew(0); if (decoder == NULL) { @@ -434,20 +416,18 @@ PyImaging_FliDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingFliDecode; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* GIF */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_GifDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_GifDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; + char *mode; int bits = 8; int interlace = 0; if (!PyArg_ParseTuple(args, "s|ii", &mode, &bits, &interlace)) { @@ -466,24 +446,22 @@ PyImaging_GifDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingGifDecode; - ((GIFDECODERSTATE*)decoder->state.context)->bits = bits; - ((GIFDECODERSTATE*)decoder->state.context)->interlace = interlace; + ((GIFDECODERSTATE *)decoder->state.context)->bits = bits; + ((GIFDECODERSTATE *)decoder->state.context)->interlace = interlace; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* HEX */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_HexDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_HexDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* rawmode; + char *mode; + char *rawmode; if (!PyArg_ParseTuple(args, "ss", &mode, &rawmode)) { return NULL; } @@ -499,10 +477,9 @@ PyImaging_HexDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingHexDecode; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* LibTiff */ /* -------------------------------------------------------------------- */ @@ -513,17 +490,16 @@ PyImaging_HexDecoderNew(PyObject* self, PyObject* args) #include -PyObject* -PyImaging_LibTiffDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; - char* mode; - char* rawmode; - char* compname; +PyObject * +PyImaging_LibTiffDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; + char *mode; + char *rawmode; + char *compname; int fp; uint32 ifdoffset; - if (! PyArg_ParseTuple(args, "sssiI", &mode, &rawmode, &compname, &fp, &ifdoffset)) { + if (!PyArg_ParseTuple(args, "sssiI", &mode, &rawmode, &compname, &fp, &ifdoffset)) { return NULL; } @@ -538,31 +514,29 @@ PyImaging_LibTiffDecoderNew(PyObject* self, PyObject* args) return NULL; } - if (! ImagingLibTiffInit(&decoder->state, fp, ifdoffset)) { + if (!ImagingLibTiffInit(&decoder->state, fp, ifdoffset)) { Py_DECREF(decoder); PyErr_SetString(PyExc_RuntimeError, "tiff codec initialization failed"); return NULL; } - decoder->decode = ImagingLibTiffDecode; + decoder->decode = ImagingLibTiffDecode; - return (PyObject*) decoder; + return (PyObject *)decoder; } #endif - /* -------------------------------------------------------------------- */ /* PackBits */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_PackbitsDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_PackbitsDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* rawmode; + char *mode; + char *rawmode; if (!PyArg_ParseTuple(args, "ss", &mode, &rawmode)) { return NULL; } @@ -578,18 +552,16 @@ PyImaging_PackbitsDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingPackbitsDecode; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* PCD */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_PcdDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_PcdDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; decoder = PyImaging_DecoderNew(0); if (decoder == NULL) { @@ -603,21 +575,19 @@ PyImaging_PcdDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingPcdDecode; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* PCX */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_PcxDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_PcxDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* rawmode; + char *mode; + char *rawmode; int stride; if (!PyArg_ParseTuple(args, "ssi", &mode, &rawmode, &stride)) { return NULL; @@ -636,23 +606,21 @@ PyImaging_PcxDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingPcxDecode; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* RAW */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_RawDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_RawDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* rawmode; + char *mode; + char *rawmode; int stride = 0; - int ystep = 1; + int ystep = 1; if (!PyArg_ParseTuple(args, "ss|ii", &mode, &rawmode, &stride, &ystep)) { return NULL; } @@ -670,23 +638,21 @@ PyImaging_RawDecoderNew(PyObject* self, PyObject* args) decoder->state.ystep = ystep; - ((RAWSTATE*)decoder->state.context)->stride = stride; + ((RAWSTATE *)decoder->state.context)->stride = stride; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* SGI RLE */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_SgiRleDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_SgiRleDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* rawmode; + char *mode; + char *rawmode; int ystep = 1; int bpc = 1; if (!PyArg_ParseTuple(args, "ss|ii", &mode, &rawmode, &ystep, &bpc)) { @@ -706,23 +672,21 @@ PyImaging_SgiRleDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingSgiRleDecode; decoder->state.ystep = ystep; - ((SGISTATE*)decoder->state.context)->bpc = bpc; + ((SGISTATE *)decoder->state.context)->bpc = bpc; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* SUN RLE */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_SunRleDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_SunRleDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* rawmode; + char *mode; + char *rawmode; if (!PyArg_ParseTuple(args, "ss", &mode, &rawmode)) { return NULL; } @@ -738,21 +702,19 @@ PyImaging_SunRleDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingSunRleDecode; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* TGA RLE */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_TgaRleDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_TgaRleDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* rawmode; + char *mode; + char *rawmode; int ystep = 1; int depth = 8; if (!PyArg_ParseTuple(args, "ss|ii", &mode, &rawmode, &ystep, &depth)) { @@ -773,18 +735,16 @@ PyImaging_TgaRleDecoderNew(PyObject* self, PyObject* args) decoder->state.ystep = ystep; decoder->state.count = depth / 8; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* XBM */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_XbmDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_XbmDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; decoder = PyImaging_DecoderNew(0); if (decoder == NULL) { @@ -797,10 +757,9 @@ PyImaging_XbmDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingXbmDecode; - return (PyObject*) decoder; + return (PyObject *)decoder; } - /* -------------------------------------------------------------------- */ /* ZIP */ /* -------------------------------------------------------------------- */ @@ -809,13 +768,12 @@ PyImaging_XbmDecoderNew(PyObject* self, PyObject* args) #include "libImaging/ZipCodecs.h" -PyObject* -PyImaging_ZipDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_ZipDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* rawmode; + char *mode; + char *rawmode; int interlaced = 0; if (!PyArg_ParseTuple(args, "ss|i", &mode, &rawmode, &interlaced)) { return NULL; @@ -833,13 +791,12 @@ PyImaging_ZipDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingZipDecode; decoder->cleanup = ImagingZipDecodeCleanup; - ((ZIPSTATE*)decoder->state.context)->interlaced = interlaced; + ((ZIPSTATE *)decoder->state.context)->interlaced = interlaced; - return (PyObject*) decoder; + return (PyObject *)decoder; } #endif - /* -------------------------------------------------------------------- */ /* JPEG */ /* -------------------------------------------------------------------- */ @@ -849,31 +806,29 @@ PyImaging_ZipDecoderNew(PyObject* self, PyObject* args) /* We better define this decoder last in this file, so the following undef's won't mess things up for the Imaging library proper. */ -#undef HAVE_PROTOTYPES -#undef HAVE_STDDEF_H -#undef HAVE_STDLIB_H -#undef UINT8 -#undef UINT16 -#undef UINT32 -#undef INT8 -#undef INT16 -#undef INT32 +#undef HAVE_PROTOTYPES +#undef HAVE_STDDEF_H +#undef HAVE_STDLIB_H +#undef UINT8 +#undef UINT16 +#undef UINT32 +#undef INT8 +#undef INT16 +#undef INT32 #include "libImaging/Jpeg.h" -PyObject* -PyImaging_JpegDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_JpegDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; - char* mode; - char* rawmode; /* what we want from the decoder */ - char* jpegmode; /* what's in the file */ + char *mode; + char *rawmode; /* what we want from the decoder */ + char *jpegmode; /* what's in the file */ int scale = 1; int draft = 0; - if (!PyArg_ParseTuple(args, "ssz|ii", &mode, &rawmode, &jpegmode, - &scale, &draft)) { + if (!PyArg_ParseTuple(args, "ssz|ii", &mode, &rawmode, &jpegmode, &scale, &draft)) { return NULL; } @@ -900,13 +855,13 @@ PyImaging_JpegDecoderNew(PyObject* self, PyObject* args) decoder->decode = ImagingJpegDecode; decoder->cleanup = ImagingJpegDecodeCleanup; - strncpy(((JPEGSTATE*)decoder->state.context)->rawmode, rawmode, 8); - strncpy(((JPEGSTATE*)decoder->state.context)->jpegmode, jpegmode, 8); + strncpy(((JPEGSTATE *)decoder->state.context)->rawmode, rawmode, 8); + strncpy(((JPEGSTATE *)decoder->state.context)->jpegmode, jpegmode, 8); - ((JPEGSTATE*)decoder->state.context)->scale = scale; - ((JPEGSTATE*)decoder->state.context)->draft = draft; + ((JPEGSTATE *)decoder->state.context)->scale = scale; + ((JPEGSTATE *)decoder->state.context)->draft = draft; - return (PyObject*) decoder; + return (PyObject *)decoder; } #endif @@ -918,22 +873,21 @@ PyImaging_JpegDecoderNew(PyObject* self, PyObject* args) #include "libImaging/Jpeg2K.h" -PyObject* -PyImaging_Jpeg2KDecoderNew(PyObject* self, PyObject* args) -{ - ImagingDecoderObject* decoder; +PyObject * +PyImaging_Jpeg2KDecoderNew(PyObject *self, PyObject *args) { + ImagingDecoderObject *decoder; JPEG2KDECODESTATE *context; - char* mode; - char* format; + char *mode; + char *format; OPJ_CODEC_FORMAT codec_format; int reduce = 0; int layers = 0; int fd = -1; PY_LONG_LONG length = -1; - if (!PyArg_ParseTuple(args, "ss|iiiL", &mode, &format, - &reduce, &layers, &fd, &length)) { + if (!PyArg_ParseTuple( + args, "ss|iiiL", &mode, &format, &reduce, &layers, &fd, &length)) { return NULL; } @@ -964,7 +918,6 @@ PyImaging_Jpeg2KDecoderNew(PyObject* self, PyObject* args) context->reduce = reduce; context->layers = layers; - return (PyObject*) decoder; + return (PyObject *)decoder; } #endif /* HAVE_OPENJPEG */ - diff --git a/src/display.c b/src/display.c index b8190db8c..3541655cf 100644 --- a/src/display.c +++ b/src/display.c @@ -41,15 +41,13 @@ #endif typedef struct { - PyObject_HEAD - ImagingDIB dib; + PyObject_HEAD ImagingDIB dib; } ImagingDisplayObject; static PyTypeObject ImagingDisplayType; -static ImagingDisplayObject* -_new(const char* mode, int xsize, int ysize) -{ +static ImagingDisplayObject * +_new(const char *mode, int xsize, int ysize) { ImagingDisplayObject *display; if (PyType_Ready(&ImagingDisplayType) < 0) { @@ -71,17 +69,15 @@ _new(const char* mode, int xsize, int ysize) } static void -_delete(ImagingDisplayObject* display) -{ +_delete(ImagingDisplayObject *display) { if (display->dib) { ImagingDeleteDIB(display->dib); } PyObject_Del(display); } -static PyObject* -_expose(ImagingDisplayObject* display, PyObject* args) -{ +static PyObject * +_expose(ImagingDisplayObject *display, PyObject *args) { HDC hdc; if (!PyArg_ParseTuple(args, F_HANDLE, &hdc)) { return NULL; @@ -93,15 +89,23 @@ _expose(ImagingDisplayObject* display, PyObject* args) return Py_None; } -static PyObject* -_draw(ImagingDisplayObject* display, PyObject* args) -{ +static PyObject * +_draw(ImagingDisplayObject *display, PyObject *args) { HDC hdc; int dst[4]; int src[4]; - if (!PyArg_ParseTuple(args, F_HANDLE "(iiii)(iiii)", &hdc, - dst+0, dst+1, dst+2, dst+3, - src+0, src+1, src+2, src+3)) { + if (!PyArg_ParseTuple( + args, + F_HANDLE "(iiii)(iiii)", + &hdc, + dst + 0, + dst + 1, + dst + 2, + dst + 3, + src + 0, + src + 1, + src + 2, + src + 3)) { return NULL; } @@ -111,17 +115,17 @@ _draw(ImagingDisplayObject* display, PyObject* args) return Py_None; } -extern Imaging PyImaging_AsImaging(PyObject *op); +extern Imaging +PyImaging_AsImaging(PyObject *op); -static PyObject* -_paste(ImagingDisplayObject* display, PyObject* args) -{ +static PyObject * +_paste(ImagingDisplayObject *display, PyObject *args) { Imaging im; - PyObject* op; + PyObject *op; int xy[4]; xy[0] = xy[1] = xy[2] = xy[3] = 0; - if (!PyArg_ParseTuple(args, "O|(iiii)", &op, xy+0, xy+1, xy+2, xy+3)) { + if (!PyArg_ParseTuple(args, "O|(iiii)", &op, xy + 0, xy + 1, xy + 2, xy + 3)) { return NULL; } im = PyImaging_AsImaging(op); @@ -142,9 +146,8 @@ _paste(ImagingDisplayObject* display, PyObject* args) return Py_None; } -static PyObject* -_query_palette(ImagingDisplayObject* display, PyObject* args) -{ +static PyObject * +_query_palette(ImagingDisplayObject *display, PyObject *args) { HDC hdc; int status; @@ -157,9 +160,8 @@ _query_palette(ImagingDisplayObject* display, PyObject* args) return Py_BuildValue("i", status); } -static PyObject* -_getdc(ImagingDisplayObject* display, PyObject* args) -{ +static PyObject * +_getdc(ImagingDisplayObject *display, PyObject *args) { HWND window; HDC dc; @@ -176,9 +178,8 @@ _getdc(ImagingDisplayObject* display, PyObject* args) return Py_BuildValue(F_HANDLE, dc); } -static PyObject* -_releasedc(ImagingDisplayObject* display, PyObject* args) -{ +static PyObject * +_releasedc(ImagingDisplayObject *display, PyObject *args) { HWND window; HDC dc; @@ -192,10 +193,9 @@ _releasedc(ImagingDisplayObject* display, PyObject* args) return Py_None; } -static PyObject* -_frombytes(ImagingDisplayObject* display, PyObject* args) -{ - char* ptr; +static PyObject * +_frombytes(ImagingDisplayObject *display, PyObject *args) { + char *ptr; Py_ssize_t bytes; if (!PyArg_ParseTuple(args, "y#:frombytes", &ptr, &bytes)) { @@ -213,16 +213,14 @@ _frombytes(ImagingDisplayObject* display, PyObject* args) return Py_None; } -static PyObject* -_tobytes(ImagingDisplayObject* display, PyObject* args) -{ +static PyObject * +_tobytes(ImagingDisplayObject *display, PyObject *args) { if (!PyArg_ParseTuple(args, ":tobytes")) { return NULL; } return PyBytes_FromStringAndSize( - display->dib->bits, display->dib->ysize * display->dib->linesize - ); + display->dib->bits, display->dib->ysize * display->dib->linesize); } static struct PyMethodDef methods[] = { @@ -237,62 +235,55 @@ static struct PyMethodDef methods[] = { {NULL, NULL} /* sentinel */ }; -static PyObject* -_getattr_mode(ImagingDisplayObject* self, void* closure) -{ +static PyObject * +_getattr_mode(ImagingDisplayObject *self, void *closure) { return Py_BuildValue("s", self->dib->mode); } -static PyObject* -_getattr_size(ImagingDisplayObject* self, void* closure) -{ +static PyObject * +_getattr_size(ImagingDisplayObject *self, void *closure) { return Py_BuildValue("ii", self->dib->xsize, self->dib->ysize); } static struct PyGetSetDef getsetters[] = { - { "mode", (getter) _getattr_mode }, - { "size", (getter) _getattr_size }, - { NULL } -}; + {"mode", (getter)_getattr_mode}, {"size", (getter)_getattr_size}, {NULL}}; static PyTypeObject ImagingDisplayType = { - PyVarObject_HEAD_INIT(NULL, 0) - "ImagingDisplay", /*tp_name*/ - sizeof(ImagingDisplayObject),/*tp_size*/ - 0, /*tp_itemsize*/ + PyVarObject_HEAD_INIT(NULL, 0) "ImagingDisplay", /*tp_name*/ + sizeof(ImagingDisplayObject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - (destructor)_delete, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - methods, /*tp_methods*/ - 0, /*tp_members*/ - getsetters, /*tp_getset*/ + (destructor)_delete, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + methods, /*tp_methods*/ + 0, /*tp_members*/ + getsetters, /*tp_getset*/ }; -PyObject* -PyImaging_DisplayWin32(PyObject* self, PyObject* args) -{ - ImagingDisplayObject* display; +PyObject * +PyImaging_DisplayWin32(PyObject *self, PyObject *args) { + ImagingDisplayObject *display; char *mode; int xsize, ysize; @@ -305,12 +296,11 @@ PyImaging_DisplayWin32(PyObject* self, PyObject* args) return NULL; } - return (PyObject*) display; + return (PyObject *)display; } -PyObject* -PyImaging_DisplayModeWin32(PyObject* self, PyObject* args) -{ +PyObject * +PyImaging_DisplayModeWin32(PyObject *self, PyObject *args) { char *mode; int size[2]; @@ -322,18 +312,17 @@ PyImaging_DisplayModeWin32(PyObject* self, PyObject* args) /* -------------------------------------------------------------------- */ /* Windows screen grabber */ -typedef HANDLE(__stdcall* Func_SetThreadDpiAwarenessContext)(HANDLE); +typedef HANDLE(__stdcall *Func_SetThreadDpiAwarenessContext)(HANDLE); -PyObject* -PyImaging_GrabScreenWin32(PyObject* self, PyObject* args) -{ +PyObject * +PyImaging_GrabScreenWin32(PyObject *self, PyObject *args) { int x = 0, y = 0, width, height; int includeLayeredWindows = 0, all_screens = 0; HBITMAP bitmap; BITMAPCOREHEADER core; HDC screen, screen_copy; DWORD rop; - PyObject* buffer; + PyObject *buffer; HANDLE dpiAwareness; HMODULE user32; Func_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContext_function; @@ -352,11 +341,11 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args) // loaded dynamically to avoid link errors user32 = LoadLibraryA("User32.dll"); SetThreadDpiAwarenessContext_function = - (Func_SetThreadDpiAwarenessContext) - GetProcAddress(user32, "SetThreadDpiAwarenessContext"); + (Func_SetThreadDpiAwarenessContext)GetProcAddress( + user32, "SetThreadDpiAwarenessContext"); if (SetThreadDpiAwarenessContext_function != NULL) { // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = ((DPI_CONTEXT_HANDLE)-3) - dpiAwareness = SetThreadDpiAwarenessContext_function((HANDLE) -3); + dpiAwareness = SetThreadDpiAwarenessContext_function((HANDLE)-3); } if (all_screens) { @@ -396,7 +385,7 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args) /* step 3: extract bits from bitmap */ - buffer = PyBytes_FromStringAndSize(NULL, height * ((width*3 + 3) & -4)); + buffer = PyBytes_FromStringAndSize(NULL, height * ((width * 3 + 3) & -4)); if (!buffer) { return NULL; } @@ -406,8 +395,14 @@ PyImaging_GrabScreenWin32(PyObject* self, PyObject* args) core.bcHeight = height; core.bcPlanes = 1; core.bcBitCount = 24; - if (!GetDIBits(screen_copy, bitmap, 0, height, PyBytes_AS_STRING(buffer), - (BITMAPINFO*) &core, DIB_RGB_COLORS)) { + if (!GetDIBits( + screen_copy, + bitmap, + 0, + height, + PyBytes_AS_STRING(buffer), + (BITMAPINFO *)&core, + DIB_RGB_COLORS)) { goto error; } @@ -426,11 +421,11 @@ error: return NULL; } -static BOOL CALLBACK list_windows_callback(HWND hwnd, LPARAM lParam) -{ - PyObject* window_list = (PyObject*) lParam; - PyObject* item; - PyObject* title; +static BOOL CALLBACK +list_windows_callback(HWND hwnd, LPARAM lParam) { + PyObject *window_list = (PyObject *)lParam; + PyObject *item; + PyObject *title; RECT inner, outer; int title_size; int status; @@ -440,7 +435,7 @@ static BOOL CALLBACK list_windows_callback(HWND hwnd, LPARAM lParam) if (title_size > 0) { title = PyUnicode_FromStringAndSize(NULL, title_size); if (title) { - GetWindowTextW(hwnd, PyUnicode_AS_UNICODE(title), title_size+1); + GetWindowTextW(hwnd, PyUnicode_AS_UNICODE(title), title_size + 1); } } else { title = PyUnicode_FromString(""); @@ -454,10 +449,17 @@ static BOOL CALLBACK list_windows_callback(HWND hwnd, LPARAM lParam) GetWindowRect(hwnd, &outer); item = Py_BuildValue( - F_HANDLE "N(iiii)(iiii)", hwnd, title, - inner.left, inner.top, inner.right, inner.bottom, - outer.left, outer.top, outer.right, outer.bottom - ); + F_HANDLE "N(iiii)(iiii)", + hwnd, + title, + inner.left, + inner.top, + inner.right, + inner.bottom, + outer.left, + outer.top, + outer.right, + outer.bottom); if (!item) { return 0; } @@ -473,17 +475,16 @@ static BOOL CALLBACK list_windows_callback(HWND hwnd, LPARAM lParam) return 1; } -PyObject* -PyImaging_ListWindowsWin32(PyObject* self, PyObject* args) -{ - PyObject* window_list; +PyObject * +PyImaging_ListWindowsWin32(PyObject *self, PyObject *args) { + PyObject *window_list; window_list = PyList_New(0); if (!window_list) { return NULL; } - EnumWindows(list_windows_callback, (LPARAM) window_list); + EnumWindows(list_windows_callback, (LPARAM)window_list); if (PyErr_Occurred()) { Py_DECREF(window_list); @@ -496,17 +497,16 @@ PyImaging_ListWindowsWin32(PyObject* self, PyObject* args) /* -------------------------------------------------------------------- */ /* Windows clipboard grabber */ -PyObject* -PyImaging_GrabClipboardWin32(PyObject* self, PyObject* args) -{ +PyObject * +PyImaging_GrabClipboardWin32(PyObject *self, PyObject *args) { int clip; HANDLE handle = NULL; int size; - void* data; - PyObject* result; + void *data; + PyObject *result; UINT format; - UINT formats[] = { CF_DIB, CF_DIBV5, CF_HDROP, RegisterClipboardFormatA("PNG"), 0 }; - LPCSTR format_names[] = { "DIB", "DIB", "file", "png", NULL }; + UINT formats[] = {CF_DIB, CF_DIBV5, CF_HDROP, RegisterClipboardFormatA("PNG"), 0}; + LPCSTR format_names[] = {"DIB", "DIB", "file", "png", NULL}; if (!OpenClipboard(NULL)) { PyErr_SetString(PyExc_OSError, "failed to open clipboard"); @@ -551,15 +551,14 @@ PyImaging_GrabClipboardWin32(PyObject* self, PyObject* args) static int mainloop = 0; static void -callback_error(const char* handler) -{ - PyObject* sys_stderr; +callback_error(const char *handler) { + PyObject *sys_stderr; sys_stderr = PySys_GetObject("stderr"); if (sys_stderr) { PyFile_WriteString("*** ImageWin: error in ", sys_stderr); - PyFile_WriteString((char*) handler, sys_stderr); + PyFile_WriteString((char *)handler, sys_stderr); PyFile_WriteString(":\n", sys_stderr); } @@ -568,109 +567,119 @@ callback_error(const char* handler) } static LRESULT CALLBACK -windowCallback(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam) -{ +windowCallback(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; - PyObject* callback = NULL; - PyObject* result; - PyThreadState* threadstate; - PyThreadState* current_threadstate; + PyObject *callback = NULL; + PyObject *result; + PyThreadState *threadstate; + PyThreadState *current_threadstate; HDC dc; RECT rect; LRESULT status = 0; /* set up threadstate for messages that calls back into python */ switch (message) { - case WM_CREATE: - mainloop++; - break; - case WM_DESTROY: - mainloop--; - /* fall through... */ - case WM_PAINT: - case WM_SIZE: - callback = (PyObject*) GetWindowLongPtr(wnd, 0); - if (callback) { - threadstate = (PyThreadState*) - GetWindowLongPtr(wnd, sizeof(PyObject*)); - current_threadstate = PyThreadState_Swap(NULL); - PyEval_RestoreThread(threadstate); - } else { - return DefWindowProc(wnd, message, wParam, lParam); - } + case WM_CREATE: + mainloop++; + break; + case WM_DESTROY: + mainloop--; + /* fall through... */ + case WM_PAINT: + case WM_SIZE: + callback = (PyObject *)GetWindowLongPtr(wnd, 0); + if (callback) { + threadstate = + (PyThreadState *)GetWindowLongPtr(wnd, sizeof(PyObject *)); + current_threadstate = PyThreadState_Swap(NULL); + PyEval_RestoreThread(threadstate); + } else { + return DefWindowProc(wnd, message, wParam, lParam); + } } /* process message */ switch (message) { + case WM_PAINT: + /* redraw (part of) window. this generates a WCK-style + damage/clear/repair cascade */ + BeginPaint(wnd, &ps); + dc = GetDC(wnd); + GetWindowRect(wnd, &rect); /* in screen coordinates */ - case WM_PAINT: - /* redraw (part of) window. this generates a WCK-style - damage/clear/repair cascade */ - BeginPaint(wnd, &ps); - dc = GetDC(wnd); - GetWindowRect(wnd, &rect); /* in screen coordinates */ + result = PyObject_CallFunction( + callback, + "siiii", + "damage", + ps.rcPaint.left, + ps.rcPaint.top, + ps.rcPaint.right, + ps.rcPaint.bottom); + if (result) { + Py_DECREF(result); + } else { + callback_error("window damage callback"); + } - result = PyObject_CallFunction( - callback, "siiii", "damage", - ps.rcPaint.left, ps.rcPaint.top, - ps.rcPaint.right, ps.rcPaint.bottom - ); - if (result) { - Py_DECREF(result); - } else { - callback_error("window damage callback"); - } + result = PyObject_CallFunction( + callback, + "s" F_HANDLE "iiii", + "clear", + dc, + 0, + 0, + rect.right - rect.left, + rect.bottom - rect.top); + if (result) { + Py_DECREF(result); + } else { + callback_error("window clear callback"); + } - result = PyObject_CallFunction( - callback, "s" F_HANDLE "iiii", "clear", dc, - 0, 0, rect.right-rect.left, rect.bottom-rect.top - ); - if (result) { - Py_DECREF(result); - } else { - callback_error("window clear callback"); - } + result = PyObject_CallFunction( + callback, + "s" F_HANDLE "iiii", + "repair", + dc, + 0, + 0, + rect.right - rect.left, + rect.bottom - rect.top); + if (result) { + Py_DECREF(result); + } else { + callback_error("window repair callback"); + } - result = PyObject_CallFunction( - callback, "s" F_HANDLE "iiii", "repair", dc, - 0, 0, rect.right-rect.left, rect.bottom-rect.top - ); - if (result) { - Py_DECREF(result); - } else { - callback_error("window repair callback"); - } + ReleaseDC(wnd, dc); + EndPaint(wnd, &ps); + break; - ReleaseDC(wnd, dc); - EndPaint(wnd, &ps); - break; + case WM_SIZE: + /* resize window */ + result = PyObject_CallFunction( + callback, "sii", "resize", LOWORD(lParam), HIWORD(lParam)); + if (result) { + InvalidateRect(wnd, NULL, 1); + Py_DECREF(result); + } else { + callback_error("window resize callback"); + } + break; - case WM_SIZE: - /* resize window */ - result = PyObject_CallFunction( - callback, "sii", "resize", LOWORD(lParam), HIWORD(lParam) - ); - if (result) { - InvalidateRect(wnd, NULL, 1); - Py_DECREF(result); - } else { - callback_error("window resize callback"); - } - break; + case WM_DESTROY: + /* destroy window */ + result = PyObject_CallFunction(callback, "s", "destroy"); + if (result) { + Py_DECREF(result); + } else { + callback_error("window destroy callback"); + } + Py_DECREF(callback); + break; - case WM_DESTROY: - /* destroy window */ - result = PyObject_CallFunction(callback, "s", "destroy"); - if (result) { - Py_DECREF(result); - } else { - callback_error("window destroy callback"); - } - Py_DECREF(callback); - break; - - default: - status = DefWindowProc(wnd, message, wParam, lParam); + default: + status = DefWindowProc(wnd, message, wParam, lParam); } if (callback) { @@ -682,14 +691,13 @@ windowCallback(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam) return status; } -PyObject* -PyImaging_CreateWindowWin32(PyObject* self, PyObject* args) -{ +PyObject * +PyImaging_CreateWindowWin32(PyObject *self, PyObject *args) { HWND wnd; WNDCLASS windowClass; - char* title; - PyObject* callback; + char *title; + PyObject *callback; int width = 0, height = 0; if (!PyArg_ParseTuple(args, "sO|ii", &title, &callback, &width, &height)) { return NULL; @@ -705,7 +713,7 @@ PyImaging_CreateWindowWin32(PyObject* self, PyObject* args) /* register toplevel window class */ windowClass.style = CS_CLASSDC; windowClass.cbClsExtra = 0; - windowClass.cbWndExtra = sizeof(PyObject*) + sizeof(PyThreadState*); + windowClass.cbWndExtra = sizeof(PyObject *) + sizeof(PyThreadState *); windowClass.hInstance = GetModuleHandle(NULL); /* windowClass.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); */ windowClass.hbrBackground = NULL; @@ -718,11 +726,18 @@ PyImaging_CreateWindowWin32(PyObject* self, PyObject* args) RegisterClass(&windowClass); /* FIXME: check return status */ wnd = CreateWindowEx( - 0, windowClass.lpszClassName, title, + 0, + windowClass.lpszClassName, + title, WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, CW_USEDEFAULT, width, height, - HWND_DESKTOP, NULL, NULL, NULL - ); + CW_USEDEFAULT, + CW_USEDEFAULT, + width, + height, + HWND_DESKTOP, + NULL, + NULL, + NULL); if (!wnd) { PyErr_SetString(PyExc_OSError, "failed to create window"); @@ -731,76 +746,76 @@ PyImaging_CreateWindowWin32(PyObject* self, PyObject* args) /* register window callback */ Py_INCREF(callback); - SetWindowLongPtr(wnd, 0, (LONG_PTR) callback); - SetWindowLongPtr(wnd, sizeof(callback), (LONG_PTR) PyThreadState_Get()); + SetWindowLongPtr(wnd, 0, (LONG_PTR)callback); + SetWindowLongPtr(wnd, sizeof(callback), (LONG_PTR)PyThreadState_Get()); - Py_BEGIN_ALLOW_THREADS - ShowWindow(wnd, SW_SHOWNORMAL); + Py_BEGIN_ALLOW_THREADS ShowWindow(wnd, SW_SHOWNORMAL); SetForegroundWindow(wnd); /* to make sure it's visible */ Py_END_ALLOW_THREADS - return Py_BuildValue(F_HANDLE, wnd); + return Py_BuildValue(F_HANDLE, wnd); } -PyObject* -PyImaging_EventLoopWin32(PyObject* self, PyObject* args) -{ +PyObject * +PyImaging_EventLoopWin32(PyObject *self, PyObject *args) { MSG msg; - Py_BEGIN_ALLOW_THREADS - while (mainloop && GetMessage(&msg, NULL, 0, 0)) { + Py_BEGIN_ALLOW_THREADS while (mainloop && GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } Py_END_ALLOW_THREADS - Py_INCREF(Py_None); + Py_INCREF(Py_None); return Py_None; } /* -------------------------------------------------------------------- */ /* windows WMF renderer */ -#define GET32(p,o) ((DWORD*)(p+o))[0] +#define GET32(p, o) ((DWORD *)(p + o))[0] PyObject * -PyImaging_DrawWmf(PyObject* self, PyObject* args) -{ +PyImaging_DrawWmf(PyObject *self, PyObject *args) { HBITMAP bitmap; HENHMETAFILE meta; BITMAPCOREHEADER core; HDC dc; RECT rect; - PyObject* buffer = NULL; - char* ptr; + PyObject *buffer = NULL; + char *ptr; - char* data; + char *data; Py_ssize_t datasize; int width, height; int x0, y0, x1, y1; - if (!PyArg_ParseTuple(args, "y#(ii)(iiii):_load", &data, &datasize, - &width, &height, &x0, &x1, &y0, &y1)) { + if (!PyArg_ParseTuple( + args, + "y#(ii)(iiii):_load", + &data, + &datasize, + &width, + &height, + &x0, + &x1, + &y0, + &y1)) { return NULL; } /* step 1: copy metafile contents into METAFILE object */ if (datasize > 22 && GET32(data, 0) == 0x9ac6cdd7) { - /* placeable windows metafile (22-byte aldus header) */ - meta = SetWinMetaFileBits(datasize-22, data+22, NULL, NULL); - - } else if (datasize > 80 && GET32(data, 0) == 1 && - GET32(data, 40) == 0x464d4520) { + meta = SetWinMetaFileBits(datasize - 22, data + 22, NULL, NULL); + } else if (datasize > 80 && GET32(data, 0) == 1 && GET32(data, 40) == 0x464d4520) { /* enhanced metafile */ meta = SetEnhMetaFileBits(datasize, data); } else { - /* unknown meta format */ meta = NULL; - } if (!meta) { @@ -818,9 +833,7 @@ PyImaging_DrawWmf(PyObject* self, PyObject* args) dc = CreateCompatibleDC(NULL); - bitmap = CreateDIBSection( - dc, (BITMAPINFO*) &core, DIB_RGB_COLORS, &ptr, NULL, 0 - ); + bitmap = CreateDIBSection(dc, (BITMAPINFO *)&core, DIB_RGB_COLORS, &ptr, NULL, 0); if (!bitmap) { PyErr_SetString(PyExc_OSError, "cannot create bitmap"); @@ -850,7 +863,7 @@ PyImaging_DrawWmf(PyObject* self, PyObject* args) GdiFlush(); - buffer = PyBytes_FromStringAndSize(ptr, height * ((width*3 + 3) & -4)); + buffer = PyBytes_FromStringAndSize(ptr, height * ((width * 3 + 3) & -4)); error: DeleteEnhMetaFile(meta); @@ -875,18 +888,17 @@ error: /* -------------------------------------------------------------------- */ /* X11 screen grabber */ -PyObject* -PyImaging_GrabScreenX11(PyObject* self, PyObject* args) -{ +PyObject * +PyImaging_GrabScreenX11(PyObject *self, PyObject *args) { int width, height; - char* display_name; - xcb_connection_t* connection; + char *display_name; + xcb_connection_t *connection; int screen_number; xcb_screen_iterator_t iter; - xcb_screen_t* screen = NULL; - xcb_get_image_reply_t* reply; - xcb_generic_error_t* error; - PyObject* buffer = NULL; + xcb_screen_t *screen = NULL; + xcb_get_image_reply_t *reply; + xcb_generic_error_t *error; + PyObject *buffer = NULL; if (!PyArg_ParseTuple(args, "|z", &display_name)) { return NULL; @@ -896,7 +908,10 @@ PyImaging_GrabScreenX11(PyObject* self, PyObject* args) connection = xcb_connect(display_name, &screen_number); if (xcb_connection_has_error(connection)) { - PyErr_Format(PyExc_OSError, "X connection failed: error %i", xcb_connection_has_error(connection)); + PyErr_Format( + PyExc_OSError, + "X connection failed: error %i", + xcb_connection_has_error(connection)); xcb_disconnect(connection); return NULL; } @@ -920,13 +935,26 @@ PyImaging_GrabScreenX11(PyObject* self, PyObject* args) /* get image data */ - reply = xcb_get_image_reply(connection, - xcb_get_image(connection, XCB_IMAGE_FORMAT_Z_PIXMAP, screen->root, - 0, 0, width, height, 0x00ffffff), - &error); + reply = xcb_get_image_reply( + connection, + xcb_get_image( + connection, + XCB_IMAGE_FORMAT_Z_PIXMAP, + screen->root, + 0, + 0, + width, + height, + 0x00ffffff), + &error); if (reply == NULL) { - PyErr_Format(PyExc_OSError, "X get_image failed: error %i (%i, %i, %i)", - error->error_code, error->major_code, error->minor_code, error->resource_id); + PyErr_Format( + PyExc_OSError, + "X get_image failed: error %i (%i, %i, %i)", + error->error_code, + error->major_code, + error->minor_code, + error->resource_id); free(error); xcb_disconnect(connection); return NULL; @@ -935,8 +963,8 @@ PyImaging_GrabScreenX11(PyObject* self, PyObject* args) /* store data in Python buffer */ if (reply->depth == 24) { - buffer = PyBytes_FromStringAndSize((char*)xcb_get_image_data(reply), - xcb_get_image_data_length(reply)); + buffer = PyBytes_FromStringAndSize( + (char *)xcb_get_image_data(reply), xcb_get_image_data_length(reply)); } else { PyErr_Format(PyExc_OSError, "unsupported bit depth: %i", reply->depth); } diff --git a/src/encode.c b/src/encode.c index 57ce42734..f92ba62c2 100644 --- a/src/encode.c +++ b/src/encode.c @@ -37,25 +37,23 @@ /* -------------------------------------------------------------------- */ typedef struct { - PyObject_HEAD - int (*encode)(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); + PyObject_HEAD int (*encode)( + Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); int (*cleanup)(ImagingCodecState state); struct ImagingCodecStateInstance state; Imaging im; - PyObject* lock; + PyObject *lock; int pushes_fd; } ImagingEncoderObject; static PyTypeObject ImagingEncoderType; -static ImagingEncoderObject* -PyImaging_EncoderNew(int contextsize) -{ +static ImagingEncoderObject * +PyImaging_EncoderNew(int contextsize) { ImagingEncoderObject *encoder; void *context; - if(PyType_Ready(&ImagingEncoderType) < 0) { + if (PyType_Ready(&ImagingEncoderType) < 0) { return NULL; } @@ -69,10 +67,10 @@ PyImaging_EncoderNew(int contextsize) /* Allocate encoder context */ if (contextsize > 0) { - context = (void*) calloc(1, contextsize); + context = (void *)calloc(1, contextsize); if (!context) { Py_DECREF(encoder); - (void) ImagingError_MemoryError(); + (void)ImagingError_MemoryError(); return NULL; } } else { @@ -94,8 +92,7 @@ PyImaging_EncoderNew(int contextsize) } static void -_dealloc(ImagingEncoderObject* encoder) -{ +_dealloc(ImagingEncoderObject *encoder) { if (encoder->cleanup) { encoder->cleanup(&encoder->state); } @@ -106,23 +103,21 @@ _dealloc(ImagingEncoderObject* encoder) PyObject_Del(encoder); } -static PyObject* -_encode_cleanup(ImagingEncoderObject* encoder, PyObject* args) -{ +static PyObject * +_encode_cleanup(ImagingEncoderObject *encoder, PyObject *args) { int status = 0; - if (encoder->cleanup){ + if (encoder->cleanup) { status = encoder->cleanup(&encoder->state); } return Py_BuildValue("i", status); } -static PyObject* -_encode(ImagingEncoderObject* encoder, PyObject* args) -{ - PyObject* buf; - PyObject* result; +static PyObject * +_encode(ImagingEncoderObject *encoder, PyObject *args) { + PyObject *buf; + PyObject *result; int status; /* Encode to a Python string (allocated by this method) */ @@ -138,8 +133,8 @@ _encode(ImagingEncoderObject* encoder, PyObject* args) return NULL; } - status = encoder->encode(encoder->im, &encoder->state, - (UINT8*) PyBytes_AsString(buf), bufsize); + status = encoder->encode( + encoder->im, &encoder->state, (UINT8 *)PyBytes_AsString(buf), bufsize); /* adjust string length to avoid slicing in encoder */ if (_PyBytes_Resize(&buf, (status > 0) ? status : 0) < 0) { @@ -153,31 +148,28 @@ _encode(ImagingEncoderObject* encoder, PyObject* args) return result; } -static PyObject* -_encode_to_pyfd(ImagingEncoderObject* encoder, PyObject* args) -{ - +static PyObject * +_encode_to_pyfd(ImagingEncoderObject *encoder, PyObject *args) { PyObject *result; int status; if (!encoder->pushes_fd) { // UNDONE, appropriate errcode??? - result = Py_BuildValue("ii", 0, IMAGING_CODEC_CONFIG);; + result = Py_BuildValue("ii", 0, IMAGING_CODEC_CONFIG); + ; return result; } - status = encoder->encode(encoder->im, &encoder->state, - (UINT8*) NULL, 0); + status = encoder->encode(encoder->im, &encoder->state, (UINT8 *)NULL, 0); result = Py_BuildValue("ii", status, encoder->state.errcode); return result; } -static PyObject* -_encode_to_file(ImagingEncoderObject* encoder, PyObject* args) -{ - UINT8* buf; +static PyObject * +_encode_to_file(ImagingEncoderObject *encoder, PyObject *args) { + UINT8 *buf; int status; ImagingSectionCookie cookie; @@ -192,7 +184,7 @@ _encode_to_file(ImagingEncoderObject* encoder, PyObject* args) /* Allocate an encoder buffer */ /* malloc check ok, either constant int, or checked by PyArg_ParseTuple */ - buf = (UINT8*) malloc(bufsize); + buf = (UINT8 *)malloc(bufsize); if (!buf) { return ImagingError_MemoryError(); } @@ -200,7 +192,6 @@ _encode_to_file(ImagingEncoderObject* encoder, PyObject* args) ImagingSectionEnter(&cookie); do { - /* This replaces the inner loop in the ImageFile _save function. */ @@ -223,12 +214,12 @@ _encode_to_file(ImagingEncoderObject* encoder, PyObject* args) return Py_BuildValue("i", encoder->state.errcode); } -extern Imaging PyImaging_AsImaging(PyObject *op); +extern Imaging +PyImaging_AsImaging(PyObject *op); -static PyObject* -_setimage(ImagingEncoderObject* encoder, PyObject* args) -{ - PyObject* op; +static PyObject * +_setimage(ImagingEncoderObject *encoder, PyObject *args) { + PyObject *op; Imaging im; ImagingCodecState state; Py_ssize_t x0, y0, x1, y1; @@ -260,22 +251,20 @@ _setimage(ImagingEncoderObject* encoder, PyObject* args) state->ysize = y1 - y0; } - if (state->xsize <= 0 || - state->xsize + state->xoff > im->xsize || - state->ysize <= 0 || - state->ysize + state->yoff > im->ysize) { + if (state->xsize <= 0 || state->xsize + state->xoff > im->xsize || + state->ysize <= 0 || state->ysize + state->yoff > im->ysize) { PyErr_SetString(PyExc_SystemError, "tile cannot extend outside image"); return NULL; } /* Allocate memory buffer (if bits field is set) */ if (state->bits > 0) { - if (state->xsize > ((INT_MAX / state->bits)-7)) { + if (state->xsize > ((INT_MAX / state->bits) - 7)) { return ImagingError_MemoryError(); } - state->bytes = (state->bits * state->xsize+7)/8; + state->bytes = (state->bits * state->xsize + 7) / 8; /* malloc check ok, overflow checked above */ - state->buffer = (UINT8*) malloc(state->bytes); + state->buffer = (UINT8 *)malloc(state->bytes); if (!state->buffer) { return ImagingError_MemoryError(); } @@ -291,10 +280,9 @@ _setimage(ImagingEncoderObject* encoder, PyObject* args) return Py_None; } -static PyObject* -_setfd(ImagingEncoderObject* encoder, PyObject* args) -{ - PyObject* fd; +static PyObject * +_setfd(ImagingEncoderObject *encoder, PyObject *args) { + PyObject *fd; ImagingCodecState state; if (!PyArg_ParseTuple(args, "O", &fd)) { @@ -311,8 +299,7 @@ _setfd(ImagingEncoderObject* encoder, PyObject* args) } static PyObject * -_get_pushes_fd(ImagingEncoderObject *encoder) -{ +_get_pushes_fd(ImagingEncoderObject *encoder) { return PyBool_FromLong(encoder->pushes_fd); } @@ -327,52 +314,51 @@ static struct PyMethodDef methods[] = { }; static struct PyGetSetDef getseters[] = { - {"pushes_fd", (getter)_get_pushes_fd, NULL, + {"pushes_fd", + (getter)_get_pushes_fd, + NULL, "True if this decoder expects to push directly to self.fd", NULL}, {NULL, NULL, NULL, NULL, NULL} /* sentinel */ }; static PyTypeObject ImagingEncoderType = { - PyVarObject_HEAD_INIT(NULL, 0) - "ImagingEncoder", /*tp_name*/ - sizeof(ImagingEncoderObject), /*tp_size*/ - 0, /*tp_itemsize*/ + PyVarObject_HEAD_INIT(NULL, 0) "ImagingEncoder", /*tp_name*/ + sizeof(ImagingEncoderObject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - (destructor)_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - methods, /*tp_methods*/ - 0, /*tp_members*/ - getseters, /*tp_getset*/ + (destructor)_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + methods, /*tp_methods*/ + 0, /*tp_members*/ + getseters, /*tp_getset*/ }; /* -------------------------------------------------------------------- */ int -get_packer(ImagingEncoderObject* encoder, const char* mode, - const char* rawmode) -{ +get_packer(ImagingEncoderObject *encoder, const char *mode, const char *rawmode) { int bits; ImagingShuffler pack; @@ -389,15 +375,13 @@ get_packer(ImagingEncoderObject* encoder, const char* mode, return 0; } - /* -------------------------------------------------------------------- */ /* EPS */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_EpsEncoderNew(PyObject* self, PyObject* args) -{ - ImagingEncoderObject* encoder; +PyObject * +PyImaging_EpsEncoderNew(PyObject *self, PyObject *args) { + ImagingEncoderObject *encoder; encoder = PyImaging_EncoderNew(0); if (encoder == NULL) { @@ -406,18 +390,16 @@ PyImaging_EpsEncoderNew(PyObject* self, PyObject* args) encoder->encode = ImagingEpsEncode; - return (PyObject*) encoder; + return (PyObject *)encoder; } - /* -------------------------------------------------------------------- */ /* GIF */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_GifEncoderNew(PyObject* self, PyObject* args) -{ - ImagingEncoderObject* encoder; +PyObject * +PyImaging_GifEncoderNew(PyObject *self, PyObject *args) { + ImagingEncoderObject *encoder; char *mode; char *rawmode; @@ -438,21 +420,19 @@ PyImaging_GifEncoderNew(PyObject* self, PyObject* args) encoder->encode = ImagingGifEncode; - ((GIFENCODERSTATE*)encoder->state.context)->bits = bits; - ((GIFENCODERSTATE*)encoder->state.context)->interlace = interlace; + ((GIFENCODERSTATE *)encoder->state.context)->bits = bits; + ((GIFENCODERSTATE *)encoder->state.context)->interlace = interlace; - return (PyObject*) encoder; + return (PyObject *)encoder; } - /* -------------------------------------------------------------------- */ /* PCX */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_PcxEncoderNew(PyObject* self, PyObject* args) -{ - ImagingEncoderObject* encoder; +PyObject * +PyImaging_PcxEncoderNew(PyObject *self, PyObject *args) { + ImagingEncoderObject *encoder; char *mode; char *rawmode; @@ -473,18 +453,16 @@ PyImaging_PcxEncoderNew(PyObject* self, PyObject* args) encoder->encode = ImagingPcxEncode; - return (PyObject*) encoder; + return (PyObject *)encoder; } - /* -------------------------------------------------------------------- */ /* RAW */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_RawEncoderNew(PyObject* self, PyObject* args) -{ - ImagingEncoderObject* encoder; +PyObject * +PyImaging_RawEncoderNew(PyObject *self, PyObject *args) { + ImagingEncoderObject *encoder; char *mode; char *rawmode; @@ -509,18 +487,16 @@ PyImaging_RawEncoderNew(PyObject* self, PyObject* args) encoder->state.ystep = ystep; encoder->state.count = stride; - return (PyObject*) encoder; + return (PyObject *)encoder; } - /* -------------------------------------------------------------------- */ /* TGA */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_TgaRleEncoderNew(PyObject* self, PyObject* args) -{ - ImagingEncoderObject* encoder; +PyObject * +PyImaging_TgaRleEncoderNew(PyObject *self, PyObject *args) { + ImagingEncoderObject *encoder; char *mode; char *rawmode; @@ -543,19 +519,16 @@ PyImaging_TgaRleEncoderNew(PyObject* self, PyObject* args) encoder->state.ystep = ystep; - return (PyObject*) encoder; + return (PyObject *)encoder; } - - /* -------------------------------------------------------------------- */ /* XBM */ /* -------------------------------------------------------------------- */ -PyObject* -PyImaging_XbmEncoderNew(PyObject* self, PyObject* args) -{ - ImagingEncoderObject* encoder; +PyObject * +PyImaging_XbmEncoderNew(PyObject *self, PyObject *args) { + ImagingEncoderObject *encoder; encoder = PyImaging_EncoderNew(0); if (encoder == NULL) { @@ -568,10 +541,9 @@ PyImaging_XbmEncoderNew(PyObject* self, PyObject* args) encoder->encode = ImagingXbmEncode; - return (PyObject*) encoder; + return (PyObject *)encoder; } - /* -------------------------------------------------------------------- */ /* ZIP */ /* -------------------------------------------------------------------- */ @@ -580,29 +552,34 @@ PyImaging_XbmEncoderNew(PyObject* self, PyObject* args) #include "libImaging/ZipCodecs.h" -PyObject* -PyImaging_ZipEncoderNew(PyObject* self, PyObject* args) -{ - ImagingEncoderObject* encoder; +PyObject * +PyImaging_ZipEncoderNew(PyObject *self, PyObject *args) { + ImagingEncoderObject *encoder; - char* mode; - char* rawmode; + char *mode; + char *rawmode; Py_ssize_t optimize = 0; Py_ssize_t compress_level = -1; Py_ssize_t compress_type = -1; - char* dictionary = NULL; + char *dictionary = NULL; Py_ssize_t dictionary_size = 0; - if (!PyArg_ParseTuple(args, "ss|nnny#", &mode, &rawmode, - &optimize, - &compress_level, &compress_type, - &dictionary, &dictionary_size)) { + if (!PyArg_ParseTuple( + args, + "ss|nnny#", + &mode, + &rawmode, + &optimize, + &compress_level, + &compress_type, + &dictionary, + &dictionary_size)) { return NULL; } /* Copy to avoid referencing Python's memory */ if (dictionary && dictionary_size > 0) { /* malloc check ok, size comes from PyArg_ParseTuple */ - char* p = malloc(dictionary_size); + char *p = malloc(dictionary_size); if (!p) { return ImagingError_MemoryError(); } @@ -628,20 +605,19 @@ PyImaging_ZipEncoderNew(PyObject* self, PyObject* args) if (rawmode[0] == 'P') { /* disable filtering */ - ((ZIPSTATE*)encoder->state.context)->mode = ZIP_PNG_PALETTE; + ((ZIPSTATE *)encoder->state.context)->mode = ZIP_PNG_PALETTE; } - ((ZIPSTATE*)encoder->state.context)->optimize = optimize; - ((ZIPSTATE*)encoder->state.context)->compress_level = compress_level; - ((ZIPSTATE*)encoder->state.context)->compress_type = compress_type; - ((ZIPSTATE*)encoder->state.context)->dictionary = dictionary; - ((ZIPSTATE*)encoder->state.context)->dictionary_size = dictionary_size; + ((ZIPSTATE *)encoder->state.context)->optimize = optimize; + ((ZIPSTATE *)encoder->state.context)->compress_level = compress_level; + ((ZIPSTATE *)encoder->state.context)->compress_type = compress_type; + ((ZIPSTATE *)encoder->state.context)->dictionary = dictionary; + ((ZIPSTATE *)encoder->state.context)->dictionary_size = dictionary_size; - return (PyObject*) encoder; + return (PyObject *)encoder; } #endif - /* -------------------------------------------------------------------- */ /* LibTiff */ /* -------------------------------------------------------------------- */ @@ -652,15 +628,14 @@ PyImaging_ZipEncoderNew(PyObject* self, PyObject* args) #include -PyObject* -PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) -{ - ImagingEncoderObject* encoder; +PyObject * +PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) { + ImagingEncoderObject *encoder; - char* mode; - char* rawmode; - char* compname; - char* filename; + char *mode; + char *rawmode; + char *compname; + char *filename; Py_ssize_t fp; PyObject *tags, *types; @@ -669,16 +644,24 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) int key_int, status, is_core_tag, is_var_length, num_core_tags, i; TIFFDataType type = TIFF_NOTYPE; // This list also exists in TiffTags.py - const int core_tags[] = { - 256, 257, 258, 259, 262, 263, 266, 269, 274, 277, 278, 280, 281, 340, - 341, 282, 283, 284, 286, 287, 296, 297, 320, 321, 338, 32995, 32998, 32996, - 339, 32997, 330, 531, 530, 65537 - }; + const int core_tags[] = {256, 257, 258, 259, 262, 263, 266, 269, 274, + 277, 278, 280, 281, 340, 341, 282, 283, 284, + 286, 287, 296, 297, 320, 321, 338, 32995, 32998, + 32996, 339, 32997, 330, 531, 530, 65537}; Py_ssize_t tags_size; PyObject *item; - if (! PyArg_ParseTuple(args, "sssnsOO", &mode, &rawmode, &compname, &fp, &filename, &tags, &types)) { + if (!PyArg_ParseTuple( + args, + "sssnsOO", + &mode, + &rawmode, + &compname, + &fp, + &filename, + &tags, + &types)) { return NULL; } @@ -688,11 +671,11 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) } else { tags_size = PyList_Size(tags); TRACE(("tags size: %d\n", (int)tags_size)); - for (pos=0;posstate, filename, fp)) { + if (!ImagingLibTiffEncodeInit(&encoder->state, filename, fp)) { Py_DECREF(encoder); PyErr_SetString(PyExc_RuntimeError, "tiff codec initialization failed"); return NULL; @@ -731,7 +714,7 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) is_var_length = 0; type = TIFF_NOTYPE; - for (i=0; istate, type, key_int, is_var_length)) { + if (ImagingLibTiffMergeFieldInfo( + &encoder->state, type, key_int, is_var_length)) { continue; } } if (type == TIFF_BYTE || type == TIFF_UNDEFINED) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - PyBytes_Size(value), PyBytes_AsString(value)); + status = ImagingLibTiffSetField( + &encoder->state, + (ttag_t)key_int, + PyBytes_Size(value), + PyBytes_AsString(value)); } else if (is_var_length) { - Py_ssize_t len,i; + Py_ssize_t len, i; TRACE(("Setting from Tuple: %d \n", key_int)); len = PyTuple_Size(value); if (key_int == TIFFTAG_COLORMAP) { int stride = 256; if (len != 768) { - PyErr_SetString(PyExc_ValueError, "Requiring 768 items for for Colormap"); + PyErr_SetString( + PyExc_ValueError, "Requiring 768 items for for Colormap"); return NULL; } UINT16 *av; /* malloc check ok, calloc checks for overflow */ av = calloc(len, sizeof(UINT16)); if (av) { - for (i=0;istate, (ttag_t) key_int, - av, - av + stride, - av + stride * 2); + status = ImagingLibTiffSetField( + &encoder->state, + (ttag_t)key_int, + av, + av + stride, + av + stride * 2); free(av); } } else if (type == TIFF_SHORT) { @@ -825,10 +813,11 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) /* malloc check ok, calloc checks for overflow */ av = calloc(len, sizeof(UINT16)); if (av) { - for (i=0;istate, (ttag_t) key_int, len, av); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, len, av); free(av); } } else if (type == TIFF_LONG) { @@ -836,10 +825,11 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) /* malloc check ok, calloc checks for overflow */ av = calloc(len, sizeof(UINT32)); if (av) { - for (i=0;istate, (ttag_t) key_int, len, av); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, len, av); free(av); } } else if (type == TIFF_SBYTE) { @@ -847,10 +837,11 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) /* malloc check ok, calloc checks for overflow */ av = calloc(len, sizeof(INT8)); if (av) { - for (i=0;istate, (ttag_t) key_int, len, av); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, len, av); free(av); } } else if (type == TIFF_SSHORT) { @@ -858,10 +849,11 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) /* malloc check ok, calloc checks for overflow */ av = calloc(len, sizeof(INT16)); if (av) { - for (i=0;istate, (ttag_t) key_int, len, av); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, len, av); free(av); } } else if (type == TIFF_SLONG) { @@ -869,10 +861,11 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) /* malloc check ok, calloc checks for overflow */ av = calloc(len, sizeof(INT32)); if (av) { - for (i=0;istate, (ttag_t) key_int, len, av); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, len, av); free(av); } } else if (type == TIFF_FLOAT) { @@ -880,10 +873,11 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) /* malloc check ok, calloc checks for overflow */ av = calloc(len, sizeof(FLOAT32)); if (av) { - for (i=0;istate, (ttag_t) key_int, len, av); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, len, av); free(av); } } else if (type == TIFF_DOUBLE) { @@ -891,54 +885,47 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) /* malloc check ok, calloc checks for overflow */ av = calloc(len, sizeof(FLOAT64)); if (av) { - for (i=0;istate, (ttag_t) key_int, len, av); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, len, av); free(av); } } } else { if (type == TIFF_SHORT) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - (UINT16)PyLong_AsLong(value)); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, (UINT16)PyLong_AsLong(value)); } else if (type == TIFF_LONG) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - (UINT32)PyLong_AsLong(value)); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, (UINT32)PyLong_AsLong(value)); } else if (type == TIFF_SSHORT) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - (INT16)PyLong_AsLong(value)); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, (INT16)PyLong_AsLong(value)); } else if (type == TIFF_SLONG) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - (INT32)PyLong_AsLong(value)); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, (INT32)PyLong_AsLong(value)); } else if (type == TIFF_FLOAT) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - (FLOAT32)PyFloat_AsDouble(value)); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, (FLOAT32)PyFloat_AsDouble(value)); } else if (type == TIFF_DOUBLE) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - (FLOAT64)PyFloat_AsDouble(value)); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, (FLOAT64)PyFloat_AsDouble(value)); } else if (type == TIFF_SBYTE) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - (INT8)PyLong_AsLong(value)); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, (INT8)PyLong_AsLong(value)); } else if (type == TIFF_ASCII) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - PyBytes_AsString(value)); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, PyBytes_AsString(value)); } else if (type == TIFF_RATIONAL) { - status = ImagingLibTiffSetField(&encoder->state, - (ttag_t) key_int, - (FLOAT64)PyFloat_AsDouble(value)); + status = ImagingLibTiffSetField( + &encoder->state, (ttag_t)key_int, (FLOAT64)PyFloat_AsDouble(value)); } else { - TRACE(("Unhandled type for key %d : %s \n", - key_int, - PyBytes_AsString(PyObject_Str(value)))); + TRACE( + ("Unhandled type for key %d : %s \n", + key_int, + PyBytes_AsString(PyObject_Str(value)))); } } if (!status) { @@ -949,9 +936,9 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) } } - encoder->encode = ImagingLibTiffEncode; + encoder->encode = ImagingLibTiffEncode; - return (PyObject*) encoder; + return (PyObject *)encoder; } #endif @@ -965,26 +952,27 @@ PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args) /* We better define this encoder last in this file, so the following undef's won't mess things up for the Imaging library proper. */ -#undef HAVE_PROTOTYPES -#undef HAVE_STDDEF_H -#undef HAVE_STDLIB_H -#undef UINT8 -#undef UINT16 -#undef UINT32 -#undef INT8 -#undef INT16 -#undef INT32 +#undef HAVE_PROTOTYPES +#undef HAVE_STDDEF_H +#undef HAVE_STDLIB_H +#undef UINT8 +#undef UINT16 +#undef UINT32 +#undef INT8 +#undef INT16 +#undef INT32 #include "libImaging/Jpeg.h" -static unsigned int* get_qtables_arrays(PyObject* qtables, int* qtablesLen) { - PyObject* tables; - PyObject* table; - PyObject* table_data; +static unsigned int * +get_qtables_arrays(PyObject *qtables, int *qtablesLen) { + PyObject *tables; + PyObject *table; + PyObject *table_data; int i, j, num_tables; unsigned int *qarrays; - if ((qtables == NULL) || (qtables == Py_None)) { + if ((qtables == NULL) || (qtables == Py_None)) { return NULL; } @@ -996,13 +984,14 @@ static unsigned int* get_qtables_arrays(PyObject* qtables, int* qtablesLen) { tables = PySequence_Fast(qtables, "expected a sequence"); num_tables = PySequence_Size(qtables); if (num_tables < 1 || num_tables > NUM_QUANT_TBLS) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString( + PyExc_ValueError, "Not a valid number of quantization tables. Should be between 1 and 4."); Py_DECREF(tables); return NULL; } /* malloc check ok, num_tables <4, DCTSIZE2 == 64 from jpeglib.h */ - qarrays = (unsigned int*) malloc(num_tables * DCTSIZE2 * sizeof(unsigned int)); + qarrays = (unsigned int *)malloc(num_tables * DCTSIZE2 * sizeof(unsigned int)); if (!qarrays) { Py_DECREF(tables); return ImagingError_MemoryError(); @@ -1019,7 +1008,8 @@ static unsigned int* get_qtables_arrays(PyObject* qtables, int* qtablesLen) { } table_data = PySequence_Fast(table, "expected a sequence"); for (j = 0; j < DCTSIZE2; j++) { - qarrays[i * DCTSIZE2 + j] = PyLong_AS_LONG(PySequence_Fast_GET_ITEM(table_data, j)); + qarrays[i * DCTSIZE2 + j] = + PyLong_AS_LONG(PySequence_Fast_GET_ITEM(table_data, j)); } Py_DECREF(table_data); } @@ -1037,10 +1027,9 @@ JPEG_QTABLES_ERR: return qarrays; } -PyObject* -PyImaging_JpegEncoderNew(PyObject* self, PyObject* args) -{ - ImagingEncoderObject* encoder; +PyObject * +PyImaging_JpegEncoderNew(PyObject *self, PyObject *args) { + ImagingEncoderObject *encoder; char *mode; char *rawmode; @@ -1051,19 +1040,32 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args) Py_ssize_t streamtype = 0; /* 0=interchange, 1=tables only, 2=image only */ Py_ssize_t xdpi = 0, ydpi = 0; Py_ssize_t subsampling = -1; /* -1=default, 0=none, 1=medium, 2=high */ - PyObject* qtables=NULL; + PyObject *qtables = NULL; unsigned int *qarrays = NULL; int qtablesLen = 0; - char* extra = NULL; + char *extra = NULL; Py_ssize_t extra_size; - char* rawExif = NULL; + char *rawExif = NULL; Py_ssize_t rawExifLen = 0; - if (!PyArg_ParseTuple(args, "ss|nnnnnnnnOy#y#", - &mode, &rawmode, &quality, - &progressive, &smooth, &optimize, &streamtype, - &xdpi, &ydpi, &subsampling, &qtables, &extra, &extra_size, - &rawExif, &rawExifLen)) { + if (!PyArg_ParseTuple( + args, + "ss|nnnnnnnnOy#y#", + &mode, + &rawmode, + &quality, + &progressive, + &smooth, + &optimize, + &streamtype, + &xdpi, + &ydpi, + &subsampling, + &qtables, + &extra, + &extra_size, + &rawExif, + &rawExifLen)) { return NULL; } @@ -1088,7 +1090,7 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args) if (extra && extra_size > 0) { /* malloc check ok, length is from python parsearg */ - char* p = malloc(extra_size); // Freed in JpegEncode, Case 5 + char *p = malloc(extra_size); // Freed in JpegEncode, Case 5 if (!p) { return ImagingError_MemoryError(); } @@ -1100,7 +1102,7 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args) if (rawExif && rawExifLen > 0) { /* malloc check ok, length is from python parsearg */ - char* pp = malloc(rawExifLen); // Freed in JpegEncode, Case 5 + char *pp = malloc(rawExifLen); // Freed in JpegEncode, Case 5 if (!pp) { if (extra) { free(extra); @@ -1115,29 +1117,28 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args) encoder->encode = ImagingJpegEncode; - strncpy(((JPEGENCODERSTATE*)encoder->state.context)->rawmode, rawmode, 8); + strncpy(((JPEGENCODERSTATE *)encoder->state.context)->rawmode, rawmode, 8); - ((JPEGENCODERSTATE*)encoder->state.context)->quality = quality; - ((JPEGENCODERSTATE*)encoder->state.context)->qtables = qarrays; - ((JPEGENCODERSTATE*)encoder->state.context)->qtablesLen = qtablesLen; - ((JPEGENCODERSTATE*)encoder->state.context)->subsampling = subsampling; - ((JPEGENCODERSTATE*)encoder->state.context)->progressive = progressive; - ((JPEGENCODERSTATE*)encoder->state.context)->smooth = smooth; - ((JPEGENCODERSTATE*)encoder->state.context)->optimize = optimize; - ((JPEGENCODERSTATE*)encoder->state.context)->streamtype = streamtype; - ((JPEGENCODERSTATE*)encoder->state.context)->xdpi = xdpi; - ((JPEGENCODERSTATE*)encoder->state.context)->ydpi = ydpi; - ((JPEGENCODERSTATE*)encoder->state.context)->extra = extra; - ((JPEGENCODERSTATE*)encoder->state.context)->extra_size = extra_size; - ((JPEGENCODERSTATE*)encoder->state.context)->rawExif = rawExif; - ((JPEGENCODERSTATE*)encoder->state.context)->rawExifLen = rawExifLen; + ((JPEGENCODERSTATE *)encoder->state.context)->quality = quality; + ((JPEGENCODERSTATE *)encoder->state.context)->qtables = qarrays; + ((JPEGENCODERSTATE *)encoder->state.context)->qtablesLen = qtablesLen; + ((JPEGENCODERSTATE *)encoder->state.context)->subsampling = subsampling; + ((JPEGENCODERSTATE *)encoder->state.context)->progressive = progressive; + ((JPEGENCODERSTATE *)encoder->state.context)->smooth = smooth; + ((JPEGENCODERSTATE *)encoder->state.context)->optimize = optimize; + ((JPEGENCODERSTATE *)encoder->state.context)->streamtype = streamtype; + ((JPEGENCODERSTATE *)encoder->state.context)->xdpi = xdpi; + ((JPEGENCODERSTATE *)encoder->state.context)->ydpi = ydpi; + ((JPEGENCODERSTATE *)encoder->state.context)->extra = extra; + ((JPEGENCODERSTATE *)encoder->state.context)->extra_size = extra_size; + ((JPEGENCODERSTATE *)encoder->state.context)->rawExif = rawExif; + ((JPEGENCODERSTATE *)encoder->state.context)->rawExifLen = rawExifLen; - return (PyObject*) encoder; + return (PyObject *)encoder; } #endif - /* -------------------------------------------------------------------- */ /* JPEG 2000 */ /* -------------------------------------------------------------------- */ @@ -1147,8 +1148,7 @@ PyImaging_JpegEncoderNew(PyObject* self, PyObject* args) #include "libImaging/Jpeg2K.h" static void -j2k_decode_coord_tuple(PyObject *tuple, int *x, int *y) -{ +j2k_decode_coord_tuple(PyObject *tuple, int *x, int *y) { *x = *y = 0; if (tuple && PyTuple_Check(tuple) && PyTuple_GET_SIZE(tuple) == 2) { @@ -1164,9 +1164,8 @@ j2k_decode_coord_tuple(PyObject *tuple, int *x, int *y) } } -PyObject* -PyImaging_Jpeg2KEncoderNew(PyObject *self, PyObject *args) -{ +PyObject * +PyImaging_Jpeg2KEncoderNew(PyObject *self, PyObject *args) { ImagingEncoderObject *encoder; JPEG2KENCODESTATE *context; @@ -1185,20 +1184,31 @@ PyImaging_Jpeg2KEncoderNew(PyObject *self, PyObject *args) OPJ_CINEMA_MODE cine_mode; Py_ssize_t fd = -1; - if (!PyArg_ParseTuple(args, "ss|OOOsOnOOOssn", &mode, &format, - &offset, &tile_offset, &tile_size, - &quality_mode, &quality_layers, &num_resolutions, - &cblk_size, &precinct_size, - &irreversible, &progression, &cinema_mode, - &fd)) { + if (!PyArg_ParseTuple( + args, + "ss|OOOsOnOOOssn", + &mode, + &format, + &offset, + &tile_offset, + &tile_size, + &quality_mode, + &quality_layers, + &num_resolutions, + &cblk_size, + &precinct_size, + &irreversible, + &progression, + &cinema_mode, + &fd)) { return NULL; } - if (strcmp (format, "j2k") == 0) { + if (strcmp(format, "j2k") == 0) { codec_format = OPJ_CODEC_J2K; - } else if (strcmp (format, "jpt") == 0) { + } else if (strcmp(format, "jpt") == 0) { codec_format = OPJ_CODEC_JPT; - } else if (strcmp (format, "jp2") == 0) { + } else if (strcmp(format, "jp2") == 0) { codec_format = OPJ_CODEC_JP2; } else { return NULL; @@ -1245,49 +1255,44 @@ PyImaging_Jpeg2KEncoderNew(PyObject *self, PyObject *args) context->format = codec_format; context->offset_x = context->offset_y = 0; - j2k_decode_coord_tuple(offset, &context->offset_x, &context->offset_y); - j2k_decode_coord_tuple(tile_offset, - &context->tile_offset_x, - &context->tile_offset_y); - j2k_decode_coord_tuple(tile_size, - &context->tile_size_x, - &context->tile_size_y); + j2k_decode_coord_tuple( + tile_offset, &context->tile_offset_x, &context->tile_offset_y); + j2k_decode_coord_tuple(tile_size, &context->tile_size_x, &context->tile_size_y); /* Error on illegal tile offsets */ if (context->tile_size_x && context->tile_size_y) { - if (context->tile_offset_x <= context->offset_x - context->tile_size_x - || context->tile_offset_y <= context->offset_y - context->tile_size_y) { - PyErr_SetString(PyExc_ValueError, - "JPEG 2000 tile offset too small; top left tile must " - "intersect image area"); + if (context->tile_offset_x <= context->offset_x - context->tile_size_x || + context->tile_offset_y <= context->offset_y - context->tile_size_y) { + PyErr_SetString( + PyExc_ValueError, + "JPEG 2000 tile offset too small; top left tile must " + "intersect image area"); Py_DECREF(encoder); return NULL; } - if (context->tile_offset_x > context->offset_x - || context->tile_offset_y > context->offset_y) { - PyErr_SetString(PyExc_ValueError, - "JPEG 2000 tile offset too large to cover image area"); + if (context->tile_offset_x > context->offset_x || + context->tile_offset_y > context->offset_y) { + PyErr_SetString( + PyExc_ValueError, + "JPEG 2000 tile offset too large to cover image area"); Py_DECREF(encoder); return NULL; } } if (quality_layers && PySequence_Check(quality_layers)) { - context->quality_is_in_db = strcmp (quality_mode, "dB") == 0; + context->quality_is_in_db = strcmp(quality_mode, "dB") == 0; context->quality_layers = quality_layers; Py_INCREF(quality_layers); } context->num_resolutions = num_resolutions; - j2k_decode_coord_tuple(cblk_size, - &context->cblk_width, - &context->cblk_height); - j2k_decode_coord_tuple(precinct_size, - &context->precinct_width, - &context->precinct_height); + j2k_decode_coord_tuple(cblk_size, &context->cblk_width, &context->cblk_height); + j2k_decode_coord_tuple( + precinct_size, &context->precinct_width, &context->precinct_height); context->irreversible = PyObject_IsTrue(irreversible); context->progression = prog_order; diff --git a/src/libImaging/Access.c b/src/libImaging/Access.c index 755e2639a..6bb16fe3a 100644 --- a/src/libImaging/Access.c +++ b/src/libImaging/Access.c @@ -9,7 +9,6 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" /* use Tests/make_hash.py to calculate these values */ @@ -19,23 +18,25 @@ static struct ImagingAccessInstance access_table[ACCESS_TABLE_SIZE]; static inline UINT32 -hash(const char* mode) -{ +hash(const char *mode) { UINT32 i = ACCESS_TABLE_HASH; while (*mode) { - i = ((i<<5) + i) ^ (UINT8) *mode++; + i = ((i << 5) + i) ^ (UINT8)*mode++; } return i % ACCESS_TABLE_SIZE; } static ImagingAccess -add_item(const char* mode) -{ +add_item(const char *mode) { UINT32 i = hash(mode); /* printf("hash %s => %d\n", mode, i); */ if (access_table[i].mode && strcmp(access_table[i].mode, mode) != 0) { - fprintf(stderr, "AccessInit: hash collision: %d for both %s and %s\n", - i, mode, access_table[i].mode); + fprintf( + stderr, + "AccessInit: hash collision: %d for both %s and %s\n", + i, + mode, + access_table[i].mode); exit(1); } access_table[i].mode = mode; @@ -44,37 +45,33 @@ add_item(const char* mode) /* fetch pointer to pixel line */ -static void* -line_8(Imaging im, int x, int y) -{ +static void * +line_8(Imaging im, int x, int y) { return &im->image8[y][x]; } -static void* -line_16(Imaging im, int x, int y) -{ - return &im->image8[y][x+x]; +static void * +line_16(Imaging im, int x, int y) { + return &im->image8[y][x + x]; } -static void* -line_32(Imaging im, int x, int y) -{ +static void * +line_32(Imaging im, int x, int y) { return &im->image32[y][x]; } /* fetch individual pixel */ static void -get_pixel(Imaging im, int x, int y, void* color) -{ - char* out = color; +get_pixel(Imaging im, int x, int y, void *color) { + char *out = color; /* generic pixel access*/ if (im->image8) { out[0] = im->image8[y][x]; } else { - UINT8* p = (UINT8*) &im->image32[y][x]; + UINT8 *p = (UINT8 *)&im->image32[y][x]; if (im->type == IMAGING_TYPE_UINT8 && im->bands == 2) { out[0] = p[0]; out[1] = p[3]; @@ -85,18 +82,16 @@ get_pixel(Imaging im, int x, int y, void* color) } static void -get_pixel_8(Imaging im, int x, int y, void* color) -{ - char* out = color; +get_pixel_8(Imaging im, int x, int y, void *color) { + char *out = color; out[0] = im->image8[y][x]; } static void -get_pixel_16L(Imaging im, int x, int y, void* color) -{ - UINT8* in = (UINT8*) &im->image[y][x+x]; +get_pixel_16L(Imaging im, int x, int y, void *color) { + UINT8 *in = (UINT8 *)&im->image[y][x + x]; #ifdef WORDS_BIGENDIAN - UINT16 out = in[0] + (in[1]<<8); + UINT16 out = in[0] + (in[1] << 8); memcpy(color, &out, sizeof(out)); #else memcpy(color, in, sizeof(UINT16)); @@ -104,29 +99,26 @@ get_pixel_16L(Imaging im, int x, int y, void* color) } static void -get_pixel_16B(Imaging im, int x, int y, void* color) -{ - UINT8* in = (UINT8*) &im->image[y][x+x]; +get_pixel_16B(Imaging im, int x, int y, void *color) { + UINT8 *in = (UINT8 *)&im->image[y][x + x]; #ifdef WORDS_BIGENDIAN memcpy(color, in, sizeof(UINT16)); #else - UINT16 out = in[1] + (in[0]<<8); + UINT16 out = in[1] + (in[0] << 8); memcpy(color, &out, sizeof(out)); #endif } static void -get_pixel_32(Imaging im, int x, int y, void* color) -{ +get_pixel_32(Imaging im, int x, int y, void *color) { memcpy(color, &im->image32[y][x], sizeof(INT32)); } static void -get_pixel_32L(Imaging im, int x, int y, void* color) -{ - UINT8* in = (UINT8*) &im->image[y][x*4]; +get_pixel_32L(Imaging im, int x, int y, void *color) { + UINT8 *in = (UINT8 *)&im->image[y][x * 4]; #ifdef WORDS_BIGENDIAN - INT32 out = in[0] + (in[1]<<8) + (in[2]<<16) + (in[3]<<24); + INT32 out = in[0] + (in[1] << 8) + (in[2] << 16) + (in[3] << 24); memcpy(color, &out, sizeof(out)); #else memcpy(color, in, sizeof(INT32)); @@ -134,13 +126,12 @@ get_pixel_32L(Imaging im, int x, int y, void* color) } static void -get_pixel_32B(Imaging im, int x, int y, void* color) -{ - UINT8* in = (UINT8*) &im->image[y][x*4]; +get_pixel_32B(Imaging im, int x, int y, void *color) { + UINT8 *in = (UINT8 *)&im->image[y][x * 4]; #ifdef WORDS_BIGENDIAN memcpy(color, in, sizeof(INT32)); #else - INT32 out = in[3] + (in[2]<<8) + (in[1]<<16) + (in[0]<<24); + INT32 out = in[3] + (in[2] << 8) + (in[1] << 16) + (in[0] << 24); memcpy(color, &out, sizeof(out)); #endif } @@ -148,47 +139,41 @@ get_pixel_32B(Imaging im, int x, int y, void* color) /* store individual pixel */ static void -put_pixel(Imaging im, int x, int y, const void* color) -{ +put_pixel(Imaging im, int x, int y, const void *color) { if (im->image8) { - im->image8[y][x] = *((UINT8*) color); + im->image8[y][x] = *((UINT8 *)color); } else { memcpy(&im->image32[y][x], color, sizeof(INT32)); } } static void -put_pixel_8(Imaging im, int x, int y, const void* color) -{ - im->image8[y][x] = *((UINT8*) color); +put_pixel_8(Imaging im, int x, int y, const void *color) { + im->image8[y][x] = *((UINT8 *)color); } static void -put_pixel_16L(Imaging im, int x, int y, const void* color) -{ - memcpy(&im->image8[y][x+x], color, 2); +put_pixel_16L(Imaging im, int x, int y, const void *color) { + memcpy(&im->image8[y][x + x], color, 2); } static void -put_pixel_16B(Imaging im, int x, int y, const void* color) -{ - const char* in = color; - UINT8* out = (UINT8*) &im->image8[y][x+x]; +put_pixel_16B(Imaging im, int x, int y, const void *color) { + const char *in = color; + UINT8 *out = (UINT8 *)&im->image8[y][x + x]; out[0] = in[1]; out[1] = in[0]; } static void -put_pixel_32L(Imaging im, int x, int y, const void* color) -{ - memcpy(&im->image8[y][x*4], color, 4); +put_pixel_32L(Imaging im, int x, int y, const void *color) { + memcpy(&im->image8[y][x * 4], color, 4); } static void -put_pixel_32B(Imaging im, int x, int y, const void* color) -{ - const char* in = color; - UINT8* out = (UINT8*) &im->image8[y][x*4]; +put_pixel_32B(Imaging im, int x, int y, const void *color) { + const char *in = color; + UINT8 *out = (UINT8 *)&im->image8[y][x * 4]; out[0] = in[3]; out[1] = in[2]; out[2] = in[1]; @@ -196,19 +181,18 @@ put_pixel_32B(Imaging im, int x, int y, const void* color) } static void -put_pixel_32(Imaging im, int x, int y, const void* color) -{ +put_pixel_32(Imaging im, int x, int y, const void *color) { memcpy(&im->image32[y][x], color, sizeof(INT32)); } void -ImagingAccessInit() -{ -#define ADD(mode_, line_, get_pixel_, put_pixel_) \ - { ImagingAccess access = add_item(mode_); \ - access->line = line_; \ - access->get_pixel = get_pixel_; \ - access->put_pixel = put_pixel_; \ +ImagingAccessInit() { +#define ADD(mode_, line_, get_pixel_, put_pixel_) \ + { \ + ImagingAccess access = add_item(mode_); \ + access->line = line_; \ + access->get_pixel = get_pixel_; \ + access->put_pixel = put_pixel_; \ } /* populate access table */ @@ -236,8 +220,7 @@ ImagingAccessInit() } ImagingAccess -ImagingAccessNew(Imaging im) -{ +ImagingAccessNew(Imaging im) { ImagingAccess access = &access_table[hash(im->mode)]; if (im->mode[0] != access->mode[0] || strcmp(im->mode, access->mode) != 0) { return NULL; @@ -246,7 +229,4 @@ ImagingAccessNew(Imaging im) } void -_ImagingAccessDelete(Imaging im, ImagingAccess access) -{ - -} +_ImagingAccessDelete(Imaging im, ImagingAccess access) {} diff --git a/src/libImaging/AlphaComposite.c b/src/libImaging/AlphaComposite.c index 20b1df9e5..6d728f908 100644 --- a/src/libImaging/AlphaComposite.c +++ b/src/libImaging/AlphaComposite.c @@ -8,39 +8,30 @@ * See the README file for details on usage and redistribution. */ - #include "Imaging.h" #define PRECISION_BITS 7 -typedef struct -{ +typedef struct { UINT8 r; UINT8 g; UINT8 b; UINT8 a; } rgba8; - - Imaging -ImagingAlphaComposite(Imaging imDst, Imaging imSrc) -{ +ImagingAlphaComposite(Imaging imDst, Imaging imSrc) { Imaging imOut; int x, y; /* Check arguments */ - if (!imDst || !imSrc || - strcmp(imDst->mode, "RGBA") || - imDst->type != IMAGING_TYPE_UINT8 || - imDst->bands != 4) { + if (!imDst || !imSrc || strcmp(imDst->mode, "RGBA") || + imDst->type != IMAGING_TYPE_UINT8 || imDst->bands != 4) { return ImagingError_ModeError(); } - if (strcmp(imDst->mode, imSrc->mode) || - imDst->type != imSrc->type || - imDst->bands != imSrc->bands || - imDst->xsize != imSrc->xsize || + if (strcmp(imDst->mode, imSrc->mode) || imDst->type != imSrc->type || + imDst->bands != imSrc->bands || imDst->xsize != imSrc->xsize || imDst->ysize != imSrc->ysize) { return ImagingError_Mismatch(); } @@ -51,11 +42,11 @@ ImagingAlphaComposite(Imaging imDst, Imaging imSrc) } for (y = 0; y < imDst->ysize; y++) { - rgba8* dst = (rgba8*) imDst->image[y]; - rgba8* src = (rgba8*) imSrc->image[y]; - rgba8* out = (rgba8*) imOut->image[y]; + rgba8 *dst = (rgba8 *)imDst->image[y]; + rgba8 *src = (rgba8 *)imSrc->image[y]; + rgba8 *out = (rgba8 *)imOut->image[y]; - for (x = 0; x < imDst->xsize; x ++) { + for (x = 0; x < imDst->xsize; x++) { if (src->a == 0) { // Copy 4 bytes at once. *out = *dst; @@ -69,21 +60,25 @@ ImagingAlphaComposite(Imaging imDst, Imaging imSrc) UINT32 outa255 = src->a * 255 + blend; // There we use 7 bits for precision. // We could use more, but we go beyond 32 bits. - UINT32 coef1 = src->a * 255 * 255 * (1<a * 255 * 255 * (1 << PRECISION_BITS) / outa255; + UINT32 coef2 = 255 * (1 << PRECISION_BITS) - coef1; tmpr = src->r * coef1 + dst->r * coef2; tmpg = src->g * coef1 + dst->g * coef2; tmpb = src->b * coef1 + dst->b * coef2; - out->r = SHIFTFORDIV255(tmpr + (0x80<> PRECISION_BITS; - out->g = SHIFTFORDIV255(tmpg + (0x80<> PRECISION_BITS; - out->b = SHIFTFORDIV255(tmpb + (0x80<> PRECISION_BITS; + out->r = + SHIFTFORDIV255(tmpr + (0x80 << PRECISION_BITS)) >> PRECISION_BITS; + out->g = + SHIFTFORDIV255(tmpg + (0x80 << PRECISION_BITS)) >> PRECISION_BITS; + out->b = + SHIFTFORDIV255(tmpb + (0x80 << PRECISION_BITS)) >> PRECISION_BITS; out->a = SHIFTFORDIV255(outa255 + 0x80); } - dst++; src++; out++; + dst++; + src++; + out++; } - } return imOut; diff --git a/src/libImaging/Bands.c b/src/libImaging/Bands.c index 39ce5c49c..e1b16b34a 100644 --- a/src/libImaging/Bands.c +++ b/src/libImaging/Bands.c @@ -15,23 +15,20 @@ * See the README file for details on usage and redistribution. */ - #include "Imaging.h" - Imaging -ImagingGetBand(Imaging imIn, int band) -{ +ImagingGetBand(Imaging imIn, int band) { Imaging imOut; int x, y; /* Check arguments */ if (!imIn || imIn->type != IMAGING_TYPE_UINT8) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (band < 0 || band >= imIn->bands) { - return (Imaging) ImagingError_ValueError("band index out of range"); + return (Imaging)ImagingError_ValueError("band index out of range"); } /* Shortcuts */ @@ -51,8 +48,8 @@ ImagingGetBand(Imaging imIn, int band) /* Extract band from image */ for (y = 0; y < imIn->ysize; y++) { - UINT8* in = (UINT8*) imIn->image[y] + band; - UINT8* out = imOut->image8[y]; + UINT8 *in = (UINT8 *)imIn->image[y] + band; + UINT8 *out = imOut->image8[y]; x = 0; for (; x < imIn->xsize - 3; x += 4) { UINT32 v = MAKE_UINT32(in[0], in[4], in[8], in[12]); @@ -68,15 +65,13 @@ ImagingGetBand(Imaging imIn, int band) return imOut; } - int -ImagingSplit(Imaging imIn, Imaging bands[4]) -{ +ImagingSplit(Imaging imIn, Imaging bands[4]) { int i, j, x, y; /* Check arguments */ if (!imIn || imIn->type != IMAGING_TYPE_UINT8) { - (void) ImagingError_ModeError(); + (void)ImagingError_ModeError(); return 0; } @@ -88,7 +83,7 @@ ImagingSplit(Imaging imIn, Imaging bands[4]) for (i = 0; i < imIn->bands; i++) { bands[i] = ImagingNewDirty("L", imIn->xsize, imIn->ysize); - if ( ! bands[i]) { + if (!bands[i]) { for (j = 0; j < i; ++j) { ImagingDelete(bands[j]); } @@ -99,14 +94,14 @@ ImagingSplit(Imaging imIn, Imaging bands[4]) /* Extract bands from image */ if (imIn->bands == 2) { for (y = 0; y < imIn->ysize; y++) { - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out0 = bands[0]->image8[y]; - UINT8* out1 = bands[1]->image8[y]; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out0 = bands[0]->image8[y]; + UINT8 *out1 = bands[1]->image8[y]; x = 0; for (; x < imIn->xsize - 3; x += 4) { UINT32 v = MAKE_UINT32(in[0], in[4], in[8], in[12]); memcpy(out0 + x, &v, sizeof(v)); - v = MAKE_UINT32(in[0+3], in[4+3], in[8+3], in[12+3]); + v = MAKE_UINT32(in[0 + 3], in[4 + 3], in[8 + 3], in[12 + 3]); memcpy(out1 + x, &v, sizeof(v)); in += 16; } @@ -118,17 +113,17 @@ ImagingSplit(Imaging imIn, Imaging bands[4]) } } else if (imIn->bands == 3) { for (y = 0; y < imIn->ysize; y++) { - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out0 = bands[0]->image8[y]; - UINT8* out1 = bands[1]->image8[y]; - UINT8* out2 = bands[2]->image8[y]; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out0 = bands[0]->image8[y]; + UINT8 *out1 = bands[1]->image8[y]; + UINT8 *out2 = bands[2]->image8[y]; x = 0; for (; x < imIn->xsize - 3; x += 4) { UINT32 v = MAKE_UINT32(in[0], in[4], in[8], in[12]); memcpy(out0 + x, &v, sizeof(v)); - v = MAKE_UINT32(in[0+1], in[4+1], in[8+1], in[12+1]); + v = MAKE_UINT32(in[0 + 1], in[4 + 1], in[8 + 1], in[12 + 1]); memcpy(out1 + x, &v, sizeof(v)); - v = MAKE_UINT32(in[0+2], in[4+2], in[8+2], in[12+2]); + v = MAKE_UINT32(in[0 + 2], in[4 + 2], in[8 + 2], in[12 + 2]); memcpy(out2 + x, &v, sizeof(v)); in += 16; } @@ -141,20 +136,20 @@ ImagingSplit(Imaging imIn, Imaging bands[4]) } } else { for (y = 0; y < imIn->ysize; y++) { - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out0 = bands[0]->image8[y]; - UINT8* out1 = bands[1]->image8[y]; - UINT8* out2 = bands[2]->image8[y]; - UINT8* out3 = bands[3]->image8[y]; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out0 = bands[0]->image8[y]; + UINT8 *out1 = bands[1]->image8[y]; + UINT8 *out2 = bands[2]->image8[y]; + UINT8 *out3 = bands[3]->image8[y]; x = 0; for (; x < imIn->xsize - 3; x += 4) { UINT32 v = MAKE_UINT32(in[0], in[4], in[8], in[12]); memcpy(out0 + x, &v, sizeof(v)); - v = MAKE_UINT32(in[0+1], in[4+1], in[8+1], in[12+1]); + v = MAKE_UINT32(in[0 + 1], in[4 + 1], in[8 + 1], in[12 + 1]); memcpy(out1 + x, &v, sizeof(v)); - v = MAKE_UINT32(in[0+2], in[4+2], in[8+2], in[12+2]); + v = MAKE_UINT32(in[0 + 2], in[4 + 2], in[8 + 2], in[12 + 2]); memcpy(out2 + x, &v, sizeof(v)); - v = MAKE_UINT32(in[0+3], in[4+3], in[8+3], in[12+3]); + v = MAKE_UINT32(in[0 + 3], in[4 + 3], in[8 + 3], in[12 + 3]); memcpy(out3 + x, &v, sizeof(v)); in += 16; } @@ -171,25 +166,22 @@ ImagingSplit(Imaging imIn, Imaging bands[4]) return imIn->bands; } - Imaging -ImagingPutBand(Imaging imOut, Imaging imIn, int band) -{ +ImagingPutBand(Imaging imOut, Imaging imIn, int band) { int x, y; /* Check arguments */ if (!imIn || imIn->bands != 1 || !imOut) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (band < 0 || band >= imOut->bands) { - return (Imaging) ImagingError_ValueError("band index out of range"); + return (Imaging)ImagingError_ValueError("band index out of range"); } - if (imIn->type != imOut->type || - imIn->xsize != imOut->xsize || + if (imIn->type != imOut->type || imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize) { - return (Imaging) ImagingError_Mismatch(); + return (Imaging)ImagingError_Mismatch(); } /* Shortcuts */ @@ -204,8 +196,8 @@ ImagingPutBand(Imaging imOut, Imaging imIn, int band) /* Insert band into image */ for (y = 0; y < imIn->ysize; y++) { - UINT8* in = imIn->image8[y]; - UINT8* out = (UINT8*) imOut->image[y] + band; + UINT8 *in = imIn->image8[y]; + UINT8 *out = (UINT8 *)imOut->image[y] + band; for (x = 0; x < imIn->xsize; x++) { *out = in[x]; out += 4; @@ -216,17 +208,16 @@ ImagingPutBand(Imaging imOut, Imaging imIn, int band) } Imaging -ImagingFillBand(Imaging imOut, int band, int color) -{ +ImagingFillBand(Imaging imOut, int band, int color) { int x, y; /* Check arguments */ if (!imOut || imOut->type != IMAGING_TYPE_UINT8) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (band < 0 || band >= imOut->bands) { - return (Imaging) ImagingError_ValueError("band index out of range"); + return (Imaging)ImagingError_ValueError("band index out of range"); } /* Special case for LXXA etc */ @@ -238,9 +229,9 @@ ImagingFillBand(Imaging imOut, int band, int color) /* Insert color into image */ for (y = 0; y < imOut->ysize; y++) { - UINT8* out = (UINT8*) imOut->image[y] + band; + UINT8 *out = (UINT8 *)imOut->image[y] + band; for (x = 0; x < imOut->xsize; x++) { - *out = (UINT8) color; + *out = (UINT8)color; out += 4; } } @@ -249,40 +240,39 @@ ImagingFillBand(Imaging imOut, int band, int color) } Imaging -ImagingMerge(const char* mode, Imaging bands[4]) -{ +ImagingMerge(const char *mode, Imaging bands[4]) { int i, x, y; int bandsCount = 0; Imaging imOut; Imaging firstBand; firstBand = bands[0]; - if ( ! firstBand) { - return (Imaging) ImagingError_ValueError("wrong number of bands"); + if (!firstBand) { + return (Imaging)ImagingError_ValueError("wrong number of bands"); } for (i = 0; i < 4; ++i) { - if ( ! bands[i]) { + if (!bands[i]) { break; } if (bands[i]->bands != 1) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } - if (bands[i]->xsize != firstBand->xsize - || bands[i]->ysize != firstBand->ysize) { - return (Imaging) ImagingError_Mismatch(); + if (bands[i]->xsize != firstBand->xsize || + bands[i]->ysize != firstBand->ysize) { + return (Imaging)ImagingError_Mismatch(); } } bandsCount = i; imOut = ImagingNewDirty(mode, firstBand->xsize, firstBand->ysize); - if ( ! imOut) { + if (!imOut) { return NULL; } if (imOut->bands != bandsCount) { ImagingDelete(imOut); - return (Imaging) ImagingError_ValueError("wrong number of bands"); + return (Imaging)ImagingError_ValueError("wrong number of bands"); } if (imOut->bands == 1) { @@ -291,30 +281,30 @@ ImagingMerge(const char* mode, Imaging bands[4]) if (imOut->bands == 2) { for (y = 0; y < imOut->ysize; y++) { - UINT8* in0 = bands[0]->image8[y]; - UINT8* in1 = bands[1]->image8[y]; - UINT32* out = (UINT32*) imOut->image32[y]; + UINT8 *in0 = bands[0]->image8[y]; + UINT8 *in1 = bands[1]->image8[y]; + UINT32 *out = (UINT32 *)imOut->image32[y]; for (x = 0; x < imOut->xsize; x++) { out[x] = MAKE_UINT32(in0[x], 0, 0, in1[x]); } } } else if (imOut->bands == 3) { for (y = 0; y < imOut->ysize; y++) { - UINT8* in0 = bands[0]->image8[y]; - UINT8* in1 = bands[1]->image8[y]; - UINT8* in2 = bands[2]->image8[y]; - UINT32* out = (UINT32*) imOut->image32[y]; + UINT8 *in0 = bands[0]->image8[y]; + UINT8 *in1 = bands[1]->image8[y]; + UINT8 *in2 = bands[2]->image8[y]; + UINT32 *out = (UINT32 *)imOut->image32[y]; for (x = 0; x < imOut->xsize; x++) { out[x] = MAKE_UINT32(in0[x], in1[x], in2[x], 0); } } } else if (imOut->bands == 4) { for (y = 0; y < imOut->ysize; y++) { - UINT8* in0 = bands[0]->image8[y]; - UINT8* in1 = bands[1]->image8[y]; - UINT8* in2 = bands[2]->image8[y]; - UINT8* in3 = bands[3]->image8[y]; - UINT32* out = (UINT32*) imOut->image32[y]; + UINT8 *in0 = bands[0]->image8[y]; + UINT8 *in1 = bands[1]->image8[y]; + UINT8 *in2 = bands[2]->image8[y]; + UINT8 *in3 = bands[3]->image8[y]; + UINT32 *out = (UINT32 *)imOut->image32[y]; for (x = 0; x < imOut->xsize; x++) { out[x] = MAKE_UINT32(in0[x], in1[x], in2[x], in3[x]); } diff --git a/src/libImaging/BcnDecode.c b/src/libImaging/BcnDecode.c index f908a03ad..b6a4cbadc 100644 --- a/src/libImaging/BcnDecode.c +++ b/src/libImaging/BcnDecode.c @@ -11,10 +11,8 @@ * https://creativecommons.org/publicdomain/zero/1.0/ */ - #include "Imaging.h" - typedef struct { UINT8 r, g, b, a; } rgba; @@ -37,23 +35,24 @@ typedef struct { UINT8 lut[6]; } bc3_alpha; -#define LOAD16(p) \ - (p)[0] | ((p)[1] << 8) +#define LOAD16(p) (p)[0] | ((p)[1] << 8) -#define LOAD32(p) \ - (p)[0] | ((p)[1] << 8) | ((p)[2] << 16) | ((p)[3] << 24) +#define LOAD32(p) (p)[0] | ((p)[1] << 8) | ((p)[2] << 16) | ((p)[3] << 24) -static void bc1_color_load(bc1_color *dst, const UINT8 *src) { +static void +bc1_color_load(bc1_color *dst, const UINT8 *src) { dst->c0 = LOAD16(src); dst->c1 = LOAD16(src + 2); dst->lut = LOAD32(src + 4); } -static void bc3_alpha_load(bc3_alpha *dst, const UINT8 *src) { +static void +bc3_alpha_load(bc3_alpha *dst, const UINT8 *src) { memcpy(dst, src, sizeof(bc3_alpha)); } -static rgba decode_565(UINT16 x) { +static rgba +decode_565(UINT16 x) { rgba c; int r, g, b; r = (x & 0xf800) >> 8; @@ -69,7 +68,8 @@ static rgba decode_565(UINT16 x) { return c; } -static void decode_bc1_color(rgba *dst, const UINT8 *src) { +static void +decode_bc1_color(rgba *dst, const UINT8 *src) { bc1_color col; rgba p[4]; int n, cw; @@ -85,13 +85,13 @@ static void decode_bc1_color(rgba *dst, const UINT8 *src) { g1 = p[1].g; b1 = p[1].b; if (col.c0 > col.c1) { - p[2].r = (2*r0 + 1*r1) / 3; - p[2].g = (2*g0 + 1*g1) / 3; - p[2].b = (2*b0 + 1*b1) / 3; + p[2].r = (2 * r0 + 1 * r1) / 3; + p[2].g = (2 * g0 + 1 * g1) / 3; + p[2].b = (2 * b0 + 1 * b1) / 3; p[2].a = 0xff; - p[3].r = (1*r0 + 2*r1) / 3; - p[3].g = (1*g0 + 2*g1) / 3; - p[3].b = (1*b0 + 2*b1) / 3; + p[3].r = (1 * r0 + 2 * r1) / 3; + p[3].g = (1 * g0 + 2 * g1) / 3; + p[3].b = (1 * b0 + 2 * b1) / 3; p[3].a = 0xff; } else { p[2].r = (r0 + r1) / 2; @@ -109,7 +109,8 @@ static void decode_bc1_color(rgba *dst, const UINT8 *src) { } } -static void decode_bc3_alpha(char *dst, const UINT8 *src, int stride, int o) { +static void +decode_bc3_alpha(char *dst, const UINT8 *src, int stride, int o) { bc3_alpha b; UINT16 a0, a1; UINT8 a[8]; @@ -121,17 +122,17 @@ static void decode_bc3_alpha(char *dst, const UINT8 *src, int stride, int o) { a[0] = (UINT8)a0; a[1] = (UINT8)a1; if (a0 > a1) { - a[2] = (6*a0 + 1*a1) / 7; - a[3] = (5*a0 + 2*a1) / 7; - a[4] = (4*a0 + 3*a1) / 7; - a[5] = (3*a0 + 4*a1) / 7; - a[6] = (2*a0 + 5*a1) / 7; - a[7] = (1*a0 + 6*a1) / 7; + a[2] = (6 * a0 + 1 * a1) / 7; + a[3] = (5 * a0 + 2 * a1) / 7; + a[4] = (4 * a0 + 3 * a1) / 7; + a[5] = (3 * a0 + 4 * a1) / 7; + a[6] = (2 * a0 + 5 * a1) / 7; + a[7] = (1 * a0 + 6 * a1) / 7; } else { - a[2] = (4*a0 + 1*a1) / 5; - a[3] = (3*a0 + 2*a1) / 5; - a[4] = (2*a0 + 3*a1) / 5; - a[5] = (1*a0 + 4*a1) / 5; + a[2] = (4 * a0 + 1 * a1) / 5; + a[3] = (3 * a0 + 2 * a1) / 5; + a[4] = (2 * a0 + 3 * a1) / 5; + a[5] = (1 * a0 + 4 * a1) / 5; a[6] = 0; a[7] = 0xff; } @@ -143,15 +144,17 @@ static void decode_bc3_alpha(char *dst, const UINT8 *src, int stride, int o) { lut = b.lut[3] | (b.lut[4] << 8) | (b.lut[5] << 16); for (n = 0; n < 8; n++) { aw = 7 & (lut >> (3 * n)); - dst[stride * (8+n) + o] = a[aw]; + dst[stride * (8 + n) + o] = a[aw]; } } -static void decode_bc1_block(rgba *col, const UINT8* src) { +static void +decode_bc1_block(rgba *col, const UINT8 *src) { decode_bc1_color(col, src); } -static void decode_bc2_block(rgba *col, const UINT8* src) { +static void +decode_bc2_block(rgba *col, const UINT8 *src) { int n, bitI, byI, av; decode_bc1_color(col, src + 8); for (n = 0; n < 16; n++) { @@ -163,30 +166,36 @@ static void decode_bc2_block(rgba *col, const UINT8* src) { } } -static void decode_bc3_block(rgba *col, const UINT8* src) { +static void +decode_bc3_block(rgba *col, const UINT8 *src) { decode_bc1_color(col, src + 8); decode_bc3_alpha((char *)col, src, sizeof(col[0]), 3); } -static void decode_bc4_block(lum *col, const UINT8* src) { +static void +decode_bc4_block(lum *col, const UINT8 *src) { decode_bc3_alpha((char *)col, src, sizeof(col[0]), 0); } -static void decode_bc5_block(rgba *col, const UINT8* src) { +static void +decode_bc5_block(rgba *col, const UINT8 *src) { decode_bc3_alpha((char *)col, src, sizeof(col[0]), 0); decode_bc3_alpha((char *)col, src + 8, sizeof(col[0]), 1); } /* BC6 and BC7 are described here: - https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_compression_bptc.txt */ + https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_compression_bptc.txt + */ -static UINT8 get_bit(const UINT8* src, int bit) { +static UINT8 +get_bit(const UINT8 *src, int bit) { int by = bit >> 3; bit &= 7; return (src[by] >> bit) & 1; } -static UINT8 get_bits(const UINT8* src, int bit, int count) { +static UINT8 +get_bits(const UINT8 *src, int bit, int count) { UINT8 v; int x; int by = bit >> 3; @@ -197,7 +206,7 @@ static UINT8 get_bits(const UINT8* src, int bit, int count) { if (bit + count <= 8) { v = (src[by] >> bit) & ((1 << count) - 1); } else { - x = src[by] | (src[by+1] << 8); + x = src[by] | (src[by + 1] << 8); v = (x >> bit) & ((1 << count) - 1); } return v; @@ -225,73 +234,51 @@ static const bc7_mode_info bc7_modes[] = { {1, 0, 2, 1, 5, 6, 0, 0, 2, 3}, {1, 0, 2, 0, 7, 8, 0, 0, 2, 2}, {1, 0, 0, 0, 7, 7, 1, 0, 4, 0}, - {2, 6, 0, 0, 5, 5, 1, 0, 2, 0} -}; + {2, 6, 0, 0, 5, 5, 1, 0, 2, 0}}; /* Subset indices: Table.P2, 1 bit per index */ static const UINT16 bc7_si2[] = { - 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, - 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, - 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, - 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, - 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, - 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, - 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, - 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22}; + 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, + 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, 0xf710, 0x008e, 0x7100, 0x08ce, + 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, + 0x718e, 0x399c, 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, + 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, 0x0272, 0x04e4, + 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, + 0xccf0, 0x0fcc, 0x7744, 0xee22}; /* Table.P3, 2 bits per index */ static const UINT32 bc7_si3[] = { - 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, - 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, - 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090, - 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, - 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, - 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, - 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, - 0xa08585a0, 0xaa821414, 0x50a4a450, 0x6a5a0200, - 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, - 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, - 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, - 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, - 0xaa444444, 0x54a854a8, 0x95809580, 0x96969600, - 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, - 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, - 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254}; + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, + 0x5a5a5050, 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090, 0x94949494, 0xa4a4a4a4, + 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, 0xa8a85454, + 0x6a6a4040, 0xa4a45000, 0x1a1a0500, 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, + 0xa08585a0, 0xaa821414, 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, + 0x24242424, 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, 0x500aa550, 0xaaaa4444, + 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, 0xaa444444, + 0x54a854a8, 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, + 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, + 0x2a4a5254}; /* Anchor indices: Table.A2 */ static const char bc7_ai0[] = { - 15,15,15,15,15,15,15,15, - 15,15,15,15,15,15,15,15, - 15, 2, 8, 2, 2, 8, 8,15, - 2, 8, 2, 2, 8, 8, 2, 2, - 15,15, 6, 8, 2, 8,15,15, - 2, 8, 2, 2, 2,15,15, 6, - 6, 2, 6, 8,15,15, 2, 2, - 15,15,15,15,15, 2, 2,15}; + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, + 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, + 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15}; /* Table.A3a */ static const char bc7_ai1[] = { - 3, 3,15,15, 8, 3,15,15, - 8, 8, 6, 6, 6, 5, 3, 3, - 3, 3, 8,15, 3, 3, 6,10, - 5, 8, 8, 6, 8, 5,15,15, - 8,15, 3, 5, 6,10, 8,15, - 15, 3,15, 5,15,15,15,15, - 3,15, 5, 5, 5, 8, 5,10, - 5,10, 8,13,15,12, 3, 3}; + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, + 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, + 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3}; /* Table.A3b */ -static const char bc7_ai2[] = { - 15, 8, 8, 3,15,15, 3, 8, - 15,15,15,15,15,15,15, 8, - 15, 8,15, 3,15, 8,15, 8, - 3,15, 6,10,15,15,10, 8, - 15, 3,15,10,10, 8, 9,10, - 6,15, 8,15, 3, 6, 6, 8, - 15, 3,15,15,15,15,15,15, - 15,15,15,15, 3,15,15, 8}; +static const char bc7_ai2[] = {15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, + 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, + 6, 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, + 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8}; /* Interpolation weights */ static const char bc7_weights2[] = {0, 21, 43, 64}; @@ -299,7 +286,8 @@ static const char bc7_weights3[] = {0, 9, 18, 27, 37, 46, 55, 64}; static const char bc7_weights4[] = { 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64}; -static const char *bc7_get_weights(int n) { +static const char * +bc7_get_weights(int n) { if (n == 2) { return bc7_weights2; } @@ -309,7 +297,8 @@ static const char *bc7_get_weights(int n) { return bc7_weights4; } -static int bc7_get_subset(int ns, int partition, int n) { +static int +bc7_get_subset(int ns, int partition, int n) { if (ns == 2) { return 1 & (bc7_si2[partition] >> n); } @@ -319,12 +308,14 @@ static int bc7_get_subset(int ns, int partition, int n) { return 0; } -static UINT8 expand_quantized(UINT8 v, int bits) { +static UINT8 +expand_quantized(UINT8 v, int bits) { v = v << (8 - bits); return v | (v >> bits); } -static void bc7_lerp(rgba *dst, const rgba *e, int s0, int s1) { +static void +bc7_lerp(rgba *dst, const rgba *e, int s0, int s1) { int t0 = 64 - s0; int t1 = 64 - s1; dst->r = (UINT8)((t0 * e[0].r + s0 * e[1].r + 32) >> 6); @@ -333,7 +324,8 @@ static void bc7_lerp(rgba *dst, const rgba *e, int s0, int s1) { dst->a = (UINT8)((t1 * e[0].a + s1 * e[1].a + 32) >> 6); } -static void decode_bc7_block(rgba *col, const UINT8* src) { +static void +decode_bc7_block(rgba *col, const UINT8 *src) { rgba endpoints[6]; int bit = 0, cibit, aibit; int mode = src[0]; @@ -352,7 +344,8 @@ static void decode_bc7_block(rgba *col, const UINT8* src) { } return; } - while (!(mode & (1 << bit++))) ; + while (!(mode & (1 << bit++))) + ; mode = bit - 1; info = &bc7_modes[mode]; /* color selection bits: {subset}{endpoint} */ @@ -361,7 +354,7 @@ static void decode_bc7_block(rgba *col, const UINT8* src) { cw = bc7_get_weights(info->ib); aw = bc7_get_weights((ab && info->ib2) ? info->ib2 : info->ib); -#define LOAD(DST, N) \ +#define LOAD(DST, N) \ DST = get_bits(src, bit, N); \ bit += N; LOAD(partition, info->pb); @@ -421,14 +414,14 @@ static void decode_bc7_block(rgba *col, const UINT8* src) { if (ab) { ab++; } - for (i = 0; i < numep; i+=2) { + for (i = 0; i < numep; i += 2) { LOAD(val, 1); for (j = 0; j < 2; j++) { - ASSIGN_P(endpoints[i+j].r); - ASSIGN_P(endpoints[i+j].g); - ASSIGN_P(endpoints[i+j].b); + ASSIGN_P(endpoints[i + j].r); + ASSIGN_P(endpoints[i + j].g); + ASSIGN_P(endpoints[i + j].b); if (ab) { - ASSIGN_P(endpoints[i+j].a); + ASSIGN_P(endpoints[i + j].a); } } } @@ -482,9 +475,9 @@ static void decode_bc7_block(rgba *col, const UINT8* src) { bc7_lerp(&col[i], &endpoints[s], cw[i0], cw[i0]); } #define ROTATE(x, y) \ - val = x; \ - x = y; \ - y = val + val = x; \ + x = y; \ + y = val if (rotation == 1) { ROTATE(col[i].r, col[i].a); } else if (rotation == 2) { @@ -498,106 +491,102 @@ static void decode_bc7_block(rgba *col, const UINT8* src) { /* BC6 */ typedef struct { - char ns; /* number of subsets (also called regions) */ - char tr; /* whether endpoints are delta-compressed */ - char pb; /* partition bits */ + char ns; /* number of subsets (also called regions) */ + char tr; /* whether endpoints are delta-compressed */ + char pb; /* partition bits */ char epb; /* endpoint bits */ - char rb; /* red bits (delta) */ - char gb; /* green bits (delta) */ - char bb; /* blue bits (delta) */ + char rb; /* red bits (delta) */ + char gb; /* green bits (delta) */ + char bb; /* blue bits (delta) */ } bc6_mode_info; static const bc6_mode_info bc6_modes[] = { // 00 {2, 1, 5, 10, 5, 5, 5}, // 01 - {2, 1, 5, 7, 6, 6, 6}, + {2, 1, 5, 7, 6, 6, 6}, // 10 {2, 1, 5, 11, 5, 4, 4}, {2, 1, 5, 11, 4, 5, 4}, {2, 1, 5, 11, 4, 4, 5}, - {2, 1, 5, 9, 5, 5, 5}, - {2, 1, 5, 8, 6, 5, 5}, - {2, 1, 5, 8, 5, 6, 5}, - {2, 1, 5, 8, 5, 5, 6}, - {2, 0, 5, 6, 6, 6, 6}, + {2, 1, 5, 9, 5, 5, 5}, + {2, 1, 5, 8, 6, 5, 5}, + {2, 1, 5, 8, 5, 6, 5}, + {2, 1, 5, 8, 5, 5, 6}, + {2, 0, 5, 6, 6, 6, 6}, // 11 {1, 0, 0, 10, 10, 10, 10}, - {1, 1, 0, 11, 9, 9, 9}, - {1, 1, 0, 12, 8, 8, 8}, - {1, 1, 0, 16, 4, 4, 4} -}; + {1, 1, 0, 11, 9, 9, 9}, + {1, 1, 0, 12, 8, 8, 8}, + {1, 1, 0, 16, 4, 4, 4}}; /* Table.F, encoded as a sequence of bit indices */ static const UINT8 bc6_bit_packings[][75] = { - {116, 132, 176, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, - 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, - 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, - 81, 82, 83, 84, 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, - 145, 146, 147, 148, 175}, - {117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 172, 173, 132, 16, 17, 18, 19, 20, 21, - 22, 133, 174, 116, 32, 33, 34, 35, 36, 37, 38, 175, 177, 176, 48, 49, 50, - 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, - 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, - 145, 146, 147, 148, 149}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, - 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114, - 115, 64, 65, 66, 67, 26, 172, 160, 161, 162, 163, 80, 81, 82, 83, 42, 173, - 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148, - 175}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, - 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114, - 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 173, - 128, 129, 130, 131, 96, 97, 98, 99, 172, 174, 144, 145, 146, 147, 116, - 175}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, - 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114, - 115, 64, 65, 66, 67, 26, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, - 128, 129, 130, 131, 96, 97, 98, 99, 173, 174, 144, 145, 146, 147, 176, - 175}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116, - 32, 33, 34, 35, 36, 37, 38, 39, 40, 176, 48, 49, 50, 51, 52, 164, 112, 113, - 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, - 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148, - 175}, - {0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 174, 116, - 32, 33, 34, 35, 36, 37, 38, 39, 175, 176, 48, 49, 50, 51, 52, 53, 112, 113, - 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, - 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, - 149}, - {0, 1, 2, 3, 4, 5, 6, 7, 172, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116, - 32, 33, 34, 35, 36, 37, 38, 39, 165, 176, 48, 49, 50, 51, 52, 164, 112, - 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, - 84, 173, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, - 148, 175}, - {0, 1, 2, 3, 4, 5, 6, 7, 173, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116, - 32, 33, 34, 35, 36, 37, 38, 39, 177, 176, 48, 49, 50, 51, 52, 164, 112, - 113, 114, 115, 64, 65, 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83, - 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, - 148, 175}, - {0, 1, 2, 3, 4, 5, 164, 172, 173, 132, 16, 17, 18, 19, 20, 21, 117, 133, - 174, 116, 32, 33, 34, 35, 36, 37, 165, 175, 177, 176, 48, 49, 50, 51, 52, - 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, - 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, - 146, 147, 148, 149}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, - 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, - 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 42}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, - 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, - 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, - 42}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, - 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, - 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, - 42}}; + {116, 132, 176, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, + 66, 67, 68, 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, 173, 128, + 129, 130, 131, 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148, 175}, + {117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 172, 173, 132, 16, 17, + 18, 19, 20, 21, 22, 133, 174, 116, 32, 33, 34, 35, 36, 37, 38, + 175, 177, 176, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, + 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, + 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26, + 172, 160, 161, 162, 163, 80, 81, 82, 83, 42, 173, 128, 129, 130, 131, + 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148, 175}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, + 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 173, 128, 129, 130, 131, + 96, 97, 98, 99, 172, 174, 144, 145, 146, 147, 116, 175}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + 48, 49, 50, 51, 10, 132, 112, 113, 114, 115, 64, 65, 66, 67, 26, + 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, 128, 129, 130, 131, + 96, 97, 98, 99, 173, 174, 144, 145, 146, 147, 176, 175}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 116, 32, 33, 34, 35, 36, 37, 38, 39, 40, 176, + 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, + 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, 173, 128, 129, 130, 131, + 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148, 175}, + {0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, + 21, 22, 23, 174, 116, 32, 33, 34, 35, 36, 37, 38, 39, 175, 176, + 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, + 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, 173, 128, 129, 130, 131, + 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149}, + {0, 1, 2, 3, 4, 5, 6, 7, 172, 132, 16, 17, 18, 19, 20, + 21, 22, 23, 117, 116, 32, 33, 34, 35, 36, 37, 38, 39, 165, 176, + 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, + 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 173, 128, 129, 130, 131, + 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148, 175}, + {0, 1, 2, 3, 4, 5, 6, 7, 173, 132, 16, 17, 18, 19, 20, + 21, 22, 23, 133, 116, 32, 33, 34, 35, 36, 37, 38, 39, 177, 176, + 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, + 172, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, + 96, 97, 98, 99, 100, 174, 144, 145, 146, 147, 148, 175}, + {0, 1, 2, 3, 4, 5, 164, 172, 173, 132, 16, 17, 18, 19, 20, + 21, 117, 133, 174, 116, 32, 33, 34, 35, 36, 37, 165, 175, 177, 176, + 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, + 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, + 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, + 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, 42}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, + 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, 42}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, + 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, 42}}; -static void bc6_sign_extend(UINT16 *v, int prec) { +static void +bc6_sign_extend(UINT16 *v, int prec) { int x = *v; if (x & (1 << (prec - 1))) { x |= -1 << prec; @@ -605,7 +594,8 @@ static void bc6_sign_extend(UINT16 *v, int prec) { *v = (UINT16)x; } -static int bc6_unquantize(UINT16 v, int prec, int sign) { +static int +bc6_unquantize(UINT16 v, int prec, int sign) { int s = 0; int x; if (!sign) { @@ -645,7 +635,8 @@ static int bc6_unquantize(UINT16 v, int prec, int sign) { } } -static float half_to_float(UINT16 h) { +static float +half_to_float(UINT16 h) { /* https://gist.github.com/rygorous/2144712 */ union { UINT32 u; @@ -662,7 +653,8 @@ static float half_to_float(UINT16 h) { return o.f; } -static float bc6_finalize(int v, int sign) { +static float +bc6_finalize(int v, int sign) { if (sign) { if (v < 0) { v = ((-v) * 31) / 32; @@ -675,7 +667,8 @@ static float bc6_finalize(int v, int sign) { } } -static void bc6_lerp(rgb32f *col, int *e0, int *e1, int s, int sign) { +static void +bc6_lerp(rgb32f *col, int *e0, int *e1, int s, int sign) { int r, g, b; int t = 64 - s; r = (e0[0] * t + e1[0] * s) >> 6; @@ -686,7 +679,8 @@ static void bc6_lerp(rgb32f *col, int *e0, int *e1, int s, int sign) { col->b = bc6_finalize(b, sign); } -static void decode_bc6_block(rgb32f *col, const UINT8* src, int sign) { +static void +decode_bc6_block(rgb32f *col, const UINT8 *src, int sign) { UINT16 endpoints[12]; /* storage for r0, g0, b0, r1, ... */ int ueps[12]; int i, i0, ib2, di, dw, mask, numep, s; @@ -736,9 +730,9 @@ static void decode_bc6_block(rgb32f *col, const UINT8* src, int sign) { } if (sign || info->tr) { /* sign-extend e1,2,3 if signed or deltas */ for (i = 3; i < numep; i += 3) { - bc6_sign_extend(&endpoints[i+0], info->rb); - bc6_sign_extend(&endpoints[i+1], info->gb); - bc6_sign_extend(&endpoints[i+2], info->bb); + bc6_sign_extend(&endpoints[i + 0], info->rb); + bc6_sign_extend(&endpoints[i + 1], info->gb); + bc6_sign_extend(&endpoints[i + 2], info->bb); } } if (info->tr) { /* apply deltas */ @@ -747,9 +741,9 @@ static void decode_bc6_block(rgb32f *col, const UINT8* src, int sign) { } if (sign) { for (i = 3; i < numep; i += 3) { - bc6_sign_extend(&endpoints[i+0], info->rb); - bc6_sign_extend(&endpoints[i+1], info->gb); - bc6_sign_extend(&endpoints[i+2], info->bb); + bc6_sign_extend(&endpoints[i + 0], info->rb); + bc6_sign_extend(&endpoints[i + 1], info->gb); + bc6_sign_extend(&endpoints[i + 2], info->bb); } } } @@ -769,11 +763,12 @@ static void decode_bc6_block(rgb32f *col, const UINT8* src, int sign) { i0 = get_bits(src, bit, ib2); bit += ib2; - bc6_lerp(&col[i], &ueps[s], &ueps[s+3], cw[i0], sign); + bc6_lerp(&col[i], &ueps[s], &ueps[s + 3], cw[i0], sign); } } -static void put_block(Imaging im, ImagingCodecState state, const char *col, int sz, int C) { +static void +put_block(Imaging im, ImagingCodecState state, const char *col, int sz, int C) { int width = state->xsize; int height = state->ysize; int xmax = width + state->xoff; @@ -795,15 +790,15 @@ static void put_block(Imaging im, ImagingCodecState state, const char *col, int if (x >= width) { continue; } - memcpy(dst + sz*x, col + sz*(j*4 + i), sz); + memcpy(dst + sz * x, col + sz * (j * 4 + i), sz); } } else { if (state->ystep < 0) { y = state->yoff + ymax - y - 1; } x = state->x; - dst = im->image[y] + sz*x; - memcpy(dst, col + sz*(j*4), 4 * sz); + dst = im->image[y] + sz * x; + memcpy(dst, col + sz * (j * 4), 4 * sz); } } state->x += 4; @@ -813,23 +808,25 @@ static void put_block(Imaging im, ImagingCodecState state, const char *col, int } } -static int decode_bcn(Imaging im, ImagingCodecState state, const UINT8* src, int bytes, int N, int C) { +static int +decode_bcn( + Imaging im, ImagingCodecState state, const UINT8 *src, int bytes, int N, int C) { int ymax = state->ysize + state->yoff; const UINT8 *ptr = src; switch (N) { -#define DECODE_LOOP(NN, SZ, TY, ...) \ - case NN: \ - while (bytes >= SZ) { \ - TY col[16]; \ - memset(col, 0, 16 * sizeof(col[0])); \ - decode_bc##NN##_block(col, ptr); \ +#define DECODE_LOOP(NN, SZ, TY, ...) \ + case NN: \ + while (bytes >= SZ) { \ + TY col[16]; \ + memset(col, 0, 16 * sizeof(col[0])); \ + decode_bc##NN##_block(col, ptr); \ put_block(im, state, (const char *)col, sizeof(col[0]), C); \ - ptr += SZ; \ - bytes -= SZ; \ - if (state->y >= ymax) {\ - return -1; \ - }\ - } \ + ptr += SZ; \ + bytes -= SZ; \ + if (state->y >= ymax) { \ + return -1; \ + } \ + } \ break DECODE_LOOP(1, 8, rgba); @@ -844,18 +841,19 @@ static int decode_bcn(Imaging im, ImagingCodecState state, const UINT8* src, int put_block(im, state, (const char *)col, sizeof(col[0]), C); ptr += 16; bytes -= 16; - if (state->y >= ymax) {\ - return -1; \ - }\ + if (state->y >= ymax) { + return -1; + } } break; - DECODE_LOOP(7, 16, rgba); + DECODE_LOOP(7, 16, rgba); #undef DECODE_LOOP } return (int)(ptr - src); } -int ImagingBcnDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { +int +ImagingBcnDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { int N = state->state & 0xf; int width = state->xsize; int height = state->ysize; diff --git a/src/libImaging/Bit.h b/src/libImaging/Bit.h index 56e3a17d2..f64bfb469 100644 --- a/src/libImaging/Bit.h +++ b/src/libImaging/Bit.h @@ -1,7 +1,6 @@ /* Bit.h */ typedef struct { - /* CONFIGURATION */ /* Number of bits per pixel */ @@ -19,7 +18,7 @@ typedef struct { /* Lookup table (not implemented) */ unsigned long lutsize; - FLOAT32* lut; + FLOAT32 *lut; /* INTERNAL */ unsigned long mask; diff --git a/src/libImaging/BitDecode.c b/src/libImaging/BitDecode.c index 92edd746f..28baa8b7e 100644 --- a/src/libImaging/BitDecode.c +++ b/src/libImaging/BitDecode.c @@ -13,20 +13,16 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" #include "Bit.h" - int -ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ - BITSTATE* bitstate = state->context; - UINT8* ptr; +ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { + BITSTATE *bitstate = state->context; + UINT8 *ptr; if (state->state == 0) { - /* Initialize context variables */ /* this decoder only works for float32 image buffers */ @@ -41,37 +37,35 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt return -1; } - bitstate->mask = (1<bits)-1; + bitstate->mask = (1 << bitstate->bits) - 1; if (bitstate->sign) { - bitstate->signmask = (1<<(bitstate->bits-1)); + bitstate->signmask = (1 << (bitstate->bits - 1)); } /* check image orientation */ if (state->ystep < 0) { - state->y = state->ysize-1; + state->y = state->ysize - 1; state->ystep = -1; } else { state->ystep = 1; } state->state = 1; - } ptr = buf; while (bytes > 0) { - UINT8 byte = *ptr; ptr++; bytes--; /* get a byte from the input stream and insert in the bit buffer */ - if (bitstate->fill&1) { + if (bitstate->fill & 1) { /* fill MSB first */ - bitstate->bitbuffer |= (unsigned long) byte << bitstate->bitcount; + bitstate->bitbuffer |= (unsigned long)byte << bitstate->bitcount; } else { /* fill LSB first */ bitstate->bitbuffer = (bitstate->bitbuffer << 8) | byte; @@ -80,26 +74,24 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt bitstate->bitcount += 8; while (bitstate->bitcount >= bitstate->bits) { - /* get a pixel from the bit buffer */ unsigned long data; FLOAT32 pixel; - if (bitstate->fill&2) { + if (bitstate->fill & 2) { /* store LSB first */ data = bitstate->bitbuffer & bitstate->mask; if (bitstate->bitcount > 32) { /* bitbuffer overflow; restore it from last input byte */ - bitstate->bitbuffer = byte >> (8 - (bitstate->bitcount - - bitstate->bits)); + bitstate->bitbuffer = + byte >> (8 - (bitstate->bitcount - bitstate->bits)); } else { bitstate->bitbuffer >>= bitstate->bits; } } else { /* store MSB first */ - data = (bitstate->bitbuffer >> (bitstate->bitcount - - bitstate->bits)) - & bitstate->mask; + data = (bitstate->bitbuffer >> (bitstate->bitcount - bitstate->bits)) & + bitstate->mask; } bitstate->bitcount -= bitstate->bits; @@ -109,7 +101,7 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt if (data <= 0) { pixel = bitstate->lut[0]; } else if (data >= bitstate->lutsize) { - pixel = bitstate->lut[bitstate->lutsize-1]; + pixel = bitstate->lut[bitstate->lutsize - 1]; } else { pixel = bitstate->lut[data]; } @@ -117,13 +109,13 @@ ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt /* convert */ if (data & bitstate->signmask) { /* image memory contains signed data */ - pixel = (FLOAT32) (INT32) (data | ~bitstate->mask); + pixel = (FLOAT32)(INT32)(data | ~bitstate->mask); } else { - pixel = (FLOAT32) data; + pixel = (FLOAT32)data; } } - *(FLOAT32*)(&im->image32[state->y][state->x]) = pixel; + *(FLOAT32 *)(&im->image32[state->y][state->x]) = pixel; /* step forward */ if (++state->x >= state->xsize) { diff --git a/src/libImaging/Blend.c b/src/libImaging/Blend.c index 0bac4cda9..a53ae0fad 100644 --- a/src/libImaging/Blend.c +++ b/src/libImaging/Blend.c @@ -15,27 +15,22 @@ * See the README file for details on usage and redistribution. */ - #include "Imaging.h" - Imaging -ImagingBlend(Imaging imIn1, Imaging imIn2, float alpha) -{ +ImagingBlend(Imaging imIn1, Imaging imIn2, float alpha) { Imaging imOut; int x, y; /* Check arguments */ - if (!imIn1 || !imIn2 || imIn1->type != IMAGING_TYPE_UINT8 - || imIn1->palette || strcmp(imIn1->mode, "1") == 0 - || imIn2->palette || strcmp(imIn2->mode, "1") == 0) { + if (!imIn1 || !imIn2 || imIn1->type != IMAGING_TYPE_UINT8 || imIn1->palette || + strcmp(imIn1->mode, "1") == 0 || imIn2->palette || + strcmp(imIn2->mode, "1") == 0) { return ImagingError_ModeError(); } - if (imIn1->type != imIn2->type || - imIn1->bands != imIn2->bands || - imIn1->xsize != imIn2->xsize || - imIn1->ysize != imIn2->ysize) { + if (imIn1->type != imIn2->type || imIn1->bands != imIn2->bands || + imIn1->xsize != imIn2->xsize || imIn1->ysize != imIn2->ysize) { return ImagingError_Mismatch(); } @@ -54,29 +49,27 @@ ImagingBlend(Imaging imIn1, Imaging imIn2, float alpha) if (alpha >= 0 && alpha <= 1.0) { /* Interpolate between bands */ for (y = 0; y < imIn1->ysize; y++) { - UINT8* in1 = (UINT8*) imIn1->image[y]; - UINT8* in2 = (UINT8*) imIn2->image[y]; - UINT8* out = (UINT8*) imOut->image[y]; + UINT8 *in1 = (UINT8 *)imIn1->image[y]; + UINT8 *in2 = (UINT8 *)imIn2->image[y]; + UINT8 *out = (UINT8 *)imOut->image[y]; for (x = 0; x < imIn1->linesize; x++) { - out[x] = (UINT8) - ((int) in1[x] + alpha * ((int) in2[x] - (int) in1[x])); + out[x] = (UINT8)((int)in1[x] + alpha * ((int)in2[x] - (int)in1[x])); } } } else { /* Extrapolation; must make sure to clip resulting values */ for (y = 0; y < imIn1->ysize; y++) { - UINT8* in1 = (UINT8*) imIn1->image[y]; - UINT8* in2 = (UINT8*) imIn2->image[y]; - UINT8* out = (UINT8*) imOut->image[y]; + UINT8 *in1 = (UINT8 *)imIn1->image[y]; + UINT8 *in2 = (UINT8 *)imIn2->image[y]; + UINT8 *out = (UINT8 *)imOut->image[y]; for (x = 0; x < imIn1->linesize; x++) { - float temp = (float) - ((int) in1[x] + alpha * ((int) in2[x] - (int) in1[x])); + float temp = (float)((int)in1[x] + alpha * ((int)in2[x] - (int)in1[x])); if (temp <= 0.0) { out[x] = 0; } else if (temp >= 255.0) { out[x] = 255; } else { - out[x] = (UINT8) temp; + out[x] = (UINT8)temp; } } } diff --git a/src/libImaging/BoxBlur.c b/src/libImaging/BoxBlur.c index dcdc52cbc..88862eb73 100644 --- a/src/libImaging/BoxBlur.c +++ b/src/libImaging/BoxBlur.c @@ -1,37 +1,40 @@ #include "Imaging.h" - #define MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) - typedef UINT8 pixel[4]; -void static inline -ImagingLineBoxBlur32(pixel *lineOut, pixel *lineIn, int lastx, int radius, int edgeA, - int edgeB, UINT32 ww, UINT32 fw) -{ +void static inline ImagingLineBoxBlur32( + pixel *lineOut, + pixel *lineIn, + int lastx, + int radius, + int edgeA, + int edgeB, + UINT32 ww, + UINT32 fw) { int x; UINT32 acc[4]; UINT32 bulk[4]; - #define MOVE_ACC(acc, subtract, add) \ - acc[0] += lineIn[add][0] - lineIn[subtract][0]; \ - acc[1] += lineIn[add][1] - lineIn[subtract][1]; \ - acc[2] += lineIn[add][2] - lineIn[subtract][2]; \ - acc[3] += lineIn[add][3] - lineIn[subtract][3]; +#define MOVE_ACC(acc, subtract, add) \ + acc[0] += lineIn[add][0] - lineIn[subtract][0]; \ + acc[1] += lineIn[add][1] - lineIn[subtract][1]; \ + acc[2] += lineIn[add][2] - lineIn[subtract][2]; \ + acc[3] += lineIn[add][3] - lineIn[subtract][3]; - #define ADD_FAR(bulk, acc, left, right) \ - bulk[0] = (acc[0] * ww) + (lineIn[left][0] + lineIn[right][0]) * fw; \ - bulk[1] = (acc[1] * ww) + (lineIn[left][1] + lineIn[right][1]) * fw; \ - bulk[2] = (acc[2] * ww) + (lineIn[left][2] + lineIn[right][2]) * fw; \ - bulk[3] = (acc[3] * ww) + (lineIn[left][3] + lineIn[right][3]) * fw; +#define ADD_FAR(bulk, acc, left, right) \ + bulk[0] = (acc[0] * ww) + (lineIn[left][0] + lineIn[right][0]) * fw; \ + bulk[1] = (acc[1] * ww) + (lineIn[left][1] + lineIn[right][1]) * fw; \ + bulk[2] = (acc[2] * ww) + (lineIn[left][2] + lineIn[right][2]) * fw; \ + bulk[3] = (acc[3] * ww) + (lineIn[left][3] + lineIn[right][3]) * fw; - #define SAVE(x, bulk) \ - lineOut[x][0] = (UINT8)((bulk[0] + (1 << 23)) >> 24); \ - lineOut[x][1] = (UINT8)((bulk[1] + (1 << 23)) >> 24); \ - lineOut[x][2] = (UINT8)((bulk[2] + (1 << 23)) >> 24); \ - lineOut[x][3] = (UINT8)((bulk[3] + (1 << 23)) >> 24); +#define SAVE(x, bulk) \ + lineOut[x][0] = (UINT8)((bulk[0] + (1 << 23)) >> 24); \ + lineOut[x][1] = (UINT8)((bulk[1] + (1 << 23)) >> 24); \ + lineOut[x][2] = (UINT8)((bulk[2] + (1 << 23)) >> 24); \ + lineOut[x][3] = (UINT8)((bulk[3] + (1 << 23)) >> 24); /* Compute acc for -1 pixel (outside of image): From "-radius-1" to "-1" get first pixel, @@ -53,8 +56,7 @@ ImagingLineBoxBlur32(pixel *lineOut, pixel *lineIn, int lastx, int radius, int e acc[2] += lineIn[lastx][2] * (radius - edgeA + 1); acc[3] += lineIn[lastx][3] * (radius - edgeA + 1); - if (edgeA <= edgeB) - { + if (edgeA <= edgeB) { /* Subtract pixel from left ("0"). Add pixels from radius. */ for (x = 0; x < edgeA; x++) { @@ -76,9 +78,7 @@ ImagingLineBoxBlur32(pixel *lineOut, pixel *lineIn, int lastx, int radius, int e ADD_FAR(bulk, acc, x - radius - 1, lastx); SAVE(x, bulk); } - } - else - { + } else { for (x = 0; x < edgeB; x++) { MOVE_ACC(acc, 0, x + radius); ADD_FAR(bulk, acc, 0, x + radius + 1); @@ -96,28 +96,30 @@ ImagingLineBoxBlur32(pixel *lineOut, pixel *lineIn, int lastx, int radius, int e } } - #undef MOVE_ACC - #undef ADD_FAR - #undef SAVE +#undef MOVE_ACC +#undef ADD_FAR +#undef SAVE } - -void static inline -ImagingLineBoxBlur8(UINT8 *lineOut, UINT8 *lineIn, int lastx, int radius, int edgeA, - int edgeB, UINT32 ww, UINT32 fw) -{ +void static inline ImagingLineBoxBlur8( + UINT8 *lineOut, + UINT8 *lineIn, + int lastx, + int radius, + int edgeA, + int edgeB, + UINT32 ww, + UINT32 fw) { int x; UINT32 acc; UINT32 bulk; - #define MOVE_ACC(acc, subtract, add) \ - acc += lineIn[add] - lineIn[subtract]; +#define MOVE_ACC(acc, subtract, add) acc += lineIn[add] - lineIn[subtract]; - #define ADD_FAR(bulk, acc, left, right) \ - bulk = (acc * ww) + (lineIn[left] + lineIn[right]) * fw; +#define ADD_FAR(bulk, acc, left, right) \ + bulk = (acc * ww) + (lineIn[left] + lineIn[right]) * fw; - #define SAVE(x, bulk) \ - lineOut[x] = (UINT8)((bulk + (1 << 23)) >> 24) +#define SAVE(x, bulk) lineOut[x] = (UINT8)((bulk + (1 << 23)) >> 24) acc = lineIn[0] * (radius + 1); for (x = 0; x < edgeA - 1; x++) { @@ -125,8 +127,7 @@ ImagingLineBoxBlur8(UINT8 *lineOut, UINT8 *lineIn, int lastx, int radius, int ed } acc += lineIn[lastx] * (radius - edgeA + 1); - if (edgeA <= edgeB) - { + if (edgeA <= edgeB) { for (x = 0; x < edgeA; x++) { MOVE_ACC(acc, 0, x + radius); ADD_FAR(bulk, acc, 0, x + radius + 1); @@ -142,9 +143,7 @@ ImagingLineBoxBlur8(UINT8 *lineOut, UINT8 *lineIn, int lastx, int radius, int ed ADD_FAR(bulk, acc, x - radius - 1, lastx); SAVE(x, bulk); } - } - else - { + } else { for (x = 0; x < edgeB; x++) { MOVE_ACC(acc, 0, x + radius); ADD_FAR(bulk, acc, 0, x + radius + 1); @@ -162,22 +161,19 @@ ImagingLineBoxBlur8(UINT8 *lineOut, UINT8 *lineIn, int lastx, int radius, int ed } } - #undef MOVE_ACC - #undef ADD_FAR - #undef SAVE +#undef MOVE_ACC +#undef ADD_FAR +#undef SAVE } - - Imaging -ImagingHorizontalBoxBlur(Imaging imOut, Imaging imIn, float floatRadius) -{ +ImagingHorizontalBoxBlur(Imaging imOut, Imaging imIn, float floatRadius) { ImagingSectionCookie cookie; int y; - int radius = (int) floatRadius; - UINT32 ww = (UINT32) (1 << 24) / (floatRadius * 2 + 1); + int radius = (int)floatRadius; + UINT32 ww = (UINT32)(1 << 24) / (floatRadius * 2 + 1); UINT32 fw = ((1 << 24) - (radius * 2 + 1) * ww) / 2; int edgeA = MIN(radius + 1, imIn->xsize); @@ -192,32 +188,33 @@ ImagingHorizontalBoxBlur(Imaging imOut, Imaging imIn, float floatRadius) ImagingSectionEnter(&cookie); - if (imIn->image8) - { + if (imIn->image8) { for (y = 0; y < imIn->ysize; y++) { ImagingLineBoxBlur8( - (imIn == imOut ? (UINT8 *) lineOut : imOut->image8[y]), + (imIn == imOut ? (UINT8 *)lineOut : imOut->image8[y]), imIn->image8[y], imIn->xsize - 1, - radius, edgeA, edgeB, - ww, fw - ); + radius, + edgeA, + edgeB, + ww, + fw); if (imIn == imOut) { // Commit. memcpy(imOut->image8[y], lineOut, imIn->xsize); } } - } - else - { + } else { for (y = 0; y < imIn->ysize; y++) { ImagingLineBoxBlur32( - imIn == imOut ? (pixel *) lineOut : (pixel *) imOut->image32[y], - (pixel *) imIn->image32[y], + imIn == imOut ? (pixel *)lineOut : (pixel *)imOut->image32[y], + (pixel *)imIn->image32[y], imIn->xsize - 1, - radius, edgeA, edgeB, - ww, fw - ); + radius, + edgeA, + edgeB, + ww, + fw); if (imIn == imOut) { // Commit. memcpy(imOut->image32[y], lineOut, imIn->xsize * 4); @@ -232,23 +229,17 @@ ImagingHorizontalBoxBlur(Imaging imOut, Imaging imIn, float floatRadius) return imOut; } - Imaging -ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n) -{ +ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n) { int i; Imaging imTransposed; if (n < 1) { - return ImagingError_ValueError( - "number of passes must be greater than zero" - ); + return ImagingError_ValueError("number of passes must be greater than zero"); } - if (strcmp(imIn->mode, imOut->mode) || - imIn->type != imOut->type || - imIn->bands != imOut->bands || - imIn->xsize != imOut->xsize || + if (strcmp(imIn->mode, imOut->mode) || imIn->type != imOut->type || + imIn->bands != imOut->bands || imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize) { return ImagingError_Mismatch(); } @@ -257,14 +248,10 @@ ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n) return ImagingError_ModeError(); } - if (!(strcmp(imIn->mode, "RGB") == 0 || - strcmp(imIn->mode, "RGBA") == 0 || - strcmp(imIn->mode, "RGBa") == 0 || - strcmp(imIn->mode, "RGBX") == 0 || - strcmp(imIn->mode, "CMYK") == 0 || - strcmp(imIn->mode, "L") == 0 || - strcmp(imIn->mode, "LA") == 0 || - strcmp(imIn->mode, "La") == 0)) { + if (!(strcmp(imIn->mode, "RGB") == 0 || strcmp(imIn->mode, "RGBA") == 0 || + strcmp(imIn->mode, "RGBa") == 0 || strcmp(imIn->mode, "RGBX") == 0 || + strcmp(imIn->mode, "CMYK") == 0 || strcmp(imIn->mode, "L") == 0 || + strcmp(imIn->mode, "LA") == 0 || strcmp(imIn->mode, "La") == 0)) { return ImagingError_ModeError(); } @@ -277,14 +264,14 @@ ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n) Use imOut as a destination at first pass, then use imOut as a source too. */ ImagingHorizontalBoxBlur(imOut, imIn, radius); - for (i = 1; i < n; i ++) { + for (i = 1; i < n; i++) { ImagingHorizontalBoxBlur(imOut, imOut, radius); } /* Transpose result for blur in another direction. */ ImagingTranspose(imTransposed, imOut); /* Reuse imTransposed as a source and destination there. */ - for (i = 0; i < n; i ++) { + for (i = 0; i < n; i++) { ImagingHorizontalBoxBlur(imTransposed, imTransposed, radius); } /* Restore original orientation. */ @@ -295,10 +282,8 @@ ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n) return imOut; } - -Imaging ImagingGaussianBlur(Imaging imOut, Imaging imIn, float radius, - int passes) -{ +Imaging +ImagingGaussianBlur(Imaging imOut, Imaging imIn, float radius, int passes) { float sigma2, L, l, a; sigma2 = radius * radius / passes; diff --git a/src/libImaging/Chops.c b/src/libImaging/Chops.c index a0a70abd9..f9c005efe 100644 --- a/src/libImaging/Chops.c +++ b/src/libImaging/Chops.c @@ -16,62 +16,59 @@ * See the README file for details on usage and redistribution. */ - #include "Imaging.h" -#define CHOP(operation)\ - int x, y;\ - Imaging imOut;\ - imOut = create(imIn1, imIn2, NULL);\ - if (!imOut) {\ - return NULL;\ - }\ - for (y = 0; y < imOut->ysize; y++) {\ - UINT8* out = (UINT8*) imOut->image[y];\ - UINT8* in1 = (UINT8*) imIn1->image[y];\ - UINT8* in2 = (UINT8*) imIn2->image[y];\ - for (x = 0; x < imOut->linesize; x++) {\ - int temp = operation;\ - if (temp <= 0) {\ - out[x] = 0;\ - } else if (temp >= 255) {\ - out[x] = 255;\ - } else {\ - out[x] = temp;\ - }\ - }\ - }\ +#define CHOP(operation) \ + int x, y; \ + Imaging imOut; \ + imOut = create(imIn1, imIn2, NULL); \ + if (!imOut) { \ + return NULL; \ + } \ + for (y = 0; y < imOut->ysize; y++) { \ + UINT8 *out = (UINT8 *)imOut->image[y]; \ + UINT8 *in1 = (UINT8 *)imIn1->image[y]; \ + UINT8 *in2 = (UINT8 *)imIn2->image[y]; \ + for (x = 0; x < imOut->linesize; x++) { \ + int temp = operation; \ + if (temp <= 0) { \ + out[x] = 0; \ + } else if (temp >= 255) { \ + out[x] = 255; \ + } else { \ + out[x] = temp; \ + } \ + } \ + } \ return imOut; -#define CHOP2(operation, mode)\ - int x, y;\ - Imaging imOut;\ - imOut = create(imIn1, imIn2, mode);\ - if (!imOut) {\ - return NULL;\ - }\ - for (y = 0; y < imOut->ysize; y++) {\ - UINT8* out = (UINT8*) imOut->image[y];\ - UINT8* in1 = (UINT8*) imIn1->image[y];\ - UINT8* in2 = (UINT8*) imIn2->image[y];\ - for (x = 0; x < imOut->linesize; x++) {\ - out[x] = operation;\ - }\ - }\ +#define CHOP2(operation, mode) \ + int x, y; \ + Imaging imOut; \ + imOut = create(imIn1, imIn2, mode); \ + if (!imOut) { \ + return NULL; \ + } \ + for (y = 0; y < imOut->ysize; y++) { \ + UINT8 *out = (UINT8 *)imOut->image[y]; \ + UINT8 *in1 = (UINT8 *)imIn1->image[y]; \ + UINT8 *in2 = (UINT8 *)imIn2->image[y]; \ + for (x = 0; x < imOut->linesize; x++) { \ + out[x] = operation; \ + } \ + } \ return imOut; static Imaging -create(Imaging im1, Imaging im2, char* mode) -{ +create(Imaging im1, Imaging im2, char *mode) { int xsize, ysize; if (!im1 || !im2 || im1->type != IMAGING_TYPE_UINT8 || (mode != NULL && (strcmp(im1->mode, "1") || strcmp(im2->mode, "1")))) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } - if (im1->type != im2->type || - im1->bands != im2->bands) { - return (Imaging) ImagingError_Mismatch(); + if (im1->type != im2->type || im1->bands != im2->bands) { + return (Imaging)ImagingError_Mismatch(); } xsize = (im1->xsize < im2->xsize) ? im1->xsize : im2->xsize; @@ -81,97 +78,85 @@ create(Imaging im1, Imaging im2, char* mode) } Imaging -ImagingChopLighter(Imaging imIn1, Imaging imIn2) -{ +ImagingChopLighter(Imaging imIn1, Imaging imIn2) { CHOP((in1[x] > in2[x]) ? in1[x] : in2[x]); } Imaging -ImagingChopDarker(Imaging imIn1, Imaging imIn2) -{ +ImagingChopDarker(Imaging imIn1, Imaging imIn2) { CHOP((in1[x] < in2[x]) ? in1[x] : in2[x]); } Imaging -ImagingChopDifference(Imaging imIn1, Imaging imIn2) -{ - CHOP(abs((int) in1[x] - (int) in2[x])); +ImagingChopDifference(Imaging imIn1, Imaging imIn2) { + CHOP(abs((int)in1[x] - (int)in2[x])); } Imaging -ImagingChopMultiply(Imaging imIn1, Imaging imIn2) -{ - CHOP((int) in1[x] * (int) in2[x] / 255); +ImagingChopMultiply(Imaging imIn1, Imaging imIn2) { + CHOP((int)in1[x] * (int)in2[x] / 255); } Imaging -ImagingChopScreen(Imaging imIn1, Imaging imIn2) -{ - CHOP(255 - ((int) (255 - in1[x]) * (int) (255 - in2[x])) / 255); +ImagingChopScreen(Imaging imIn1, Imaging imIn2) { + CHOP(255 - ((int)(255 - in1[x]) * (int)(255 - in2[x])) / 255); } Imaging -ImagingChopAdd(Imaging imIn1, Imaging imIn2, float scale, int offset) -{ - CHOP(((int) in1[x] + (int) in2[x]) / scale + offset); +ImagingChopAdd(Imaging imIn1, Imaging imIn2, float scale, int offset) { + CHOP(((int)in1[x] + (int)in2[x]) / scale + offset); } Imaging -ImagingChopSubtract(Imaging imIn1, Imaging imIn2, float scale, int offset) -{ - CHOP(((int) in1[x] - (int) in2[x]) / scale + offset); +ImagingChopSubtract(Imaging imIn1, Imaging imIn2, float scale, int offset) { + CHOP(((int)in1[x] - (int)in2[x]) / scale + offset); } Imaging -ImagingChopAnd(Imaging imIn1, Imaging imIn2) -{ +ImagingChopAnd(Imaging imIn1, Imaging imIn2) { CHOP2((in1[x] && in2[x]) ? 255 : 0, "1"); } Imaging -ImagingChopOr(Imaging imIn1, Imaging imIn2) -{ +ImagingChopOr(Imaging imIn1, Imaging imIn2) { CHOP2((in1[x] || in2[x]) ? 255 : 0, "1"); } Imaging -ImagingChopXor(Imaging imIn1, Imaging imIn2) -{ +ImagingChopXor(Imaging imIn1, Imaging imIn2) { CHOP2(((in1[x] != 0) ^ (in2[x] != 0)) ? 255 : 0, "1"); } Imaging -ImagingChopAddModulo(Imaging imIn1, Imaging imIn2) -{ +ImagingChopAddModulo(Imaging imIn1, Imaging imIn2) { CHOP2(in1[x] + in2[x], NULL); } Imaging -ImagingChopSubtractModulo(Imaging imIn1, Imaging imIn2) -{ +ImagingChopSubtractModulo(Imaging imIn1, Imaging imIn2) { CHOP2(in1[x] - in2[x], NULL); } Imaging -ImagingChopSoftLight(Imaging imIn1, Imaging imIn2) -{ - CHOP2( (((255-in1[x]) * (in1[x]*in2[x]) ) / 65536) + - (in1[x] * ( 255 - ( (255 - in1[x]) * (255 - in2[x] ) / 255) )) / 255 - , NULL ); +ImagingChopSoftLight(Imaging imIn1, Imaging imIn2) { + CHOP2( + (((255 - in1[x]) * (in1[x] * in2[x])) / 65536) + + (in1[x] * (255 - ((255 - in1[x]) * (255 - in2[x]) / 255))) / 255, + NULL); } Imaging -ImagingChopHardLight(Imaging imIn1, Imaging imIn2) -{ - CHOP2( (in2[x]<128) ? ( (in1[x]*in2[x])/127) - : 255 - ( ((255-in2[x]) * (255-in1[x])) / 127) - , NULL); +ImagingChopHardLight(Imaging imIn1, Imaging imIn2) { + CHOP2( + (in2[x] < 128) ? ((in1[x] * in2[x]) / 127) + : 255 - (((255 - in2[x]) * (255 - in1[x])) / 127), + NULL); } Imaging -ImagingOverlay(Imaging imIn1, Imaging imIn2) -{ - CHOP2( (in1[x]<128) ? ( (in1[x]*in2[x])/127) - : 255 - ( ((255-in1[x]) * (255-in2[x])) / 127) - , NULL); +ImagingOverlay(Imaging imIn1, Imaging imIn2) { + CHOP2( + (in1[x] < 128) ? ((in1[x] * in2[x]) / 127) + : 255 - (((255 - in1[x]) * (255 - in2[x])) / 127), + NULL); } diff --git a/src/libImaging/ColorLUT.c b/src/libImaging/ColorLUT.c index f01d38993..fd6e268b5 100644 --- a/src/libImaging/ColorLUT.c +++ b/src/libImaging/ColorLUT.c @@ -1,52 +1,45 @@ #include "Imaging.h" #include - /* 8 bits for result. Table can overflow [0, 1.0] range, so we need extra bits for overflow and negative values. NOTE: This value should be the same as in _imaging/_prepare_lut_table() */ #define PRECISION_BITS (16 - 8 - 2) -#define PRECISION_ROUNDING (1<<(PRECISION_BITS-1)) +#define PRECISION_ROUNDING (1 << (PRECISION_BITS - 1)) /* 8 — scales are multiplied on byte. 6 — max index in the table (max size is 65, but index 64 is not reachable) */ #define SCALE_BITS (32 - 8 - 6) -#define SCALE_MASK ((1<> PRECISION_BITS]; } static inline void -interpolate3(INT16 out[3], const INT16 a[3], const INT16 b[3], INT16 shift) -{ - out[0] = (a[0] * ((1<> SHIFT_BITS; - out[1] = (a[1] * ((1<> SHIFT_BITS; - out[2] = (a[2] * ((1<> SHIFT_BITS; +interpolate3(INT16 out[3], const INT16 a[3], const INT16 b[3], INT16 shift) { + out[0] = (a[0] * ((1 << SHIFT_BITS) - shift) + b[0] * shift) >> SHIFT_BITS; + out[1] = (a[1] * ((1 << SHIFT_BITS) - shift) + b[1] * shift) >> SHIFT_BITS; + out[2] = (a[2] * ((1 << SHIFT_BITS) - shift) + b[2] * shift) >> SHIFT_BITS; } static inline void -interpolate4(INT16 out[4], const INT16 a[4], const INT16 b[4], INT16 shift) -{ - out[0] = (a[0] * ((1<> SHIFT_BITS; - out[1] = (a[1] * ((1<> SHIFT_BITS; - out[2] = (a[2] * ((1<> SHIFT_BITS; - out[3] = (a[3] * ((1<> SHIFT_BITS; +interpolate4(INT16 out[4], const INT16 a[4], const INT16 b[4], INT16 shift) { + out[0] = (a[0] * ((1 << SHIFT_BITS) - shift) + b[0] * shift) >> SHIFT_BITS; + out[1] = (a[1] * ((1 << SHIFT_BITS) - shift) + b[1] * shift) >> SHIFT_BITS; + out[2] = (a[2] * ((1 << SHIFT_BITS) - shift) + b[2] * shift) >> SHIFT_BITS; + out[3] = (a[3] * ((1 << SHIFT_BITS) - shift) + b[3] * shift) >> SHIFT_BITS; } static inline int -table_index3D(int index1D, int index2D, int index3D, - int size1D, int size1D_2D) -{ +table_index3D(int index1D, int index2D, int index3D, int size1D, int size1D_2D) { return index1D + index2D * size1D + index3D * size1D_2D; } - /* Transforms colors of imIn using provided 3D lookup table and puts the result in imOut. Returns imOut on success or 0 on error. @@ -63,10 +56,14 @@ table_index3D(int index1D, int index2D, int index3D, and 255 << PRECISION_BITS (16320) is highest value. */ Imaging -ImagingColorLUT3D_linear(Imaging imOut, Imaging imIn, int table_channels, - int size1D, int size2D, int size3D, - INT16* table) -{ +ImagingColorLUT3D_linear( + Imaging imOut, + Imaging imIn, + int table_channels, + int size1D, + int size2D, + int size3D, + INT16 *table) { /* This float to int conversion doesn't have rounding error compensation (+0.5) for two reasons: 1. As we don't hit the highest value, @@ -77,9 +74,9 @@ ImagingColorLUT3D_linear(Imaging imOut, Imaging imIn, int table_channels, +1 cells will be outside of the table. With this compensation we never hit the upper cells but this also doesn't introduce any noticeable difference. */ - UINT32 scale1D = (size1D - 1) / 255.0 * (1<type != IMAGING_TYPE_UINT8 || - imOut->type != IMAGING_TYPE_UINT8 || - imIn->bands < 3 || - imOut->bands < table_channels - ) { - return (Imaging) ImagingError_ModeError(); + if (imIn->type != IMAGING_TYPE_UINT8 || imOut->type != IMAGING_TYPE_UINT8 || + imIn->bands < 3 || imOut->bands < table_channels) { + return (Imaging)ImagingError_ModeError(); } /* In case we have one extra band in imOut and don't have in imIn.*/ if (imOut->bands > table_channels && imOut->bands > imIn->bands) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } ImagingSectionEnter(&cookie); for (y = 0; y < imOut->ysize; y++) { - UINT8* rowIn = (UINT8 *)imIn->image[y]; - char* rowOut = (char *)imOut->image[y]; + UINT8 *rowIn = (UINT8 *)imIn->image[y]; + char *rowOut = (char *)imOut->image[y]; for (x = 0; x < imOut->xsize; x++) { - UINT32 index1D = rowIn[x*4 + 0] * scale1D; - UINT32 index2D = rowIn[x*4 + 1] * scale2D; - UINT32 index3D = rowIn[x*4 + 2] * scale3D; + UINT32 index1D = rowIn[x * 4 + 0] * scale1D; + UINT32 index2D = rowIn[x * 4 + 1] * scale2D; + UINT32 index3D = rowIn[x * 4 + 2] * scale3D; INT16 shift1D = (SCALE_MASK & index1D) >> (SCALE_BITS - SHIFT_BITS); INT16 shift2D = (SCALE_MASK & index2D) >> (SCALE_BITS - SHIFT_BITS); INT16 shift3D = (SCALE_MASK & index3D) >> (SCALE_BITS - SHIFT_BITS); int idx = table_channels * table_index3D( - index1D >> SCALE_BITS, index2D >> SCALE_BITS, - index3D >> SCALE_BITS, size1D, size1D_2D); + index1D >> SCALE_BITS, + index2D >> SCALE_BITS, + index3D >> SCALE_BITS, + size1D, + size1D_2D); INT16 result[4], left[4], right[4]; INT16 leftleft[4], leftright[4], rightleft[4], rightright[4]; if (table_channels == 3) { UINT32 v; interpolate3(leftleft, &table[idx + 0], &table[idx + 3], shift1D); - interpolate3(leftright, &table[idx + size1D*3], - &table[idx + size1D*3 + 3], shift1D); + interpolate3( + leftright, + &table[idx + size1D * 3], + &table[idx + size1D * 3 + 3], + shift1D); interpolate3(left, leftleft, leftright, shift2D); - interpolate3(rightleft, &table[idx + size1D_2D*3], - &table[idx + size1D_2D*3 + 3], shift1D); - interpolate3(rightright, &table[idx + size1D_2D*3 + size1D*3], - &table[idx + size1D_2D*3 + size1D*3 + 3], shift1D); + interpolate3( + rightleft, + &table[idx + size1D_2D * 3], + &table[idx + size1D_2D * 3 + 3], + shift1D); + interpolate3( + rightright, + &table[idx + size1D_2D * 3 + size1D * 3], + &table[idx + size1D_2D * 3 + size1D * 3 + 3], + shift1D); interpolate3(right, rightleft, rightright, shift2D); interpolate3(result, left, right, shift3D); v = MAKE_UINT32( - clip8(result[0]), clip8(result[1]), - clip8(result[2]), rowIn[x*4 + 3]); + clip8(result[0]), + clip8(result[1]), + clip8(result[2]), + rowIn[x * 4 + 3]); memcpy(rowOut + x * sizeof(v), &v, sizeof(v)); } if (table_channels == 4) { UINT32 v; interpolate4(leftleft, &table[idx + 0], &table[idx + 4], shift1D); - interpolate4(leftright, &table[idx + size1D*4], - &table[idx + size1D*4 + 4], shift1D); + interpolate4( + leftright, + &table[idx + size1D * 4], + &table[idx + size1D * 4 + 4], + shift1D); interpolate4(left, leftleft, leftright, shift2D); - interpolate4(rightleft, &table[idx + size1D_2D*4], - &table[idx + size1D_2D*4 + 4], shift1D); - interpolate4(rightright, &table[idx + size1D_2D*4 + size1D*4], - &table[idx + size1D_2D*4 + size1D*4 + 4], shift1D); + interpolate4( + rightleft, + &table[idx + size1D_2D * 4], + &table[idx + size1D_2D * 4 + 4], + shift1D); + interpolate4( + rightright, + &table[idx + size1D_2D * 4 + size1D * 4], + &table[idx + size1D_2D * 4 + size1D * 4 + 4], + shift1D); interpolate4(right, rightleft, rightright, shift2D); interpolate4(result, left, right, shift3D); v = MAKE_UINT32( - clip8(result[0]), clip8(result[1]), - clip8(result[2]), clip8(result[3])); + clip8(result[0]), + clip8(result[1]), + clip8(result[2]), + clip8(result[3])); memcpy(rowOut + x * sizeof(v), &v, sizeof(v)); } } diff --git a/src/libImaging/Convert.c b/src/libImaging/Convert.c index b0b794d72..8c7be36a2 100644 --- a/src/libImaging/Convert.c +++ b/src/libImaging/Convert.c @@ -32,24 +32,21 @@ * See the README file for details on usage and redistribution. */ - #include "Imaging.h" -#define MAX(a, b) (a)>(b) ? (a) : (b) -#define MIN(a, b) (a)<(b) ? (a) : (b) +#define MAX(a, b) (a) > (b) ? (a) : (b) +#define MIN(a, b) (a) < (b) ? (a) : (b) #define CLIP16(v) ((v) <= -32768 ? -32768 : (v) >= 32767 ? 32767 : (v)) /* ITU-R Recommendation 601-2 (assuming nonlinear RGB) */ -#define L(rgb)\ - ((INT32) (rgb)[0]*299 + (INT32) (rgb)[1]*587 + (INT32) (rgb)[2]*114) -#define L24(rgb)\ - ((rgb)[0]*19595 + (rgb)[1]*38470 + (rgb)[2]*7471 + 0x8000) - +#define L(rgb) ((INT32)(rgb)[0] * 299 + (INT32)(rgb)[1] * 587 + (INT32)(rgb)[2] * 114) +#define L24(rgb) ((rgb)[0] * 19595 + (rgb)[1] * 38470 + (rgb)[2] * 7471 + 0x8000) #ifndef round -double round(double x) { - return floor(x+0.5); +double +round(double x) { + return floor(x + 0.5); } #endif @@ -58,16 +55,13 @@ double round(double x) { /* ------------------- */ static void -bit2l(UINT8* out, const UINT8* in, int xsize) -{ +bit2l(UINT8 *out, const UINT8 *in, int xsize) { int x; - for (x = 0; x < xsize; x++) - *out++ = (*in++ != 0) ? 255 : 0; + for (x = 0; x < xsize; x++) *out++ = (*in++ != 0) ? 255 : 0; } static void -bit2rgb(UINT8* out, const UINT8* in, int xsize) -{ +bit2rgb(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { UINT8 v = (*in++ != 0) ? 255 : 0; @@ -79,8 +73,7 @@ bit2rgb(UINT8* out, const UINT8* in, int xsize) } static void -bit2cmyk(UINT8* out, const UINT8* in, int xsize) -{ +bit2cmyk(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { *out++ = 0; @@ -91,8 +84,7 @@ bit2cmyk(UINT8* out, const UINT8* in, int xsize) } static void -bit2ycbcr(UINT8* out, const UINT8* in, int xsize) -{ +bit2ycbcr(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { *out++ = (*in++ != 0) ? 255 : 0; @@ -103,8 +95,7 @@ bit2ycbcr(UINT8* out, const UINT8* in, int xsize) } static void -bit2hsv(UINT8* out, const UINT8* in, int xsize) -{ +bit2hsv(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, out += 4) { UINT8 v = (*in++ != 0) ? 255 : 0; @@ -120,8 +111,7 @@ bit2hsv(UINT8* out, const UINT8* in, int xsize) /* ----------------- */ static void -l2bit(UINT8* out, const UINT8* in, int xsize) -{ +l2bit(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { *out++ = (*in++ >= 128) ? 255 : 0; @@ -129,44 +119,41 @@ l2bit(UINT8* out, const UINT8* in, int xsize) } static void -lA2la(UINT8* out, const UINT8* in, int xsize) -{ +lA2la(UINT8 *out, const UINT8 *in, int xsize) { int x; unsigned int alpha, pixel, tmp; for (x = 0; x < xsize; x++, in += 4) { alpha = in[3]; pixel = MULDIV255(in[0], alpha, tmp); - *out++ = (UINT8) pixel; - *out++ = (UINT8) pixel; - *out++ = (UINT8) pixel; - *out++ = (UINT8) alpha; + *out++ = (UINT8)pixel; + *out++ = (UINT8)pixel; + *out++ = (UINT8)pixel; + *out++ = (UINT8)alpha; } } /* RGBa -> RGBA conversion to remove premultiplication Needed for correct transforms/resizing on RGBA images */ static void -la2lA(UINT8* out, const UINT8* in, int xsize) -{ +la2lA(UINT8 *out, const UINT8 *in, int xsize) { int x; unsigned int alpha, pixel; - for (x = 0; x < xsize; x++, in+=4) { + for (x = 0; x < xsize; x++, in += 4) { alpha = in[3]; if (alpha == 255 || alpha == 0) { pixel = in[0]; } else { pixel = CLIP8((255 * in[0]) / alpha); } - *out++ = (UINT8) pixel; - *out++ = (UINT8) pixel; - *out++ = (UINT8) pixel; - *out++ = (UINT8) alpha; + *out++ = (UINT8)pixel; + *out++ = (UINT8)pixel; + *out++ = (UINT8)pixel; + *out++ = (UINT8)alpha; } } static void -l2la(UINT8* out, const UINT8* in, int xsize) -{ +l2la(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { UINT8 v = *in++; @@ -178,8 +165,7 @@ l2la(UINT8* out, const UINT8* in, int xsize) } static void -l2rgb(UINT8* out, const UINT8* in, int xsize) -{ +l2rgb(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { UINT8 v = *in++; @@ -191,8 +177,7 @@ l2rgb(UINT8* out, const UINT8* in, int xsize) } static void -l2hsv(UINT8* out, const UINT8* in, int xsize) -{ +l2hsv(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, out += 4) { UINT8 v = *in++; @@ -204,8 +189,7 @@ l2hsv(UINT8* out, const UINT8* in, int xsize) } static void -la2l(UINT8* out, const UINT8* in, int xsize) -{ +la2l(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4) { *out++ = in[0]; @@ -213,8 +197,7 @@ la2l(UINT8* out, const UINT8* in, int xsize) } static void -la2rgb(UINT8* out, const UINT8* in, int xsize) -{ +la2rgb(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4) { UINT8 v = in[0]; @@ -226,8 +209,7 @@ la2rgb(UINT8* out, const UINT8* in, int xsize) } static void -la2hsv(UINT8* out, const UINT8* in, int xsize) -{ +la2hsv(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4, out += 4) { UINT8 v = in[0]; @@ -239,8 +221,7 @@ la2hsv(UINT8* out, const UINT8* in, int xsize) } static void -rgb2bit(UINT8* out, const UINT8* in, int xsize) -{ +rgb2bit(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4) { /* ITU-R Recommendation 601-2 (assuming nonlinear RGB) */ @@ -249,8 +230,7 @@ rgb2bit(UINT8* out, const UINT8* in, int xsize) } static void -rgb2l(UINT8* out, const UINT8* in, int xsize) -{ +rgb2l(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4) { /* ITU-R Recommendation 601-2 (assuming nonlinear RGB) */ @@ -259,8 +239,7 @@ rgb2l(UINT8* out, const UINT8* in, int xsize) } static void -rgb2la(UINT8* out, const UINT8* in, int xsize) -{ +rgb2la(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4, out += 4) { /* ITU-R Recommendation 601-2 (assuming nonlinear RGB) */ @@ -270,8 +249,7 @@ rgb2la(UINT8* out, const UINT8* in, int xsize) } static void -rgb2i(UINT8* out_, const UINT8* in, int xsize) -{ +rgb2i(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4, out_ += 4) { INT32 v = L24(in) >> 16; @@ -280,44 +258,38 @@ rgb2i(UINT8* out_, const UINT8* in, int xsize) } static void -rgb2f(UINT8* out_, const UINT8* in, int xsize) -{ +rgb2f(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4, out_ += 4) { - FLOAT32 v = (float) L(in) / 1000.0F; + FLOAT32 v = (float)L(in) / 1000.0F; memcpy(out_, &v, sizeof(v)); } } static void -rgb2bgr15(UINT8* out_, const UINT8* in, int xsize) -{ +rgb2bgr15(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4, out_ += 2) { - UINT16 v = - ((((UINT16)in[0])<<7)&0x7c00) + - ((((UINT16)in[1])<<2)&0x03e0) + - ((((UINT16)in[2])>>3)&0x001f); + UINT16 v = ((((UINT16)in[0]) << 7) & 0x7c00) + + ((((UINT16)in[1]) << 2) & 0x03e0) + + ((((UINT16)in[2]) >> 3) & 0x001f); memcpy(out_, &v, sizeof(v)); } } static void -rgb2bgr16(UINT8* out_, const UINT8* in, int xsize) -{ +rgb2bgr16(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4, out_ += 2) { - UINT16 v = - ((((UINT16)in[0])<<8)&0xf800) + - ((((UINT16)in[1])<<3)&0x07e0) + - ((((UINT16)in[2])>>3)&0x001f); + UINT16 v = ((((UINT16)in[0]) << 8) & 0xf800) + + ((((UINT16)in[1]) << 3) & 0x07e0) + + ((((UINT16)in[2]) >> 3) & 0x001f); memcpy(out_, &v, sizeof(v)); } } static void -rgb2bgr24(UINT8* out, const UINT8* in, int xsize) -{ +rgb2bgr24(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4) { *out++ = in[2]; @@ -327,40 +299,39 @@ rgb2bgr24(UINT8* out, const UINT8* in, int xsize) } static void -rgb2hsv_row(UINT8* out, const UINT8* in) -{ // following colorsys.py - float h,s,rc,gc,bc,cr; - UINT8 maxc,minc; +rgb2hsv_row(UINT8 *out, const UINT8 *in) { // following colorsys.py + float h, s, rc, gc, bc, cr; + UINT8 maxc, minc; UINT8 r, g, b; - UINT8 uh,us,uv; + UINT8 uh, us, uv; r = in[0]; g = in[1]; b = in[2]; - maxc = MAX(r,MAX(g,b)); - minc = MIN(r,MIN(g,b)); + maxc = MAX(r, MAX(g, b)); + minc = MIN(r, MIN(g, b)); uv = maxc; - if (minc == maxc){ + if (minc == maxc) { uh = 0; us = 0; } else { - cr = (float)(maxc-minc); - s = cr/(float)maxc; - rc = ((float)(maxc-r))/cr; - gc = ((float)(maxc-g))/cr; - bc = ((float)(maxc-b))/cr; + cr = (float)(maxc - minc); + s = cr / (float)maxc; + rc = ((float)(maxc - r)) / cr; + gc = ((float)(maxc - g)) / cr; + bc = ((float)(maxc - b)) / cr; if (r == maxc) { - h = bc-gc; + h = bc - gc; } else if (g == maxc) { - h = 2.0 + rc-bc; + h = 2.0 + rc - bc; } else { - h = 4.0 + gc-rc; + h = 4.0 + gc - rc; } // incorrect hue happens if h/6 is negative. - h = fmod((h/6.0 + 1.0), 1.0); + h = fmod((h / 6.0 + 1.0), 1.0); - uh = (UINT8)CLIP8((int)(h*255.0)); - us = (UINT8)CLIP8((int)(s*255.0)); + uh = (UINT8)CLIP8((int)(h * 255.0)); + us = (UINT8)CLIP8((int)(s * 255.0)); } out[0] = uh; out[1] = us; @@ -368,8 +339,7 @@ rgb2hsv_row(UINT8* out, const UINT8* in) } static void -rgb2hsv(UINT8* out, const UINT8* in, int xsize) -{ +rgb2hsv(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4, out += 4) { rgb2hsv_row(out, in); @@ -377,98 +347,91 @@ rgb2hsv(UINT8* out, const UINT8* in, int xsize) } } - - static void -hsv2rgb(UINT8* out, const UINT8* in, int xsize) -{ // following colorsys.py +hsv2rgb(UINT8 *out, const UINT8 *in, int xsize) { // following colorsys.py - int p,q,t; - UINT8 up,uq,ut; + int p, q, t; + UINT8 up, uq, ut; int i, x; float f, fs; - UINT8 h,s,v; + UINT8 h, s, v; for (x = 0; x < xsize; x++, in += 4) { h = in[0]; s = in[1]; v = in[2]; - if (s==0){ + if (s == 0) { *out++ = v; *out++ = v; *out++ = v; } else { - i = floor((float)h * 6.0 / 255.0); // 0 - 6 - f = (float)h * 6.0 / 255.0 - (float)i; // 0-1 : remainder. - fs = ((float)s)/255.0; + i = floor((float)h * 6.0 / 255.0); // 0 - 6 + f = (float)h * 6.0 / 255.0 - (float)i; // 0-1 : remainder. + fs = ((float)s) / 255.0; - p = round((float)v * (1.0-fs)); - q = round((float)v * (1.0-fs*f)); - t = round((float)v * (1.0-fs*(1.0-f))); + p = round((float)v * (1.0 - fs)); + q = round((float)v * (1.0 - fs * f)); + t = round((float)v * (1.0 - fs * (1.0 - f))); up = (UINT8)CLIP8(p); uq = (UINT8)CLIP8(q); ut = (UINT8)CLIP8(t); - switch (i%6) { - case 0: - *out++ = v; - *out++ = ut; - *out++ = up; - break; - case 1: - *out++ = uq; - *out++ = v; - *out++ = up; - break; - case 2: - *out++ = up; - *out++ = v; - *out++ = ut; - break; - case 3: - *out++ = up; - *out++ = uq; - *out++ = v; - break; - case 4: - *out++ = ut; - *out++ = up; - *out++ = v; - break; - case 5: - *out++ = v; - *out++ = up; - *out++ = uq; - break; - + switch (i % 6) { + case 0: + *out++ = v; + *out++ = ut; + *out++ = up; + break; + case 1: + *out++ = uq; + *out++ = v; + *out++ = up; + break; + case 2: + *out++ = up; + *out++ = v; + *out++ = ut; + break; + case 3: + *out++ = up; + *out++ = uq; + *out++ = v; + break; + case 4: + *out++ = ut; + *out++ = up; + *out++ = v; + break; + case 5: + *out++ = v; + *out++ = up; + *out++ = uq; + break; } } *out++ = in[3]; } } - - /* ---------------- */ /* RGBA conversions */ /* ---------------- */ static void -rgb2rgba(UINT8* out, const UINT8* in, int xsize) -{ +rgb2rgba(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { *out++ = *in++; *out++ = *in++; *out++ = *in++; - *out++ = 255; in++; + *out++ = 255; + in++; } } static void -rgba2la(UINT8* out, const UINT8* in, int xsize) -{ +rgba2la(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4, out += 4) { /* ITU-R Recommendation 601-2 (assuming nonlinear RGB) */ @@ -478,20 +441,19 @@ rgba2la(UINT8* out, const UINT8* in, int xsize) } static void -rgba2rgb(UINT8* out, const UINT8* in, int xsize) -{ +rgba2rgb(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { *out++ = *in++; *out++ = *in++; *out++ = *in++; - *out++ = 255; in++; + *out++ = 255; + in++; } } static void -rgbA2rgba(UINT8* out, const UINT8* in, int xsize) -{ +rgbA2rgba(UINT8 *out, const UINT8 *in, int xsize) { int x; unsigned int alpha, tmp; for (x = 0; x < xsize; x++) { @@ -506,11 +468,10 @@ rgbA2rgba(UINT8* out, const UINT8* in, int xsize) /* RGBa -> RGBA conversion to remove premultiplication Needed for correct transforms/resizing on RGBA images */ static void -rgba2rgbA(UINT8* out, const UINT8* in, int xsize) -{ +rgba2rgbA(UINT8 *out, const UINT8 *in, int xsize) { int x; unsigned int alpha; - for (x = 0; x < xsize; x++, in+=4) { + for (x = 0; x < xsize; x++, in += 4) { alpha = in[3]; if (alpha == 255 || alpha == 0) { *out++ = in[0]; @@ -532,35 +493,32 @@ rgba2rgbA(UINT8* out, const UINT8* in, int xsize) */ static void -rgbT2rgba(UINT8* out, int xsize, int r, int g, int b) -{ +rgbT2rgba(UINT8 *out, int xsize, int r, int g, int b) { #ifdef WORDS_BIGENDIAN - UINT32 trns = ((r & 0xff)<<24) | ((g & 0xff)<<16) | ((b & 0xff)<<8) | 0xff; + UINT32 trns = ((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | 0xff; UINT32 repl = trns & 0xffffff00; #else - UINT32 trns = (0xff <<24) | ((b & 0xff)<<16) | ((g & 0xff)<<8) | (r & 0xff); + UINT32 trns = (0xff << 24) | ((b & 0xff) << 16) | ((g & 0xff) << 8) | (r & 0xff); UINT32 repl = trns & 0x00ffffff; #endif int i; - for (i=0; i < xsize; i++ ,out += sizeof(trns)) { + for (i = 0; i < xsize; i++, out += sizeof(trns)) { UINT32 v; memcpy(&v, out, sizeof(v)); - if (v==trns) { + if (v == trns) { memcpy(out, &repl, sizeof(repl)); } } } - /* ---------------- */ /* CMYK conversions */ /* ---------------- */ static void -l2cmyk(UINT8* out, const UINT8* in, int xsize) -{ +l2cmyk(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { *out++ = 0; @@ -571,8 +529,7 @@ l2cmyk(UINT8* out, const UINT8* in, int xsize) } static void -la2cmyk(UINT8* out, const UINT8* in, int xsize) -{ +la2cmyk(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4) { *out++ = 0; @@ -583,21 +540,20 @@ la2cmyk(UINT8* out, const UINT8* in, int xsize) } static void -rgb2cmyk(UINT8* out, const UINT8* in, int xsize) -{ +rgb2cmyk(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { /* Note: no undercolour removal */ *out++ = ~(*in++); *out++ = ~(*in++); *out++ = ~(*in++); - *out++ = 0; in++; + *out++ = 0; + in++; } } static void -cmyk2rgb(UINT8* out, const UINT8* in, int xsize) -{ +cmyk2rgb(UINT8 *out, const UINT8 *in, int xsize) { int x, nk, tmp; for (x = 0; x < xsize; x++) { nk = 255 - in[3]; @@ -611,8 +567,7 @@ cmyk2rgb(UINT8* out, const UINT8* in, int xsize) } static void -cmyk2hsv(UINT8* out, const UINT8* in, int xsize) -{ +cmyk2hsv(UINT8 *out, const UINT8 *in, int xsize) { int x, nk, tmp; for (x = 0; x < xsize; x++) { nk = 255 - in[3]; @@ -631,8 +586,7 @@ cmyk2hsv(UINT8* out, const UINT8* in, int xsize) /* ------------- */ static void -bit2i(UINT8* out_, const UINT8* in, int xsize) -{ +bit2i(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, out_ += 4) { INT32 v = (*in++ != 0) ? 255 : 0; @@ -641,8 +595,7 @@ bit2i(UINT8* out_, const UINT8* in, int xsize) } static void -l2i(UINT8* out_, const UINT8* in, int xsize) -{ +l2i(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, out_ += 4) { INT32 v = *in++; @@ -651,8 +604,7 @@ l2i(UINT8* out_, const UINT8* in, int xsize) } static void -i2l(UINT8* out, const UINT8* in_, int xsize) -{ +i2l(UINT8 *out, const UINT8 *in_, int xsize) { int x; for (x = 0; x < xsize; x++, out++, in_ += 4) { INT32 v; @@ -662,14 +614,13 @@ i2l(UINT8* out, const UINT8* in_, int xsize) } else if (v >= 255) { *out = 255; } else { - *out = (UINT8) v; + *out = (UINT8)v; } } } static void -i2f(UINT8* out_, const UINT8* in_, int xsize) -{ +i2f(UINT8 *out_, const UINT8 *in_, int xsize) { int x; for (x = 0; x < xsize; x++, in_ += 4, out_ += 4) { INT32 i; @@ -681,28 +632,26 @@ i2f(UINT8* out_, const UINT8* in_, int xsize) } static void -i2rgb(UINT8* out, const UINT8* in_, int xsize) -{ +i2rgb(UINT8 *out, const UINT8 *in_, int xsize) { int x; - INT32* in = (INT32*) in_; - for (x = 0; x < xsize; x++, in++, out+=4) { + INT32 *in = (INT32 *)in_; + for (x = 0; x < xsize; x++, in++, out += 4) { if (*in <= 0) { out[0] = out[1] = out[2] = 0; } else if (*in >= 255) { out[0] = out[1] = out[2] = 255; } else { - out[0] = out[1] = out[2] = (UINT8) *in; + out[0] = out[1] = out[2] = (UINT8)*in; } out[3] = 255; } } static void -i2hsv(UINT8* out, const UINT8* in_, int xsize) -{ +i2hsv(UINT8 *out, const UINT8 *in_, int xsize) { int x; - INT32* in = (INT32*) in_; - for (x = 0; x < xsize; x++, in++, out+=4) { + INT32 *in = (INT32 *)in_; + for (x = 0; x < xsize; x++, in++, out += 4) { out[0] = 0; out[1] = 0; if (*in <= 0) { @@ -710,7 +659,7 @@ i2hsv(UINT8* out, const UINT8* in_, int xsize) } else if (*in >= 255) { out[2] = 255; } else { - out[2] = (UINT8) *in; + out[2] = (UINT8)*in; } out[3] = 255; } @@ -721,8 +670,7 @@ i2hsv(UINT8* out, const UINT8* in_, int xsize) /* ------------- */ static void -bit2f(UINT8* out_, const UINT8* in, int xsize) -{ +bit2f(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, out_ += 4) { FLOAT32 f = (*in++ != 0) ? 255.0F : 0.0F; @@ -731,18 +679,16 @@ bit2f(UINT8* out_, const UINT8* in, int xsize) } static void -l2f(UINT8* out_, const UINT8* in, int xsize) -{ +l2f(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, out_ += 4) { - FLOAT32 f = (FLOAT32) *in++; + FLOAT32 f = (FLOAT32)*in++; memcpy(out_, &f, sizeof(f)); } } static void -f2l(UINT8* out, const UINT8* in_, int xsize) -{ +f2l(UINT8 *out, const UINT8 *in_, int xsize) { int x; for (x = 0; x < xsize; x++, out++, in_ += 4) { FLOAT32 v; @@ -752,14 +698,13 @@ f2l(UINT8* out, const UINT8* in_, int xsize) } else if (v >= 255.0) { *out = 255; } else { - *out = (UINT8) v; + *out = (UINT8)v; } } } static void -f2i(UINT8* out_, const UINT8* in_, int xsize) -{ +f2i(UINT8 *out_, const UINT8 *in_, int xsize) { int x; for (x = 0; x < xsize; x++, in_ += 4, out_ += 4) { FLOAT32 f; @@ -777,8 +722,7 @@ f2i(UINT8* out_, const UINT8* in_, int xsize) /* See ConvertYCbCr.c for RGB/YCbCr tables */ static void -l2ycbcr(UINT8* out, const UINT8* in, int xsize) -{ +l2ycbcr(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++) { *out++ = *in++; @@ -789,8 +733,7 @@ l2ycbcr(UINT8* out, const UINT8* in, int xsize) } static void -la2ycbcr(UINT8* out, const UINT8* in, int xsize) -{ +la2ycbcr(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4) { *out++ = in[0]; @@ -801,8 +744,7 @@ la2ycbcr(UINT8* out, const UINT8* in, int xsize) } static void -ycbcr2l(UINT8* out, const UINT8* in, int xsize) -{ +ycbcr2l(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4) { *out++ = in[0]; @@ -810,8 +752,7 @@ ycbcr2l(UINT8* out, const UINT8* in, int xsize) } static void -ycbcr2la(UINT8* out, const UINT8* in, int xsize) -{ +ycbcr2la(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 4, out += 4) { out[0] = out[1] = out[2] = in[0]; @@ -824,77 +765,67 @@ ycbcr2la(UINT8* out, const UINT8* in, int xsize) /* ------------------------- */ static void -I_I16L(UINT8* out, const UINT8* in_, int xsize) -{ +I_I16L(UINT8 *out, const UINT8 *in_, int xsize) { int x, v; for (x = 0; x < xsize; x++, in_ += 4) { INT32 i; memcpy(&i, in_, sizeof(i)); v = CLIP16(i); - *out++ = (UINT8) v; - *out++ = (UINT8) (v >> 8); + *out++ = (UINT8)v; + *out++ = (UINT8)(v >> 8); } } static void -I_I16B(UINT8* out, const UINT8* in_, int xsize) -{ +I_I16B(UINT8 *out, const UINT8 *in_, int xsize) { int x, v; for (x = 0; x < xsize; x++, in_ += 4) { INT32 i; memcpy(&i, in_, sizeof(i)); v = CLIP16(i); - *out++ = (UINT8) (v >> 8); - *out++ = (UINT8) v; + *out++ = (UINT8)(v >> 8); + *out++ = (UINT8)v; } } - static void -I16L_I(UINT8* out_, const UINT8* in, int xsize) -{ +I16L_I(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 2, out_ += 4) { - INT32 v = in[0] + ((int) in[1] << 8); - memcpy(out_, &v, sizeof(v)); - } -} - - -static void -I16B_I(UINT8* out_, const UINT8* in, int xsize) -{ - int x; - for (x = 0; x < xsize; x++, in += 2, out_ += 4) { - INT32 v = in[1] + ((int) in[0] << 8); + INT32 v = in[0] + ((int)in[1] << 8); memcpy(out_, &v, sizeof(v)); } } static void -I16L_F(UINT8* out_, const UINT8* in, int xsize) -{ +I16B_I(UINT8 *out_, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 2, out_ += 4) { - FLOAT32 v = in[0] + ((int) in[1] << 8); - memcpy(out_, &v, sizeof(v)); - } -} - - -static void -I16B_F(UINT8* out_, const UINT8* in, int xsize) -{ - int x; - for (x = 0; x < xsize; x++, in += 2, out_ += 4) { - FLOAT32 v = in[1] + ((int) in[0] << 8); + INT32 v = in[1] + ((int)in[0] << 8); memcpy(out_, &v, sizeof(v)); } } static void -L_I16L(UINT8* out, const UINT8* in, int xsize) -{ +I16L_F(UINT8 *out_, const UINT8 *in, int xsize) { + int x; + for (x = 0; x < xsize; x++, in += 2, out_ += 4) { + FLOAT32 v = in[0] + ((int)in[1] << 8); + memcpy(out_, &v, sizeof(v)); + } +} + +static void +I16B_F(UINT8 *out_, const UINT8 *in, int xsize) { + int x; + for (x = 0; x < xsize; x++, in += 2, out_ += 4) { + FLOAT32 v = in[1] + ((int)in[0] << 8); + memcpy(out_, &v, sizeof(v)); + } +} + +static void +L_I16L(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in++) { *out++ = *in; @@ -903,8 +834,7 @@ L_I16L(UINT8* out, const UINT8* in, int xsize) } static void -L_I16B(UINT8* out, const UINT8* in, int xsize) -{ +L_I16B(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in++) { *out++ = 0; @@ -913,8 +843,7 @@ L_I16B(UINT8* out, const UINT8* in, int xsize) } static void -I16L_L(UINT8* out, const UINT8* in, int xsize) -{ +I16L_L(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 2) { if (in[1] != 0) { @@ -926,8 +855,7 @@ I16L_L(UINT8* out, const UINT8* in, int xsize) } static void -I16B_L(UINT8* out, const UINT8* in, int xsize) -{ +I16B_L(UINT8 *out, const UINT8 *in, int xsize) { int x; for (x = 0; x < xsize; x++, in += 2) { if (in[0] != 0) { @@ -939,123 +867,122 @@ I16B_L(UINT8* out, const UINT8* in, int xsize) } static struct { - const char* from; - const char* to; + const char *from; + const char *to; ImagingShuffler convert; } converters[] = { - { "1", "L", bit2l }, - { "1", "I", bit2i }, - { "1", "F", bit2f }, - { "1", "RGB", bit2rgb }, - { "1", "RGBA", bit2rgb }, - { "1", "RGBX", bit2rgb }, - { "1", "CMYK", bit2cmyk }, - { "1", "YCbCr", bit2ycbcr }, - { "1", "HSV", bit2hsv }, + {"1", "L", bit2l}, + {"1", "I", bit2i}, + {"1", "F", bit2f}, + {"1", "RGB", bit2rgb}, + {"1", "RGBA", bit2rgb}, + {"1", "RGBX", bit2rgb}, + {"1", "CMYK", bit2cmyk}, + {"1", "YCbCr", bit2ycbcr}, + {"1", "HSV", bit2hsv}, - { "L", "1", l2bit }, - { "L", "LA", l2la }, - { "L", "I", l2i }, - { "L", "F", l2f }, - { "L", "RGB", l2rgb }, - { "L", "RGBA", l2rgb }, - { "L", "RGBX", l2rgb }, - { "L", "CMYK", l2cmyk }, - { "L", "YCbCr", l2ycbcr }, - { "L", "HSV", l2hsv }, + {"L", "1", l2bit}, + {"L", "LA", l2la}, + {"L", "I", l2i}, + {"L", "F", l2f}, + {"L", "RGB", l2rgb}, + {"L", "RGBA", l2rgb}, + {"L", "RGBX", l2rgb}, + {"L", "CMYK", l2cmyk}, + {"L", "YCbCr", l2ycbcr}, + {"L", "HSV", l2hsv}, - { "LA", "L", la2l }, - { "LA", "La", lA2la }, - { "LA", "RGB", la2rgb }, - { "LA", "RGBA", la2rgb }, - { "LA", "RGBX", la2rgb }, - { "LA", "CMYK", la2cmyk }, - { "LA", "YCbCr", la2ycbcr }, - { "LA", "HSV", la2hsv }, + {"LA", "L", la2l}, + {"LA", "La", lA2la}, + {"LA", "RGB", la2rgb}, + {"LA", "RGBA", la2rgb}, + {"LA", "RGBX", la2rgb}, + {"LA", "CMYK", la2cmyk}, + {"LA", "YCbCr", la2ycbcr}, + {"LA", "HSV", la2hsv}, - { "La", "LA", la2lA }, + {"La", "LA", la2lA}, - { "I", "L", i2l }, - { "I", "F", i2f }, - { "I", "RGB", i2rgb }, - { "I", "RGBA", i2rgb }, - { "I", "RGBX", i2rgb }, - { "I", "HSV", i2hsv }, + {"I", "L", i2l}, + {"I", "F", i2f}, + {"I", "RGB", i2rgb}, + {"I", "RGBA", i2rgb}, + {"I", "RGBX", i2rgb}, + {"I", "HSV", i2hsv}, - { "F", "L", f2l }, - { "F", "I", f2i }, + {"F", "L", f2l}, + {"F", "I", f2i}, - { "RGB", "1", rgb2bit }, - { "RGB", "L", rgb2l }, - { "RGB", "LA", rgb2la }, - { "RGB", "I", rgb2i }, - { "RGB", "F", rgb2f }, - { "RGB", "BGR;15", rgb2bgr15 }, - { "RGB", "BGR;16", rgb2bgr16 }, - { "RGB", "BGR;24", rgb2bgr24 }, - { "RGB", "RGBA", rgb2rgba }, - { "RGB", "RGBX", rgb2rgba }, - { "RGB", "CMYK", rgb2cmyk }, - { "RGB", "YCbCr", ImagingConvertRGB2YCbCr }, - { "RGB", "HSV", rgb2hsv }, + {"RGB", "1", rgb2bit}, + {"RGB", "L", rgb2l}, + {"RGB", "LA", rgb2la}, + {"RGB", "I", rgb2i}, + {"RGB", "F", rgb2f}, + {"RGB", "BGR;15", rgb2bgr15}, + {"RGB", "BGR;16", rgb2bgr16}, + {"RGB", "BGR;24", rgb2bgr24}, + {"RGB", "RGBA", rgb2rgba}, + {"RGB", "RGBX", rgb2rgba}, + {"RGB", "CMYK", rgb2cmyk}, + {"RGB", "YCbCr", ImagingConvertRGB2YCbCr}, + {"RGB", "HSV", rgb2hsv}, - { "RGBA", "1", rgb2bit }, - { "RGBA", "L", rgb2l }, - { "RGBA", "LA", rgba2la }, - { "RGBA", "I", rgb2i }, - { "RGBA", "F", rgb2f }, - { "RGBA", "RGB", rgba2rgb }, - { "RGBA", "RGBa", rgbA2rgba }, - { "RGBA", "RGBX", rgb2rgba }, - { "RGBA", "CMYK", rgb2cmyk }, - { "RGBA", "YCbCr", ImagingConvertRGB2YCbCr }, - { "RGBA", "HSV", rgb2hsv }, + {"RGBA", "1", rgb2bit}, + {"RGBA", "L", rgb2l}, + {"RGBA", "LA", rgba2la}, + {"RGBA", "I", rgb2i}, + {"RGBA", "F", rgb2f}, + {"RGBA", "RGB", rgba2rgb}, + {"RGBA", "RGBa", rgbA2rgba}, + {"RGBA", "RGBX", rgb2rgba}, + {"RGBA", "CMYK", rgb2cmyk}, + {"RGBA", "YCbCr", ImagingConvertRGB2YCbCr}, + {"RGBA", "HSV", rgb2hsv}, - { "RGBa", "RGBA", rgba2rgbA }, + {"RGBa", "RGBA", rgba2rgbA}, - { "RGBX", "1", rgb2bit }, - { "RGBX", "L", rgb2l }, - { "RGBX", "LA", rgb2la }, - { "RGBX", "I", rgb2i }, - { "RGBX", "F", rgb2f }, - { "RGBX", "RGB", rgba2rgb }, - { "RGBX", "CMYK", rgb2cmyk }, - { "RGBX", "YCbCr", ImagingConvertRGB2YCbCr }, - { "RGBX", "HSV", rgb2hsv }, + {"RGBX", "1", rgb2bit}, + {"RGBX", "L", rgb2l}, + {"RGBX", "LA", rgb2la}, + {"RGBX", "I", rgb2i}, + {"RGBX", "F", rgb2f}, + {"RGBX", "RGB", rgba2rgb}, + {"RGBX", "CMYK", rgb2cmyk}, + {"RGBX", "YCbCr", ImagingConvertRGB2YCbCr}, + {"RGBX", "HSV", rgb2hsv}, - { "CMYK", "RGB", cmyk2rgb }, - { "CMYK", "RGBA", cmyk2rgb }, - { "CMYK", "RGBX", cmyk2rgb }, - { "CMYK", "HSV", cmyk2hsv }, + {"CMYK", "RGB", cmyk2rgb}, + {"CMYK", "RGBA", cmyk2rgb}, + {"CMYK", "RGBX", cmyk2rgb}, + {"CMYK", "HSV", cmyk2hsv}, - { "YCbCr", "L", ycbcr2l }, - { "YCbCr", "LA", ycbcr2la }, - { "YCbCr", "RGB", ImagingConvertYCbCr2RGB }, + {"YCbCr", "L", ycbcr2l}, + {"YCbCr", "LA", ycbcr2la}, + {"YCbCr", "RGB", ImagingConvertYCbCr2RGB}, - { "HSV", "RGB", hsv2rgb }, + {"HSV", "RGB", hsv2rgb}, - { "I", "I;16", I_I16L }, - { "I;16", "I", I16L_I }, - { "L", "I;16", L_I16L }, - { "I;16", "L", I16L_L }, + {"I", "I;16", I_I16L}, + {"I;16", "I", I16L_I}, + {"L", "I;16", L_I16L}, + {"I;16", "L", I16L_L}, - { "I", "I;16L", I_I16L }, - { "I;16L", "I", I16L_I }, - { "I", "I;16B", I_I16B }, - { "I;16B", "I", I16B_I }, + {"I", "I;16L", I_I16L}, + {"I;16L", "I", I16L_I}, + {"I", "I;16B", I_I16B}, + {"I;16B", "I", I16B_I}, - { "L", "I;16L", L_I16L }, - { "I;16L", "L", I16L_L }, - { "L", "I;16B", L_I16B }, - { "I;16B", "L", I16B_L }, + {"L", "I;16L", L_I16L}, + {"I;16L", "L", I16L_L}, + {"L", "I;16B", L_I16B}, + {"I;16B", "L", I16B_L}, - { "I;16", "F", I16L_F }, - { "I;16L", "F", I16L_F }, - { "I;16B", "F", I16B_F }, + {"I;16", "F", I16L_F}, + {"I;16L", "F", I16L_F}, + {"I;16B", "F", I16B_F}, - { NULL } -}; + {NULL}}; /* FIXME: translate indexed versions to pointer versions below this line */ @@ -1064,51 +991,46 @@ static struct { /* ------------------- */ static void -p2bit(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +p2bit(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; /* FIXME: precalculate greyscale palette? */ for (x = 0; x < xsize; x++) { - *out++ = (L(&palette[in[x]*4]) >= 128000) ? 255 : 0; + *out++ = (L(&palette[in[x] * 4]) >= 128000) ? 255 : 0; } } static void -pa2bit(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2bit(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; /* FIXME: precalculate greyscale palette? */ for (x = 0; x < xsize; x++, in += 4) { - *out++ = (L(&palette[in[0]*4]) >= 128000) ? 255 : 0; + *out++ = (L(&palette[in[0] * 4]) >= 128000) ? 255 : 0; } } static void -p2l(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +p2l(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; /* FIXME: precalculate greyscale palette? */ for (x = 0; x < xsize; x++) { - *out++ = L(&palette[in[x]*4]) / 1000; + *out++ = L(&palette[in[x] * 4]) / 1000; } } static void -pa2l(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2l(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; /* FIXME: precalculate greyscale palette? */ for (x = 0; x < xsize; x++, in += 4) { - *out++ = L(&palette[in[0]*4]) / 1000; + *out++ = L(&palette[in[0] * 4]) / 1000; } } static void -p2pa(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +p2pa(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; for (x = 0; x < xsize; x++, in++) { - const UINT8* rgba = &palette[in[0]]; + const UINT8 *rgba = &palette[in[0]]; *out++ = in[0]; *out++ = in[0]; *out++ = in[0]; @@ -1117,74 +1039,67 @@ p2pa(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) } static void -p2la(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +p2la(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; /* FIXME: precalculate greyscale palette? */ - for (x = 0; x < xsize; x++, out+=4) { - const UINT8* rgba = &palette[*in++ * 4]; + for (x = 0; x < xsize; x++, out += 4) { + const UINT8 *rgba = &palette[*in++ * 4]; out[0] = out[1] = out[2] = L(rgba) / 1000; out[3] = rgba[3]; } } static void -pa2la(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2la(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; /* FIXME: precalculate greyscale palette? */ for (x = 0; x < xsize; x++, in += 4, out += 4) { - out[0] = out[1] = out[2] = L(&palette[in[0]*4]) / 1000; + out[0] = out[1] = out[2] = L(&palette[in[0] * 4]) / 1000; out[3] = in[3]; } } static void -p2i(UINT8* out_, const UINT8* in, int xsize, const UINT8* palette) -{ +p2i(UINT8 *out_, const UINT8 *in, int xsize, const UINT8 *palette) { int x; for (x = 0; x < xsize; x++, out_ += 4) { - INT32 v = L(&palette[in[x]*4]) / 1000; + INT32 v = L(&palette[in[x] * 4]) / 1000; memcpy(out_, &v, sizeof(v)); } } static void -pa2i(UINT8* out_, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2i(UINT8 *out_, const UINT8 *in, int xsize, const UINT8 *palette) { int x; - INT32* out = (INT32*) out_; + INT32 *out = (INT32 *)out_; for (x = 0; x < xsize; x++, in += 4) { - *out++ = L(&palette[in[0]*4]) / 1000; + *out++ = L(&palette[in[0] * 4]) / 1000; } } static void -p2f(UINT8* out_, const UINT8* in, int xsize, const UINT8* palette) -{ +p2f(UINT8 *out_, const UINT8 *in, int xsize, const UINT8 *palette) { int x; for (x = 0; x < xsize; x++, out_ += 4) { - FLOAT32 v = L(&palette[in[x]*4]) / 1000.0F; + FLOAT32 v = L(&palette[in[x] * 4]) / 1000.0F; memcpy(out_, &v, sizeof(v)); } } static void -pa2f(UINT8* out_, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2f(UINT8 *out_, const UINT8 *in, int xsize, const UINT8 *palette) { int x; - FLOAT32* out = (FLOAT32*) out_; + FLOAT32 *out = (FLOAT32 *)out_; for (x = 0; x < xsize; x++, in += 4) { - *out++ = (float) L(&palette[in[0]*4]) / 1000.0F; + *out++ = (float)L(&palette[in[0] * 4]) / 1000.0F; } } static void -p2rgb(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +p2rgb(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; for (x = 0; x < xsize; x++) { - const UINT8* rgb = &palette[*in++ * 4]; + const UINT8 *rgb = &palette[*in++ * 4]; *out++ = rgb[0]; *out++ = rgb[1]; *out++ = rgb[2]; @@ -1193,11 +1108,10 @@ p2rgb(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) } static void -pa2rgb(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2rgb(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; for (x = 0; x < xsize; x++, in += 4) { - const UINT8* rgb = &palette[in[0] * 4]; + const UINT8 *rgb = &palette[in[0] * 4]; *out++ = rgb[0]; *out++ = rgb[1]; *out++ = rgb[2]; @@ -1206,33 +1120,30 @@ pa2rgb(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) } static void -p2hsv(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +p2hsv(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; for (x = 0; x < xsize; x++, out += 4) { - const UINT8* rgb = &palette[*in++ * 4]; + const UINT8 *rgb = &palette[*in++ * 4]; rgb2hsv_row(out, rgb); out[3] = 255; } } static void -pa2hsv(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2hsv(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; for (x = 0; x < xsize; x++, in += 4, out += 4) { - const UINT8* rgb = &palette[in[0] * 4]; + const UINT8 *rgb = &palette[in[0] * 4]; rgb2hsv_row(out, rgb); out[3] = 255; } } static void -p2rgba(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +p2rgba(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; for (x = 0; x < xsize; x++) { - const UINT8* rgba = &palette[*in++ * 4]; + const UINT8 *rgba = &palette[*in++ * 4]; *out++ = rgba[0]; *out++ = rgba[1]; *out++ = rgba[2]; @@ -1241,11 +1152,10 @@ p2rgba(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) } static void -pa2rgba(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2rgba(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { int x; for (x = 0; x < xsize; x++, in += 4) { - const UINT8* rgb = &palette[in[0] * 4]; + const UINT8 *rgb = &palette[in[0] * 4]; *out++ = rgb[0]; *out++ = rgb[1]; *out++ = rgb[2]; @@ -1254,45 +1164,40 @@ pa2rgba(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) } static void -p2cmyk(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +p2cmyk(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { p2rgb(out, in, xsize, palette); rgb2cmyk(out, out, xsize); } static void -pa2cmyk(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2cmyk(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { pa2rgb(out, in, xsize, palette); rgb2cmyk(out, out, xsize); } static void -p2ycbcr(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +p2ycbcr(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { p2rgb(out, in, xsize, palette); ImagingConvertRGB2YCbCr(out, out, xsize); } static void -pa2ycbcr(UINT8* out, const UINT8* in, int xsize, const UINT8* palette) -{ +pa2ycbcr(UINT8 *out, const UINT8 *in, int xsize, const UINT8 *palette) { pa2rgb(out, in, xsize, palette); ImagingConvertRGB2YCbCr(out, out, xsize); } static Imaging -frompalette(Imaging imOut, Imaging imIn, const char *mode) -{ +frompalette(Imaging imOut, Imaging imIn, const char *mode) { ImagingSectionCookie cookie; int alpha; int y; - void (*convert)(UINT8*, const UINT8*, int, const UINT8*); + void (*convert)(UINT8 *, const UINT8 *, int, const UINT8 *); /* Map palette image to L, RGB, RGBA, or CMYK */ if (!imIn->palette) { - return (Imaging) ImagingError_ValueError("no palette"); + return (Imaging)ImagingError_ValueError("no palette"); } alpha = !strcmp(imIn->mode, "PA"); @@ -1322,7 +1227,7 @@ frompalette(Imaging imOut, Imaging imIn, const char *mode) } else if (strcmp(mode, "HSV") == 0) { convert = alpha ? pa2hsv : p2hsv; } else { - return (Imaging) ImagingError_ValueError("conversion not supported"); + return (Imaging)ImagingError_ValueError("conversion not supported"); } imOut = ImagingNew2Dirty(mode, imOut, imIn); @@ -1332,8 +1237,11 @@ frompalette(Imaging imOut, Imaging imIn, const char *mode) ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { - (*convert)((UINT8*) imOut->image[y], (UINT8*) imIn->image[y], - imIn->xsize, imIn->palette->palette); + (*convert)( + (UINT8 *)imOut->image[y], + (UINT8 *)imIn->image[y], + imIn->xsize, + imIn->palette->palette); } ImagingSectionLeave(&cookie); @@ -1344,39 +1252,44 @@ frompalette(Imaging imOut, Imaging imIn, const char *mode) #pragma optimize("", off) #endif static Imaging -topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalette, int dither) -{ +topalette( + Imaging imOut, + Imaging imIn, + const char *mode, + ImagingPalette inpalette, + int dither) { ImagingSectionCookie cookie; int alpha; int x, y; - ImagingPalette palette = inpalette;; + ImagingPalette palette = inpalette; + ; /* Map L or RGB/RGBX/RGBA to palette image */ if (strcmp(imIn->mode, "L") != 0 && strncmp(imIn->mode, "RGB", 3) != 0) { - return (Imaging) ImagingError_ValueError("conversion not supported"); + return (Imaging)ImagingError_ValueError("conversion not supported"); } alpha = !strcmp(mode, "PA"); if (palette == NULL) { - /* FIXME: make user configurable */ - if (imIn->bands == 1) { - palette = ImagingPaletteNew("RGB"); /* Initialised to grey ramp */ - } else { - palette = ImagingPaletteNewBrowser(); /* Standard colour cube */ - } + /* FIXME: make user configurable */ + if (imIn->bands == 1) { + palette = ImagingPaletteNew("RGB"); /* Initialised to grey ramp */ + } else { + palette = ImagingPaletteNewBrowser(); /* Standard colour cube */ + } } if (!palette) { - return (Imaging) ImagingError_ValueError("no palette"); + return (Imaging)ImagingError_ValueError("no palette"); } imOut = ImagingNew2Dirty(mode, imOut, imIn); if (!imOut) { - if (palette != inpalette) { - ImagingPaletteDelete(palette); - } - return NULL; + if (palette != inpalette) { + ImagingPaletteDelete(palette); + } + return NULL; } ImagingPaletteDelete(imOut->palette); @@ -1389,7 +1302,7 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { if (alpha) { - l2la((UINT8*) imOut->image[y], (UINT8*) imIn->image[y], imIn->xsize); + l2la((UINT8 *)imOut->image[y], (UINT8 *)imIn->image[y], imIn->xsize); } else { memcpy(imOut->image[y], imIn->image[y], imIn->linesize); } @@ -1403,7 +1316,7 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett if (ImagingPaletteCachePrepare(palette) < 0) { ImagingDelete(imOut); if (palette != inpalette) { - ImagingPaletteDelete(palette); + ImagingPaletteDelete(palette); } return NULL; } @@ -1411,7 +1324,7 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett if (dither) { /* floyd-steinberg dither */ - int* errors; + int *errors; errors = calloc(imIn->xsize + 1, sizeof(int) * 3); if (!errors) { ImagingDelete(imOut); @@ -1424,9 +1337,9 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett int r, r0, r1, r2; int g, g0, g1, g2; int b, b0, b1, b2; - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out = alpha ? (UINT8*) imOut->image32[y] : imOut->image8[y]; - int* e = errors; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out = alpha ? (UINT8 *)imOut->image32[y] : imOut->image8[y]; + int *e = errors; r = r0 = r1 = 0; g = g0 = g1 = 0; @@ -1434,11 +1347,11 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett for (x = 0; x < imIn->xsize; x++, in += 4) { int d2; - INT16* cache; + INT16 *cache; - r = CLIP8(in[0] + (r + e[3+0])/16); - g = CLIP8(in[1] + (g + e[3+1])/16); - b = CLIP8(in[2] + (b + e[3+2])/16); + r = CLIP8(in[0] + (r + e[3 + 0]) / 16); + g = CLIP8(in[1] + (g + e[3 + 1]) / 16); + b = CLIP8(in[2] + (b + e[3 + 2]) / 16); /* get closest colour */ cache = &ImagingPaletteCache(palette, r, g, b); @@ -1446,49 +1359,66 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett ImagingPaletteCacheUpdate(palette, r, g, b); } if (alpha) { - out[x*4] = out[x*4+1] = out[x*4+2] = (UINT8) cache[0]; - out[x*4+3] = 255; + out[x * 4] = out[x * 4 + 1] = out[x * 4 + 2] = (UINT8)cache[0]; + out[x * 4 + 3] = 255; } else { - out[x] = (UINT8) cache[0]; + out[x] = (UINT8)cache[0]; } - r -= (int) palette->palette[cache[0]*4]; - g -= (int) palette->palette[cache[0]*4+1]; - b -= (int) palette->palette[cache[0]*4+2]; + r -= (int)palette->palette[cache[0] * 4]; + g -= (int)palette->palette[cache[0] * 4 + 1]; + b -= (int)palette->palette[cache[0] * 4 + 2]; /* propagate errors (don't ask ;-) */ - r2 = r; d2 = r + r; r += d2; e[0] = r + r0; - r += d2; r0 = r + r1; r1 = r2; r += d2; - g2 = g; d2 = g + g; g += d2; e[1] = g + g0; - g += d2; g0 = g + g1; g1 = g2; g += d2; - b2 = b; d2 = b + b; b += d2; e[2] = b + b0; - b += d2; b0 = b + b1; b1 = b2; b += d2; + r2 = r; + d2 = r + r; + r += d2; + e[0] = r + r0; + r += d2; + r0 = r + r1; + r1 = r2; + r += d2; + g2 = g; + d2 = g + g; + g += d2; + e[1] = g + g0; + g += d2; + g0 = g + g1; + g1 = g2; + g += d2; + b2 = b; + d2 = b + b; + b += d2; + e[2] = b + b0; + b += d2; + b0 = b + b1; + b1 = b2; + b += d2; e += 3; - } e[0] = b0; e[1] = b1; e[2] = b2; - } ImagingSectionLeave(&cookie); free(errors); } else { - /* closest colour */ ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { int r, g, b; - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out = alpha ? (UINT8*) imOut->image32[y] : imOut->image8[y]; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out = alpha ? (UINT8 *)imOut->image32[y] : imOut->image8[y]; for (x = 0; x < imIn->xsize; x++, in += 4) { - INT16* cache; + INT16 *cache; - r = in[0]; g = in[1]; b = in[2]; + r = in[0]; + g = in[1]; + b = in[2]; /* get closest colour */ cache = &ImagingPaletteCache(palette, r, g, b); @@ -1496,38 +1426,36 @@ topalette(Imaging imOut, Imaging imIn, const char *mode, ImagingPalette inpalett ImagingPaletteCacheUpdate(palette, r, g, b); } if (alpha) { - out[x*4] = out[x*4+1] = out[x*4+2] = (UINT8) cache[0]; - out[x*4+3] = 255; + out[x * 4] = out[x * 4 + 1] = out[x * 4 + 2] = (UINT8)cache[0]; + out[x * 4 + 3] = 255; } else { - out[x] = (UINT8) cache[0]; + out[x] = (UINT8)cache[0]; } } } ImagingSectionLeave(&cookie); - } if (inpalette != palette) { - ImagingPaletteCacheDelete(palette); + ImagingPaletteCacheDelete(palette); } } if (inpalette != palette) { - ImagingPaletteDelete(palette); + ImagingPaletteDelete(palette); } return imOut; } static Imaging -tobilevel(Imaging imOut, Imaging imIn, int dither) -{ +tobilevel(Imaging imOut, Imaging imIn, int dither) { ImagingSectionCookie cookie; int x, y; - int* errors; + int *errors; /* Map L or RGB to dithered 1 image */ if (strcmp(imIn->mode, "L") != 0 && strcmp(imIn->mode, "RGB") != 0) { - return (Imaging) ImagingError_ValueError("conversion not supported"); + return (Imaging)ImagingError_ValueError("conversion not supported"); } imOut = ImagingNew2Dirty("1", imOut, imIn); @@ -1542,59 +1470,64 @@ tobilevel(Imaging imOut, Imaging imIn, int dither) } if (imIn->bands == 1) { - /* map each pixel to black or white, using error diffusion */ ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { int l, l0, l1, l2, d2; - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out = imOut->image8[y]; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out = imOut->image8[y]; l = l0 = l1 = 0; for (x = 0; x < imIn->xsize; x++) { - /* pick closest colour */ - l = CLIP8(in[x] + (l + errors[x+1])/16); + l = CLIP8(in[x] + (l + errors[x + 1]) / 16); out[x] = (l > 128) ? 255 : 0; /* propagate errors */ - l -= (int) out[x]; - l2 = l; d2 = l + l; l += d2; errors[x] = l + l0; - l += d2; l0 = l + l1; l1 = l2; l += d2; + l -= (int)out[x]; + l2 = l; + d2 = l + l; + l += d2; + errors[x] = l + l0; + l += d2; + l0 = l + l1; + l1 = l2; + l += d2; } errors[x] = l0; - } ImagingSectionLeave(&cookie); } else { - /* map each pixel to black or white, using error diffusion */ ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { int l, l0, l1, l2, d2; - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out = imOut->image8[y]; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out = imOut->image8[y]; l = l0 = l1 = 0; for (x = 0; x < imIn->xsize; x++, in += 4) { - /* pick closest colour */ - l = CLIP8(L(in)/1000 + (l + errors[x+1])/16); + l = CLIP8(L(in) / 1000 + (l + errors[x + 1]) / 16); out[x] = (l > 128) ? 255 : 0; /* propagate errors */ - l -= (int) out[x]; - l2 = l; d2 = l + l; l += d2; errors[x] = l + l0; - l += d2; l0 = l + l1; l1 = l2; l += d2; - + l -= (int)out[x]; + l2 = l; + d2 = l + l; + l += d2; + errors[x] = l + l0; + l += d2; + l0 = l + l1; + l1 = l2; + l += d2; } errors[x] = l0; - } ImagingSectionLeave(&cookie); } @@ -1608,21 +1541,20 @@ tobilevel(Imaging imOut, Imaging imIn, int dither) #endif static Imaging -convert(Imaging imOut, Imaging imIn, const char *mode, - ImagingPalette palette, int dither) -{ +convert( + Imaging imOut, Imaging imIn, const char *mode, ImagingPalette palette, int dither) { ImagingSectionCookie cookie; ImagingShuffler convert; int y; if (!imIn) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (!mode) { /* Map palette image to full depth */ if (!imIn->palette) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } mode = imIn->palette->mode; } else { @@ -1632,7 +1564,6 @@ convert(Imaging imOut, Imaging imIn, const char *mode, } } - /* test for special conversions */ if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "PA") == 0) { @@ -1647,7 +1578,6 @@ convert(Imaging imOut, Imaging imIn, const char *mode, return tobilevel(imOut, imIn, dither); } - /* standard conversion machinery */ convert = NULL; @@ -1662,12 +1592,12 @@ convert(Imaging imOut, Imaging imIn, const char *mode, if (!convert) { #ifdef notdef - return (Imaging) ImagingError_ValueError("conversion not supported"); + return (Imaging)ImagingError_ValueError("conversion not supported"); #else static char buf[256]; /* FIXME: may overflow if mode is too large */ sprintf(buf, "conversion from %s to %s not supported", imIn->mode, mode); - return (Imaging) ImagingError_ValueError(buf); + return (Imaging)ImagingError_ValueError(buf); #endif } @@ -1678,8 +1608,7 @@ convert(Imaging imOut, Imaging imIn, const char *mode, ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { - (*convert)((UINT8*) imOut->image[y], (UINT8*) imIn->image[y], - imIn->xsize); + (*convert)((UINT8 *)imOut->image[y], (UINT8 *)imIn->image[y], imIn->xsize); } ImagingSectionLeave(&cookie); @@ -1687,47 +1616,43 @@ convert(Imaging imOut, Imaging imIn, const char *mode, } Imaging -ImagingConvert(Imaging imIn, const char *mode, - ImagingPalette palette, int dither) -{ +ImagingConvert(Imaging imIn, const char *mode, ImagingPalette palette, int dither) { return convert(NULL, imIn, mode, palette, dither); } Imaging -ImagingConvert2(Imaging imOut, Imaging imIn) -{ +ImagingConvert2(Imaging imOut, Imaging imIn) { return convert(imOut, imIn, imOut->mode, NULL, 0); } - Imaging -ImagingConvertTransparent(Imaging imIn, const char *mode, - int r, int g, int b) -{ +ImagingConvertTransparent(Imaging imIn, const char *mode, int r, int g, int b) { ImagingSectionCookie cookie; ImagingShuffler convert; Imaging imOut = NULL; int y; - if (!imIn){ - return (Imaging) ImagingError_ModeError(); + if (!imIn) { + return (Imaging)ImagingError_ModeError(); } - if (!((strcmp(imIn->mode, "RGB") == 0 || - strcmp(imIn->mode, "1") == 0 || - strcmp(imIn->mode, "I") == 0 || - strcmp(imIn->mode, "L") == 0) - && strcmp(mode, "RGBA") == 0)) + if (!((strcmp(imIn->mode, "RGB") == 0 || strcmp(imIn->mode, "1") == 0 || + strcmp(imIn->mode, "I") == 0 || strcmp(imIn->mode, "L") == 0) && + strcmp(mode, "RGBA") == 0)) #ifdef notdef { - return (Imaging) ImagingError_ValueError("conversion not supported"); + return (Imaging)ImagingError_ValueError("conversion not supported"); } #else { - static char buf[256]; - /* FIXME: may overflow if mode is too large */ - sprintf(buf, "conversion from %s to %s not supported in convert_transparent", imIn->mode, mode); - return (Imaging) ImagingError_ValueError(buf); + static char buf[256]; + /* FIXME: may overflow if mode is too large */ + sprintf( + buf, + "conversion from %s to %s not supported in convert_transparent", + imIn->mode, + mode); + return (Imaging)ImagingError_ValueError(buf); } #endif @@ -1745,25 +1670,22 @@ ImagingConvertTransparent(Imaging imIn, const char *mode, } imOut = ImagingNew2Dirty(mode, imOut, imIn); - if (!imOut){ + if (!imOut) { return NULL; } ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { - (*convert)((UINT8*) imOut->image[y], (UINT8*) imIn->image[y], - imIn->xsize); - rgbT2rgba((UINT8*) imOut->image[y], imIn->xsize, r, g, b); + (*convert)((UINT8 *)imOut->image[y], (UINT8 *)imIn->image[y], imIn->xsize); + rgbT2rgba((UINT8 *)imOut->image[y], imIn->xsize, r, g, b); } ImagingSectionLeave(&cookie); return imOut; - } Imaging -ImagingConvertInPlace(Imaging imIn, const char* mode) -{ +ImagingConvertInPlace(Imaging imIn, const char *mode) { ImagingSectionCookie cookie; ImagingShuffler convert; int y; @@ -1779,8 +1701,7 @@ ImagingConvertInPlace(Imaging imIn, const char* mode) ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { - (*convert)((UINT8*) imIn->image[y], (UINT8*) imIn->image[y], - imIn->xsize); + (*convert)((UINT8 *)imIn->image[y], (UINT8 *)imIn->image[y], imIn->xsize); } ImagingSectionLeave(&cookie); diff --git a/src/libImaging/ConvertYCbCr.c b/src/libImaging/ConvertYCbCr.c index 47de4ff71..142f065e5 100644 --- a/src/libImaging/ConvertYCbCr.c +++ b/src/libImaging/ConvertYCbCr.c @@ -28,356 +28,332 @@ #define SCALE 6 /* bits */ -static INT16 Y_R[] = { 0, 19, 38, 57, 77, 96, 115, 134, 153, 172, 191, -210, 230, 249, 268, 287, 306, 325, 344, 364, 383, 402, 421, 440, 459, -478, 498, 517, 536, 555, 574, 593, 612, 631, 651, 670, 689, 708, 727, -746, 765, 785, 804, 823, 842, 861, 880, 899, 919, 938, 957, 976, 995, -1014, 1033, 1052, 1072, 1091, 1110, 1129, 1148, 1167, 1186, 1206, -1225, 1244, 1263, 1282, 1301, 1320, 1340, 1359, 1378, 1397, 1416, -1435, 1454, 1473, 1493, 1512, 1531, 1550, 1569, 1588, 1607, 1627, -1646, 1665, 1684, 1703, 1722, 1741, 1761, 1780, 1799, 1818, 1837, -1856, 1875, 1894, 1914, 1933, 1952, 1971, 1990, 2009, 2028, 2048, -2067, 2086, 2105, 2124, 2143, 2162, 2182, 2201, 2220, 2239, 2258, -2277, 2296, 2315, 2335, 2354, 2373, 2392, 2411, 2430, 2449, 2469, -2488, 2507, 2526, 2545, 2564, 2583, 2602, 2622, 2641, 2660, 2679, -2698, 2717, 2736, 2756, 2775, 2794, 2813, 2832, 2851, 2870, 2890, -2909, 2928, 2947, 2966, 2985, 3004, 3023, 3043, 3062, 3081, 3100, -3119, 3138, 3157, 3177, 3196, 3215, 3234, 3253, 3272, 3291, 3311, -3330, 3349, 3368, 3387, 3406, 3425, 3444, 3464, 3483, 3502, 3521, -3540, 3559, 3578, 3598, 3617, 3636, 3655, 3674, 3693, 3712, 3732, -3751, 3770, 3789, 3808, 3827, 3846, 3865, 3885, 3904, 3923, 3942, -3961, 3980, 3999, 4019, 4038, 4057, 4076, 4095, 4114, 4133, 4153, -4172, 4191, 4210, 4229, 4248, 4267, 4286, 4306, 4325, 4344, 4363, -4382, 4401, 4420, 4440, 4459, 4478, 4497, 4516, 4535, 4554, 4574, -4593, 4612, 4631, 4650, 4669, 4688, 4707, 4727, 4746, 4765, 4784, -4803, 4822, 4841, 4861, 4880 }; +static INT16 Y_R[] = { + 0, 19, 38, 57, 77, 96, 115, 134, 153, 172, 191, 210, 230, 249, + 268, 287, 306, 325, 344, 364, 383, 402, 421, 440, 459, 478, 498, 517, + 536, 555, 574, 593, 612, 631, 651, 670, 689, 708, 727, 746, 765, 785, + 804, 823, 842, 861, 880, 899, 919, 938, 957, 976, 995, 1014, 1033, 1052, + 1072, 1091, 1110, 1129, 1148, 1167, 1186, 1206, 1225, 1244, 1263, 1282, 1301, 1320, + 1340, 1359, 1378, 1397, 1416, 1435, 1454, 1473, 1493, 1512, 1531, 1550, 1569, 1588, + 1607, 1627, 1646, 1665, 1684, 1703, 1722, 1741, 1761, 1780, 1799, 1818, 1837, 1856, + 1875, 1894, 1914, 1933, 1952, 1971, 1990, 2009, 2028, 2048, 2067, 2086, 2105, 2124, + 2143, 2162, 2182, 2201, 2220, 2239, 2258, 2277, 2296, 2315, 2335, 2354, 2373, 2392, + 2411, 2430, 2449, 2469, 2488, 2507, 2526, 2545, 2564, 2583, 2602, 2622, 2641, 2660, + 2679, 2698, 2717, 2736, 2756, 2775, 2794, 2813, 2832, 2851, 2870, 2890, 2909, 2928, + 2947, 2966, 2985, 3004, 3023, 3043, 3062, 3081, 3100, 3119, 3138, 3157, 3177, 3196, + 3215, 3234, 3253, 3272, 3291, 3311, 3330, 3349, 3368, 3387, 3406, 3425, 3444, 3464, + 3483, 3502, 3521, 3540, 3559, 3578, 3598, 3617, 3636, 3655, 3674, 3693, 3712, 3732, + 3751, 3770, 3789, 3808, 3827, 3846, 3865, 3885, 3904, 3923, 3942, 3961, 3980, 3999, + 4019, 4038, 4057, 4076, 4095, 4114, 4133, 4153, 4172, 4191, 4210, 4229, 4248, 4267, + 4286, 4306, 4325, 4344, 4363, 4382, 4401, 4420, 4440, 4459, 4478, 4497, 4516, 4535, + 4554, 4574, 4593, 4612, 4631, 4650, 4669, 4688, 4707, 4727, 4746, 4765, 4784, 4803, + 4822, 4841, 4861, 4880}; -static INT16 Y_G[] = { 0, 38, 75, 113, 150, 188, 225, 263, 301, 338, -376, 413, 451, 488, 526, 564, 601, 639, 676, 714, 751, 789, 826, 864, -902, 939, 977, 1014, 1052, 1089, 1127, 1165, 1202, 1240, 1277, 1315, -1352, 1390, 1428, 1465, 1503, 1540, 1578, 1615, 1653, 1691, 1728, -1766, 1803, 1841, 1878, 1916, 1954, 1991, 2029, 2066, 2104, 2141, -2179, 2217, 2254, 2292, 2329, 2367, 2404, 2442, 2479, 2517, 2555, -2592, 2630, 2667, 2705, 2742, 2780, 2818, 2855, 2893, 2930, 2968, -3005, 3043, 3081, 3118, 3156, 3193, 3231, 3268, 3306, 3344, 3381, -3419, 3456, 3494, 3531, 3569, 3607, 3644, 3682, 3719, 3757, 3794, -3832, 3870, 3907, 3945, 3982, 4020, 4057, 4095, 4132, 4170, 4208, -4245, 4283, 4320, 4358, 4395, 4433, 4471, 4508, 4546, 4583, 4621, -4658, 4696, 4734, 4771, 4809, 4846, 4884, 4921, 4959, 4997, 5034, -5072, 5109, 5147, 5184, 5222, 5260, 5297, 5335, 5372, 5410, 5447, -5485, 5522, 5560, 5598, 5635, 5673, 5710, 5748, 5785, 5823, 5861, -5898, 5936, 5973, 6011, 6048, 6086, 6124, 6161, 6199, 6236, 6274, -6311, 6349, 6387, 6424, 6462, 6499, 6537, 6574, 6612, 6650, 6687, -6725, 6762, 6800, 6837, 6875, 6913, 6950, 6988, 7025, 7063, 7100, -7138, 7175, 7213, 7251, 7288, 7326, 7363, 7401, 7438, 7476, 7514, -7551, 7589, 7626, 7664, 7701, 7739, 7777, 7814, 7852, 7889, 7927, -7964, 8002, 8040, 8077, 8115, 8152, 8190, 8227, 8265, 8303, 8340, -8378, 8415, 8453, 8490, 8528, 8566, 8603, 8641, 8678, 8716, 8753, -8791, 8828, 8866, 8904, 8941, 8979, 9016, 9054, 9091, 9129, 9167, -9204, 9242, 9279, 9317, 9354, 9392, 9430, 9467, 9505, 9542, 9580 }; +static INT16 Y_G[] = { + 0, 38, 75, 113, 150, 188, 225, 263, 301, 338, 376, 413, 451, 488, + 526, 564, 601, 639, 676, 714, 751, 789, 826, 864, 902, 939, 977, 1014, + 1052, 1089, 1127, 1165, 1202, 1240, 1277, 1315, 1352, 1390, 1428, 1465, 1503, 1540, + 1578, 1615, 1653, 1691, 1728, 1766, 1803, 1841, 1878, 1916, 1954, 1991, 2029, 2066, + 2104, 2141, 2179, 2217, 2254, 2292, 2329, 2367, 2404, 2442, 2479, 2517, 2555, 2592, + 2630, 2667, 2705, 2742, 2780, 2818, 2855, 2893, 2930, 2968, 3005, 3043, 3081, 3118, + 3156, 3193, 3231, 3268, 3306, 3344, 3381, 3419, 3456, 3494, 3531, 3569, 3607, 3644, + 3682, 3719, 3757, 3794, 3832, 3870, 3907, 3945, 3982, 4020, 4057, 4095, 4132, 4170, + 4208, 4245, 4283, 4320, 4358, 4395, 4433, 4471, 4508, 4546, 4583, 4621, 4658, 4696, + 4734, 4771, 4809, 4846, 4884, 4921, 4959, 4997, 5034, 5072, 5109, 5147, 5184, 5222, + 5260, 5297, 5335, 5372, 5410, 5447, 5485, 5522, 5560, 5598, 5635, 5673, 5710, 5748, + 5785, 5823, 5861, 5898, 5936, 5973, 6011, 6048, 6086, 6124, 6161, 6199, 6236, 6274, + 6311, 6349, 6387, 6424, 6462, 6499, 6537, 6574, 6612, 6650, 6687, 6725, 6762, 6800, + 6837, 6875, 6913, 6950, 6988, 7025, 7063, 7100, 7138, 7175, 7213, 7251, 7288, 7326, + 7363, 7401, 7438, 7476, 7514, 7551, 7589, 7626, 7664, 7701, 7739, 7777, 7814, 7852, + 7889, 7927, 7964, 8002, 8040, 8077, 8115, 8152, 8190, 8227, 8265, 8303, 8340, 8378, + 8415, 8453, 8490, 8528, 8566, 8603, 8641, 8678, 8716, 8753, 8791, 8828, 8866, 8904, + 8941, 8979, 9016, 9054, 9091, 9129, 9167, 9204, 9242, 9279, 9317, 9354, 9392, 9430, + 9467, 9505, 9542, 9580}; -static INT16 Y_B[] = { 0, 7, 15, 22, 29, 36, 44, 51, 58, 66, 73, 80, -88, 95, 102, 109, 117, 124, 131, 139, 146, 153, 161, 168, 175, 182, -190, 197, 204, 212, 219, 226, 233, 241, 248, 255, 263, 270, 277, 285, -292, 299, 306, 314, 321, 328, 336, 343, 350, 358, 365, 372, 379, 387, -394, 401, 409, 416, 423, 430, 438, 445, 452, 460, 467, 474, 482, 489, -496, 503, 511, 518, 525, 533, 540, 547, 554, 562, 569, 576, 584, 591, -598, 606, 613, 620, 627, 635, 642, 649, 657, 664, 671, 679, 686, 693, -700, 708, 715, 722, 730, 737, 744, 751, 759, 766, 773, 781, 788, 795, -803, 810, 817, 824, 832, 839, 846, 854, 861, 868, 876, 883, 890, 897, -905, 912, 919, 927, 934, 941, 948, 956, 963, 970, 978, 985, 992, 1000, -1007, 1014, 1021, 1029, 1036, 1043, 1051, 1058, 1065, 1073, 1080, -1087, 1094, 1102, 1109, 1116, 1124, 1131, 1138, 1145, 1153, 1160, -1167, 1175, 1182, 1189, 1197, 1204, 1211, 1218, 1226, 1233, 1240, -1248, 1255, 1262, 1270, 1277, 1284, 1291, 1299, 1306, 1313, 1321, -1328, 1335, 1342, 1350, 1357, 1364, 1372, 1379, 1386, 1394, 1401, -1408, 1415, 1423, 1430, 1437, 1445, 1452, 1459, 1466, 1474, 1481, -1488, 1496, 1503, 1510, 1518, 1525, 1532, 1539, 1547, 1554, 1561, -1569, 1576, 1583, 1591, 1598, 1605, 1612, 1620, 1627, 1634, 1642, -1649, 1656, 1663, 1671, 1678, 1685, 1693, 1700, 1707, 1715, 1722, -1729, 1736, 1744, 1751, 1758, 1766, 1773, 1780, 1788, 1795, 1802, -1809, 1817, 1824, 1831, 1839, 1846, 1853, 1860 }; +static INT16 Y_B[] = { + 0, 7, 15, 22, 29, 36, 44, 51, 58, 66, 73, 80, 88, 95, + 102, 109, 117, 124, 131, 139, 146, 153, 161, 168, 175, 182, 190, 197, + 204, 212, 219, 226, 233, 241, 248, 255, 263, 270, 277, 285, 292, 299, + 306, 314, 321, 328, 336, 343, 350, 358, 365, 372, 379, 387, 394, 401, + 409, 416, 423, 430, 438, 445, 452, 460, 467, 474, 482, 489, 496, 503, + 511, 518, 525, 533, 540, 547, 554, 562, 569, 576, 584, 591, 598, 606, + 613, 620, 627, 635, 642, 649, 657, 664, 671, 679, 686, 693, 700, 708, + 715, 722, 730, 737, 744, 751, 759, 766, 773, 781, 788, 795, 803, 810, + 817, 824, 832, 839, 846, 854, 861, 868, 876, 883, 890, 897, 905, 912, + 919, 927, 934, 941, 948, 956, 963, 970, 978, 985, 992, 1000, 1007, 1014, + 1021, 1029, 1036, 1043, 1051, 1058, 1065, 1073, 1080, 1087, 1094, 1102, 1109, 1116, + 1124, 1131, 1138, 1145, 1153, 1160, 1167, 1175, 1182, 1189, 1197, 1204, 1211, 1218, + 1226, 1233, 1240, 1248, 1255, 1262, 1270, 1277, 1284, 1291, 1299, 1306, 1313, 1321, + 1328, 1335, 1342, 1350, 1357, 1364, 1372, 1379, 1386, 1394, 1401, 1408, 1415, 1423, + 1430, 1437, 1445, 1452, 1459, 1466, 1474, 1481, 1488, 1496, 1503, 1510, 1518, 1525, + 1532, 1539, 1547, 1554, 1561, 1569, 1576, 1583, 1591, 1598, 1605, 1612, 1620, 1627, + 1634, 1642, 1649, 1656, 1663, 1671, 1678, 1685, 1693, 1700, 1707, 1715, 1722, 1729, + 1736, 1744, 1751, 1758, 1766, 1773, 1780, 1788, 1795, 1802, 1809, 1817, 1824, 1831, + 1839, 1846, 1853, 1860}; -static INT16 Cb_R[] = { 0, -10, -21, -31, -42, -53, -64, -75, -85, --96, -107, -118, -129, -139, -150, -161, -172, -183, -193, -204, -215, --226, -237, -247, -258, -269, -280, -291, -301, -312, -323, -334, --345, -355, -366, -377, -388, -399, -409, -420, -431, -442, -453, --463, -474, -485, -496, -507, -517, -528, -539, -550, -561, -571, --582, -593, -604, -615, -625, -636, -647, -658, -669, -679, -690, --701, -712, -723, -733, -744, -755, -766, -777, -787, -798, -809, --820, -831, -841, -852, -863, -874, -885, -895, -906, -917, -928, --939, -949, -960, -971, -982, -993, -1003, -1014, -1025, -1036, -1047, --1057, -1068, -1079, -1090, -1101, -1111, -1122, -1133, -1144, -1155, --1165, -1176, -1187, -1198, -1209, -1219, -1230, -1241, -1252, -1263, --1273, -1284, -1295, -1306, -1317, -1327, -1338, -1349, -1360, -1371, --1381, -1392, -1403, -1414, -1425, -1435, -1446, -1457, -1468, -1479, --1489, -1500, -1511, -1522, -1533, -1543, -1554, -1565, -1576, -1587, --1597, -1608, -1619, -1630, -1641, -1651, -1662, -1673, -1684, -1694, --1705, -1716, -1727, -1738, -1748, -1759, -1770, -1781, -1792, -1802, --1813, -1824, -1835, -1846, -1856, -1867, -1878, -1889, -1900, -1910, --1921, -1932, -1943, -1954, -1964, -1975, -1986, -1997, -2008, -2018, --2029, -2040, -2051, -2062, -2072, -2083, -2094, -2105, -2116, -2126, --2137, -2148, -2159, -2170, -2180, -2191, -2202, -2213, -2224, -2234, --2245, -2256, -2267, -2278, -2288, -2299, -2310, -2321, -2332, -2342, --2353, -2364, -2375, -2386, -2396, -2407, -2418, -2429, -2440, -2450, --2461, -2472, -2483, -2494, -2504, -2515, -2526, -2537, -2548, -2558, --2569, -2580, -2591, -2602, -2612, -2623, -2634, -2645, -2656, -2666, --2677, -2688, -2699, -2710, -2720, -2731, -2742, -2753 }; +static INT16 Cb_R[] = { + 0, -10, -21, -31, -42, -53, -64, -75, -85, -96, -107, -118, + -129, -139, -150, -161, -172, -183, -193, -204, -215, -226, -237, -247, + -258, -269, -280, -291, -301, -312, -323, -334, -345, -355, -366, -377, + -388, -399, -409, -420, -431, -442, -453, -463, -474, -485, -496, -507, + -517, -528, -539, -550, -561, -571, -582, -593, -604, -615, -625, -636, + -647, -658, -669, -679, -690, -701, -712, -723, -733, -744, -755, -766, + -777, -787, -798, -809, -820, -831, -841, -852, -863, -874, -885, -895, + -906, -917, -928, -939, -949, -960, -971, -982, -993, -1003, -1014, -1025, + -1036, -1047, -1057, -1068, -1079, -1090, -1101, -1111, -1122, -1133, -1144, -1155, + -1165, -1176, -1187, -1198, -1209, -1219, -1230, -1241, -1252, -1263, -1273, -1284, + -1295, -1306, -1317, -1327, -1338, -1349, -1360, -1371, -1381, -1392, -1403, -1414, + -1425, -1435, -1446, -1457, -1468, -1479, -1489, -1500, -1511, -1522, -1533, -1543, + -1554, -1565, -1576, -1587, -1597, -1608, -1619, -1630, -1641, -1651, -1662, -1673, + -1684, -1694, -1705, -1716, -1727, -1738, -1748, -1759, -1770, -1781, -1792, -1802, + -1813, -1824, -1835, -1846, -1856, -1867, -1878, -1889, -1900, -1910, -1921, -1932, + -1943, -1954, -1964, -1975, -1986, -1997, -2008, -2018, -2029, -2040, -2051, -2062, + -2072, -2083, -2094, -2105, -2116, -2126, -2137, -2148, -2159, -2170, -2180, -2191, + -2202, -2213, -2224, -2234, -2245, -2256, -2267, -2278, -2288, -2299, -2310, -2321, + -2332, -2342, -2353, -2364, -2375, -2386, -2396, -2407, -2418, -2429, -2440, -2450, + -2461, -2472, -2483, -2494, -2504, -2515, -2526, -2537, -2548, -2558, -2569, -2580, + -2591, -2602, -2612, -2623, -2634, -2645, -2656, -2666, -2677, -2688, -2699, -2710, + -2720, -2731, -2742, -2753}; -static INT16 Cb_G[] = { 0, -20, -41, -63, -84, -105, -126, -147, -169, --190, -211, -232, -253, -275, -296, -317, -338, -359, -381, -402, --423, -444, -465, -487, -508, -529, -550, -571, -593, -614, -635, --656, -677, -699, -720, -741, -762, -783, -805, -826, -847, -868, --889, -911, -932, -953, -974, -995, -1017, -1038, -1059, -1080, -1101, --1123, -1144, -1165, -1186, -1207, -1229, -1250, -1271, -1292, -1313, --1335, -1356, -1377, -1398, -1419, -1441, -1462, -1483, -1504, -1525, --1547, -1568, -1589, -1610, -1631, -1653, -1674, -1695, -1716, -1737, --1759, -1780, -1801, -1822, -1843, -1865, -1886, -1907, -1928, -1949, --1971, -1992, -2013, -2034, -2055, -2077, -2098, -2119, -2140, -2161, --2183, -2204, -2225, -2246, -2267, -2289, -2310, -2331, -2352, -2373, --2395, -2416, -2437, -2458, -2479, -2501, -2522, -2543, -2564, -2585, --2607, -2628, -2649, -2670, -2691, -2713, -2734, -2755, -2776, -2797, --2819, -2840, -2861, -2882, -2903, -2925, -2946, -2967, -2988, -3009, --3031, -3052, -3073, -3094, -3115, -3137, -3158, -3179, -3200, -3221, --3243, -3264, -3285, -3306, -3328, -3349, -3370, -3391, -3412, -3434, --3455, -3476, -3497, -3518, -3540, -3561, -3582, -3603, -3624, -3646, --3667, -3688, -3709, -3730, -3752, -3773, -3794, -3815, -3836, -3858, --3879, -3900, -3921, -3942, -3964, -3985, -4006, -4027, -4048, -4070, --4091, -4112, -4133, -4154, -4176, -4197, -4218, -4239, -4260, -4282, --4303, -4324, -4345, -4366, -4388, -4409, -4430, -4451, -4472, -4494, --4515, -4536, -4557, -4578, -4600, -4621, -4642, -4663, -4684, -4706, --4727, -4748, -4769, -4790, -4812, -4833, -4854, -4875, -4896, -4918, --4939, -4960, -4981, -5002, -5024, -5045, -5066, -5087, -5108, -5130, --5151, -5172, -5193, -5214, -5236, -5257, -5278, -5299, -5320, -5342, --5363, -5384, -5405 }; +static INT16 Cb_G[] = { + 0, -20, -41, -63, -84, -105, -126, -147, -169, -190, -211, -232, + -253, -275, -296, -317, -338, -359, -381, -402, -423, -444, -465, -487, + -508, -529, -550, -571, -593, -614, -635, -656, -677, -699, -720, -741, + -762, -783, -805, -826, -847, -868, -889, -911, -932, -953, -974, -995, + -1017, -1038, -1059, -1080, -1101, -1123, -1144, -1165, -1186, -1207, -1229, -1250, + -1271, -1292, -1313, -1335, -1356, -1377, -1398, -1419, -1441, -1462, -1483, -1504, + -1525, -1547, -1568, -1589, -1610, -1631, -1653, -1674, -1695, -1716, -1737, -1759, + -1780, -1801, -1822, -1843, -1865, -1886, -1907, -1928, -1949, -1971, -1992, -2013, + -2034, -2055, -2077, -2098, -2119, -2140, -2161, -2183, -2204, -2225, -2246, -2267, + -2289, -2310, -2331, -2352, -2373, -2395, -2416, -2437, -2458, -2479, -2501, -2522, + -2543, -2564, -2585, -2607, -2628, -2649, -2670, -2691, -2713, -2734, -2755, -2776, + -2797, -2819, -2840, -2861, -2882, -2903, -2925, -2946, -2967, -2988, -3009, -3031, + -3052, -3073, -3094, -3115, -3137, -3158, -3179, -3200, -3221, -3243, -3264, -3285, + -3306, -3328, -3349, -3370, -3391, -3412, -3434, -3455, -3476, -3497, -3518, -3540, + -3561, -3582, -3603, -3624, -3646, -3667, -3688, -3709, -3730, -3752, -3773, -3794, + -3815, -3836, -3858, -3879, -3900, -3921, -3942, -3964, -3985, -4006, -4027, -4048, + -4070, -4091, -4112, -4133, -4154, -4176, -4197, -4218, -4239, -4260, -4282, -4303, + -4324, -4345, -4366, -4388, -4409, -4430, -4451, -4472, -4494, -4515, -4536, -4557, + -4578, -4600, -4621, -4642, -4663, -4684, -4706, -4727, -4748, -4769, -4790, -4812, + -4833, -4854, -4875, -4896, -4918, -4939, -4960, -4981, -5002, -5024, -5045, -5066, + -5087, -5108, -5130, -5151, -5172, -5193, -5214, -5236, -5257, -5278, -5299, -5320, + -5342, -5363, -5384, -5405}; -static INT16 Cb_B[] = { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, -320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, -768, 800, 832, 864, 896, 928, 960, 992, 1024, 1056, 1088, 1120, 1152, -1184, 1216, 1248, 1280, 1312, 1344, 1376, 1408, 1440, 1472, 1504, -1536, 1568, 1600, 1632, 1664, 1696, 1728, 1760, 1792, 1824, 1856, -1888, 1920, 1952, 1984, 2016, 2048, 2080, 2112, 2144, 2176, 2208, -2240, 2272, 2304, 2336, 2368, 2400, 2432, 2464, 2496, 2528, 2560, -2592, 2624, 2656, 2688, 2720, 2752, 2784, 2816, 2848, 2880, 2912, -2944, 2976, 3008, 3040, 3072, 3104, 3136, 3168, 3200, 3232, 3264, -3296, 3328, 3360, 3392, 3424, 3456, 3488, 3520, 3552, 3584, 3616, -3648, 3680, 3712, 3744, 3776, 3808, 3840, 3872, 3904, 3936, 3968, -4000, 4032, 4064, 4096, 4128, 4160, 4192, 4224, 4256, 4288, 4320, -4352, 4384, 4416, 4448, 4480, 4512, 4544, 4576, 4608, 4640, 4672, -4704, 4736, 4768, 4800, 4832, 4864, 4896, 4928, 4960, 4992, 5024, -5056, 5088, 5120, 5152, 5184, 5216, 5248, 5280, 5312, 5344, 5376, -5408, 5440, 5472, 5504, 5536, 5568, 5600, 5632, 5664, 5696, 5728, -5760, 5792, 5824, 5856, 5888, 5920, 5952, 5984, 6016, 6048, 6080, -6112, 6144, 6176, 6208, 6240, 6272, 6304, 6336, 6368, 6400, 6432, -6464, 6496, 6528, 6560, 6592, 6624, 6656, 6688, 6720, 6752, 6784, -6816, 6848, 6880, 6912, 6944, 6976, 7008, 7040, 7072, 7104, 7136, -7168, 7200, 7232, 7264, 7296, 7328, 7360, 7392, 7424, 7456, 7488, -7520, 7552, 7584, 7616, 7648, 7680, 7712, 7744, 7776, 7808, 7840, -7872, 7904, 7936, 7968, 8000, 8032, 8064, 8096, 8128, 8160 }; +static INT16 Cb_B[] = { + 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, + 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, + 896, 928, 960, 992, 1024, 1056, 1088, 1120, 1152, 1184, 1216, 1248, 1280, 1312, + 1344, 1376, 1408, 1440, 1472, 1504, 1536, 1568, 1600, 1632, 1664, 1696, 1728, 1760, + 1792, 1824, 1856, 1888, 1920, 1952, 1984, 2016, 2048, 2080, 2112, 2144, 2176, 2208, + 2240, 2272, 2304, 2336, 2368, 2400, 2432, 2464, 2496, 2528, 2560, 2592, 2624, 2656, + 2688, 2720, 2752, 2784, 2816, 2848, 2880, 2912, 2944, 2976, 3008, 3040, 3072, 3104, + 3136, 3168, 3200, 3232, 3264, 3296, 3328, 3360, 3392, 3424, 3456, 3488, 3520, 3552, + 3584, 3616, 3648, 3680, 3712, 3744, 3776, 3808, 3840, 3872, 3904, 3936, 3968, 4000, + 4032, 4064, 4096, 4128, 4160, 4192, 4224, 4256, 4288, 4320, 4352, 4384, 4416, 4448, + 4480, 4512, 4544, 4576, 4608, 4640, 4672, 4704, 4736, 4768, 4800, 4832, 4864, 4896, + 4928, 4960, 4992, 5024, 5056, 5088, 5120, 5152, 5184, 5216, 5248, 5280, 5312, 5344, + 5376, 5408, 5440, 5472, 5504, 5536, 5568, 5600, 5632, 5664, 5696, 5728, 5760, 5792, + 5824, 5856, 5888, 5920, 5952, 5984, 6016, 6048, 6080, 6112, 6144, 6176, 6208, 6240, + 6272, 6304, 6336, 6368, 6400, 6432, 6464, 6496, 6528, 6560, 6592, 6624, 6656, 6688, + 6720, 6752, 6784, 6816, 6848, 6880, 6912, 6944, 6976, 7008, 7040, 7072, 7104, 7136, + 7168, 7200, 7232, 7264, 7296, 7328, 7360, 7392, 7424, 7456, 7488, 7520, 7552, 7584, + 7616, 7648, 7680, 7712, 7744, 7776, 7808, 7840, 7872, 7904, 7936, 7968, 8000, 8032, + 8064, 8096, 8128, 8160}; #define Cr_R Cb_B -static INT16 Cr_G[] = { 0, -26, -53, -79, -106, -133, -160, -187, --213, -240, -267, -294, -321, -347, -374, -401, -428, -455, -481, --508, -535, -562, -589, -615, -642, -669, -696, -722, -749, -776, --803, -830, -856, -883, -910, -937, -964, -990, -1017, -1044, -1071, --1098, -1124, -1151, -1178, -1205, -1232, -1258, -1285, -1312, -1339, --1366, -1392, -1419, -1446, -1473, -1500, -1526, -1553, -1580, -1607, --1634, -1660, -1687, -1714, -1741, -1768, -1794, -1821, -1848, -1875, --1902, -1928, -1955, -1982, -2009, -2036, -2062, -2089, -2116, -2143, --2169, -2196, -2223, -2250, -2277, -2303, -2330, -2357, -2384, -2411, --2437, -2464, -2491, -2518, -2545, -2571, -2598, -2625, -2652, -2679, --2705, -2732, -2759, -2786, -2813, -2839, -2866, -2893, -2920, -2947, --2973, -3000, -3027, -3054, -3081, -3107, -3134, -3161, -3188, -3215, --3241, -3268, -3295, -3322, -3349, -3375, -3402, -3429, -3456, -3483, --3509, -3536, -3563, -3590, -3616, -3643, -3670, -3697, -3724, -3750, --3777, -3804, -3831, -3858, -3884, -3911, -3938, -3965, -3992, -4018, --4045, -4072, -4099, -4126, -4152, -4179, -4206, -4233, -4260, -4286, --4313, -4340, -4367, -4394, -4420, -4447, -4474, -4501, -4528, -4554, --4581, -4608, -4635, -4662, -4688, -4715, -4742, -4769, -4796, -4822, --4849, -4876, -4903, -4929, -4956, -4983, -5010, -5037, -5063, -5090, --5117, -5144, -5171, -5197, -5224, -5251, -5278, -5305, -5331, -5358, --5385, -5412, -5439, -5465, -5492, -5519, -5546, -5573, -5599, -5626, --5653, -5680, -5707, -5733, -5760, -5787, -5814, -5841, -5867, -5894, --5921, -5948, -5975, -6001, -6028, -6055, -6082, -6109, -6135, -6162, --6189, -6216, -6243, -6269, -6296, -6323, -6350, -6376, -6403, -6430, --6457, -6484, -6510, -6537, -6564, -6591, -6618, -6644, -6671, -6698, --6725, -6752, -6778, -6805, -6832 }; +static INT16 Cr_G[] = { + 0, -26, -53, -79, -106, -133, -160, -187, -213, -240, -267, -294, + -321, -347, -374, -401, -428, -455, -481, -508, -535, -562, -589, -615, + -642, -669, -696, -722, -749, -776, -803, -830, -856, -883, -910, -937, + -964, -990, -1017, -1044, -1071, -1098, -1124, -1151, -1178, -1205, -1232, -1258, + -1285, -1312, -1339, -1366, -1392, -1419, -1446, -1473, -1500, -1526, -1553, -1580, + -1607, -1634, -1660, -1687, -1714, -1741, -1768, -1794, -1821, -1848, -1875, -1902, + -1928, -1955, -1982, -2009, -2036, -2062, -2089, -2116, -2143, -2169, -2196, -2223, + -2250, -2277, -2303, -2330, -2357, -2384, -2411, -2437, -2464, -2491, -2518, -2545, + -2571, -2598, -2625, -2652, -2679, -2705, -2732, -2759, -2786, -2813, -2839, -2866, + -2893, -2920, -2947, -2973, -3000, -3027, -3054, -3081, -3107, -3134, -3161, -3188, + -3215, -3241, -3268, -3295, -3322, -3349, -3375, -3402, -3429, -3456, -3483, -3509, + -3536, -3563, -3590, -3616, -3643, -3670, -3697, -3724, -3750, -3777, -3804, -3831, + -3858, -3884, -3911, -3938, -3965, -3992, -4018, -4045, -4072, -4099, -4126, -4152, + -4179, -4206, -4233, -4260, -4286, -4313, -4340, -4367, -4394, -4420, -4447, -4474, + -4501, -4528, -4554, -4581, -4608, -4635, -4662, -4688, -4715, -4742, -4769, -4796, + -4822, -4849, -4876, -4903, -4929, -4956, -4983, -5010, -5037, -5063, -5090, -5117, + -5144, -5171, -5197, -5224, -5251, -5278, -5305, -5331, -5358, -5385, -5412, -5439, + -5465, -5492, -5519, -5546, -5573, -5599, -5626, -5653, -5680, -5707, -5733, -5760, + -5787, -5814, -5841, -5867, -5894, -5921, -5948, -5975, -6001, -6028, -6055, -6082, + -6109, -6135, -6162, -6189, -6216, -6243, -6269, -6296, -6323, -6350, -6376, -6403, + -6430, -6457, -6484, -6510, -6537, -6564, -6591, -6618, -6644, -6671, -6698, -6725, + -6752, -6778, -6805, -6832}; -static INT16 Cr_B[] = { 0, -4, -9, -15, -20, -25, -30, -35, -41, -46, --51, -56, -61, -67, -72, -77, -82, -87, -93, -98, -103, -108, -113, --119, -124, -129, -134, -140, -145, -150, -155, -160, -166, -171, --176, -181, -186, -192, -197, -202, -207, -212, -218, -223, -228, --233, -238, -244, -249, -254, -259, -264, -270, -275, -280, -285, --290, -296, -301, -306, -311, -316, -322, -327, -332, -337, -342, --348, -353, -358, -363, -368, -374, -379, -384, -389, -394, -400, --405, -410, -415, -421, -426, -431, -436, -441, -447, -452, -457, --462, -467, -473, -478, -483, -488, -493, -499, -504, -509, -514, --519, -525, -530, -535, -540, -545, -551, -556, -561, -566, -571, --577, -582, -587, -592, -597, -603, -608, -613, -618, -623, -629, --634, -639, -644, -649, -655, -660, -665, -670, -675, -681, -686, --691, -696, -702, -707, -712, -717, -722, -728, -733, -738, -743, --748, -754, -759, -764, -769, -774, -780, -785, -790, -795, -800, --806, -811, -816, -821, -826, -832, -837, -842, -847, -852, -858, --863, -868, -873, -878, -884, -889, -894, -899, -904, -910, -915, --920, -925, -930, -936, -941, -946, -951, -957, -962, -967, -972, --977, -983, -988, -993, -998, -1003, -1009, -1014, -1019, -1024, --1029, -1035, -1040, -1045, -1050, -1055, -1061, -1066, -1071, -1076, --1081, -1087, -1092, -1097, -1102, -1107, -1113, -1118, -1123, -1128, --1133, -1139, -1144, -1149, -1154, -1159, -1165, -1170, -1175, -1180, --1185, -1191, -1196, -1201, -1206, -1211, -1217, -1222, -1227, -1232, --1238, -1243, -1248, -1253, -1258, -1264, -1269, -1274, -1279, -1284, --1290, -1295, -1300, -1305, -1310, -1316, -1321, -1326 }; +static INT16 Cr_B[] = { + 0, -4, -9, -15, -20, -25, -30, -35, -41, -46, -51, -56, + -61, -67, -72, -77, -82, -87, -93, -98, -103, -108, -113, -119, + -124, -129, -134, -140, -145, -150, -155, -160, -166, -171, -176, -181, + -186, -192, -197, -202, -207, -212, -218, -223, -228, -233, -238, -244, + -249, -254, -259, -264, -270, -275, -280, -285, -290, -296, -301, -306, + -311, -316, -322, -327, -332, -337, -342, -348, -353, -358, -363, -368, + -374, -379, -384, -389, -394, -400, -405, -410, -415, -421, -426, -431, + -436, -441, -447, -452, -457, -462, -467, -473, -478, -483, -488, -493, + -499, -504, -509, -514, -519, -525, -530, -535, -540, -545, -551, -556, + -561, -566, -571, -577, -582, -587, -592, -597, -603, -608, -613, -618, + -623, -629, -634, -639, -644, -649, -655, -660, -665, -670, -675, -681, + -686, -691, -696, -702, -707, -712, -717, -722, -728, -733, -738, -743, + -748, -754, -759, -764, -769, -774, -780, -785, -790, -795, -800, -806, + -811, -816, -821, -826, -832, -837, -842, -847, -852, -858, -863, -868, + -873, -878, -884, -889, -894, -899, -904, -910, -915, -920, -925, -930, + -936, -941, -946, -951, -957, -962, -967, -972, -977, -983, -988, -993, + -998, -1003, -1009, -1014, -1019, -1024, -1029, -1035, -1040, -1045, -1050, -1055, + -1061, -1066, -1071, -1076, -1081, -1087, -1092, -1097, -1102, -1107, -1113, -1118, + -1123, -1128, -1133, -1139, -1144, -1149, -1154, -1159, -1165, -1170, -1175, -1180, + -1185, -1191, -1196, -1201, -1206, -1211, -1217, -1222, -1227, -1232, -1238, -1243, + -1248, -1253, -1258, -1264, -1269, -1274, -1279, -1284, -1290, -1295, -1300, -1305, + -1310, -1316, -1321, -1326}; -static INT16 R_Cr[] = { -11484, -11394, -11305, -11215, -11125, --11036, -10946, -10856, -10766, -10677, -10587, -10497, -10407, --10318, -10228, -10138, -10049, -9959, -9869, -9779, -9690, -9600, --9510, -9420, -9331, -9241, -9151, -9062, -8972, -8882, -8792, -8703, --8613, -8523, -8433, -8344, -8254, -8164, -8075, -7985, -7895, -7805, --7716, -7626, -7536, -7446, -7357, -7267, -7177, -7088, -6998, -6908, --6818, -6729, -6639, -6549, -6459, -6370, -6280, -6190, -6101, -6011, --5921, -5831, -5742, -5652, -5562, -5472, -5383, -5293, -5203, -5113, --5024, -4934, -4844, -4755, -4665, -4575, -4485, -4396, -4306, -4216, --4126, -4037, -3947, -3857, -3768, -3678, -3588, -3498, -3409, -3319, --3229, -3139, -3050, -2960, -2870, -2781, -2691, -2601, -2511, -2422, --2332, -2242, -2152, -2063, -1973, -1883, -1794, -1704, -1614, -1524, --1435, -1345, -1255, -1165, -1076, -986, -896, -807, -717, -627, -537, --448, -358, -268, -178, -89, 0, 90, 179, 269, 359, 449, 538, 628, 718, -808, 897, 987, 1077, 1166, 1256, 1346, 1436, 1525, 1615, 1705, 1795, -1884, 1974, 2064, 2153, 2243, 2333, 2423, 2512, 2602, 2692, 2782, -2871, 2961, 3051, 3140, 3230, 3320, 3410, 3499, 3589, 3679, 3769, -3858, 3948, 4038, 4127, 4217, 4307, 4397, 4486, 4576, 4666, 4756, -4845, 4935, 5025, 5114, 5204, 5294, 5384, 5473, 5563, 5653, 5743, -5832, 5922, 6012, 6102, 6191, 6281, 6371, 6460, 6550, 6640, 6730, -6819, 6909, 6999, 7089, 7178, 7268, 7358, 7447, 7537, 7627, 7717, -7806, 7896, 7986, 8076, 8165, 8255, 8345, 8434, 8524, 8614, 8704, -8793, 8883, 8973, 9063, 9152, 9242, 9332, 9421, 9511, 9601, 9691, -9780, 9870, 9960, 10050, 10139, 10229, 10319, 10408, 10498, 10588, -10678, 10767, 10857, 10947, 11037, 11126, 11216, 11306, 11395 }; +static INT16 R_Cr[] = { + -11484, -11394, -11305, -11215, -11125, -11036, -10946, -10856, -10766, -10677, + -10587, -10497, -10407, -10318, -10228, -10138, -10049, -9959, -9869, -9779, + -9690, -9600, -9510, -9420, -9331, -9241, -9151, -9062, -8972, -8882, + -8792, -8703, -8613, -8523, -8433, -8344, -8254, -8164, -8075, -7985, + -7895, -7805, -7716, -7626, -7536, -7446, -7357, -7267, -7177, -7088, + -6998, -6908, -6818, -6729, -6639, -6549, -6459, -6370, -6280, -6190, + -6101, -6011, -5921, -5831, -5742, -5652, -5562, -5472, -5383, -5293, + -5203, -5113, -5024, -4934, -4844, -4755, -4665, -4575, -4485, -4396, + -4306, -4216, -4126, -4037, -3947, -3857, -3768, -3678, -3588, -3498, + -3409, -3319, -3229, -3139, -3050, -2960, -2870, -2781, -2691, -2601, + -2511, -2422, -2332, -2242, -2152, -2063, -1973, -1883, -1794, -1704, + -1614, -1524, -1435, -1345, -1255, -1165, -1076, -986, -896, -807, + -717, -627, -537, -448, -358, -268, -178, -89, 0, 90, + 179, 269, 359, 449, 538, 628, 718, 808, 897, 987, + 1077, 1166, 1256, 1346, 1436, 1525, 1615, 1705, 1795, 1884, + 1974, 2064, 2153, 2243, 2333, 2423, 2512, 2602, 2692, 2782, + 2871, 2961, 3051, 3140, 3230, 3320, 3410, 3499, 3589, 3679, + 3769, 3858, 3948, 4038, 4127, 4217, 4307, 4397, 4486, 4576, + 4666, 4756, 4845, 4935, 5025, 5114, 5204, 5294, 5384, 5473, + 5563, 5653, 5743, 5832, 5922, 6012, 6102, 6191, 6281, 6371, + 6460, 6550, 6640, 6730, 6819, 6909, 6999, 7089, 7178, 7268, + 7358, 7447, 7537, 7627, 7717, 7806, 7896, 7986, 8076, 8165, + 8255, 8345, 8434, 8524, 8614, 8704, 8793, 8883, 8973, 9063, + 9152, 9242, 9332, 9421, 9511, 9601, 9691, 9780, 9870, 9960, + 10050, 10139, 10229, 10319, 10408, 10498, 10588, 10678, 10767, 10857, + 10947, 11037, 11126, 11216, 11306, 11395}; -static INT16 G_Cb[] = { 2819, 2797, 2775, 2753, 2731, 2709, 2687, -2665, 2643, 2621, 2599, 2577, 2555, 2533, 2511, 2489, 2467, 2445, -2423, 2401, 2379, 2357, 2335, 2313, 2291, 2269, 2247, 2225, 2202, -2180, 2158, 2136, 2114, 2092, 2070, 2048, 2026, 2004, 1982, 1960, -1938, 1916, 1894, 1872, 1850, 1828, 1806, 1784, 1762, 1740, 1718, -1696, 1674, 1652, 1630, 1608, 1586, 1564, 1542, 1520, 1498, 1476, -1454, 1432, 1410, 1388, 1366, 1344, 1321, 1299, 1277, 1255, 1233, -1211, 1189, 1167, 1145, 1123, 1101, 1079, 1057, 1035, 1013, 991, 969, -947, 925, 903, 881, 859, 837, 815, 793, 771, 749, 727, 705, 683, 661, -639, 617, 595, 573, 551, 529, 507, 485, 463, 440, 418, 396, 374, 352, -330, 308, 286, 264, 242, 220, 198, 176, 154, 132, 110, 88, 66, 44, 22, -0, -21, -43, -65, -87, -109, -131, -153, -175, -197, -219, -241, -263, --285, -307, -329, -351, -373, -395, -417, -439, -462, -484, -506, --528, -550, -572, -594, -616, -638, -660, -682, -704, -726, -748, --770, -792, -814, -836, -858, -880, -902, -924, -946, -968, -990, --1012, -1034, -1056, -1078, -1100, -1122, -1144, -1166, -1188, -1210, --1232, -1254, -1276, -1298, -1320, -1343, -1365, -1387, -1409, -1431, --1453, -1475, -1497, -1519, -1541, -1563, -1585, -1607, -1629, -1651, --1673, -1695, -1717, -1739, -1761, -1783, -1805, -1827, -1849, -1871, --1893, -1915, -1937, -1959, -1981, -2003, -2025, -2047, -2069, -2091, --2113, -2135, -2157, -2179, -2201, -2224, -2246, -2268, -2290, -2312, --2334, -2356, -2378, -2400, -2422, -2444, -2466, -2488, -2510, -2532, --2554, -2576, -2598, -2620, -2642, -2664, -2686, -2708, -2730, -2752, --2774, -2796 }; +static INT16 G_Cb[] = { + 2819, 2797, 2775, 2753, 2731, 2709, 2687, 2665, 2643, 2621, 2599, 2577, + 2555, 2533, 2511, 2489, 2467, 2445, 2423, 2401, 2379, 2357, 2335, 2313, + 2291, 2269, 2247, 2225, 2202, 2180, 2158, 2136, 2114, 2092, 2070, 2048, + 2026, 2004, 1982, 1960, 1938, 1916, 1894, 1872, 1850, 1828, 1806, 1784, + 1762, 1740, 1718, 1696, 1674, 1652, 1630, 1608, 1586, 1564, 1542, 1520, + 1498, 1476, 1454, 1432, 1410, 1388, 1366, 1344, 1321, 1299, 1277, 1255, + 1233, 1211, 1189, 1167, 1145, 1123, 1101, 1079, 1057, 1035, 1013, 991, + 969, 947, 925, 903, 881, 859, 837, 815, 793, 771, 749, 727, + 705, 683, 661, 639, 617, 595, 573, 551, 529, 507, 485, 463, + 440, 418, 396, 374, 352, 330, 308, 286, 264, 242, 220, 198, + 176, 154, 132, 110, 88, 66, 44, 22, 0, -21, -43, -65, + -87, -109, -131, -153, -175, -197, -219, -241, -263, -285, -307, -329, + -351, -373, -395, -417, -439, -462, -484, -506, -528, -550, -572, -594, + -616, -638, -660, -682, -704, -726, -748, -770, -792, -814, -836, -858, + -880, -902, -924, -946, -968, -990, -1012, -1034, -1056, -1078, -1100, -1122, + -1144, -1166, -1188, -1210, -1232, -1254, -1276, -1298, -1320, -1343, -1365, -1387, + -1409, -1431, -1453, -1475, -1497, -1519, -1541, -1563, -1585, -1607, -1629, -1651, + -1673, -1695, -1717, -1739, -1761, -1783, -1805, -1827, -1849, -1871, -1893, -1915, + -1937, -1959, -1981, -2003, -2025, -2047, -2069, -2091, -2113, -2135, -2157, -2179, + -2201, -2224, -2246, -2268, -2290, -2312, -2334, -2356, -2378, -2400, -2422, -2444, + -2466, -2488, -2510, -2532, -2554, -2576, -2598, -2620, -2642, -2664, -2686, -2708, + -2730, -2752, -2774, -2796}; -static INT16 G_Cr[] = { 5850, 5805, 5759, 5713, 5667, 5622, 5576, -5530, 5485, 5439, 5393, 5347, 5302, 5256, 5210, 5165, 5119, 5073, -5028, 4982, 4936, 4890, 4845, 4799, 4753, 4708, 4662, 4616, 4570, -4525, 4479, 4433, 4388, 4342, 4296, 4251, 4205, 4159, 4113, 4068, -4022, 3976, 3931, 3885, 3839, 3794, 3748, 3702, 3656, 3611, 3565, -3519, 3474, 3428, 3382, 3336, 3291, 3245, 3199, 3154, 3108, 3062, -3017, 2971, 2925, 2879, 2834, 2788, 2742, 2697, 2651, 2605, 2559, -2514, 2468, 2422, 2377, 2331, 2285, 2240, 2194, 2148, 2102, 2057, -2011, 1965, 1920, 1874, 1828, 1782, 1737, 1691, 1645, 1600, 1554, -1508, 1463, 1417, 1371, 1325, 1280, 1234, 1188, 1143, 1097, 1051, -1006, 960, 914, 868, 823, 777, 731, 686, 640, 594, 548, 503, 457, 411, -366, 320, 274, 229, 183, 137, 91, 46, 0, -45, -90, -136, -182, -228, --273, -319, -365, -410, -456, -502, -547, -593, -639, -685, -730, --776, -822, -867, -913, -959, -1005, -1050, -1096, -1142, -1187, --1233, -1279, -1324, -1370, -1416, -1462, -1507, -1553, -1599, -1644, --1690, -1736, -1781, -1827, -1873, -1919, -1964, -2010, -2056, -2101, --2147, -2193, -2239, -2284, -2330, -2376, -2421, -2467, -2513, -2558, --2604, -2650, -2696, -2741, -2787, -2833, -2878, -2924, -2970, -3016, --3061, -3107, -3153, -3198, -3244, -3290, -3335, -3381, -3427, -3473, --3518, -3564, -3610, -3655, -3701, -3747, -3793, -3838, -3884, -3930, --3975, -4021, -4067, -4112, -4158, -4204, -4250, -4295, -4341, -4387, --4432, -4478, -4524, -4569, -4615, -4661, -4707, -4752, -4798, -4844, --4889, -4935, -4981, -5027, -5072, -5118, -5164, -5209, -5255, -5301, --5346, -5392, -5438, -5484, -5529, -5575, -5621, -5666, -5712, -5758, --5804 }; - -static INT16 B_Cb[] = { -14515, -14402, -14288, -14175, -14062, --13948, -13835, -13721, -13608, -13495, -13381, -13268, -13154, --13041, -12928, -12814, -12701, -12587, -12474, -12360, -12247, --12134, -12020, -11907, -11793, -11680, -11567, -11453, -11340, --11226, -11113, -11000, -10886, -10773, -10659, -10546, -10433, --10319, -10206, -10092, -9979, -9865, -9752, -9639, -9525, -9412, --9298, -9185, -9072, -8958, -8845, -8731, -8618, -8505, -8391, -8278, --8164, -8051, -7938, -7824, -7711, -7597, -7484, -7371, -7257, -7144, --7030, -6917, -6803, -6690, -6577, -6463, -6350, -6236, -6123, -6010, --5896, -5783, -5669, -5556, -5443, -5329, -5216, -5102, -4989, -4876, --4762, -4649, -4535, -4422, -4309, -4195, -4082, -3968, -3855, -3741, --3628, -3515, -3401, -3288, -3174, -3061, -2948, -2834, -2721, -2607, --2494, -2381, -2267, -2154, -2040, -1927, -1814, -1700, -1587, -1473, --1360, -1246, -1133, -1020, -906, -793, -679, -566, -453, -339, -226, --112, 0, 113, 227, 340, 454, 567, 680, 794, 907, 1021, 1134, 1247, -1361, 1474, 1588, 1701, 1815, 1928, 2041, 2155, 2268, 2382, 2495, -2608, 2722, 2835, 2949, 3062, 3175, 3289, 3402, 3516, 3629, 3742, -3856, 3969, 4083, 4196, 4310, 4423, 4536, 4650, 4763, 4877, 4990, -5103, 5217, 5330, 5444, 5557, 5670, 5784, 5897, 6011, 6124, 6237, -6351, 6464, 6578, 6691, 6804, 6918, 7031, 7145, 7258, 7372, 7485, -7598, 7712, 7825, 7939, 8052, 8165, 8279, 8392, 8506, 8619, 8732, -8846, 8959, 9073, 9186, 9299, 9413, 9526, 9640, 9753, 9866, 9980, -10093, 10207, 10320, 10434, 10547, 10660, 10774, 10887, 11001, 11114, -11227, 11341, 11454, 11568, 11681, 11794, 11908, 12021, 12135, 12248, -12361, 12475, 12588, 12702, 12815, 12929, 13042, 13155, 13269, 13382, -13496, 13609, 13722, 13836, 13949, 14063, 14176, 14289, 14403 }; +static INT16 G_Cr[] = { + 5850, 5805, 5759, 5713, 5667, 5622, 5576, 5530, 5485, 5439, 5393, 5347, + 5302, 5256, 5210, 5165, 5119, 5073, 5028, 4982, 4936, 4890, 4845, 4799, + 4753, 4708, 4662, 4616, 4570, 4525, 4479, 4433, 4388, 4342, 4296, 4251, + 4205, 4159, 4113, 4068, 4022, 3976, 3931, 3885, 3839, 3794, 3748, 3702, + 3656, 3611, 3565, 3519, 3474, 3428, 3382, 3336, 3291, 3245, 3199, 3154, + 3108, 3062, 3017, 2971, 2925, 2879, 2834, 2788, 2742, 2697, 2651, 2605, + 2559, 2514, 2468, 2422, 2377, 2331, 2285, 2240, 2194, 2148, 2102, 2057, + 2011, 1965, 1920, 1874, 1828, 1782, 1737, 1691, 1645, 1600, 1554, 1508, + 1463, 1417, 1371, 1325, 1280, 1234, 1188, 1143, 1097, 1051, 1006, 960, + 914, 868, 823, 777, 731, 686, 640, 594, 548, 503, 457, 411, + 366, 320, 274, 229, 183, 137, 91, 46, 0, -45, -90, -136, + -182, -228, -273, -319, -365, -410, -456, -502, -547, -593, -639, -685, + -730, -776, -822, -867, -913, -959, -1005, -1050, -1096, -1142, -1187, -1233, + -1279, -1324, -1370, -1416, -1462, -1507, -1553, -1599, -1644, -1690, -1736, -1781, + -1827, -1873, -1919, -1964, -2010, -2056, -2101, -2147, -2193, -2239, -2284, -2330, + -2376, -2421, -2467, -2513, -2558, -2604, -2650, -2696, -2741, -2787, -2833, -2878, + -2924, -2970, -3016, -3061, -3107, -3153, -3198, -3244, -3290, -3335, -3381, -3427, + -3473, -3518, -3564, -3610, -3655, -3701, -3747, -3793, -3838, -3884, -3930, -3975, + -4021, -4067, -4112, -4158, -4204, -4250, -4295, -4341, -4387, -4432, -4478, -4524, + -4569, -4615, -4661, -4707, -4752, -4798, -4844, -4889, -4935, -4981, -5027, -5072, + -5118, -5164, -5209, -5255, -5301, -5346, -5392, -5438, -5484, -5529, -5575, -5621, + -5666, -5712, -5758, -5804}; +static INT16 B_Cb[] = { + -14515, -14402, -14288, -14175, -14062, -13948, -13835, -13721, -13608, -13495, + -13381, -13268, -13154, -13041, -12928, -12814, -12701, -12587, -12474, -12360, + -12247, -12134, -12020, -11907, -11793, -11680, -11567, -11453, -11340, -11226, + -11113, -11000, -10886, -10773, -10659, -10546, -10433, -10319, -10206, -10092, + -9979, -9865, -9752, -9639, -9525, -9412, -9298, -9185, -9072, -8958, + -8845, -8731, -8618, -8505, -8391, -8278, -8164, -8051, -7938, -7824, + -7711, -7597, -7484, -7371, -7257, -7144, -7030, -6917, -6803, -6690, + -6577, -6463, -6350, -6236, -6123, -6010, -5896, -5783, -5669, -5556, + -5443, -5329, -5216, -5102, -4989, -4876, -4762, -4649, -4535, -4422, + -4309, -4195, -4082, -3968, -3855, -3741, -3628, -3515, -3401, -3288, + -3174, -3061, -2948, -2834, -2721, -2607, -2494, -2381, -2267, -2154, + -2040, -1927, -1814, -1700, -1587, -1473, -1360, -1246, -1133, -1020, + -906, -793, -679, -566, -453, -339, -226, -112, 0, 113, + 227, 340, 454, 567, 680, 794, 907, 1021, 1134, 1247, + 1361, 1474, 1588, 1701, 1815, 1928, 2041, 2155, 2268, 2382, + 2495, 2608, 2722, 2835, 2949, 3062, 3175, 3289, 3402, 3516, + 3629, 3742, 3856, 3969, 4083, 4196, 4310, 4423, 4536, 4650, + 4763, 4877, 4990, 5103, 5217, 5330, 5444, 5557, 5670, 5784, + 5897, 6011, 6124, 6237, 6351, 6464, 6578, 6691, 6804, 6918, + 7031, 7145, 7258, 7372, 7485, 7598, 7712, 7825, 7939, 8052, + 8165, 8279, 8392, 8506, 8619, 8732, 8846, 8959, 9073, 9186, + 9299, 9413, 9526, 9640, 9753, 9866, 9980, 10093, 10207, 10320, + 10434, 10547, 10660, 10774, 10887, 11001, 11114, 11227, 11341, 11454, + 11568, 11681, 11794, 11908, 12021, 12135, 12248, 12361, 12475, 12588, + 12702, 12815, 12929, 13042, 13155, 13269, 13382, 13496, 13609, 13722, + 13836, 13949, 14063, 14176, 14289, 14403}; void -ImagingConvertRGB2YCbCr(UINT8* out, const UINT8* in, int pixels) -{ - int x; - UINT8 a; - int r, g, b; - int y, cr, cb; - - for (x = 0; x < pixels; x++, in +=4, out += 4) { - - r = in[0]; - g = in[1]; - b = in[2]; - a = in[3]; - - y = (Y_R[r] + Y_G[g] + Y_B[b]) >> SCALE; - cb = ((Cb_R[r] + Cb_G[g] + Cb_B[b]) >> SCALE) + 128; - cr = ((Cr_R[r] + Cr_G[g] + Cr_B[b]) >> SCALE) + 128; - - out[0] = (UINT8) y; - out[1] = (UINT8) cb; - out[2] = (UINT8) cr; - out[3] = a; - } -} - -void -ImagingConvertYCbCr2RGB(UINT8* out, const UINT8* in, int pixels) -{ +ImagingConvertRGB2YCbCr(UINT8 *out, const UINT8 *in, int pixels) { int x; UINT8 a; int r, g, b; int y, cr, cb; for (x = 0; x < pixels; x++, in += 4, out += 4) { + r = in[0]; + g = in[1]; + b = in[2]; + a = in[3]; + y = (Y_R[r] + Y_G[g] + Y_B[b]) >> SCALE; + cb = ((Cb_R[r] + Cb_G[g] + Cb_B[b]) >> SCALE) + 128; + cr = ((Cr_R[r] + Cr_G[g] + Cr_B[b]) >> SCALE) + 128; + + out[0] = (UINT8)y; + out[1] = (UINT8)cb; + out[2] = (UINT8)cr; + out[3] = a; + } +} + +void +ImagingConvertYCbCr2RGB(UINT8 *out, const UINT8 *in, int pixels) { + int x; + UINT8 a; + int r, g, b; + int y, cr, cb; + + for (x = 0; x < pixels; x++, in += 4, out += 4) { y = in[0]; cb = in[1]; cr = in[2]; a = in[3]; - r = y + (( R_Cr[cr]) >> SCALE); + r = y + ((R_Cr[cr]) >> SCALE); g = y + ((G_Cb[cb] + G_Cr[cr]) >> SCALE); - b = y + ((B_Cb[cb] ) >> SCALE); + b = y + ((B_Cb[cb]) >> SCALE); out[0] = (r <= 0) ? 0 : (r >= 255) ? 255 : r; out[1] = (g <= 0) ? 0 : (g >= 255) ? 255 : g; diff --git a/src/libImaging/Copy.c b/src/libImaging/Copy.c index 5b4899f39..571133e14 100644 --- a/src/libImaging/Copy.c +++ b/src/libImaging/Copy.c @@ -15,18 +15,15 @@ * See the README file for details on usage and redistribution. */ - #include "Imaging.h" - static Imaging -_copy(Imaging imOut, Imaging imIn) -{ +_copy(Imaging imOut, Imaging imIn) { ImagingSectionCookie cookie; int y; if (!imIn) { - return (Imaging) ImagingError_ValueError(NULL); + return (Imaging)ImagingError_ValueError(NULL); } imOut = ImagingNew2Dirty(imIn->mode, imOut, imIn); @@ -50,13 +47,11 @@ _copy(Imaging imOut, Imaging imIn) } Imaging -ImagingCopy(Imaging imIn) -{ +ImagingCopy(Imaging imIn) { return _copy(NULL, imIn); } Imaging -ImagingCopy2(Imaging imOut, Imaging imIn) -{ +ImagingCopy2(Imaging imOut, Imaging imIn) { return _copy(imOut, imIn); } diff --git a/src/libImaging/Crop.c b/src/libImaging/Crop.c index d136edbfc..2425b4cd5 100644 --- a/src/libImaging/Crop.c +++ b/src/libImaging/Crop.c @@ -15,20 +15,17 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - Imaging -ImagingCrop(Imaging imIn, int sx0, int sy0, int sx1, int sy1) -{ +ImagingCrop(Imaging imIn, int sx0, int sy0, int sx1, int sy1) { Imaging imOut; int xsize, ysize; int dx0, dy0, dx1, dy1; INT32 zero = 0; if (!imIn) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } xsize = sx1 - sx0; @@ -48,7 +45,7 @@ ImagingCrop(Imaging imIn, int sx0, int sy0, int sx1, int sy1) ImagingCopyPalette(imOut, imIn); if (sx0 < 0 || sy0 < 0 || sx1 > imIn->xsize || sy1 > imIn->ysize) { - (void) ImagingFill(imOut, &zero); + (void)ImagingFill(imOut, &zero); } dx0 = -sx0; diff --git a/src/libImaging/Dib.c b/src/libImaging/Dib.c index 202b0c9fa..f8a2901b8 100644 --- a/src/libImaging/Dib.c +++ b/src/libImaging/Dib.c @@ -19,21 +19,18 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" #ifdef _WIN32 #include "ImDib.h" - -char* -ImagingGetModeDIB(int size_out[2]) -{ +char * +ImagingGetModeDIB(int size_out[2]) { /* Get device characteristics */ HDC dc; - char* mode; + char *mode; dc = CreateCompatibleDC(NULL); @@ -55,10 +52,8 @@ ImagingGetModeDIB(int size_out[2]) return mode; } - ImagingDIB -ImagingNewDIB(const char *mode, int xsize, int ysize) -{ +ImagingNewDIB(const char *mode, int xsize, int ysize) { /* Create a Windows bitmap */ ImagingDIB dib; @@ -66,23 +61,21 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) int i; /* Check mode */ - if (strcmp(mode, "1") != 0 && strcmp(mode, "L") != 0 && - strcmp(mode, "RGB") != 0) { - return (ImagingDIB) ImagingError_ModeError(); + if (strcmp(mode, "1") != 0 && strcmp(mode, "L") != 0 && strcmp(mode, "RGB") != 0) { + return (ImagingDIB)ImagingError_ModeError(); } /* Create DIB context and info header */ /* malloc check ok, small constant allocation */ - dib = (ImagingDIB) malloc(sizeof(*dib)); + dib = (ImagingDIB)malloc(sizeof(*dib)); if (!dib) { - return (ImagingDIB) ImagingError_MemoryError(); + return (ImagingDIB)ImagingError_MemoryError(); } /* malloc check ok, small constant allocation */ - dib->info = (BITMAPINFO*) malloc(sizeof(BITMAPINFOHEADER) + - 256 * sizeof(RGBQUAD)); + dib->info = (BITMAPINFO *)malloc(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD)); if (!dib->info) { free(dib); - return (ImagingDIB) ImagingError_MemoryError(); + return (ImagingDIB)ImagingError_MemoryError(); } memset(dib->info, 0, sizeof(BITMAPINFOHEADER)); @@ -90,7 +83,7 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) dib->info->bmiHeader.biWidth = xsize; dib->info->bmiHeader.biHeight = ysize; dib->info->bmiHeader.biPlanes = 1; - dib->info->bmiHeader.biBitCount = strlen(mode)*8; + dib->info->bmiHeader.biBitCount = strlen(mode) * 8; dib->info->bmiHeader.biCompression = BI_RGB; /* Create DIB */ @@ -98,15 +91,15 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) if (!dib->dc) { free(dib->info); free(dib); - return (ImagingDIB) ImagingError_MemoryError(); + return (ImagingDIB)ImagingError_MemoryError(); } - dib->bitmap = CreateDIBSection(dib->dc, dib->info, DIB_RGB_COLORS, - &dib->bits, NULL, 0); + dib->bitmap = + CreateDIBSection(dib->dc, dib->info, DIB_RGB_COLORS, &dib->bits, NULL, 0); if (!dib->bitmap) { free(dib->info); free(dib); - return (ImagingDIB) ImagingError_MemoryError(); + return (ImagingDIB)ImagingError_MemoryError(); } strcpy(dib->mode, mode); @@ -117,7 +110,7 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) dib->linesize = (xsize * dib->pixelsize + 3) & -4; if (dib->pixelsize == 1) { - dib->pack = dib->unpack = (ImagingShuffler) memcpy; + dib->pack = dib->unpack = (ImagingShuffler)memcpy; } else { dib->pack = ImagingPackBGR; dib->unpack = ImagingPackBGR; @@ -131,9 +124,7 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) /* Bind a palette to it as well (only required for 8-bit DIBs) */ if (dib->pixelsize == 1) { for (i = 0; i < 256; i++) { - palette[i].rgbRed = - palette[i].rgbGreen = - palette[i].rgbBlue = i; + palette[i].rgbRed = palette[i].rgbGreen = palette[i].rgbBlue = i; palette[i].rgbReserved = 0; } SetDIBColorTable(dib->dc, 0, 256, palette); @@ -141,9 +132,8 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) /* Create an associated palette (for 8-bit displays only) */ if (strcmp(ImagingGetModeDIB(NULL), "P") == 0) { - - char palbuf[sizeof(LOGPALETTE)+256*sizeof(PALETTEENTRY)]; - LPLOGPALETTE pal = (LPLOGPALETTE) palbuf; + char palbuf[sizeof(LOGPALETTE) + 256 * sizeof(PALETTEENTRY)]; + LPLOGPALETTE pal = (LPLOGPALETTE)palbuf; int i, r, g, b; /* Load system palette */ @@ -152,7 +142,6 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) GetSystemPaletteEntries(dib->dc, 0, 256, pal->palPalEntry); if (strcmp(mode, "L") == 0) { - /* Greyscale DIB. Fill all 236 slots with a greyscale ramp * (this is usually overkill on Windows since VGA only offers * 6 bits greyscale resolution). Ignore the slots already @@ -160,16 +149,14 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) i = 10; for (r = 0; r < 236; r++) { - pal->palPalEntry[i].peRed = - pal->palPalEntry[i].peGreen = - pal->palPalEntry[i].peBlue = i; + pal->palPalEntry[i].peRed = pal->palPalEntry[i].peGreen = + pal->palPalEntry[i].peBlue = i; i++; } dib->palette = CreatePalette(pal); } else if (strcmp(mode, "RGB") == 0) { - #ifdef CUBE216 /* Colour DIB. Create a 6x6x6 colour cube (216 entries) and @@ -187,11 +174,10 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) } } } - for (r = 1; r < 22-1; r++) { + for (r = 1; r < 22 - 1; r++) { /* Black and white are already provided by the cube. */ - pal->palPalEntry[i].peRed = - pal->palPalEntry[i].peGreen = - pal->palPalEntry[i].peBlue = r * 255 / (22-1); + pal->palPalEntry[i].peRed = pal->palPalEntry[i].peGreen = + pal->palPalEntry[i].peBlue = r * 255 / (22 - 1); i++; } @@ -214,76 +200,91 @@ ImagingNewDIB(const char *mode, int xsize, int ysize) #endif dib->palette = CreatePalette(pal); - } - } return dib; } void -ImagingPasteDIB(ImagingDIB dib, Imaging im, int xy[4]) -{ +ImagingPasteDIB(ImagingDIB dib, Imaging im, int xy[4]) { /* Paste image data into a bitmap */ /* FIXME: check size! */ int y; for (y = 0; y < im->ysize; y++) { - dib->pack(dib->bits + dib->linesize*(dib->ysize-(xy[1]+y)-1) + - xy[0]*dib->pixelsize, im->image[y], im->xsize); + dib->pack( + dib->bits + dib->linesize * (dib->ysize - (xy[1] + y) - 1) + + xy[0] * dib->pixelsize, + im->image[y], + im->xsize); } - } void -ImagingExposeDIB(ImagingDIB dib, void *dc) -{ +ImagingExposeDIB(ImagingDIB dib, void *dc) { /* Copy bitmap to display */ if (dib->palette != 0) { - SelectPalette((HDC) dc, dib->palette, FALSE); + SelectPalette((HDC)dc, dib->palette, FALSE); } - BitBlt((HDC) dc, 0, 0, dib->xsize, dib->ysize, dib->dc, 0, 0, SRCCOPY); + BitBlt((HDC)dc, 0, 0, dib->xsize, dib->ysize, dib->dc, 0, 0, SRCCOPY); } void -ImagingDrawDIB(ImagingDIB dib, void *dc, int dst[4], int src[4]) -{ +ImagingDrawDIB(ImagingDIB dib, void *dc, int dst[4], int src[4]) { /* Copy bitmap to printer/display */ - if (GetDeviceCaps((HDC) dc, RASTERCAPS) & RC_STRETCHDIB) { + if (GetDeviceCaps((HDC)dc, RASTERCAPS) & RC_STRETCHDIB) { /* stretchdib (printers) */ - StretchDIBits((HDC) dc, dst[0], dst[1], dst[2]-dst[0], dst[3]-dst[1], - src[0], src[1], src[2]-src[0], src[3]-src[1], dib->bits, - dib->info, DIB_RGB_COLORS, SRCCOPY); + StretchDIBits( + (HDC)dc, + dst[0], + dst[1], + dst[2] - dst[0], + dst[3] - dst[1], + src[0], + src[1], + src[2] - src[0], + src[3] - src[1], + dib->bits, + dib->info, + DIB_RGB_COLORS, + SRCCOPY); } else { /* stretchblt (displays) */ if (dib->palette != 0) { - SelectPalette((HDC) dc, dib->palette, FALSE); + SelectPalette((HDC)dc, dib->palette, FALSE); } - StretchBlt((HDC) dc, dst[0], dst[1], dst[2]-dst[0], dst[3]-dst[1], - dib->dc, src[0], src[1], src[2]-src[0], src[3]-src[1], - SRCCOPY); + StretchBlt( + (HDC)dc, + dst[0], + dst[1], + dst[2] - dst[0], + dst[3] - dst[1], + dib->dc, + src[0], + src[1], + src[2] - src[0], + src[3] - src[1], + SRCCOPY); } } int -ImagingQueryPaletteDIB(ImagingDIB dib, void *dc) -{ +ImagingQueryPaletteDIB(ImagingDIB dib, void *dc) { /* Install bitmap palette */ int n; if (dib->palette != 0) { - /* Realize associated palette */ - HPALETTE now = SelectPalette((HDC) dc, dib->palette, FALSE); - n = RealizePalette((HDC) dc); + HPALETTE now = SelectPalette((HDC)dc, dib->palette, FALSE); + n = RealizePalette((HDC)dc); /* Restore palette */ - SelectPalette((HDC) dc, now, FALSE); + SelectPalette((HDC)dc, now, FALSE); } else { n = 0; @@ -293,8 +294,7 @@ ImagingQueryPaletteDIB(ImagingDIB dib, void *dc) } void -ImagingDeleteDIB(ImagingDIB dib) -{ +ImagingDeleteDIB(ImagingDIB dib) { /* Clean up */ if (dib->palette) { diff --git a/src/libImaging/Draw.c b/src/libImaging/Draw.c index 339e1cd35..8471ffb17 100644 --- a/src/libImaging/Draw.c +++ b/src/libImaging/Draw.c @@ -37,17 +37,17 @@ #include #include -#define CEIL(v) (int) ceil(v) -#define FLOOR(v) ((v) >= 0.0 ? (int) (v) : (int) floor(v)) +#define CEIL(v) (int)ceil(v) +#define FLOOR(v) ((v) >= 0.0 ? (int)(v) : (int)floor(v)) -#define INK8(ink) (*(UINT8*)ink) +#define INK8(ink) (*(UINT8 *)ink) /* * Rounds around zero (up=away from zero, down=towards zero) * This guarantees that ROUND_UP|DOWN(f) == -ROUND_UP|DOWN(-f) */ -#define ROUND_UP(f) ((int) ((f) >= 0.0 ? floor((f) + 0.5F) : -floor(fabs(f) + 0.5F))) -#define ROUND_DOWN(f) ((int) ((f) >= 0.0 ? ceil((f) - 0.5F) : -ceil(fabs(f) - 0.5F))) +#define ROUND_UP(f) ((int)((f) >= 0.0 ? floor((f) + 0.5F) : -floor(fabs(f) + 0.5F))) +#define ROUND_DOWN(f) ((int)((f) >= 0.0 ? ceil((f)-0.5F) : -ceil(fabs(f) - 0.5F))) /* -------------------------------------------------------------------- */ /* Primitives */ @@ -65,34 +65,31 @@ typedef struct { typedef void (*hline_handler)(Imaging, int, int, int, int); static inline void -point8(Imaging im, int x, int y, int ink) -{ +point8(Imaging im, int x, int y, int ink) { if (x >= 0 && x < im->xsize && y >= 0 && y < im->ysize) { if (strncmp(im->mode, "I;16", 4) == 0) { - im->image8[y][x*2] = (UINT8) ink; - im->image8[y][x*2+1] = (UINT8) ink; + im->image8[y][x * 2] = (UINT8)ink; + im->image8[y][x * 2 + 1] = (UINT8)ink; } else { - im->image8[y][x] = (UINT8) ink; + im->image8[y][x] = (UINT8)ink; } } } static inline void -point32(Imaging im, int x, int y, int ink) -{ +point32(Imaging im, int x, int y, int ink) { if (x >= 0 && x < im->xsize && y >= 0 && y < im->ysize) { im->image32[y][x] = ink; } } static inline void -point32rgba(Imaging im, int x, int y, int ink) -{ +point32rgba(Imaging im, int x, int y, int ink) { unsigned int tmp1; if (x >= 0 && x < im->xsize && y >= 0 && y < im->ysize) { - UINT8* out = (UINT8*) im->image[y]+x*4; - UINT8* in = (UINT8*) &ink; + UINT8 *out = (UINT8 *)im->image[y] + x * 4; + UINT8 *in = (UINT8 *)&ink; out[0] = BLEND(in[3], out[0], in[0], tmp1); out[1] = BLEND(in[3], out[1], in[1], tmp1); out[2] = BLEND(in[3], out[2], in[2], tmp1); @@ -100,8 +97,7 @@ point32rgba(Imaging im, int x, int y, int ink) } static inline void -hline8(Imaging im, int x0, int y0, int x1, int ink) -{ +hline8(Imaging im, int x0, int y0, int x1, int ink) { int tmp, pixelwidth; if (y0 >= 0 && y0 < im->ysize) { @@ -116,21 +112,22 @@ hline8(Imaging im, int x0, int y0, int x1, int ink) if (x1 < 0) { return; } else if (x1 >= im->xsize) { - x1 = im->xsize-1; + x1 = im->xsize - 1; } if (x0 <= x1) { pixelwidth = strncmp(im->mode, "I;16", 4) == 0 ? 2 : 1; - memset(im->image8[y0] + x0 * pixelwidth, (UINT8) ink, - (x1 - x0 + 1) * pixelwidth); + memset( + im->image8[y0] + x0 * pixelwidth, + (UINT8)ink, + (x1 - x0 + 1) * pixelwidth); } } } static inline void -hline32(Imaging im, int x0, int y0, int x1, int ink) -{ +hline32(Imaging im, int x0, int y0, int x1, int ink) { int tmp; - INT32* p; + INT32 *p; if (y0 >= 0 && y0 < im->ysize) { if (x0 > x1) { @@ -144,7 +141,7 @@ hline32(Imaging im, int x0, int y0, int x1, int ink) if (x1 < 0) { return; } else if (x1 >= im->xsize) { - x1 = im->xsize-1; + x1 = im->xsize - 1; } p = im->image32[y0]; while (x0 <= x1) { @@ -154,8 +151,7 @@ hline32(Imaging im, int x0, int y0, int x1, int ink) } static inline void -hline32rgba(Imaging im, int x0, int y0, int x1, int ink) -{ +hline32rgba(Imaging im, int x0, int y0, int x1, int ink) { int tmp; unsigned int tmp1; @@ -171,36 +167,36 @@ hline32rgba(Imaging im, int x0, int y0, int x1, int ink) if (x1 < 0) { return; } else if (x1 >= im->xsize) { - x1 = im->xsize-1; + x1 = im->xsize - 1; } if (x0 <= x1) { - UINT8* out = (UINT8*) im->image[y0]+x0*4; - UINT8* in = (UINT8*) &ink; + UINT8 *out = (UINT8 *)im->image[y0] + x0 * 4; + UINT8 *in = (UINT8 *)&ink; while (x0 <= x1) { out[0] = BLEND(in[3], out[0], in[0], tmp1); out[1] = BLEND(in[3], out[1], in[1], tmp1); out[2] = BLEND(in[3], out[2], in[2], tmp1); - x0++; out += 4; + x0++; + out += 4; } } } } static inline void -line8(Imaging im, int x0, int y0, int x1, int y1, int ink) -{ +line8(Imaging im, int x0, int y0, int x1, int y1, int ink) { int i, n, e; int dx, dy; int xs, ys; /* normalize coordinates */ - dx = x1-x0; + dx = x1 - x0; if (dx < 0) { dx = -dx, xs = -1; } else { xs = 1; } - dy = y1-y0; + dy = y1 - y0; if (dy < 0) { dy = -dy, ys = -1; } else { @@ -210,7 +206,6 @@ line8(Imaging im, int x0, int y0, int x1, int y1, int ink) n = (dx > dy) ? dx : dy; if (dx == 0) { - /* vertical */ for (i = 0; i < dy; i++) { point8(im, x0, y0, ink); @@ -218,7 +213,6 @@ line8(Imaging im, int x0, int y0, int x1, int y1, int ink) } } else if (dy == 0) { - /* horizontal */ for (i = 0; i < dx; i++) { point8(im, x0, y0, ink); @@ -226,7 +220,6 @@ line8(Imaging im, int x0, int y0, int x1, int y1, int ink) } } else if (dx > dy) { - /* bresenham, horizontal slope */ n = dx; dy += dy; @@ -244,7 +237,6 @@ line8(Imaging im, int x0, int y0, int x1, int y1, int ink) } } else { - /* bresenham, vertical slope */ n = dy; dx += dx; @@ -260,25 +252,23 @@ line8(Imaging im, int x0, int y0, int x1, int y1, int ink) e += dx; y0 += ys; } - } } static inline void -line32(Imaging im, int x0, int y0, int x1, int y1, int ink) -{ +line32(Imaging im, int x0, int y0, int x1, int y1, int ink) { int i, n, e; int dx, dy; int xs, ys; /* normalize coordinates */ - dx = x1-x0; + dx = x1 - x0; if (dx < 0) { dx = -dx, xs = -1; } else { xs = 1; } - dy = y1-y0; + dy = y1 - y0; if (dy < 0) { dy = -dy, ys = -1; } else { @@ -288,7 +278,6 @@ line32(Imaging im, int x0, int y0, int x1, int y1, int ink) n = (dx > dy) ? dx : dy; if (dx == 0) { - /* vertical */ for (i = 0; i < dy; i++) { point32(im, x0, y0, ink); @@ -296,7 +285,6 @@ line32(Imaging im, int x0, int y0, int x1, int y1, int ink) } } else if (dy == 0) { - /* horizontal */ for (i = 0; i < dx; i++) { point32(im, x0, y0, ink); @@ -304,7 +292,6 @@ line32(Imaging im, int x0, int y0, int x1, int y1, int ink) } } else if (dx > dy) { - /* bresenham, horizontal slope */ n = dx; dy += dy; @@ -322,7 +309,6 @@ line32(Imaging im, int x0, int y0, int x1, int y1, int ink) } } else { - /* bresenham, vertical slope */ n = dy; dx += dx; @@ -338,25 +324,23 @@ line32(Imaging im, int x0, int y0, int x1, int y1, int ink) e += dx; y0 += ys; } - } } static inline void -line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink) -{ +line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink) { int i, n, e; int dx, dy; int xs, ys; /* normalize coordinates */ - dx = x1-x0; + dx = x1 - x0; if (dx < 0) { dx = -dx, xs = -1; } else { xs = 1; } - dy = y1-y0; + dy = y1 - y0; if (dy < 0) { dy = -dy, ys = -1; } else { @@ -366,7 +350,6 @@ line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink) n = (dx > dy) ? dx : dy; if (dx == 0) { - /* vertical */ for (i = 0; i < dy; i++) { point32rgba(im, x0, y0, ink); @@ -374,7 +357,6 @@ line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink) } } else if (dy == 0) { - /* horizontal */ for (i = 0; i < dx; i++) { point32rgba(im, x0, y0, ink); @@ -382,7 +364,6 @@ line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink) } } else if (dx > dy) { - /* bresenham, horizontal slope */ n = dx; dy += dy; @@ -400,7 +381,6 @@ line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink) } } else { - /* bresenham, vertical slope */ n = dy; dx += dx; @@ -416,14 +396,12 @@ line32rgba(Imaging im, int x0, int y0, int x1, int y1, int ink) e += dx; y0 += ys; } - } } static int -x_cmp(const void *x0, const void *x1) -{ - float diff = *((float*)x0) - *((float*)x1); +x_cmp(const void *x0, const void *x1) { + float diff = *((float *)x0) - *((float *)x1); if (diff < 0) { return -1; } else if (diff > 0) { @@ -433,10 +411,9 @@ x_cmp(const void *x0, const void *x1) } } - static void -draw_horizontal_lines(Imaging im, int n, Edge *e, int ink, int *x_pos, int y, hline_handler hline) -{ +draw_horizontal_lines( + Imaging im, int n, Edge *e, int ink, int *x_pos, int y, hline_handler hline) { int i; for (i = 0; i < n; i++) { if (e[i].ymin == y && e[i].ymin == e[i].ymax) { @@ -458,7 +435,7 @@ draw_horizontal_lines(Imaging im, int n, Edge *e, int ink, int *x_pos, int y, hl } (*hline)(im, xmin, e[i].ymin, xmax, ink); - *x_pos = xmax+1; + *x_pos = xmax + 1; } } } @@ -467,12 +444,9 @@ draw_horizontal_lines(Imaging im, int n, Edge *e, int ink, int *x_pos, int y, hl * Filled polygon draw function using scan line algorithm. */ static inline int -polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, - hline_handler hline) -{ - - Edge** edge_table; - float* xx; +polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, hline_handler hline) { + Edge **edge_table; + float *xx; int edge_count = 0; int ymin = im->ysize - 1; int ymax = 0; @@ -484,7 +458,7 @@ polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, /* Initialize the edge table and find polygon boundaries */ /* malloc check ok, using calloc */ - edge_table = calloc(n, sizeof(Edge*)); + edge_table = calloc(n, sizeof(Edge *)); if (!edge_table) { return -1; } @@ -519,7 +493,7 @@ polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, int j = 0; int x_pos = 0; for (i = 0; i < edge_count; i++) { - Edge* current = edge_table[i]; + Edge *current = edge_table[i]; if (ymin >= current->ymin && ymin <= current->ymax) { xx[j++] = (ymin - current->y0) * current->dx + current->x0; } @@ -542,7 +516,7 @@ polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, continue; } - int x_start = ROUND_UP(xx[i-1]); + int x_start = ROUND_UP(xx[i - 1]); if (x_pos > x_start) { // Line would be partway through x_pos, so increase the starting point x_start = x_pos; @@ -552,7 +526,7 @@ polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, } } (*hline)(im, x_start, ymin, x_end, ink); - x_pos = x_end+1; + x_pos = x_end + 1; } draw_horizontal_lines(im, n, e, ink, &x_pos, ymin, hline); } @@ -563,26 +537,22 @@ polygon_generic(Imaging im, int n, Edge *e, int ink, int eofill, } static inline int -polygon8(Imaging im, int n, Edge *e, int ink, int eofill) -{ +polygon8(Imaging im, int n, Edge *e, int ink, int eofill) { return polygon_generic(im, n, e, ink, eofill, hline8); } static inline int -polygon32(Imaging im, int n, Edge *e, int ink, int eofill) -{ +polygon32(Imaging im, int n, Edge *e, int ink, int eofill) { return polygon_generic(im, n, e, ink, eofill, hline32); } static inline int -polygon32rgba(Imaging im, int n, Edge *e, int ink, int eofill) -{ +polygon32rgba(Imaging im, int n, Edge *e, int ink, int eofill) { return polygon_generic(im, n, e, ink, eofill, hline32rgba); } static inline void -add_edge(Edge *e, int x0, int y0, int x1, int y1) -{ +add_edge(Edge *e, int x0, int y0, int x1, int y1) { /* printf("edge %d %d %d %d\n", x0, y0, x1, y1); */ if (x0 <= x1) { @@ -601,7 +571,7 @@ add_edge(Edge *e, int x0, int y0, int x1, int y1) e->d = 0; e->dx = 0.0; } else { - e->dx = ((float)(x1-x0)) / (y1-y0); + e->dx = ((float)(x1 - x0)) / (y1 - y0); if (y0 == e->ymin) { e->d = 1; } else { @@ -620,27 +590,26 @@ typedef struct { int (*polygon)(Imaging im, int n, Edge *e, int ink, int eofill); } DRAW; -DRAW draw8 = { point8, hline8, line8, polygon8 }; -DRAW draw32 = { point32, hline32, line32, polygon32 }; -DRAW draw32rgba = { point32rgba, hline32rgba, line32rgba, polygon32rgba }; +DRAW draw8 = {point8, hline8, line8, polygon8}; +DRAW draw32 = {point32, hline32, line32, polygon32}; +DRAW draw32rgba = {point32rgba, hline32rgba, line32rgba, polygon32rgba}; /* -------------------------------------------------------------------- */ /* Interface */ /* -------------------------------------------------------------------- */ -#define DRAWINIT()\ - if (im->image8) {\ - draw = &draw8;\ - ink = INK8(ink_);\ - } else {\ - draw = (op) ? &draw32rgba : &draw32; \ - memcpy(&ink, ink_, sizeof(ink)); \ +#define DRAWINIT() \ + if (im->image8) { \ + draw = &draw8; \ + ink = INK8(ink_); \ + } else { \ + draw = (op) ? &draw32rgba : &draw32; \ + memcpy(&ink, ink_, sizeof(ink)); \ } int -ImagingDrawPoint(Imaging im, int x0, int y0, const void* ink_, int op) -{ - DRAW* draw; +ImagingDrawPoint(Imaging im, int x0, int y0, const void *ink_, int op) { + DRAW *draw; INT32 ink; DRAWINIT(); @@ -651,10 +620,8 @@ ImagingDrawPoint(Imaging im, int x0, int y0, const void* ink_, int op) } int -ImagingDrawLine(Imaging im, int x0, int y0, int x1, int y1, const void* ink_, - int op) -{ - DRAW* draw; +ImagingDrawLine(Imaging im, int x0, int y0, int x1, int y1, const void *ink_, int op) { + DRAW *draw; INT32 ink; DRAWINIT(); @@ -665,10 +632,9 @@ ImagingDrawLine(Imaging im, int x0, int y0, int x1, int y1, const void* ink_, } int -ImagingDrawWideLine(Imaging im, int x0, int y0, int x1, int y1, - const void* ink_, int width, int op) -{ - DRAW* draw; +ImagingDrawWideLine( + Imaging im, int x0, int y0, int x1, int y1, const void *ink_, int width, int op) { + DRAW *draw; INT32 ink; int dx, dy; double big_hypotenuse, small_hypotenuse, ratio_max, ratio_min; @@ -677,8 +643,8 @@ ImagingDrawWideLine(Imaging im, int x0, int y0, int x1, int y1, DRAWINIT(); - dx = x1-x0; - dy = y1-y0; + dx = x1 - x0; + dy = y1 - y0; if (dx == 0 && dy == 0) { draw->point(im, x0, y0, ink); return 0; @@ -698,13 +664,12 @@ ImagingDrawWideLine(Imaging im, int x0, int y0, int x1, int y1, {x0 - dxmin, y0 + dymax}, {x1 - dxmin, y1 + dymax}, {x1 + dxmax, y1 - dymin}, - {x0 + dxmax, y0 - dymin} - }; + {x0 + dxmax, y0 - dymin}}; - add_edge(e+0, vertices[0][0], vertices[0][1], vertices[1][0], vertices[1][1]); - add_edge(e+1, vertices[1][0], vertices[1][1], vertices[2][0], vertices[2][1]); - add_edge(e+2, vertices[2][0], vertices[2][1], vertices[3][0], vertices[3][1]); - add_edge(e+3, vertices[3][0], vertices[3][1], vertices[0][0], vertices[0][1]); + add_edge(e + 0, vertices[0][0], vertices[0][1], vertices[1][0], vertices[1][1]); + add_edge(e + 1, vertices[1][0], vertices[1][1], vertices[2][0], vertices[2][1]); + add_edge(e + 2, vertices[2][0], vertices[2][1], vertices[3][0], vertices[3][1]); + add_edge(e + 3, vertices[3][0], vertices[3][1], vertices[0][0], vertices[0][1]); draw->polygon(im, 4, e, ink, 0); } @@ -712,13 +677,20 @@ ImagingDrawWideLine(Imaging im, int x0, int y0, int x1, int y1, } int -ImagingDrawRectangle(Imaging im, int x0, int y0, int x1, int y1, - const void* ink_, int fill, int width, int op) -{ +ImagingDrawRectangle( + Imaging im, + int x0, + int y0, + int x1, + int y1, + const void *ink_, + int fill, + int width, + int op) { int i; int y; int tmp; - DRAW* draw; + DRAW *draw; INT32 ink; DRAWINIT(); @@ -728,7 +700,6 @@ ImagingDrawRectangle(Imaging im, int x0, int y0, int x1, int y1, } if (fill) { - if (y0 < 0) { y0 = 0; } else if (y0 >= im->ysize) { @@ -751,10 +722,10 @@ ImagingDrawRectangle(Imaging im, int x0, int y0, int x1, int y1, width = 1; } for (i = 0; i < width; i++) { - draw->hline(im, x0, y0+i, x1, ink); - draw->hline(im, x0, y1-i, x1, ink); - draw->line(im, x1-i, y0, x1-i, y1, ink); - draw->line(im, x0+i, y1, x0+i, y0, ink); + draw->hline(im, x0, y0 + i, x1, ink); + draw->hline(im, x0, y1 - i, x1, ink); + draw->line(im, x1 - i, y0, x1 - i, y1, ink); + draw->line(im, x0 + i, y1, x0 + i, y0, ink); } } @@ -762,11 +733,9 @@ ImagingDrawRectangle(Imaging im, int x0, int y0, int x1, int y1, } int -ImagingDrawPolygon(Imaging im, int count, int* xy, const void* ink_, - int fill, int op) -{ +ImagingDrawPolygon(Imaging im, int count, int *xy, const void *ink_, int fill, int op) { int i, n; - DRAW* draw; + DRAW *draw; INT32 ink; if (count <= 0) { @@ -776,44 +745,37 @@ ImagingDrawPolygon(Imaging im, int count, int* xy, const void* ink_, DRAWINIT(); if (fill) { - /* Build edge list */ /* malloc check ok, using calloc */ - Edge* e = calloc(count, sizeof(Edge)); + Edge *e = calloc(count, sizeof(Edge)); if (!e) { - (void) ImagingError_MemoryError(); + (void)ImagingError_MemoryError(); return -1; } - for (i = n = 0; i < count-1; i++) { - add_edge(&e[n++], xy[i+i], xy[i+i+1], xy[i+i+2], xy[i+i+3]); + for (i = n = 0; i < count - 1; i++) { + add_edge(&e[n++], xy[i + i], xy[i + i + 1], xy[i + i + 2], xy[i + i + 3]); } - if (xy[i+i] != xy[0] || xy[i+i+1] != xy[1]) { - add_edge(&e[n++], xy[i+i], xy[i+i+1], xy[0], xy[1]); + if (xy[i + i] != xy[0] || xy[i + i + 1] != xy[1]) { + add_edge(&e[n++], xy[i + i], xy[i + i + 1], xy[0], xy[1]); } draw->polygon(im, n, e, ink, 0); free(e); } else { - /* Outline */ - for (i = 0; i < count-1; i++) { - draw->line(im, xy[i+i], xy[i+i+1], xy[i+i+2], xy[i+i+3], ink); + for (i = 0; i < count - 1; i++) { + draw->line(im, xy[i + i], xy[i + i + 1], xy[i + i + 2], xy[i + i + 3], ink); } - draw->line(im, xy[i+i], xy[i+i+1], xy[0], xy[1], ink); - + draw->line(im, xy[i + i], xy[i + i + 1], xy[0], xy[1], ink); } return 0; } int -ImagingDrawBitmap(Imaging im, int x0, int y0, Imaging bitmap, const void* ink, - int op) -{ +ImagingDrawBitmap(Imaging im, int x0, int y0, Imaging bitmap, const void *ink, int op) { return ImagingFill2( - im, ink, bitmap, - x0, y0, x0 + bitmap->xsize, y0 + bitmap->ysize - ); + im, ink, bitmap, x0, y0, x0 + bitmap->xsize, y0 + bitmap->ysize); } /* -------------------------------------------------------------------- */ @@ -830,7 +792,8 @@ typedef struct { int8_t finished; } quarter_state; -void quarter_init(quarter_state* s, int32_t a, int32_t b) { +void +quarter_init(quarter_state *s, int32_t a, int32_t b) { if (a < 0 || b < 0) { s->finished = 1; } else { @@ -849,11 +812,13 @@ void quarter_init(quarter_state* s, int32_t a, int32_t b) { // deviation of the point from ellipse curve, basically a substitution // of the point into the ellipse equation -int64_t quarter_delta(quarter_state* s, int64_t x, int64_t y) { +int64_t +quarter_delta(quarter_state *s, int64_t x, int64_t y) { return llabs(s->a2 * y * y + s->b2 * x * x - s->a2b2); } -int8_t quarter_next(quarter_state* s, int32_t* ret_x, int32_t* ret_y) { +int8_t +quarter_next(quarter_state *s, int32_t *ret_x, int32_t *ret_y) { if (s->finished) { return -1; } @@ -903,7 +868,8 @@ typedef struct { int8_t leftmost; } ellipse_state; -void ellipse_init(ellipse_state* s, int32_t a, int32_t b, int32_t w) { +void +ellipse_init(ellipse_state *s, int32_t a, int32_t b, int32_t w) { s->bufcnt = 0; s->leftmost = a % 2; quarter_init(&s->st_o, a, b); @@ -916,7 +882,8 @@ void ellipse_init(ellipse_state* s, int32_t a, int32_t b, int32_t w) { } } -int8_t ellipse_next(ellipse_state* s, int32_t* ret_x0, int32_t* ret_y, int32_t* ret_x1) { +int8_t +ellipse_next(ellipse_state *s, int32_t *ret_x0, int32_t *ret_y, int32_t *ret_x1) { if (s->bufcnt == 0) { if (s->finished) { return -1; @@ -974,470 +941,503 @@ int8_t ellipse_next(ellipse_state* s, int32_t* ret_x0, int32_t* ret_y, int32_t* // of resulting disjoint clipped segments organized into a sorted linked list // of their end points. typedef enum { - CT_AND, // intersection - CT_OR, // union - CT_CLIP // half-plane clipping + CT_AND, // intersection + CT_OR, // union + CT_CLIP // half-plane clipping } clip_type; typedef struct clip_node { - clip_type type; - double a, b, c; // half-plane coeffs, only used in clipping nodes - struct clip_node* l; // child pointers, are only non-NULL in combining nodes - struct clip_node* r; + clip_type type; + double a, b, c; // half-plane coeffs, only used in clipping nodes + struct clip_node *l; // child pointers, are only non-NULL in combining nodes + struct clip_node *r; } clip_node; // Linked list for the ends of the clipped horizontal segments. // Since the segment is always horizontal, we don't need to store Y coordinate. typedef struct event_list { - int32_t x; - int8_t type; // used internally, 1 for the left end (smaller X), -1 for the - // right end; pointless in output since the output segments - // are disjoint, therefore the types would always come in pairs - // and interchange (1 -1 1 -1 ...) - struct event_list* next; + int32_t x; + int8_t type; // used internally, 1 for the left end (smaller X), -1 for the + // right end; pointless in output since the output segments + // are disjoint, therefore the types would always come in pairs + // and interchange (1 -1 1 -1 ...) + struct event_list *next; } event_list; // Mirrors all the clipping nodes of the tree relative to the y = x line. -void clip_tree_transpose(clip_node* root) { - if (root != NULL) { - if (root->type == CT_CLIP) { - double t = root->a; - root->a = root->b; - root->b = t; +void +clip_tree_transpose(clip_node *root) { + if (root != NULL) { + if (root->type == CT_CLIP) { + double t = root->a; + root->a = root->b; + root->b = t; + } + clip_tree_transpose(root->l); + clip_tree_transpose(root->r); } - clip_tree_transpose(root->l); - clip_tree_transpose(root->r); - } } // Outputs a sequence of open-close events (types -1 and 1) for // non-intersecting segments sorted by X coordinate. // Combining nodes (AND, OR) may also accept sequences for intersecting // segments, i.e. something like correct bracket sequences. -int clip_tree_do_clip(clip_node* root, int32_t x0, int32_t y, int32_t x1, event_list** ret) { - if (root == NULL) { - event_list* start = malloc(sizeof(event_list)); - if (!start) { - ImagingError_MemoryError(); - return -1; +int +clip_tree_do_clip( + clip_node *root, int32_t x0, int32_t y, int32_t x1, event_list **ret) { + if (root == NULL) { + event_list *start = malloc(sizeof(event_list)); + if (!start) { + ImagingError_MemoryError(); + return -1; + } + event_list *end = malloc(sizeof(event_list)); + if (!end) { + free(start); + ImagingError_MemoryError(); + return -1; + } + start->x = x0; + start->type = 1; + start->next = end; + end->x = x1; + end->type = -1; + end->next = NULL; + *ret = start; + return 0; } - event_list* end = malloc(sizeof(event_list)); - if (!end) { - free(start); - ImagingError_MemoryError(); - return -1; + if (root->type == CT_CLIP) { + double eps = 1e-9; + double A = root->a; + double B = root->b; + double C = root->c; + if (fabs(A) < eps) { + if (B * y + C < -eps) { + x0 = 1; + x1 = 0; + } + } else { + // X of intersection + double ix = -(B * y + C) / A; + if (A * x0 + B * y + C < eps) { + x0 = lround(fmax(x0, ix)); + } + if (A * x1 + B * y + C < eps) { + x1 = lround(fmin(x1, ix)); + } + } + if (x0 <= x1) { + event_list *start = malloc(sizeof(event_list)); + if (!start) { + ImagingError_MemoryError(); + return -1; + } + event_list *end = malloc(sizeof(event_list)); + if (!end) { + free(start); + ImagingError_MemoryError(); + return -1; + } + start->x = x0; + start->type = 1; + start->next = end; + end->x = x1; + end->type = -1; + end->next = NULL; + *ret = start; + } else { + *ret = NULL; + } + return 0; } - start->x = x0; - start->type = 1; - start->next = end; - end->x = x1; - end->type = -1; - end->next = NULL; - *ret = start; - return 0; - } - if (root->type == CT_CLIP) { - double eps = 1e-9; - double A = root->a; - double B = root->b; - double C = root->c; - if (fabs(A) < eps) { - if (B * y + C < -eps) { - x0 = 1; - x1 = 0; - } - } else { - // X of intersection - double ix = - (B * y + C) / A; - if (A * x0 + B * y + C < eps) { - x0 = lround(fmax(x0, ix)); - } - if (A * x1 + B * y + C < eps) { - x1 = lround(fmin(x1, ix)); - } - } - if (x0 <= x1) { - event_list* start = malloc(sizeof(event_list)); - if (!start) { - ImagingError_MemoryError(); - return -1; - } - event_list* end = malloc(sizeof(event_list)); - if (!end) { - free(start); - ImagingError_MemoryError(); - return -1; - } - start->x = x0; - start->type = 1; - start->next = end; - end->x = x1; - end->type = -1; - end->next = NULL; - *ret = start; - } else { - *ret = NULL; - } - return 0; - } - if (root->type == CT_OR || root->type == CT_AND) { - event_list* l1; - event_list* l2; - if (clip_tree_do_clip(root->l, x0, y, x1, &l1) < 0) { - return -1; - } - if (clip_tree_do_clip(root->r, x0, y, x1, &l2) < 0) { - while (l1) { - l2 = l1->next; - free(l1); - l1 = l2; - } - return -1; + if (root->type == CT_OR || root->type == CT_AND) { + event_list *l1; + event_list *l2; + if (clip_tree_do_clip(root->l, x0, y, x1, &l1) < 0) { + return -1; + } + if (clip_tree_do_clip(root->r, x0, y, x1, &l2) < 0) { + while (l1) { + l2 = l1->next; + free(l1); + l1 = l2; + } + return -1; + } + *ret = NULL; + event_list *tail = NULL; + int32_t k1 = 0; + int32_t k2 = 0; + while (l1 != NULL || l2 != NULL) { + event_list *t; + if (l2 == NULL || + (l1 != NULL && + (l1->x < l2->x || (l1->x == l2->x && l1->type > l2->type)))) { + t = l1; + k1 += t->type; + assert(k1 >= 0); + l1 = l1->next; + } else { + t = l2; + k2 += t->type; + assert(k2 >= 0); + l2 = l2->next; + } + t->next = NULL; + if ((root->type == CT_OR && + ((t->type == 1 && (tail == NULL || tail->type == -1)) || + (t->type == -1 && k1 == 0 && k2 == 0))) || + (root->type == CT_AND && + ((t->type == 1 && (tail == NULL || tail->type == -1) && k1 > 0 && + k2 > 0) || + (t->type == -1 && tail != NULL && tail->type == 1 && + (k1 == 0 || k2 == 0))))) { + if (tail == NULL) { + *ret = t; + } else { + tail->next = t; + } + tail = t; + } else { + free(t); + } + } + return 0; } *ret = NULL; - event_list* tail = NULL; - int32_t k1 = 0; - int32_t k2 = 0; - while (l1 != NULL || l2 != NULL) { - event_list* t; - if (l2 == NULL || (l1 != NULL && (l1->x < l2->x || (l1->x == l2->x && l1->type > l2->type)))) { - t = l1; - k1 += t->type; - assert(k1 >= 0); - l1 = l1->next; - } else { - t = l2; - k2 += t->type; - assert(k2 >= 0); - l2 = l2->next; - } - t->next = NULL; - if ((root->type == CT_OR && ( - (t->type == 1 && (tail == NULL || tail->type == -1)) || - (t->type == -1 && k1 == 0 && k2 == 0) - )) || - (root->type == CT_AND && ( - (t->type == 1 && (tail == NULL || tail->type == -1) && k1 > 0 && k2 > 0) || - (t->type == -1 && tail != NULL && tail->type == 1 && (k1 == 0 || k2 == 0)) - ))) { - if (tail == NULL) { - *ret = t; - } else { - tail->next = t; - } - tail = t; - } else { - free(t); - } - } return 0; - } - *ret = NULL; - return 0; } // One more layer of processing on top of the regular ellipse. // Uses the clipping tree. // Used for producing ellipse derivatives such as arc, chord, pie, etc. typedef struct { - ellipse_state st; - clip_node* root; - clip_node nodes[7]; - int32_t node_count; - event_list* head; - int32_t y; + ellipse_state st; + clip_node *root; + clip_node nodes[7]; + int32_t node_count; + event_list *head; + int32_t y; } clip_ellipse_state; -typedef void (*clip_ellipse_init)(clip_ellipse_state*, int32_t, int32_t, int32_t, float, float); +typedef void (*clip_ellipse_init)( + clip_ellipse_state *, int32_t, int32_t, int32_t, float, float); -void debug_clip_tree(clip_node* root, int space) { - if (root == NULL) { - return; - } - if (root->type == CT_CLIP) { - int t = space; - while (t--) { - fputc(' ', stderr); +void +debug_clip_tree(clip_node *root, int space) { + if (root == NULL) { + return; } - fprintf(stderr, "clip %+fx%+fy%+f > 0\n", root->a, root->b, root->c); - } else { - debug_clip_tree(root->l, space + 2); - int t = space; - while (t--) { - fputc(' ', stderr); + if (root->type == CT_CLIP) { + int t = space; + while (t--) { + fputc(' ', stderr); + } + fprintf(stderr, "clip %+fx%+fy%+f > 0\n", root->a, root->b, root->c); + } else { + debug_clip_tree(root->l, space + 2); + int t = space; + while (t--) { + fputc(' ', stderr); + } + fprintf(stderr, "%s\n", root->type == CT_AND ? "and" : "or"); + debug_clip_tree(root->r, space + 2); + } + if (space == 0) { + fputc('\n', stderr); } - fprintf(stderr, "%s\n", root->type == CT_AND ? "and" : "or"); - debug_clip_tree(root->r, space + 2); - } - if (space == 0) { - fputc('\n', stderr); - } } // Resulting angles will satisfy 0 <= al < 360, al <= ar <= al + 360 -void normalize_angles(float* al, float* ar) { - if (*ar - *al >= 360) { - *al = 0; - *ar = 360; - } else { - *al = fmod(*al < 0 ? 360 - (fmod(-*al, 360)) : *al, 360); - *ar = *al + fmod(*ar < *al ? 360 - fmod(*al - *ar, 360) : *ar - *al, 360); - } +void +normalize_angles(float *al, float *ar) { + if (*ar - *al >= 360) { + *al = 0; + *ar = 360; + } else { + *al = fmod(*al < 0 ? 360 - (fmod(-*al, 360)) : *al, 360); + *ar = *al + fmod(*ar < *al ? 360 - fmod(*al - *ar, 360) : *ar - *al, 360); + } } // An arc with caps orthogonal to the ellipse curve. -void arc_init(clip_ellipse_state* s, int32_t a, int32_t b, int32_t w, float al, float ar) { - if (a < b) { - // transpose the coordinate system - arc_init(s, b, a, w, 90 - ar, 90 - al); - ellipse_init(&s->st, a, b, w); - clip_tree_transpose(s->root); - } else { - // a >= b, based on "wide" ellipse +void +arc_init(clip_ellipse_state *s, int32_t a, int32_t b, int32_t w, float al, float ar) { + if (a < b) { + // transpose the coordinate system + arc_init(s, b, a, w, 90 - ar, 90 - al); + ellipse_init(&s->st, a, b, w); + clip_tree_transpose(s->root); + } else { + // a >= b, based on "wide" ellipse + ellipse_init(&s->st, a, b, w); + + s->head = NULL; + s->node_count = 0; + normalize_angles(&al, &ar); + + // building clipping tree, a lot of different cases + if (ar == al + 360) { + s->root = NULL; + } else { + clip_node *lc = s->nodes + s->node_count++; + clip_node *rc = s->nodes + s->node_count++; + lc->l = lc->r = rc->l = rc->r = NULL; + lc->type = rc->type = CT_CLIP; + lc->a = -a * sin(al * M_PI / 180.0); + lc->b = b * cos(al * M_PI / 180.0); + lc->c = (a * a - b * b) * sin(al * M_PI / 90.0) / 2.0; + rc->a = a * sin(ar * M_PI / 180.0); + rc->b = -b * cos(ar * M_PI / 180.0); + rc->c = (b * b - a * a) * sin(ar * M_PI / 90.0) / 2.0; + if (fmod(al, 180) == 0 || fmod(ar, 180) == 0) { + s->root = s->nodes + s->node_count++; + s->root->l = lc; + s->root->r = rc; + s->root->type = ar - al < 180 ? CT_AND : CT_OR; + } else if (((int)(al / 180) + (int)(ar / 180)) % 2 == 1) { + s->root = s->nodes + s->node_count++; + s->root->l = s->nodes + s->node_count++; + s->root->l->l = s->nodes + s->node_count++; + s->root->l->r = lc; + s->root->r = s->nodes + s->node_count++; + s->root->r->l = s->nodes + s->node_count++; + s->root->r->r = rc; + s->root->type = CT_OR; + s->root->l->type = CT_AND; + s->root->r->type = CT_AND; + s->root->l->l->type = CT_CLIP; + s->root->r->l->type = CT_CLIP; + s->root->l->l->l = s->root->l->l->r = NULL; + s->root->r->l->l = s->root->r->l->r = NULL; + s->root->l->l->a = s->root->l->l->c = 0; + s->root->r->l->a = s->root->r->l->c = 0; + s->root->l->l->b = (int)(al / 180) % 2 == 0 ? 1 : -1; + s->root->r->l->b = (int)(ar / 180) % 2 == 0 ? 1 : -1; + } else { + s->root = s->nodes + s->node_count++; + s->root->l = s->nodes + s->node_count++; + s->root->r = s->nodes + s->node_count++; + s->root->type = s->root->l->type = ar - al < 180 ? CT_AND : CT_OR; + s->root->l->l = lc; + s->root->l->r = rc; + s->root->r->type = CT_CLIP; + s->root->r->l = s->root->r->r = NULL; + s->root->r->a = s->root->r->c = 0; + s->root->r->b = ar < 180 || ar > 540 ? 1 : -1; + } + } + } +} + +// A chord line. +void +chord_line_init( + clip_ellipse_state *s, int32_t a, int32_t b, int32_t w, float al, float ar) { + ellipse_init(&s->st, a, b, a + b + 1); + + s->head = NULL; + s->node_count = 0; + + // line equation for chord + double xl = a * cos(al * M_PI / 180.0), xr = a * cos(ar * M_PI / 180.0); + double yl = b * sin(al * M_PI / 180.0), yr = b * sin(ar * M_PI / 180.0); + s->root = s->nodes + s->node_count++; + s->root->l = s->nodes + s->node_count++; + s->root->r = s->nodes + s->node_count++; + s->root->type = CT_AND; + s->root->l->type = s->root->r->type = CT_CLIP; + s->root->l->l = s->root->l->r = s->root->r->l = s->root->r->r = NULL; + s->root->l->a = yr - yl; + s->root->l->b = xl - xr; + s->root->l->c = -(s->root->l->a * xl + s->root->l->b * yl); + s->root->r->a = -s->root->l->a; + s->root->r->b = -s->root->l->b; + s->root->r->c = + 2 * w * sqrt(pow(s->root->l->a, 2.0) + pow(s->root->l->b, 2.0)) - s->root->l->c; +} + +// Pie side. +void +pie_side_init( + clip_ellipse_state *s, int32_t a, int32_t b, int32_t w, float al, float _) { + ellipse_init(&s->st, a, b, a + b + 1); + + s->head = NULL; + s->node_count = 0; + + double xl = a * cos(al * M_PI / 180.0); + double yl = b * sin(al * M_PI / 180.0); + double a1 = -yl; + double b1 = xl; + double c1 = w * sqrt(a1 * a1 + b1 * b1); + + s->root = s->nodes + s->node_count++; + s->root->type = CT_AND; + s->root->l = s->nodes + s->node_count++; + s->root->l->type = CT_AND; + + clip_node *cnode; + cnode = s->nodes + s->node_count++; + cnode->l = cnode->r = NULL; + cnode->type = CT_CLIP; + cnode->a = a1; + cnode->b = b1; + cnode->c = c1; + s->root->l->l = cnode; + cnode = s->nodes + s->node_count++; + cnode->l = cnode->r = NULL; + cnode->type = CT_CLIP; + cnode->a = -a1; + cnode->b = -b1; + cnode->c = c1; + s->root->l->r = cnode; + cnode = s->nodes + s->node_count++; + cnode->l = cnode->r = NULL; + cnode->type = CT_CLIP; + cnode->a = b1; + cnode->b = -a1; + cnode->c = 0; + s->root->r = cnode; +} + +// A chord. +void +chord_init(clip_ellipse_state *s, int32_t a, int32_t b, int32_t w, float al, float ar) { ellipse_init(&s->st, a, b, w); s->head = NULL; s->node_count = 0; - normalize_angles(&al, &ar); - // building clipping tree, a lot of different cases - if (ar == al + 360) { - s->root = NULL; - } else { - clip_node* lc = s->nodes + s->node_count++; - clip_node* rc = s->nodes + s->node_count++; - lc->l = lc->r = rc->l = rc->r = NULL; - lc->type = rc->type = CT_CLIP; - lc->a = -a * sin(al * M_PI / 180.0); - lc->b = b * cos(al * M_PI / 180.0); - lc->c = (a * a - b * b) * sin(al * M_PI / 90.0) / 2.0; - rc->a = a * sin(ar * M_PI / 180.0); - rc->b = -b * cos(ar * M_PI / 180.0); - rc->c = (b * b - a * a) * sin(ar * M_PI / 90.0) / 2.0; - if (fmod(al, 180) == 0 || fmod(ar, 180) == 0) { - s->root = s->nodes + s->node_count++; - s->root->l = lc; - s->root->r = rc; - s->root->type = ar - al < 180 ? CT_AND : CT_OR; - } else if (((int)(al / 180) + (int)(ar / 180)) % 2 == 1) { - s->root = s->nodes + s->node_count++; - s->root->l = s->nodes + s->node_count++; - s->root->l->l = s->nodes + s->node_count++; - s->root->l->r = lc; - s->root->r = s->nodes + s->node_count++; - s->root->r->l = s->nodes + s->node_count++; - s->root->r->r = rc; - s->root->type = CT_OR; - s->root->l->type = CT_AND; - s->root->r->type = CT_AND; - s->root->l->l->type = CT_CLIP; - s->root->r->l->type = CT_CLIP; - s->root->l->l->l = s->root->l->l->r = NULL; - s->root->r->l->l = s->root->r->l->r = NULL; - s->root->l->l->a = s->root->l->l->c = 0; - s->root->r->l->a = s->root->r->l->c = 0; - s->root->l->l->b = (int)(al / 180) % 2 == 0 ? 1 : -1; - s->root->r->l->b = (int)(ar / 180) % 2 == 0 ? 1 : -1; - } else { - s->root = s->nodes + s->node_count++; - s->root->l = s->nodes + s->node_count++; - s->root->r = s->nodes + s->node_count++; - s->root->type = s->root->l->type = ar - al < 180 ? CT_AND : CT_OR; - s->root->l->l = lc; - s->root->l->r = rc; - s->root->r->type = CT_CLIP; - s->root->r->l = s->root->r->r = NULL; - s->root->r->a = s->root->r->c = 0; - s->root->r->b = ar < 180 || ar > 540 ? 1 : -1; - } - } - } -} - -// A chord line. -void chord_line_init(clip_ellipse_state* s, int32_t a, int32_t b, int32_t w, float al, float ar) { - ellipse_init(&s->st, a, b, a + b + 1); - - s->head = NULL; - s->node_count = 0; - - // line equation for chord - double xl = a * cos(al * M_PI / 180.0), xr = a * cos(ar * M_PI / 180.0); - double yl = b * sin(al * M_PI / 180.0), yr = b * sin(ar * M_PI / 180.0); - s->root = s->nodes + s->node_count++; - s->root->l = s->nodes + s->node_count++; - s->root->r = s->nodes + s->node_count++; - s->root->type = CT_AND; - s->root->l->type = s->root->r->type = CT_CLIP; - s->root->l->l = s->root->l->r = s->root->r->l = s->root->r->r = NULL; - s->root->l->a = yr - yl; - s->root->l->b = xl - xr; - s->root->l->c = -(s->root->l->a * xl + s->root->l->b * yl); - s->root->r->a = -s->root->l->a; - s->root->r->b = -s->root->l->b; - s->root->r->c = 2 * w * sqrt(pow(s->root->l->a, 2.0) + pow(s->root->l->b, 2.0)) - s->root->l->c; -} - -// Pie side. -void pie_side_init(clip_ellipse_state* s, int32_t a, int32_t b, int32_t w, float al, float _) { - ellipse_init(&s->st, a, b, a + b + 1); - - s->head = NULL; - s->node_count = 0; - - double xl = a * cos(al * M_PI / 180.0); - double yl = b * sin(al * M_PI / 180.0); - double a1 = -yl; - double b1 = xl; - double c1 = w * sqrt(a1 * a1 + b1 * b1); - - s->root = s->nodes + s->node_count++; - s->root->type = CT_AND; - s->root->l = s->nodes + s->node_count++; - s->root->l->type = CT_AND; - - clip_node* cnode; - cnode = s->nodes + s->node_count++; - cnode->l = cnode->r = NULL; - cnode->type = CT_CLIP; - cnode->a = a1; - cnode->b = b1; - cnode->c = c1; - s->root->l->l = cnode; - cnode = s->nodes + s->node_count++; - cnode->l = cnode->r = NULL; - cnode->type = CT_CLIP; - cnode->a = -a1; - cnode->b = -b1; - cnode->c = c1; - s->root->l->r = cnode; - cnode = s->nodes + s->node_count++; - cnode->l = cnode->r = NULL; - cnode->type = CT_CLIP; - cnode->a = b1; - cnode->b = -a1; - cnode->c = 0; - s->root->r = cnode; -} - -// A chord. -void chord_init(clip_ellipse_state* s, int32_t a, int32_t b, int32_t w, float al, float ar) { - ellipse_init(&s->st, a, b, w); - - s->head = NULL; - s->node_count = 0; - - // line equation for chord - double xl = a * cos(al * M_PI / 180.0), xr = a * cos(ar * M_PI / 180.0); - double yl = b * sin(al * M_PI / 180.0), yr = b * sin(ar * M_PI / 180.0); - s->root = s->nodes + s->node_count++; - s->root->l = s->root->r = NULL; - s->root->type = CT_CLIP; - s->root->a = yr - yl; - s->root->b = xl - xr; - s->root->c = -(s->root->a * xl + s->root->b * yl); + // line equation for chord + double xl = a * cos(al * M_PI / 180.0), xr = a * cos(ar * M_PI / 180.0); + double yl = b * sin(al * M_PI / 180.0), yr = b * sin(ar * M_PI / 180.0); + s->root = s->nodes + s->node_count++; + s->root->l = s->root->r = NULL; + s->root->type = CT_CLIP; + s->root->a = yr - yl; + s->root->b = xl - xr; + s->root->c = -(s->root->a * xl + s->root->b * yl); } // A pie. Can also be used to draw an arc with ugly sharp caps. -void pie_init(clip_ellipse_state* s, int32_t a, int32_t b, int32_t w, float al, float ar) { - ellipse_init(&s->st, a, b, w); +void +pie_init(clip_ellipse_state *s, int32_t a, int32_t b, int32_t w, float al, float ar) { + ellipse_init(&s->st, a, b, w); - s->head = NULL; - s->node_count = 0; + s->head = NULL; + s->node_count = 0; - // line equations for pie sides - double xl = a * cos(al * M_PI / 180.0), xr = a * cos(ar * M_PI / 180.0); - double yl = b * sin(al * M_PI / 180.0), yr = b * sin(ar * M_PI / 180.0); + // line equations for pie sides + double xl = a * cos(al * M_PI / 180.0), xr = a * cos(ar * M_PI / 180.0); + double yl = b * sin(al * M_PI / 180.0), yr = b * sin(ar * M_PI / 180.0); - clip_node* lc = s->nodes + s->node_count++; - clip_node* rc = s->nodes + s->node_count++; - lc->l = lc->r = rc->l = rc->r = NULL; - lc->type = rc->type = CT_CLIP; - lc->a = -yl; - lc->b = xl; - lc->c = 0; - rc->a = yr; - rc->b = -xr; - rc->c = 0; + clip_node *lc = s->nodes + s->node_count++; + clip_node *rc = s->nodes + s->node_count++; + lc->l = lc->r = rc->l = rc->r = NULL; + lc->type = rc->type = CT_CLIP; + lc->a = -yl; + lc->b = xl; + lc->c = 0; + rc->a = yr; + rc->b = -xr; + rc->c = 0; - s->root = s->nodes + s->node_count++; - s->root->l = lc; - s->root->r = rc; - s->root->type = ar - al < 180 ? CT_AND : CT_OR; + s->root = s->nodes + s->node_count++; + s->root->l = lc; + s->root->r = rc; + s->root->type = ar - al < 180 ? CT_AND : CT_OR; } -void clip_ellipse_free(clip_ellipse_state* s) { - while (s->head != NULL) { - event_list* t = s->head; - s->head = s->head->next; - free(t); - } -} - -int8_t clip_ellipse_next(clip_ellipse_state* s, int32_t* ret_x0, int32_t* ret_y, int32_t* ret_x1) { - int32_t x0, y, x1; - while (s->head == NULL && ellipse_next(&s->st, &x0, &y, &x1) >= 0) { - if (clip_tree_do_clip(s->root, x0, y, x1, &s->head) < 0) { - return -2; +void +clip_ellipse_free(clip_ellipse_state *s) { + while (s->head != NULL) { + event_list *t = s->head; + s->head = s->head->next; + free(t); } - s->y = y; - } - if (s->head != NULL) { - *ret_y = s->y; - event_list* t = s->head; - s->head = s->head->next; - *ret_x0 = t->x; - free(t); - t = s->head; - assert(t != NULL); - s->head = s->head->next; - *ret_x1 = t->x; - free(t); - return 0; - } - return -1; +} + +int8_t +clip_ellipse_next( + clip_ellipse_state *s, int32_t *ret_x0, int32_t *ret_y, int32_t *ret_x1) { + int32_t x0, y, x1; + while (s->head == NULL && ellipse_next(&s->st, &x0, &y, &x1) >= 0) { + if (clip_tree_do_clip(s->root, x0, y, x1, &s->head) < 0) { + return -2; + } + s->y = y; + } + if (s->head != NULL) { + *ret_y = s->y; + event_list *t = s->head; + s->head = s->head->next; + *ret_x0 = t->x; + free(t); + t = s->head; + assert(t != NULL); + s->head = s->head->next; + *ret_x1 = t->x; + free(t); + return 0; + } + return -1; } static int -ellipseNew(Imaging im, int x0, int y0, int x1, int y1, - const void* ink_, int fill, - int width, int op) -{ - DRAW* draw; +ellipseNew( + Imaging im, + int x0, + int y0, + int x1, + int y1, + const void *ink_, + int fill, + int width, + int op) { + DRAW *draw; INT32 ink; DRAWINIT(); int a = x1 - x0; int b = y1 - y0; if (a < 0 || b < 0) { - return 0; + return 0; } if (fill) { - width = a + b; + width = a + b; } ellipse_state st; ellipse_init(&st, a, b, width); int32_t X0, Y, X1; while (ellipse_next(&st, &X0, &Y, &X1) != -1) { - draw->hline(im, x0 + (X0 + a) / 2, y0 + (Y + b) / 2, x0 + (X1 + a) / 2, ink); + draw->hline(im, x0 + (X0 + a) / 2, y0 + (Y + b) / 2, x0 + (X1 + a) / 2, ink); } return 0; } static int -clipEllipseNew(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, - const void* ink_, int width, int op, clip_ellipse_init init) -{ - DRAW* draw; +clipEllipseNew( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink_, + int width, + int op, + clip_ellipse_init init) { + DRAW *draw; INT32 ink; DRAWINIT(); int a = x1 - x0; int b = y1 - y0; if (a < 0 || b < 0) { - return 0; + return 0; } clip_ellipse_state st; @@ -1446,124 +1446,187 @@ clipEllipseNew(Imaging im, int x0, int y0, int x1, int y1, int32_t X0, Y, X1; int next_code; while ((next_code = clip_ellipse_next(&st, &X0, &Y, &X1)) >= 0) { - draw->hline(im, x0 + (X0 + a) / 2, y0 + (Y + b) / 2, x0 + (X1 + a) / 2, ink); + draw->hline(im, x0 + (X0 + a) / 2, y0 + (Y + b) / 2, x0 + (X1 + a) / 2, ink); } clip_ellipse_free(&st); return next_code == -1 ? 0 : -1; } static int -arcNew(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, - const void* ink_, int width, int op) -{ - return clipEllipseNew(im, x0, y0, x1, y1, start, end, ink_, width, op, arc_init); +arcNew( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink_, + int width, + int op) { + return clipEllipseNew(im, x0, y0, x1, y1, start, end, ink_, width, op, arc_init); } static int -chordNew(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, - const void* ink_, int width, int op) -{ - return clipEllipseNew(im, x0, y0, x1, y1, start, end, ink_, width, op, chord_init); +chordNew( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink_, + int width, + int op) { + return clipEllipseNew(im, x0, y0, x1, y1, start, end, ink_, width, op, chord_init); } static int -chordLineNew(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, - const void* ink_, int width, int op) -{ - return clipEllipseNew(im, x0, y0, x1, y1, start, end, ink_, width, op, chord_line_init); +chordLineNew( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink_, + int width, + int op) { + return clipEllipseNew( + im, x0, y0, x1, y1, start, end, ink_, width, op, chord_line_init); } static int -pieNew(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, - const void* ink_, int width, int op) -{ - return clipEllipseNew(im, x0, y0, x1, y1, start, end, ink_, width, op, pie_init); +pieNew( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink_, + int width, + int op) { + return clipEllipseNew(im, x0, y0, x1, y1, start, end, ink_, width, op, pie_init); } static int -pieSideNew(Imaging im, int x0, int y0, int x1, int y1, - float start, - const void* ink_, int width, int op) -{ - return clipEllipseNew(im, x0, y0, x1, y1, start, 0, ink_, width, op, pie_side_init); +pieSideNew( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + const void *ink_, + int width, + int op) { + return clipEllipseNew(im, x0, y0, x1, y1, start, 0, ink_, width, op, pie_side_init); } int -ImagingDrawEllipse(Imaging im, int x0, int y0, int x1, int y1, - const void* ink, int fill, int width, int op) -{ +ImagingDrawEllipse( + Imaging im, + int x0, + int y0, + int x1, + int y1, + const void *ink, + int fill, + int width, + int op) { return ellipseNew(im, x0, y0, x1, y1, ink, fill, width, op); } int -ImagingDrawArc(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, const void* ink, int width, int op) -{ +ImagingDrawArc( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink, + int width, + int op) { normalize_angles(&start, &end); if (start + 360 == end) { - return ImagingDrawEllipse(im, x0, y0, x1, y1, ink, 0, width, op); + return ImagingDrawEllipse(im, x0, y0, x1, y1, ink, 0, width, op); } if (start == end) { - return 0; + return 0; } return arcNew(im, x0, y0, x1, y1, start, end, ink, width, op); } - int -ImagingDrawChord(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, const void* ink, int fill, - int width, int op) -{ +ImagingDrawChord( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink, + int fill, + int width, + int op) { normalize_angles(&start, &end); if (start + 360 == end) { - return ImagingDrawEllipse(im, x0, y0, x1, y1, ink, fill, width, op); + return ImagingDrawEllipse(im, x0, y0, x1, y1, ink, fill, width, op); } if (start == end) { - return 0; + return 0; } if (fill) { - return chordNew(im, x0, y0, x1, y1, start, end, ink, x1 - x0 + y1 - y0 + 1, op); + return chordNew(im, x0, y0, x1, y1, start, end, ink, x1 - x0 + y1 - y0 + 1, op); } else { - if (chordLineNew(im, x0, y0, x1, y1, start, end, ink, width, op)) { - return -1; - } - return chordNew(im, x0, y0, x1, y1, start, end, ink, width, op); + if (chordLineNew(im, x0, y0, x1, y1, start, end, ink, width, op)) { + return -1; + } + return chordNew(im, x0, y0, x1, y1, start, end, ink, width, op); } } - int -ImagingDrawPieslice(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, const void* ink, int fill, - int width, int op) -{ +ImagingDrawPieslice( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink, + int fill, + int width, + int op) { normalize_angles(&start, &end); if (start + 360 == end) { - return ellipseNew(im, x0, y0, x1, y1, ink, fill, width, op); + return ellipseNew(im, x0, y0, x1, y1, ink, fill, width, op); } if (start == end) { - return 0; + return 0; } if (fill) { - return pieNew(im, x0, y0, x1, y1, start, end, ink, x1 + y1 - x0 - y0, op); + return pieNew(im, x0, y0, x1, y1, start, end, ink, x1 + y1 - x0 - y0, op); } else { - if (pieSideNew(im, x0, y0, x1, y1, start, ink, width, op)) { - return -1; - } - if (pieSideNew(im, x0, y0, x1, y1, end, ink, width, op)) { - return -1; - } - int xc = lround((x0 + x1 - width) / 2.0), yc = lround((y0 + y1 - width) / 2.0); - ellipseNew(im, xc, yc, xc + width - 1, yc + width - 1, ink, 1, 0, op); - return pieNew(im, x0, y0, x1, y1, start, end, ink, width, op); + if (pieSideNew(im, x0, y0, x1, y1, start, ink, width, op)) { + return -1; + } + if (pieSideNew(im, x0, y0, x1, y1, end, ink, width, op)) { + return -1; + } + int xc = lround((x0 + x1 - width) / 2.0), yc = lround((y0 + y1 - width) / 2.0); + ellipseNew(im, xc, yc, xc + width - 1, yc + width - 1, ink, 1, 0, op); + return pieNew(im, x0, y0, x1, y1, start, end, ink, width, op); } } - /* -------------------------------------------------------------------- */ /* experimental level 2 ("arrow") graphics stuff. this implements @@ -1572,7 +1635,6 @@ ImagingDrawPieslice(Imaging im, int x0, int y0, int x1, int y1, itself */ struct ImagingOutlineInstance { - float x0, y0; float x, y; @@ -1581,18 +1643,15 @@ struct ImagingOutlineInstance { Edge *edges; int size; - }; - ImagingOutline -ImagingOutlineNew(void) -{ +ImagingOutlineNew(void) { ImagingOutline outline; outline = calloc(1, sizeof(struct ImagingOutlineInstance)); if (!outline) { - return (ImagingOutline) ImagingError_MemoryError(); + return (ImagingOutline)ImagingError_MemoryError(); } outline->edges = NULL; @@ -1604,8 +1663,7 @@ ImagingOutlineNew(void) } void -ImagingOutlineDelete(ImagingOutline outline) -{ +ImagingOutlineDelete(ImagingOutline outline) { if (!outline) { return; } @@ -1617,11 +1675,9 @@ ImagingOutlineDelete(ImagingOutline outline) free(outline); } - -static Edge* -allocate(ImagingOutline outline, int extra) -{ - Edge* e; +static Edge * +allocate(ImagingOutline outline, int extra) { + Edge *e; if (outline->count + extra > outline->size) { /* expand outline buffer */ @@ -1650,8 +1706,7 @@ allocate(ImagingOutline outline, int extra) } int -ImagingOutlineMove(ImagingOutline outline, float x0, float y0) -{ +ImagingOutlineMove(ImagingOutline outline, float x0, float y0) { outline->x = outline->x0 = x0; outline->y = outline->y0 = y0; @@ -1659,16 +1714,15 @@ ImagingOutlineMove(ImagingOutline outline, float x0, float y0) } int -ImagingOutlineLine(ImagingOutline outline, float x1, float y1) -{ - Edge* e; +ImagingOutlineLine(ImagingOutline outline, float x1, float y1) { + Edge *e; e = allocate(outline, 1); if (!e) { return -1; /* out of memory */ } - add_edge(e, (int) outline->x, (int) outline->y, (int) x1, (int) y1); + add_edge(e, (int)outline->x, (int)outline->y, (int)x1, (int)y1); outline->x = x1; outline->y = y1; @@ -1677,10 +1731,15 @@ ImagingOutlineLine(ImagingOutline outline, float x1, float y1) } int -ImagingOutlineCurve(ImagingOutline outline, float x1, float y1, - float x2, float y2, float x3, float y3) -{ - Edge* e; +ImagingOutlineCurve( + ImagingOutline outline, + float x1, + float y1, + float x2, + float y2, + float x3, + float y3) { + Edge *e; int i; float xo, yo; @@ -1697,22 +1756,20 @@ ImagingOutlineCurve(ImagingOutline outline, float x1, float y1, /* flatten the bezier segment */ for (i = 1; i <= STEPS; i++) { - - float t = ((float) i) / STEPS; - float t2 = t*t; - float t3 = t2*t; + float t = ((float)i) / STEPS; + float t2 = t * t; + float t3 = t2 * t; float u = 1.0F - t; - float u2 = u*u; - float u3 = u2*u; + float u2 = u * u; + float u3 = u2 * u; - float x = outline->x*u3 + 3*(x1*t*u2 + x2*t2*u) + x3*t3 + 0.5; - float y = outline->y*u3 + 3*(y1*t*u2 + y2*t2*u) + y3*t3 + 0.5; + float x = outline->x * u3 + 3 * (x1 * t * u2 + x2 * t2 * u) + x3 * t3 + 0.5; + float y = outline->y * u3 + 3 * (y1 * t * u2 + y2 * t2 * u) + y3 * t3 + 0.5; - add_edge(e++, xo, yo, (int) x, (int) y); + add_edge(e++, xo, yo, (int)x, (int)y); xo = x, yo = y; - } outline->x = xo; @@ -1722,8 +1779,7 @@ ImagingOutlineCurve(ImagingOutline outline, float x1, float y1, } int -ImagingOutlineClose(ImagingOutline outline) -{ +ImagingOutlineClose(ImagingOutline outline) { if (outline->x == outline->x0 && outline->y == outline->y0) { return 0; } @@ -1731,16 +1787,19 @@ ImagingOutlineClose(ImagingOutline outline) } int -ImagingOutlineTransform(ImagingOutline outline, double a[6]) -{ +ImagingOutlineTransform(ImagingOutline outline, double a[6]) { Edge *eIn; Edge *eOut; int i, n; int x0, y0, x1, y1; int X0, Y0, X1, Y1; - double a0 = a[0]; double a1 = a[1]; double a2 = a[2]; - double a3 = a[3]; double a4 = a[4]; double a5 = a[5]; + double a0 = a[0]; + double a1 = a[1]; + double a2 = a[2]; + double a3 = a[3]; + double a4 = a[4]; + double a5 = a[5]; eIn = outline->edges; n = outline->count; @@ -1758,7 +1817,6 @@ ImagingOutlineTransform(ImagingOutline outline, double a[6]) } for (i = 0; i < n; i++) { - x0 = eIn->x0; y0 = eIn->y0; @@ -1778,16 +1836,15 @@ ImagingOutlineTransform(ImagingOutline outline, double a[6]) upgrade your compiler (make sure you have the right service pack) */ - X0 = (int) (a0*x0 + a1*y0 + a2); - Y0 = (int) (a3*x0 + a4*y0 + a5); - X1 = (int) (a0*x1 + a1*y1 + a2); - Y1 = (int) (a3*x1 + a4*y1 + a5); + X0 = (int)(a0 * x0 + a1 * y0 + a2); + Y0 = (int)(a3 * x0 + a4 * y0 + a5); + X1 = (int)(a0 * x1 + a1 * y1 + a2); + Y1 = (int)(a3 * x1 + a4 * y1 + a5); add_edge(eOut, X0, Y0, X1, Y1); eIn++; eOut++; - } free(eIn); @@ -1796,10 +1853,9 @@ ImagingOutlineTransform(ImagingOutline outline, double a[6]) } int -ImagingDrawOutline(Imaging im, ImagingOutline outline, const void* ink_, - int fill, int op) -{ - DRAW* draw; +ImagingDrawOutline( + Imaging im, ImagingOutline outline, const void *ink_, int fill, int op) { + DRAW *draw; INT32 ink; DRAWINIT(); diff --git a/src/libImaging/Effects.c b/src/libImaging/Effects.c index e0f1d0339..93e7af0bc 100644 --- a/src/libImaging/Effects.c +++ b/src/libImaging/Effects.c @@ -15,14 +15,12 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" #include Imaging -ImagingEffectMandelbrot(int xsize, int ysize, double extent[4], int quality) -{ +ImagingEffectMandelbrot(int xsize, int ysize, double extent[4], int quality) { /* Generate a Mandelbrot set covering the given extent */ Imaging im; @@ -32,10 +30,10 @@ ImagingEffectMandelbrot(int xsize, int ysize, double extent[4], int quality) double dr, di; /* Check arguments */ - width = extent[2] - extent[0]; + width = extent[2] - extent[0]; height = extent[3] - extent[1]; if (width < 0.0 || height < 0.0 || quality < 2) { - return (Imaging) ImagingError_ValueError(NULL); + return (Imaging)ImagingError_ValueError(NULL); } im = ImagingNewDirty("L", xsize, ysize); @@ -43,24 +41,24 @@ ImagingEffectMandelbrot(int xsize, int ysize, double extent[4], int quality) return NULL; } - dr = width/(xsize-1); - di = height/(ysize-1); + dr = width / (xsize - 1); + di = height / (ysize - 1); radius = 100.0; for (y = 0; y < ysize; y++) { - UINT8* buf = im->image8[y]; + UINT8 *buf = im->image8[y]; for (x = 0; x < xsize; x++) { x1 = y1 = xi2 = yi2 = 0.0; - cr = x*dr + extent[0]; - ci = y*di + extent[1]; + cr = x * dr + extent[0]; + ci = y * di + extent[1]; for (k = 1;; k++) { - y1 = 2*x1*y1 + ci; + y1 = 2 * x1 * y1 + ci; x1 = xi2 - yi2 + cr; - xi2 = x1*x1; - yi2 = y1*y1; + xi2 = x1 * x1; + yi2 = y1 * y1; if ((xi2 + yi2) > radius) { - buf[x] = k*255/quality; + buf[x] = k * 255 / quality; break; } if (k > quality) { @@ -74,8 +72,7 @@ ImagingEffectMandelbrot(int xsize, int ysize, double extent[4], int quality) } Imaging -ImagingEffectNoise(int xsize, int ysize, float sigma) -{ +ImagingEffectNoise(int xsize, int ysize, float sigma) { /* Generate Gaussian noise centered around 128 */ Imaging imOut; @@ -92,7 +89,7 @@ ImagingEffectNoise(int xsize, int ysize, float sigma) nextok = 0; for (y = 0; y < imOut->ysize; y++) { - UINT8* out = imOut->image8[y]; + UINT8 *out = imOut->image8[y]; for (x = 0; x < imOut->xsize; x++) { if (nextok) { this = next; @@ -101,11 +98,11 @@ ImagingEffectNoise(int xsize, int ysize, float sigma) /* after numerical recipes */ double v1, v2, radius, factor; do { - v1 = rand()*(2.0/RAND_MAX) - 1.0; - v2 = rand()*(2.0/RAND_MAX) - 1.0; - radius= v1*v1 + v2*v2; + v1 = rand() * (2.0 / RAND_MAX) - 1.0; + v2 = rand() * (2.0 / RAND_MAX) - 1.0; + radius = v1 * v1 + v2 * v2; } while (radius >= 1.0); - factor = sqrt(-2.0*log(radius)/radius); + factor = sqrt(-2.0 * log(radius) / radius); this = factor * v1; next = factor * v2; } @@ -117,8 +114,7 @@ ImagingEffectNoise(int xsize, int ysize, float sigma) } Imaging -ImagingEffectSpread(Imaging imIn, int distance) -{ +ImagingEffectSpread(Imaging imIn, int distance) { /* Randomly spread pixels in an image */ Imaging imOut; @@ -130,26 +126,26 @@ ImagingEffectSpread(Imaging imIn, int distance) return NULL; } -#define SPREAD(type, image)\ - if (distance == 0) {\ - for (y = 0; y < imOut->ysize; y++) {\ - for (x = 0; x < imOut->xsize; x++) {\ - imOut->image[y][x] = imIn->image[y][x];\ - }\ - }\ - } else {\ - for (y = 0; y < imOut->ysize; y++) {\ - for (x = 0; x < imOut->xsize; x++) {\ - int xx = x + (rand() % distance) - distance/2;\ - int yy = y + (rand() % distance) - distance/2;\ - if (xx >= 0 && xx < imIn->xsize && yy >= 0 && yy < imIn->ysize) {\ - imOut->image[yy][xx] = imIn->image[y][x];\ - imOut->image[y][x] = imIn->image[yy][xx];\ - } else {\ - imOut->image[y][x] = imIn->image[y][x];\ - }\ - }\ - }\ +#define SPREAD(type, image) \ + if (distance == 0) { \ + for (y = 0; y < imOut->ysize; y++) { \ + for (x = 0; x < imOut->xsize; x++) { \ + imOut->image[y][x] = imIn->image[y][x]; \ + } \ + } \ + } else { \ + for (y = 0; y < imOut->ysize; y++) { \ + for (x = 0; x < imOut->xsize; x++) { \ + int xx = x + (rand() % distance) - distance / 2; \ + int yy = y + (rand() % distance) - distance / 2; \ + if (xx >= 0 && xx < imIn->xsize && yy >= 0 && yy < imIn->ysize) { \ + imOut->image[yy][xx] = imIn->image[y][x]; \ + imOut->image[y][x] = imIn->image[yy][xx]; \ + } else { \ + imOut->image[y][x] = imIn->image[y][x]; \ + } \ + } \ + } \ } if (imIn->image8) { diff --git a/src/libImaging/EpsEncode.c b/src/libImaging/EpsEncode.c index ac8a4059c..3f2cb33b2 100644 --- a/src/libImaging/EpsEncode.c +++ b/src/libImaging/EpsEncode.c @@ -17,28 +17,24 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - int -ImagingEpsEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) -{ - enum { HEXBYTE=1, NEWLINE }; +ImagingEpsEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { + enum { HEXBYTE = 1, NEWLINE }; const char *hex = "0123456789abcdef"; - UINT8* ptr = buf; - UINT8* in, i; + UINT8 *ptr = buf; + UINT8 *in, i; if (!state->state) { state->state = HEXBYTE; state->xsize *= im->pixelsize; /* Hack! */ } - in = (UINT8*) im->image[state->y]; + in = (UINT8 *)im->image[state->y]; for (;;) { - if (state->state == NEWLINE) { if (bytes < 1) { break; @@ -53,8 +49,8 @@ ImagingEpsEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) } i = in[state->x++]; - *ptr++ = hex[(i>>4)&15]; - *ptr++ = hex[i&15]; + *ptr++ = hex[(i >> 4) & 15]; + *ptr++ = hex[i & 15]; bytes -= 2; /* Skip junk bytes */ @@ -62,7 +58,7 @@ ImagingEpsEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) state->x++; } - if (++state->count >= 79/2) { + if (++state->count >= 79 / 2) { state->state = NEWLINE; state->count = 0; } @@ -73,11 +69,9 @@ ImagingEpsEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) state->errcode = IMAGING_CODEC_END; break; } - in = (UINT8*) im->image[state->y]; + in = (UINT8 *)im->image[state->y]; } - } return ptr - buf; - } diff --git a/src/libImaging/Except.c b/src/libImaging/Except.c index 3903b5bb8..f42ff9aec 100644 --- a/src/libImaging/Except.c +++ b/src/libImaging/Except.c @@ -19,41 +19,34 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - /* exception state */ void * -ImagingError_OSError(void) -{ +ImagingError_OSError(void) { fprintf(stderr, "*** exception: file access error\n"); return NULL; } void * -ImagingError_MemoryError(void) -{ +ImagingError_MemoryError(void) { fprintf(stderr, "*** exception: out of memory\n"); return NULL; } void * -ImagingError_ModeError(void) -{ +ImagingError_ModeError(void) { return ImagingError_ValueError("bad image mode"); } void * -ImagingError_Mismatch(void) -{ +ImagingError_Mismatch(void) { return ImagingError_ValueError("images don't match"); } void * -ImagingError_ValueError(const char *message) -{ +ImagingError_ValueError(const char *message) { if (!message) { message = "exception: bad argument to function"; } @@ -62,21 +55,18 @@ ImagingError_ValueError(const char *message) } void -ImagingError_Clear(void) -{ +ImagingError_Clear(void) { /* nop */; } /* thread state */ void -ImagingSectionEnter(ImagingSectionCookie* cookie) -{ +ImagingSectionEnter(ImagingSectionCookie *cookie) { /* pass */ } void -ImagingSectionLeave(ImagingSectionCookie* cookie) -{ +ImagingSectionLeave(ImagingSectionCookie *cookie) { /* pass */ } diff --git a/src/libImaging/File.c b/src/libImaging/File.c index 14688d661..76d0abccc 100644 --- a/src/libImaging/File.c +++ b/src/libImaging/File.c @@ -15,19 +15,15 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" #include - int -ImagingSaveRaw(Imaging im, FILE* fp) -{ +ImagingSaveRaw(Imaging im, FILE *fp) { int x, y, i; if (strcmp(im->mode, "1") == 0 || strcmp(im->mode, "L") == 0) { - /* @PIL227: FIXME: for mode "1", map != 0 to 255 */ /* PGM "L" */ @@ -36,33 +32,29 @@ ImagingSaveRaw(Imaging im, FILE* fp) } } else { - /* PPM "RGB" or other internal format */ for (y = 0; y < im->ysize; y++) { for (x = i = 0; x < im->xsize; x++, i += im->pixelsize) { - fwrite(im->image[y]+i, 1, im->bands, fp); + fwrite(im->image[y] + i, 1, im->bands, fp); } } - } return 1; } - int -ImagingSavePPM(Imaging im, const char* outfile) -{ - FILE* fp; +ImagingSavePPM(Imaging im, const char *outfile) { + FILE *fp; if (!im) { - (void) ImagingError_ValueError(NULL); + (void)ImagingError_ValueError(NULL); return 0; } fp = fopen(outfile, "wb"); if (!fp) { - (void) ImagingError_OSError(); + (void)ImagingError_OSError(); return 0; } @@ -74,7 +66,7 @@ ImagingSavePPM(Imaging im, const char* outfile) fprintf(fp, "P6\n%d %d\n255\n", im->xsize, im->ysize); } else { fclose(fp); - (void) ImagingError_ModeError(); + (void)ImagingError_ModeError(); return 0; } @@ -84,4 +76,3 @@ ImagingSavePPM(Imaging im, const char* outfile) return 1; } - diff --git a/src/libImaging/Fill.c b/src/libImaging/Fill.c index da143b4f9..e4e4b4344 100644 --- a/src/libImaging/Fill.c +++ b/src/libImaging/Fill.c @@ -15,14 +15,12 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" #include "math.h" Imaging -ImagingFill(Imaging im, const void* colour) -{ +ImagingFill(Imaging im, const void *colour) { int x, y; ImagingSectionCookie cookie; @@ -53,7 +51,7 @@ ImagingFill(Imaging im, const void* colour) } } } else { - unsigned char cc = (unsigned char) *(UINT8*) colour; + unsigned char cc = (unsigned char)*(UINT8 *)colour; for (y = 0; y < im->ysize; y++) { memset(im->image[y], cc, im->linesize); } @@ -65,13 +63,12 @@ ImagingFill(Imaging im, const void* colour) } Imaging -ImagingFillLinearGradient(const char *mode) -{ +ImagingFillLinearGradient(const char *mode) { Imaging im; int y; if (strlen(mode) != 1) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } im = ImagingNewDirty(mode, 256, 256); @@ -80,21 +77,20 @@ ImagingFillLinearGradient(const char *mode) } for (y = 0; y < 256; y++) { - memset(im->image8[y], (unsigned char) y, 256); + memset(im->image8[y], (unsigned char)y, 256); } return im; } Imaging -ImagingFillRadialGradient(const char *mode) -{ +ImagingFillRadialGradient(const char *mode) { Imaging im; int x, y; int d; if (strlen(mode) != 1) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } im = ImagingNewDirty(mode, 256, 256); @@ -104,7 +100,8 @@ ImagingFillRadialGradient(const char *mode) for (y = 0; y < 256; y++) { for (x = 0; x < 256; x++) { - d = (int) sqrt((double) ((x-128)*(x-128) + (y-128)*(y-128)) * 2.0); + d = (int)sqrt( + (double)((x - 128) * (x - 128) + (y - 128) * (y - 128)) * 2.0); if (d >= 255) { im->image8[y][x] = 255; } else { diff --git a/src/libImaging/Filter.c b/src/libImaging/Filter.c index 0897ddbfe..fab3b4948 100644 --- a/src/libImaging/Filter.c +++ b/src/libImaging/Filter.c @@ -26,59 +26,59 @@ #include "Imaging.h" - -static inline UINT8 clip8(float in) -{ +static inline UINT8 +clip8(float in) { if (in <= 0.0) { return 0; } if (in >= 255.0) { return 255; } - return (UINT8) in; + return (UINT8)in; } Imaging -ImagingExpand(Imaging imIn, int xmargin, int ymargin, int mode) -{ +ImagingExpand(Imaging imIn, int xmargin, int ymargin, int mode) { Imaging imOut; int x, y; ImagingSectionCookie cookie; if (xmargin < 0 && ymargin < 0) { - return (Imaging) ImagingError_ValueError("bad kernel size"); + return (Imaging)ImagingError_ValueError("bad kernel size"); } imOut = ImagingNewDirty( - imIn->mode, imIn->xsize+2*xmargin, imIn->ysize+2*ymargin); + imIn->mode, imIn->xsize + 2 * xmargin, imIn->ysize + 2 * ymargin); if (!imOut) { return NULL; } -#define EXPAND_LINE(type, image, yin, yout) {\ - for (x = 0; x < xmargin; x++) {\ - imOut->image[yout][x] = imIn->image[yin][0];\ - }\ - for (x = 0; x < imIn->xsize; x++) {\ - imOut->image[yout][x+xmargin] = imIn->image[yin][x];\ - }\ - for (x = 0; x < xmargin; x++) {\ - imOut->image[yout][xmargin+imIn->xsize+x] =\ - imIn->image[yin][imIn->xsize-1];\ - }\ -} +#define EXPAND_LINE(type, image, yin, yout) \ + { \ + for (x = 0; x < xmargin; x++) { \ + imOut->image[yout][x] = imIn->image[yin][0]; \ + } \ + for (x = 0; x < imIn->xsize; x++) { \ + imOut->image[yout][x + xmargin] = imIn->image[yin][x]; \ + } \ + for (x = 0; x < xmargin; x++) { \ + imOut->image[yout][xmargin + imIn->xsize + x] = \ + imIn->image[yin][imIn->xsize - 1]; \ + } \ + } -#define EXPAND(type, image) {\ - for (y = 0; y < ymargin; y++) {\ - EXPAND_LINE(type, image, 0, y);\ - }\ - for (y = 0; y < imIn->ysize; y++) {\ - EXPAND_LINE(type, image, y, y+ymargin);\ - }\ - for (y = 0; y < ymargin; y++) {\ - EXPAND_LINE(type, image, imIn->ysize-1, ymargin+imIn->ysize+y);\ - }\ -} +#define EXPAND(type, image) \ + { \ + for (y = 0; y < ymargin; y++) { \ + EXPAND_LINE(type, image, 0, y); \ + } \ + for (y = 0; y < imIn->ysize; y++) { \ + EXPAND_LINE(type, image, y, y + ymargin); \ + } \ + for (y = 0; y < ymargin; y++) { \ + EXPAND_LINE(type, image, imIn->ysize - 1, ymargin + imIn->ysize + y); \ + } \ + } ImagingSectionEnter(&cookie); if (imIn->image8) { @@ -93,15 +93,11 @@ ImagingExpand(Imaging imIn, int xmargin, int ymargin, int mode) return imOut; } - void -ImagingFilter3x3(Imaging imOut, Imaging im, const float* kernel, - float offset) -{ -#define KERNEL1x3(in0, x, kernel, d) ( \ - _i2f((UINT8) in0[x-d]) * (kernel)[0] + \ - _i2f((UINT8) in0[x]) * (kernel)[1] + \ - _i2f((UINT8) in0[x+d]) * (kernel)[2]) +ImagingFilter3x3(Imaging imOut, Imaging im, const float *kernel, float offset) { +#define KERNEL1x3(in0, x, kernel, d) \ + (_i2f((UINT8)in0[x - d]) * (kernel)[0] + _i2f((UINT8)in0[x]) * (kernel)[1] + \ + _i2f((UINT8)in0[x + d]) * (kernel)[2]) int x = 0, y = 0; @@ -109,86 +105,84 @@ ImagingFilter3x3(Imaging imOut, Imaging im, const float* kernel, if (im->bands == 1) { // Add one time for rounding offset += 0.5; - for (y = 1; y < im->ysize-1; y++) { - UINT8* in_1 = (UINT8*) im->image[y-1]; - UINT8* in0 = (UINT8*) im->image[y]; - UINT8* in1 = (UINT8*) im->image[y+1]; - UINT8* out = (UINT8*) imOut->image[y]; + for (y = 1; y < im->ysize - 1; y++) { + UINT8 *in_1 = (UINT8 *)im->image[y - 1]; + UINT8 *in0 = (UINT8 *)im->image[y]; + UINT8 *in1 = (UINT8 *)im->image[y + 1]; + UINT8 *out = (UINT8 *)imOut->image[y]; out[0] = in0[0]; - for (x = 1; x < im->xsize-1; x++) { + for (x = 1; x < im->xsize - 1; x++) { float ss = offset; ss += KERNEL1x3(in1, x, &kernel[0], 1); ss += KERNEL1x3(in0, x, &kernel[3], 1); ss += KERNEL1x3(in_1, x, &kernel[6], 1); out[x] = clip8(ss); - } + } out[x] = in0[x]; } } else { // Add one time for rounding offset += 0.5; - for (y = 1; y < im->ysize-1; y++) { - UINT8* in_1 = (UINT8*) im->image[y-1]; - UINT8* in0 = (UINT8*) im->image[y]; - UINT8* in1 = (UINT8*) im->image[y+1]; - UINT8* out = (UINT8*) imOut->image[y]; + for (y = 1; y < im->ysize - 1; y++) { + UINT8 *in_1 = (UINT8 *)im->image[y - 1]; + UINT8 *in0 = (UINT8 *)im->image[y]; + UINT8 *in1 = (UINT8 *)im->image[y + 1]; + UINT8 *out = (UINT8 *)imOut->image[y]; memcpy(out, in0, sizeof(UINT32)); if (im->bands == 2) { - for (x = 1; x < im->xsize-1; x++) { + for (x = 1; x < im->xsize - 1; x++) { float ss0 = offset; float ss3 = offset; UINT32 v; - ss0 += KERNEL1x3(in1, x*4+0, &kernel[0], 4); - ss3 += KERNEL1x3(in1, x*4+3, &kernel[0], 4); - ss0 += KERNEL1x3(in0, x*4+0, &kernel[3], 4); - ss3 += KERNEL1x3(in0, x*4+3, &kernel[3], 4); - ss0 += KERNEL1x3(in_1, x*4+0, &kernel[6], 4); - ss3 += KERNEL1x3(in_1, x*4+3, &kernel[6], 4); + ss0 += KERNEL1x3(in1, x * 4 + 0, &kernel[0], 4); + ss3 += KERNEL1x3(in1, x * 4 + 3, &kernel[0], 4); + ss0 += KERNEL1x3(in0, x * 4 + 0, &kernel[3], 4); + ss3 += KERNEL1x3(in0, x * 4 + 3, &kernel[3], 4); + ss0 += KERNEL1x3(in_1, x * 4 + 0, &kernel[6], 4); + ss3 += KERNEL1x3(in_1, x * 4 + 3, &kernel[6], 4); v = MAKE_UINT32(clip8(ss0), 0, 0, clip8(ss3)); memcpy(out + x * sizeof(v), &v, sizeof(v)); } } else if (im->bands == 3) { - for (x = 1; x < im->xsize-1; x++) { + for (x = 1; x < im->xsize - 1; x++) { float ss0 = offset; float ss1 = offset; float ss2 = offset; UINT32 v; - ss0 += KERNEL1x3(in1, x*4+0, &kernel[0], 4); - ss1 += KERNEL1x3(in1, x*4+1, &kernel[0], 4); - ss2 += KERNEL1x3(in1, x*4+2, &kernel[0], 4); - ss0 += KERNEL1x3(in0, x*4+0, &kernel[3], 4); - ss1 += KERNEL1x3(in0, x*4+1, &kernel[3], 4); - ss2 += KERNEL1x3(in0, x*4+2, &kernel[3], 4); - ss0 += KERNEL1x3(in_1, x*4+0, &kernel[6], 4); - ss1 += KERNEL1x3(in_1, x*4+1, &kernel[6], 4); - ss2 += KERNEL1x3(in_1, x*4+2, &kernel[6], 4); - v = MAKE_UINT32( - clip8(ss0), clip8(ss1), clip8(ss2), 0); + ss0 += KERNEL1x3(in1, x * 4 + 0, &kernel[0], 4); + ss1 += KERNEL1x3(in1, x * 4 + 1, &kernel[0], 4); + ss2 += KERNEL1x3(in1, x * 4 + 2, &kernel[0], 4); + ss0 += KERNEL1x3(in0, x * 4 + 0, &kernel[3], 4); + ss1 += KERNEL1x3(in0, x * 4 + 1, &kernel[3], 4); + ss2 += KERNEL1x3(in0, x * 4 + 2, &kernel[3], 4); + ss0 += KERNEL1x3(in_1, x * 4 + 0, &kernel[6], 4); + ss1 += KERNEL1x3(in_1, x * 4 + 1, &kernel[6], 4); + ss2 += KERNEL1x3(in_1, x * 4 + 2, &kernel[6], 4); + v = MAKE_UINT32(clip8(ss0), clip8(ss1), clip8(ss2), 0); memcpy(out + x * sizeof(v), &v, sizeof(v)); } } else if (im->bands == 4) { - for (x = 1; x < im->xsize-1; x++) { + for (x = 1; x < im->xsize - 1; x++) { float ss0 = offset; float ss1 = offset; float ss2 = offset; float ss3 = offset; UINT32 v; - ss0 += KERNEL1x3(in1, x*4+0, &kernel[0], 4); - ss1 += KERNEL1x3(in1, x*4+1, &kernel[0], 4); - ss2 += KERNEL1x3(in1, x*4+2, &kernel[0], 4); - ss3 += KERNEL1x3(in1, x*4+3, &kernel[0], 4); - ss0 += KERNEL1x3(in0, x*4+0, &kernel[3], 4); - ss1 += KERNEL1x3(in0, x*4+1, &kernel[3], 4); - ss2 += KERNEL1x3(in0, x*4+2, &kernel[3], 4); - ss3 += KERNEL1x3(in0, x*4+3, &kernel[3], 4); - ss0 += KERNEL1x3(in_1, x*4+0, &kernel[6], 4); - ss1 += KERNEL1x3(in_1, x*4+1, &kernel[6], 4); - ss2 += KERNEL1x3(in_1, x*4+2, &kernel[6], 4); - ss3 += KERNEL1x3(in_1, x*4+3, &kernel[6], 4); - v = MAKE_UINT32( - clip8(ss0), clip8(ss1), clip8(ss2), clip8(ss3)); + ss0 += KERNEL1x3(in1, x * 4 + 0, &kernel[0], 4); + ss1 += KERNEL1x3(in1, x * 4 + 1, &kernel[0], 4); + ss2 += KERNEL1x3(in1, x * 4 + 2, &kernel[0], 4); + ss3 += KERNEL1x3(in1, x * 4 + 3, &kernel[0], 4); + ss0 += KERNEL1x3(in0, x * 4 + 0, &kernel[3], 4); + ss1 += KERNEL1x3(in0, x * 4 + 1, &kernel[3], 4); + ss2 += KERNEL1x3(in0, x * 4 + 2, &kernel[3], 4); + ss3 += KERNEL1x3(in0, x * 4 + 3, &kernel[3], 4); + ss0 += KERNEL1x3(in_1, x * 4 + 0, &kernel[6], 4); + ss1 += KERNEL1x3(in_1, x * 4 + 1, &kernel[6], 4); + ss2 += KERNEL1x3(in_1, x * 4 + 2, &kernel[6], 4); + ss3 += KERNEL1x3(in_1, x * 4 + 3, &kernel[6], 4); + v = MAKE_UINT32(clip8(ss0), clip8(ss1), clip8(ss2), clip8(ss3)); memcpy(out + x * sizeof(v), &v, sizeof(v)); } } @@ -198,17 +192,13 @@ ImagingFilter3x3(Imaging imOut, Imaging im, const float* kernel, memcpy(imOut->image[y], im->image[y], im->linesize); } - void -ImagingFilter5x5(Imaging imOut, Imaging im, const float* kernel, - float offset) -{ -#define KERNEL1x5(in0, x, kernel, d) ( \ - _i2f((UINT8) in0[x-d-d]) * (kernel)[0] + \ - _i2f((UINT8) in0[x-d]) * (kernel)[1] + \ - _i2f((UINT8) in0[x]) * (kernel)[2] + \ - _i2f((UINT8) in0[x+d]) * (kernel)[3] + \ - _i2f((UINT8) in0[x+d+d]) * (kernel)[4]) +ImagingFilter5x5(Imaging imOut, Imaging im, const float *kernel, float offset) { +#define KERNEL1x5(in0, x, kernel, d) \ + (_i2f((UINT8)in0[x - d - d]) * (kernel)[0] + \ + _i2f((UINT8)in0[x - d]) * (kernel)[1] + _i2f((UINT8)in0[x]) * (kernel)[2] + \ + _i2f((UINT8)in0[x + d]) * (kernel)[3] + \ + _i2f((UINT8)in0[x + d + d]) * (kernel)[4]) int x = 0, y = 0; @@ -217,17 +207,17 @@ ImagingFilter5x5(Imaging imOut, Imaging im, const float* kernel, if (im->bands == 1) { // Add one time for rounding offset += 0.5; - for (y = 2; y < im->ysize-2; y++) { - UINT8* in_2 = (UINT8*) im->image[y-2]; - UINT8* in_1 = (UINT8*) im->image[y-1]; - UINT8* in0 = (UINT8*) im->image[y]; - UINT8* in1 = (UINT8*) im->image[y+1]; - UINT8* in2 = (UINT8*) im->image[y+2]; - UINT8* out = (UINT8*) imOut->image[y]; + for (y = 2; y < im->ysize - 2; y++) { + UINT8 *in_2 = (UINT8 *)im->image[y - 2]; + UINT8 *in_1 = (UINT8 *)im->image[y - 1]; + UINT8 *in0 = (UINT8 *)im->image[y]; + UINT8 *in1 = (UINT8 *)im->image[y + 1]; + UINT8 *in2 = (UINT8 *)im->image[y + 2]; + UINT8 *out = (UINT8 *)imOut->image[y]; out[0] = in0[0]; out[1] = in0[1]; - for (x = 2; x < im->xsize-2; x++) { + for (x = 2; x < im->xsize - 2; x++) { float ss = offset; ss += KERNEL1x5(in2, x, &kernel[0], 1); ss += KERNEL1x5(in1, x, &kernel[5], 1); @@ -236,112 +226,109 @@ ImagingFilter5x5(Imaging imOut, Imaging im, const float* kernel, ss += KERNEL1x5(in_2, x, &kernel[20], 1); out[x] = clip8(ss); } - out[x+0] = in0[x+0]; - out[x+1] = in0[x+1]; + out[x + 0] = in0[x + 0]; + out[x + 1] = in0[x + 1]; } } else { // Add one time for rounding offset += 0.5; - for (y = 2; y < im->ysize-2; y++) { - UINT8* in_2 = (UINT8*) im->image[y-2]; - UINT8* in_1 = (UINT8*) im->image[y-1]; - UINT8* in0 = (UINT8*) im->image[y]; - UINT8* in1 = (UINT8*) im->image[y+1]; - UINT8* in2 = (UINT8*) im->image[y+2]; - UINT8* out = (UINT8*) imOut->image[y]; + for (y = 2; y < im->ysize - 2; y++) { + UINT8 *in_2 = (UINT8 *)im->image[y - 2]; + UINT8 *in_1 = (UINT8 *)im->image[y - 1]; + UINT8 *in0 = (UINT8 *)im->image[y]; + UINT8 *in1 = (UINT8 *)im->image[y + 1]; + UINT8 *in2 = (UINT8 *)im->image[y + 2]; + UINT8 *out = (UINT8 *)imOut->image[y]; memcpy(out, in0, sizeof(UINT32) * 2); if (im->bands == 2) { - for (x = 2; x < im->xsize-2; x++) { + for (x = 2; x < im->xsize - 2; x++) { float ss0 = offset; float ss3 = offset; UINT32 v; - ss0 += KERNEL1x5(in2, x*4+0, &kernel[0], 4); - ss3 += KERNEL1x5(in2, x*4+3, &kernel[0], 4); - ss0 += KERNEL1x5(in1, x*4+0, &kernel[5], 4); - ss3 += KERNEL1x5(in1, x*4+3, &kernel[5], 4); - ss0 += KERNEL1x5(in0, x*4+0, &kernel[10], 4); - ss3 += KERNEL1x5(in0, x*4+3, &kernel[10], 4); - ss0 += KERNEL1x5(in_1, x*4+0, &kernel[15], 4); - ss3 += KERNEL1x5(in_1, x*4+3, &kernel[15], 4); - ss0 += KERNEL1x5(in_2, x*4+0, &kernel[20], 4); - ss3 += KERNEL1x5(in_2, x*4+3, &kernel[20], 4); + ss0 += KERNEL1x5(in2, x * 4 + 0, &kernel[0], 4); + ss3 += KERNEL1x5(in2, x * 4 + 3, &kernel[0], 4); + ss0 += KERNEL1x5(in1, x * 4 + 0, &kernel[5], 4); + ss3 += KERNEL1x5(in1, x * 4 + 3, &kernel[5], 4); + ss0 += KERNEL1x5(in0, x * 4 + 0, &kernel[10], 4); + ss3 += KERNEL1x5(in0, x * 4 + 3, &kernel[10], 4); + ss0 += KERNEL1x5(in_1, x * 4 + 0, &kernel[15], 4); + ss3 += KERNEL1x5(in_1, x * 4 + 3, &kernel[15], 4); + ss0 += KERNEL1x5(in_2, x * 4 + 0, &kernel[20], 4); + ss3 += KERNEL1x5(in_2, x * 4 + 3, &kernel[20], 4); v = MAKE_UINT32(clip8(ss0), 0, 0, clip8(ss3)); memcpy(out + x * sizeof(v), &v, sizeof(v)); } } else if (im->bands == 3) { - for (x = 2; x < im->xsize-2; x++) { + for (x = 2; x < im->xsize - 2; x++) { float ss0 = offset; float ss1 = offset; float ss2 = offset; UINT32 v; - ss0 += KERNEL1x5(in2, x*4+0, &kernel[0], 4); - ss1 += KERNEL1x5(in2, x*4+1, &kernel[0], 4); - ss2 += KERNEL1x5(in2, x*4+2, &kernel[0], 4); - ss0 += KERNEL1x5(in1, x*4+0, &kernel[5], 4); - ss1 += KERNEL1x5(in1, x*4+1, &kernel[5], 4); - ss2 += KERNEL1x5(in1, x*4+2, &kernel[5], 4); - ss0 += KERNEL1x5(in0, x*4+0, &kernel[10], 4); - ss1 += KERNEL1x5(in0, x*4+1, &kernel[10], 4); - ss2 += KERNEL1x5(in0, x*4+2, &kernel[10], 4); - ss0 += KERNEL1x5(in_1, x*4+0, &kernel[15], 4); - ss1 += KERNEL1x5(in_1, x*4+1, &kernel[15], 4); - ss2 += KERNEL1x5(in_1, x*4+2, &kernel[15], 4); - ss0 += KERNEL1x5(in_2, x*4+0, &kernel[20], 4); - ss1 += KERNEL1x5(in_2, x*4+1, &kernel[20], 4); - ss2 += KERNEL1x5(in_2, x*4+2, &kernel[20], 4); - v = MAKE_UINT32( - clip8(ss0), clip8(ss1), clip8(ss2), 0); + ss0 += KERNEL1x5(in2, x * 4 + 0, &kernel[0], 4); + ss1 += KERNEL1x5(in2, x * 4 + 1, &kernel[0], 4); + ss2 += KERNEL1x5(in2, x * 4 + 2, &kernel[0], 4); + ss0 += KERNEL1x5(in1, x * 4 + 0, &kernel[5], 4); + ss1 += KERNEL1x5(in1, x * 4 + 1, &kernel[5], 4); + ss2 += KERNEL1x5(in1, x * 4 + 2, &kernel[5], 4); + ss0 += KERNEL1x5(in0, x * 4 + 0, &kernel[10], 4); + ss1 += KERNEL1x5(in0, x * 4 + 1, &kernel[10], 4); + ss2 += KERNEL1x5(in0, x * 4 + 2, &kernel[10], 4); + ss0 += KERNEL1x5(in_1, x * 4 + 0, &kernel[15], 4); + ss1 += KERNEL1x5(in_1, x * 4 + 1, &kernel[15], 4); + ss2 += KERNEL1x5(in_1, x * 4 + 2, &kernel[15], 4); + ss0 += KERNEL1x5(in_2, x * 4 + 0, &kernel[20], 4); + ss1 += KERNEL1x5(in_2, x * 4 + 1, &kernel[20], 4); + ss2 += KERNEL1x5(in_2, x * 4 + 2, &kernel[20], 4); + v = MAKE_UINT32(clip8(ss0), clip8(ss1), clip8(ss2), 0); memcpy(out + x * sizeof(v), &v, sizeof(v)); } } else if (im->bands == 4) { - for (x = 2; x < im->xsize-2; x++) { + for (x = 2; x < im->xsize - 2; x++) { float ss0 = offset; float ss1 = offset; float ss2 = offset; float ss3 = offset; UINT32 v; - ss0 += KERNEL1x5(in2, x*4+0, &kernel[0], 4); - ss1 += KERNEL1x5(in2, x*4+1, &kernel[0], 4); - ss2 += KERNEL1x5(in2, x*4+2, &kernel[0], 4); - ss3 += KERNEL1x5(in2, x*4+3, &kernel[0], 4); - ss0 += KERNEL1x5(in1, x*4+0, &kernel[5], 4); - ss1 += KERNEL1x5(in1, x*4+1, &kernel[5], 4); - ss2 += KERNEL1x5(in1, x*4+2, &kernel[5], 4); - ss3 += KERNEL1x5(in1, x*4+3, &kernel[5], 4); - ss0 += KERNEL1x5(in0, x*4+0, &kernel[10], 4); - ss1 += KERNEL1x5(in0, x*4+1, &kernel[10], 4); - ss2 += KERNEL1x5(in0, x*4+2, &kernel[10], 4); - ss3 += KERNEL1x5(in0, x*4+3, &kernel[10], 4); - ss0 += KERNEL1x5(in_1, x*4+0, &kernel[15], 4); - ss1 += KERNEL1x5(in_1, x*4+1, &kernel[15], 4); - ss2 += KERNEL1x5(in_1, x*4+2, &kernel[15], 4); - ss3 += KERNEL1x5(in_1, x*4+3, &kernel[15], 4); - ss0 += KERNEL1x5(in_2, x*4+0, &kernel[20], 4); - ss1 += KERNEL1x5(in_2, x*4+1, &kernel[20], 4); - ss2 += KERNEL1x5(in_2, x*4+2, &kernel[20], 4); - ss3 += KERNEL1x5(in_2, x*4+3, &kernel[20], 4); - v = MAKE_UINT32( - clip8(ss0), clip8(ss1), clip8(ss2), clip8(ss3)); + ss0 += KERNEL1x5(in2, x * 4 + 0, &kernel[0], 4); + ss1 += KERNEL1x5(in2, x * 4 + 1, &kernel[0], 4); + ss2 += KERNEL1x5(in2, x * 4 + 2, &kernel[0], 4); + ss3 += KERNEL1x5(in2, x * 4 + 3, &kernel[0], 4); + ss0 += KERNEL1x5(in1, x * 4 + 0, &kernel[5], 4); + ss1 += KERNEL1x5(in1, x * 4 + 1, &kernel[5], 4); + ss2 += KERNEL1x5(in1, x * 4 + 2, &kernel[5], 4); + ss3 += KERNEL1x5(in1, x * 4 + 3, &kernel[5], 4); + ss0 += KERNEL1x5(in0, x * 4 + 0, &kernel[10], 4); + ss1 += KERNEL1x5(in0, x * 4 + 1, &kernel[10], 4); + ss2 += KERNEL1x5(in0, x * 4 + 2, &kernel[10], 4); + ss3 += KERNEL1x5(in0, x * 4 + 3, &kernel[10], 4); + ss0 += KERNEL1x5(in_1, x * 4 + 0, &kernel[15], 4); + ss1 += KERNEL1x5(in_1, x * 4 + 1, &kernel[15], 4); + ss2 += KERNEL1x5(in_1, x * 4 + 2, &kernel[15], 4); + ss3 += KERNEL1x5(in_1, x * 4 + 3, &kernel[15], 4); + ss0 += KERNEL1x5(in_2, x * 4 + 0, &kernel[20], 4); + ss1 += KERNEL1x5(in_2, x * 4 + 1, &kernel[20], 4); + ss2 += KERNEL1x5(in_2, x * 4 + 2, &kernel[20], 4); + ss3 += KERNEL1x5(in_2, x * 4 + 3, &kernel[20], 4); + v = MAKE_UINT32(clip8(ss0), clip8(ss1), clip8(ss2), clip8(ss3)); memcpy(out + x * sizeof(v), &v, sizeof(v)); } } - memcpy(out + x * sizeof(UINT32), in0 + x * sizeof(UINT32), sizeof(UINT32) * 2); + memcpy( + out + x * sizeof(UINT32), in0 + x * sizeof(UINT32), sizeof(UINT32) * 2); } } memcpy(imOut->image[y], im->image[y], im->linesize); - memcpy(imOut->image[y+1], im->image[y+1], im->linesize); + memcpy(imOut->image[y + 1], im->image[y + 1], im->linesize); } Imaging -ImagingFilter(Imaging im, int xsize, int ysize, const FLOAT32* kernel, - FLOAT32 offset) -{ +ImagingFilter(Imaging im, int xsize, int ysize, const FLOAT32 *kernel, FLOAT32 offset) { Imaging imOut; ImagingSectionCookie cookie; - if ( ! im || im->type != IMAGING_TYPE_UINT8) { - return (Imaging) ImagingError_ModeError(); + if (!im || im->type != IMAGING_TYPE_UINT8) { + return (Imaging)ImagingError_ModeError(); } if (im->xsize < xsize || im->ysize < ysize) { @@ -349,7 +336,7 @@ ImagingFilter(Imaging im, int xsize, int ysize, const FLOAT32* kernel, } if ((xsize != 3 && xsize != 5) || xsize != ysize) { - return (Imaging) ImagingError_ValueError("bad kernel size"); + return (Imaging)ImagingError_ValueError("bad kernel size"); } imOut = ImagingNewDirty(im->mode, im->xsize, im->ysize); @@ -368,4 +355,3 @@ ImagingFilter(Imaging im, int xsize, int ysize, const FLOAT32* kernel, ImagingSectionLeave(&cookie); return imOut; } - diff --git a/src/libImaging/FliDecode.c b/src/libImaging/FliDecode.c index 84508013d..e9000fc99 100644 --- a/src/libImaging/FliDecode.c +++ b/src/libImaging/FliDecode.c @@ -14,26 +14,21 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" +#define I16(ptr) ((ptr)[0] + ((ptr)[1] << 8)) -#define I16(ptr)\ - ((ptr)[0] + ((ptr)[1] << 8)) +#define I32(ptr) ((ptr)[0] + ((ptr)[1] << 8) + ((ptr)[2] << 16) + ((ptr)[3] << 24)) -#define I32(ptr)\ - ((ptr)[0] + ((ptr)[1] << 8) + ((ptr)[2] << 16) + ((ptr)[3] << 24)) - -#define ERR_IF_DATA_OOB(offset) \ - if ((data + (offset)) > ptr + bytes) {\ - state->errcode = IMAGING_CODEC_OVERRUN; \ - return -1; \ - } +#define ERR_IF_DATA_OOB(offset) \ + if ((data + (offset)) > ptr + bytes) { \ + state->errcode = IMAGING_CODEC_OVERRUN; \ + return -1; \ + } int -ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ - UINT8* ptr; +ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { + UINT8 *ptr; int framesize; int c, chunks, advance; int l, lines; @@ -62,36 +57,39 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt state->errcode = IMAGING_CODEC_OVERRUN; return -1; } - if (I16(ptr+4) != 0xF1FA) { + if (I16(ptr + 4) != 0xF1FA) { state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } - chunks = I16(ptr+6); + chunks = I16(ptr + 6); ptr += 16; bytes -= 16; /* Process subchunks */ for (c = 0; c < chunks; c++) { - UINT8* data; + UINT8 *data; if (bytes < 10) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } data = ptr + 6; - switch (I16(ptr+4)) { - case 4: case 11: + switch (I16(ptr + 4)) { + case 4: + case 11: /* FLI COLOR chunk */ break; /* ignored; handled by Python code */ case 7: /* FLI SS2 chunk (word delta) */ /* OOB ok, we've got 4 bytes min on entry */ - lines = I16(data); data += 2; + lines = I16(data); + data += 2; for (l = y = 0; l < lines && y < state->ysize; l++, y++) { - UINT8* local_buf = (UINT8*) im->image[y]; + UINT8 *local_buf = (UINT8 *)im->image[y]; int p, packets; ERR_IF_DATA_OOB(2) - packets = I16(data); data += 2; + packets = I16(data); + data += 2; while (packets & 0x8000) { /* flag word */ if (packets & 0x4000) { @@ -100,20 +98,21 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt state->errcode = IMAGING_CODEC_OVERRUN; return -1; } - local_buf = (UINT8*) im->image[y]; + local_buf = (UINT8 *)im->image[y]; } else { /* store last byte (used if line width is odd) */ - local_buf[state->xsize-1] = (UINT8) packets; + local_buf[state->xsize - 1] = (UINT8)packets; } ERR_IF_DATA_OOB(2) - packets = I16(data); data += 2; + packets = I16(data); + data += 2; } for (p = x = 0; p < packets; p++) { ERR_IF_DATA_OOB(2) x += data[0]; /* pixel skip */ if (data[1] >= 128) { ERR_IF_DATA_OOB(4) - i = 256-data[1]; /* run */ + i = 256 - data[1]; /* run */ if (x + i + i > state->xsize) { break; } @@ -123,11 +122,11 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt } data += 2 + 2; } else { - i = 2 * (int) data[1]; /* chunk */ + i = 2 * (int)data[1]; /* chunk */ if (x + i > state->xsize) { break; } - ERR_IF_DATA_OOB(2+i) + ERR_IF_DATA_OOB(2 + i) memcpy(local_buf + x, data + 2, i); data += 2 + i; x += i; @@ -146,16 +145,18 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt case 12: /* FLI LC chunk (byte delta) */ /* OOB Check ok, we have 4 bytes min here */ - y = I16(data); ymax = y + I16(data+2); data += 4; + y = I16(data); + ymax = y + I16(data + 2); + data += 4; for (; y < ymax && y < state->ysize; y++) { - UINT8* out = (UINT8*) im->image[y]; - ERR_IF_DATA_OOB(1) + UINT8 *out = (UINT8 *)im->image[y]; + ERR_IF_DATA_OOB(1) int p, packets = *data++; for (p = x = 0; p < packets; p++, x += i) { ERR_IF_DATA_OOB(2) x += data[0]; /* skip pixels */ if (data[1] & 0x80) { - i = 256-data[1]; /* run */ + i = 256 - data[1]; /* run */ if (x + i > state->xsize) { break; } @@ -167,7 +168,7 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt if (x + i > state->xsize) { break; } - ERR_IF_DATA_OOB(2+i) + ERR_IF_DATA_OOB(2 + i) memcpy(out + x, data + 2, i); data += i + 2; } @@ -192,7 +193,7 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt /* FLI BRUN chunk */ /* OOB, ok, we've got 4 bytes min on entry */ for (y = 0; y < state->ysize; y++) { - UINT8* out = (UINT8*) im->image[y]; + UINT8 *out = (UINT8 *)im->image[y]; data += 1; /* ignore packetcount byte */ for (x = 0; x < state->xsize; x += i) { ERR_IF_DATA_OOB(2) @@ -201,7 +202,7 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt if (x + i > state->xsize) { break; /* safety first */ } - ERR_IF_DATA_OOB(i+1) + ERR_IF_DATA_OOB(i + 1) memcpy(out + x, data + 1, i); data += i + 1; } else { @@ -222,12 +223,12 @@ ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt break; case 16: /* COPY chunk */ - if (state->xsize > bytes/state->ysize) { + if (state->xsize > bytes / state->ysize) { /* not enough data for frame */ return ptr - buf; /* bytes consumed */ } for (y = 0; y < state->ysize; y++) { - UINT8* local_buf = (UINT8*) im->image[y]; + UINT8 *local_buf = (UINT8 *)im->image[y]; memcpy(local_buf, data, state->xsize); data += state->xsize; } diff --git a/src/libImaging/Geometry.c b/src/libImaging/Geometry.c index 06d0cf24d..0c5915792 100644 --- a/src/libImaging/Geometry.c +++ b/src/libImaging/Geometry.c @@ -15,28 +15,27 @@ /* Transpose operations */ Imaging -ImagingFlipLeftRight(Imaging imOut, Imaging imIn) -{ +ImagingFlipLeftRight(Imaging imOut, Imaging imIn) { ImagingSectionCookie cookie; int x, y, xr; if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize) { - return (Imaging) ImagingError_Mismatch(); + return (Imaging)ImagingError_Mismatch(); } ImagingCopyPalette(imOut, imIn); -#define FLIP_LEFT_RIGHT(INT, image) \ - for (y = 0; y < imIn->ysize; y++) { \ - INT* in = (INT *)imIn->image[y]; \ - INT* out = (INT *)imOut->image[y]; \ - xr = imIn->xsize-1; \ +#define FLIP_LEFT_RIGHT(INT, image) \ + for (y = 0; y < imIn->ysize; y++) { \ + INT *in = (INT *)imIn->image[y]; \ + INT *out = (INT *)imOut->image[y]; \ + xr = imIn->xsize - 1; \ for (x = 0; x < imIn->xsize; x++, xr--) { \ - out[xr] = in[x]; \ - } \ + out[xr] = in[x]; \ + } \ } ImagingSectionEnter(&cookie); @@ -58,18 +57,16 @@ ImagingFlipLeftRight(Imaging imOut, Imaging imIn) return imOut; } - Imaging -ImagingFlipTopBottom(Imaging imOut, Imaging imIn) -{ +ImagingFlipTopBottom(Imaging imOut, Imaging imIn) { ImagingSectionCookie cookie; int y, yr; if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize) { - return (Imaging) ImagingError_Mismatch(); + return (Imaging)ImagingError_Mismatch(); } ImagingCopyPalette(imOut, imIn); @@ -86,43 +83,45 @@ ImagingFlipTopBottom(Imaging imOut, Imaging imIn) return imOut; } - Imaging -ImagingRotate90(Imaging imOut, Imaging imIn) -{ +ImagingRotate90(Imaging imOut, Imaging imIn) { ImagingSectionCookie cookie; int x, y, xx, yy, xr, xxsize, yysize; int xxx, yyy, xxxsize, yyysize; if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize) { - return (Imaging) ImagingError_Mismatch(); + return (Imaging)ImagingError_Mismatch(); } ImagingCopyPalette(imOut, imIn); -#define ROTATE_90(INT, image) \ - for (y = 0; y < imIn->ysize; y += ROTATE_CHUNK) { \ - for (x = 0; x < imIn->xsize; x += ROTATE_CHUNK) { \ +#define ROTATE_90(INT, image) \ + for (y = 0; y < imIn->ysize; y += ROTATE_CHUNK) { \ + for (x = 0; x < imIn->xsize; x += ROTATE_CHUNK) { \ yysize = y + ROTATE_CHUNK < imIn->ysize ? y + ROTATE_CHUNK : imIn->ysize; \ xxsize = x + ROTATE_CHUNK < imIn->xsize ? x + ROTATE_CHUNK : imIn->xsize; \ - for (yy = y; yy < yysize; yy += ROTATE_SMALL_CHUNK) { \ - for (xx = x; xx < xxsize; xx += ROTATE_SMALL_CHUNK) { \ - yyysize = yy + ROTATE_SMALL_CHUNK < imIn->ysize ? yy + ROTATE_SMALL_CHUNK : imIn->ysize; \ - xxxsize = xx + ROTATE_SMALL_CHUNK < imIn->xsize ? xx + ROTATE_SMALL_CHUNK : imIn->xsize; \ - for (yyy = yy; yyy < yyysize; yyy++) { \ - INT* in = (INT *)imIn->image[yyy]; \ - xr = imIn->xsize - 1 - xx; \ - for (xxx = xx; xxx < xxxsize; xxx++, xr--) { \ - INT* out = (INT *)imOut->image[xr]; \ - out[yyy] = in[xxx]; \ - } \ - } \ - } \ - } \ - } \ + for (yy = y; yy < yysize; yy += ROTATE_SMALL_CHUNK) { \ + for (xx = x; xx < xxsize; xx += ROTATE_SMALL_CHUNK) { \ + yyysize = yy + ROTATE_SMALL_CHUNK < imIn->ysize \ + ? yy + ROTATE_SMALL_CHUNK \ + : imIn->ysize; \ + xxxsize = xx + ROTATE_SMALL_CHUNK < imIn->xsize \ + ? xx + ROTATE_SMALL_CHUNK \ + : imIn->xsize; \ + for (yyy = yy; yyy < yyysize; yyy++) { \ + INT *in = (INT *)imIn->image[yyy]; \ + xr = imIn->xsize - 1 - xx; \ + for (xxx = xx; xxx < xxxsize; xxx++, xr--) { \ + INT *out = (INT *)imOut->image[xr]; \ + out[yyy] = in[xxx]; \ + } \ + } \ + } \ + } \ + } \ } ImagingSectionEnter(&cookie); @@ -144,42 +143,44 @@ ImagingRotate90(Imaging imOut, Imaging imIn) return imOut; } - Imaging -ImagingTranspose(Imaging imOut, Imaging imIn) -{ +ImagingTranspose(Imaging imOut, Imaging imIn) { ImagingSectionCookie cookie; int x, y, xx, yy, xxsize, yysize; int xxx, yyy, xxxsize, yyysize; if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize) { - return (Imaging) ImagingError_Mismatch(); + return (Imaging)ImagingError_Mismatch(); } ImagingCopyPalette(imOut, imIn); -#define TRANSPOSE(INT, image) \ - for (y = 0; y < imIn->ysize; y += ROTATE_CHUNK) { \ - for (x = 0; x < imIn->xsize; x += ROTATE_CHUNK) { \ +#define TRANSPOSE(INT, image) \ + for (y = 0; y < imIn->ysize; y += ROTATE_CHUNK) { \ + for (x = 0; x < imIn->xsize; x += ROTATE_CHUNK) { \ yysize = y + ROTATE_CHUNK < imIn->ysize ? y + ROTATE_CHUNK : imIn->ysize; \ xxsize = x + ROTATE_CHUNK < imIn->xsize ? x + ROTATE_CHUNK : imIn->xsize; \ - for (yy = y; yy < yysize; yy += ROTATE_SMALL_CHUNK) { \ - for (xx = x; xx < xxsize; xx += ROTATE_SMALL_CHUNK) { \ - yyysize = yy + ROTATE_SMALL_CHUNK < imIn->ysize ? yy + ROTATE_SMALL_CHUNK : imIn->ysize; \ - xxxsize = xx + ROTATE_SMALL_CHUNK < imIn->xsize ? xx + ROTATE_SMALL_CHUNK : imIn->xsize; \ - for (yyy = yy; yyy < yyysize; yyy++) { \ - INT* in = (INT *)imIn->image[yyy]; \ - for (xxx = xx; xxx < xxxsize; xxx++) { \ - INT* out = (INT *)imOut->image[xxx]; \ - out[yyy] = in[xxx]; \ - } \ - } \ - } \ - } \ - } \ + for (yy = y; yy < yysize; yy += ROTATE_SMALL_CHUNK) { \ + for (xx = x; xx < xxsize; xx += ROTATE_SMALL_CHUNK) { \ + yyysize = yy + ROTATE_SMALL_CHUNK < imIn->ysize \ + ? yy + ROTATE_SMALL_CHUNK \ + : imIn->ysize; \ + xxxsize = xx + ROTATE_SMALL_CHUNK < imIn->xsize \ + ? xx + ROTATE_SMALL_CHUNK \ + : imIn->xsize; \ + for (yyy = yy; yyy < yyysize; yyy++) { \ + INT *in = (INT *)imIn->image[yyy]; \ + for (xxx = xx; xxx < xxxsize; xxx++) { \ + INT *out = (INT *)imOut->image[xxx]; \ + out[yyy] = in[xxx]; \ + } \ + } \ + } \ + } \ + } \ } ImagingSectionEnter(&cookie); @@ -201,44 +202,46 @@ ImagingTranspose(Imaging imOut, Imaging imIn) return imOut; } - Imaging -ImagingTransverse(Imaging imOut, Imaging imIn) -{ +ImagingTransverse(Imaging imOut, Imaging imIn) { ImagingSectionCookie cookie; int x, y, xr, yr, xx, yy, xxsize, yysize; int xxx, yyy, xxxsize, yyysize; if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize) { - return (Imaging) ImagingError_Mismatch(); + return (Imaging)ImagingError_Mismatch(); } ImagingCopyPalette(imOut, imIn); -#define TRANSVERSE(INT, image) \ - for (y = 0; y < imIn->ysize; y += ROTATE_CHUNK) { \ - for (x = 0; x < imIn->xsize; x += ROTATE_CHUNK) { \ +#define TRANSVERSE(INT, image) \ + for (y = 0; y < imIn->ysize; y += ROTATE_CHUNK) { \ + for (x = 0; x < imIn->xsize; x += ROTATE_CHUNK) { \ yysize = y + ROTATE_CHUNK < imIn->ysize ? y + ROTATE_CHUNK : imIn->ysize; \ xxsize = x + ROTATE_CHUNK < imIn->xsize ? x + ROTATE_CHUNK : imIn->xsize; \ - for (yy = y; yy < yysize; yy += ROTATE_SMALL_CHUNK) { \ - for (xx = x; xx < xxsize; xx += ROTATE_SMALL_CHUNK) { \ - yyysize = yy + ROTATE_SMALL_CHUNK < imIn->ysize ? yy + ROTATE_SMALL_CHUNK : imIn->ysize; \ - xxxsize = xx + ROTATE_SMALL_CHUNK < imIn->xsize ? xx + ROTATE_SMALL_CHUNK : imIn->xsize; \ - yr = imIn->ysize - 1 - yy; \ - for (yyy = yy; yyy < yyysize; yyy++, yr--) { \ - INT* in = (INT *)imIn->image[yyy]; \ - xr = imIn->xsize - 1 - xx; \ - for (xxx = xx; xxx < xxxsize; xxx++, xr--) { \ - INT* out = (INT *)imOut->image[xr]; \ - out[yr] = in[xxx]; \ - } \ - } \ - } \ - } \ - } \ + for (yy = y; yy < yysize; yy += ROTATE_SMALL_CHUNK) { \ + for (xx = x; xx < xxsize; xx += ROTATE_SMALL_CHUNK) { \ + yyysize = yy + ROTATE_SMALL_CHUNK < imIn->ysize \ + ? yy + ROTATE_SMALL_CHUNK \ + : imIn->ysize; \ + xxxsize = xx + ROTATE_SMALL_CHUNK < imIn->xsize \ + ? xx + ROTATE_SMALL_CHUNK \ + : imIn->xsize; \ + yr = imIn->ysize - 1 - yy; \ + for (yyy = yy; yyy < yyysize; yyy++, yr--) { \ + INT *in = (INT *)imIn->image[yyy]; \ + xr = imIn->xsize - 1 - xx; \ + for (xxx = xx; xxx < xxxsize; xxx++, xr--) { \ + INT *out = (INT *)imOut->image[xr]; \ + out[yr] = in[xxx]; \ + } \ + } \ + } \ + } \ + } \ } ImagingSectionEnter(&cookie); @@ -260,35 +263,33 @@ ImagingTransverse(Imaging imOut, Imaging imIn) return imOut; } - Imaging -ImagingRotate180(Imaging imOut, Imaging imIn) -{ +ImagingRotate180(Imaging imOut, Imaging imIn) { ImagingSectionCookie cookie; int x, y, xr, yr; if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (imIn->xsize != imOut->xsize || imIn->ysize != imOut->ysize) { - return (Imaging) ImagingError_Mismatch(); + return (Imaging)ImagingError_Mismatch(); } ImagingCopyPalette(imOut, imIn); -#define ROTATE_180(INT, image) \ - for (y = 0; y < imIn->ysize; y++, yr--) { \ - INT* in = (INT *)imIn->image[y]; \ - INT* out = (INT *)imOut->image[yr]; \ - xr = imIn->xsize-1; \ +#define ROTATE_180(INT, image) \ + for (y = 0; y < imIn->ysize; y++, yr--) { \ + INT *in = (INT *)imIn->image[y]; \ + INT *out = (INT *)imOut->image[yr]; \ + xr = imIn->xsize - 1; \ for (x = 0; x < imIn->xsize; x++, xr--) { \ - out[xr] = in[x]; \ - } \ + out[xr] = in[x]; \ + } \ } ImagingSectionEnter(&cookie); - yr = imIn->ysize-1; + yr = imIn->ysize - 1; if (imIn->image8) { if (strncmp(imIn->mode, "I;16", 4) == 0) { ROTATE_180(UINT16, image8) @@ -306,43 +307,45 @@ ImagingRotate180(Imaging imOut, Imaging imIn) return imOut; } - Imaging -ImagingRotate270(Imaging imOut, Imaging imIn) -{ +ImagingRotate270(Imaging imOut, Imaging imIn) { ImagingSectionCookie cookie; int x, y, xx, yy, yr, xxsize, yysize; int xxx, yyy, xxxsize, yyysize; if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (imIn->xsize != imOut->ysize || imIn->ysize != imOut->xsize) { - return (Imaging) ImagingError_Mismatch(); + return (Imaging)ImagingError_Mismatch(); } ImagingCopyPalette(imOut, imIn); -#define ROTATE_270(INT, image) \ - for (y = 0; y < imIn->ysize; y += ROTATE_CHUNK) { \ - for (x = 0; x < imIn->xsize; x += ROTATE_CHUNK) { \ +#define ROTATE_270(INT, image) \ + for (y = 0; y < imIn->ysize; y += ROTATE_CHUNK) { \ + for (x = 0; x < imIn->xsize; x += ROTATE_CHUNK) { \ yysize = y + ROTATE_CHUNK < imIn->ysize ? y + ROTATE_CHUNK : imIn->ysize; \ xxsize = x + ROTATE_CHUNK < imIn->xsize ? x + ROTATE_CHUNK : imIn->xsize; \ - for (yy = y; yy < yysize; yy += ROTATE_SMALL_CHUNK) { \ - for (xx = x; xx < xxsize; xx += ROTATE_SMALL_CHUNK) { \ - yyysize = yy + ROTATE_SMALL_CHUNK < imIn->ysize ? yy + ROTATE_SMALL_CHUNK : imIn->ysize; \ - xxxsize = xx + ROTATE_SMALL_CHUNK < imIn->xsize ? xx + ROTATE_SMALL_CHUNK : imIn->xsize; \ - yr = imIn->ysize - 1 - yy; \ - for (yyy = yy; yyy < yyysize; yyy++, yr--) { \ - INT* in = (INT *)imIn->image[yyy]; \ - for (xxx = xx; xxx < xxxsize; xxx++) { \ - INT* out = (INT *)imOut->image[xxx]; \ - out[yr] = in[xxx]; \ - } \ - } \ - } \ - } \ - } \ + for (yy = y; yy < yysize; yy += ROTATE_SMALL_CHUNK) { \ + for (xx = x; xx < xxsize; xx += ROTATE_SMALL_CHUNK) { \ + yyysize = yy + ROTATE_SMALL_CHUNK < imIn->ysize \ + ? yy + ROTATE_SMALL_CHUNK \ + : imIn->ysize; \ + xxxsize = xx + ROTATE_SMALL_CHUNK < imIn->xsize \ + ? xx + ROTATE_SMALL_CHUNK \ + : imIn->xsize; \ + yr = imIn->ysize - 1 - yy; \ + for (yyy = yy; yyy < yyysize; yyy++, yr--) { \ + INT *in = (INT *)imIn->image[yyy]; \ + for (xxx = xx; xxx < xxxsize; xxx++) { \ + INT *out = (INT *)imOut->image[xxx]; \ + out[yr] = in[xxx]; \ + } \ + } \ + } \ + } \ + } \ } ImagingSectionEnter(&cookie); @@ -364,63 +367,74 @@ ImagingRotate270(Imaging imOut, Imaging imIn) return imOut; } - /* -------------------------------------------------------------------- */ /* Transforms */ /* transform primitives (ImagingTransformMap) */ static int -affine_transform(double* xout, double* yout, int x, int y, void* data) -{ +affine_transform(double *xout, double *yout, int x, int y, void *data) { /* full moon tonight. your compiler will generate bogus code for simple expressions, unless you reorganize the code, or install Service Pack 3 */ - double* a = (double*) data; - double a0 = a[0]; double a1 = a[1]; double a2 = a[2]; - double a3 = a[3]; double a4 = a[4]; double a5 = a[5]; + double *a = (double *)data; + double a0 = a[0]; + double a1 = a[1]; + double a2 = a[2]; + double a3 = a[3]; + double a4 = a[4]; + double a5 = a[5]; double xin = x + 0.5; double yin = y + 0.5; - xout[0] = a0*xin + a1*yin + a2; - yout[0] = a3*xin + a4*yin + a5; + xout[0] = a0 * xin + a1 * yin + a2; + yout[0] = a3 * xin + a4 * yin + a5; return 1; } static int -perspective_transform(double* xout, double* yout, int x, int y, void* data) -{ - double* a = (double*) data; - double a0 = a[0]; double a1 = a[1]; double a2 = a[2]; - double a3 = a[3]; double a4 = a[4]; double a5 = a[5]; - double a6 = a[6]; double a7 = a[7]; +perspective_transform(double *xout, double *yout, int x, int y, void *data) { + double *a = (double *)data; + double a0 = a[0]; + double a1 = a[1]; + double a2 = a[2]; + double a3 = a[3]; + double a4 = a[4]; + double a5 = a[5]; + double a6 = a[6]; + double a7 = a[7]; double xin = x + 0.5; double yin = y + 0.5; - xout[0] = (a0*xin + a1*yin + a2) / (a6*xin + a7*yin + 1); - yout[0] = (a3*xin + a4*yin + a5) / (a6*xin + a7*yin + 1); + xout[0] = (a0 * xin + a1 * yin + a2) / (a6 * xin + a7 * yin + 1); + yout[0] = (a3 * xin + a4 * yin + a5) / (a6 * xin + a7 * yin + 1); return 1; } static int -quad_transform(double* xout, double* yout, int x, int y, void* data) -{ +quad_transform(double *xout, double *yout, int x, int y, void *data) { /* quad warp: map quadrilateral to rectangle */ - double* a = (double*) data; - double a0 = a[0]; double a1 = a[1]; double a2 = a[2]; double a3 = a[3]; - double a4 = a[4]; double a5 = a[5]; double a6 = a[6]; double a7 = a[7]; + double *a = (double *)data; + double a0 = a[0]; + double a1 = a[1]; + double a2 = a[2]; + double a3 = a[3]; + double a4 = a[4]; + double a5 = a[5]; + double a6 = a[6]; + double a7 = a[7]; double xin = x + 0.5; double yin = y + 0.5; - xout[0] = a0 + a1*xin + a2*yin + a3*xin*yin; - yout[0] = a4 + a5*xin + a6*yin + a7*xin*yin; + xout[0] = a0 + a1 * xin + a2 * yin + a3 * xin * yin; + yout[0] = a4 + a5 * xin + a6 * yin + a7 * xin * yin; return 1; } @@ -428,20 +442,18 @@ quad_transform(double* xout, double* yout, int x, int y, void* data) /* transform filters (ImagingTransformFilter) */ static int -nearest_filter8(void* out, Imaging im, double xin, double yin) -{ +nearest_filter8(void *out, Imaging im, double xin, double yin) { int x = COORD(xin); int y = COORD(yin); if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize) { return 0; } - ((UINT8*)out)[0] = im->image8[y][x]; + ((UINT8 *)out)[0] = im->image8[y][x]; return 1; } static int -nearest_filter16(void* out, Imaging im, double xin, double yin) -{ +nearest_filter16(void *out, Imaging im, double xin, double yin) { int x = COORD(xin); int y = COORD(yin); if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize) { @@ -452,8 +464,7 @@ nearest_filter16(void* out, Imaging im, double xin, double yin) } static int -nearest_filter32(void* out, Imaging im, double xin, double yin) -{ +nearest_filter32(void *out, Imaging im, double xin, double yin) { int x = COORD(xin); int y = COORD(yin); if (x < 0 || x >= im->xsize || y < 0 || y >= im->ysize) { @@ -463,54 +474,52 @@ nearest_filter32(void* out, Imaging im, double xin, double yin) return 1; } -#define XCLIP(im, x) ( ((x) < 0) ? 0 : ((x) < im->xsize) ? (x) : im->xsize-1 ) -#define YCLIP(im, y) ( ((y) < 0) ? 0 : ((y) < im->ysize) ? (y) : im->ysize-1 ) +#define XCLIP(im, x) (((x) < 0) ? 0 : ((x) < im->xsize) ? (x) : im->xsize - 1) +#define YCLIP(im, y) (((y) < 0) ? 0 : ((y) < im->ysize) ? (y) : im->ysize - 1) -#define BILINEAR(v, a, b, d)\ - (v = (a) + ( (b) - (a) ) * (d)) +#define BILINEAR(v, a, b, d) (v = (a) + ((b) - (a)) * (d)) -#define BILINEAR_HEAD(type)\ - int x, y;\ - int x0, x1;\ - double v1, v2;\ - double dx, dy;\ - type* in;\ - if (xin < 0.0 || xin >= im->xsize || yin < 0.0 || yin >= im->ysize) {\ - return 0;\ - }\ - xin -= 0.5;\ - yin -= 0.5;\ - x = FLOOR(xin);\ - y = FLOOR(yin);\ - dx = xin - x;\ +#define BILINEAR_HEAD(type) \ + int x, y; \ + int x0, x1; \ + double v1, v2; \ + double dx, dy; \ + type *in; \ + if (xin < 0.0 || xin >= im->xsize || yin < 0.0 || yin >= im->ysize) { \ + return 0; \ + } \ + xin -= 0.5; \ + yin -= 0.5; \ + x = FLOOR(xin); \ + y = FLOOR(yin); \ + dx = xin - x; \ dy = yin - y; -#define BILINEAR_BODY(type, image, step, offset) {\ - in = (type*) ((image)[YCLIP(im, y)] + offset);\ - x0 = XCLIP(im, x+0)*step;\ - x1 = XCLIP(im, x+1)*step;\ - BILINEAR(v1, in[x0], in[x1], dx);\ - if (y+1 >= 0 && y+1 < im->ysize) {\ - in = (type*) ((image)[y+1] + offset);\ - BILINEAR(v2, in[x0], in[x1], dx);\ - } else {\ - v2 = v1;\ - }\ - BILINEAR(v1, v1, v2, dy);\ -} +#define BILINEAR_BODY(type, image, step, offset) \ + { \ + in = (type *)((image)[YCLIP(im, y)] + offset); \ + x0 = XCLIP(im, x + 0) * step; \ + x1 = XCLIP(im, x + 1) * step; \ + BILINEAR(v1, in[x0], in[x1], dx); \ + if (y + 1 >= 0 && y + 1 < im->ysize) { \ + in = (type *)((image)[y + 1] + offset); \ + BILINEAR(v2, in[x0], in[x1], dx); \ + } else { \ + v2 = v1; \ + } \ + BILINEAR(v1, v1, v2, dy); \ + } static int -bilinear_filter8(void* out, Imaging im, double xin, double yin) -{ +bilinear_filter8(void *out, Imaging im, double xin, double yin) { BILINEAR_HEAD(UINT8); BILINEAR_BODY(UINT8, im->image8, 1, 0); - ((UINT8*)out)[0] = (UINT8) v1; + ((UINT8 *)out)[0] = (UINT8)v1; return 1; } static int -bilinear_filter32I(void* out, Imaging im, double xin, double yin) -{ +bilinear_filter32I(void *out, Imaging im, double xin, double yin) { INT32 k; BILINEAR_HEAD(INT32); BILINEAR_BODY(INT32, im->image32, 1, 0); @@ -520,8 +529,7 @@ bilinear_filter32I(void* out, Imaging im, double xin, double yin) } static int -bilinear_filter32F(void* out, Imaging im, double xin, double yin) -{ +bilinear_filter32F(void *out, Imaging im, double xin, double yin) { FLOAT32 k; BILINEAR_HEAD(FLOAT32); BILINEAR_BODY(FLOAT32, im->image32, 1, 0); @@ -531,26 +539,24 @@ bilinear_filter32F(void* out, Imaging im, double xin, double yin) } static int -bilinear_filter32LA(void* out, Imaging im, double xin, double yin) -{ +bilinear_filter32LA(void *out, Imaging im, double xin, double yin) { BILINEAR_HEAD(UINT8); BILINEAR_BODY(UINT8, im->image, 4, 0); - ((UINT8*)out)[0] = (UINT8) v1; - ((UINT8*)out)[1] = (UINT8) v1; - ((UINT8*)out)[2] = (UINT8) v1; + ((UINT8 *)out)[0] = (UINT8)v1; + ((UINT8 *)out)[1] = (UINT8)v1; + ((UINT8 *)out)[2] = (UINT8)v1; BILINEAR_BODY(UINT8, im->image, 4, 3); - ((UINT8*)out)[3] = (UINT8) v1; + ((UINT8 *)out)[3] = (UINT8)v1; return 1; } static int -bilinear_filter32RGB(void* out, Imaging im, double xin, double yin) -{ +bilinear_filter32RGB(void *out, Imaging im, double xin, double yin) { int b; BILINEAR_HEAD(UINT8); for (b = 0; b < im->bands; b++) { BILINEAR_BODY(UINT8, im->image, 4, b); - ((UINT8*)out)[b] = (UINT8) v1; + ((UINT8 *)out)[b] = (UINT8)v1; } return 1; } @@ -559,79 +565,79 @@ bilinear_filter32RGB(void* out, Imaging im, double xin, double yin) #undef BILINEAR_HEAD #undef BILINEAR_BODY -#define BICUBIC(v, v1, v2, v3, v4, d) {\ - double p1 = v2;\ - double p2 = -v1 + v3;\ - double p3 = 2*(v1 - v2) + v3 - v4;\ - double p4 = -v1 + v2 - v3 + v4;\ - v = p1 + (d)*(p2 + (d)*(p3 + (d)*p4));\ -} +#define BICUBIC(v, v1, v2, v3, v4, d) \ + { \ + double p1 = v2; \ + double p2 = -v1 + v3; \ + double p3 = 2 * (v1 - v2) + v3 - v4; \ + double p4 = -v1 + v2 - v3 + v4; \ + v = p1 + (d) * (p2 + (d) * (p3 + (d)*p4)); \ + } -#define BICUBIC_HEAD(type)\ - int x = FLOOR(xin);\ - int y = FLOOR(yin);\ - int x0, x1, x2, x3;\ - double v1, v2, v3, v4;\ - double dx, dy;\ - type* in;\ - if (xin < 0.0 || xin >= im->xsize || yin < 0.0 || yin >= im->ysize) {\ - return 0;\ - }\ - xin -= 0.5;\ - yin -= 0.5;\ - x = FLOOR(xin);\ - y = FLOOR(yin);\ - dx = xin - x;\ - dy = yin - y;\ - x--; y--; - -#define BICUBIC_BODY(type, image, step, offset) {\ - in = (type*) ((image)[YCLIP(im, y)] + offset);\ - x0 = XCLIP(im, x+0)*step;\ - x1 = XCLIP(im, x+1)*step;\ - x2 = XCLIP(im, x+2)*step;\ - x3 = XCLIP(im, x+3)*step;\ - BICUBIC(v1, in[x0], in[x1], in[x2], in[x3], dx);\ - if (y+1 >= 0 && y+1 < im->ysize) {\ - in = (type*) ((image)[y+1] + offset);\ - BICUBIC(v2, in[x0], in[x1], in[x2], in[x3], dx);\ - } else {\ - v2 = v1;\ - }\ - if (y+2 >= 0 && y+2 < im->ysize) {\ - in = (type*) ((image)[y+2] + offset);\ - BICUBIC(v3, in[x0], in[x1], in[x2], in[x3], dx);\ - } else {\ - v3 = v2;\ - }\ - if (y+3 >= 0 && y+3 < im->ysize) {\ - in = (type*) ((image)[y+3] + offset);\ - BICUBIC(v4, in[x0], in[x1], in[x2], in[x3], dx);\ - } else {\ - v4 = v3;\ - }\ - BICUBIC(v1, v1, v2, v3, v4, dy);\ -} +#define BICUBIC_HEAD(type) \ + int x = FLOOR(xin); \ + int y = FLOOR(yin); \ + int x0, x1, x2, x3; \ + double v1, v2, v3, v4; \ + double dx, dy; \ + type *in; \ + if (xin < 0.0 || xin >= im->xsize || yin < 0.0 || yin >= im->ysize) { \ + return 0; \ + } \ + xin -= 0.5; \ + yin -= 0.5; \ + x = FLOOR(xin); \ + y = FLOOR(yin); \ + dx = xin - x; \ + dy = yin - y; \ + x--; \ + y--; +#define BICUBIC_BODY(type, image, step, offset) \ + { \ + in = (type *)((image)[YCLIP(im, y)] + offset); \ + x0 = XCLIP(im, x + 0) * step; \ + x1 = XCLIP(im, x + 1) * step; \ + x2 = XCLIP(im, x + 2) * step; \ + x3 = XCLIP(im, x + 3) * step; \ + BICUBIC(v1, in[x0], in[x1], in[x2], in[x3], dx); \ + if (y + 1 >= 0 && y + 1 < im->ysize) { \ + in = (type *)((image)[y + 1] + offset); \ + BICUBIC(v2, in[x0], in[x1], in[x2], in[x3], dx); \ + } else { \ + v2 = v1; \ + } \ + if (y + 2 >= 0 && y + 2 < im->ysize) { \ + in = (type *)((image)[y + 2] + offset); \ + BICUBIC(v3, in[x0], in[x1], in[x2], in[x3], dx); \ + } else { \ + v3 = v2; \ + } \ + if (y + 3 >= 0 && y + 3 < im->ysize) { \ + in = (type *)((image)[y + 3] + offset); \ + BICUBIC(v4, in[x0], in[x1], in[x2], in[x3], dx); \ + } else { \ + v4 = v3; \ + } \ + BICUBIC(v1, v1, v2, v3, v4, dy); \ + } static int -bicubic_filter8(void* out, Imaging im, double xin, double yin) -{ +bicubic_filter8(void *out, Imaging im, double xin, double yin) { BICUBIC_HEAD(UINT8); BICUBIC_BODY(UINT8, im->image8, 1, 0); if (v1 <= 0.0) { - ((UINT8*)out)[0] = 0; + ((UINT8 *)out)[0] = 0; } else if (v1 >= 255.0) { - ((UINT8*)out)[0] = 255; + ((UINT8 *)out)[0] = 255; } else { - ((UINT8*)out)[0] = (UINT8) v1; + ((UINT8 *)out)[0] = (UINT8)v1; } return 1; } static int -bicubic_filter32I(void* out, Imaging im, double xin, double yin) -{ +bicubic_filter32I(void *out, Imaging im, double xin, double yin) { INT32 k; BICUBIC_HEAD(INT32); BICUBIC_BODY(INT32, im->image32, 1, 0); @@ -641,8 +647,7 @@ bicubic_filter32I(void* out, Imaging im, double xin, double yin) } static int -bicubic_filter32F(void* out, Imaging im, double xin, double yin) -{ +bicubic_filter32F(void *out, Imaging im, double xin, double yin) { FLOAT32 k; BICUBIC_HEAD(FLOAT32); BICUBIC_BODY(FLOAT32, im->image32, 1, 0); @@ -652,47 +657,45 @@ bicubic_filter32F(void* out, Imaging im, double xin, double yin) } static int -bicubic_filter32LA(void* out, Imaging im, double xin, double yin) -{ +bicubic_filter32LA(void *out, Imaging im, double xin, double yin) { BICUBIC_HEAD(UINT8); BICUBIC_BODY(UINT8, im->image, 4, 0); if (v1 <= 0.0) { - ((UINT8*)out)[0] = 0; - ((UINT8*)out)[1] = 0; - ((UINT8*)out)[2] = 0; + ((UINT8 *)out)[0] = 0; + ((UINT8 *)out)[1] = 0; + ((UINT8 *)out)[2] = 0; } else if (v1 >= 255.0) { - ((UINT8*)out)[0] = 255; - ((UINT8*)out)[1] = 255; - ((UINT8*)out)[2] = 255; + ((UINT8 *)out)[0] = 255; + ((UINT8 *)out)[1] = 255; + ((UINT8 *)out)[2] = 255; } else { - ((UINT8*)out)[0] = (UINT8) v1; - ((UINT8*)out)[1] = (UINT8) v1; - ((UINT8*)out)[2] = (UINT8) v1; + ((UINT8 *)out)[0] = (UINT8)v1; + ((UINT8 *)out)[1] = (UINT8)v1; + ((UINT8 *)out)[2] = (UINT8)v1; } BICUBIC_BODY(UINT8, im->image, 4, 3); if (v1 <= 0.0) { - ((UINT8*)out)[3] = 0; + ((UINT8 *)out)[3] = 0; } else if (v1 >= 255.0) { - ((UINT8*)out)[3] = 255; + ((UINT8 *)out)[3] = 255; } else { - ((UINT8*)out)[3] = (UINT8) v1; + ((UINT8 *)out)[3] = (UINT8)v1; } return 1; } static int -bicubic_filter32RGB(void* out, Imaging im, double xin, double yin) -{ +bicubic_filter32RGB(void *out, Imaging im, double xin, double yin) { int b; BICUBIC_HEAD(UINT8); for (b = 0; b < im->bands; b++) { BICUBIC_BODY(UINT8, im->image, 4, b); if (v1 <= 0.0) { - ((UINT8*)out)[b] = 0; + ((UINT8 *)out)[b] = 0; } else if (v1 >= 255.0) { - ((UINT8*)out)[b] = 255; + ((UINT8 *)out)[b] = 255; } else { - ((UINT8*)out)[b] = (UINT8) v1; + ((UINT8 *)out)[b] = (UINT8)v1; } } return 1; @@ -703,64 +706,63 @@ bicubic_filter32RGB(void* out, Imaging im, double xin, double yin) #undef BICUBIC_BODY static ImagingTransformFilter -getfilter(Imaging im, int filterid) -{ +getfilter(Imaging im, int filterid) { switch (filterid) { - case IMAGING_TRANSFORM_NEAREST: - if (im->image8) { - switch (im->type) { - case IMAGING_TYPE_UINT8: - return nearest_filter8; - case IMAGING_TYPE_SPECIAL: - switch (im->pixelsize) { - case 1: - return nearest_filter8; - case 2: - return nearest_filter16; - case 4: - return nearest_filter32; + case IMAGING_TRANSFORM_NEAREST: + if (im->image8) { + switch (im->type) { + case IMAGING_TYPE_UINT8: + return nearest_filter8; + case IMAGING_TYPE_SPECIAL: + switch (im->pixelsize) { + case 1: + return nearest_filter8; + case 2: + return nearest_filter16; + case 4: + return nearest_filter32; + } + } + } else { + return nearest_filter32; + } + break; + case IMAGING_TRANSFORM_BILINEAR: + if (im->image8) { + return bilinear_filter8; + } else if (im->image32) { + switch (im->type) { + case IMAGING_TYPE_UINT8: + if (im->bands == 2) { + return bilinear_filter32LA; + } else { + return bilinear_filter32RGB; + } + case IMAGING_TYPE_INT32: + return bilinear_filter32I; + case IMAGING_TYPE_FLOAT32: + return bilinear_filter32F; } } - } else { - return nearest_filter32; - } - break; - case IMAGING_TRANSFORM_BILINEAR: - if (im->image8) { - return bilinear_filter8; - } else if (im->image32) { - switch (im->type) { - case IMAGING_TYPE_UINT8: - if (im->bands == 2) { - return bilinear_filter32LA; - } else { - return bilinear_filter32RGB; + break; + case IMAGING_TRANSFORM_BICUBIC: + if (im->image8) { + return bicubic_filter8; + } else if (im->image32) { + switch (im->type) { + case IMAGING_TYPE_UINT8: + if (im->bands == 2) { + return bicubic_filter32LA; + } else { + return bicubic_filter32RGB; + } + case IMAGING_TYPE_INT32: + return bicubic_filter32I; + case IMAGING_TYPE_FLOAT32: + return bicubic_filter32F; } - case IMAGING_TYPE_INT32: - return bilinear_filter32I; - case IMAGING_TYPE_FLOAT32: - return bilinear_filter32F; } - } - break; - case IMAGING_TRANSFORM_BICUBIC: - if (im->image8) { - return bicubic_filter8; - } else if (im->image32) { - switch (im->type) { - case IMAGING_TYPE_UINT8: - if (im->bands == 2) { - return bicubic_filter32LA; - } else { - return bicubic_filter32RGB; - } - case IMAGING_TYPE_INT32: - return bicubic_filter32I; - case IMAGING_TYPE_FLOAT32: - return bicubic_filter32F; - } - } - break; + break; } /* no such filter */ return NULL; @@ -770,10 +772,16 @@ getfilter(Imaging im, int filterid) Imaging ImagingGenericTransform( - Imaging imOut, Imaging imIn, int x0, int y0, int x1, int y1, - ImagingTransformMap transform, void* transform_data, - int filterid, int fill) -{ + Imaging imOut, + Imaging imIn, + int x0, + int y0, + int x1, + int y1, + ImagingTransformMap transform, + void *transform_data, + int filterid, + int fill) { /* slow generic transformation. use ImagingTransformAffine or ImagingScaleAffine where possible. */ @@ -784,11 +792,11 @@ ImagingGenericTransform( ImagingTransformFilter filter = getfilter(imIn, filterid); if (!filter) { - return (Imaging) ImagingError_ValueError("bad filter number"); + return (Imaging)ImagingError_ValueError("bad filter number"); } if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } ImagingCopyPalette(imOut, imIn); @@ -809,10 +817,10 @@ ImagingGenericTransform( } for (y = y0; y < y1; y++) { - out = imOut->image[y] + x0*imOut->pixelsize; + out = imOut->image[y] + x0 * imOut->pixelsize; for (x = x0; x < x1; x++) { - if ( ! transform(&xx, &yy, x-x0, y-y0, transform_data) || - ! filter(out, imIn, xx, yy)) { + if (!transform(&xx, &yy, x - x0, y - y0, transform_data) || + !filter(out, imIn, xx, yy)) { if (fill) { memset(out, 0, imOut->pixelsize); } @@ -827,10 +835,15 @@ ImagingGenericTransform( } static Imaging -ImagingScaleAffine(Imaging imOut, Imaging imIn, - int x0, int y0, int x1, int y1, - double a[6], int fill) -{ +ImagingScaleAffine( + Imaging imOut, + Imaging imIn, + int x0, + int y0, + int x1, + int y1, + double a[6], + int fill) { /* scale, nearest neighbour resampling */ ImagingSectionCookie cookie; @@ -841,7 +854,7 @@ ImagingScaleAffine(Imaging imOut, Imaging imIn, int *xintab; if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } ImagingCopyPalette(imOut, imIn); @@ -860,10 +873,10 @@ ImagingScaleAffine(Imaging imOut, Imaging imIn, } /* malloc check ok, uses calloc for overflow */ - xintab = (int*) calloc(imOut->xsize, sizeof(int)); + xintab = (int *)calloc(imOut->xsize, sizeof(int)); if (!xintab) { ImagingDelete(imOut); - return (Imaging) ImagingError_MemoryError(); + return (Imaging)ImagingError_MemoryError(); } xo = a[2] + a[0] * 0.5; @@ -875,8 +888,8 @@ ImagingScaleAffine(Imaging imOut, Imaging imIn, /* Pretabulate horizontal pixel positions */ for (x = x0; x < x1; x++) { xin = COORD(xo); - if (xin >= 0 && xin < (int) imIn->xsize) { - xmax = x+1; + if (xin >= 0 && xin < (int)imIn->xsize) { + xmax = x + 1; if (x < xmin) { xmin = x; } @@ -885,21 +898,21 @@ ImagingScaleAffine(Imaging imOut, Imaging imIn, xo += a[0]; } -#define AFFINE_SCALE(pixel, image)\ - for (y = y0; y < y1; y++) {\ - int yi = COORD(yo);\ - pixel *in, *out;\ - out = imOut->image[y];\ - if (fill && x1 > x0) {\ - memset(out+x0, 0, (x1-x0)*sizeof(pixel));\ - }\ - if (yi >= 0 && yi < imIn->ysize) {\ - in = imIn->image[yi];\ - for (x = xmin; x < xmax; x++) {\ - out[x] = in[xintab[x]];\ - }\ - }\ - yo += a[4];\ +#define AFFINE_SCALE(pixel, image) \ + for (y = y0; y < y1; y++) { \ + int yi = COORD(yo); \ + pixel *in, *out; \ + out = imOut->image[y]; \ + if (fill && x1 > x0) { \ + memset(out + x0, 0, (x1 - x0) * sizeof(pixel)); \ + } \ + if (yi >= 0 && yi < imIn->ysize) { \ + in = imIn->image[yi]; \ + for (x = xmin; x < xmax; x++) { \ + out[x] = in[xintab[x]]; \ + } \ + } \ + yo += a[4]; \ } ImagingSectionEnter(&cookie); @@ -920,17 +933,23 @@ ImagingScaleAffine(Imaging imOut, Imaging imIn, } static inline int -check_fixed(double a[6], int x, int y) -{ - return (fabs(x*a[0] + y*a[1] + a[2]) < 32768.0 && - fabs(x*a[3] + y*a[4] + a[5]) < 32768.0); +check_fixed(double a[6], int x, int y) { + return ( + fabs(x * a[0] + y * a[1] + a[2]) < 32768.0 && + fabs(x * a[3] + y * a[4] + a[5]) < 32768.0); } static inline Imaging -affine_fixed(Imaging imOut, Imaging imIn, - int x0, int y0, int x1, int y1, - double a[6], int filterid, int fill) -{ +affine_fixed( + Imaging imOut, + Imaging imIn, + int x0, + int y0, + int x1, + int y1, + double a[6], + int filterid, + int fill) { /* affine transform, nearest neighbour resampling, fixed point arithmetics */ @@ -943,41 +962,43 @@ affine_fixed(Imaging imOut, Imaging imIn, ImagingCopyPalette(imOut, imIn); - xsize = (int) imIn->xsize; - ysize = (int) imIn->ysize; + xsize = (int)imIn->xsize; + ysize = (int)imIn->ysize; /* use 16.16 fixed point arithmetics */ #define FIX(v) FLOOR((v)*65536.0 + 0.5) - a0 = FIX(a[0]); a1 = FIX(a[1]); - a3 = FIX(a[3]); a4 = FIX(a[4]); + a0 = FIX(a[0]); + a1 = FIX(a[1]); + a3 = FIX(a[3]); + a4 = FIX(a[4]); a2 = FIX(a[2] + a[0] * 0.5 + a[1] * 0.5); a5 = FIX(a[5] + a[3] * 0.5 + a[4] * 0.5); #undef FIX -#define AFFINE_TRANSFORM_FIXED(pixel, image)\ - for (y = y0; y < y1; y++) {\ - pixel *out;\ - xx = a2;\ - yy = a5;\ - out = imOut->image[y];\ - if (fill && x1 > x0) {\ - memset(out+x0, 0, (x1-x0)*sizeof(pixel));\ - }\ - for (x = x0; x < x1; x++, out++) {\ - xin = xx >> 16;\ - if (xin >= 0 && xin < xsize) {\ - yin = yy >> 16;\ - if (yin >= 0 && yin < ysize) {\ - *out = imIn->image[yin][xin];\ - }\ - }\ - xx += a0;\ - yy += a3;\ - }\ - a2 += a1;\ - a5 += a4;\ +#define AFFINE_TRANSFORM_FIXED(pixel, image) \ + for (y = y0; y < y1; y++) { \ + pixel *out; \ + xx = a2; \ + yy = a5; \ + out = imOut->image[y]; \ + if (fill && x1 > x0) { \ + memset(out + x0, 0, (x1 - x0) * sizeof(pixel)); \ + } \ + for (x = x0; x < x1; x++, out++) { \ + xin = xx >> 16; \ + if (xin >= 0 && xin < xsize) { \ + yin = yy >> 16; \ + if (yin >= 0 && yin < ysize) { \ + *out = imIn->image[yin][xin]; \ + } \ + } \ + xx += a0; \ + yy += a3; \ + } \ + a2 += a1; \ + a5 += a4; \ } ImagingSectionEnter(&cookie); @@ -996,10 +1017,16 @@ affine_fixed(Imaging imOut, Imaging imIn, } Imaging -ImagingTransformAffine(Imaging imOut, Imaging imIn, - int x0, int y0, int x1, int y1, - double a[6], int filterid, int fill) -{ +ImagingTransformAffine( + Imaging imOut, + Imaging imIn, + int x0, + int y0, + int x1, + int y1, + double a[6], + int filterid, + int fill) { /* affine transform, nearest neighbour resampling, floating point arithmetics*/ @@ -1012,10 +1039,7 @@ ImagingTransformAffine(Imaging imOut, Imaging imIn, if (filterid || imIn->type == IMAGING_TYPE_SPECIAL) { return ImagingGenericTransform( - imOut, imIn, - x0, y0, x1, y1, - affine_transform, a, - filterid, fill); + imOut, imIn, x0, y0, x1, y1, affine_transform, a, filterid, fill); } if (a[1] == 0 && a[3] == 0) { @@ -1024,7 +1048,7 @@ ImagingTransformAffine(Imaging imOut, Imaging imIn, } if (!imOut || !imIn || strcmp(imIn->mode, imOut->mode) != 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (x0 < 0) { @@ -1043,8 +1067,8 @@ ImagingTransformAffine(Imaging imOut, Imaging imIn, /* translate all four corners to check if they are within the range that can be represented by the fixed point arithmetics */ - if (check_fixed(a, 0, 0) && check_fixed(a, x1-x0, y1-y0) && - check_fixed(a, 0, y1-y0) && check_fixed(a, x1-x0, 0)) { + if (check_fixed(a, 0, 0) && check_fixed(a, x1 - x0, y1 - y0) && + check_fixed(a, 0, y1 - y0) && check_fixed(a, x1 - x0, 0)) { return affine_fixed(imOut, imIn, x0, y0, x1, y1, a, filterid, fill); } @@ -1054,34 +1078,34 @@ ImagingTransformAffine(Imaging imOut, Imaging imIn, ImagingCopyPalette(imOut, imIn); - xsize = (int) imIn->xsize; - ysize = (int) imIn->ysize; + xsize = (int)imIn->xsize; + ysize = (int)imIn->ysize; xo = a[2] + a[1] * 0.5 + a[0] * 0.5; yo = a[5] + a[4] * 0.5 + a[3] * 0.5; -#define AFFINE_TRANSFORM(pixel, image)\ - for (y = y0; y < y1; y++) {\ - pixel *out;\ - xx = xo;\ - yy = yo;\ - out = imOut->image[y];\ - if (fill && x1 > x0) {\ - memset(out+x0, 0, (x1-x0)*sizeof(pixel));\ - }\ - for (x = x0; x < x1; x++, out++) {\ - xin = COORD(xx);\ - if (xin >= 0 && xin < xsize) {\ - yin = COORD(yy);\ - if (yin >= 0 && yin < ysize) {\ - *out = imIn->image[yin][xin];\ - }\ - }\ - xx += a[0];\ - yy += a[3];\ - }\ - xo += a[1];\ - yo += a[4];\ +#define AFFINE_TRANSFORM(pixel, image) \ + for (y = y0; y < y1; y++) { \ + pixel *out; \ + xx = xo; \ + yy = yo; \ + out = imOut->image[y]; \ + if (fill && x1 > x0) { \ + memset(out + x0, 0, (x1 - x0) * sizeof(pixel)); \ + } \ + for (x = x0; x < x1; x++, out++) { \ + xin = COORD(xx); \ + if (xin >= 0 && xin < xsize) { \ + yin = COORD(yy); \ + if (yin >= 0 && yin < ysize) { \ + *out = imIn->image[yin][xin]; \ + } \ + } \ + xx += a[0]; \ + yy += a[3]; \ + } \ + xo += a[1]; \ + yo += a[4]; \ } ImagingSectionEnter(&cookie); @@ -1100,29 +1124,34 @@ ImagingTransformAffine(Imaging imOut, Imaging imIn, } Imaging -ImagingTransform(Imaging imOut, Imaging imIn, int method, - int x0, int y0, int x1, int y1, - double a[8], int filterid, int fill) -{ +ImagingTransform( + Imaging imOut, + Imaging imIn, + int method, + int x0, + int y0, + int x1, + int y1, + double a[8], + int filterid, + int fill) { ImagingTransformMap transform; - switch(method) { - case IMAGING_TRANSFORM_AFFINE: - return ImagingTransformAffine( - imOut, imIn, x0, y0, x1, y1, a, filterid, fill); - break; - case IMAGING_TRANSFORM_PERSPECTIVE: - transform = perspective_transform; - break; - case IMAGING_TRANSFORM_QUAD: - transform = quad_transform; - break; - default: - return (Imaging) ImagingError_ValueError("bad transform method"); + switch (method) { + case IMAGING_TRANSFORM_AFFINE: + return ImagingTransformAffine( + imOut, imIn, x0, y0, x1, y1, a, filterid, fill); + break; + case IMAGING_TRANSFORM_PERSPECTIVE: + transform = perspective_transform; + break; + case IMAGING_TRANSFORM_QUAD: + transform = quad_transform; + break; + default: + return (Imaging)ImagingError_ValueError("bad transform method"); } return ImagingGenericTransform( - imOut, imIn, - x0, y0, x1, y1, - transform, a, filterid, fill); + imOut, imIn, x0, y0, x1, y1, transform, a, filterid, fill); } diff --git a/src/libImaging/GetBBox.c b/src/libImaging/GetBBox.c index 8db78c2e2..e73153600 100644 --- a/src/libImaging/GetBBox.c +++ b/src/libImaging/GetBBox.c @@ -16,13 +16,10 @@ * See the README file for details on usage and redistribution. */ - #include "Imaging.h" - int -ImagingGetBBox(Imaging im, int bbox[4]) -{ +ImagingGetBBox(Imaging im, int bbox[4]) { /* Get the bounding box for any non-zero data in the image.*/ int x, y; @@ -33,26 +30,26 @@ ImagingGetBBox(Imaging im, int bbox[4]) bbox[1] = -1; bbox[2] = bbox[3] = 0; -#define GETBBOX(image, mask)\ - for (y = 0; y < im->ysize; y++) {\ - has_data = 0;\ - for (x = 0; x < im->xsize; x++) {\ - if (im->image[y][x] & mask) {\ - has_data = 1;\ - if (x < bbox[0]) {\ - bbox[0] = x;\ - }\ - if (x >= bbox[2]) {\ - bbox[2] = x+1;\ - }\ - }\ - }\ - if (has_data) {\ - if (bbox[1] < 0) {\ - bbox[1] = y;\ - }\ - bbox[3] = y+1;\ - }\ +#define GETBBOX(image, mask) \ + for (y = 0; y < im->ysize; y++) { \ + has_data = 0; \ + for (x = 0; x < im->xsize; x++) { \ + if (im->image[y][x] & mask) { \ + has_data = 1; \ + if (x < bbox[0]) { \ + bbox[0] = x; \ + } \ + if (x >= bbox[2]) { \ + bbox[2] = x + 1; \ + } \ + } \ + } \ + if (has_data) { \ + if (bbox[1] < 0) { \ + bbox[1] = y; \ + } \ + bbox[3] = y + 1; \ + } \ } if (im->image8) { @@ -60,16 +57,15 @@ ImagingGetBBox(Imaging im, int bbox[4]) } else { INT32 mask = 0xffffffff; if (im->bands == 3) { - ((UINT8*) &mask)[3] = 0; - } else if (strcmp(im->mode, "RGBa") == 0 || - strcmp(im->mode, "RGBA") == 0 || - strcmp(im->mode, "La") == 0 || - strcmp(im->mode, "LA") == 0 || - strcmp(im->mode, "PA") == 0) { + ((UINT8 *)&mask)[3] = 0; + } else if ( + strcmp(im->mode, "RGBa") == 0 || strcmp(im->mode, "RGBA") == 0 || + strcmp(im->mode, "La") == 0 || strcmp(im->mode, "LA") == 0 || + strcmp(im->mode, "PA") == 0) { #ifdef WORDS_BIGENDIAN - mask = 0x000000ff; + mask = 0x000000ff; #else - mask = 0xff000000; + mask = 0xff000000; #endif } GETBBOX(image32, mask); @@ -83,10 +79,8 @@ ImagingGetBBox(Imaging im, int bbox[4]) return 1; /* ok */ } - int -ImagingGetProjection(Imaging im, UINT8* xproj, UINT8* yproj) -{ +ImagingGetProjection(Imaging im, UINT8 *xproj, UINT8 *yproj) { /* Get projection arrays for non-zero data in the image.*/ int x, y; @@ -96,26 +90,26 @@ ImagingGetProjection(Imaging im, UINT8* xproj, UINT8* yproj) memset(xproj, 0, im->xsize); memset(yproj, 0, im->ysize); - #define GETPROJ(image, mask)\ - for (y = 0; y < im->ysize; y++) {\ - has_data = 0;\ - for (x = 0; x < im->xsize; x++) {\ - if (im->image[y][x] & mask) {\ - has_data = 1;\ - xproj[x] = 1;\ - }\ - }\ - if (has_data) {\ - yproj[y] = 1;\ - }\ - } +#define GETPROJ(image, mask) \ + for (y = 0; y < im->ysize; y++) { \ + has_data = 0; \ + for (x = 0; x < im->xsize; x++) { \ + if (im->image[y][x] & mask) { \ + has_data = 1; \ + xproj[x] = 1; \ + } \ + } \ + if (has_data) { \ + yproj[y] = 1; \ + } \ + } if (im->image8) { GETPROJ(image8, 0xff); } else { INT32 mask = 0xffffffff; if (im->bands == 3) { - ((UINT8*) &mask)[3] = 0; + ((UINT8 *)&mask)[3] = 0; } GETPROJ(image32, mask); } @@ -123,16 +117,14 @@ ImagingGetProjection(Imaging im, UINT8* xproj, UINT8* yproj) return 1; /* ok */ } - int -ImagingGetExtrema(Imaging im, void *extrema) -{ +ImagingGetExtrema(Imaging im, void *extrema) { int x, y; INT32 imin, imax; FLOAT32 fmin, fmax; if (im->bands != 1) { - (void) ImagingError_ModeError(); + (void)ImagingError_ModeError(); return -1; /* mismatch */ } @@ -141,111 +133,109 @@ ImagingGetExtrema(Imaging im, void *extrema) } switch (im->type) { - case IMAGING_TYPE_UINT8: - imin = imax = im->image8[0][0]; - for (y = 0; y < im->ysize; y++) { - UINT8* in = im->image8[y]; - for (x = 0; x < im->xsize; x++) { - if (imin > in[x]) { - imin = in[x]; - } else if (imax < in[x]) { - imax = in[x]; + case IMAGING_TYPE_UINT8: + imin = imax = im->image8[0][0]; + for (y = 0; y < im->ysize; y++) { + UINT8 *in = im->image8[y]; + for (x = 0; x < im->xsize; x++) { + if (imin > in[x]) { + imin = in[x]; + } else if (imax < in[x]) { + imax = in[x]; + } } } - } - ((UINT8*) extrema)[0] = (UINT8) imin; - ((UINT8*) extrema)[1] = (UINT8) imax; - break; - case IMAGING_TYPE_INT32: - imin = imax = im->image32[0][0]; - for (y = 0; y < im->ysize; y++) { - INT32* in = im->image32[y]; - for (x = 0; x < im->xsize; x++) { - if (imin > in[x]) { - imin = in[x]; - } else if (imax < in[x]) { - imax = in[x]; + ((UINT8 *)extrema)[0] = (UINT8)imin; + ((UINT8 *)extrema)[1] = (UINT8)imax; + break; + case IMAGING_TYPE_INT32: + imin = imax = im->image32[0][0]; + for (y = 0; y < im->ysize; y++) { + INT32 *in = im->image32[y]; + for (x = 0; x < im->xsize; x++) { + if (imin > in[x]) { + imin = in[x]; + } else if (imax < in[x]) { + imax = in[x]; + } } } - } - memcpy(extrema, &imin, sizeof(imin)); - memcpy(((char*)extrema) + sizeof(imin), &imax, sizeof(imax)); - break; - case IMAGING_TYPE_FLOAT32: - fmin = fmax = ((FLOAT32*) im->image32[0])[0]; - for (y = 0; y < im->ysize; y++) { - FLOAT32* in = (FLOAT32*) im->image32[y]; - for (x = 0; x < im->xsize; x++) { - if (fmin > in[x]) { - fmin = in[x]; - } else if (fmax < in[x]) { - fmax = in[x]; + memcpy(extrema, &imin, sizeof(imin)); + memcpy(((char *)extrema) + sizeof(imin), &imax, sizeof(imax)); + break; + case IMAGING_TYPE_FLOAT32: + fmin = fmax = ((FLOAT32 *)im->image32[0])[0]; + for (y = 0; y < im->ysize; y++) { + FLOAT32 *in = (FLOAT32 *)im->image32[y]; + for (x = 0; x < im->xsize; x++) { + if (fmin > in[x]) { + fmin = in[x]; + } else if (fmax < in[x]) { + fmax = in[x]; + } } } - } - memcpy(extrema, &fmin, sizeof(fmin)); - memcpy(((char*)extrema) + sizeof(fmin), &fmax, sizeof(fmax)); - break; - case IMAGING_TYPE_SPECIAL: - if (strcmp(im->mode, "I;16") == 0) { - UINT16 v; - UINT8* pixel = *im->image8; + memcpy(extrema, &fmin, sizeof(fmin)); + memcpy(((char *)extrema) + sizeof(fmin), &fmax, sizeof(fmax)); + break; + case IMAGING_TYPE_SPECIAL: + if (strcmp(im->mode, "I;16") == 0) { + UINT16 v; + UINT8 *pixel = *im->image8; #ifdef WORDS_BIGENDIAN - v = pixel[0] + (pixel[1] << 8); + v = pixel[0] + (pixel[1] << 8); #else - memcpy(&v, pixel, sizeof(v)); + memcpy(&v, pixel, sizeof(v)); #endif - imin = imax = v; - for (y = 0; y < im->ysize; y++) { - for (x = 0; x < im->xsize; x++) { - pixel = (UINT8*)im->image[y] + x * sizeof(v); + imin = imax = v; + for (y = 0; y < im->ysize; y++) { + for (x = 0; x < im->xsize; x++) { + pixel = (UINT8 *)im->image[y] + x * sizeof(v); #ifdef WORDS_BIGENDIAN - v = pixel[0] + (pixel[1] << 8); + v = pixel[0] + (pixel[1] << 8); #else - memcpy(&v, pixel, sizeof(v)); + memcpy(&v, pixel, sizeof(v)); #endif - if (imin > v) { - imin = v; - } else if (imax < v) { - imax = v; - } - } - } - v = (UINT16) imin; - memcpy(extrema, &v, sizeof(v)); - v = (UINT16) imax; - memcpy(((char*)extrema) + sizeof(v), &v, sizeof(v)); - break; - } - /* FALL THROUGH */ - default: - (void) ImagingError_ModeError(); - return -1; + if (imin > v) { + imin = v; + } else if (imax < v) { + imax = v; + } + } + } + v = (UINT16)imin; + memcpy(extrema, &v, sizeof(v)); + v = (UINT16)imax; + memcpy(((char *)extrema) + sizeof(v), &v, sizeof(v)); + break; + } + /* FALL THROUGH */ + default: + (void)ImagingError_ModeError(); + return -1; } return 1; /* ok */ } - /* static ImagingColorItem* getcolors8(Imaging im, int maxcolors, int* size);*/ -static ImagingColorItem* getcolors32(Imaging im, int maxcolors, int* size); +static ImagingColorItem * +getcolors32(Imaging im, int maxcolors, int *size); -ImagingColorItem* -ImagingGetColors(Imaging im, int maxcolors, int* size) -{ +ImagingColorItem * +ImagingGetColors(Imaging im, int maxcolors, int *size) { /* FIXME: add support for 8-bit images */ return getcolors32(im, maxcolors, size); } -static ImagingColorItem* -getcolors32(Imaging im, int maxcolors, int* size) -{ +static ImagingColorItem * +getcolors32(Imaging im, int maxcolors, int *size) { unsigned int h; unsigned int i, incr; int colors; INT32 pixel_mask; int x, y; - ImagingColorItem* table; - ImagingColorItem* v; + ImagingColorItem *table; + ImagingColorItem *v; unsigned int code_size; unsigned int code_poly; @@ -256,19 +246,19 @@ getcolors32(Imaging im, int maxcolors, int* size) Python's Unicode property database (written by yours truly) /F */ static int SIZES[] = { - 4,3, 8,3, 16,3, 32,5, 64,3, 128,3, 256,29, 512,17, 1024,9, 2048,5, - 4096,83, 8192,27, 16384,43, 32768,3, 65536,45, 131072,9, 262144,39, - 524288,39, 1048576,9, 2097152,5, 4194304,3, 8388608,33, 16777216,27, - 33554432,9, 67108864,71, 134217728,39, 268435456,9, 536870912,5, - 1073741824,83, 0 - }; + 4, 3, 8, 3, 16, 3, 32, 5, 64, 3, + 128, 3, 256, 29, 512, 17, 1024, 9, 2048, 5, + 4096, 83, 8192, 27, 16384, 43, 32768, 3, 65536, 45, + 131072, 9, 262144, 39, 524288, 39, 1048576, 9, 2097152, 5, + 4194304, 3, 8388608, 33, 16777216, 27, 33554432, 9, 67108864, 71, + 134217728, 39, 268435456, 9, 536870912, 5, 1073741824, 83, 0}; code_size = code_poly = code_mask = 0; for (i = 0; SIZES[i]; i += 2) { if (SIZES[i] > maxcolors) { code_size = SIZES[i]; - code_poly = SIZES[i+1]; + code_poly = SIZES[i + 1]; code_mask = code_size - 1; break; } @@ -292,13 +282,13 @@ getcolors32(Imaging im, int maxcolors, int* size) pixel_mask = 0xffffffff; if (im->bands == 3) { - ((UINT8*) &pixel_mask)[3] = 0; + ((UINT8 *)&pixel_mask)[3] = 0; } colors = 0; for (y = 0; y < im->ysize; y++) { - INT32* p = im->image32[y]; + INT32 *p = im->image32[y]; for (x = 0; x < im->xsize; x++) { INT32 pixel = p[x] & pixel_mask; h = (pixel); /* null hashing */ @@ -309,7 +299,8 @@ getcolors32(Imaging im, int maxcolors, int* size) if (colors++ == maxcolors) { goto overflow; } - v->x = x; v->y = y; + v->x = x; + v->y = y; v->pixel = pixel; v->count = 1; continue; @@ -329,7 +320,8 @@ getcolors32(Imaging im, int maxcolors, int* size) if (colors++ == maxcolors) { goto overflow; } - v->x = x; v->y = y; + v->x = x; + v->y = y; v->pixel = pixel; v->count = 1; break; @@ -348,7 +340,7 @@ getcolors32(Imaging im, int maxcolors, int* size) overflow: /* pack the table */ - for (x = y = 0; x < (int) code_size; x++) + for (x = y = 0; x < (int)code_size; x++) if (table[x].count) { if (x != y) { table[y] = table[x]; diff --git a/src/libImaging/Gif.h b/src/libImaging/Gif.h index bb118396c..a85ce2b6e 100644 --- a/src/libImaging/Gif.h +++ b/src/libImaging/Gif.h @@ -7,17 +7,14 @@ * Copyright (c) Fredrik Lundh 1995-96. */ - /* Max size for a LZW code word. */ -#define GIFBITS 12 - -#define GIFTABLE (1< @@ -29,48 +28,44 @@ #include "Gif.h" - -#define NEWLINE(state, context) {\ - state->x = 0;\ - state->y += context->step;\ - while (state->y >= state->ysize)\ - switch (context->interlace) {\ - case 1:\ - context->repeat = state->y = 4;\ - context->interlace = 2;\ - break;\ - case 2:\ - context->step = 4;\ - context->repeat = state->y = 2;\ - context->interlace = 3;\ - break;\ - case 3:\ - context->step = 2;\ - context->repeat = state->y = 1;\ - context->interlace = 0;\ - break;\ - default:\ - return -1;\ - }\ - if (state->y < state->ysize) {\ - out = im->image8[state->y + state->yoff] + state->xoff;\ - }\ -} - +#define NEWLINE(state, context) \ + { \ + state->x = 0; \ + state->y += context->step; \ + while (state->y >= state->ysize) switch (context->interlace) { \ + case 1: \ + context->repeat = state->y = 4; \ + context->interlace = 2; \ + break; \ + case 2: \ + context->step = 4; \ + context->repeat = state->y = 2; \ + context->interlace = 3; \ + break; \ + case 3: \ + context->step = 2; \ + context->repeat = state->y = 1; \ + context->interlace = 0; \ + break; \ + default: \ + return -1; \ + } \ + if (state->y < state->ysize) { \ + out = im->image8[state->y + state->yoff] + state->xoff; \ + } \ + } int -ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t bytes) -{ - UINT8* p; - UINT8* out; +ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes) { + UINT8 *p; + UINT8 *out; int c, i; int thiscode; - GIFDECODERSTATE *context = (GIFDECODERSTATE*) state->context; + GIFDECODERSTATE *context = (GIFDECODERSTATE *)state->context; UINT8 *ptr = buffer; if (!state->state) { - /* Initialise state */ if (context->bits < 0 || context->bits > 12) { state->errcode = IMAGING_CODEC_CONFIG; @@ -97,9 +92,7 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t out = im->image8[state->y + state->yoff] + state->xoff + state->x; for (;;) { - if (state->state == 1) { - /* First free entry in table */ context->next = context->clear + 2; @@ -115,7 +108,6 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t } if (context->bufferindex < GIFBUFFER) { - /* Return whole buffer in one chunk */ i = GIFBUFFER - context->bufferindex; p = &context->buffer[context->bufferindex]; @@ -123,24 +115,21 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t context->bufferindex = GIFBUFFER; } else { - /* Get current symbol */ while (context->bitcount < context->codesize) { - if (context->blocksize > 0) { - /* Read next byte */ - c = *ptr++; bytes--; + c = *ptr++; + bytes--; context->blocksize--; /* New bits are shifted in from from the left. */ - context->bitbuffer |= (INT32) c << context->bitcount; + context->bitbuffer |= (INT32)c << context->bitcount; context->bitcount += 8; } else { - /* New GIF block */ /* We don't start decoding unless we have a full block */ @@ -148,19 +137,19 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t return ptr - buffer; } c = *ptr; - if (bytes < c+1) { + if (bytes < c + 1) { return ptr - buffer; } context->blocksize = c; - ptr++; bytes--; - + ptr++; + bytes--; } } /* Extract current symbol from bit buffer. */ - c = (int) context->bitbuffer & context->codemask; + c = (int)context->bitbuffer & context->codemask; /* Adjust buffer */ context->bitbuffer >>= context->codesize; @@ -185,7 +174,6 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t p = &context->lastdata; if (state->state == 2) { - /* First valid symbol after clear; use as is */ if (c > context->clear) { state->errcode = IMAGING_CODEC_BROKEN; @@ -196,7 +184,6 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t state->state = 3; } else { - thiscode = c; if (c > context->next) { @@ -205,7 +192,6 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t } if (c == context->next) { - /* c == next is allowed. not sure why. */ if (context->bufferindex <= 0) { @@ -213,15 +199,12 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t return -1; } - context->buffer[--context->bufferindex] = - context->lastdata; + context->buffer[--context->bufferindex] = context->lastdata; c = context->lastcode; - } while (c >= context->clear) { - /* Copy data string to buffer (beginning from right) */ if (context->bufferindex <= 0 || c >= GIFTABLE) { @@ -229,8 +212,7 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t return -1; } - context->buffer[--context->bufferindex] = - context->data[c]; + context->buffer[--context->bufferindex] = context->data[c]; c = context->link[c]; } @@ -238,26 +220,22 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t context->lastdata = c; if (context->next < GIFTABLE) { - /* We'll only add this symbol if we have room for it (take advise, Netscape!) */ context->data[context->next] = c; context->link[context->next] = context->lastcode; if (context->next == context->codemask && - context->codesize < GIFBITS) { - + context->codesize < GIFBITS) { /* Expand code size */ context->codesize++; context->codemask = (1 << context->codesize) - 1; } context->next++; - } context->lastcode = thiscode; - } } @@ -273,7 +251,7 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t /* FIXME: should we handle the transparency index in here??? */ if (i == 1) { - if (state->x < state->xsize-1) { + if (state->x < state->xsize - 1) { /* Single pixel, not at the end of the line. */ *out++ = p[0]; state->x++; @@ -282,7 +260,7 @@ ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t } else if (state->x + i <= state->xsize) { /* This string fits into current line. */ memcpy(out, p, i); - out += i; + out += i; state->x += i; if (state->x == state->xsize) { NEWLINE(state, context); diff --git a/src/libImaging/GifEncode.c b/src/libImaging/GifEncode.c index a0fef9933..14fd07cdd 100644 --- a/src/libImaging/GifEncode.c +++ b/src/libImaging/GifEncode.c @@ -35,12 +35,11 @@ enum { INIT, ENCODE, ENCODE_EOF, FLUSH, EXIT }; necessary. */ static inline int -emit(GIFENCODERSTATE *context, int byte) -{ +emit(GIFENCODERSTATE *context, int byte) { /* write a byte to the output buffer */ if (!context->block || context->block->size == 255) { - GIFENCODERBLOCK* block; + GIFENCODERBLOCK *block; /* no room in the current block (or no current block); allocate a new one */ @@ -74,7 +73,6 @@ emit(GIFENCODERSTATE *context, int byte) block->next = NULL; context->block = block; - } /* write new byte to block */ @@ -86,68 +84,68 @@ emit(GIFENCODERSTATE *context, int byte) /* write a code word to the current block. this is a macro to make sure it's inlined on all platforms */ -#define EMIT(code) {\ - context->bitbuffer |= ((INT32) (code)) << context->bitcount;\ - context->bitcount += 9;\ - while (context->bitcount >= 8) {\ - if (!emit(context, (UINT8) context->bitbuffer)) {\ - state->errcode = IMAGING_CODEC_MEMORY;\ - return 0;\ - }\ - context->bitbuffer >>= 8;\ - context->bitcount -= 8;\ - }\ -} +#define EMIT(code) \ + { \ + context->bitbuffer |= ((INT32)(code)) << context->bitcount; \ + context->bitcount += 9; \ + while (context->bitcount >= 8) { \ + if (!emit(context, (UINT8)context->bitbuffer)) { \ + state->errcode = IMAGING_CODEC_MEMORY; \ + return 0; \ + } \ + context->bitbuffer >>= 8; \ + context->bitcount -= 8; \ + } \ + } /* write a run. we use a combination of literals and combinations of literals. this can give quite decent compression for images with long stretches of identical pixels. but remember: if you want really good compression, use another file format. */ -#define EMIT_RUN(label) {\ -label:\ - while (context->count > 0) {\ - int run = 2;\ - EMIT(context->last);\ - context->count--;\ - if (state->count++ == LAST_CODE) {\ - EMIT(CLEAR_CODE);\ - state->count = FIRST_CODE;\ - goto label;\ - }\ - while (context->count >= run) {\ - EMIT(state->count - 1);\ - context->count -= run;\ - run++;\ - if (state->count++ == LAST_CODE) {\ - EMIT(CLEAR_CODE);\ - state->count = FIRST_CODE;\ - goto label;\ - }\ - }\ - if (context->count > 1) {\ - EMIT(state->count - 1 - (run - context->count));\ - context->count = 0;\ - if (state->count++ == LAST_CODE) {\ - EMIT(CLEAR_CODE);\ - state->count = FIRST_CODE;\ - }\ - break;\ - }\ - }\ -} +#define EMIT_RUN(label) \ + { \ + label: \ + while (context->count > 0) { \ + int run = 2; \ + EMIT(context->last); \ + context->count--; \ + if (state->count++ == LAST_CODE) { \ + EMIT(CLEAR_CODE); \ + state->count = FIRST_CODE; \ + goto label; \ + } \ + while (context->count >= run) { \ + EMIT(state->count - 1); \ + context->count -= run; \ + run++; \ + if (state->count++ == LAST_CODE) { \ + EMIT(CLEAR_CODE); \ + state->count = FIRST_CODE; \ + goto label; \ + } \ + } \ + if (context->count > 1) { \ + EMIT(state->count - 1 - (run - context->count)); \ + context->count = 0; \ + if (state->count++ == LAST_CODE) { \ + EMIT(CLEAR_CODE); \ + state->count = FIRST_CODE; \ + } \ + break; \ + } \ + } \ + } int -ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) -{ - UINT8* ptr; +ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { + UINT8 *ptr; int this; - GIFENCODERBLOCK* block; - GIFENCODERSTATE *context = (GIFENCODERSTATE*) state->context; + GIFENCODERBLOCK *block; + GIFENCODERSTATE *context = (GIFENCODERSTATE *)state->context; if (!state->state) { - /* place a clear code in the output buffer */ context->bitbuffer = CLEAR_CODE; context->bitcount = 9; @@ -167,22 +165,17 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) if (state->xsize <= 0 || state->ysize <= 0) { state->state = ENCODE_EOF; } - } ptr = buf; - for (;;) - - switch (state->state) { - + for (;;) switch (state->state) { case INIT: case ENCODE: /* identify and store a run of pixels */ if (state->x == 0 || state->x >= state->xsize) { - if (!context->interlace && state->y >= state->ysize) { state->state = ENCODE_EOF; break; @@ -196,9 +189,9 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) /* get another line of data */ state->shuffle( state->buffer, - (UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->xsize - ); + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->xsize); state->x = 0; @@ -231,7 +224,6 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) /* just make sure we don't loop forever */ context->interlace = 0; } - } /* Potential special case for xsize==1 */ if (state->x < state->xsize) { @@ -250,7 +242,6 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) } break; - case ENCODE_EOF: /* write the final run */ @@ -261,7 +252,7 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) /* empty the bit buffer */ while (context->bitcount > 0) { - if (!emit(context, (UINT8) context->bitbuffer)) { + if (!emit(context, (UINT8)context->bitbuffer)) { state->errcode = IMAGING_CODEC_MEMORY; return 0; } @@ -271,7 +262,7 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) /* flush the last block, and exit */ if (context->block) { - GIFENCODERBLOCK* block; + GIFENCODERBLOCK *block; block = context->flush; while (block && block->next) { block = block->next; @@ -291,45 +282,41 @@ ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) case EXIT: case FLUSH: - while (context->flush) { - - /* get a block from the flush queue */ - block = context->flush; - - if (block->size > 0) { - - /* make sure it fits into the output buffer */ - if (bytes < block->size+1) { - return ptr - buf; - } - - ptr[0] = block->size; - memcpy(ptr+1, block->data, block->size); - - ptr += block->size+1; - bytes -= block->size+1; + while (context->flush) { + /* get a block from the flush queue */ + block = context->flush; + if (block->size > 0) { + /* make sure it fits into the output buffer */ + if (bytes < block->size + 1) { + return ptr - buf; } - context->flush = block->next; - - if (context->free) { - free(context->free); - } - context->free = block; + ptr[0] = block->size; + memcpy(ptr + 1, block->data, block->size); + ptr += block->size + 1; + bytes -= block->size + 1; } - if (state->state == EXIT) { - /* this was the last block! */ - if (context->free) { - free(context->free); - } - state->errcode = IMAGING_CODEC_END; - return ptr - buf; - } + context->flush = block->next; - state->state = ENCODE; - break; - } + if (context->free) { + free(context->free); + } + context->free = block; + } + + if (state->state == EXIT) { + /* this was the last block! */ + if (context->free) { + free(context->free); + } + state->errcode = IMAGING_CODEC_END; + return ptr - buf; + } + + state->state = ENCODE; + break; + } } diff --git a/src/libImaging/HexDecode.c b/src/libImaging/HexDecode.c index 1def8766f..bd16cdbe1 100644 --- a/src/libImaging/HexDecode.c +++ b/src/libImaging/HexDecode.c @@ -13,23 +13,22 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" -#define HEX(v) ((v >= '0' && v <= '9') ? v - '0' :\ - (v >= 'a' && v <= 'f') ? v - 'a' + 10 :\ - (v >= 'A' && v <= 'F') ? v - 'A' + 10 : -1) +#define HEX(v) \ + ((v >= '0' && v <= '9') ? v - '0' \ + : (v >= 'a' && v <= 'f') ? v - 'a' + 10 \ + : (v >= 'A' && v <= 'F') ? v - 'A' + 10 \ + : -1) int -ImagingHexDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ - UINT8* ptr; +ImagingHexDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { + UINT8 *ptr; int a, b; ptr = buf; for (;;) { - if (bytes < 2) { return ptr - buf; } @@ -38,22 +37,19 @@ ImagingHexDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt b = HEX(ptr[1]); if (a < 0 || b < 0) { - ptr++; bytes--; } else { - ptr += 2; bytes -= 2; - state->buffer[state->x] = (a<<4) + b; + state->buffer[state->x] = (a << 4) + b; if (++state->x >= state->bytes) { - /* Got a full line, unpack it */ - state->shuffle((UINT8*) im->image[state->y], state->buffer, - state->xsize); + state->shuffle( + (UINT8 *)im->image[state->y], state->buffer, state->xsize); state->x = 0; @@ -62,7 +58,6 @@ ImagingHexDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt return -1; } } - } } } diff --git a/src/libImaging/Histo.c b/src/libImaging/Histo.c index 512e57a98..c5a547a64 100644 --- a/src/libImaging/Histo.c +++ b/src/libImaging/Histo.c @@ -16,10 +16,8 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - /* HISTOGRAM */ /* -------------------------------------------------------------------- * Take a histogram of an image. Returns a histogram object containing @@ -27,8 +25,7 @@ */ void -ImagingHistogramDelete(ImagingHistogram h) -{ +ImagingHistogramDelete(ImagingHistogram h) { if (h) { if (h->histogram) { free(h->histogram); @@ -38,31 +35,29 @@ ImagingHistogramDelete(ImagingHistogram h) } ImagingHistogram -ImagingHistogramNew(Imaging im) -{ +ImagingHistogramNew(Imaging im) { ImagingHistogram h; /* Create histogram descriptor */ h = calloc(1, sizeof(struct ImagingHistogramInstance)); if (!h) { - return (ImagingHistogram) ImagingError_MemoryError(); + return (ImagingHistogram)ImagingError_MemoryError(); } - strncpy(h->mode, im->mode, IMAGING_MODE_LENGTH-1); - h->mode[IMAGING_MODE_LENGTH-1] = 0; + strncpy(h->mode, im->mode, IMAGING_MODE_LENGTH - 1); + h->mode[IMAGING_MODE_LENGTH - 1] = 0; h->bands = im->bands; h->histogram = calloc(im->pixelsize, 256 * sizeof(long)); if (!h->histogram) { free(h); - return (ImagingHistogram) ImagingError_MemoryError(); + return (ImagingHistogram)ImagingError_MemoryError(); } return h; } ImagingHistogram -ImagingGetHistogram(Imaging im, Imaging imMask, void* minmax) -{ +ImagingGetHistogram(Imaging im, Imaging imMask, void *minmax) { ImagingSectionCookie cookie; int x, y, i; ImagingHistogram h; @@ -107,13 +102,13 @@ ImagingGetHistogram(Imaging im, Imaging imMask, void* minmax) } ImagingSectionEnter(&cookie); for (y = 0; y < im->ysize; y++) { - UINT8* in = (UINT8*) im->image32[y]; + UINT8 *in = (UINT8 *)im->image32[y]; for (x = 0; x < im->xsize; x++) { if (imMask->image8[y][x] != 0) { h->histogram[(*in++)]++; - h->histogram[(*in++)+256]++; - h->histogram[(*in++)+512]++; - h->histogram[(*in++)+768]++; + h->histogram[(*in++) + 256]++; + h->histogram[(*in++) + 512]++; + h->histogram[(*in++) + 768]++; } else { in += 4; } @@ -136,12 +131,12 @@ ImagingGetHistogram(Imaging im, Imaging imMask, void* minmax) case IMAGING_TYPE_UINT8: ImagingSectionEnter(&cookie); for (y = 0; y < im->ysize; y++) { - UINT8* in = (UINT8*) im->image[y]; + UINT8 *in = (UINT8 *)im->image[y]; for (x = 0; x < im->xsize; x++) { h->histogram[(*in++)]++; - h->histogram[(*in++)+256]++; - h->histogram[(*in++)+512]++; - h->histogram[(*in++)+768]++; + h->histogram[(*in++) + 256]++; + h->histogram[(*in++) + 512]++; + h->histogram[(*in++) + 768]++; } } ImagingSectionLeave(&cookie); @@ -155,16 +150,16 @@ ImagingGetHistogram(Imaging im, Imaging imMask, void* minmax) break; } memcpy(&imin, minmax, sizeof(imin)); - memcpy(&imax, ((char*)minmax) + sizeof(imin), sizeof(imax)); + memcpy(&imax, ((char *)minmax) + sizeof(imin), sizeof(imax)); if (imin >= imax) { break; } ImagingSectionEnter(&cookie); scale = 255.0F / (imax - imin); for (y = 0; y < im->ysize; y++) { - INT32* in = im->image32[y]; + INT32 *in = im->image32[y]; for (x = 0; x < im->xsize; x++) { - i = (int) (((*in++)-imin)*scale); + i = (int)(((*in++) - imin) * scale); if (i >= 0 && i < 256) { h->histogram[i]++; } @@ -181,16 +176,16 @@ ImagingGetHistogram(Imaging im, Imaging imMask, void* minmax) break; } memcpy(&fmin, minmax, sizeof(fmin)); - memcpy(&fmax, ((char*)minmax) + sizeof(fmin), sizeof(fmax)); + memcpy(&fmax, ((char *)minmax) + sizeof(fmin), sizeof(fmax)); if (fmin >= fmax) { break; } ImagingSectionEnter(&cookie); scale = 255.0F / (fmax - fmin); for (y = 0; y < im->ysize; y++) { - FLOAT32* in = (FLOAT32*) im->image32[y]; + FLOAT32 *in = (FLOAT32 *)im->image32[y]; for (x = 0; x < im->xsize; x++) { - i = (int) (((*in++)-fmin)*scale); + i = (int)(((*in++) - fmin) * scale); if (i >= 0 && i < 256) { h->histogram[i]++; } diff --git a/src/libImaging/ImDib.h b/src/libImaging/ImDib.h index e5a2cc0f6..91ff3f322 100644 --- a/src/libImaging/ImDib.h +++ b/src/libImaging/ImDib.h @@ -35,20 +35,27 @@ struct ImagingDIBInstance { ImagingShuffler unpack; }; -typedef struct ImagingDIBInstance* ImagingDIB; +typedef struct ImagingDIBInstance *ImagingDIB; -extern char* ImagingGetModeDIB(int size_out[2]); +extern char * +ImagingGetModeDIB(int size_out[2]); -extern ImagingDIB ImagingNewDIB(const char *mode, int xsize, int ysize); +extern ImagingDIB +ImagingNewDIB(const char *mode, int xsize, int ysize); -extern void ImagingDeleteDIB(ImagingDIB im); +extern void +ImagingDeleteDIB(ImagingDIB im); -extern void ImagingDrawDIB(ImagingDIB dib, void *dc, int dst[4], int src[4]); -extern void ImagingExposeDIB(ImagingDIB dib, void *dc); +extern void +ImagingDrawDIB(ImagingDIB dib, void *dc, int dst[4], int src[4]); +extern void +ImagingExposeDIB(ImagingDIB dib, void *dc); -extern int ImagingQueryPaletteDIB(ImagingDIB dib, void *dc); +extern int +ImagingQueryPaletteDIB(ImagingDIB dib, void *dc); -extern void ImagingPasteDIB(ImagingDIB dib, Imaging im, int xy[4]); +extern void +ImagingPasteDIB(ImagingDIB dib, Imaging im, int xy[4]); #if defined(__cplusplus) } diff --git a/src/libImaging/ImPlatform.h b/src/libImaging/ImPlatform.h index 576ceaa58..9a2060edf 100644 --- a/src/libImaging/ImPlatform.h +++ b/src/libImaging/ImPlatform.h @@ -10,7 +10,8 @@ #include "Python.h" /* Workaround issue #2479 */ -#if PY_VERSION_HEX < 0x03070000 && defined(PySlice_GetIndicesEx) && !defined(PYPY_VERSION) +#if PY_VERSION_HEX < 0x03070000 && defined(PySlice_GetIndicesEx) && \ + !defined(PYPY_VERSION) #undef PySlice_GetIndicesEx #endif @@ -62,7 +63,7 @@ #define INT64 long #endif -#define INT8 signed char +#define INT8 signed char #define UINT8 unsigned char #define UINT16 unsigned INT16 @@ -76,11 +77,9 @@ #define FLOAT64 double #ifdef _MSC_VER -typedef signed __int64 int64_t; +typedef signed __int64 int64_t; #endif #ifdef __GNUC__ - #define GCC_VERSION (__GNUC__ * 10000 \ - + __GNUC_MINOR__ * 100 \ - + __GNUC_PATCHLEVEL__) +#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif diff --git a/src/libImaging/Imaging.h b/src/libImaging/Imaging.h index d7dbe0325..ae323f390 100644 --- a/src/libImaging/Imaging.h +++ b/src/libImaging/Imaging.h @@ -10,20 +10,16 @@ * See the README file for information on usage and redistribution. */ - #include "ImPlatform.h" - #if defined(__cplusplus) extern "C" { #endif - #ifndef M_PI -#define M_PI 3.1415926535897932384626433832795 +#define M_PI 3.1415926535897932384626433832795 #endif - /* -------------------------------------------------------------------- */ /* @@ -57,12 +53,12 @@ extern "C" { /* Handles */ -typedef struct ImagingMemoryInstance* Imaging; +typedef struct ImagingMemoryInstance *Imaging; -typedef struct ImagingAccessInstance* ImagingAccess; -typedef struct ImagingHistogramInstance* ImagingHistogram; -typedef struct ImagingOutlineInstance* ImagingOutline; -typedef struct ImagingPaletteInstance* ImagingPalette; +typedef struct ImagingAccessInstance *ImagingAccess; +typedef struct ImagingHistogramInstance *ImagingHistogram; +typedef struct ImagingOutlineInstance *ImagingOutline; +typedef struct ImagingPaletteInstance *ImagingPalette; /* handle magics (used with PyCObject). */ #define IMAGING_MAGIC "PIL Imaging" @@ -73,7 +69,8 @@ typedef struct ImagingPaletteInstance* ImagingPalette; #define IMAGING_TYPE_FLOAT32 2 #define IMAGING_TYPE_SPECIAL 3 /* check mode for details */ -#define IMAGING_MODE_LENGTH 6+1 /* Band names ("1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "BGR;xy") */ +#define IMAGING_MODE_LENGTH \ + 6 + 1 /* Band names ("1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "BGR;xy") */ typedef struct { char *ptr; @@ -81,158 +78,178 @@ typedef struct { } ImagingMemoryBlock; struct ImagingMemoryInstance { - /* Format */ - char mode[IMAGING_MODE_LENGTH]; /* Band names ("1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "BGR;xy") */ - int type; /* Data type (IMAGING_TYPE_*) */ - int depth; /* Depth (ignored in this version) */ - int bands; /* Number of bands (1, 2, 3, or 4) */ - int xsize; /* Image dimension. */ + char mode[IMAGING_MODE_LENGTH]; /* Band names ("1", "L", "P", "RGB", "RGBA", "CMYK", + "YCbCr", "BGR;xy") */ + int type; /* Data type (IMAGING_TYPE_*) */ + int depth; /* Depth (ignored in this version) */ + int bands; /* Number of bands (1, 2, 3, or 4) */ + int xsize; /* Image dimension. */ int ysize; /* Colour palette (for "P" images only) */ ImagingPalette palette; /* Data pointers */ - UINT8 **image8; /* Set for 8-bit images (pixelsize=1). */ - INT32 **image32; /* Set for 32-bit images (pixelsize=4). */ + UINT8 **image8; /* Set for 8-bit images (pixelsize=1). */ + INT32 **image32; /* Set for 32-bit images (pixelsize=4). */ /* Internals */ - char **image; /* Actual raster data. */ - char *block; /* Set if data is allocated in a single block. */ - ImagingMemoryBlock *blocks; /* Memory blocks for pixel storage */ + char **image; /* Actual raster data. */ + char *block; /* Set if data is allocated in a single block. */ + ImagingMemoryBlock *blocks; /* Memory blocks for pixel storage */ - int pixelsize; /* Size of a pixel, in bytes (1, 2 or 4) */ - int linesize; /* Size of a line, in bytes (xsize * pixelsize) */ + int pixelsize; /* Size of a pixel, in bytes (1, 2 or 4) */ + int linesize; /* Size of a line, in bytes (xsize * pixelsize) */ /* Virtual methods */ void (*destroy)(Imaging im); }; +#define IMAGING_PIXEL_1(im, x, y) ((im)->image8[(y)][(x)]) +#define IMAGING_PIXEL_L(im, x, y) ((im)->image8[(y)][(x)]) +#define IMAGING_PIXEL_LA(im, x, y) ((im)->image[(y)][(x)*4]) +#define IMAGING_PIXEL_P(im, x, y) ((im)->image8[(y)][(x)]) +#define IMAGING_PIXEL_PA(im, x, y) ((im)->image[(y)][(x)*4]) +#define IMAGING_PIXEL_I(im, x, y) ((im)->image32[(y)][(x)]) +#define IMAGING_PIXEL_F(im, x, y) (((FLOAT32 *)(im)->image32[y])[x]) +#define IMAGING_PIXEL_RGB(im, x, y) ((im)->image[(y)][(x)*4]) +#define IMAGING_PIXEL_RGBA(im, x, y) ((im)->image[(y)][(x)*4]) +#define IMAGING_PIXEL_CMYK(im, x, y) ((im)->image[(y)][(x)*4]) +#define IMAGING_PIXEL_YCbCr(im, x, y) ((im)->image[(y)][(x)*4]) -#define IMAGING_PIXEL_1(im,x,y) ((im)->image8[(y)][(x)]) -#define IMAGING_PIXEL_L(im,x,y) ((im)->image8[(y)][(x)]) -#define IMAGING_PIXEL_LA(im,x,y) ((im)->image[(y)][(x)*4]) -#define IMAGING_PIXEL_P(im,x,y) ((im)->image8[(y)][(x)]) -#define IMAGING_PIXEL_PA(im,x,y) ((im)->image[(y)][(x)*4]) -#define IMAGING_PIXEL_I(im,x,y) ((im)->image32[(y)][(x)]) -#define IMAGING_PIXEL_F(im,x,y) (((FLOAT32*)(im)->image32[y])[x]) -#define IMAGING_PIXEL_RGB(im,x,y) ((im)->image[(y)][(x)*4]) -#define IMAGING_PIXEL_RGBA(im,x,y) ((im)->image[(y)][(x)*4]) -#define IMAGING_PIXEL_CMYK(im,x,y) ((im)->image[(y)][(x)*4]) -#define IMAGING_PIXEL_YCbCr(im,x,y) ((im)->image[(y)][(x)*4]) - -#define IMAGING_PIXEL_UINT8(im,x,y) ((im)->image8[(y)][(x)]) -#define IMAGING_PIXEL_INT32(im,x,y) ((im)->image32[(y)][(x)]) -#define IMAGING_PIXEL_FLOAT32(im,x,y) (((FLOAT32*)(im)->image32[y])[x]) +#define IMAGING_PIXEL_UINT8(im, x, y) ((im)->image8[(y)][(x)]) +#define IMAGING_PIXEL_INT32(im, x, y) ((im)->image32[(y)][(x)]) +#define IMAGING_PIXEL_FLOAT32(im, x, y) (((FLOAT32 *)(im)->image32[y])[x]) struct ImagingAccessInstance { - const char* mode; - void* (*line)(Imaging im, int x, int y); - void (*get_pixel)(Imaging im, int x, int y, void* pixel); - void (*put_pixel)(Imaging im, int x, int y, const void* pixel); + const char *mode; + void *(*line)(Imaging im, int x, int y); + void (*get_pixel)(Imaging im, int x, int y, void *pixel); + void (*put_pixel)(Imaging im, int x, int y, const void *pixel); }; struct ImagingHistogramInstance { - /* Format */ - char mode[IMAGING_MODE_LENGTH]; /* Band names (of corresponding source image) */ - int bands; /* Number of bands (1, 3, or 4) */ + char mode[IMAGING_MODE_LENGTH]; /* Band names (of corresponding source image) */ + int bands; /* Number of bands (1, 3, or 4) */ /* Data */ - long *histogram; /* Histogram (bands*256 longs) */ - + long *histogram; /* Histogram (bands*256 longs) */ }; - struct ImagingPaletteInstance { - /* Format */ - char mode[IMAGING_MODE_LENGTH]; /* Band names */ + char mode[IMAGING_MODE_LENGTH]; /* Band names */ /* Data */ - UINT8 palette[1024];/* Palette data (same format as image data) */ - - INT16* cache; /* Palette cache (used for predefined palettes) */ - int keep_cache; /* This palette will be reused; keep cache */ + UINT8 palette[1024]; /* Palette data (same format as image data) */ + INT16 *cache; /* Palette cache (used for predefined palettes) */ + int keep_cache; /* This palette will be reused; keep cache */ }; typedef struct ImagingMemoryArena { - int alignment; /* Alignment in memory of each line of an image */ - int block_size; /* Preferred block size, bytes */ - int blocks_max; /* Maximum number of cached blocks */ - int blocks_cached; /* Current number of blocks not associated with images */ + int alignment; /* Alignment in memory of each line of an image */ + int block_size; /* Preferred block size, bytes */ + int blocks_max; /* Maximum number of cached blocks */ + int blocks_cached; /* Current number of blocks not associated with images */ ImagingMemoryBlock *blocks_pool; - int stats_new_count; /* Number of new allocated images */ - int stats_allocated_blocks; /* Number of allocated blocks */ - int stats_reused_blocks; /* Number of blocks which were retrieved from a pool */ - int stats_reallocated_blocks; /* Number of blocks which were actually reallocated after retrieving */ - int stats_freed_blocks; /* Number of freed blocks */ -} *ImagingMemoryArena; - + int stats_new_count; /* Number of new allocated images */ + int stats_allocated_blocks; /* Number of allocated blocks */ + int stats_reused_blocks; /* Number of blocks which were retrieved from a pool */ + int stats_reallocated_blocks; /* Number of blocks which were actually reallocated + after retrieving */ + int stats_freed_blocks; /* Number of freed blocks */ +} * ImagingMemoryArena; /* Objects */ /* ------- */ extern struct ImagingMemoryArena ImagingDefaultArena; -extern int ImagingMemorySetBlocksMax(ImagingMemoryArena arena, int blocks_max); -extern void ImagingMemoryClearCache(ImagingMemoryArena arena, int new_size); +extern int +ImagingMemorySetBlocksMax(ImagingMemoryArena arena, int blocks_max); +extern void +ImagingMemoryClearCache(ImagingMemoryArena arena, int new_size); -extern Imaging ImagingNew(const char* mode, int xsize, int ysize); -extern Imaging ImagingNewDirty(const char* mode, int xsize, int ysize); -extern Imaging ImagingNew2Dirty(const char* mode, Imaging imOut, Imaging imIn); -extern void ImagingDelete(Imaging im); +extern Imaging +ImagingNew(const char *mode, int xsize, int ysize); +extern Imaging +ImagingNewDirty(const char *mode, int xsize, int ysize); +extern Imaging +ImagingNew2Dirty(const char *mode, Imaging imOut, Imaging imIn); +extern void +ImagingDelete(Imaging im); -extern Imaging ImagingNewBlock(const char* mode, int xsize, int ysize); +extern Imaging +ImagingNewBlock(const char *mode, int xsize, int ysize); -extern Imaging ImagingNewPrologue(const char *mode, - int xsize, int ysize); -extern Imaging ImagingNewPrologueSubtype(const char *mode, - int xsize, int ysize, - int structure_size); +extern Imaging +ImagingNewPrologue(const char *mode, int xsize, int ysize); +extern Imaging +ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int structure_size); -extern void ImagingCopyPalette(Imaging destination, Imaging source); +extern void +ImagingCopyPalette(Imaging destination, Imaging source); -extern void ImagingHistogramDelete(ImagingHistogram histogram); +extern void +ImagingHistogramDelete(ImagingHistogram histogram); -extern void ImagingAccessInit(void); -extern ImagingAccess ImagingAccessNew(Imaging im); -extern void _ImagingAccessDelete(Imaging im, ImagingAccess access); +extern void +ImagingAccessInit(void); +extern ImagingAccess +ImagingAccessNew(Imaging im); +extern void +_ImagingAccessDelete(Imaging im, ImagingAccess access); #define ImagingAccessDelete(im, access) /* nop, for now */ -extern ImagingPalette ImagingPaletteNew(const char *mode); -extern ImagingPalette ImagingPaletteNewBrowser(void); -extern ImagingPalette ImagingPaletteDuplicate(ImagingPalette palette); -extern void ImagingPaletteDelete(ImagingPalette palette); +extern ImagingPalette +ImagingPaletteNew(const char *mode); +extern ImagingPalette +ImagingPaletteNewBrowser(void); +extern ImagingPalette +ImagingPaletteDuplicate(ImagingPalette palette); +extern void +ImagingPaletteDelete(ImagingPalette palette); -extern int ImagingPaletteCachePrepare(ImagingPalette palette); -extern void ImagingPaletteCacheUpdate(ImagingPalette palette, - int r, int g, int b); -extern void ImagingPaletteCacheDelete(ImagingPalette palette); +extern int +ImagingPaletteCachePrepare(ImagingPalette palette); +extern void +ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b); +extern void +ImagingPaletteCacheDelete(ImagingPalette palette); -#define ImagingPaletteCache(p, r, g, b)\ - p->cache[(r>>2) + (g>>2)*64 + (b>>2)*64*64] +#define ImagingPaletteCache(p, r, g, b) \ + p->cache[(r >> 2) + (g >> 2) * 64 + (b >> 2) * 64 * 64] -extern Imaging ImagingQuantize(Imaging im, int colours, int mode, int kmeans); +extern Imaging +ImagingQuantize(Imaging im, int colours, int mode, int kmeans); /* Threading */ /* --------- */ -typedef void* ImagingSectionCookie; +typedef void *ImagingSectionCookie; -extern void ImagingSectionEnter(ImagingSectionCookie* cookie); -extern void ImagingSectionLeave(ImagingSectionCookie* cookie); +extern void +ImagingSectionEnter(ImagingSectionCookie *cookie); +extern void +ImagingSectionLeave(ImagingSectionCookie *cookie); /* Exceptions */ /* ---------- */ -extern void* ImagingError_OSError(void); -extern void* ImagingError_MemoryError(void); -extern void* ImagingError_ModeError(void); /* maps to ValueError by default */ -extern void* ImagingError_Mismatch(void); /* maps to ValueError by default */ -extern void* ImagingError_ValueError(const char* message); -extern void ImagingError_Clear(void); +extern void * +ImagingError_OSError(void); +extern void * +ImagingError_MemoryError(void); +extern void * +ImagingError_ModeError(void); /* maps to ValueError by default */ +extern void * +ImagingError_Mismatch(void); /* maps to ValueError by default */ +extern void * +ImagingError_ValueError(const char *message); +extern void +ImagingError_Clear(void); /* Transform callbacks */ /* ------------------- */ @@ -242,7 +259,6 @@ extern void ImagingError_Clear(void); #define IMAGING_TRANSFORM_PERSPECTIVE 2 #define IMAGING_TRANSFORM_QUAD 3 - /* standard filters */ #define IMAGING_TRANSFORM_NEAREST 0 #define IMAGING_TRANSFORM_BOX 4 @@ -251,249 +267,391 @@ extern void ImagingError_Clear(void); #define IMAGING_TRANSFORM_BICUBIC 3 #define IMAGING_TRANSFORM_LANCZOS 1 -typedef int (*ImagingTransformMap)(double* X, double* Y, - int x, int y, void* data); -typedef int (*ImagingTransformFilter)(void* out, Imaging im, - double x, double y); +typedef int (*ImagingTransformMap)(double *X, double *Y, int x, int y, void *data); +typedef int (*ImagingTransformFilter)(void *out, Imaging im, double x, double y); /* Image Manipulation Methods */ /* -------------------------- */ -extern Imaging ImagingAlphaComposite(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingBlend(Imaging imIn1, Imaging imIn2, float alpha); -extern Imaging ImagingCopy(Imaging im); -extern Imaging ImagingConvert(Imaging im, const char* mode, ImagingPalette palette, int dither); -extern Imaging ImagingConvertInPlace(Imaging im, const char* mode); -extern Imaging ImagingConvertMatrix(Imaging im, const char *mode, float m[]); -extern Imaging ImagingConvertTransparent(Imaging im, const char *mode, int r, int g, int b); -extern Imaging ImagingCrop(Imaging im, int x0, int y0, int x1, int y1); -extern Imaging ImagingExpand(Imaging im, int x, int y, int mode); -extern Imaging ImagingFill(Imaging im, const void* ink); -extern int ImagingFill2( - Imaging into, const void* ink, Imaging mask, - int x0, int y0, int x1, int y1); -extern Imaging ImagingFillBand(Imaging im, int band, int color); -extern Imaging ImagingFillLinearGradient(const char* mode); -extern Imaging ImagingFillRadialGradient(const char* mode); -extern Imaging ImagingFilter( - Imaging im, int xsize, int ysize, const FLOAT32* kernel, - FLOAT32 offset); -extern Imaging ImagingFlipLeftRight(Imaging imOut, Imaging imIn); -extern Imaging ImagingFlipTopBottom(Imaging imOut, Imaging imIn); -extern Imaging ImagingGaussianBlur(Imaging imOut, Imaging imIn, float radius, - int passes); -extern Imaging ImagingGetBand(Imaging im, int band); -extern Imaging ImagingMerge(const char* mode, Imaging bands[4]); -extern int ImagingSplit(Imaging im, Imaging bands[4]); -extern int ImagingGetBBox(Imaging im, int bbox[4]); -typedef struct { int x, y; INT32 count; INT32 pixel; } ImagingColorItem; -extern ImagingColorItem* ImagingGetColors(Imaging im, int maxcolors, - int *colors); -extern int ImagingGetExtrema(Imaging im, void *extrema); -extern int ImagingGetProjection(Imaging im, UINT8* xproj, UINT8* yproj); -extern ImagingHistogram ImagingGetHistogram( - Imaging im, Imaging mask, void *extrema); -extern Imaging ImagingModeFilter(Imaging im, int size); -extern Imaging ImagingNegative(Imaging im); -extern Imaging ImagingOffset(Imaging im, int xoffset, int yoffset); -extern int ImagingPaste( - Imaging into, Imaging im, Imaging mask, - int x0, int y0, int x1, int y1); -extern Imaging ImagingPoint( - Imaging im, const char* tablemode, const void* table); -extern Imaging ImagingPointTransform( - Imaging imIn, double scale, double offset); -extern Imaging ImagingPutBand(Imaging im, Imaging imIn, int band); -extern Imaging ImagingRankFilter(Imaging im, int size, int rank); -extern Imaging ImagingRotate90(Imaging imOut, Imaging imIn); -extern Imaging ImagingRotate180(Imaging imOut, Imaging imIn); -extern Imaging ImagingRotate270(Imaging imOut, Imaging imIn); -extern Imaging ImagingTranspose(Imaging imOut, Imaging imIn); -extern Imaging ImagingTransverse(Imaging imOut, Imaging imIn); -extern Imaging ImagingResample(Imaging imIn, int xsize, int ysize, int filter, float box[4]); -extern Imaging ImagingReduce(Imaging imIn, int xscale, int yscale, int box[4]); -extern Imaging ImagingTransform( - Imaging imOut, Imaging imIn, int method, int x0, int y0, int x1, int y1, - double *a, int filter, int fill); -extern Imaging ImagingUnsharpMask( - Imaging imOut, Imaging im, float radius, int percent, int threshold); -extern Imaging ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n); -extern Imaging ImagingColorLUT3D_linear(Imaging imOut, Imaging imIn, - int table_channels, int size1D, int size2D, int size3D, INT16* table); +extern Imaging +ImagingAlphaComposite(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingBlend(Imaging imIn1, Imaging imIn2, float alpha); +extern Imaging +ImagingCopy(Imaging im); +extern Imaging +ImagingConvert(Imaging im, const char *mode, ImagingPalette palette, int dither); +extern Imaging +ImagingConvertInPlace(Imaging im, const char *mode); +extern Imaging +ImagingConvertMatrix(Imaging im, const char *mode, float m[]); +extern Imaging +ImagingConvertTransparent(Imaging im, const char *mode, int r, int g, int b); +extern Imaging +ImagingCrop(Imaging im, int x0, int y0, int x1, int y1); +extern Imaging +ImagingExpand(Imaging im, int x, int y, int mode); +extern Imaging +ImagingFill(Imaging im, const void *ink); +extern int +ImagingFill2( + Imaging into, const void *ink, Imaging mask, int x0, int y0, int x1, int y1); +extern Imaging +ImagingFillBand(Imaging im, int band, int color); +extern Imaging +ImagingFillLinearGradient(const char *mode); +extern Imaging +ImagingFillRadialGradient(const char *mode); +extern Imaging +ImagingFilter(Imaging im, int xsize, int ysize, const FLOAT32 *kernel, FLOAT32 offset); +extern Imaging +ImagingFlipLeftRight(Imaging imOut, Imaging imIn); +extern Imaging +ImagingFlipTopBottom(Imaging imOut, Imaging imIn); +extern Imaging +ImagingGaussianBlur(Imaging imOut, Imaging imIn, float radius, int passes); +extern Imaging +ImagingGetBand(Imaging im, int band); +extern Imaging +ImagingMerge(const char *mode, Imaging bands[4]); +extern int +ImagingSplit(Imaging im, Imaging bands[4]); +extern int +ImagingGetBBox(Imaging im, int bbox[4]); +typedef struct { + int x, y; + INT32 count; + INT32 pixel; +} ImagingColorItem; +extern ImagingColorItem * +ImagingGetColors(Imaging im, int maxcolors, int *colors); +extern int +ImagingGetExtrema(Imaging im, void *extrema); +extern int +ImagingGetProjection(Imaging im, UINT8 *xproj, UINT8 *yproj); +extern ImagingHistogram +ImagingGetHistogram(Imaging im, Imaging mask, void *extrema); +extern Imaging +ImagingModeFilter(Imaging im, int size); +extern Imaging +ImagingNegative(Imaging im); +extern Imaging +ImagingOffset(Imaging im, int xoffset, int yoffset); +extern int +ImagingPaste(Imaging into, Imaging im, Imaging mask, int x0, int y0, int x1, int y1); +extern Imaging +ImagingPoint(Imaging im, const char *tablemode, const void *table); +extern Imaging +ImagingPointTransform(Imaging imIn, double scale, double offset); +extern Imaging +ImagingPutBand(Imaging im, Imaging imIn, int band); +extern Imaging +ImagingRankFilter(Imaging im, int size, int rank); +extern Imaging +ImagingRotate90(Imaging imOut, Imaging imIn); +extern Imaging +ImagingRotate180(Imaging imOut, Imaging imIn); +extern Imaging +ImagingRotate270(Imaging imOut, Imaging imIn); +extern Imaging +ImagingTranspose(Imaging imOut, Imaging imIn); +extern Imaging +ImagingTransverse(Imaging imOut, Imaging imIn); +extern Imaging +ImagingResample(Imaging imIn, int xsize, int ysize, int filter, float box[4]); +extern Imaging +ImagingReduce(Imaging imIn, int xscale, int yscale, int box[4]); +extern Imaging +ImagingTransform( + Imaging imOut, + Imaging imIn, + int method, + int x0, + int y0, + int x1, + int y1, + double *a, + int filter, + int fill); +extern Imaging +ImagingUnsharpMask(Imaging imOut, Imaging im, float radius, int percent, int threshold); +extern Imaging +ImagingBoxBlur(Imaging imOut, Imaging imIn, float radius, int n); +extern Imaging +ImagingColorLUT3D_linear( + Imaging imOut, + Imaging imIn, + int table_channels, + int size1D, + int size2D, + int size3D, + INT16 *table); -extern Imaging ImagingCopy2(Imaging imOut, Imaging imIn); -extern Imaging ImagingConvert2(Imaging imOut, Imaging imIn); +extern Imaging +ImagingCopy2(Imaging imOut, Imaging imIn); +extern Imaging +ImagingConvert2(Imaging imOut, Imaging imIn); /* Channel operations */ /* any mode, except "F" */ -extern Imaging ImagingChopLighter(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopDarker(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopDifference(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopMultiply(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopScreen(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopAdd( - Imaging imIn1, Imaging imIn2, float scale, int offset); -extern Imaging ImagingChopSubtract( - Imaging imIn1, Imaging imIn2, float scale, int offset); -extern Imaging ImagingChopAddModulo(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopSubtractModulo(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopSoftLight(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopHardLight(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingOverlay(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopLighter(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopDarker(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopDifference(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopMultiply(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopScreen(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopAdd(Imaging imIn1, Imaging imIn2, float scale, int offset); +extern Imaging +ImagingChopSubtract(Imaging imIn1, Imaging imIn2, float scale, int offset); +extern Imaging +ImagingChopAddModulo(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopSubtractModulo(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopSoftLight(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopHardLight(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingOverlay(Imaging imIn1, Imaging imIn2); /* "1" images only */ -extern Imaging ImagingChopAnd(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopOr(Imaging imIn1, Imaging imIn2); -extern Imaging ImagingChopXor(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopAnd(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopOr(Imaging imIn1, Imaging imIn2); +extern Imaging +ImagingChopXor(Imaging imIn1, Imaging imIn2); /* Graphics */ -extern int ImagingDrawArc(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, const void* ink, int width, - int op); -extern int ImagingDrawBitmap(Imaging im, int x0, int y0, Imaging bitmap, - const void* ink, int op); -extern int ImagingDrawChord(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, const void* ink, int fill, - int width, int op); -extern int ImagingDrawEllipse(Imaging im, int x0, int y0, int x1, int y1, - const void* ink, int fill, int width, int op); -extern int ImagingDrawLine(Imaging im, int x0, int y0, int x1, int y1, - const void* ink, int op); -extern int ImagingDrawWideLine(Imaging im, int x0, int y0, int x1, int y1, - const void* ink, int width, int op); -extern int ImagingDrawPieslice(Imaging im, int x0, int y0, int x1, int y1, - float start, float end, const void* ink, int fill, - int width, int op); -extern int ImagingDrawPoint(Imaging im, int x, int y, const void* ink, int op); -extern int ImagingDrawPolygon(Imaging im, int points, int *xy, - const void* ink, int fill, int op); -extern int ImagingDrawRectangle(Imaging im, int x0, int y0, int x1, int y1, - const void* ink, int fill, int width, int op); +extern int +ImagingDrawArc( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink, + int width, + int op); +extern int +ImagingDrawBitmap(Imaging im, int x0, int y0, Imaging bitmap, const void *ink, int op); +extern int +ImagingDrawChord( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink, + int fill, + int width, + int op); +extern int +ImagingDrawEllipse( + Imaging im, + int x0, + int y0, + int x1, + int y1, + const void *ink, + int fill, + int width, + int op); +extern int +ImagingDrawLine(Imaging im, int x0, int y0, int x1, int y1, const void *ink, int op); +extern int +ImagingDrawWideLine( + Imaging im, int x0, int y0, int x1, int y1, const void *ink, int width, int op); +extern int +ImagingDrawPieslice( + Imaging im, + int x0, + int y0, + int x1, + int y1, + float start, + float end, + const void *ink, + int fill, + int width, + int op); +extern int +ImagingDrawPoint(Imaging im, int x, int y, const void *ink, int op); +extern int +ImagingDrawPolygon(Imaging im, int points, int *xy, const void *ink, int fill, int op); +extern int +ImagingDrawRectangle( + Imaging im, + int x0, + int y0, + int x1, + int y1, + const void *ink, + int fill, + int width, + int op); /* Level 2 graphics (WORK IN PROGRESS) */ -extern ImagingOutline ImagingOutlineNew(void); -extern void ImagingOutlineDelete(ImagingOutline outline); +extern ImagingOutline +ImagingOutlineNew(void); +extern void +ImagingOutlineDelete(ImagingOutline outline); -extern int ImagingDrawOutline(Imaging im, ImagingOutline outline, - const void* ink, int fill, int op); +extern int +ImagingDrawOutline( + Imaging im, ImagingOutline outline, const void *ink, int fill, int op); -extern int ImagingOutlineMove(ImagingOutline outline, float x, float y); -extern int ImagingOutlineLine(ImagingOutline outline, float x, float y); -extern int ImagingOutlineCurve(ImagingOutline outline, float x1, float y1, - float x2, float y2, float x3, float y3); -extern int ImagingOutlineTransform(ImagingOutline outline, double a[6]); +extern int +ImagingOutlineMove(ImagingOutline outline, float x, float y); +extern int +ImagingOutlineLine(ImagingOutline outline, float x, float y); +extern int +ImagingOutlineCurve( + ImagingOutline outline, float x1, float y1, float x2, float y2, float x3, float y3); +extern int +ImagingOutlineTransform(ImagingOutline outline, double a[6]); -extern int ImagingOutlineClose(ImagingOutline outline); +extern int +ImagingOutlineClose(ImagingOutline outline); /* Special effects */ -extern Imaging ImagingEffectSpread(Imaging imIn, int distance); -extern Imaging ImagingEffectNoise(int xsize, int ysize, float sigma); -extern Imaging ImagingEffectMandelbrot(int xsize, int ysize, - double extent[4], int quality); - +extern Imaging +ImagingEffectSpread(Imaging imIn, int distance); +extern Imaging +ImagingEffectNoise(int xsize, int ysize, float sigma); +extern Imaging +ImagingEffectMandelbrot(int xsize, int ysize, double extent[4], int quality); /* File I/O */ /* -------- */ /* Built-in drivers */ -extern Imaging ImagingOpenPPM(const char* filename); -extern int ImagingSavePPM(Imaging im, const char* filename); +extern Imaging +ImagingOpenPPM(const char *filename); +extern int +ImagingSavePPM(Imaging im, const char *filename); /* Codecs */ typedef struct ImagingCodecStateInstance *ImagingCodecState; -typedef int (*ImagingCodec)(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); +typedef int (*ImagingCodec)( + Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); -extern int ImagingBcnDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingBitDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingEpsEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); -extern int ImagingFliDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingGifDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingGifEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); -extern int ImagingHexDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -#ifdef HAVE_LIBJPEG -extern int ImagingJpegDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingJpegDecodeCleanup(ImagingCodecState state); -extern int ImagingJpegUseJCSExtensions(void); +extern int +ImagingBcnDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingBitDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingEpsEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); +extern int +ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingGifDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingGifEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); +extern int +ImagingHexDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +#ifdef HAVE_LIBJPEG +extern int +ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingJpegDecodeCleanup(ImagingCodecState state); +extern int +ImagingJpegUseJCSExtensions(void); -extern int ImagingJpegEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); +extern int +ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); #endif #ifdef HAVE_OPENJPEG -extern int ImagingJpeg2KDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingJpeg2KDecodeCleanup(ImagingCodecState state); -extern int ImagingJpeg2KEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); -extern int ImagingJpeg2KEncodeCleanup(ImagingCodecState state); +extern int +ImagingJpeg2KDecode( + Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingJpeg2KDecodeCleanup(ImagingCodecState state); +extern int +ImagingJpeg2KEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); +extern int +ImagingJpeg2KEncodeCleanup(ImagingCodecState state); #endif -#ifdef HAVE_LIBTIFF -extern int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); +#ifdef HAVE_LIBTIFF +extern int +ImagingLibTiffDecode( + Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); #endif -#ifdef HAVE_LIBMPEG -extern int ImagingMpegDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); +#ifdef HAVE_LIBMPEG +extern int +ImagingMpegDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); #endif -extern int ImagingMspDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingPackbitsDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingPcdDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingPcxDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingPcxEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); -extern int ImagingRawDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingRawEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); -extern int ImagingSgiRleDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingSunRleDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingTgaRleDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingTgaRleEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); -extern int ImagingXbmDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingXbmEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); -#ifdef HAVE_LIBZ -extern int ImagingZipDecode(Imaging im, ImagingCodecState state, - UINT8* buffer, Py_ssize_t bytes); -extern int ImagingZipDecodeCleanup(ImagingCodecState state); -extern int ImagingZipEncode(Imaging im, ImagingCodecState state, - UINT8* buffer, int bytes); -extern int ImagingZipEncodeCleanup(ImagingCodecState state); +extern int +ImagingMspDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingPackbitsDecode( + Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingPcxEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); +extern int +ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingRawEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); +extern int +ImagingSgiRleDecode( + Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingSunRleDecode( + Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingTgaRleDecode( + Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); +extern int +ImagingXbmDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingXbmEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); +#ifdef HAVE_LIBZ +extern int +ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes); +extern int +ImagingZipDecodeCleanup(ImagingCodecState state); +extern int +ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes); +extern int +ImagingZipEncodeCleanup(ImagingCodecState state); #endif -typedef void (*ImagingShuffler)(UINT8* out, const UINT8* in, int pixels); +typedef void (*ImagingShuffler)(UINT8 *out, const UINT8 *in, int pixels); /* Public shufflers */ -extern void ImagingPackBGR(UINT8* out, const UINT8* in, int pixels); -extern void ImagingUnpackYCC(UINT8* out, const UINT8* in, int pixels); -extern void ImagingUnpackYCCA(UINT8* out, const UINT8* in, int pixels); +extern void +ImagingPackBGR(UINT8 *out, const UINT8 *in, int pixels); +extern void +ImagingUnpackYCC(UINT8 *out, const UINT8 *in, int pixels); +extern void +ImagingUnpackYCCA(UINT8 *out, const UINT8 *in, int pixels); -extern void ImagingConvertRGB2YCbCr(UINT8* out, const UINT8* in, int pixels); -extern void ImagingConvertYCbCr2RGB(UINT8* out, const UINT8* in, int pixels); +extern void +ImagingConvertRGB2YCbCr(UINT8 *out, const UINT8 *in, int pixels); +extern void +ImagingConvertYCbCr2RGB(UINT8 *out, const UINT8 *in, int pixels); -extern ImagingShuffler ImagingFindUnpacker(const char* mode, - const char* rawmode, int* bits_out); -extern ImagingShuffler ImagingFindPacker(const char* mode, - const char* rawmode, int* bits_out); +extern ImagingShuffler +ImagingFindUnpacker(const char *mode, const char *rawmode, int *bits_out); +extern ImagingShuffler +ImagingFindPacker(const char *mode, const char *rawmode, int *bits_out); struct ImagingCodecStateInstance { int count; @@ -509,30 +667,27 @@ struct ImagingCodecStateInstance { PyObject *fd; }; - - /* Codec read/write python fd */ -extern Py_ssize_t _imaging_read_pyFd(PyObject *fd, char* dest, Py_ssize_t bytes); -extern Py_ssize_t _imaging_write_pyFd(PyObject *fd, char* src, Py_ssize_t bytes); -extern int _imaging_seek_pyFd(PyObject *fd, Py_ssize_t offset, int whence); -extern Py_ssize_t _imaging_tell_pyFd(PyObject *fd); - - +extern Py_ssize_t +_imaging_read_pyFd(PyObject *fd, char *dest, Py_ssize_t bytes); +extern Py_ssize_t +_imaging_write_pyFd(PyObject *fd, char *src, Py_ssize_t bytes); +extern int +_imaging_seek_pyFd(PyObject *fd, Py_ssize_t offset, int whence); +extern Py_ssize_t +_imaging_tell_pyFd(PyObject *fd); /* Errcodes */ -#define IMAGING_CODEC_END 1 -#define IMAGING_CODEC_OVERRUN -1 -#define IMAGING_CODEC_BROKEN -2 -#define IMAGING_CODEC_UNKNOWN -3 -#define IMAGING_CODEC_CONFIG -8 -#define IMAGING_CODEC_MEMORY -9 - - +#define IMAGING_CODEC_END 1 +#define IMAGING_CODEC_OVERRUN -1 +#define IMAGING_CODEC_BROKEN -2 +#define IMAGING_CODEC_UNKNOWN -3 +#define IMAGING_CODEC_CONFIG -8 +#define IMAGING_CODEC_MEMORY -9 #include "ImagingUtils.h" extern UINT8 *clip8_lookups; - #if defined(__cplusplus) } #endif diff --git a/src/libImaging/ImagingUtils.h b/src/libImaging/ImagingUtils.h index 21c2688d8..ad6f280ac 100644 --- a/src/libImaging/ImagingUtils.h +++ b/src/libImaging/ImagingUtils.h @@ -1,47 +1,42 @@ #ifdef WORDS_BIGENDIAN - #define MAKE_UINT32(u0, u1, u2, u3) ((UINT32)(u3) | ((UINT32)(u2)<<8) | ((UINT32)(u1)<<16) | ((UINT32)(u0)<<24)) - #define MASK_UINT32_CHANNEL_0 0xff000000 - #define MASK_UINT32_CHANNEL_1 0x00ff0000 - #define MASK_UINT32_CHANNEL_2 0x0000ff00 - #define MASK_UINT32_CHANNEL_3 0x000000ff +#define MAKE_UINT32(u0, u1, u2, u3) \ + ((UINT32)(u3) | ((UINT32)(u2) << 8) | ((UINT32)(u1) << 16) | ((UINT32)(u0) << 24)) +#define MASK_UINT32_CHANNEL_0 0xff000000 +#define MASK_UINT32_CHANNEL_1 0x00ff0000 +#define MASK_UINT32_CHANNEL_2 0x0000ff00 +#define MASK_UINT32_CHANNEL_3 0x000000ff #else - #define MAKE_UINT32(u0, u1, u2, u3) ((UINT32)(u0) | ((UINT32)(u1)<<8) | ((UINT32)(u2)<<16) | ((UINT32)(u3)<<24)) - #define MASK_UINT32_CHANNEL_0 0x000000ff - #define MASK_UINT32_CHANNEL_1 0x0000ff00 - #define MASK_UINT32_CHANNEL_2 0x00ff0000 - #define MASK_UINT32_CHANNEL_3 0xff000000 +#define MAKE_UINT32(u0, u1, u2, u3) \ + ((UINT32)(u0) | ((UINT32)(u1) << 8) | ((UINT32)(u2) << 16) | ((UINT32)(u3) << 24)) +#define MASK_UINT32_CHANNEL_0 0x000000ff +#define MASK_UINT32_CHANNEL_1 0x0000ff00 +#define MASK_UINT32_CHANNEL_2 0x00ff0000 +#define MASK_UINT32_CHANNEL_3 0xff000000 #endif - -#define SHIFTFORDIV255(a)\ - ((((a) >> 8) + a) >> 8) +#define SHIFTFORDIV255(a) ((((a) >> 8) + a) >> 8) /* like (a * b + 127) / 255), but much faster on most platforms */ -#define MULDIV255(a, b, tmp)\ - (tmp = (a) * (b) + 128, SHIFTFORDIV255(tmp)) +#define MULDIV255(a, b, tmp) (tmp = (a) * (b) + 128, SHIFTFORDIV255(tmp)) -#define DIV255(a, tmp)\ - (tmp = (a) + 128, SHIFTFORDIV255(tmp)) +#define DIV255(a, tmp) (tmp = (a) + 128, SHIFTFORDIV255(tmp)) -#define BLEND(mask, in1, in2, tmp1)\ - DIV255(in1 * (255 - mask) + in2 * mask, tmp1) - -#define PREBLEND(mask, in1, in2, tmp1)\ - (MULDIV255(in1, (255 - mask), tmp1) + in2) +#define BLEND(mask, in1, in2, tmp1) DIV255(in1 *(255 - mask) + in2 * mask, tmp1) +#define PREBLEND(mask, in1, in2, tmp1) (MULDIV255(in1, (255 - mask), tmp1) + in2) #define CLIP8(v) ((v) <= 0 ? 0 : (v) < 256 ? (v) : 255) /* This is to work around a bug in GCC prior 4.9 in 64 bit mode. GCC generates code with partial dependency which is 3 times slower. See: http://stackoverflow.com/a/26588074/253146 */ -#if defined(__x86_64__) && defined(__SSE__) && ! defined(__NO_INLINE__) && \ - ! defined(__clang__) && defined(GCC_VERSION) && (GCC_VERSION < 40900) +#if defined(__x86_64__) && defined(__SSE__) && !defined(__NO_INLINE__) && \ + !defined(__clang__) && defined(GCC_VERSION) && (GCC_VERSION < 40900) static float __attribute__((always_inline)) inline _i2f(int v) { float x; - __asm__("xorps %0, %0; cvtsi2ss %1, %0" : "=x"(x) : "r"(v) ); + __asm__("xorps %0, %0; cvtsi2ss %1, %0" : "=x"(x) : "r"(v)); return x; } #else -static float inline _i2f(int v) { return (float) v; } +static float inline _i2f(int v) { return (float)v; } #endif diff --git a/src/libImaging/Jpeg.h b/src/libImaging/Jpeg.h index 280b6d638..a876d3bb6 100644 --- a/src/libImaging/Jpeg.h +++ b/src/libImaging/Jpeg.h @@ -12,13 +12,11 @@ #include - typedef struct { - struct jpeg_error_mgr pub; /* "public" fields */ - jmp_buf setjmp_buffer; /* for return to caller */ + struct jpeg_error_mgr pub; /* "public" fields */ + jmp_buf setjmp_buffer; /* for return to caller */ } JPEGERROR; - /* -------------------------------------------------------------------- */ /* Decoder */ @@ -28,15 +26,14 @@ typedef struct { } JPEGSOURCE; typedef struct { - /* CONFIGURATION */ /* Jpeg file mode (empty if not known) */ - char jpegmode[8+1]; + char jpegmode[8 + 1]; /* Converter output mode (input to the shuffler). If empty, convert conversions are disabled */ - char rawmode[8+1]; + char rawmode[8 + 1]; /* If set, trade quality for speed */ int draft; @@ -54,7 +51,6 @@ typedef struct { } JPEGSTATE; - /* -------------------------------------------------------------------- */ /* Encoder */ @@ -64,7 +60,6 @@ typedef struct { } JPEGDESTINATION; typedef struct { - /* CONFIGURATION */ /* Quality (0-100, -1 means default) */ @@ -89,7 +84,7 @@ typedef struct { int subsampling; /* Converter input mode (input to the shuffler) */ - char rawmode[8+1]; + char rawmode[8 + 1]; /* Custom quantization tables () */ unsigned int *qtables; @@ -98,7 +93,8 @@ typedef struct { int qtablesLen; /* Extra data (to be injected after header) */ - char* extra; int extra_size; + char *extra; + int extra_size; /* PRIVATE CONTEXT (set by encoder) */ @@ -110,7 +106,7 @@ typedef struct { int extra_offset; - size_t rawExifLen; /* EXIF data length */ - char* rawExif; /* EXIF buffer pointer */ + size_t rawExifLen; /* EXIF data length */ + char *rawExif; /* EXIF buffer pointer */ } JPEGENCODERSTATE; diff --git a/src/libImaging/Jpeg2K.h b/src/libImaging/Jpeg2K.h index 7645b9326..f749ecfb2 100644 --- a/src/libImaging/Jpeg2K.h +++ b/src/libImaging/Jpeg2K.h @@ -24,7 +24,7 @@ typedef struct { int fd; /* File pointer, when opened */ - FILE * pfile; + FILE *pfile; /* Length of data, if available; otherwise, -1 */ off_t length; @@ -33,13 +33,13 @@ typedef struct { OPJ_CODEC_FORMAT format; /* Set to divide image resolution by 2**reduce. */ - int reduce; + int reduce; /* Set to limit the number of quality layers to decode (0 = all layers) */ - int layers; + int layers; /* PRIVATE CONTEXT (set by decoder) */ - const char *error_msg; + const char *error_msg; } JPEG2KDECODESTATE; @@ -51,36 +51,36 @@ typedef struct { /* CONFIGURATION */ /* File descriptor, if available; otherwise, -1 */ - int fd; + int fd; /* File pointer, when opened */ - FILE * pfile; + FILE *pfile; /* Specify the desired format */ OPJ_CODEC_FORMAT format; /* Image offset */ - int offset_x, offset_y; + int offset_x, offset_y; /* Tile information */ - int tile_offset_x, tile_offset_y; - int tile_size_x, tile_size_y; + int tile_offset_x, tile_offset_y; + int tile_size_x, tile_size_y; /* Quality layers (a sequence of numbers giving *either* rates or dB) */ - int quality_is_in_db; - PyObject *quality_layers; + int quality_is_in_db; + PyObject *quality_layers; /* Number of resolutions (DWT decompositions + 1 */ - int num_resolutions; + int num_resolutions; /* Code block size */ - int cblk_width, cblk_height; + int cblk_width, cblk_height; /* Precinct size */ - int precinct_width, precinct_height; + int precinct_width, precinct_height; /* Compression style */ - int irreversible; + int irreversible; /* Progression order (LRCP/RLCP/RPCL/PCRL/CPRL) */ OPJ_PROG_ORDER progression; @@ -89,8 +89,7 @@ typedef struct { OPJ_CINEMA_MODE cinema_mode; /* PRIVATE CONTEXT (set by decoder) */ - const char *error_msg; - + const char *error_msg; } JPEG2KENCODESTATE; diff --git a/src/libImaging/Jpeg2KDecode.c b/src/libImaging/Jpeg2KDecode.c index 8cce5454f..a2a7354db 100644 --- a/src/libImaging/Jpeg2KDecode.c +++ b/src/libImaging/Jpeg2KDecode.c @@ -23,7 +23,7 @@ typedef struct { OPJ_UINT32 tile_index; OPJ_UINT32 data_size; - OPJ_INT32 x0, y0, x1, y1; + OPJ_INT32 x0, y0, x1, y1; OPJ_UINT32 nb_comps; } JPEG2KTILEINFO; @@ -32,9 +32,8 @@ typedef struct { /* -------------------------------------------------------------------- */ static void -j2k_error(const char *msg, void *client_data) -{ - JPEG2KDECODESTATE *state = (JPEG2KDECODESTATE *) client_data; +j2k_error(const char *msg, void *client_data) { + JPEG2KDECODESTATE *state = (JPEG2KDECODESTATE *)client_data; free((void *)state->error_msg); state->error_msg = strdup(msg); } @@ -44,8 +43,7 @@ j2k_error(const char *msg, void *client_data) /* -------------------------------------------------------------------- */ static OPJ_SIZE_T -j2k_read(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) -{ +j2k_read(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) { ImagingCodecState state = (ImagingCodecState)p_user_data; size_t len = _imaging_read_pyFd(state->fd, p_buffer, p_nb_bytes); @@ -54,8 +52,7 @@ j2k_read(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) } static OPJ_OFF_T -j2k_skip(OPJ_OFF_T p_nb_bytes, void *p_user_data) -{ +j2k_skip(OPJ_OFF_T p_nb_bytes, void *p_user_data) { off_t pos; ImagingCodecState state = (ImagingCodecState)p_user_data; @@ -69,21 +66,18 @@ j2k_skip(OPJ_OFF_T p_nb_bytes, void *p_user_data) /* Unpackers */ /* -------------------------------------------------------------------- */ -typedef void (*j2k_unpacker_t)(opj_image_t *in, - const JPEG2KTILEINFO *tileInfo, - const UINT8 *data, - Imaging im); +typedef void (*j2k_unpacker_t)( + opj_image_t *in, const JPEG2KTILEINFO *tileInfo, const UINT8 *data, Imaging im); struct j2k_decode_unpacker { - const char *mode; - OPJ_COLOR_SPACE color_space; - unsigned components; - j2k_unpacker_t unpacker; + const char *mode; + OPJ_COLOR_SPACE color_space; + unsigned components; + j2k_unpacker_t unpacker; }; -static inline -unsigned j2ku_shift(unsigned x, int n) -{ +static inline unsigned +j2ku_shift(unsigned x, int n) { if (n < 0) { return x >> -n; } else { @@ -92,9 +86,11 @@ unsigned j2ku_shift(unsigned x, int n) } static void -j2ku_gray_l(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, - const UINT8 *tiledata, Imaging im) -{ +j2ku_gray_l( + opj_image_t *in, + const JPEG2KTILEINFO *tileinfo, + const UINT8 *tiledata, + Imaging im) { unsigned x0 = tileinfo->x0 - in->x0, y0 = tileinfo->y0 - in->y0; unsigned w = tileinfo->x1 - tileinfo->x0; unsigned h = tileinfo->y1 - tileinfo->y0; @@ -115,41 +111,42 @@ j2ku_gray_l(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, /* csiz*h*w + offset = tileinfo.datasize */ switch (csiz) { - case 1: - for (y = 0; y < h; ++y) { - const UINT8 *data = &tiledata[y * w]; - UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; - for (x = 0; x < w; ++x) { - *row++ = j2ku_shift(offset + *data++, shift); + case 1: + for (y = 0; y < h; ++y) { + const UINT8 *data = &tiledata[y * w]; + UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; + for (x = 0; x < w; ++x) { + *row++ = j2ku_shift(offset + *data++, shift); + } } - } - break; - case 2: - for (y = 0; y < h; ++y) { - const UINT16 *data = (const UINT16 *)&tiledata[2 * y * w]; - UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; - for (x = 0; x < w; ++x) { - *row++ = j2ku_shift(offset + *data++, shift); + break; + case 2: + for (y = 0; y < h; ++y) { + const UINT16 *data = (const UINT16 *)&tiledata[2 * y * w]; + UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; + for (x = 0; x < w; ++x) { + *row++ = j2ku_shift(offset + *data++, shift); + } } - } - break; - case 4: - for (y = 0; y < h; ++y) { - const UINT32 *data = (const UINT32 *)&tiledata[4 * y * w]; - UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; - for (x = 0; x < w; ++x) { - *row++ = j2ku_shift(offset + *data++, shift); + break; + case 4: + for (y = 0; y < h; ++y) { + const UINT32 *data = (const UINT32 *)&tiledata[4 * y * w]; + UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; + for (x = 0; x < w; ++x) { + *row++ = j2ku_shift(offset + *data++, shift); + } } - } - break; + break; } } - static void -j2ku_gray_i(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, - const UINT8 *tiledata, Imaging im) -{ +j2ku_gray_i( + opj_image_t *in, + const JPEG2KTILEINFO *tileinfo, + const UINT8 *tiledata, + Imaging im) { unsigned x0 = tileinfo->x0 - in->x0, y0 = tileinfo->y0 - in->y0; unsigned w = tileinfo->x1 - tileinfo->x0; unsigned h = tileinfo->y1 - tileinfo->y0; @@ -169,41 +166,42 @@ j2ku_gray_i(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, } switch (csiz) { - case 1: - for (y = 0; y < h; ++y) { - const UINT8 *data = &tiledata[y * w]; - UINT16 *row = (UINT16 *)im->image[y0 + y] + x0; - for (x = 0; x < w; ++x) { - *row++ = j2ku_shift(offset + *data++, shift); + case 1: + for (y = 0; y < h; ++y) { + const UINT8 *data = &tiledata[y * w]; + UINT16 *row = (UINT16 *)im->image[y0 + y] + x0; + for (x = 0; x < w; ++x) { + *row++ = j2ku_shift(offset + *data++, shift); + } } - } - break; - case 2: - for (y = 0; y < h; ++y) { - const UINT16 *data = (const UINT16 *)&tiledata[2 * y * w]; - UINT16 *row = (UINT16 *)im->image[y0 + y] + x0; - for (x = 0; x < w; ++x) { - *row++ = j2ku_shift(offset + *data++, shift); + break; + case 2: + for (y = 0; y < h; ++y) { + const UINT16 *data = (const UINT16 *)&tiledata[2 * y * w]; + UINT16 *row = (UINT16 *)im->image[y0 + y] + x0; + for (x = 0; x < w; ++x) { + *row++ = j2ku_shift(offset + *data++, shift); + } } - } - break; - case 4: - for (y = 0; y < h; ++y) { - const UINT32 *data = (const UINT32 *)&tiledata[4 * y * w]; - UINT16 *row = (UINT16 *)im->image[y0 + y] + x0; - for (x = 0; x < w; ++x) { - *row++ = j2ku_shift(offset + *data++, shift); + break; + case 4: + for (y = 0; y < h; ++y) { + const UINT32 *data = (const UINT32 *)&tiledata[4 * y * w]; + UINT16 *row = (UINT16 *)im->image[y0 + y] + x0; + for (x = 0; x < w; ++x) { + *row++ = j2ku_shift(offset + *data++, shift); + } } - } - break; + break; } } - static void -j2ku_gray_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, - const UINT8 *tiledata, Imaging im) -{ +j2ku_gray_rgb( + opj_image_t *in, + const JPEG2KTILEINFO *tileinfo, + const UINT8 *tiledata, + Imaging im) { unsigned x0 = tileinfo->x0 - in->x0, y0 = tileinfo->y0 - in->y0; unsigned w = tileinfo->x1 - tileinfo->x0; unsigned h = tileinfo->y1 - tileinfo->y0; @@ -223,49 +221,51 @@ j2ku_gray_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, } switch (csiz) { - case 1: - for (y = 0; y < h; ++y) { - const UINT8 *data = &tiledata[y * w]; - UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; - for (x = 0; x < w; ++x) { - UINT8 byte = j2ku_shift(offset + *data++, shift); - row[0] = row[1] = row[2] = byte; - row[3] = 0xff; - row += 4; + case 1: + for (y = 0; y < h; ++y) { + const UINT8 *data = &tiledata[y * w]; + UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; + for (x = 0; x < w; ++x) { + UINT8 byte = j2ku_shift(offset + *data++, shift); + row[0] = row[1] = row[2] = byte; + row[3] = 0xff; + row += 4; + } } - } - break; - case 2: - for (y = 0; y < h; ++y) { - const UINT16 *data = (UINT16 *)&tiledata[2 * y * w]; - UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; - for (x = 0; x < w; ++x) { - UINT8 byte = j2ku_shift(offset + *data++, shift); - row[0] = row[1] = row[2] = byte; - row[3] = 0xff; - row += 4; + break; + case 2: + for (y = 0; y < h; ++y) { + const UINT16 *data = (UINT16 *)&tiledata[2 * y * w]; + UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; + for (x = 0; x < w; ++x) { + UINT8 byte = j2ku_shift(offset + *data++, shift); + row[0] = row[1] = row[2] = byte; + row[3] = 0xff; + row += 4; + } } - } - break; - case 4: - for (y = 0; y < h; ++y) { - const UINT32 *data = (UINT32 *)&tiledata[4 * y * w]; - UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; - for (x = 0; x < w; ++x) { - UINT8 byte = j2ku_shift(offset + *data++, shift); - row[0] = row[1] = row[2] = byte; - row[3] = 0xff; - row += 4; + break; + case 4: + for (y = 0; y < h; ++y) { + const UINT32 *data = (UINT32 *)&tiledata[4 * y * w]; + UINT8 *row = (UINT8 *)im->image[y0 + y] + x0; + for (x = 0; x < w; ++x) { + UINT8 byte = j2ku_shift(offset + *data++, shift); + row[0] = row[1] = row[2] = byte; + row[3] = 0xff; + row += 4; + } } - } - break; + break; } } static void -j2ku_graya_la(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, - const UINT8 *tiledata, Imaging im) -{ +j2ku_graya_la( + opj_image_t *in, + const JPEG2KTILEINFO *tileinfo, + const UINT8 *tiledata, + Imaging im) { unsigned x0 = tileinfo->x0 - in->x0, y0 = tileinfo->y0 - in->y0; unsigned w = tileinfo->x1 - tileinfo->x0; unsigned h = tileinfo->y1 - tileinfo->y0; @@ -304,15 +304,31 @@ j2ku_graya_la(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, UINT32 word = 0, aword = 0, byte; switch (csiz) { - case 1: word = *data++; break; - case 2: word = *(const UINT16 *)data; data += 2; break; - case 4: word = *(const UINT32 *)data; data += 4; break; + case 1: + word = *data++; + break; + case 2: + word = *(const UINT16 *)data; + data += 2; + break; + case 4: + word = *(const UINT32 *)data; + data += 4; + break; } switch (acsiz) { - case 1: aword = *adata++; break; - case 2: aword = *(const UINT16 *)adata; adata += 2; break; - case 4: aword = *(const UINT32 *)adata; adata += 4; break; + case 1: + aword = *adata++; + break; + case 2: + aword = *(const UINT16 *)adata; + adata += 2; + break; + case 4: + aword = *(const UINT32 *)adata; + adata += 4; + break; } byte = j2ku_shift(offset + word, shift); @@ -324,9 +340,11 @@ j2ku_graya_la(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, } static void -j2ku_srgb_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, - const UINT8 *tiledata, Imaging im) -{ +j2ku_srgb_rgb( + opj_image_t *in, + const JPEG2KTILEINFO *tileinfo, + const UINT8 *tiledata, + Imaging im) { unsigned x0 = tileinfo->x0 - in->x0, y0 = tileinfo->y0 - in->y0; unsigned w = tileinfo->x1 - tileinfo->x0; unsigned h = tileinfo->y1 - tileinfo->y0; @@ -365,9 +383,17 @@ j2ku_srgb_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, UINT32 word = 0; switch (csiz[n]) { - case 1: word = *data[n]++; break; - case 2: word = *(const UINT16 *)data[n]; data[n] += 2; break; - case 4: word = *(const UINT32 *)data[n]; data[n] += 4; break; + case 1: + word = *data[n]++; + break; + case 2: + word = *(const UINT16 *)data[n]; + data[n] += 2; + break; + case 4: + word = *(const UINT32 *)data[n]; + data[n] += 4; + break; } row[n] = j2ku_shift(offsets[n] + word, shifts[n]); @@ -379,9 +405,11 @@ j2ku_srgb_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, } static void -j2ku_sycc_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, - const UINT8 *tiledata, Imaging im) -{ +j2ku_sycc_rgb( + opj_image_t *in, + const JPEG2KTILEINFO *tileinfo, + const UINT8 *tiledata, + Imaging im) { unsigned x0 = tileinfo->x0 - in->x0, y0 = tileinfo->y0 - in->y0; unsigned w = tileinfo->x1 - tileinfo->x0; unsigned h = tileinfo->y1 - tileinfo->y0; @@ -421,9 +449,17 @@ j2ku_sycc_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, UINT32 word = 0; switch (csiz[n]) { - case 1: word = *data[n]++; break; - case 2: word = *(const UINT16 *)data[n]; data[n] += 2; break; - case 4: word = *(const UINT32 *)data[n]; data[n] += 4; break; + case 1: + word = *data[n]++; + break; + case 2: + word = *(const UINT16 *)data[n]; + data[n] += 2; + break; + case 4: + word = *(const UINT32 *)data[n]; + data[n] += 4; + break; } row[n] = j2ku_shift(offsets[n] + word, shifts[n]); @@ -437,9 +473,11 @@ j2ku_sycc_rgb(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, } static void -j2ku_srgba_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, - const UINT8 *tiledata, Imaging im) -{ +j2ku_srgba_rgba( + opj_image_t *in, + const JPEG2KTILEINFO *tileinfo, + const UINT8 *tiledata, + Imaging im) { unsigned x0 = tileinfo->x0 - in->x0, y0 = tileinfo->y0 - in->y0; unsigned w = tileinfo->x1 - tileinfo->x0; unsigned h = tileinfo->y1 - tileinfo->y0; @@ -478,9 +516,17 @@ j2ku_srgba_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, UINT32 word = 0; switch (csiz[n]) { - case 1: word = *data[n]++; break; - case 2: word = *(const UINT16 *)data[n]; data[n] += 2; break; - case 4: word = *(const UINT32 *)data[n]; data[n] += 4; break; + case 1: + word = *data[n]++; + break; + case 2: + word = *(const UINT16 *)data[n]; + data[n] += 2; + break; + case 4: + word = *(const UINT32 *)data[n]; + data[n] += 4; + break; } row[n] = j2ku_shift(offsets[n] + word, shifts[n]); @@ -491,9 +537,11 @@ j2ku_srgba_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, } static void -j2ku_sycca_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, - const UINT8 *tiledata, Imaging im) -{ +j2ku_sycca_rgba( + opj_image_t *in, + const JPEG2KTILEINFO *tileinfo, + const UINT8 *tiledata, + Imaging im) { unsigned x0 = tileinfo->x0 - in->x0, y0 = tileinfo->y0 - in->y0; unsigned w = tileinfo->x1 - tileinfo->x0; unsigned h = tileinfo->y1 - tileinfo->y0; @@ -533,9 +581,17 @@ j2ku_sycca_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, UINT32 word = 0; switch (csiz[n]) { - case 1: word = *data[n]++; break; - case 2: word = *(const UINT16 *)data[n]; data[n] += 2; break; - case 4: word = *(const UINT32 *)data[n]; data[n] += 4; break; + case 1: + word = *data[n]++; + break; + case 2: + word = *(const UINT16 *)data[n]; + data[n] += 2; + break; + case 4: + word = *(const UINT32 *)data[n]; + data[n] += 4; + break; } row[n] = j2ku_shift(offsets[n] + word, shifts[n]); @@ -548,22 +604,22 @@ j2ku_sycca_rgba(opj_image_t *in, const JPEG2KTILEINFO *tileinfo, } static const struct j2k_decode_unpacker j2k_unpackers[] = { - { "L", OPJ_CLRSPC_GRAY, 1, j2ku_gray_l }, - { "I;16", OPJ_CLRSPC_GRAY, 1, j2ku_gray_i }, - { "I;16B", OPJ_CLRSPC_GRAY, 1, j2ku_gray_i }, - { "LA", OPJ_CLRSPC_GRAY, 2, j2ku_graya_la }, - { "RGB", OPJ_CLRSPC_GRAY, 1, j2ku_gray_rgb }, - { "RGB", OPJ_CLRSPC_GRAY, 2, j2ku_gray_rgb }, - { "RGB", OPJ_CLRSPC_SRGB, 3, j2ku_srgb_rgb }, - { "RGB", OPJ_CLRSPC_SYCC, 3, j2ku_sycc_rgb }, - { "RGB", OPJ_CLRSPC_SRGB, 4, j2ku_srgb_rgb }, - { "RGB", OPJ_CLRSPC_SYCC, 4, j2ku_sycc_rgb }, - { "RGBA", OPJ_CLRSPC_GRAY, 1, j2ku_gray_rgb }, - { "RGBA", OPJ_CLRSPC_GRAY, 2, j2ku_graya_la }, - { "RGBA", OPJ_CLRSPC_SRGB, 3, j2ku_srgb_rgb }, - { "RGBA", OPJ_CLRSPC_SYCC, 3, j2ku_sycc_rgb }, - { "RGBA", OPJ_CLRSPC_SRGB, 4, j2ku_srgba_rgba }, - { "RGBA", OPJ_CLRSPC_SYCC, 4, j2ku_sycca_rgba }, + {"L", OPJ_CLRSPC_GRAY, 1, j2ku_gray_l}, + {"I;16", OPJ_CLRSPC_GRAY, 1, j2ku_gray_i}, + {"I;16B", OPJ_CLRSPC_GRAY, 1, j2ku_gray_i}, + {"LA", OPJ_CLRSPC_GRAY, 2, j2ku_graya_la}, + {"RGB", OPJ_CLRSPC_GRAY, 1, j2ku_gray_rgb}, + {"RGB", OPJ_CLRSPC_GRAY, 2, j2ku_gray_rgb}, + {"RGB", OPJ_CLRSPC_SRGB, 3, j2ku_srgb_rgb}, + {"RGB", OPJ_CLRSPC_SYCC, 3, j2ku_sycc_rgb}, + {"RGB", OPJ_CLRSPC_SRGB, 4, j2ku_srgb_rgb}, + {"RGB", OPJ_CLRSPC_SYCC, 4, j2ku_sycc_rgb}, + {"RGBA", OPJ_CLRSPC_GRAY, 1, j2ku_gray_rgb}, + {"RGBA", OPJ_CLRSPC_GRAY, 2, j2ku_graya_la}, + {"RGBA", OPJ_CLRSPC_SRGB, 3, j2ku_srgb_rgb}, + {"RGBA", OPJ_CLRSPC_SYCC, 3, j2ku_sycc_rgb}, + {"RGBA", OPJ_CLRSPC_SRGB, 4, j2ku_srgba_rgba}, + {"RGBA", OPJ_CLRSPC_SYCC, 4, j2ku_sycca_rgba}, }; /* -------------------------------------------------------------------- */ @@ -578,9 +634,8 @@ enum { }; static int -j2k_decode_entry(Imaging im, ImagingCodecState state) -{ - JPEG2KDECODESTATE *context = (JPEG2KDECODESTATE *) state->context; +j2k_decode_entry(Imaging im, ImagingCodecState state) { + JPEG2KDECODESTATE *context = (JPEG2KDECODESTATE *)state->context; opj_stream_t *stream = NULL; opj_image_t *image = NULL; opj_codec_t *codec = NULL; @@ -591,7 +646,6 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) unsigned n, tile_height, tile_width; int components; - stream = opj_stream_create(BUFFER_SIZE, OPJ_TRUE); if (!stream) { @@ -645,8 +699,8 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) } /* Check that this image is something we can handle */ - if (image->numcomps < 1 || image->numcomps > 4 - || image->color_space == OPJ_CLRSPC_UNKNOWN) { + if (image->numcomps < 1 || image->numcomps > 4 || + image->color_space == OPJ_CLRSPC_UNKNOWN) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; goto quick_exit; @@ -686,15 +740,21 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) if (color_space == OPJ_CLRSPC_UNSPECIFIED) { switch (image->numcomps) { - case 1: case 2: color_space = OPJ_CLRSPC_GRAY; break; - case 3: case 4: color_space = OPJ_CLRSPC_SRGB; break; + case 1: + case 2: + color_space = OPJ_CLRSPC_GRAY; + break; + case 3: + case 4: + color_space = OPJ_CLRSPC_SRGB; + break; } } - for (n = 0; n < sizeof(j2k_unpackers) / sizeof (j2k_unpackers[0]); ++n) { - if (color_space == j2k_unpackers[n].color_space - && image->numcomps == j2k_unpackers[n].components - && strcmp (im->mode, j2k_unpackers[n].mode) == 0) { + for (n = 0; n < sizeof(j2k_unpackers) / sizeof(j2k_unpackers[0]); ++n) { + if (color_space == j2k_unpackers[n].color_space && + image->numcomps == j2k_unpackers[n].components && + strcmp(im->mode, j2k_unpackers[n].mode) == 0) { unpack = j2k_unpackers[n].unpacker; break; } @@ -713,14 +773,17 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) OPJ_BOOL should_continue; unsigned correction = (1 << params.cp_reduce) - 1; - if (!opj_read_tile_header(codec, - stream, - &tile_info.tile_index, - &tile_info.data_size, - &tile_info.x0, &tile_info.y0, - &tile_info.x1, &tile_info.y1, - &tile_info.nb_comps, - &should_continue)) { + if (!opj_read_tile_header( + codec, + stream, + &tile_info.tile_index, + &tile_info.data_size, + &tile_info.x0, + &tile_info.y0, + &tile_info.x1, + &tile_info.y1, + &tile_info.nb_comps, + &should_continue)) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; goto quick_exit; @@ -740,14 +803,12 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) /* Check the tile bounds; if the tile is outside the image area, or if it has a negative width or height (i.e. the coordinates are swapped), bail. */ - if (tile_info.x0 >= tile_info.x1 - || tile_info.y0 >= tile_info.y1 - || tile_info.x0 < 0 - || tile_info.y0 < 0 - || (OPJ_UINT32)tile_info.x0 < image->x0 - || (OPJ_UINT32)tile_info.y0 < image->y0 - || (OPJ_INT32)(tile_info.x1 - image->x0) > im->xsize - || (OPJ_INT32)(tile_info.y1 - image->y0) > im->ysize) { + if (tile_info.x0 >= tile_info.x1 || tile_info.y0 >= tile_info.y1 || + tile_info.x0 < 0 || tile_info.y0 < 0 || + (OPJ_UINT32)tile_info.x0 < image->x0 || + (OPJ_UINT32)tile_info.y0 < image->y0 || + (OPJ_INT32)(tile_info.x1 - image->x0) > im->xsize || + (OPJ_INT32)(tile_info.y1 - image->y0) > im->ysize) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; goto quick_exit; @@ -760,10 +821,10 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) tile_width = tile_info.x1 - tile_info.x0; tile_height = tile_info.y1 - tile_info.y0; components = tile_info.nb_comps == 3 ? 4 : tile_info.nb_comps; - if (( tile_width > UINT_MAX / components ) || - ( tile_height > UINT_MAX / components ) || - ( tile_width > UINT_MAX / (tile_height * components )) || - ( tile_height > UINT_MAX / (tile_width * components ))) { + if ((tile_width > UINT_MAX / components) || + (tile_height > UINT_MAX / components) || + (tile_width > UINT_MAX / (tile_height * components)) || + (tile_height > UINT_MAX / (tile_width * components))) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; goto quick_exit; @@ -777,7 +838,7 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) if (buffer_size < tile_info.data_size) { /* malloc check ok, overflow and tile size sanity check above */ - UINT8 *new = realloc (state->buffer, tile_info.data_size); + UINT8 *new = realloc(state->buffer, tile_info.data_size); if (!new) { state->errcode = IMAGING_CODEC_MEMORY; state->state = J2K_STATE_FAILED; @@ -787,12 +848,12 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) buffer_size = tile_info.data_size; } - - if (!opj_decode_tile_data(codec, - tile_info.tile_index, - (OPJ_BYTE *)state->buffer, - tile_info.data_size, - stream)) { + if (!opj_decode_tile_data( + codec, + tile_info.tile_index, + (OPJ_BYTE *)state->buffer, + tile_info.data_size, + stream)) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; goto quick_exit; @@ -811,12 +872,12 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) state->errcode = IMAGING_CODEC_END; if (context->pfile) { - if(fclose(context->pfile)){ + if (fclose(context->pfile)) { context->pfile = NULL; } } - quick_exit: +quick_exit: if (codec) { opj_destroy_codec(codec); } @@ -831,10 +892,8 @@ j2k_decode_entry(Imaging im, ImagingCodecState state) } int -ImagingJpeg2KDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ - - if (bytes){ +ImagingJpeg2KDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { + if (bytes) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; return -1; @@ -867,7 +926,7 @@ ImagingJpeg2KDecodeCleanup(ImagingCodecState state) { JPEG2KDECODESTATE *context = (JPEG2KDECODESTATE *)state->context; if (context->error_msg) { - free ((void *)context->error_msg); + free((void *)context->error_msg); } context->error_msg = NULL; @@ -876,8 +935,7 @@ ImagingJpeg2KDecodeCleanup(ImagingCodecState state) { } const char * -ImagingJpeg2KVersion(void) -{ +ImagingJpeg2KVersion(void) { return opj_version(); } diff --git a/src/libImaging/Jpeg2KEncode.c b/src/libImaging/Jpeg2KEncode.c index 5b18e472c..5829cf37f 100644 --- a/src/libImaging/Jpeg2KEncode.c +++ b/src/libImaging/Jpeg2KEncode.c @@ -19,26 +19,24 @@ #include "Jpeg2K.h" -#define CINEMA_24_CS_LENGTH 1302083 -#define CINEMA_48_CS_LENGTH 651041 +#define CINEMA_24_CS_LENGTH 1302083 +#define CINEMA_48_CS_LENGTH 651041 #define COMP_24_CS_MAX_LENGTH 1041666 -#define COMP_48_CS_MAX_LENGTH 520833 +#define COMP_48_CS_MAX_LENGTH 520833 /* -------------------------------------------------------------------- */ /* Error handler */ /* -------------------------------------------------------------------- */ static void -j2k_error(const char *msg, void *client_data) -{ - JPEG2KENCODESTATE *state = (JPEG2KENCODESTATE *) client_data; +j2k_error(const char *msg, void *client_data) { + JPEG2KENCODESTATE *state = (JPEG2KENCODESTATE *)client_data; free((void *)state->error_msg); state->error_msg = strdup(msg); } static void -j2k_warn(const char *msg, void *client_data) -{ +j2k_warn(const char *msg, void *client_data) { // Null handler } @@ -47,8 +45,7 @@ j2k_warn(const char *msg, void *client_data) /* -------------------------------------------------------------------- */ static OPJ_SIZE_T -j2k_write(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) -{ +j2k_write(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) { ImagingCodecState state = (ImagingCodecState)p_user_data; unsigned int result; @@ -57,16 +54,14 @@ j2k_write(void *p_buffer, OPJ_SIZE_T p_nb_bytes, void *p_user_data) return result ? result : (OPJ_SIZE_T)-1; } - static OPJ_OFF_T -j2k_skip(OPJ_OFF_T p_nb_bytes, void *p_user_data) -{ +j2k_skip(OPJ_OFF_T p_nb_bytes, void *p_user_data) { ImagingCodecState state = (ImagingCodecState)p_user_data; char *buffer; int result; /* Explicitly write zeros */ - buffer = calloc(p_nb_bytes,1); + buffer = calloc(p_nb_bytes, 1); if (!buffer) { return (OPJ_OFF_T)-1; } @@ -79,8 +74,7 @@ j2k_skip(OPJ_OFF_T p_nb_bytes, void *p_user_data) } static OPJ_BOOL -j2k_seek(OPJ_OFF_T p_nb_bytes, void *p_user_data) -{ +j2k_seek(OPJ_OFF_T p_nb_bytes, void *p_user_data) { ImagingCodecState state = (ImagingCodecState)p_user_data; off_t pos = 0; @@ -94,16 +88,13 @@ j2k_seek(OPJ_OFF_T p_nb_bytes, void *p_user_data) /* Encoder */ /* -------------------------------------------------------------------- */ -typedef void (*j2k_pack_tile_t)(Imaging im, UINT8 *buf, - unsigned x0, unsigned y0, - unsigned w, unsigned h); +typedef void (*j2k_pack_tile_t)( + Imaging im, UINT8 *buf, unsigned x0, unsigned y0, unsigned w, unsigned h); static void -j2k_pack_l(Imaging im, UINT8 *buf, - unsigned x0, unsigned y0, unsigned w, unsigned h) -{ +j2k_pack_l(Imaging im, UINT8 *buf, unsigned x0, unsigned y0, unsigned w, unsigned h) { UINT8 *ptr = buf; - unsigned x,y; + unsigned x, y; for (y = 0; y < h; ++y) { UINT8 *data = (UINT8 *)(im->image[y + y0] + x0); for (x = 0; x < w; ++x) { @@ -113,11 +104,9 @@ j2k_pack_l(Imaging im, UINT8 *buf, } static void -j2k_pack_i16(Imaging im, UINT8 *buf, - unsigned x0, unsigned y0, unsigned w, unsigned h) -{ +j2k_pack_i16(Imaging im, UINT8 *buf, unsigned x0, unsigned y0, unsigned w, unsigned h) { UINT8 *ptr = buf; - unsigned x,y; + unsigned x, y; for (y = 0; y < h; ++y) { UINT8 *data = (UINT8 *)(im->image[y + y0] + x0); for (x = 0; x < w; ++x) { @@ -127,14 +116,11 @@ j2k_pack_i16(Imaging im, UINT8 *buf, } } - static void -j2k_pack_la(Imaging im, UINT8 *buf, - unsigned x0, unsigned y0, unsigned w, unsigned h) -{ +j2k_pack_la(Imaging im, UINT8 *buf, unsigned x0, unsigned y0, unsigned w, unsigned h) { UINT8 *ptr = buf; UINT8 *ptra = buf + w * h; - unsigned x,y; + unsigned x, y; for (y = 0; y < h; ++y) { UINT8 *data = (UINT8 *)(im->image[y + y0] + 4 * x0); for (x = 0; x < w; ++x) { @@ -146,13 +132,11 @@ j2k_pack_la(Imaging im, UINT8 *buf, } static void -j2k_pack_rgb(Imaging im, UINT8 *buf, - unsigned x0, unsigned y0, unsigned w, unsigned h) -{ +j2k_pack_rgb(Imaging im, UINT8 *buf, unsigned x0, unsigned y0, unsigned w, unsigned h) { UINT8 *pr = buf; UINT8 *pg = pr + w * h; UINT8 *pb = pg + w * h; - unsigned x,y; + unsigned x, y; for (y = 0; y < h; ++y) { UINT8 *data = (UINT8 *)(im->image[y + y0] + 4 * x0); for (x = 0; x < w; ++x) { @@ -165,14 +149,13 @@ j2k_pack_rgb(Imaging im, UINT8 *buf, } static void -j2k_pack_rgba(Imaging im, UINT8 *buf, - unsigned x0, unsigned y0, unsigned w, unsigned h) -{ +j2k_pack_rgba( + Imaging im, UINT8 *buf, unsigned x0, unsigned y0, unsigned w, unsigned h) { UINT8 *pr = buf; UINT8 *pg = pr + w * h; UINT8 *pb = pg + w * h; UINT8 *pa = pb + w * h; - unsigned x,y; + unsigned x, y; for (y = 0; y < h; ++y) { UINT8 *data = (UINT8 *)(im->image[y + y0] + 4 * x0); for (x = 0; x < w; ++x) { @@ -192,8 +175,7 @@ enum { }; static void -j2k_set_cinema_params(Imaging im, int components, opj_cparameters_t *params) -{ +j2k_set_cinema_params(Imaging im, int components, opj_cparameters_t *params) { float rate; int n; @@ -215,8 +197,9 @@ j2k_set_cinema_params(Imaging im, int components, opj_cparameters_t *params) params->irreversible = 1; if (params->cp_cinema == OPJ_CINEMA4K_24) { - float max_rate = ((float)(components * im->xsize * im->ysize * 8) - / (CINEMA_24_CS_LENGTH * 8)); + float max_rate = + ((float)(components * im->xsize * im->ysize * 8) / + (CINEMA_24_CS_LENGTH * 8)); params->POC[0].tile = 1; params->POC[0].resno0 = 0; @@ -239,8 +222,9 @@ j2k_set_cinema_params(Imaging im, int components, opj_cparameters_t *params) if (params->tcp_rates[0] == 0) { params->tcp_rates[n] = max_rate; } else { - rate = ((float)(components * im->xsize * im->ysize * 8) - / (params->tcp_rates[n] * 8)); + rate = + ((float)(components * im->xsize * im->ysize * 8) / + (params->tcp_rates[n] * 8)); if (rate > CINEMA_24_CS_LENGTH) { params->tcp_rates[n] = max_rate; } @@ -249,16 +233,18 @@ j2k_set_cinema_params(Imaging im, int components, opj_cparameters_t *params) params->max_comp_size = COMP_24_CS_MAX_LENGTH; } else { - float max_rate = ((float)(components * im->xsize * im->ysize * 8) - / (CINEMA_48_CS_LENGTH * 8)); + float max_rate = + ((float)(components * im->xsize * im->ysize * 8) / + (CINEMA_48_CS_LENGTH * 8)); for (n = 0; n < params->tcp_numlayers; ++n) { rate = 0; if (params->tcp_rates[0] == 0) { params->tcp_rates[n] = max_rate; } else { - rate = ((float)(components * im->xsize * im->ysize * 8) - / (params->tcp_rates[n] * 8)); + rate = + ((float)(components * im->xsize * im->ysize * 8) / + (params->tcp_rates[n] * 8)); if (rate > CINEMA_48_CS_LENGTH) { params->tcp_rates[n] = max_rate; } @@ -270,8 +256,7 @@ j2k_set_cinema_params(Imaging im, int components, opj_cparameters_t *params) } static int -j2k_encode_entry(Imaging im, ImagingCodecState state) -{ +j2k_encode_entry(Imaging im, ImagingCodecState state) { JPEG2KENCODESTATE *context = (JPEG2KENCODESTATE *)state->context; opj_stream_t *stream = NULL; opj_image_t *image = NULL; @@ -312,35 +297,35 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) #endif /* Setup an opj_image */ - if (strcmp (im->mode, "L") == 0) { + if (strcmp(im->mode, "L") == 0) { components = 1; color_space = OPJ_CLRSPC_GRAY; pack = j2k_pack_l; - } else if (strcmp (im->mode, "I;16") == 0){ + } else if (strcmp(im->mode, "I;16") == 0) { components = 1; color_space = OPJ_CLRSPC_GRAY; pack = j2k_pack_i16; prec = 16; bpp = 12; - } else if (strcmp (im->mode, "I;16B") == 0){ + } else if (strcmp(im->mode, "I;16B") == 0) { components = 1; color_space = OPJ_CLRSPC_GRAY; pack = j2k_pack_i16; prec = 16; bpp = 12; - } else if (strcmp (im->mode, "LA") == 0) { + } else if (strcmp(im->mode, "LA") == 0) { components = 2; color_space = OPJ_CLRSPC_GRAY; pack = j2k_pack_la; - } else if (strcmp (im->mode, "RGB") == 0) { + } else if (strcmp(im->mode, "RGB") == 0) { components = 3; color_space = OPJ_CLRSPC_SRGB; pack = j2k_pack_rgb; - } else if (strcmp (im->mode, "YCbCr") == 0) { + } else if (strcmp(im->mode, "YCbCr") == 0) { components = 3; color_space = OPJ_CLRSPC_SYCC; pack = j2k_pack_rgb; - } else if (strcmp (im->mode, "RGBA") == 0) { + } else if (strcmp(im->mode, "RGBA") == 0) { components = 4; color_space = OPJ_CLRSPC_SRGB; pack = j2k_pack_rgba; @@ -400,8 +385,9 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) float *pq; if (len > 0) { - if ((unsigned)len > sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0])) { - len = sizeof(params.tcp_rates)/sizeof(params.tcp_rates[0]); + if ((unsigned)len > + sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0])) { + len = sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0]); } params.tcp_numlayers = (int)len; @@ -431,16 +417,16 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) params.numresolution = context->num_resolutions; } - if (context->cblk_width >= 4 && context->cblk_width <= 1024 - && context->cblk_height >= 4 && context->cblk_height <= 1024 - && context->cblk_width * context->cblk_height <= 4096) { + if (context->cblk_width >= 4 && context->cblk_width <= 1024 && + context->cblk_height >= 4 && context->cblk_height <= 1024 && + context->cblk_width * context->cblk_height <= 4096) { params.cblockw_init = context->cblk_width; params.cblockh_init = context->cblk_height; } - if (context->precinct_width >= 4 && context->precinct_height >= 4 - && context->precinct_width >= context->cblk_width - && context->precinct_height > context->cblk_height) { + if (context->precinct_width >= 4 && context->precinct_height >= 4 && + context->precinct_width >= context->cblk_width && + context->precinct_height > context->cblk_height) { params.prcw_init[0] = context->precinct_width; params.prch_init[0] = context->precinct_height; params.res_spec = 1; @@ -454,22 +440,22 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) params.cp_cinema = context->cinema_mode; switch (params.cp_cinema) { - case OPJ_OFF: - params.cp_rsiz = OPJ_STD_RSIZ; - break; - case OPJ_CINEMA2K_24: - case OPJ_CINEMA2K_48: - params.cp_rsiz = OPJ_CINEMA2K; - if (params.numresolution > 6) { - params.numresolution = 6; - } - break; - case OPJ_CINEMA4K_24: - params.cp_rsiz = OPJ_CINEMA4K; - if (params.numresolution > 7) { - params.numresolution = 7; - } - break; + case OPJ_OFF: + params.cp_rsiz = OPJ_STD_RSIZ; + break; + case OPJ_CINEMA2K_24: + case OPJ_CINEMA2K_48: + params.cp_rsiz = OPJ_CINEMA2K; + if (params.numresolution > 6) { + params.numresolution = 6; + } + break; + case OPJ_CINEMA4K_24: + params.cp_rsiz = OPJ_CINEMA4K; + if (params.numresolution > 7) { + params.numresolution = 7; + } + break; } if (context->cinema_mode != OPJ_OFF) { @@ -504,24 +490,24 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) } /* Write each tile */ - tiles_x = (im->xsize + (params.image_offset_x0 - params.cp_tx0) - + tile_width - 1) / tile_width; - tiles_y = (im->ysize + (params.image_offset_y0 - params.cp_ty0) - + tile_height - 1) / tile_height; + tiles_x = (im->xsize + (params.image_offset_x0 - params.cp_tx0) + tile_width - 1) / + tile_width; + tiles_y = (im->ysize + (params.image_offset_y0 - params.cp_ty0) + tile_height - 1) / + tile_height; /* check for integer overflow for the malloc line, checking any expression that may multiply either tile_width or tile_height */ _overflow_scale_factor = components * prec; - if (( tile_width > UINT_MAX / _overflow_scale_factor ) || - ( tile_height > UINT_MAX / _overflow_scale_factor ) || - ( tile_width > UINT_MAX / (tile_height * _overflow_scale_factor )) || - ( tile_height > UINT_MAX / (tile_width * _overflow_scale_factor ))) { + if ((tile_width > UINT_MAX / _overflow_scale_factor) || + (tile_height > UINT_MAX / _overflow_scale_factor) || + (tile_width > UINT_MAX / (tile_height * _overflow_scale_factor)) || + (tile_height > UINT_MAX / (tile_width * _overflow_scale_factor))) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; goto quick_exit; } /* malloc check ok, checked for overflow above */ - state->buffer = malloc (tile_width * tile_height * components * prec / 8); + state->buffer = malloc(tile_width * tile_height * components * prec / 8); if (!state->buffer) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; @@ -564,8 +550,7 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) data_size = pixw * pixh * components * prec / 8; - if (!opj_write_tile(codec, tile_ndx++, state->buffer, - data_size, stream)) { + if (!opj_write_tile(codec, tile_ndx++, state->buffer, data_size, stream)) { state->errcode = IMAGING_CODEC_BROKEN; state->state = J2K_STATE_FAILED; goto quick_exit; @@ -583,7 +568,7 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) state->state = J2K_STATE_DONE; ret = -1; - quick_exit: +quick_exit: if (codec) { opj_destroy_codec(codec); } @@ -598,14 +583,12 @@ j2k_encode_entry(Imaging im, ImagingCodecState state) } int -ImagingJpeg2KEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) -{ +ImagingJpeg2KEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { if (state->state == J2K_STATE_FAILED) { return -1; } if (state->state == J2K_STATE_START) { - state->state = J2K_STATE_ENCODING; return j2k_encode_entry(im, state); @@ -628,12 +611,11 @@ ImagingJpeg2KEncodeCleanup(ImagingCodecState state) { } if (context->error_msg) { - free ((void *)context->error_msg); + free((void *)context->error_msg); } context->error_msg = NULL; - return -1; } diff --git a/src/libImaging/JpegDecode.c b/src/libImaging/JpegDecode.c index fb6112044..55d10a81a 100644 --- a/src/libImaging/JpegDecode.c +++ b/src/libImaging/JpegDecode.c @@ -21,10 +21,9 @@ * See the README file for details on usage and redistribution. */ - #include "Imaging.h" -#ifdef HAVE_LIBJPEG +#ifdef HAVE_LIBJPEG #undef HAVE_PROTOTYPES #undef HAVE_STDLIB_H @@ -37,7 +36,6 @@ #include "Jpeg.h" - #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) @@ -50,20 +48,19 @@ char *libjpeg_turbo_version = NULL; #endif int -ImagingJpegUseJCSExtensions() -{ +ImagingJpegUseJCSExtensions() { int use_jcs_extensions = 0; - #ifdef JCS_EXTENSIONS - #if defined(LIBJPEG_TURBO_VERSION_NUMBER) - #if LIBJPEG_TURBO_VERSION_NUMBER >= 1002010 - use_jcs_extensions = 1; - #endif - #else - if (libjpeg_turbo_version) { - use_jcs_extensions = strcmp(libjpeg_turbo_version, "1.2.1") >= 0; - } - #endif - #endif +#ifdef JCS_EXTENSIONS +#if defined(LIBJPEG_TURBO_VERSION_NUMBER) +#if LIBJPEG_TURBO_VERSION_NUMBER >= 1002010 + use_jcs_extensions = 1; +#endif +#else + if (libjpeg_turbo_version) { + use_jcs_extensions = strcmp(libjpeg_turbo_version, "1.2.1") >= 0; + } +#endif +#endif return use_jcs_extensions; } @@ -72,24 +69,19 @@ ImagingJpegUseJCSExtensions() /* -------------------------------------------------------------------- */ METHODDEF(void) -stub(j_decompress_ptr cinfo) -{ - /* empty */ -} +stub(j_decompress_ptr cinfo) { /* empty */ } METHODDEF(boolean) -fill_input_buffer(j_decompress_ptr cinfo) -{ +fill_input_buffer(j_decompress_ptr cinfo) { /* Suspension */ return FALSE; } METHODDEF(void) -skip_input_data(j_decompress_ptr cinfo, long num_bytes) -{ - JPEGSOURCE* source = (JPEGSOURCE*) cinfo->src; +skip_input_data(j_decompress_ptr cinfo, long num_bytes) { + JPEGSOURCE *source = (JPEGSOURCE *)cinfo->src; - if (num_bytes > (long) source->pub.bytes_in_buffer) { + if (num_bytes > (long)source->pub.bytes_in_buffer) { /* We need to skip more data than we have in the buffer. This will force the JPEG library to suspend decoding. */ source->skip = num_bytes - source->pub.bytes_in_buffer; @@ -103,50 +95,42 @@ skip_input_data(j_decompress_ptr cinfo, long num_bytes) } } - GLOBAL(void) -jpeg_buffer_src(j_decompress_ptr cinfo, JPEGSOURCE* source) -{ - cinfo->src = (void*) source; +jpeg_buffer_src(j_decompress_ptr cinfo, JPEGSOURCE *source) { + cinfo->src = (void *)source; - /* Prepare for suspending reader */ - source->pub.init_source = stub; - source->pub.fill_input_buffer = fill_input_buffer; - source->pub.skip_input_data = skip_input_data; - source->pub.resync_to_restart = jpeg_resync_to_restart; - source->pub.term_source = stub; - source->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ + /* Prepare for suspending reader */ + source->pub.init_source = stub; + source->pub.fill_input_buffer = fill_input_buffer; + source->pub.skip_input_data = skip_input_data; + source->pub.resync_to_restart = jpeg_resync_to_restart; + source->pub.term_source = stub; + source->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ - source->skip = 0; + source->skip = 0; } - /* -------------------------------------------------------------------- */ /* Error handler */ /* -------------------------------------------------------------------- */ METHODDEF(void) -error(j_common_ptr cinfo) -{ - JPEGERROR* error; - error = (JPEGERROR*) cinfo->err; - longjmp(error->setjmp_buffer, 1); +error(j_common_ptr cinfo) { + JPEGERROR *error; + error = (JPEGERROR *)cinfo->err; + longjmp(error->setjmp_buffer, 1); } METHODDEF(void) -output(j_common_ptr cinfo) -{ - /* nothing */ -} +output(j_common_ptr cinfo) { /* nothing */ } /* -------------------------------------------------------------------- */ /* Decoder */ /* -------------------------------------------------------------------- */ int -ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ - JPEGSTATE* context = (JPEGSTATE*) state->context; +ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { + JPEGSTATE *context = (JPEGSTATE *)state->context; int ok; if (setjmp(context->error.setjmp_buffer)) { @@ -157,7 +141,6 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t by } if (!state->state) { - /* Setup decompression context */ context->cinfo.err = jpeg_std_error(&context->error.pub); context->error.pub.error_exit = error; @@ -167,7 +150,6 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t by /* Ready to decode */ state->state = 1; - } /* Load the source buffer */ @@ -182,137 +164,137 @@ ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t by } switch (state->state) { + case 1: - case 1: + /* Read JPEG header, until we find an image body. */ + do { + /* Note that we cannot return unless we have decoded + as much data as possible. */ + ok = jpeg_read_header(&context->cinfo, FALSE); - /* Read JPEG header, until we find an image body. */ - do { + } while (ok == JPEG_HEADER_TABLES_ONLY); - /* Note that we cannot return unless we have decoded - as much data as possible. */ - ok = jpeg_read_header(&context->cinfo, FALSE); + if (ok == JPEG_SUSPENDED) { + break; + } - } while (ok == JPEG_HEADER_TABLES_ONLY); + /* Decoder settings */ - if (ok == JPEG_SUSPENDED) { - break; - } + /* jpegmode indicates whats in the file; if not set, we'll + trust the decoder */ + if (strcmp(context->jpegmode, "L") == 0) { + context->cinfo.jpeg_color_space = JCS_GRAYSCALE; + } else if (strcmp(context->jpegmode, "RGB") == 0) { + context->cinfo.jpeg_color_space = JCS_RGB; + } else if (strcmp(context->jpegmode, "CMYK") == 0) { + context->cinfo.jpeg_color_space = JCS_CMYK; + } else if (strcmp(context->jpegmode, "YCbCr") == 0) { + context->cinfo.jpeg_color_space = JCS_YCbCr; + } else if (strcmp(context->jpegmode, "YCbCrK") == 0) { + context->cinfo.jpeg_color_space = JCS_YCCK; + } - /* Decoder settings */ - - /* jpegmode indicates whats in the file; if not set, we'll - trust the decoder */ - if (strcmp(context->jpegmode, "L") == 0) { - context->cinfo.jpeg_color_space = JCS_GRAYSCALE; - } else if (strcmp(context->jpegmode, "RGB") == 0) { - context->cinfo.jpeg_color_space = JCS_RGB; - } else if (strcmp(context->jpegmode, "CMYK") == 0) { - context->cinfo.jpeg_color_space = JCS_CMYK; - } else if (strcmp(context->jpegmode, "YCbCr") == 0) { - context->cinfo.jpeg_color_space = JCS_YCbCr; - } else if (strcmp(context->jpegmode, "YCbCrK") == 0) { - context->cinfo.jpeg_color_space = JCS_YCCK; - } - - /* rawmode indicates what we want from the decoder. if not - set, conversions are disabled */ - if (strcmp(context->rawmode, "L") == 0) { - context->cinfo.out_color_space = JCS_GRAYSCALE; - } else if (strcmp(context->rawmode, "RGB") == 0) { - context->cinfo.out_color_space = JCS_RGB; - } - #ifdef JCS_EXTENSIONS - else if (strcmp(context->rawmode, "RGBX") == 0) { + /* rawmode indicates what we want from the decoder. if not + set, conversions are disabled */ + if (strcmp(context->rawmode, "L") == 0) { + context->cinfo.out_color_space = JCS_GRAYSCALE; + } else if (strcmp(context->rawmode, "RGB") == 0) { + context->cinfo.out_color_space = JCS_RGB; + } +#ifdef JCS_EXTENSIONS + else if (strcmp(context->rawmode, "RGBX") == 0) { context->cinfo.out_color_space = JCS_EXT_RGBX; - } - #endif - else if (strcmp(context->rawmode, "CMYK") == 0 || - strcmp(context->rawmode, "CMYK;I") == 0) { - context->cinfo.out_color_space = JCS_CMYK; - } else if (strcmp(context->rawmode, "YCbCr") == 0) { - context->cinfo.out_color_space = JCS_YCbCr; - } else if (strcmp(context->rawmode, "YCbCrK") == 0) { - context->cinfo.out_color_space = JCS_YCCK; - } else { - /* Disable decoder conversions */ - context->cinfo.jpeg_color_space = JCS_UNKNOWN; - context->cinfo.out_color_space = JCS_UNKNOWN; - } + } +#endif + else if ( + strcmp(context->rawmode, "CMYK") == 0 || + strcmp(context->rawmode, "CMYK;I") == 0) { + context->cinfo.out_color_space = JCS_CMYK; + } else if (strcmp(context->rawmode, "YCbCr") == 0) { + context->cinfo.out_color_space = JCS_YCbCr; + } else if (strcmp(context->rawmode, "YCbCrK") == 0) { + context->cinfo.out_color_space = JCS_YCCK; + } else { + /* Disable decoder conversions */ + context->cinfo.jpeg_color_space = JCS_UNKNOWN; + context->cinfo.out_color_space = JCS_UNKNOWN; + } - if (context->scale > 1) { - context->cinfo.scale_num = 1; - context->cinfo.scale_denom = context->scale; - } - if (context->draft) { - context->cinfo.do_fancy_upsampling = FALSE; - context->cinfo.dct_method = JDCT_FASTEST; - } + if (context->scale > 1) { + context->cinfo.scale_num = 1; + context->cinfo.scale_denom = context->scale; + } + if (context->draft) { + context->cinfo.do_fancy_upsampling = FALSE; + context->cinfo.dct_method = JDCT_FASTEST; + } - state->state++; - /* fall through */ + state->state++; + /* fall through */ - case 2: + case 2: - /* Set things up for decompression (this processes the entire - file if necessary to return data line by line) */ - if (!jpeg_start_decompress(&context->cinfo)) { - break; - } + /* Set things up for decompression (this processes the entire + file if necessary to return data line by line) */ + if (!jpeg_start_decompress(&context->cinfo)) { + break; + } - state->state++; - /* fall through */ + state->state++; + /* fall through */ - case 3: + case 3: - /* Decompress a single line of data */ - ok = 1; - while (state->y < state->ysize) { - ok = jpeg_read_scanlines(&context->cinfo, &state->buffer, 1); + /* Decompress a single line of data */ + ok = 1; + while (state->y < state->ysize) { + ok = jpeg_read_scanlines(&context->cinfo, &state->buffer, 1); + if (ok != 1) { + break; + } + state->shuffle( + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->buffer, + state->xsize); + state->y++; + } if (ok != 1) { break; } - state->shuffle((UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->buffer, - state->xsize); - state->y++; - } - if (ok != 1) { - break; - } - state->state++; - /* fall through */ + state->state++; + /* fall through */ - case 4: + case 4: - /* Finish decompression */ - if (!jpeg_finish_decompress(&context->cinfo)) { - /* FIXME: add strictness mode test */ - if (state->y < state->ysize) { - break; + /* Finish decompression */ + if (!jpeg_finish_decompress(&context->cinfo)) { + /* FIXME: add strictness mode test */ + if (state->y < state->ysize) { + break; + } } - } - - /* Clean up */ - jpeg_destroy_decompress(&context->cinfo); - /* if (jerr.pub.num_warnings) return BROKEN; */ - return -1; + /* Clean up */ + jpeg_destroy_decompress(&context->cinfo); + /* if (jerr.pub.num_warnings) return BROKEN; */ + return -1; } /* Return number of bytes consumed */ return context->source.pub.next_input_byte - buf; - } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ -int ImagingJpegDecodeCleanup(ImagingCodecState state){ +int +ImagingJpegDecodeCleanup(ImagingCodecState state) { /* called to free the decompression engine when the decode terminates due to a corrupt or truncated image */ - JPEGSTATE* context = (JPEGSTATE*) state->context; + JPEGSTATE *context = (JPEGSTATE *)state->context; /* Clean up */ jpeg_destroy_decompress(&context->cinfo); @@ -320,4 +302,3 @@ int ImagingJpegDecodeCleanup(ImagingCodecState state){ } #endif - diff --git a/src/libImaging/JpegEncode.c b/src/libImaging/JpegEncode.c index ab730d92d..a44debcaf 100644 --- a/src/libImaging/JpegEncode.c +++ b/src/libImaging/JpegEncode.c @@ -19,10 +19,9 @@ * See the README file for details on usage and redistribution. */ - #include "Imaging.h" -#ifdef HAVE_LIBJPEG +#ifdef HAVE_LIBJPEG #undef HAVE_PROTOTYPES #undef HAVE_STDLIB_H @@ -40,51 +39,42 @@ /* -------------------------------------------------------------------- */ METHODDEF(void) -stub(j_compress_ptr cinfo) -{ - /* empty */ -} +stub(j_compress_ptr cinfo) { /* empty */ } METHODDEF(boolean) -empty_output_buffer (j_compress_ptr cinfo) -{ +empty_output_buffer(j_compress_ptr cinfo) { /* Suspension */ return FALSE; } GLOBAL(void) -jpeg_buffer_dest(j_compress_ptr cinfo, JPEGDESTINATION* destination) -{ - cinfo->dest = (void*) destination; +jpeg_buffer_dest(j_compress_ptr cinfo, JPEGDESTINATION *destination) { + cinfo->dest = (void *)destination; destination->pub.init_destination = stub; destination->pub.empty_output_buffer = empty_output_buffer; destination->pub.term_destination = stub; } - /* -------------------------------------------------------------------- */ /* Error handler */ /* -------------------------------------------------------------------- */ METHODDEF(void) -error(j_common_ptr cinfo) -{ - JPEGERROR* error; - error = (JPEGERROR*) cinfo->err; - (*cinfo->err->output_message) (cinfo); +error(j_common_ptr cinfo) { + JPEGERROR *error; + error = (JPEGERROR *)cinfo->err; + (*cinfo->err->output_message)(cinfo); longjmp(error->setjmp_buffer, 1); } - /* -------------------------------------------------------------------- */ /* Encoder */ /* -------------------------------------------------------------------- */ int -ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) -{ - JPEGENCODERSTATE* context = (JPEGENCODERSTATE*) state->context; +ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { + JPEGENCODERSTATE *context = (JPEGENCODERSTATE *)state->context; int ok; if (setjmp(context->error.setjmp_buffer)) { @@ -95,7 +85,6 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) } if (!state->state) { - /* Setup compression context (very similar to the decoder) */ context->cinfo.err = jpeg_std_error(&context->error.pub); context->error.pub.error_exit = error; @@ -106,7 +95,6 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) /* Ready to encode */ state->state = 1; - } /* Load the destination buffer */ @@ -114,7 +102,6 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) context->destination.pub.free_in_buffer = bytes; switch (state->state) { - case 1: context->cinfo.image_width = state->xsize; @@ -136,11 +123,11 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) case 32: context->cinfo.input_components = 4; context->cinfo.in_color_space = JCS_CMYK; - #ifdef JCS_EXTENSIONS +#ifdef JCS_EXTENSIONS if (strcmp(context->rawmode, "RGBX") == 0) { context->cinfo.in_color_space = JCS_EXT_RGBX; } - #endif +#endif break; default: state->errcode = IMAGING_CODEC_CONFIG; @@ -159,15 +146,20 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) quality = context->quality; } for (i = 0; i < context->qtablesLen; i++) { - jpeg_add_quant_table(&context->cinfo, i, &context->qtables[i * DCTSIZE2], - quality, FALSE); + jpeg_add_quant_table( + &context->cinfo, + i, + &context->qtables[i * DCTSIZE2], + quality, + FALSE); context->cinfo.comp_info[i].quant_tbl_no = i; last_q = i; } if (context->qtablesLen == 1) { - // jpeg_set_defaults created two qtables internally, but we only wanted one. - jpeg_add_quant_table(&context->cinfo, 1, &context->qtables[0], - quality, FALSE); + // jpeg_set_defaults created two qtables internally, but we only + // wanted one. + jpeg_add_quant_table( + &context->cinfo, 1, &context->qtables[0], quality, FALSE); } for (i = last_q; i < context->cinfo.num_components; i++) { context->cinfo.comp_info[i].quant_tbl_no = last_q; @@ -177,9 +169,8 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) } /* Set subsampling options */ - switch (context->subsampling) - { - case 0: /* 1x1 1x1 1x1 (4:4:4) : None */ + switch (context->subsampling) { + case 0: /* 1x1 1x1 1x1 (4:4:4) : None */ { context->cinfo.comp_info[0].h_samp_factor = 1; context->cinfo.comp_info[0].v_samp_factor = 1; @@ -189,7 +180,7 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) context->cinfo.comp_info[2].v_samp_factor = 1; break; } - case 1: /* 2x1, 1x1, 1x1 (4:2:2) : Medium */ + case 1: /* 2x1, 1x1, 1x1 (4:2:2) : Medium */ { context->cinfo.comp_info[0].h_samp_factor = 2; context->cinfo.comp_info[0].v_samp_factor = 1; @@ -199,7 +190,7 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) context->cinfo.comp_info[2].v_samp_factor = 1; break; } - case 2: /* 2x2, 1x1, 1x1 (4:2:0) : High */ + case 2: /* 2x2, 1x1, 1x1 (4:2:0) : High */ { context->cinfo.comp_info[0].h_samp_factor = 2; context->cinfo.comp_info[0].v_samp_factor = 2; @@ -209,23 +200,22 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) context->cinfo.comp_info[2].v_samp_factor = 1; break; } - default: - { + default: { /* Use the lib's default */ break; } - } - if (context->progressive) { - jpeg_simple_progression(&context->cinfo); - } - context->cinfo.smoothing_factor = context->smooth; - context->cinfo.optimize_coding = (boolean) context->optimize; - if (context->xdpi > 0 && context->ydpi > 0) { - context->cinfo.write_JFIF_header = TRUE; - context->cinfo.density_unit = 1; /* dots per inch */ - context->cinfo.X_density = context->xdpi; - context->cinfo.Y_density = context->ydpi; - } + } + if (context->progressive) { + jpeg_simple_progression(&context->cinfo); + } + context->cinfo.smoothing_factor = context->smooth; + context->cinfo.optimize_coding = (boolean)context->optimize; + if (context->xdpi > 0 && context->ydpi > 0) { + context->cinfo.write_JFIF_header = TRUE; + context->cinfo.density_unit = 1; /* dots per inch */ + context->cinfo.X_density = context->xdpi; + context->cinfo.Y_density = context->ydpi; + } switch (context->streamtype) { case 1: /* tables only -- not yet implemented */ @@ -248,13 +238,16 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) case 2: // check for exif len + 'APP1' header bytes - if (context->rawExifLen + 5 > context->destination.pub.free_in_buffer){ + if (context->rawExifLen + 5 > context->destination.pub.free_in_buffer) { break; } - //add exif header - if (context->rawExifLen > 0){ - jpeg_write_marker(&context->cinfo, JPEG_APP0+1, - (unsigned char*)context->rawExif, context->rawExifLen); + // add exif header + if (context->rawExifLen > 0) { + jpeg_write_marker( + &context->cinfo, + JPEG_APP0 + 1, + (unsigned char *)context->rawExif, + context->rawExifLen); } state->state++; @@ -267,8 +260,10 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) if (n > context->destination.pub.free_in_buffer) { n = context->destination.pub.free_in_buffer; } - memcpy(context->destination.pub.next_output_byte, - context->extra + context->extra_offset, n); + memcpy( + context->destination.pub.next_output_byte, + context->extra + context->extra_offset, + n); context->destination.pub.next_output_byte += n; context->destination.pub.free_in_buffer -= n; context->extra_offset += n; @@ -282,15 +277,17 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) } case 4: - if (1024 > context->destination.pub.free_in_buffer){ + if (1024 > context->destination.pub.free_in_buffer) { break; } ok = 1; while (state->y < state->ysize) { - state->shuffle(state->buffer, - (UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->xsize); + state->shuffle( + state->buffer, + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->xsize); ok = jpeg_write_scanlines(&context->cinfo, &state->buffer, 1); if (ok != 1) { break; @@ -330,17 +327,14 @@ ImagingJpegEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) /* if (jerr.pub.num_warnings) return BROKEN; */ state->errcode = IMAGING_CODEC_END; break; - } /* Return number of bytes in output buffer */ return context->destination.pub.next_output_byte - buf; - } -const char* -ImagingJpegVersion(void) -{ +const char * +ImagingJpegVersion(void) { static char version[20]; sprintf(version, "%d.%d", JPEG_LIB_VERSION / 10, JPEG_LIB_VERSION % 10); return version; diff --git a/src/libImaging/Matrix.c b/src/libImaging/Matrix.c index e02b7b312..137ed242a 100644 --- a/src/libImaging/Matrix.c +++ b/src/libImaging/Matrix.c @@ -13,65 +13,60 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - -#define CLIPF(v) ((v <= 0.0) ? 0 : (v >= 255.0F) ? 255 : (UINT8) v) - +#define CLIPF(v) ((v <= 0.0) ? 0 : (v >= 255.0F) ? 255 : (UINT8)v) Imaging -ImagingConvertMatrix(Imaging im, const char *mode, float m[]) -{ +ImagingConvertMatrix(Imaging im, const char *mode, float m[]) { Imaging imOut; int x, y; /* Assume there's enough data in the buffer */ if (!im) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (strcmp(mode, "L") == 0 && im->bands == 3) { - imOut = ImagingNewDirty("L", im->xsize, im->ysize); if (!imOut) { return NULL; } for (y = 0; y < im->ysize; y++) { - UINT8* in = (UINT8*) im->image[y]; - UINT8* out = (UINT8*) imOut->image[y]; + UINT8 *in = (UINT8 *)im->image[y]; + UINT8 *out = (UINT8 *)imOut->image[y]; for (x = 0; x < im->xsize; x++) { - float v = m[0]*in[0] + m[1]*in[1] + m[2]*in[2] + m[3] + 0.5; + float v = m[0] * in[0] + m[1] * in[1] + m[2] * in[2] + m[3] + 0.5; out[x] = CLIPF(v); in += 4; } } } else if (strlen(mode) == 3 && im->bands == 3) { - imOut = ImagingNewDirty(mode, im->xsize, im->ysize); if (!imOut) { return NULL; } for (y = 0; y < im->ysize; y++) { - UINT8* in = (UINT8*) im->image[y]; - UINT8* out = (UINT8*) imOut->image[y]; + UINT8 *in = (UINT8 *)im->image[y]; + UINT8 *out = (UINT8 *)imOut->image[y]; for (x = 0; x < im->xsize; x++) { - float v0 = m[0]*in[0] + m[1]*in[1] + m[2]*in[2] + m[3] + 0.5; - float v1 = m[4]*in[0] + m[5]*in[1] + m[6]*in[2] + m[7] + 0.5; - float v2 = m[8]*in[0] + m[9]*in[1] + m[10]*in[2] + m[11] + 0.5; + float v0 = m[0] * in[0] + m[1] * in[1] + m[2] * in[2] + m[3] + 0.5; + float v1 = m[4] * in[0] + m[5] * in[1] + m[6] * in[2] + m[7] + 0.5; + float v2 = m[8] * in[0] + m[9] * in[1] + m[10] * in[2] + m[11] + 0.5; out[0] = CLIPF(v0); out[1] = CLIPF(v1); out[2] = CLIPF(v2); - in += 4; out += 4; + in += 4; + out += 4; } } } else { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } return imOut; diff --git a/src/libImaging/ModeFilter.c b/src/libImaging/ModeFilter.c index b1cf7442c..757cbc3fb 100644 --- a/src/libImaging/ModeFilter.c +++ b/src/libImaging/ModeFilter.c @@ -16,8 +16,7 @@ #include "Imaging.h" Imaging -ImagingModeFilter(Imaging im, int size) -{ +ImagingModeFilter(Imaging im, int size) { Imaging imOut; int x, y, i; int xx, yy; @@ -26,7 +25,7 @@ ImagingModeFilter(Imaging im, int size) int histogram[256]; if (!im || im->bands != 1 || im->type != IMAGING_TYPE_UINT8) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } imOut = ImagingNewDirty(im->mode, im->xsize, im->ysize); @@ -37,9 +36,8 @@ ImagingModeFilter(Imaging im, int size) size = size / 2; for (y = 0; y < imOut->ysize; y++) { - UINT8* out = &IMAGING_PIXEL_L(imOut, 0, y); + UINT8 *out = &IMAGING_PIXEL_L(imOut, 0, y); for (x = 0; x < imOut->xsize; x++) { - /* calculate histogram over current area */ /* FIXME: brute force! to improve, update the histogram @@ -50,7 +48,7 @@ ImagingModeFilter(Imaging im, int size) memset(histogram, 0, sizeof(histogram)); for (yy = y - size; yy <= y + size; yy++) { if (yy >= 0 && yy < imOut->ysize) { - UINT8* in = &IMAGING_PIXEL_L(im, 0, yy); + UINT8 *in = &IMAGING_PIXEL_L(im, 0, yy); for (xx = x - size; xx <= x + size; xx++) { if (xx >= 0 && xx < imOut->xsize) { histogram[in[xx]]++; @@ -65,7 +63,7 @@ ImagingModeFilter(Imaging im, int size) for (i = 1; i < 256; i++) { if (histogram[i] > maxcount) { maxcount = histogram[i]; - maxpixel = (UINT8) i; + maxpixel = (UINT8)i; } } @@ -74,9 +72,7 @@ ImagingModeFilter(Imaging im, int size) } else { out[x] = IMAGING_PIXEL_L(im, x, y); } - } - } ImagingCopyPalette(imOut, im); diff --git a/src/libImaging/Negative.c b/src/libImaging/Negative.c index 09c946bbe..70b96c397 100644 --- a/src/libImaging/Negative.c +++ b/src/libImaging/Negative.c @@ -16,18 +16,15 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - Imaging -ImagingNegative(Imaging im) -{ +ImagingNegative(Imaging im) { Imaging imOut; int x, y; if (!im) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } imOut = ImagingNewDirty(im->mode, im->xsize, im->ysize); @@ -43,4 +40,3 @@ ImagingNegative(Imaging im) return imOut; } - diff --git a/src/libImaging/Offset.c b/src/libImaging/Offset.c index 29f038153..91ee91083 100644 --- a/src/libImaging/Offset.c +++ b/src/libImaging/Offset.c @@ -14,18 +14,15 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - Imaging -ImagingOffset(Imaging im, int xoffset, int yoffset) -{ +ImagingOffset(Imaging im, int xoffset, int yoffset) { int x, y; Imaging imOut; if (!im) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } imOut = ImagingNewDirty(im->mode, im->xsize, im->ysize); @@ -48,13 +45,13 @@ ImagingOffset(Imaging im, int xoffset, int yoffset) yoffset += im->ysize; } -#define OFFSET(image)\ - for (y = 0; y < im->ysize; y++) {\ - for (x = 0; x < im->xsize; x++) {\ - int yi = (y + yoffset) % im->ysize;\ - int xi = (x + xoffset) % im->xsize;\ - imOut->image[y][x] = im->image[yi][xi];\ - }\ +#define OFFSET(image) \ + for (y = 0; y < im->ysize; y++) { \ + for (x = 0; x < im->xsize; x++) { \ + int yi = (y + yoffset) % im->ysize; \ + int xi = (x + xoffset) % im->xsize; \ + imOut->image[y][x] = im->image[yi][xi]; \ + } \ } if (im->image8) { diff --git a/src/libImaging/Pack.c b/src/libImaging/Pack.c index 0be7ad8c9..2fdee919f 100644 --- a/src/libImaging/Pack.c +++ b/src/libImaging/Pack.c @@ -1,4 +1,4 @@ - /* +/* * The Python Imaging Library. * $Id$ * @@ -25,7 +25,6 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" #define R 0 @@ -41,20 +40,28 @@ /* byte swapping macros */ -#define C16N\ - (out[0]=tmp[0], out[1]=tmp[1]); -#define C16S\ - (out[1]=tmp[0], out[0]=tmp[1]); -#define C32N\ - (out[0]=tmp[0], out[1]=tmp[1], out[2]=tmp[2], out[3]=tmp[3]); -#define C32S\ - (out[3]=tmp[0], out[2]=tmp[1], out[1]=tmp[2], out[0]=tmp[3]); -#define C64N\ - (out[0]=tmp[0], out[1]=tmp[1], out[2]=tmp[2], out[3]=tmp[3],\ - out[4]=tmp[4], out[5]=tmp[5], out[6]=tmp[6], out[7]=tmp[7]); -#define C64S\ - (out[7]=tmp[0], out[6]=tmp[1], out[5]=tmp[2], out[4]=tmp[3],\ - out[3]=tmp[4], out[2]=tmp[5], out[1]=tmp[6], out[0]=tmp[7]); +#define C16N (out[0] = tmp[0], out[1] = tmp[1]); +#define C16S (out[1] = tmp[0], out[0] = tmp[1]); +#define C32N (out[0] = tmp[0], out[1] = tmp[1], out[2] = tmp[2], out[3] = tmp[3]); +#define C32S (out[3] = tmp[0], out[2] = tmp[1], out[1] = tmp[2], out[0] = tmp[3]); +#define C64N \ + (out[0] = tmp[0], \ + out[1] = tmp[1], \ + out[2] = tmp[2], \ + out[3] = tmp[3], \ + out[4] = tmp[4], \ + out[5] = tmp[5], \ + out[6] = tmp[6], \ + out[7] = tmp[7]); +#define C64S \ + (out[7] = tmp[0], \ + out[6] = tmp[1], \ + out[5] = tmp[2], \ + out[4] = tmp[3], \ + out[3] = tmp[4], \ + out[2] = tmp[5], \ + out[1] = tmp[6], \ + out[0] = tmp[7]); #ifdef WORDS_BIGENDIAN #define C16B C16N @@ -72,13 +79,12 @@ #define C64L C64N #endif - static void -pack1(UINT8* out, const UINT8* in, int pixels) -{ +pack1(UINT8 *out, const UINT8 *in, int pixels) { int i, m, b; /* bilevel (black is 0) */ - b = 0; m = 128; + b = 0; + m = 128; for (i = 0; i < pixels; i++) { if (in[i] != 0) { b |= m; @@ -86,7 +92,8 @@ pack1(UINT8* out, const UINT8* in, int pixels) m >>= 1; if (m == 0) { *out++ = b; - b = 0; m = 128; + b = 0; + m = 128; } } if (m != 128) { @@ -95,11 +102,11 @@ pack1(UINT8* out, const UINT8* in, int pixels) } static void -pack1I(UINT8* out, const UINT8* in, int pixels) -{ +pack1I(UINT8 *out, const UINT8 *in, int pixels) { int i, m, b; /* bilevel (black is 1) */ - b = 0; m = 128; + b = 0; + m = 128; for (i = 0; i < pixels; i++) { if (in[i] == 0) { b |= m; @@ -107,7 +114,8 @@ pack1I(UINT8* out, const UINT8* in, int pixels) m >>= 1; if (m == 0) { *out++ = b; - b = 0; m = 128; + b = 0; + m = 128; } } if (m != 128) { @@ -116,19 +124,20 @@ pack1I(UINT8* out, const UINT8* in, int pixels) } static void -pack1R(UINT8* out, const UINT8* in, int pixels) -{ +pack1R(UINT8 *out, const UINT8 *in, int pixels) { int i, m, b; /* bilevel, lsb first (black is 0) */ - b = 0; m = 1; + b = 0; + m = 1; for (i = 0; i < pixels; i++) { if (in[i] != 0) { b |= m; } m <<= 1; - if (m == 256){ + if (m == 256) { *out++ = b; - b = 0; m = 1; + b = 0; + m = 1; } } if (m != 1) { @@ -137,19 +146,20 @@ pack1R(UINT8* out, const UINT8* in, int pixels) } static void -pack1IR(UINT8* out, const UINT8* in, int pixels) -{ +pack1IR(UINT8 *out, const UINT8 *in, int pixels) { int i, m, b; /* bilevel, lsb first (black is 1) */ - b = 0; m = 1; + b = 0; + m = 1; for (i = 0; i < pixels; i++) { if (in[i] == 0) { b |= m; } m <<= 1; - if (m == 256){ + if (m == 256) { *out++ = b; - b = 0; m = 1; + b = 0; + m = 1; } } if (m != 1) { @@ -158,8 +168,7 @@ pack1IR(UINT8* out, const UINT8* in, int pixels) } static void -pack1L(UINT8* out, const UINT8* in, int pixels) -{ +pack1L(UINT8 *out, const UINT8 *in, int pixels) { int i; /* bilevel, stored as bytes */ for (i = 0; i < pixels; i++) { @@ -168,12 +177,11 @@ pack1L(UINT8* out, const UINT8* in, int pixels) } static void -packP4(UINT8* out, const UINT8* in, int pixels) -{ +packP4(UINT8 *out, const UINT8 *in, int pixels) { while (pixels >= 2) { - *out++ = (in[0] << 4) | - (in[1] & 15); - in += 2; pixels -= 2; + *out++ = (in[0] << 4) | (in[1] & 15); + in += 2; + pixels -= 2; } if (pixels) { @@ -182,34 +190,27 @@ packP4(UINT8* out, const UINT8* in, int pixels) } static void -packP2(UINT8* out, const UINT8* in, int pixels) -{ +packP2(UINT8 *out, const UINT8 *in, int pixels) { while (pixels >= 4) { - *out++ = (in[0] << 6) | - ((in[1] & 3) << 4) | - ((in[2] & 3) << 2) | - (in[3] & 3); - in += 4; pixels -= 4; + *out++ = (in[0] << 6) | ((in[1] & 3) << 4) | ((in[2] & 3) << 2) | (in[3] & 3); + in += 4; + pixels -= 4; } switch (pixels) { - case 3: - out[0] = (in[0] << 6) | - ((in[1] & 3) << 4) | - ((in[2] & 3) << 2); - break; - case 2: - out[0] = (in[0] << 6) | - ((in[1] & 3) << 4); - break; - case 1: - out[0] = (in[0] << 6); + case 3: + out[0] = (in[0] << 6) | ((in[1] & 3) << 4) | ((in[2] & 3) << 2); + break; + case 2: + out[0] = (in[0] << 6) | ((in[1] & 3) << 4); + break; + case 1: + out[0] = (in[0] << 6); } } static void -packL16(UINT8* out, const UINT8* in, int pixels) -{ +packL16(UINT8 *out, const UINT8 *in, int pixels) { int i; /* L -> L;16, e.g: \xff77 -> \x00\xff\x00\x77 */ for (i = 0; i < pixels; i++) { @@ -220,8 +221,7 @@ packL16(UINT8* out, const UINT8* in, int pixels) } static void -packL16B(UINT8* out, const UINT8* in, int pixels) -{ +packL16B(UINT8 *out, const UINT8 *in, int pixels) { int i; /* L -> L;16B, e.g: \xff77 -> \xff\x00\x77\x00 */ for (i = 0; i < pixels; i++) { @@ -231,34 +231,31 @@ packL16B(UINT8* out, const UINT8* in, int pixels) } } - static void -packLA(UINT8* out, const UINT8* in, int pixels) -{ +packLA(UINT8 *out, const UINT8 *in, int pixels) { int i; /* LA, pixel interleaved */ for (i = 0; i < pixels; i++) { out[0] = in[R]; out[1] = in[A]; - out += 2; in += 4; + out += 2; + in += 4; } } static void -packLAL(UINT8* out, const UINT8* in, int pixels) -{ +packLAL(UINT8 *out, const UINT8 *in, int pixels) { int i; /* LA, line interleaved */ for (i = 0; i < pixels; i++) { out[i] = in[R]; - out[i+pixels] = in[A]; + out[i + pixels] = in[A]; in += 4; } } void -ImagingPackRGB(UINT8* out, const UINT8* in, int pixels) -{ +ImagingPackRGB(UINT8 *out, const UINT8 *in, int pixels) { int i = 0; /* RGB triplets */ #ifdef __sparc @@ -267,25 +264,25 @@ ImagingPackRGB(UINT8* out, const UINT8* in, int pixels) out[0] = in[R]; out[1] = in[G]; out[2] = in[B]; - out += 3; in += 4; + out += 3; + in += 4; } #else - for (; i < pixels-1; i++) { + for (; i < pixels - 1; i++) { memcpy(out, in + i * 4, 4); out += 3; } for (; i < pixels; i++) { - out[0] = in[i*4+R]; - out[1] = in[i*4+G]; - out[2] = in[i*4+B]; + out[0] = in[i * 4 + R]; + out[1] = in[i * 4 + G]; + out[2] = in[i * 4 + B]; out += 3; } #endif } void -ImagingPackXRGB(UINT8* out, const UINT8* in, int pixels) -{ +ImagingPackXRGB(UINT8 *out, const UINT8 *in, int pixels) { int i; /* XRGB, triplets with left padding */ for (i = 0; i < pixels; i++) { @@ -293,26 +290,26 @@ ImagingPackXRGB(UINT8* out, const UINT8* in, int pixels) out[1] = in[R]; out[2] = in[G]; out[3] = in[B]; - out += 4; in += 4; + out += 4; + in += 4; } } void -ImagingPackBGR(UINT8* out, const UINT8* in, int pixels) -{ +ImagingPackBGR(UINT8 *out, const UINT8 *in, int pixels) { int i; /* RGB, reversed bytes */ for (i = 0; i < pixels; i++) { out[0] = in[B]; out[1] = in[G]; out[2] = in[R]; - out += 3; in += 4; + out += 3; + in += 4; } } void -ImagingPackBGRX(UINT8* out, const UINT8* in, int pixels) -{ +ImagingPackBGRX(UINT8 *out, const UINT8 *in, int pixels) { int i; /* BGRX, reversed bytes with right padding */ for (i = 0; i < pixels; i++) { @@ -320,13 +317,13 @@ ImagingPackBGRX(UINT8* out, const UINT8* in, int pixels) out[1] = in[G]; out[2] = in[R]; out[3] = 0; - out += 4; in += 4; + out += 4; + in += 4; } } void -ImagingPackXBGR(UINT8* out, const UINT8* in, int pixels) -{ +ImagingPackXBGR(UINT8 *out, const UINT8 *in, int pixels) { int i; /* XBGR, reversed bytes with left padding */ for (i = 0; i < pixels; i++) { @@ -334,13 +331,13 @@ ImagingPackXBGR(UINT8* out, const UINT8* in, int pixels) out[1] = in[B]; out[2] = in[G]; out[3] = in[R]; - out += 4; in += 4; + out += 4; + in += 4; } } void -ImagingPackBGRA(UINT8* out, const UINT8* in, int pixels) -{ +ImagingPackBGRA(UINT8 *out, const UINT8 *in, int pixels) { int i; /* BGRX, reversed bytes with right padding */ for (i = 0; i < pixels; i++) { @@ -348,13 +345,13 @@ ImagingPackBGRA(UINT8* out, const UINT8* in, int pixels) out[1] = in[G]; out[2] = in[R]; out[3] = in[A]; - out += 4; in += 4; + out += 4; + in += 4; } } void -ImagingPackABGR(UINT8* out, const UINT8* in, int pixels) -{ +ImagingPackABGR(UINT8 *out, const UINT8 *in, int pixels) { int i; /* XBGR, reversed bytes with left padding */ for (i = 0; i < pixels; i++) { @@ -362,13 +359,13 @@ ImagingPackABGR(UINT8* out, const UINT8* in, int pixels) out[1] = in[B]; out[2] = in[G]; out[3] = in[R]; - out += 4; in += 4; + out += 4; + in += 4; } } void -ImagingPackBGRa(UINT8* out, const UINT8* in, int pixels) -{ +ImagingPackBGRa(UINT8 *out, const UINT8 *in, int pixels) { int i; /* BGRa, reversed bytes with premultiplied alpha */ for (i = 0; i < pixels; i++) { @@ -377,43 +374,41 @@ ImagingPackBGRa(UINT8* out, const UINT8* in, int pixels) out[0] = MULDIV255(in[B], alpha, tmp); out[1] = MULDIV255(in[G], alpha, tmp); out[2] = MULDIV255(in[R], alpha, tmp); - out += 4; in += 4; + out += 4; + in += 4; } } static void -packRGBL(UINT8* out, const UINT8* in, int pixels) -{ +packRGBL(UINT8 *out, const UINT8 *in, int pixels) { int i; /* RGB, line interleaved */ for (i = 0; i < pixels; i++) { out[i] = in[R]; - out[i+pixels] = in[G]; - out[i+pixels+pixels] = in[B]; + out[i + pixels] = in[G]; + out[i + pixels + pixels] = in[B]; in += 4; } } static void -packRGBXL(UINT8* out, const UINT8* in, int pixels) -{ +packRGBXL(UINT8 *out, const UINT8 *in, int pixels) { int i; /* RGBX, line interleaved */ for (i = 0; i < pixels; i++) { out[i] = in[R]; - out[i+pixels] = in[G]; - out[i+pixels+pixels] = in[B]; - out[i+pixels+pixels+pixels] = in[X]; + out[i + pixels] = in[G]; + out[i + pixels + pixels] = in[B]; + out[i + pixels + pixels + pixels] = in[X]; in += 4; } } static void -packI16B(UINT8* out, const UINT8* in_, int pixels) -{ +packI16B(UINT8 *out, const UINT8 *in_, int pixels) { int i; UINT16 tmp_; - UINT8* tmp = (UINT8*) &tmp_; + UINT8 *tmp = (UINT8 *)&tmp_; for (i = 0; i < pixels; i++) { INT32 in; memcpy(&in, in_, sizeof(in)); @@ -425,96 +420,91 @@ packI16B(UINT8* out, const UINT8* in_, int pixels) tmp_ = in; } C16B; - out += 2; in_ += sizeof(in); + out += 2; + in_ += sizeof(in); } } static void -packI16N_I16B(UINT8* out, const UINT8* in, int pixels){ +packI16N_I16B(UINT8 *out, const UINT8 *in, int pixels) { int i; - UINT8* tmp = (UINT8*) in; + UINT8 *tmp = (UINT8 *)in; for (i = 0; i < pixels; i++) { C16B; - out += 2; tmp += 2; + out += 2; + tmp += 2; } - } static void -packI16N_I16(UINT8* out, const UINT8* in, int pixels){ +packI16N_I16(UINT8 *out, const UINT8 *in, int pixels) { int i; - UINT8* tmp = (UINT8*) in; + UINT8 *tmp = (UINT8 *)in; for (i = 0; i < pixels; i++) { C16L; - out += 2; tmp += 2; + out += 2; + tmp += 2; } } - static void -packI32S(UINT8* out, const UINT8* in, int pixels) -{ +packI32S(UINT8 *out, const UINT8 *in, int pixels) { int i; - UINT8* tmp = (UINT8*) in; + UINT8 *tmp = (UINT8 *)in; for (i = 0; i < pixels; i++) { C32L; - out += 4; tmp += 4; + out += 4; + tmp += 4; } } void -ImagingPackLAB(UINT8* out, const UINT8* in, int pixels) -{ +ImagingPackLAB(UINT8 *out, const UINT8 *in, int pixels) { int i; /* LAB triplets */ for (i = 0; i < pixels; i++) { out[0] = in[0]; out[1] = in[1] ^ 128; /* signed in outside world */ out[2] = in[2] ^ 128; - out += 3; in += 4; + out += 3; + in += 4; } } static void -copy1(UINT8* out, const UINT8* in, int pixels) -{ +copy1(UINT8 *out, const UINT8 *in, int pixels) { /* L, P */ memcpy(out, in, pixels); } static void -copy2(UINT8* out, const UINT8* in, int pixels) -{ +copy2(UINT8 *out, const UINT8 *in, int pixels) { /* I;16, etc */ - memcpy(out, in, pixels*2); + memcpy(out, in, pixels * 2); } static void -copy3(UINT8* out, const UINT8* in, int pixels) -{ +copy3(UINT8 *out, const UINT8 *in, int pixels) { /* BGR;24, etc */ - memcpy(out, in, pixels*3); + memcpy(out, in, pixels * 3); } static void -copy4(UINT8* out, const UINT8* in, int pixels) -{ +copy4(UINT8 *out, const UINT8 *in, int pixels) { /* RGBA, CMYK quadruples */ - memcpy(out, in, 4*pixels); + memcpy(out, in, 4 * pixels); } static void -copy4I(UINT8* out, const UINT8* in, int pixels) -{ +copy4I(UINT8 *out, const UINT8 *in, int pixels) { /* RGBA, CMYK quadruples, inverted */ int i; - for (i = 0; i < pixels*4; i++) { + for (i = 0; i < pixels * 4; i++) { out[i] = ~in[i]; } } static void -band0(UINT8* out, const UINT8* in, int pixels) -{ +band0(UINT8 *out, const UINT8 *in, int pixels) { int i; for (i = 0; i < pixels; i++, in += 4) { out[i] = in[0]; @@ -522,8 +512,7 @@ band0(UINT8* out, const UINT8* in, int pixels) } static void -band1(UINT8* out, const UINT8* in, int pixels) -{ +band1(UINT8 *out, const UINT8 *in, int pixels) { int i; for (i = 0; i < pixels; i++, in += 4) { out[i] = in[1]; @@ -531,8 +520,7 @@ band1(UINT8* out, const UINT8* in, int pixels) } static void -band2(UINT8* out, const UINT8* in, int pixels) -{ +band2(UINT8 *out, const UINT8 *in, int pixels) { int i; for (i = 0; i < pixels; i++, in += 4) { out[i] = in[2]; @@ -540,8 +528,7 @@ band2(UINT8* out, const UINT8* in, int pixels) } static void -band3(UINT8* out, const UINT8* in, int pixels) -{ +band3(UINT8 *out, const UINT8 *in, int pixels) { int i; for (i = 0; i < pixels; i++, in += 4) { out[i] = in[3]; @@ -549,143 +536,141 @@ band3(UINT8* out, const UINT8* in, int pixels) } static struct { - const char* mode; - const char* rawmode; + const char *mode; + const char *rawmode; int bits; ImagingShuffler pack; } packers[] = { /* bilevel */ - {"1", "1", 1, pack1}, - {"1", "1;I", 1, pack1I}, - {"1", "1;R", 1, pack1R}, - {"1", "1;IR", 1, pack1IR}, - {"1", "L", 8, pack1L}, + {"1", "1", 1, pack1}, + {"1", "1;I", 1, pack1I}, + {"1", "1;R", 1, pack1R}, + {"1", "1;IR", 1, pack1IR}, + {"1", "L", 8, pack1L}, /* greyscale */ - {"L", "L", 8, copy1}, - {"L", "L;16", 16, packL16}, - {"L", "L;16B", 16, packL16B}, + {"L", "L", 8, copy1}, + {"L", "L;16", 16, packL16}, + {"L", "L;16B", 16, packL16B}, /* greyscale w. alpha */ - {"LA", "LA", 16, packLA}, - {"LA", "LA;L", 16, packLAL}, + {"LA", "LA", 16, packLA}, + {"LA", "LA;L", 16, packLAL}, /* greyscale w. alpha premultiplied */ - {"La", "La", 16, packLA}, + {"La", "La", 16, packLA}, /* palette */ - {"P", "P;1", 1, pack1}, - {"P", "P;2", 2, packP2}, - {"P", "P;4", 4, packP4}, - {"P", "P", 8, copy1}, + {"P", "P;1", 1, pack1}, + {"P", "P;2", 2, packP2}, + {"P", "P;4", 4, packP4}, + {"P", "P", 8, copy1}, /* palette w. alpha */ - {"PA", "PA", 16, packLA}, - {"PA", "PA;L", 16, packLAL}, + {"PA", "PA", 16, packLA}, + {"PA", "PA;L", 16, packLAL}, /* true colour */ - {"RGB", "RGB", 24, ImagingPackRGB}, - {"RGB", "RGBX", 32, copy4}, - {"RGB", "XRGB", 32, ImagingPackXRGB}, - {"RGB", "BGR", 24, ImagingPackBGR}, - {"RGB", "BGRX", 32, ImagingPackBGRX}, - {"RGB", "XBGR", 32, ImagingPackXBGR}, - {"RGB", "RGB;L", 24, packRGBL}, - {"RGB", "R", 8, band0}, - {"RGB", "G", 8, band1}, - {"RGB", "B", 8, band2}, + {"RGB", "RGB", 24, ImagingPackRGB}, + {"RGB", "RGBX", 32, copy4}, + {"RGB", "XRGB", 32, ImagingPackXRGB}, + {"RGB", "BGR", 24, ImagingPackBGR}, + {"RGB", "BGRX", 32, ImagingPackBGRX}, + {"RGB", "XBGR", 32, ImagingPackXBGR}, + {"RGB", "RGB;L", 24, packRGBL}, + {"RGB", "R", 8, band0}, + {"RGB", "G", 8, band1}, + {"RGB", "B", 8, band2}, /* true colour w. alpha */ - {"RGBA", "RGBA", 32, copy4}, - {"RGBA", "RGBA;L", 32, packRGBXL}, - {"RGBA", "RGB", 24, ImagingPackRGB}, - {"RGBA", "BGR", 24, ImagingPackBGR}, - {"RGBA", "BGRA", 32, ImagingPackBGRA}, - {"RGBA", "ABGR", 32, ImagingPackABGR}, - {"RGBA", "BGRa", 32, ImagingPackBGRa}, - {"RGBA", "R", 8, band0}, - {"RGBA", "G", 8, band1}, - {"RGBA", "B", 8, band2}, - {"RGBA", "A", 8, band3}, + {"RGBA", "RGBA", 32, copy4}, + {"RGBA", "RGBA;L", 32, packRGBXL}, + {"RGBA", "RGB", 24, ImagingPackRGB}, + {"RGBA", "BGR", 24, ImagingPackBGR}, + {"RGBA", "BGRA", 32, ImagingPackBGRA}, + {"RGBA", "ABGR", 32, ImagingPackABGR}, + {"RGBA", "BGRa", 32, ImagingPackBGRa}, + {"RGBA", "R", 8, band0}, + {"RGBA", "G", 8, band1}, + {"RGBA", "B", 8, band2}, + {"RGBA", "A", 8, band3}, /* true colour w. alpha premultiplied */ - {"RGBa", "RGBa", 32, copy4}, - {"RGBa", "BGRa", 32, ImagingPackBGRA}, - {"RGBa", "aBGR", 32, ImagingPackABGR}, + {"RGBa", "RGBa", 32, copy4}, + {"RGBa", "BGRa", 32, ImagingPackBGRA}, + {"RGBa", "aBGR", 32, ImagingPackABGR}, /* true colour w. padding */ - {"RGBX", "RGBX", 32, copy4}, - {"RGBX", "RGBX;L", 32, packRGBXL}, - {"RGBX", "RGB", 24, ImagingPackRGB}, - {"RGBX", "BGR", 24, ImagingPackBGR}, - {"RGBX", "BGRX", 32, ImagingPackBGRX}, - {"RGBX", "XBGR", 32, ImagingPackXBGR}, - {"RGBX", "R", 8, band0}, - {"RGBX", "G", 8, band1}, - {"RGBX", "B", 8, band2}, - {"RGBX", "X", 8, band3}, + {"RGBX", "RGBX", 32, copy4}, + {"RGBX", "RGBX;L", 32, packRGBXL}, + {"RGBX", "RGB", 24, ImagingPackRGB}, + {"RGBX", "BGR", 24, ImagingPackBGR}, + {"RGBX", "BGRX", 32, ImagingPackBGRX}, + {"RGBX", "XBGR", 32, ImagingPackXBGR}, + {"RGBX", "R", 8, band0}, + {"RGBX", "G", 8, band1}, + {"RGBX", "B", 8, band2}, + {"RGBX", "X", 8, band3}, /* colour separation */ - {"CMYK", "CMYK", 32, copy4}, - {"CMYK", "CMYK;I", 32, copy4I}, - {"CMYK", "CMYK;L", 32, packRGBXL}, - {"CMYK", "C", 8, band0}, - {"CMYK", "M", 8, band1}, - {"CMYK", "Y", 8, band2}, - {"CMYK", "K", 8, band3}, + {"CMYK", "CMYK", 32, copy4}, + {"CMYK", "CMYK;I", 32, copy4I}, + {"CMYK", "CMYK;L", 32, packRGBXL}, + {"CMYK", "C", 8, band0}, + {"CMYK", "M", 8, band1}, + {"CMYK", "Y", 8, band2}, + {"CMYK", "K", 8, band3}, /* video (YCbCr) */ - {"YCbCr", "YCbCr", 24, ImagingPackRGB}, - {"YCbCr", "YCbCr;L", 24, packRGBL}, - {"YCbCr", "YCbCrX", 32, copy4}, - {"YCbCr", "YCbCrK", 32, copy4}, - {"YCbCr", "Y", 8, band0}, - {"YCbCr", "Cb", 8, band1}, - {"YCbCr", "Cr", 8, band2}, + {"YCbCr", "YCbCr", 24, ImagingPackRGB}, + {"YCbCr", "YCbCr;L", 24, packRGBL}, + {"YCbCr", "YCbCrX", 32, copy4}, + {"YCbCr", "YCbCrK", 32, copy4}, + {"YCbCr", "Y", 8, band0}, + {"YCbCr", "Cb", 8, band1}, + {"YCbCr", "Cr", 8, band2}, /* LAB Color */ - {"LAB", "LAB", 24, ImagingPackLAB}, - {"LAB", "L", 8, band0}, - {"LAB", "A", 8, band1}, - {"LAB", "B", 8, band2}, + {"LAB", "LAB", 24, ImagingPackLAB}, + {"LAB", "L", 8, band0}, + {"LAB", "A", 8, band1}, + {"LAB", "B", 8, band2}, /* HSV */ - {"HSV", "HSV", 24, ImagingPackRGB}, - {"HSV", "H", 8, band0}, - {"HSV", "S", 8, band1}, - {"HSV", "V", 8, band2}, + {"HSV", "HSV", 24, ImagingPackRGB}, + {"HSV", "H", 8, band0}, + {"HSV", "S", 8, band1}, + {"HSV", "V", 8, band2}, /* integer */ - {"I", "I", 32, copy4}, - {"I", "I;16B", 16, packI16B}, - {"I", "I;32S", 32, packI32S}, - {"I", "I;32NS", 32, copy4}, + {"I", "I", 32, copy4}, + {"I", "I;16B", 16, packI16B}, + {"I", "I;32S", 32, packI32S}, + {"I", "I;32NS", 32, copy4}, /* floating point */ - {"F", "F", 32, copy4}, - {"F", "F;32F", 32, packI32S}, - {"F", "F;32NF", 32, copy4}, + {"F", "F", 32, copy4}, + {"F", "F;32F", 32, packI32S}, + {"F", "F;32NF", 32, copy4}, /* storage modes */ - {"I;16", "I;16", 16, copy2}, - {"I;16", "I;16B", 16, packI16N_I16B}, - {"I;16B", "I;16B", 16, copy2}, - {"I;16L", "I;16L", 16, copy2}, - {"I;16", "I;16N", 16, packI16N_I16}, // LibTiff native->image endian. - {"I;16L", "I;16N", 16, packI16N_I16}, - {"I;16B", "I;16N", 16, packI16N_I16B}, - {"BGR;15", "BGR;15", 16, copy2}, - {"BGR;16", "BGR;16", 16, copy2}, - {"BGR;24", "BGR;24", 24, copy3}, + {"I;16", "I;16", 16, copy2}, + {"I;16", "I;16B", 16, packI16N_I16B}, + {"I;16B", "I;16B", 16, copy2}, + {"I;16L", "I;16L", 16, copy2}, + {"I;16", "I;16N", 16, packI16N_I16}, // LibTiff native->image endian. + {"I;16L", "I;16N", 16, packI16N_I16}, + {"I;16B", "I;16N", 16, packI16N_I16B}, + {"BGR;15", "BGR;15", 16, copy2}, + {"BGR;16", "BGR;16", 16, copy2}, + {"BGR;24", "BGR;24", 24, copy3}, {NULL} /* sentinel */ }; - ImagingShuffler -ImagingFindPacker(const char* mode, const char* rawmode, int* bits_out) -{ +ImagingFindPacker(const char *mode, const char *rawmode, int *bits_out) { int i; /* find a suitable pixel packer */ diff --git a/src/libImaging/PackDecode.c b/src/libImaging/PackDecode.c index 34671828a..7dd432b91 100644 --- a/src/libImaging/PackDecode.c +++ b/src/libImaging/PackDecode.c @@ -13,30 +13,27 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" int -ImagingPackbitsDecode(Imaging im, ImagingCodecState state, - UINT8* buf, Py_ssize_t bytes) -{ +ImagingPackbitsDecode( + Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { UINT8 n; - UINT8* ptr; + UINT8 *ptr; int i; ptr = buf; for (;;) { - if (bytes < 1) { return ptr - buf; } if (ptr[0] & 0x80) { - if (ptr[0] == 0x80) { /* Nop */ - ptr++; bytes--; + ptr++; + bytes--; continue; } @@ -53,12 +50,12 @@ ImagingPackbitsDecode(Imaging im, ImagingCodecState state, state->buffer[state->x++] = ptr[1]; } - ptr += 2; bytes -= 2; + ptr += 2; + bytes -= 2; } else { - /* Literal */ - n = ptr[0]+2; + n = ptr[0] + 2; if (bytes < n) { return ptr - buf; @@ -72,16 +69,17 @@ ImagingPackbitsDecode(Imaging im, ImagingCodecState state, state->buffer[state->x++] = ptr[i]; } - ptr += n; bytes -= n; - + ptr += n; + bytes -= n; } if (state->x >= state->bytes) { - /* Got a full line, unpack it */ - state->shuffle((UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->buffer, - state->xsize); + state->shuffle( + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->buffer, + state->xsize); state->x = 0; @@ -90,6 +88,5 @@ ImagingPackbitsDecode(Imaging im, ImagingCodecState state, return -1; } } - } } diff --git a/src/libImaging/Palette.c b/src/libImaging/Palette.c index ac548f50c..43bea61e3 100644 --- a/src/libImaging/Palette.c +++ b/src/libImaging/Palette.c @@ -16,46 +16,41 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" #include - ImagingPalette -ImagingPaletteNew(const char* mode) -{ +ImagingPaletteNew(const char *mode) { /* Create a palette object */ int i; ImagingPalette palette; if (strcmp(mode, "RGB") && strcmp(mode, "RGBA")) { - return (ImagingPalette) ImagingError_ModeError(); + return (ImagingPalette)ImagingError_ModeError(); } palette = calloc(1, sizeof(struct ImagingPaletteInstance)); if (!palette) { - return (ImagingPalette) ImagingError_MemoryError(); + return (ImagingPalette)ImagingError_MemoryError(); } - strncpy(palette->mode, mode, IMAGING_MODE_LENGTH-1); - palette->mode[IMAGING_MODE_LENGTH-1] = 0; + strncpy(palette->mode, mode, IMAGING_MODE_LENGTH - 1); + palette->mode[IMAGING_MODE_LENGTH - 1] = 0; /* Initialize to ramp */ for (i = 0; i < 256; i++) { - palette->palette[i*4+0] = - palette->palette[i*4+1] = - palette->palette[i*4+2] = (UINT8) i; - palette->palette[i*4+3] = 255; /* opaque */ + palette->palette[i * 4 + 0] = palette->palette[i * 4 + 1] = + palette->palette[i * 4 + 2] = (UINT8)i; + palette->palette[i * 4 + 3] = 255; /* opaque */ } return palette; } ImagingPalette -ImagingPaletteNewBrowser(void) -{ +ImagingPaletteNewBrowser(void) { /* Create a standard "browser" palette object */ int i, r, g, b; @@ -70,9 +65,8 @@ ImagingPaletteNewBrowser(void) /* FIXME: Add 10-level windows palette here? */ for (i = 0; i < 10; i++) { - palette->palette[i*4+0] = - palette->palette[i*4+1] = - palette->palette[i*4+2] = 0; + palette->palette[i * 4 + 0] = palette->palette[i * 4 + 1] = + palette->palette[i * 4 + 2] = 0; } /* Simple 6x6x6 colour cube */ @@ -80,9 +74,9 @@ ImagingPaletteNewBrowser(void) for (b = 0; b < 256; b += 51) { for (g = 0; g < 256; g += 51) { for (r = 0; r < 256; r += 51) { - palette->palette[i*4+0] = r; - palette->palette[i*4+1] = g; - palette->palette[i*4+2] = b; + palette->palette[i * 4 + 0] = r; + palette->palette[i * 4 + 1] = g; + palette->palette[i * 4 + 2] = b; i++; } } @@ -92,17 +86,15 @@ ImagingPaletteNewBrowser(void) /* FIXME: add 30-level greyscale wedge here? */ for (; i < 256; i++) { - palette->palette[i*4+0] = - palette->palette[i*4+1] = - palette->palette[i*4+2] = 0; + palette->palette[i * 4 + 0] = palette->palette[i * 4 + 1] = + palette->palette[i * 4 + 2] = 0; } return palette; } ImagingPalette -ImagingPaletteDuplicate(ImagingPalette palette) -{ +ImagingPaletteDuplicate(ImagingPalette palette) { /* Duplicate palette descriptor */ ImagingPalette new_palette; @@ -113,7 +105,7 @@ ImagingPaletteDuplicate(ImagingPalette palette) /* malloc check ok, small constant allocation */ new_palette = malloc(sizeof(struct ImagingPaletteInstance)); if (!new_palette) { - return (ImagingPalette) ImagingError_MemoryError(); + return (ImagingPalette)ImagingError_MemoryError(); } memcpy(new_palette, palette, sizeof(struct ImagingPaletteInstance)); @@ -125,8 +117,7 @@ ImagingPaletteDuplicate(ImagingPalette palette) } void -ImagingPaletteDelete(ImagingPalette palette) -{ +ImagingPaletteDelete(ImagingPalette palette) { /* Destroy palette object */ if (palette) { @@ -137,7 +128,6 @@ ImagingPaletteDelete(ImagingPalette palette) } } - /* -------------------------------------------------------------------- */ /* Colour mapping */ /* -------------------------------------------------------------------- */ @@ -155,27 +145,26 @@ ImagingPaletteDelete(ImagingPalette palette) #define DIST(a, b, s) (a - b) * (a - b) * s /* Colour weights (no scaling, for now) */ -#define RSCALE 1 -#define GSCALE 1 -#define BSCALE 1 +#define RSCALE 1 +#define GSCALE 1 +#define BSCALE 1 /* Calculated scaled distances */ -#define RDIST(a, b) DIST(a, b, RSCALE*RSCALE) -#define GDIST(a, b) DIST(a, b, GSCALE*GSCALE) -#define BDIST(a, b) DIST(a, b, BSCALE*BSCALE) +#define RDIST(a, b) DIST(a, b, RSCALE *RSCALE) +#define GDIST(a, b) DIST(a, b, GSCALE *GSCALE) +#define BDIST(a, b) DIST(a, b, BSCALE *BSCALE) /* Incremental steps */ -#define RSTEP (4 * RSCALE) -#define GSTEP (4 * GSCALE) -#define BSTEP (4 * BSCALE) +#define RSTEP (4 * RSCALE) +#define GSTEP (4 * GSCALE) +#define BSTEP (4 * BSCALE) -#define BOX 8 +#define BOX 8 -#define BOXVOLUME BOX*BOX*BOX +#define BOXVOLUME BOX *BOX *BOX void -ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b) -{ +ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b) { int i, j; unsigned int dmin[256], dmax; int r0, g0, b0; @@ -187,32 +176,37 @@ ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b) /* Get box boundaries for the given (r,g,b)-triplet. Each box covers eight cache slots (32 colour values, that is). */ - r0 = r & 0xe0; r1 = r0 + 0x1f; rc = (r0 + r1) / 2; - g0 = g & 0xe0; g1 = g0 + 0x1f; gc = (g0 + g1) / 2; - b0 = b & 0xe0; b1 = b0 + 0x1f; bc = (b0 + b1) / 2; + r0 = r & 0xe0; + r1 = r0 + 0x1f; + rc = (r0 + r1) / 2; + g0 = g & 0xe0; + g1 = g0 + 0x1f; + gc = (g0 + g1) / 2; + b0 = b & 0xe0; + b1 = b0 + 0x1f; + bc = (b0 + b1) / 2; /* Step 1 -- Select relevant palette entries (after Heckbert) */ /* For each palette entry, calculate the min and max distances to * any position in the box given by the colour we're looking for. */ - dmax = (unsigned int) ~0; + dmax = (unsigned int)~0; for (i = 0; i < 256; i++) { - int r, g, b; unsigned int tmin, tmax; /* Find min and max distances to any point in the box */ - r = palette->palette[i*4+0]; + r = palette->palette[i * 4 + 0]; tmin = (r < r0) ? RDIST(r, r1) : (r > r1) ? RDIST(r, r0) : 0; tmax = (r <= rc) ? RDIST(r, r1) : RDIST(r, r0); - g = palette->palette[i*4+1]; + g = palette->palette[i * 4 + 1]; tmin += (g < g0) ? GDIST(g, g1) : (g > g1) ? GDIST(g, g0) : 0; tmax += (g <= gc) ? GDIST(g, g1) : GDIST(g, g0); - b = palette->palette[i*4+2]; + b = palette->palette[i * 4 + 2]; tmin += (b < b0) ? BDIST(b, b1) : (b > b1) ? BDIST(b, b0) : 0; tmax += (b <= bc) ? BDIST(b, b1) : BDIST(b, b0); @@ -220,7 +214,6 @@ ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b) if (tmax < dmax) { dmax = tmax; /* keep the smallest max distance only */ } - } /* Step 2 -- Incrementally update cache slot (after Thomas) */ @@ -230,22 +223,20 @@ ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b) * distance is less than or equal the smallest max distance */ for (i = 0; i < BOXVOLUME; i++) { - d[i] = (unsigned int) ~0; + d[i] = (unsigned int)~0; } for (i = 0; i < 256; i++) { - if (dmin[i] <= dmax) { - int rd, gd, bd; int ri, gi, bi; int rx, gx, bx; - ri = (r0 - palette->palette[i*4+0]) * RSCALE; - gi = (g0 - palette->palette[i*4+1]) * GSCALE; - bi = (b0 - palette->palette[i*4+2]) * BSCALE; + ri = (r0 - palette->palette[i * 4 + 0]) * RSCALE; + gi = (g0 - palette->palette[i * 4 + 1]) * GSCALE; + bi = (b0 - palette->palette[i * 4 + 2]) * BSCALE; - rd = ri*ri + gi*gi + bi*bi; + rd = ri * ri + gi * gi + bi * bi; ri = ri * (2 * RSTEP) + RSTEP * RSTEP; gi = gi * (2 * GSTEP) + GSTEP * GSTEP; @@ -253,13 +244,15 @@ ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b) rx = ri; for (r = j = 0; r < BOX; r++) { - gd = rd; gx = gi; + gd = rd; + gx = gi; for (g = 0; g < BOX; g++) { - bd = gd; bx = bi; + bd = gd; + bx = bi; for (b = 0; b < BOX; b++) { - if ((unsigned int) bd < d[j]) { + if ((unsigned int)bd < d[j]) { d[j] = bd; - c[j] = (UINT8) i; + c[j] = (UINT8)i; } bd += bx; bx += 2 * BSTEP * BSTEP; @@ -280,33 +273,30 @@ ImagingPaletteCacheUpdate(ImagingPalette palette, int r, int g, int b) * cache slot in the box. Update the cache. */ j = 0; - for (r = r0; r < r1; r+=4) { - for (g = g0; g < g1; g+=4) { - for (b = b0; b < b1; b+=4) { + for (r = r0; r < r1; r += 4) { + for (g = g0; g < g1; g += 4) { + for (b = b0; b < b1; b += 4) { ImagingPaletteCache(palette, r, g, b) = c[j++]; } } } } - int -ImagingPaletteCachePrepare(ImagingPalette palette) -{ +ImagingPaletteCachePrepare(ImagingPalette palette) { /* Add a colour cache to a palette */ int i; - int entries = 64*64*64; + int entries = 64 * 64 * 64; if (palette->cache == NULL) { - /* The cache is 512k. It might be a good idea to break it up into a pointer array (e.g. an 8-bit image?) */ /* malloc check ok, small constant allocation */ - palette->cache = (INT16*) malloc(entries * sizeof(INT16)); + palette->cache = (INT16 *)malloc(entries * sizeof(INT16)); if (!palette->cache) { - (void) ImagingError_MemoryError(); + (void)ImagingError_MemoryError(); return -1; } @@ -314,16 +304,13 @@ ImagingPaletteCachePrepare(ImagingPalette palette) for (i = 0; i < entries; i++) { palette->cache[i] = 0x100; } - } return 0; } - void -ImagingPaletteCacheDelete(ImagingPalette palette) -{ +ImagingPaletteCacheDelete(ImagingPalette palette) { /* Release the colour cache, if any */ if (palette && palette->cache) { diff --git a/src/libImaging/Paste.c b/src/libImaging/Paste.c index b89534423..03b17f571 100644 --- a/src/libImaging/Paste.c +++ b/src/libImaging/Paste.c @@ -23,11 +23,17 @@ #include "Imaging.h" - static inline void -paste(Imaging imOut, Imaging imIn, int dx, int dy, int sx, int sy, - int xsize, int ysize, int pixelsize) -{ +paste( + Imaging imOut, + Imaging imIn, + int dx, + int dy, + int sx, + int sy, + int xsize, + int ysize, + int pixelsize) { /* paste opaque region */ int y; @@ -38,25 +44,31 @@ paste(Imaging imOut, Imaging imIn, int dx, int dy, int sx, int sy, xsize *= pixelsize; for (y = 0; y < ysize; y++) { - memcpy(imOut->image[y+dy]+dx, imIn->image[y+sy]+sx, xsize); + memcpy(imOut->image[y + dy] + dx, imIn->image[y + sy] + sx, xsize); } } static inline void -paste_mask_1(Imaging imOut, Imaging imIn, Imaging imMask, - int dx, int dy, int sx, int sy, - int xsize, int ysize, int pixelsize) -{ +paste_mask_1( + Imaging imOut, + Imaging imIn, + Imaging imMask, + int dx, + int dy, + int sx, + int sy, + int xsize, + int ysize, + int pixelsize) { /* paste with mode "1" mask */ int x, y; if (imOut->image8) { - for (y = 0; y < ysize; y++) { - UINT8* out = imOut->image8[y+dy]+dx; - UINT8* in = imIn->image8[y+sy]+sx; - UINT8* mask = imMask->image8[y+sy]+sx; + UINT8 *out = imOut->image8[y + dy] + dx; + UINT8 *in = imIn->image8[y + sy] + sx; + UINT8 *mask = imMask->image8[y + sy] + sx; for (x = 0; x < xsize; x++) { if (*mask++) { *out = *in; @@ -66,11 +78,10 @@ paste_mask_1(Imaging imOut, Imaging imIn, Imaging imMask, } } else { - for (y = 0; y < ysize; y++) { - INT32* out = imOut->image32[y+dy]+dx; - INT32* in = imIn->image32[y+sy]+sx; - UINT8* mask = imMask->image8[y+sy]+sx; + INT32 *out = imOut->image32[y + dy] + dx; + INT32 *in = imIn->image32[y + sy] + sx; + UINT8 *mask = imMask->image8[y + sy] + sx; for (x = 0; x < xsize; x++) { if (*mask++) { *out = *in; @@ -82,21 +93,27 @@ paste_mask_1(Imaging imOut, Imaging imIn, Imaging imMask, } static inline void -paste_mask_L(Imaging imOut, Imaging imIn, Imaging imMask, - int dx, int dy, int sx, int sy, - int xsize, int ysize, int pixelsize) -{ +paste_mask_L( + Imaging imOut, + Imaging imIn, + Imaging imMask, + int dx, + int dy, + int sx, + int sy, + int xsize, + int ysize, + int pixelsize) { /* paste with mode "L" matte */ int x, y; unsigned int tmp1; if (imOut->image8) { - for (y = 0; y < ysize; y++) { - UINT8* out = imOut->image8[y+dy]+dx; - UINT8* in = imIn->image8[y+sy]+sx; - UINT8* mask = imMask->image8[y+sy]+sx; + UINT8 *out = imOut->image8[y + dy] + dx; + UINT8 *in = imIn->image8[y + sy] + sx; + UINT8 *mask = imMask->image8[y + sy] + sx; for (x = 0; x < xsize; x++) { *out = BLEND(*mask, *out, *in, tmp1); out++, in++, mask++; @@ -104,39 +121,46 @@ paste_mask_L(Imaging imOut, Imaging imIn, Imaging imMask, } } else { - for (y = 0; y < ysize; y++) { - UINT8* out = (UINT8*) (imOut->image32[y + dy] + dx); - UINT8* in = (UINT8*) (imIn->image32[y + sy] + sx); - UINT8* mask = (UINT8*) (imMask->image8[y+sy] + sx); + UINT8 *out = (UINT8 *)(imOut->image32[y + dy] + dx); + UINT8 *in = (UINT8 *)(imIn->image32[y + sy] + sx); + UINT8 *mask = (UINT8 *)(imMask->image8[y + sy] + sx); for (x = 0; x < xsize; x++) { UINT8 a = mask[0]; out[0] = BLEND(a, out[0], in[0], tmp1); out[1] = BLEND(a, out[1], in[1], tmp1); out[2] = BLEND(a, out[2], in[2], tmp1); out[3] = BLEND(a, out[3], in[3], tmp1); - out += 4; in += 4; mask ++; + out += 4; + in += 4; + mask++; } } } } static inline void -paste_mask_RGBA(Imaging imOut, Imaging imIn, Imaging imMask, - int dx, int dy, int sx, int sy, - int xsize, int ysize, int pixelsize) -{ +paste_mask_RGBA( + Imaging imOut, + Imaging imIn, + Imaging imMask, + int dx, + int dy, + int sx, + int sy, + int xsize, + int ysize, + int pixelsize) { /* paste with mode "RGBA" matte */ int x, y; unsigned int tmp1; if (imOut->image8) { - for (y = 0; y < ysize; y++) { - UINT8* out = imOut->image8[y+dy]+dx; - UINT8* in = imIn->image8[y+sy]+sx; - UINT8* mask = (UINT8*) imMask->image[y+sy]+sx*4+3; + UINT8 *out = imOut->image8[y + dy] + dx; + UINT8 *in = imIn->image8[y + sy] + sx; + UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx * 4 + 3; for (x = 0; x < xsize; x++) { *out = BLEND(*mask, *out, *in, tmp1); out++, in++, mask += 4; @@ -144,40 +168,46 @@ paste_mask_RGBA(Imaging imOut, Imaging imIn, Imaging imMask, } } else { - for (y = 0; y < ysize; y++) { - UINT8* out = (UINT8*) (imOut->image32[y + dy] + dx); - UINT8* in = (UINT8*) (imIn->image32[y + sy] + sx); - UINT8* mask = (UINT8*) (imMask->image32[y+sy] + sx); + UINT8 *out = (UINT8 *)(imOut->image32[y + dy] + dx); + UINT8 *in = (UINT8 *)(imIn->image32[y + sy] + sx); + UINT8 *mask = (UINT8 *)(imMask->image32[y + sy] + sx); for (x = 0; x < xsize; x++) { UINT8 a = mask[3]; out[0] = BLEND(a, out[0], in[0], tmp1); out[1] = BLEND(a, out[1], in[1], tmp1); out[2] = BLEND(a, out[2], in[2], tmp1); out[3] = BLEND(a, out[3], in[3], tmp1); - out += 4; in += 4; mask += 4; + out += 4; + in += 4; + mask += 4; } } } } - static inline void -paste_mask_RGBa(Imaging imOut, Imaging imIn, Imaging imMask, - int dx, int dy, int sx, int sy, - int xsize, int ysize, int pixelsize) -{ +paste_mask_RGBa( + Imaging imOut, + Imaging imIn, + Imaging imMask, + int dx, + int dy, + int sx, + int sy, + int xsize, + int ysize, + int pixelsize) { /* paste with mode "RGBa" matte */ int x, y; unsigned int tmp1; if (imOut->image8) { - for (y = 0; y < ysize; y++) { - UINT8* out = imOut->image8[y+dy]+dx; - UINT8* in = imIn->image8[y+sy]+sx; - UINT8* mask = (UINT8*) imMask->image[y+sy]+sx*4+3; + UINT8 *out = imOut->image8[y + dy] + dx; + UINT8 *in = imIn->image8[y + sy] + sx; + UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx * 4 + 3; for (x = 0; x < xsize; x++) { *out = PREBLEND(*mask, *out, *in, tmp1); out++, in++, mask += 4; @@ -185,34 +215,34 @@ paste_mask_RGBa(Imaging imOut, Imaging imIn, Imaging imMask, } } else { - for (y = 0; y < ysize; y++) { - UINT8* out = (UINT8*) (imOut->image32[y + dy] + dx); - UINT8* in = (UINT8*) (imIn->image32[y + sy] + sx); - UINT8* mask = (UINT8*) (imMask->image32[y+sy] + sx); + UINT8 *out = (UINT8 *)(imOut->image32[y + dy] + dx); + UINT8 *in = (UINT8 *)(imIn->image32[y + sy] + sx); + UINT8 *mask = (UINT8 *)(imMask->image32[y + sy] + sx); for (x = 0; x < xsize; x++) { UINT8 a = mask[3]; out[0] = PREBLEND(a, out[0], in[0], tmp1); out[1] = PREBLEND(a, out[1], in[1], tmp1); out[2] = PREBLEND(a, out[2], in[2], tmp1); out[3] = PREBLEND(a, out[3], in[3], tmp1); - out += 4; in += 4; mask += 4; + out += 4; + in += 4; + mask += 4; } } } } int -ImagingPaste(Imaging imOut, Imaging imIn, Imaging imMask, - int dx0, int dy0, int dx1, int dy1) -{ +ImagingPaste( + Imaging imOut, Imaging imIn, Imaging imMask, int dx0, int dy0, int dx1, int dy1) { int xsize, ysize; int pixelsize; int sx0, sy0; ImagingSectionCookie cookie; if (!imOut || !imIn) { - (void) ImagingError_ModeError(); + (void)ImagingError_ModeError(); return -1; } @@ -221,14 +251,13 @@ ImagingPaste(Imaging imOut, Imaging imIn, Imaging imMask, xsize = dx1 - dx0; ysize = dy1 - dy0; - if (xsize != imIn->xsize || ysize != imIn->ysize || - pixelsize != imIn->pixelsize) { - (void) ImagingError_Mismatch(); + if (xsize != imIn->xsize || ysize != imIn->ysize || pixelsize != imIn->pixelsize) { + (void)ImagingError_Mismatch(); return -1; } if (imMask && (xsize != imMask->xsize || ysize != imMask->ysize)) { - (void) ImagingError_Mismatch(); + (void)ImagingError_Mismatch(); return -1; } @@ -258,30 +287,28 @@ ImagingPaste(Imaging imOut, Imaging imIn, Imaging imMask, } else if (strcmp(imMask->mode, "1") == 0) { ImagingSectionEnter(&cookie); - paste_mask_1(imOut, imIn, imMask, dx0, dy0, sx0, sy0, - xsize, ysize, pixelsize); + paste_mask_1(imOut, imIn, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize); ImagingSectionLeave(&cookie); } else if (strcmp(imMask->mode, "L") == 0) { ImagingSectionEnter(&cookie); - paste_mask_L(imOut, imIn, imMask, dx0, dy0, sx0, sy0, - xsize, ysize, pixelsize); + paste_mask_L(imOut, imIn, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize); ImagingSectionLeave(&cookie); } else if (strcmp(imMask->mode, "RGBA") == 0) { ImagingSectionEnter(&cookie); - paste_mask_RGBA(imOut, imIn, imMask, dx0, dy0, sx0, sy0, - xsize, ysize, pixelsize); + paste_mask_RGBA( + imOut, imIn, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize); ImagingSectionLeave(&cookie); } else if (strcmp(imMask->mode, "RGBa") == 0) { ImagingSectionEnter(&cookie); - paste_mask_RGBa(imOut, imIn, imMask, dx0, dy0, sx0, sy0, - xsize, ysize, pixelsize); + paste_mask_RGBa( + imOut, imIn, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize); ImagingSectionLeave(&cookie); } else { - (void) ImagingError_ValueError("bad transparency mask"); + (void)ImagingError_ValueError("bad transparency mask"); return -1; } @@ -289,9 +316,14 @@ ImagingPaste(Imaging imOut, Imaging imIn, Imaging imMask, } static inline void -fill(Imaging imOut, const void* ink_, int dx, int dy, - int xsize, int ysize, int pixelsize) -{ +fill( + Imaging imOut, + const void *ink_, + int dx, + int dy, + int xsize, + int ysize, + int pixelsize) { /* fill opaque region */ int x, y; @@ -302,30 +334,34 @@ fill(Imaging imOut, const void* ink_, int dx, int dy, memcpy(&ink8, ink_, sizeof(ink8)); if (imOut->image8 || ink32 == 0L) { - dx *= pixelsize; xsize *= pixelsize; for (y = 0; y < ysize; y++) { - memset(imOut->image[y+dy]+dx, ink8, xsize); + memset(imOut->image[y + dy] + dx, ink8, xsize); } } else { - for (y = 0; y < ysize; y++) { - INT32* out = imOut->image32[y+dy]+dx; + INT32 *out = imOut->image32[y + dy] + dx; for (x = 0; x < xsize; x++) { out[x] = ink32; } } - } } static inline void -fill_mask_1(Imaging imOut, const void* ink_, Imaging imMask, - int dx, int dy, int sx, int sy, - int xsize, int ysize, int pixelsize) -{ +fill_mask_1( + Imaging imOut, + const void *ink_, + Imaging imMask, + int dx, + int dy, + int sx, + int sy, + int xsize, + int ysize, + int pixelsize) { /* fill with mode "1" mask */ int x, y; @@ -336,10 +372,9 @@ fill_mask_1(Imaging imOut, const void* ink_, Imaging imMask, memcpy(&ink8, ink_, sizeof(ink8)); if (imOut->image8) { - for (y = 0; y < ysize; y++) { - UINT8* out = imOut->image8[y+dy]+dx; - UINT8* mask = imMask->image8[y+sy]+sx; + UINT8 *out = imOut->image8[y + dy] + dx; + UINT8 *mask = imMask->image8[y + sy] + sx; for (x = 0; x < xsize; x++) { if (*mask++) { *out = ink8; @@ -349,10 +384,9 @@ fill_mask_1(Imaging imOut, const void* ink_, Imaging imMask, } } else { - for (y = 0; y < ysize; y++) { - INT32* out = imOut->image32[y+dy]+dx; - UINT8* mask = imMask->image8[y+sy]+sx; + INT32 *out = imOut->image32[y + dy] + dx; + UINT8 *mask = imMask->image8[y + sy] + sx; for (x = 0; x < xsize; x++) { if (*mask++) { *out = ink32; @@ -364,20 +398,26 @@ fill_mask_1(Imaging imOut, const void* ink_, Imaging imMask, } static inline void -fill_mask_L(Imaging imOut, const UINT8* ink, Imaging imMask, - int dx, int dy, int sx, int sy, - int xsize, int ysize, int pixelsize) -{ +fill_mask_L( + Imaging imOut, + const UINT8 *ink, + Imaging imMask, + int dx, + int dy, + int sx, + int sy, + int xsize, + int ysize, + int pixelsize) { /* fill with mode "L" matte */ int x, y, i; unsigned int tmp1; if (imOut->image8) { - for (y = 0; y < ysize; y++) { - UINT8* out = imOut->image8[y+dy]+dx; - UINT8* mask = imMask->image8[y+sy]+sx; + UINT8 *out = imOut->image8[y + dy] + dx; + UINT8 *mask = imMask->image8[y + sy] + sx; for (x = 0; x < xsize; x++) { *out = BLEND(*mask, *out, ink[0], tmp1); out++, mask++; @@ -385,21 +425,20 @@ fill_mask_L(Imaging imOut, const UINT8* ink, Imaging imMask, } } else { - for (y = 0; y < ysize; y++) { - UINT8* out = (UINT8*) imOut->image[y+dy]+dx*pixelsize; - UINT8* mask = (UINT8*) imMask->image[y+sy]+sx; + UINT8 *out = (UINT8 *)imOut->image[y + dy] + dx * pixelsize; + UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx; for (x = 0; x < xsize; x++) { for (i = 0; i < pixelsize; i++) { UINT8 channel_mask = *mask; - if (( - strcmp(imOut->mode, "RGBa") == 0 || - strcmp(imOut->mode, "RGBA") == 0 || - strcmp(imOut->mode, "La") == 0 || - strcmp(imOut->mode, "LA") == 0 || - strcmp(imOut->mode, "PA") == 0 - ) && i != 3) { - channel_mask = 255 - (255 - channel_mask) * (1 - (255 - out[3]) / 255); + if ((strcmp(imOut->mode, "RGBa") == 0 || + strcmp(imOut->mode, "RGBA") == 0 || + strcmp(imOut->mode, "La") == 0 || + strcmp(imOut->mode, "LA") == 0 || + strcmp(imOut->mode, "PA") == 0) && + i != 3) { + channel_mask = + 255 - (255 - channel_mask) * (1 - (255 - out[3]) / 255); } out[i] = BLEND(channel_mask, out[i], ink[i], tmp1); } @@ -411,21 +450,27 @@ fill_mask_L(Imaging imOut, const UINT8* ink, Imaging imMask, } static inline void -fill_mask_RGBA(Imaging imOut, const UINT8* ink, Imaging imMask, - int dx, int dy, int sx, int sy, - int xsize, int ysize, int pixelsize) -{ +fill_mask_RGBA( + Imaging imOut, + const UINT8 *ink, + Imaging imMask, + int dx, + int dy, + int sx, + int sy, + int xsize, + int ysize, + int pixelsize) { /* fill with mode "RGBA" matte */ int x, y, i; unsigned int tmp1; if (imOut->image8) { - - sx = sx*4+3; + sx = sx * 4 + 3; for (y = 0; y < ysize; y++) { - UINT8* out = imOut->image8[y+dy]+dx; - UINT8* mask = (UINT8*) imMask->image[y+sy]+sx; + UINT8 *out = imOut->image8[y + dy] + dx; + UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx; for (x = 0; x < xsize; x++) { *out = BLEND(*mask, *out, ink[0], tmp1); out++, mask += 4; @@ -433,12 +478,11 @@ fill_mask_RGBA(Imaging imOut, const UINT8* ink, Imaging imMask, } } else { - dx *= pixelsize; - sx = sx*4 + 3; + sx = sx * 4 + 3; for (y = 0; y < ysize; y++) { - UINT8* out = (UINT8*) imOut->image[y+dy]+dx; - UINT8* mask = (UINT8*) imMask->image[y+sy]+sx; + UINT8 *out = (UINT8 *)imOut->image[y + dy] + dx; + UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx; for (x = 0; x < xsize; x++) { for (i = 0; i < pixelsize; i++) { *out = BLEND(*mask, *out, ink[i], tmp1); @@ -451,21 +495,27 @@ fill_mask_RGBA(Imaging imOut, const UINT8* ink, Imaging imMask, } static inline void -fill_mask_RGBa(Imaging imOut, const UINT8* ink, Imaging imMask, - int dx, int dy, int sx, int sy, - int xsize, int ysize, int pixelsize) -{ +fill_mask_RGBa( + Imaging imOut, + const UINT8 *ink, + Imaging imMask, + int dx, + int dy, + int sx, + int sy, + int xsize, + int ysize, + int pixelsize) { /* fill with mode "RGBa" matte */ int x, y, i; unsigned int tmp1; if (imOut->image8) { - - sx = sx*4 + 3; + sx = sx * 4 + 3; for (y = 0; y < ysize; y++) { - UINT8* out = imOut->image8[y+dy]+dx; - UINT8* mask = (UINT8*) imMask->image[y+sy]+sx; + UINT8 *out = imOut->image8[y + dy] + dx; + UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx; for (x = 0; x < xsize; x++) { *out = PREBLEND(*mask, *out, ink[0], tmp1); out++, mask += 4; @@ -473,12 +523,11 @@ fill_mask_RGBa(Imaging imOut, const UINT8* ink, Imaging imMask, } } else { - dx *= pixelsize; - sx = sx*4 + 3; + sx = sx * 4 + 3; for (y = 0; y < ysize; y++) { - UINT8* out = (UINT8*) imOut->image[y+dy]+dx; - UINT8* mask = (UINT8*) imMask->image[y+sy]+sx; + UINT8 *out = (UINT8 *)imOut->image[y + dy] + dx; + UINT8 *mask = (UINT8 *)imMask->image[y + sy] + sx; for (x = 0; x < xsize; x++) { for (i = 0; i < pixelsize; i++) { *out = PREBLEND(*mask, *out, ink[i], tmp1); @@ -491,16 +540,21 @@ fill_mask_RGBa(Imaging imOut, const UINT8* ink, Imaging imMask, } int -ImagingFill2(Imaging imOut, const void* ink, Imaging imMask, - int dx0, int dy0, int dx1, int dy1) -{ +ImagingFill2( + Imaging imOut, + const void *ink, + Imaging imMask, + int dx0, + int dy0, + int dx1, + int dy1) { ImagingSectionCookie cookie; int xsize, ysize; int pixelsize; int sx0, sy0; if (!imOut || !ink) { - (void) ImagingError_ModeError(); + (void)ImagingError_ModeError(); return -1; } @@ -510,7 +564,7 @@ ImagingFill2(Imaging imOut, const void* ink, Imaging imMask, ysize = dy1 - dy0; if (imMask && (xsize != imMask->xsize || ysize != imMask->ysize)) { - (void) ImagingError_Mismatch(); + (void)ImagingError_Mismatch(); return -1; } @@ -540,30 +594,26 @@ ImagingFill2(Imaging imOut, const void* ink, Imaging imMask, } else if (strcmp(imMask->mode, "1") == 0) { ImagingSectionEnter(&cookie); - fill_mask_1(imOut, ink, imMask, dx0, dy0, sx0, sy0, - xsize, ysize, pixelsize); + fill_mask_1(imOut, ink, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize); ImagingSectionLeave(&cookie); } else if (strcmp(imMask->mode, "L") == 0) { ImagingSectionEnter(&cookie); - fill_mask_L(imOut, ink, imMask, dx0, dy0, sx0, sy0, - xsize, ysize, pixelsize); + fill_mask_L(imOut, ink, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize); ImagingSectionLeave(&cookie); } else if (strcmp(imMask->mode, "RGBA") == 0) { ImagingSectionEnter(&cookie); - fill_mask_RGBA(imOut, ink, imMask, dx0, dy0, sx0, sy0, - xsize, ysize, pixelsize); + fill_mask_RGBA(imOut, ink, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize); ImagingSectionLeave(&cookie); } else if (strcmp(imMask->mode, "RGBa") == 0) { ImagingSectionEnter(&cookie); - fill_mask_RGBa(imOut, ink, imMask, dx0, dy0, sx0, sy0, - xsize, ysize, pixelsize); + fill_mask_RGBa(imOut, ink, imMask, dx0, dy0, sx0, sy0, xsize, ysize, pixelsize); ImagingSectionLeave(&cookie); } else { - (void) ImagingError_ValueError("bad transparency mask"); + (void)ImagingError_ValueError("bad transparency mask"); return -1; } diff --git a/src/libImaging/PcdDecode.c b/src/libImaging/PcdDecode.c index ff192a174..f13803cb6 100644 --- a/src/libImaging/PcdDecode.c +++ b/src/libImaging/PcdDecode.c @@ -19,24 +19,20 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - int -ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ +ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { int x; int chunk; - UINT8* out; - UINT8* ptr; + UINT8 *out; + UINT8 *ptr; ptr = buf; chunk = 3 * state->xsize; for (;;) { - /* We need data for two full lines before we can do anything */ if (bytes < chunk) { return ptr - buf; @@ -46,13 +42,12 @@ ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt out = state->buffer; for (x = 0; x < state->xsize; x++) { out[0] = ptr[x]; - out[1] = ptr[(x+4*state->xsize)/2]; - out[2] = ptr[(x+5*state->xsize)/2]; + out[1] = ptr[(x + 4 * state->xsize) / 2]; + out[2] = ptr[(x + 5 * state->xsize) / 2]; out += 3; } - state->shuffle((UINT8*) im->image[state->y], - state->buffer, state->xsize); + state->shuffle((UINT8 *)im->image[state->y], state->buffer, state->xsize); if (++state->y >= state->ysize) { return -1; /* This can hardly happen */ @@ -61,14 +56,13 @@ ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt /* Unpack second line */ out = state->buffer; for (x = 0; x < state->xsize; x++) { - out[0] = ptr[x+state->xsize]; - out[1] = ptr[(x+4*state->xsize)/2]; - out[2] = ptr[(x+5*state->xsize)/2]; + out[0] = ptr[x + state->xsize]; + out[1] = ptr[(x + 4 * state->xsize) / 2]; + out[2] = ptr[(x + 5 * state->xsize) / 2]; out += 3; } - state->shuffle((UINT8*) im->image[state->y], - state->buffer, state->xsize); + state->shuffle((UINT8 *)im->image[state->y], state->buffer, state->xsize); if (++state->y >= state->ysize) { return -1; @@ -76,6 +70,5 @@ ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt ptr += chunk; bytes -= chunk; - } } diff --git a/src/libImaging/PcxDecode.c b/src/libImaging/PcxDecode.c index eb0fecc83..c95ffc869 100644 --- a/src/libImaging/PcxDecode.c +++ b/src/libImaging/PcxDecode.c @@ -13,14 +13,12 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" int -ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ +ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { UINT8 n; - UINT8* ptr; + UINT8 *ptr; if ((state->xsize * state->bits + 7) / 8 > state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; @@ -30,13 +28,11 @@ ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt ptr = buf; for (;;) { - if (bytes < 1) { return ptr - buf; } if ((*ptr & 0xC0) == 0xC0) { - /* Run */ if (bytes < 2) { return ptr - buf; @@ -53,14 +49,14 @@ ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt n--; } - ptr += 2; bytes -= 2; + ptr += 2; + bytes -= 2; } else { - /* Literal */ state->buffer[state->x++] = ptr[0]; - ptr++; bytes--; - + ptr++; + bytes--; } if (state->x >= state->bytes) { @@ -68,16 +64,19 @@ ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt int bands = state->bytes / state->xsize; int stride = state->bytes / bands; int i; - for (i=1; i< bands; i++) { // note -- skipping first band - memmove(&state->buffer[i*state->xsize], - &state->buffer[i*stride], - state->xsize); + for (i = 1; i < bands; i++) { // note -- skipping first band + memmove( + &state->buffer[i * state->xsize], + &state->buffer[i * stride], + state->xsize); } } /* Got a full line, unpack it */ - state->shuffle((UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->buffer, - state->xsize); + state->shuffle( + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->buffer, + state->xsize); state->x = 0; @@ -86,6 +85,5 @@ ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt return -1; } } - } } diff --git a/src/libImaging/PcxEncode.c b/src/libImaging/PcxEncode.c index 163b09b13..549614bfd 100644 --- a/src/libImaging/PcxEncode.c +++ b/src/libImaging/PcxEncode.c @@ -13,7 +13,6 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" enum { INIT, FETCH, ENCODE }; @@ -22,9 +21,8 @@ enum { INIT, FETCH, ENCODE }; #define LAST ystep int -ImagingPcxEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) -{ - UINT8* ptr; +ImagingPcxEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { + UINT8 *ptr; int this; int bytes_per_line = 0; int padding = 0; @@ -45,12 +43,12 @@ ImagingPcxEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) } bpp = state->bits; - if (state->bits == 24){ + if (state->bits == 24) { planes = 3; bpp = 8; } - bytes_per_line = (state->xsize*bpp + 7) / 8; + bytes_per_line = (state->xsize * bpp + 7) / 8; /* The stride here needs to be kept in sync with the version in PcxImagePlugin.py. If it's not, the header and the body of the image will be out of sync and bad things will happen on decode. @@ -59,133 +57,131 @@ ImagingPcxEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) padding = stride - bytes_per_line; - for (;;) { - switch (state->state) { - case FETCH: + case FETCH: - /* get a line of data */ - if (state->y >= state->ysize) { - state->errcode = IMAGING_CODEC_END; - return ptr - buf; - } + /* get a line of data */ + if (state->y >= state->ysize) { + state->errcode = IMAGING_CODEC_END; + return ptr - buf; + } - state->shuffle(state->buffer, - (UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->xsize); + state->shuffle( + state->buffer, + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->xsize); - state->y += 1; + state->y += 1; - state->count = 1; - state->LAST = state->buffer[0]; + state->count = 1; + state->LAST = state->buffer[0]; - state->x = 1; + state->x = 1; - state->state = ENCODE; - /* fall through */ + state->state = ENCODE; + /* fall through */ - case ENCODE: - /* compress this line */ + case ENCODE: + /* compress this line */ - /* when we arrive here, "count" contains the number of - bytes having the value of "LAST" that we've already - seen */ - do { - /* If we're encoding an odd width file, and we've - got more than one plane, we need to pad each - color row with padding bytes at the end. Since - The pixels are stored RRRRRGGGGGBBBBB, so we need - to have the padding be RRRRRPGGGGGPBBBBBP. Hence - the double loop - */ - while (state->x % bytes_per_line) { - - if (state->count == 63) { - /* this run is full; flush it */ - if (bytes < 2) { - return ptr - buf; - } - ptr[0] = 0xff; - ptr[1] = state->LAST; - ptr += 2; - bytes -= 2; - - state->count = 0; - } - - this = state->buffer[state->x]; - - if (this == state->LAST) { - /* extend the current run */ - state->x += 1; - state->count += 1; - - } else { - /* start a new run */ - if (state->count == 1 && (state->LAST < 0xc0)) { - if (bytes < 1) { + /* when we arrive here, "count" contains the number of + bytes having the value of "LAST" that we've already + seen */ + do { + /* If we're encoding an odd width file, and we've + got more than one plane, we need to pad each + color row with padding bytes at the end. Since + The pixels are stored RRRRRGGGGGBBBBB, so we need + to have the padding be RRRRRPGGGGGPBBBBBP. Hence + the double loop + */ + while (state->x % bytes_per_line) { + if (state->count == 63) { + /* this run is full; flush it */ + if (bytes < 2) { return ptr - buf; } - ptr[0] = state->LAST; - ptr += 1; - bytes -= 1; + ptr[0] = 0xff; + ptr[1] = state->LAST; + ptr += 2; + bytes -= 2; + + state->count = 0; + } + + this = state->buffer[state->x]; + + if (this == state->LAST) { + /* extend the current run */ + state->x += 1; + state->count += 1; + } else { - if (state->count > 0) { - if (bytes < 2) { + /* start a new run */ + if (state->count == 1 && (state->LAST < 0xc0)) { + if (bytes < 1) { return ptr - buf; } - ptr[0] = 0xc0 | state->count; - ptr[1] = state->LAST; - ptr += 2; - bytes -= 2; + ptr[0] = state->LAST; + ptr += 1; + bytes -= 1; + } else { + if (state->count > 0) { + if (bytes < 2) { + return ptr - buf; + } + ptr[0] = 0xc0 | state->count; + ptr[1] = state->LAST; + ptr += 2; + bytes -= 2; + } } + + state->LAST = this; + state->count = 1; + + state->x += 1; } - - state->LAST = this; - state->count = 1; - - state->x += 1; } - } - /* end of line; flush the current run */ - if (state->count == 1 && (state->LAST < 0xc0)) { - if (bytes < 1 + padding) { - return ptr - buf; - } - ptr[0] = state->LAST; - ptr += 1; - bytes -= 1; - } else { - if (state->count > 0) { - if (bytes < 2 + padding) { + /* end of line; flush the current run */ + if (state->count == 1 && (state->LAST < 0xc0)) { + if (bytes < 1 + padding) { return ptr - buf; } - ptr[0] = 0xc0 | state->count; - ptr[1] = state->LAST; - ptr += 2; - bytes -= 2; + ptr[0] = state->LAST; + ptr += 1; + bytes -= 1; + } else { + if (state->count > 0) { + if (bytes < 2 + padding) { + return ptr - buf; + } + ptr[0] = 0xc0 | state->count; + ptr[1] = state->LAST; + ptr += 2; + bytes -= 2; + } } - } - /* add the padding */ - for (i = 0; i < padding; i++) { - ptr[0] = 0; - ptr += 1; - bytes -= 1; - } - /* reset for the next color plane. */ - if (state->x < planes * bytes_per_line) { - state->count = 1; - state->LAST = state->buffer[state->x]; - state->x += 1; - } - } while (state->x < planes * bytes_per_line); + /* add the padding */ + for (i = 0; i < padding; i++) { + ptr[0] = 0; + ptr += 1; + bytes -= 1; + } + /* reset for the next color plane. */ + if (state->x < planes * bytes_per_line) { + state->count = 1; + state->LAST = state->buffer[state->x]; + state->x += 1; + } + } while (state->x < planes * bytes_per_line); - /* read next line */ - state->state = FETCH; - break; + /* read next line */ + state->state = FETCH; + break; } } } - diff --git a/src/libImaging/Point.c b/src/libImaging/Point.c index b70840b07..8883578cb 100644 --- a/src/libImaging/Point.c +++ b/src/libImaging/Point.c @@ -19,22 +19,20 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" typedef struct { - const void* table; + const void *table; } im_point_context; static void -im_point_8_8(Imaging imOut, Imaging imIn, im_point_context* context) -{ +im_point_8_8(Imaging imOut, Imaging imIn, im_point_context *context) { int x, y; /* 8-bit source, 8-bit destination */ - UINT8* table = (UINT8*) context->table; + UINT8 *table = (UINT8 *)context->table; for (y = 0; y < imIn->ysize; y++) { - UINT8* in = imIn->image8[y]; - UINT8* out = imOut->image8[y]; + UINT8 *in = imIn->image8[y]; + UINT8 *out = imOut->image8[y]; for (x = 0; x < imIn->xsize; x++) { out[x] = table[in[x]]; } @@ -42,68 +40,67 @@ im_point_8_8(Imaging imOut, Imaging imIn, im_point_context* context) } static void -im_point_2x8_2x8(Imaging imOut, Imaging imIn, im_point_context* context) -{ +im_point_2x8_2x8(Imaging imOut, Imaging imIn, im_point_context *context) { int x, y; /* 2x8-bit source, 2x8-bit destination */ - UINT8* table = (UINT8*) context->table; + UINT8 *table = (UINT8 *)context->table; for (y = 0; y < imIn->ysize; y++) { - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out = (UINT8*) imOut->image[y]; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out = (UINT8 *)imOut->image[y]; for (x = 0; x < imIn->xsize; x++) { out[0] = table[in[0]]; - out[3] = table[in[3]+256]; - in += 4; out += 4; + out[3] = table[in[3] + 256]; + in += 4; + out += 4; } } } static void -im_point_3x8_3x8(Imaging imOut, Imaging imIn, im_point_context* context) -{ +im_point_3x8_3x8(Imaging imOut, Imaging imIn, im_point_context *context) { int x, y; /* 3x8-bit source, 3x8-bit destination */ - UINT8* table = (UINT8*) context->table; + UINT8 *table = (UINT8 *)context->table; for (y = 0; y < imIn->ysize; y++) { - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out = (UINT8*) imOut->image[y]; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out = (UINT8 *)imOut->image[y]; for (x = 0; x < imIn->xsize; x++) { out[0] = table[in[0]]; - out[1] = table[in[1]+256]; - out[2] = table[in[2]+512]; - in += 4; out += 4; + out[1] = table[in[1] + 256]; + out[2] = table[in[2] + 512]; + in += 4; + out += 4; } } } static void -im_point_4x8_4x8(Imaging imOut, Imaging imIn, im_point_context* context) -{ +im_point_4x8_4x8(Imaging imOut, Imaging imIn, im_point_context *context) { int x, y; /* 4x8-bit source, 4x8-bit destination */ - UINT8* table = (UINT8*) context->table; + UINT8 *table = (UINT8 *)context->table; for (y = 0; y < imIn->ysize; y++) { - UINT8* in = (UINT8*) imIn->image[y]; - UINT8* out = (UINT8*) imOut->image[y]; + UINT8 *in = (UINT8 *)imIn->image[y]; + UINT8 *out = (UINT8 *)imOut->image[y]; for (x = 0; x < imIn->xsize; x++) { out[0] = table[in[0]]; - out[1] = table[in[1]+256]; - out[2] = table[in[2]+512]; - out[3] = table[in[3]+768]; - in += 4; out += 4; + out[1] = table[in[1] + 256]; + out[2] = table[in[2] + 512]; + out[3] = table[in[3] + 768]; + in += 4; + out += 4; } } } static void -im_point_8_32(Imaging imOut, Imaging imIn, im_point_context* context) -{ +im_point_8_32(Imaging imOut, Imaging imIn, im_point_context *context) { int x, y; /* 8-bit source, 32-bit destination */ - char* table = (char*) context->table; + char *table = (char *)context->table; for (y = 0; y < imIn->ysize; y++) { - UINT8* in = imIn->image8[y]; - INT32* out = imOut->image32[y]; + UINT8 *in = imIn->image8[y]; + INT32 *out = imOut->image32[y]; for (x = 0; x < imIn->xsize; x++) { memcpy(out + x, table + in[x] * sizeof(INT32), sizeof(INT32)); } @@ -111,14 +108,13 @@ im_point_8_32(Imaging imOut, Imaging imIn, im_point_context* context) } static void -im_point_32_8(Imaging imOut, Imaging imIn, im_point_context* context) -{ +im_point_32_8(Imaging imOut, Imaging imIn, im_point_context *context) { int x, y; /* 32-bit source, 8-bit destination */ - UINT8* table = (UINT8*) context->table; + UINT8 *table = (UINT8 *)context->table; for (y = 0; y < imIn->ysize; y++) { - INT32* in = imIn->image32[y]; - UINT8* out = imOut->image8[y]; + INT32 *in = imIn->image32[y]; + UINT8 *out = imOut->image8[y]; for (x = 0; x < imIn->xsize; x++) { int v = in[x]; if (v < 0) { @@ -132,17 +128,16 @@ im_point_32_8(Imaging imOut, Imaging imIn, im_point_context* context) } Imaging -ImagingPoint(Imaging imIn, const char* mode, const void* table) -{ +ImagingPoint(Imaging imIn, const char *mode, const void *table) { /* lookup table transform */ ImagingSectionCookie cookie; Imaging imOut; im_point_context context; - void (*point)(Imaging imIn, Imaging imOut, im_point_context* context); + void (*point)(Imaging imIn, Imaging imOut, im_point_context * context); if (!imIn) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (!mode) { @@ -166,22 +161,22 @@ ImagingPoint(Imaging imIn, const char* mode, const void* table) if (imIn->type == IMAGING_TYPE_UINT8) { if (imIn->bands == imOut->bands && imIn->type == imOut->type) { switch (imIn->bands) { - case 1: - point = im_point_8_8; - break; - case 2: - point = im_point_2x8_2x8; - break; - case 3: - point = im_point_3x8_3x8; - break; - case 4: - point = im_point_4x8_4x8; - break; - default: - /* this cannot really happen */ - point = im_point_8_8; - break; + case 1: + point = im_point_8_8; + break; + case 2: + point = im_point_2x8_2x8; + break; + case 3: + point = im_point_3x8_3x8; + break; + case 4: + point = im_point_4x8_4x8; + break; + default: + /* this cannot really happen */ + point = im_point_8_8; + break; } } else { point = im_point_8_32; @@ -201,26 +196,22 @@ ImagingPoint(Imaging imIn, const char* mode, const void* table) return imOut; - mode_mismatch: - return (Imaging) ImagingError_ValueError( - "point operation not supported for this mode" - ); +mode_mismatch: + return (Imaging)ImagingError_ValueError( + "point operation not supported for this mode"); } - Imaging -ImagingPointTransform(Imaging imIn, double scale, double offset) -{ +ImagingPointTransform(Imaging imIn, double scale, double offset) { /* scale/offset transform */ ImagingSectionCookie cookie; Imaging imOut; int x, y; - if (!imIn || (strcmp(imIn->mode, "I") != 0 && - strcmp(imIn->mode, "I;16") != 0 && + if (!imIn || (strcmp(imIn->mode, "I") != 0 && strcmp(imIn->mode, "I;16") != 0 && strcmp(imIn->mode, "F") != 0)) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } imOut = ImagingNew(imIn->mode, imIn->xsize, imIn->ysize); @@ -229,50 +220,50 @@ ImagingPointTransform(Imaging imIn, double scale, double offset) } switch (imIn->type) { - case IMAGING_TYPE_INT32: - ImagingSectionEnter(&cookie); - for (y = 0; y < imIn->ysize; y++) { - INT32* in = imIn->image32[y]; - INT32* out = imOut->image32[y]; - /* FIXME: add clipping? */ - for (x = 0; x < imIn->xsize; x++) { - out[x] = in[x] * scale + offset; - } - } - ImagingSectionLeave(&cookie); - break; - case IMAGING_TYPE_FLOAT32: - ImagingSectionEnter(&cookie); - for (y = 0; y < imIn->ysize; y++) { - FLOAT32* in = (FLOAT32*) imIn->image32[y]; - FLOAT32* out = (FLOAT32*) imOut->image32[y]; - for (x = 0; x < imIn->xsize; x++) { - out[x] = in[x] * scale + offset; - } - } - ImagingSectionLeave(&cookie); - break; - case IMAGING_TYPE_SPECIAL: - if (strcmp(imIn->mode,"I;16") == 0) { + case IMAGING_TYPE_INT32: ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { - char* in = (char*)imIn->image[y]; - char* out = (char*)imOut->image[y]; + INT32 *in = imIn->image32[y]; + INT32 *out = imOut->image32[y]; /* FIXME: add clipping? */ for (x = 0; x < imIn->xsize; x++) { - UINT16 v; - memcpy(&v, in + x * sizeof(v), sizeof(v)); - v = v * scale + offset; - memcpy(out + x * sizeof(UINT16), &v, sizeof(v)); + out[x] = in[x] * scale + offset; } } ImagingSectionLeave(&cookie); break; - } - /* FALL THROUGH */ - default: - ImagingDelete(imOut); - return (Imaging) ImagingError_ValueError("internal error"); + case IMAGING_TYPE_FLOAT32: + ImagingSectionEnter(&cookie); + for (y = 0; y < imIn->ysize; y++) { + FLOAT32 *in = (FLOAT32 *)imIn->image32[y]; + FLOAT32 *out = (FLOAT32 *)imOut->image32[y]; + for (x = 0; x < imIn->xsize; x++) { + out[x] = in[x] * scale + offset; + } + } + ImagingSectionLeave(&cookie); + break; + case IMAGING_TYPE_SPECIAL: + if (strcmp(imIn->mode, "I;16") == 0) { + ImagingSectionEnter(&cookie); + for (y = 0; y < imIn->ysize; y++) { + char *in = (char *)imIn->image[y]; + char *out = (char *)imOut->image[y]; + /* FIXME: add clipping? */ + for (x = 0; x < imIn->xsize; x++) { + UINT16 v; + memcpy(&v, in + x * sizeof(v), sizeof(v)); + v = v * scale + offset; + memcpy(out + x * sizeof(UINT16), &v, sizeof(v)); + } + } + ImagingSectionLeave(&cookie); + break; + } + /* FALL THROUGH */ + default: + ImagingDelete(imOut); + return (Imaging)ImagingError_ValueError("internal error"); } return imOut; diff --git a/src/libImaging/Quant.c b/src/libImaging/Quant.c index 6c9f8d9b7..bee5e5599 100644 --- a/src/libImaging/Quant.c +++ b/src/libImaging/Quant.c @@ -43,169 +43,155 @@ typedef struct { } PixelHashData; typedef struct _PixelList { - struct _PixelList *next[3],*prev[3]; + struct _PixelList *next[3], *prev[3]; Pixel p; - unsigned int flag:1; + unsigned int flag : 1; int count; } PixelList; typedef struct _BoxNode { - struct _BoxNode *l,*r; - PixelList *head[3],*tail[3]; + struct _BoxNode *l, *r; + PixelList *head[3], *tail[3]; int axis; int volume; uint32_t pixelCount; } BoxNode; -#define _SQR(x) ((x)*(x)) -#define _DISTSQR(p1,p2) \ - _SQR((int)((p1)->c.r)-(int)((p2)->c.r))+ \ - _SQR((int)((p1)->c.g)-(int)((p2)->c.g))+ \ - _SQR((int)((p1)->c.b)-(int)((p2)->c.b)) +#define _SQR(x) ((x) * (x)) +#define _DISTSQR(p1, p2) \ + _SQR((int)((p1)->c.r) - (int)((p2)->c.r)) + \ + _SQR((int)((p1)->c.g) - (int)((p2)->c.g)) + \ + _SQR((int)((p1)->c.b) - (int)((p2)->c.b)) #define MAX_HASH_ENTRIES 65536 -#define PIXEL_HASH(r,g,b) \ - (((unsigned int)(r) )*463 ^ \ - ((unsigned int)(g)<< 8)*10069 ^ \ - ((unsigned int)(b)<<16)*64997) +#define PIXEL_HASH(r, g, b) \ + (((unsigned int)(r)) * 463 ^ ((unsigned int)(g) << 8) * 10069 ^ \ + ((unsigned int)(b) << 16) * 64997) -#define PIXEL_UNSCALE(p,q,s) \ - ((q)->c.r=(p)->c.r<<(s)), \ - ((q)->c.g=(p)->c.g<<(s)), \ - ((q)->c.b=(p)->c.b<<(s)) +#define PIXEL_UNSCALE(p, q, s) \ + ((q)->c.r = (p)->c.r << (s)), ((q)->c.g = (p)->c.g << (s)), \ + ((q)->c.b = (p)->c.b << (s)) -#define PIXEL_SCALE(p,q,s)\ - ((q)->c.r=(p)->c.r>>(s)), \ - ((q)->c.g=(p)->c.g>>(s)), \ - ((q)->c.b=(p)->c.b>>(s)) +#define PIXEL_SCALE(p, q, s) \ + ((q)->c.r = (p)->c.r >> (s)), ((q)->c.g = (p)->c.g >> (s)), \ + ((q)->c.b = (p)->c.b >> (s)) static uint32_t -unshifted_pixel_hash(const HashTable *h, const Pixel pixel) -{ - return PIXEL_HASH(pixel.c.r, pixel.c.g, pixel.c.b); +unshifted_pixel_hash(const HashTable *h, const Pixel pixel) { + return PIXEL_HASH(pixel.c.r, pixel.c.g, pixel.c.b); } static int -unshifted_pixel_cmp(const HashTable *h, const Pixel pixel1, const Pixel pixel2) -{ - if (pixel1.c.r==pixel2.c.r) { - if (pixel1.c.g==pixel2.c.g) { - if (pixel1.c.b==pixel2.c.b) { +unshifted_pixel_cmp(const HashTable *h, const Pixel pixel1, const Pixel pixel2) { + if (pixel1.c.r == pixel2.c.r) { + if (pixel1.c.g == pixel2.c.g) { + if (pixel1.c.b == pixel2.c.b) { return 0; } else { - return (int)(pixel1.c.b)-(int)(pixel2.c.b); + return (int)(pixel1.c.b) - (int)(pixel2.c.b); } } else { - return (int)(pixel1.c.g)-(int)(pixel2.c.g); + return (int)(pixel1.c.g) - (int)(pixel2.c.g); } } else { - return (int)(pixel1.c.r)-(int)(pixel2.c.r); + return (int)(pixel1.c.r) - (int)(pixel2.c.r); } } static uint32_t -pixel_hash(const HashTable *h,const Pixel pixel) -{ - PixelHashData *d=(PixelHashData *)hashtable_get_user_data(h); - return PIXEL_HASH(pixel.c.r>>d->scale, pixel.c.g>>d->scale, pixel.c.b>>d->scale); +pixel_hash(const HashTable *h, const Pixel pixel) { + PixelHashData *d = (PixelHashData *)hashtable_get_user_data(h); + return PIXEL_HASH( + pixel.c.r >> d->scale, pixel.c.g >> d->scale, pixel.c.b >> d->scale); } static int -pixel_cmp(const HashTable *h,const Pixel pixel1, const Pixel pixel2) -{ - PixelHashData *d=(PixelHashData *)hashtable_get_user_data(h); - uint32_t A,B; - A=PIXEL_HASH(pixel1.c.r>>d->scale, pixel1.c.g>>d->scale, pixel1.c.b>>d->scale); - B=PIXEL_HASH(pixel2.c.r>>d->scale, pixel2.c.g>>d->scale, pixel2.c.b>>d->scale); - return (A==B)?0:((A> d->scale, pixel1.c.g >> d->scale, pixel1.c.b >> d->scale); + B = PIXEL_HASH( + pixel2.c.r >> d->scale, pixel2.c.g >> d->scale, pixel2.c.b >> d->scale); + return (A == B) ? 0 : ((A < B) ? -1 : 1); } static void -exists_count_func(const HashTable *h, const Pixel key, uint32_t *val) -{ - *val+=1; +exists_count_func(const HashTable *h, const Pixel key, uint32_t *val) { + *val += 1; } static void -new_count_func(const HashTable *h, const Pixel key, uint32_t *val) -{ - *val=1; +new_count_func(const HashTable *h, const Pixel key, uint32_t *val) { + *val = 1; } static void -rehash_collide(const HashTable *h, - Pixel *keyp, - uint32_t *valp, - Pixel newkey, - uint32_t newval) -{ +rehash_collide( + const HashTable *h, Pixel *keyp, uint32_t *valp, Pixel newkey, uint32_t newval) { *valp += newval; } /* %% */ static HashTable * -create_pixel_hash(Pixel *pixelData,uint32_t nPixels) -{ - PixelHashData *d; - HashTable *hash; - uint32_t i; +create_pixel_hash(Pixel *pixelData, uint32_t nPixels) { + PixelHashData *d; + HashTable *hash; + uint32_t i; #ifndef NO_OUTPUT - uint32_t timer,timer2,timer3; + uint32_t timer, timer2, timer3; #endif - /* malloc check ok, small constant allocation */ - d=malloc(sizeof(PixelHashData)); - if (!d) { - return NULL; - } - hash=hashtable_new(pixel_hash,pixel_cmp); - hashtable_set_user_data(hash,d); - d->scale=0; + /* malloc check ok, small constant allocation */ + d = malloc(sizeof(PixelHashData)); + if (!d) { + return NULL; + } + hash = hashtable_new(pixel_hash, pixel_cmp); + hashtable_set_user_data(hash, d); + d->scale = 0; #ifndef NO_OUTPUT - timer=timer3=clock(); + timer = timer3 = clock(); #endif - for (i=0;iMAX_HASH_ENTRIES) { - d->scale++; + for (i = 0; i < nPixels; i++) { + if (!hashtable_insert_or_update_computed( + hash, pixelData[i], new_count_func, exists_count_func)) { + ; + } + while (hashtable_get_count(hash) > MAX_HASH_ENTRIES) { + d->scale++; #ifndef NO_OUTPUT - printf ("rehashing - new scale: %d\n",(int)d->scale); - timer2=clock(); + printf("rehashing - new scale: %d\n", (int)d->scale); + timer2 = clock(); #endif - hashtable_rehash_compute(hash,rehash_collide); + hashtable_rehash_compute(hash, rehash_collide); #ifndef NO_OUTPUT - timer2=clock()-timer2; - printf ("rehash took %f sec\n",timer2/(double)CLOCKS_PER_SEC); - timer+=timer2; + timer2 = clock() - timer2; + printf("rehash took %f sec\n", timer2 / (double)CLOCKS_PER_SEC); + timer += timer2; #endif - } - } + } + } #ifndef NO_OUTPUT - printf ("inserts took %f sec\n",(clock()-timer)/(double)CLOCKS_PER_SEC); + printf("inserts took %f sec\n", (clock() - timer) / (double)CLOCKS_PER_SEC); #endif #ifndef NO_OUTPUT - printf ("total %f sec\n",(clock()-timer3)/(double)CLOCKS_PER_SEC); + printf("total %f sec\n", (clock() - timer3) / (double)CLOCKS_PER_SEC); #endif - return hash; + return hash; } static void -destroy_pixel_hash(HashTable *hash) -{ - PixelHashData *d=(PixelHashData *)hashtable_get_user_data(hash); - if (d) { - free(d); - } - hashtable_free(hash); +destroy_pixel_hash(HashTable *hash) { + PixelHashData *d = (PixelHashData *)hashtable_get_user_data(hash); + if (d) { + free(d); + } + hashtable_free(hash); } - /* 1. hash quantized pixels. */ /* 2. create R,G,B lists of sorted quantized pixels. */ /* 3. median cut. */ @@ -215,659 +201,662 @@ destroy_pixel_hash(HashTable *hash) /* 7. map each pixel to nearest average. */ static int -compute_box_volume(BoxNode *b) -{ - unsigned char rl,rh,gl,gh,bl,bh; - if (b->volume>=0) { - return b->volume; - } - if (!b->head[0]) { - b->volume=0; - } else { - rh=b->head[0]->p.c.r; - rl=b->tail[0]->p.c.r; - gh=b->head[1]->p.c.g; - gl=b->tail[1]->p.c.g; - bh=b->head[2]->p.c.b; - bl=b->tail[2]->p.c.b; - b->volume=(rh-rl+1)*(gh-gl+1)*(bh-bl+1); - } - return b->volume; +compute_box_volume(BoxNode *b) { + unsigned char rl, rh, gl, gh, bl, bh; + if (b->volume >= 0) { + return b->volume; + } + if (!b->head[0]) { + b->volume = 0; + } else { + rh = b->head[0]->p.c.r; + rl = b->tail[0]->p.c.r; + gh = b->head[1]->p.c.g; + gl = b->tail[1]->p.c.g; + bh = b->head[2]->p.c.b; + bl = b->tail[2]->p.c.b; + b->volume = (rh - rl + 1) * (gh - gl + 1) * (bh - bl + 1); + } + return b->volume; } static void -hash_to_list(const HashTable *h, const Pixel pixel, const uint32_t count, void *u) -{ - PixelHashData *d=(PixelHashData *)hashtable_get_user_data(h); - PixelList **pl=(PixelList **)u; - PixelList *p; - int i; - Pixel q; +hash_to_list(const HashTable *h, const Pixel pixel, const uint32_t count, void *u) { + PixelHashData *d = (PixelHashData *)hashtable_get_user_data(h); + PixelList **pl = (PixelList **)u; + PixelList *p; + int i; + Pixel q; - PIXEL_SCALE(&pixel,&q,d->scale); + PIXEL_SCALE(&pixel, &q, d->scale); - /* malloc check ok, small constant allocation */ - p=malloc(sizeof(PixelList)); - if (!p) { - return; - } + /* malloc check ok, small constant allocation */ + p = malloc(sizeof(PixelList)); + if (!p) { + return; + } - p->flag=0; - p->p=q; - p->count=count; - for (i=0;i<3;i++) { - p->next[i]=pl[i]; - p->prev[i]=NULL; - if (pl[i]) { - pl[i]->prev[i]=p; - } - pl[i]=p; - } + p->flag = 0; + p->p = q; + p->count = count; + for (i = 0; i < 3; i++) { + p->next[i] = pl[i]; + p->prev[i] = NULL; + if (pl[i]) { + pl[i]->prev[i] = p; + } + pl[i] = p; + } } static PixelList * -mergesort_pixels(PixelList *head, int i) -{ - PixelList *c,*t,*a,*b,*p; - if (!head||!head->next[i]) { - if (head) { - head->next[i]=NULL; - head->prev[i]=NULL; - } - return head; - } - for (c=t=head;c&&t;c=c->next[i],t=(t->next[i])?t->next[i]->next[i]:NULL); - if (c) { - if (c->prev[i]) { - c->prev[i]->next[i]=NULL; - } - c->prev[i]=NULL; - } - a=mergesort_pixels(head,i); - b=mergesort_pixels(c,i); - head=NULL; - p=NULL; - while (a&&b) { - if (a->p.a.v[i]>b->p.a.v[i]) { - c=a; - a=a->next[i]; - } else { - c=b; - b=b->next[i]; - } - c->prev[i]=p; - c->next[i]=NULL; - if (p) { - p->next[i]=c; - } - p=c; - if (!head) { - head=c; - } - } - if (a) { - c->next[i]=a; - a->prev[i]=c; - } else if (b) { - c->next[i]=b; - b->prev[i]=c; - } - return head; +mergesort_pixels(PixelList *head, int i) { + PixelList *c, *t, *a, *b, *p; + if (!head || !head->next[i]) { + if (head) { + head->next[i] = NULL; + head->prev[i] = NULL; + } + return head; + } + for (c = t = head; c && t; + c = c->next[i], t = (t->next[i]) ? t->next[i]->next[i] : NULL) + ; + if (c) { + if (c->prev[i]) { + c->prev[i]->next[i] = NULL; + } + c->prev[i] = NULL; + } + a = mergesort_pixels(head, i); + b = mergesort_pixels(c, i); + head = NULL; + p = NULL; + while (a && b) { + if (a->p.a.v[i] > b->p.a.v[i]) { + c = a; + a = a->next[i]; + } else { + c = b; + b = b->next[i]; + } + c->prev[i] = p; + c->next[i] = NULL; + if (p) { + p->next[i] = c; + } + p = c; + if (!head) { + head = c; + } + } + if (a) { + c->next[i] = a; + a->prev[i] = c; + } else if (b) { + c->next[i] = b; + b->prev[i] = c; + } + return head; } #if defined(TEST_MERGESORT) || defined(TEST_SORTED) static int -test_sorted(PixelList *pl[3]) -{ - int i,n,l; - PixelList *t; +test_sorted(PixelList *pl[3]) { + int i, n, l; + PixelList *t; - for(i=0;i<3;i++) { - n=0; - l=256; - for (t=pl[i];t;t=t->next[i]) { - if (lp.a.v[i]) return 0; - l=t->p.a.v[i]; - } - } - return 1; + for (i = 0; i < 3; i++) { + n = 0; + l = 256; + for (t = pl[i]; t; t = t->next[i]) { + if (l < t->p.a.v[i]) + return 0; + l = t->p.a.v[i]; + } + } + return 1; } #endif static int -box_heap_cmp(const Heap *h, const void *A, const void *B) -{ - BoxNode *a=(BoxNode *)A; - BoxNode *b=(BoxNode *)B; - return (int)a->pixelCount-(int)b->pixelCount; +box_heap_cmp(const Heap *h, const void *A, const void *B) { + BoxNode *a = (BoxNode *)A; + BoxNode *b = (BoxNode *)B; + return (int)a->pixelCount - (int)b->pixelCount; } -#define LUMINANCE(p) (77*(p)->c.r+150*(p)->c.g+29*(p)->c.b) +#define LUMINANCE(p) (77 * (p)->c.r + 150 * (p)->c.g + 29 * (p)->c.b) static int -splitlists(PixelList *h[3], - PixelList *t[3], - PixelList *nh[2][3], - PixelList *nt[2][3], - uint32_t nCount[2], - int axis, - uint32_t pixelCount) -{ - uint32_t left; +splitlists( + PixelList *h[3], + PixelList *t[3], + PixelList *nh[2][3], + PixelList *nt[2][3], + uint32_t nCount[2], + int axis, + uint32_t pixelCount) { + uint32_t left; - PixelList *l,*r,*c,*n; - int i; - int nRight,nLeft; - int splitColourVal; + PixelList *l, *r, *c, *n; + int i; + int nRight, nLeft; + int splitColourVal; #ifdef TEST_SPLIT - { - PixelList *_prevTest,*_nextTest; - int _i,_nextCount[3],_prevCount[3]; - for (_i=0;_i<3;_i++) { - for (_nextCount[_i]=0,_nextTest=h[_i];_nextTest&&_nextTest->next[_i];_nextTest=_nextTest->next[_i],_nextCount[_i]++); - for (_prevCount[_i]=0,_prevTest=t[_i];_prevTest&&_prevTest->prev[_i];_prevTest=_prevTest->prev[_i],_prevCount[_i]++); - if (_nextTest!=t[_i]) { - printf ("next-list of axis %d does not end at tail\n",_i); - exit(1); - } - if (_prevTest!=h[_i]) { - printf ("prev-list of axis %d does not end at head\n",_i); - exit(1); - } - for (;_nextTest&&_nextTest->prev[_i];_nextTest=_nextTest->prev[_i]); - for (;_prevTest&&_prevTest->next[_i];_prevTest=_prevTest->next[_i]); - if (_nextTest!=h[_i]) { - printf ("next-list of axis %d does not loop back to head\n",_i); - exit(1); - } - if (_prevTest!=t[_i]) { - printf ("prev-list of axis %d does not loop back to tail\n",_i); - exit(1); - } - } - for (_i=1;_i<3;_i++) { - if (_prevCount[_i]!=_prevCount[_i-1] || - _nextCount[_i]!=_nextCount[_i-1] || - _prevCount[_i]!=_nextCount[_i]) { - printf ("{%d %d %d} {%d %d %d}\n", + { + PixelList *_prevTest, *_nextTest; + int _i, _nextCount[3], _prevCount[3]; + for (_i = 0; _i < 3; _i++) { + for (_nextCount[_i] = 0, _nextTest = h[_i]; + _nextTest && _nextTest->next[_i]; + _nextTest = _nextTest->next[_i], _nextCount[_i]++) + ; + for (_prevCount[_i] = 0, _prevTest = t[_i]; + _prevTest && _prevTest->prev[_i]; + _prevTest = _prevTest->prev[_i], _prevCount[_i]++) + ; + if (_nextTest != t[_i]) { + printf("next-list of axis %d does not end at tail\n", _i); + exit(1); + } + if (_prevTest != h[_i]) { + printf("prev-list of axis %d does not end at head\n", _i); + exit(1); + } + for (; _nextTest && _nextTest->prev[_i]; _nextTest = _nextTest->prev[_i]) + ; + for (; _prevTest && _prevTest->next[_i]; _prevTest = _prevTest->next[_i]) + ; + if (_nextTest != h[_i]) { + printf("next-list of axis %d does not loop back to head\n", _i); + exit(1); + } + if (_prevTest != t[_i]) { + printf("prev-list of axis %d does not loop back to tail\n", _i); + exit(1); + } + } + for (_i = 1; _i < 3; _i++) { + if (_prevCount[_i] != _prevCount[_i - 1] || + _nextCount[_i] != _nextCount[_i - 1] || + _prevCount[_i] != _nextCount[_i]) { + printf( + "{%d %d %d} {%d %d %d}\n", _prevCount[0], _prevCount[1], _prevCount[2], _nextCount[0], _nextCount[1], _nextCount[2]); - exit(1); - } - } + exit(1); + } + } } #endif - nCount[0]=nCount[1]=0; - nLeft=nRight=0; - for (left=0,c=h[axis];c;) { - left=left+c->count; - nCount[0]+=c->count; - c->flag=0; - nLeft++; - c=c->next[axis]; - if (left*2>pixelCount) { - break; - } - } - if (c) { - splitColourVal=c->prev[axis]->p.a.v[axis]; - for (;c;c=c->next[axis]) { - if (splitColourVal!=c->p.a.v[axis]) { + nCount[0] = nCount[1] = 0; + nLeft = nRight = 0; + for (left = 0, c = h[axis]; c;) { + left = left + c->count; + nCount[0] += c->count; + c->flag = 0; + nLeft++; + c = c->next[axis]; + if (left * 2 > pixelCount) { break; - } - c->flag=0; - nLeft++; - nCount[0]+=c->count; - } - } - for (;c;c=c->next[axis]) { - c->flag=1; - nRight++; - nCount[1]+=c->count; - } - if (!nRight) { - for (c=t[axis],splitColourVal=t[axis]->p.a.v[axis];c;c=c->prev[axis]) { - if (splitColourVal!=c->p.a.v[axis]) { - break; - } - c->flag=1; - nRight++; - nLeft--; - nCount[0]-=c->count; - nCount[1]+=c->count; - } - } + } + } + if (c) { + splitColourVal = c->prev[axis]->p.a.v[axis]; + for (; c; c = c->next[axis]) { + if (splitColourVal != c->p.a.v[axis]) { + break; + } + c->flag = 0; + nLeft++; + nCount[0] += c->count; + } + } + for (; c; c = c->next[axis]) { + c->flag = 1; + nRight++; + nCount[1] += c->count; + } + if (!nRight) { + for (c = t[axis], splitColourVal = t[axis]->p.a.v[axis]; c; c = c->prev[axis]) { + if (splitColourVal != c->p.a.v[axis]) { + break; + } + c->flag = 1; + nRight++; + nLeft--; + nCount[0] -= c->count; + nCount[1] += c->count; + } + } #ifndef NO_OUTPUT - if (!nLeft) { - for (c=h[axis];c;c=c->next[axis]) { - printf ("[%d %d %d]\n",c->p.c.r,c->p.c.g,c->p.c.b); - } - printf ("warning... trivial split\n"); - } + if (!nLeft) { + for (c = h[axis]; c; c = c->next[axis]) { + printf("[%d %d %d]\n", c->p.c.r, c->p.c.g, c->p.c.b); + } + printf("warning... trivial split\n"); + } #endif - for (i=0;i<3;i++) { - l=r=NULL; - nh[0][i]=nt[0][i]=NULL; - nh[1][i]=nt[1][i]=NULL; - for (c=h[i];c;c=n) { - n=c->next[i]; - if (c->flag) { /* move pixel to right list*/ - if (r) { - r->next[i]=c; - } else { - nh[1][i]=c; + for (i = 0; i < 3; i++) { + l = r = NULL; + nh[0][i] = nt[0][i] = NULL; + nh[1][i] = nt[1][i] = NULL; + for (c = h[i]; c; c = n) { + n = c->next[i]; + if (c->flag) { /* move pixel to right list*/ + if (r) { + r->next[i] = c; + } else { + nh[1][i] = c; + } + c->prev[i] = r; + r = c; + } else { /* move pixel to left list */ + if (l) { + l->next[i] = c; + } else { + nh[0][i] = c; + } + c->prev[i] = l; + l = c; } - c->prev[i]=r; - r=c; - } else { /* move pixel to left list */ - if (l) { - l->next[i]=c; - } else { - nh[0][i]=c; - } - c->prev[i]=l; - l=c; - } - } - if (l) { - l->next[i]=NULL; - } - if (r) { - r->next[i]=NULL; - } - nt[0][i]=l; - nt[1][i]=r; - } - return 1; + } + if (l) { + l->next[i] = NULL; + } + if (r) { + r->next[i] = NULL; + } + nt[0][i] = l; + nt[1][i] = r; + } + return 1; } static int -split(BoxNode *node) -{ - unsigned char rl,rh,gl,gh,bl,bh; - int f[3]; - int best,axis; - int i; - PixelList *heads[2][3]; - PixelList *tails[2][3]; - uint32_t newCounts[2]; - BoxNode *left,*right; +split(BoxNode *node) { + unsigned char rl, rh, gl, gh, bl, bh; + int f[3]; + int best, axis; + int i; + PixelList *heads[2][3]; + PixelList *tails[2][3]; + uint32_t newCounts[2]; + BoxNode *left, *right; - rh=node->head[0]->p.c.r; - rl=node->tail[0]->p.c.r; - gh=node->head[1]->p.c.g; - gl=node->tail[1]->p.c.g; - bh=node->head[2]->p.c.b; - bl=node->tail[2]->p.c.b; + rh = node->head[0]->p.c.r; + rl = node->tail[0]->p.c.r; + gh = node->head[1]->p.c.g; + gl = node->tail[1]->p.c.g; + bh = node->head[2]->p.c.b; + bl = node->tail[2]->p.c.b; #ifdef TEST_SPLIT - printf ("splitting node [%d %d %d] [%d %d %d] ",rl,gl,bl,rh,gh,bh); + printf("splitting node [%d %d %d] [%d %d %d] ", rl, gl, bl, rh, gh, bh); #endif - f[0]=(rh-rl)*77; - f[1]=(gh-gl)*150; - f[2]=(bh-bl)*29; + f[0] = (rh - rl) * 77; + f[1] = (gh - gl) * 150; + f[2] = (bh - bl) * 29; - best=f[0]; - axis=0; - for (i=1;i<3;i++) { - if (besttail[_i]->next[_i]) { - printf ("tail is not tail\n"); - printf ("node->tail[%d]->next[%d]=%p\n",_i,_i,node->tail[_i]->next[_i]); - } - if (node->head[_i]->prev[_i]) { - printf ("head is not head\n"); - printf ("node->head[%d]->prev[%d]=%p\n",_i,_i,node->head[_i]->prev[_i]); - } - } + { + PixelList *_prevTest, *_nextTest; + int _i, _nextCount[3], _prevCount[3]; + for (_i = 0; _i < 3; _i++) { + if (node->tail[_i]->next[_i]) { + printf("tail is not tail\n"); + printf( + "node->tail[%d]->next[%d]=%p\n", _i, _i, node->tail[_i]->next[_i]); + } + if (node->head[_i]->prev[_i]) { + printf("head is not head\n"); + printf( + "node->head[%d]->prev[%d]=%p\n", _i, _i, node->head[_i]->prev[_i]); + } + } - for (_i=0;_i<3;_i++) { - for (_nextCount[_i]=0,_nextTest=node->head[_i];_nextTest&&_nextTest->next[_i];_nextTest=_nextTest->next[_i],_nextCount[_i]++); - for (_prevCount[_i]=0,_prevTest=node->tail[_i];_prevTest&&_prevTest->prev[_i];_prevTest=_prevTest->prev[_i],_prevCount[_i]++); - if (_nextTest!=node->tail[_i]) { - printf ("next-list of axis %d does not end at tail\n",_i); - } - if (_prevTest!=node->head[_i]) { - printf ("prev-list of axis %d does not end at head\n",_i); - } - for (;_nextTest&&_nextTest->prev[_i];_nextTest=_nextTest->prev[_i]); - for (;_prevTest&&_prevTest->next[_i];_prevTest=_prevTest->next[_i]); - if (_nextTest!=node->head[_i]) { - printf ("next-list of axis %d does not loop back to head\n",_i); - } - if (_prevTest!=node->tail[_i]) { - printf ("prev-list of axis %d does not loop back to tail\n",_i); - } - } - for (_i=1;_i<3;_i++) { - if (_prevCount[_i]!=_prevCount[_i-1] || - _nextCount[_i]!=_nextCount[_i-1] || - _prevCount[_i]!=_nextCount[_i]) { - printf ("{%d %d %d} {%d %d %d}\n", + for (_i = 0; _i < 3; _i++) { + for (_nextCount[_i] = 0, _nextTest = node->head[_i]; + _nextTest && _nextTest->next[_i]; + _nextTest = _nextTest->next[_i], _nextCount[_i]++) + ; + for (_prevCount[_i] = 0, _prevTest = node->tail[_i]; + _prevTest && _prevTest->prev[_i]; + _prevTest = _prevTest->prev[_i], _prevCount[_i]++) + ; + if (_nextTest != node->tail[_i]) { + printf("next-list of axis %d does not end at tail\n", _i); + } + if (_prevTest != node->head[_i]) { + printf("prev-list of axis %d does not end at head\n", _i); + } + for (; _nextTest && _nextTest->prev[_i]; _nextTest = _nextTest->prev[_i]) + ; + for (; _prevTest && _prevTest->next[_i]; _prevTest = _prevTest->next[_i]) + ; + if (_nextTest != node->head[_i]) { + printf("next-list of axis %d does not loop back to head\n", _i); + } + if (_prevTest != node->tail[_i]) { + printf("prev-list of axis %d does not loop back to tail\n", _i); + } + } + for (_i = 1; _i < 3; _i++) { + if (_prevCount[_i] != _prevCount[_i - 1] || + _nextCount[_i] != _nextCount[_i - 1] || + _prevCount[_i] != _nextCount[_i]) { + printf( + "{%d %d %d} {%d %d %d}\n", _prevCount[0], _prevCount[1], _prevCount[2], _nextCount[0], _nextCount[1], _nextCount[2]); - } - } + } + } } #endif - node->axis=axis; - if (!splitlists(node->head, - node->tail, - heads, - tails, - newCounts, - axis, - node->pixelCount)) { + node->axis = axis; + if (!splitlists( + node->head, node->tail, heads, tails, newCounts, axis, node->pixelCount)) { #ifndef NO_OUTPUT - printf ("list split failed.\n"); + printf("list split failed.\n"); #endif - return 0; - } + return 0; + } #ifdef TEST_SPLIT - if (!test_sorted(heads[0])) { - printf ("bug in split"); - exit(1); - } - if (!test_sorted(heads[1])) { - printf ("bug in split"); - exit(1); - } + if (!test_sorted(heads[0])) { + printf("bug in split"); + exit(1); + } + if (!test_sorted(heads[1])) { + printf("bug in split"); + exit(1); + } #endif - /* malloc check ok, small constant allocation */ - left=malloc(sizeof(BoxNode)); - right=malloc(sizeof(BoxNode)); - if (!left||!right) { - free(left); - free(right); - return 0; - } - for(i=0;i<3;i++) { - left->head[i]=heads[0][i]; - left->tail[i]=tails[0][i]; - right->head[i]=heads[1][i]; - right->tail[i]=tails[1][i]; - node->head[i]=NULL; - node->tail[i]=NULL; - } + /* malloc check ok, small constant allocation */ + left = malloc(sizeof(BoxNode)); + right = malloc(sizeof(BoxNode)); + if (!left || !right) { + free(left); + free(right); + return 0; + } + for (i = 0; i < 3; i++) { + left->head[i] = heads[0][i]; + left->tail[i] = tails[0][i]; + right->head[i] = heads[1][i]; + right->tail[i] = tails[1][i]; + node->head[i] = NULL; + node->tail[i] = NULL; + } #ifdef TEST_SPLIT - if (left->head[0]) { - rh=left->head[0]->p.c.r; - rl=left->tail[0]->p.c.r; - gh=left->head[1]->p.c.g; - gl=left->tail[1]->p.c.g; - bh=left->head[2]->p.c.b; - bl=left->tail[2]->p.c.b; - printf (" left node [%3d %3d %3d] [%3d %3d %3d]\n",rl,gl,bl,rh,gh,bh); - } - if (right->head[0]) { - rh=right->head[0]->p.c.r; - rl=right->tail[0]->p.c.r; - gh=right->head[1]->p.c.g; - gl=right->tail[1]->p.c.g; - bh=right->head[2]->p.c.b; - bl=right->tail[2]->p.c.b; - printf (" right node [%3d %3d %3d] [%3d %3d %3d]\n",rl,gl,bl,rh,gh,bh); - } + if (left->head[0]) { + rh = left->head[0]->p.c.r; + rl = left->tail[0]->p.c.r; + gh = left->head[1]->p.c.g; + gl = left->tail[1]->p.c.g; + bh = left->head[2]->p.c.b; + bl = left->tail[2]->p.c.b; + printf(" left node [%3d %3d %3d] [%3d %3d %3d]\n", rl, gl, bl, rh, gh, bh); + } + if (right->head[0]) { + rh = right->head[0]->p.c.r; + rl = right->tail[0]->p.c.r; + gh = right->head[1]->p.c.g; + gl = right->tail[1]->p.c.g; + bh = right->head[2]->p.c.b; + bl = right->tail[2]->p.c.b; + printf(" right node [%3d %3d %3d] [%3d %3d %3d]\n", rl, gl, bl, rh, gh, bh); + } #endif - left->l=left->r=NULL; - right->l=right->r=NULL; - left->axis=right->axis=-1; - left->volume=right->volume=-1; - left->pixelCount=newCounts[0]; - right->pixelCount=newCounts[1]; - node->l=left; - node->r=right; - return 1; + left->l = left->r = NULL; + right->l = right->r = NULL; + left->axis = right->axis = -1; + left->volume = right->volume = -1; + left->pixelCount = newCounts[0]; + right->pixelCount = newCounts[1]; + node->l = left; + node->r = right; + return 1; } static BoxNode * -median_cut(PixelList *hl[3], - uint32_t imPixelCount, - int nPixels) -{ - PixelList *tl[3]; - int i; - BoxNode *root; - Heap* h; - BoxNode *thisNode; +median_cut(PixelList *hl[3], uint32_t imPixelCount, int nPixels) { + PixelList *tl[3]; + int i; + BoxNode *root; + Heap *h; + BoxNode *thisNode; - h=ImagingQuantHeapNew(box_heap_cmp); - /* malloc check ok, small constant allocation */ - root=malloc(sizeof(BoxNode)); - if (!root) { ImagingQuantHeapFree(h); return NULL; } - for(i=0;i<3;i++) { - for (tl[i]=hl[i];tl[i]&&tl[i]->next[i];tl[i]=tl[i]->next[i]); - root->head[i]=hl[i]; - root->tail[i]=tl[i]; - } - root->l=root->r=NULL; - root->axis=-1; - root->volume=-1; - root->pixelCount=imPixelCount; + h = ImagingQuantHeapNew(box_heap_cmp); + /* malloc check ok, small constant allocation */ + root = malloc(sizeof(BoxNode)); + if (!root) { + ImagingQuantHeapFree(h); + return NULL; + } + for (i = 0; i < 3; i++) { + for (tl[i] = hl[i]; tl[i] && tl[i]->next[i]; tl[i] = tl[i]->next[i]) + ; + root->head[i] = hl[i]; + root->tail[i] = tl[i]; + } + root->l = root->r = NULL; + root->axis = -1; + root->volume = -1; + root->pixelCount = imPixelCount; - ImagingQuantHeapAdd(h,(void *)root); - while (--nPixels) { - do { - if (!ImagingQuantHeapRemove(h,(void **)&thisNode)) { - goto done; - } - } while (compute_box_volume(thisNode)==1); - if (!split(thisNode)) { + ImagingQuantHeapAdd(h, (void *)root); + while (--nPixels) { + do { + if (!ImagingQuantHeapRemove(h, (void **)&thisNode)) { + goto done; + } + } while (compute_box_volume(thisNode) == 1); + if (!split(thisNode)) { #ifndef NO_OUTPUT - printf ("Oops, split failed...\n"); + printf("Oops, split failed...\n"); #endif - exit (1); - } - ImagingQuantHeapAdd(h,(void *)(thisNode->l)); - ImagingQuantHeapAdd(h,(void *)(thisNode->r)); - } + exit(1); + } + ImagingQuantHeapAdd(h, (void *)(thisNode->l)); + ImagingQuantHeapAdd(h, (void *)(thisNode->r)); + } done: - ImagingQuantHeapFree(h); - return root; + ImagingQuantHeapFree(h); + return root; } static void -free_box_tree(BoxNode *n) -{ - PixelList *p,*pp; - if (n->l) { - free_box_tree(n->l); - } - if (n->r) { - free_box_tree(n->r); - } - for (p=n->head[0];p;p=pp) { - pp=p->next[0]; - free(p); - } - free(n); +free_box_tree(BoxNode *n) { + PixelList *p, *pp; + if (n->l) { + free_box_tree(n->l); + } + if (n->r) { + free_box_tree(n->r); + } + for (p = n->head[0]; p; p = pp) { + pp = p->next[0]; + free(p); + } + free(n); } #ifdef TEST_SPLIT_INTEGRITY static int -checkContained(BoxNode *n,Pixel *pp) -{ - if (n->l&&n->r) { - return checkContained(n->l,pp)+checkContained(n->r,pp); - } - if (n->l||n->r) { +checkContained(BoxNode *n, Pixel *pp) { + if (n->l && n->r) { + return checkContained(n->l, pp) + checkContained(n->r, pp); + } + if (n->l || n->r) { #ifndef NO_OUTPUT - printf ("box tree is dead\n"); + printf("box tree is dead\n"); #endif - return 0; - } - if ( - pp->c.r<=n->head[0]->p.c.r && - pp->c.r>=n->tail[0]->p.c.r && - pp->c.g<=n->head[1]->p.c.g && - pp->c.g>=n->tail[1]->p.c.g && - pp->c.b<=n->head[2]->p.c.b && - pp->c.b>=n->tail[2]->p.c.b) { - return 1; - } - return 0; + return 0; + } + if (pp->c.r <= n->head[0]->p.c.r && pp->c.r >= n->tail[0]->p.c.r && + pp->c.g <= n->head[1]->p.c.g && pp->c.g >= n->tail[1]->p.c.g && + pp->c.b <= n->head[2]->p.c.b && pp->c.b >= n->tail[2]->p.c.b) { + return 1; + } + return 0; } #endif static int -annotate_hash_table(BoxNode *n,HashTable *h,uint32_t *box) -{ - PixelList *p; - PixelHashData *d=(PixelHashData *)hashtable_get_user_data(h); - Pixel q; - if (n->l&&n->r) { - return annotate_hash_table(n->l,h,box) && annotate_hash_table(n->r,h,box); - } - if (n->l||n->r) { +annotate_hash_table(BoxNode *n, HashTable *h, uint32_t *box) { + PixelList *p; + PixelHashData *d = (PixelHashData *)hashtable_get_user_data(h); + Pixel q; + if (n->l && n->r) { + return annotate_hash_table(n->l, h, box) && annotate_hash_table(n->r, h, box); + } + if (n->l || n->r) { #ifndef NO_OUTPUT - printf ("box tree is dead\n"); + printf("box tree is dead\n"); #endif - return 0; - } - for (p=n->head[0];p;p=p->next[0]) { - PIXEL_UNSCALE(&(p->p),&q,d->scale); - if (!hashtable_insert(h,q,*box)) { + return 0; + } + for (p = n->head[0]; p; p = p->next[0]) { + PIXEL_UNSCALE(&(p->p), &q, d->scale); + if (!hashtable_insert(h, q, *box)) { #ifndef NO_OUTPUT - printf ("hashtable insert failed\n"); + printf("hashtable insert failed\n"); #endif - return 0; - } - } - if (n->head[0]) { - (*box)++; - } - return 1; + return 0; + } + } + if (n->head[0]) { + (*box)++; + } + return 1; } static int -_sort_ulong_ptr_keys(const void *a, const void *b) -{ - uint32_t A=**(uint32_t **)a; - uint32_t B=**(uint32_t **)b; - return (A==B)?0:((A*(skRow[k]));k--) { - skRow[k]=skRow[k-1]; - } - if (k!=j) { - skRow[k]=skElt; - } - } - } - return 1; + for (i = 0; i < nEntries; i++) { + avgDist[i * nEntries + i] = 0; + for (j = 0; j < i; j++) { + avgDist[j * nEntries + i] = avgDist[i * nEntries + j] = + _DISTSQR(p + i, p + j); + } + } + for (i = 0; i < nEntries; i++) { + skRow = avgDistSortKey + i * nEntries; + for (j = 1; j < nEntries; j++) { + skElt = skRow[j]; + for (k = j; k && (*(skRow[k - 1]) > *(skRow[k])); k--) { + skRow[k] = skRow[k - 1]; + } + if (k != j) { + skRow[k] = skElt; + } + } + } + return 1; } static int -build_distance_tables(uint32_t *avgDist, - uint32_t **avgDistSortKey, - Pixel *p, - uint32_t nEntries) -{ - uint32_t i,j; +build_distance_tables( + uint32_t *avgDist, uint32_t **avgDistSortKey, Pixel *p, uint32_t nEntries) { + uint32_t i, j; - for (i=0;i1) { - printf ("pixel in two boxes\n"); - for(i=0;i<3;i++) { - free (avg[i]); - } - free(count); - return 0; - } + if (!(i % 100)) { + printf("%05d\r", i); + fflush(stdout); + } + if (checkContained(root, pixelData + i) > 1) { + printf("pixel in two boxes\n"); + for (i = 0; i < 3; i++) { + free(avg[i]); + } + free(count); + return 0; + } #endif - if (!hashtable_lookup(medianBoxHash,pixelData[i],&paletteEntry)) { + if (!hashtable_lookup(medianBoxHash, pixelData[i], &paletteEntry)) { #ifndef NO_OUTPUT - printf ("pixel lookup failed\n"); + printf("pixel lookup failed\n"); #endif - for(i=0;i<3;i++) { - free (avg[i]); - } - free(count); - return 0; - } - if (paletteEntry>=nPaletteEntries) { + for (i = 0; i < 3; i++) { + free(avg[i]); + } + free(count); + return 0; + } + if (paletteEntry >= nPaletteEntries) { #ifndef NO_OUTPUT - printf ("panic - paletteEntry>=nPaletteEntries (%d>=%d)\n",(int)paletteEntry,(int)nPaletteEntries); + printf( + "panic - paletteEntry>=nPaletteEntries (%d>=%d)\n", + (int)paletteEntry, + (int)nPaletteEntries); #endif - for(i=0;i<3;i++) { - free (avg[i]); - } - free(count); - return 0; - } - avg[0][paletteEntry]+=pixelData[i].c.r; - avg[1][paletteEntry]+=pixelData[i].c.g; - avg[2][paletteEntry]+=pixelData[i].c.b; - count[paletteEntry]++; - } - /* malloc check ok, using calloc */ - p=calloc(nPaletteEntries, sizeof(Pixel)); - if (!p) { - for(i=0;i<3;i++) { - free (avg[i]); - } - free(count); - return 0; - } - for (i=0;i=nPaletteEntries) { + memset(count, 0, sizeof(uint32_t) * nPaletteEntries); + for (i = 0; i < 3; i++) { + memset(avg[i], 0, sizeof(uint32_t) * nPaletteEntries); + } + for (i = 0; i < nPixels; i++) { + if (qp[i] >= nPaletteEntries) { #ifndef NO_OUTPUT - printf ("scream\n"); + printf("scream\n"); #endif - return 0; - } - avg[0][qp[i]]+=pixelData[i].c.r; - avg[1][qp[i]]+=pixelData[i].c.g; - avg[2][qp[i]]+=pixelData[i].c.b; - count[qp[i]]++; - } - for (i=0;i UINT32_MAX / (sizeof(uint32_t))) { - return 0; - } - /* malloc check ok, using calloc */ - if (!(count=calloc(nPaletteEntries, sizeof(uint32_t)))) { - return 0; - } - for(i=0;i<3;i++) { - avg[i]=NULL; - } - for(i=0;i<3;i++) { - /* malloc check ok, using calloc */ - if (!(avg[i]=calloc(nPaletteEntries, sizeof(uint32_t)))) { - goto error_1; - } - } + if (nPaletteEntries > UINT32_MAX / (sizeof(uint32_t))) { + return 0; + } + /* malloc check ok, using calloc */ + if (!(count = calloc(nPaletteEntries, sizeof(uint32_t)))) { + return 0; + } + for (i = 0; i < 3; i++) { + avg[i] = NULL; + } + for (i = 0; i < 3; i++) { + /* malloc check ok, using calloc */ + if (!(avg[i] = calloc(nPaletteEntries, sizeof(uint32_t)))) { + goto error_1; + } + } - /* this is enough of a check, since the multiplication n*size is done above */ - if (nPaletteEntries > UINT32_MAX / nPaletteEntries) { - goto error_1; - } - /* malloc check ok, using calloc, checking n*n above */ - avgDist=calloc(nPaletteEntries*nPaletteEntries, sizeof(uint32_t)); - if (!avgDist) { goto error_1; } + /* this is enough of a check, since the multiplication n*size is done above */ + if (nPaletteEntries > UINT32_MAX / nPaletteEntries) { + goto error_1; + } + /* malloc check ok, using calloc, checking n*n above */ + avgDist = calloc(nPaletteEntries * nPaletteEntries, sizeof(uint32_t)); + if (!avgDist) { + goto error_1; + } - /* malloc check ok, using calloc, checking n*n above */ - avgDistSortKey=calloc(nPaletteEntries*nPaletteEntries, sizeof(uint32_t *)); - if (!avgDistSortKey) { goto error_2; } + /* malloc check ok, using calloc, checking n*n above */ + avgDistSortKey = calloc(nPaletteEntries * nPaletteEntries, sizeof(uint32_t *)); + if (!avgDistSortKey) { + goto error_2; + } #ifndef NO_OUTPUT - printf("[");fflush(stdout); + printf("["); + fflush(stdout); #endif - while (1) { - if (!built) { - compute_palette_from_quantized_pixels(pixelData,nPixels,paletteData,nPaletteEntries,avg,count,qp); - build_distance_tables(avgDist,avgDistSortKey,paletteData,nPaletteEntries); - built=1; - } else { - recompute_palette_from_averages(paletteData,nPaletteEntries,avg,count); - resort_distance_tables(avgDist,avgDistSortKey,paletteData,nPaletteEntries); - } - changes=map_image_pixels_from_quantized_pixels(pixelData, - nPixels, - paletteData, - nPaletteEntries, - avgDist, - avgDistSortKey, - qp, - avg, - count); - if (changes<0) { - goto error_3; - } + while (1) { + if (!built) { + compute_palette_from_quantized_pixels( + pixelData, nPixels, paletteData, nPaletteEntries, avg, count, qp); + build_distance_tables( + avgDist, avgDistSortKey, paletteData, nPaletteEntries); + built = 1; + } else { + recompute_palette_from_averages(paletteData, nPaletteEntries, avg, count); + resort_distance_tables( + avgDist, avgDistSortKey, paletteData, nPaletteEntries); + } + changes = map_image_pixels_from_quantized_pixels( + pixelData, + nPixels, + paletteData, + nPaletteEntries, + avgDist, + avgDistSortKey, + qp, + avg, + count); + if (changes < 0) { + goto error_3; + } #ifndef NO_OUTPUT - printf (".(%d)",changes);fflush(stdout); + printf(".(%d)", changes); + fflush(stdout); #endif - if (changes<=threshold) { - break; - } - } + if (changes <= threshold) { + break; + } + } #ifndef NO_OUTPUT - printf("]\n"); + printf("]\n"); #endif - if (avgDistSortKey) { - free(avgDistSortKey); - } - if (avgDist) { - free(avgDist); - } - for(i=0;i<3;i++) { - if (avg[i]) { - free (avg[i]); - } - } - if (count) { - free(count); - } - return 1; + if (avgDistSortKey) { + free(avgDistSortKey); + } + if (avgDist) { + free(avgDist); + } + for (i = 0; i < 3; i++) { + if (avg[i]) { + free(avg[i]); + } + } + if (count) { + free(count); + } + return 1; error_3: - if (avgDistSortKey) { - free(avgDistSortKey); - } + if (avgDistSortKey) { + free(avgDistSortKey); + } error_2: - if (avgDist) { - free(avgDist); - } + if (avgDist) { + free(avgDist); + } error_1: - for(i=0;i<3;i++) { - if (avg[i]) { - free (avg[i]); - } - } - if (count) { - free(count); - } - return 0; + for (i = 0; i < 3; i++) { + if (avg[i]) { + free(avg[i]); + } + } + if (count) { + free(count); + } + return 0; } int -quantize(Pixel *pixelData, - uint32_t nPixels, - uint32_t nQuantPixels, - Pixel **palette, - uint32_t *paletteLength, - uint32_t **quantizedPixels, - int kmeans) -{ - PixelList *hl[3]; - HashTable *h; - BoxNode *root; - uint32_t i; - uint32_t *qp; - uint32_t nPaletteEntries; +quantize( + Pixel *pixelData, + uint32_t nPixels, + uint32_t nQuantPixels, + Pixel **palette, + uint32_t *paletteLength, + uint32_t **quantizedPixels, + int kmeans) { + PixelList *hl[3]; + HashTable *h; + BoxNode *root; + uint32_t i; + uint32_t *qp; + uint32_t nPaletteEntries; - uint32_t *avgDist; - uint32_t **avgDistSortKey; - Pixel *p; + uint32_t *avgDist; + uint32_t **avgDistSortKey; + Pixel *p; #ifndef NO_OUTPUT - uint32_t timer,timer2; + uint32_t timer, timer2; #endif #ifndef NO_OUTPUT - timer2=clock(); - printf ("create hash table..."); fflush(stdout); timer=clock(); + timer2 = clock(); + printf("create hash table..."); + fflush(stdout); + timer = clock(); #endif - h=create_pixel_hash(pixelData,nPixels); + h = create_pixel_hash(pixelData, nPixels); #ifndef NO_OUTPUT - printf ("done (%f)\n",(clock()-timer)/(double)CLOCKS_PER_SEC); + printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC); #endif - if (!h) { - goto error_0; - } + if (!h) { + goto error_0; + } #ifndef NO_OUTPUT - printf ("create lists from hash table..."); fflush(stdout); timer=clock(); + printf("create lists from hash table..."); + fflush(stdout); + timer = clock(); #endif - hl[0]=hl[1]=hl[2]=NULL; - hashtable_foreach(h,hash_to_list,hl); + hl[0] = hl[1] = hl[2] = NULL; + hashtable_foreach(h, hash_to_list, hl); #ifndef NO_OUTPUT - printf ("done (%f)\n",(clock()-timer)/(double)CLOCKS_PER_SEC); + printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC); #endif - if (!hl[0]) { - goto error_1; - } + if (!hl[0]) { + goto error_1; + } #ifndef NO_OUTPUT - printf ("mergesort lists..."); fflush(stdout); timer=clock(); + printf("mergesort lists..."); + fflush(stdout); + timer = clock(); #endif - for(i=0;i<3;i++) { - hl[i]=mergesort_pixels(hl[i],i); - } + for (i = 0; i < 3; i++) { + hl[i] = mergesort_pixels(hl[i], i); + } #ifdef TEST_MERGESORT - if (!test_sorted(hl)) { - printf ("bug in mergesort\n"); - goto error_1; - } + if (!test_sorted(hl)) { + printf("bug in mergesort\n"); + goto error_1; + } #endif #ifndef NO_OUTPUT - printf ("done (%f)\n",(clock()-timer)/(double)CLOCKS_PER_SEC); + printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC); #endif #ifndef NO_OUTPUT - printf ("median cut..."); fflush(stdout); timer=clock(); + printf("median cut..."); + fflush(stdout); + timer = clock(); #endif - root=median_cut(hl,nPixels,nQuantPixels); + root = median_cut(hl, nPixels, nQuantPixels); #ifndef NO_OUTPUT - printf ("done (%f)\n",(clock()-timer)/(double)CLOCKS_PER_SEC); + printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC); #endif - if (!root) { - goto error_1; - } - nPaletteEntries=0; + if (!root) { + goto error_1; + } + nPaletteEntries = 0; #ifndef NO_OUTPUT - printf ("median cut tree to hash table..."); fflush(stdout); timer=clock(); + printf("median cut tree to hash table..."); + fflush(stdout); + timer = clock(); #endif - annotate_hash_table(root,h,&nPaletteEntries); + annotate_hash_table(root, h, &nPaletteEntries); #ifndef NO_OUTPUT - printf ("done (%f)\n",(clock()-timer)/(double)CLOCKS_PER_SEC); + printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC); #endif #ifndef NO_OUTPUT - printf ("compute palette...\n"); fflush(stdout); timer=clock(); + printf("compute palette...\n"); + fflush(stdout); + timer = clock(); #endif - if (!compute_palette_from_median_cut(pixelData,nPixels,h,&p,nPaletteEntries)) { - goto error_3; - } + if (!compute_palette_from_median_cut(pixelData, nPixels, h, &p, nPaletteEntries)) { + goto error_3; + } #ifndef NO_OUTPUT - printf ("done (%f)\n",(clock()-timer)/(double)CLOCKS_PER_SEC); + printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC); #endif - free_box_tree(root); - root=NULL; + free_box_tree(root); + root = NULL; - /* malloc check ok, using calloc for overflow */ - qp=calloc(nPixels, sizeof(uint32_t)); - if (!qp) { goto error_4; } + /* malloc check ok, using calloc for overflow */ + qp = calloc(nPixels, sizeof(uint32_t)); + if (!qp) { + goto error_4; + } - if (nPaletteEntries > UINT32_MAX / nPaletteEntries ) { - goto error_5; - } - /* malloc check ok, using calloc for overflow, check of n*n above */ - avgDist=calloc(nPaletteEntries*nPaletteEntries, sizeof(uint32_t)); - if (!avgDist) { goto error_5; } + if (nPaletteEntries > UINT32_MAX / nPaletteEntries) { + goto error_5; + } + /* malloc check ok, using calloc for overflow, check of n*n above */ + avgDist = calloc(nPaletteEntries * nPaletteEntries, sizeof(uint32_t)); + if (!avgDist) { + goto error_5; + } - /* malloc check ok, using calloc for overflow, check of n*n above */ - avgDistSortKey=calloc(nPaletteEntries*nPaletteEntries, sizeof(uint32_t *)); - if (!avgDistSortKey) { goto error_6; } + /* malloc check ok, using calloc for overflow, check of n*n above */ + avgDistSortKey = calloc(nPaletteEntries * nPaletteEntries, sizeof(uint32_t *)); + if (!avgDistSortKey) { + goto error_6; + } - if (!build_distance_tables(avgDist,avgDistSortKey,p,nPaletteEntries)) { - goto error_7; - } + if (!build_distance_tables(avgDist, avgDistSortKey, p, nPaletteEntries)) { + goto error_7; + } - if (!map_image_pixels_from_median_box(pixelData,nPixels,p,nPaletteEntries,h,avgDist,avgDistSortKey,qp)) { - goto error_7; - } + if (!map_image_pixels_from_median_box( + pixelData, nPixels, p, nPaletteEntries, h, avgDist, avgDistSortKey, qp)) { + goto error_7; + } #ifdef TEST_NEAREST_NEIGHBOUR #include - { - uint32_t bestmatch,bestdist,dist; - HashTable *h2; - printf ("nearest neighbour search (full search)..."); fflush(stdout); timer=clock(); - h2=hashtable_new(unshifted_pixel_hash,unshifted_pixel_cmp); - for (i=0;inew),&pixel); - if (data->secondPixel || newDistdata->furthestDistance) { - data->furthestDistance=oldDist; - data->furthest.v=pixel.v; - } +compute_distances(const HashTable *h, const Pixel pixel, uint32_t *dist, void *u) { + DistanceData *data = (DistanceData *)u; + uint32_t oldDist = *dist; + uint32_t newDist; + newDist = _DISTSQR(&(data->new), &pixel); + if (data->secondPixel || newDist < oldDist) { + *dist = newDist; + oldDist = newDist; + } + if (oldDist > data->furthestDistance) { + data->furthestDistance = oldDist; + data->furthest.v = pixel.v; + } } int -quantize2(Pixel *pixelData, - uint32_t nPixels, - uint32_t nQuantPixels, - Pixel **palette, - uint32_t *paletteLength, - uint32_t **quantizedPixels, - int kmeans) -{ - HashTable *h; - uint32_t i; - uint32_t mean[3]; - Pixel *p; - DistanceData data; +quantize2( + Pixel *pixelData, + uint32_t nPixels, + uint32_t nQuantPixels, + Pixel **palette, + uint32_t *paletteLength, + uint32_t **quantizedPixels, + int kmeans) { + HashTable *h; + uint32_t i; + uint32_t mean[3]; + Pixel *p; + DistanceData data; - uint32_t *qp; - uint32_t *avgDist; - uint32_t **avgDistSortKey; + uint32_t *qp; + uint32_t *avgDist; + uint32_t **avgDistSortKey; - /* malloc check ok, using calloc */ - p=calloc(nQuantPixels, sizeof(Pixel)); - if (!p) { - return 0; - } - mean[0]=mean[1]=mean[2]=0; - h=hashtable_new(unshifted_pixel_hash,unshifted_pixel_cmp); - for (i=0;i UINT32_MAX / nQuantPixels ) { - goto error_2; - } + if (nQuantPixels > UINT32_MAX / nQuantPixels) { + goto error_2; + } - /* malloc check ok, using calloc for overflow, check of n*n above */ - avgDist=calloc(nQuantPixels*nQuantPixels, sizeof(uint32_t)); - if (!avgDist) { goto error_2; } + /* malloc check ok, using calloc for overflow, check of n*n above */ + avgDist = calloc(nQuantPixels * nQuantPixels, sizeof(uint32_t)); + if (!avgDist) { + goto error_2; + } - /* malloc check ok, using calloc for overflow, check of n*n above */ - avgDistSortKey=calloc(nQuantPixels*nQuantPixels, sizeof(uint32_t *)); - if (!avgDistSortKey) { goto error_3; } + /* malloc check ok, using calloc for overflow, check of n*n above */ + avgDistSortKey = calloc(nQuantPixels * nQuantPixels, sizeof(uint32_t *)); + if (!avgDistSortKey) { + goto error_3; + } - if (!build_distance_tables(avgDist,avgDistSortKey,p,nQuantPixels)) { - goto error_4; - } + if (!build_distance_tables(avgDist, avgDistSortKey, p, nQuantPixels)) { + goto error_4; + } - if (!map_image_pixels(pixelData,nPixels,p,nQuantPixels,avgDist,avgDistSortKey,qp)) { - goto error_4; - } - if (kmeans) { - k_means(pixelData,nPixels,p,nQuantPixels,qp,kmeans-1); - } + if (!map_image_pixels( + pixelData, nPixels, p, nQuantPixels, avgDist, avgDistSortKey, qp)) { + goto error_4; + } + if (kmeans) { + k_means(pixelData, nPixels, p, nQuantPixels, qp, kmeans - 1); + } - *paletteLength=nQuantPixels; - *palette=p; - *quantizedPixels=qp; - free(avgDistSortKey); - free(avgDist); - return 1; + *paletteLength = nQuantPixels; + *palette = p; + *quantizedPixels = qp; + free(avgDistSortKey); + free(avgDist); + return 1; error_4: - free(avgDistSortKey); + free(avgDistSortKey); error_3: - free(avgDist); + free(avgDist); error_2: - free(qp); + free(qp); error_1: - free(p); - return 0; + free(p); + return 0; } Imaging -ImagingQuantize(Imaging im, int colors, int mode, int kmeans) -{ +ImagingQuantize(Imaging im, int colors, int mode, int kmeans) { int i, j; int x, y, v; - UINT8* pp; - Pixel* p; - Pixel* palette; + UINT8 *pp; + Pixel *p; + Pixel *palette; uint32_t paletteLength; int result; - uint32_t* newData; + uint32_t *newData; Imaging imOut; int withAlpha = 0; ImagingSectionCookie cookie; @@ -1605,17 +1630,17 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans) if (colors < 1 || colors > 256) { /* FIXME: for colors > 256, consider returning an RGB image instead (see @PIL205) */ - return (Imaging) ImagingError_ValueError("bad number of colors"); + return (Imaging)ImagingError_ValueError("bad number of colors"); } if (strcmp(im->mode, "L") != 0 && strcmp(im->mode, "P") != 0 && - strcmp(im->mode, "RGB") != 0 && strcmp(im->mode, "RGBA") !=0) { + strcmp(im->mode, "RGB") != 0 && strcmp(im->mode, "RGBA") != 0) { return ImagingError_ModeError(); } /* only octree and imagequant supports RGBA */ if (!strcmp(im->mode, "RGBA") && mode != 2 && mode != 3) { - return ImagingError_ModeError(); + return ImagingError_ModeError(); } if (im->xsize > INT_MAX / im->ysize) { @@ -1653,10 +1678,10 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans) for (i = y = 0; y < im->ysize; y++) { for (x = 0; x < im->xsize; x++, i++) { v = im->image8[y][x]; - p[i].c.r = pp[v*4+0]; - p[i].c.g = pp[v*4+1]; - p[i].c.b = pp[v*4+2]; - p[i].c.a = pp[v*4+3]; + p[i].c.r = pp[v * 4 + 0]; + p[i].c.g = pp[v * 4 + 1]; + p[i].c.b = pp[v * 4 + 2]; + p[i].c.a = pp[v * 4 + 3]; } } @@ -1671,72 +1696,68 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans) } else { free(p); - return (Imaging) ImagingError_ValueError("internal error"); + return (Imaging)ImagingError_ValueError("internal error"); } ImagingSectionEnter(&cookie); switch (mode) { - case 0: - /* median cut */ - result = quantize( - p, - im->xsize*im->ysize, - colors, - &palette, - &paletteLength, - &newData, - kmeans - ); - break; - case 1: - /* maximum coverage */ - result = quantize2( - p, - im->xsize*im->ysize, - colors, - &palette, - &paletteLength, - &newData, - kmeans - ); - break; - case 2: - if (!strcmp(im->mode, "RGBA")) { - withAlpha = 1; - } - result = quantize_octree( - p, - im->xsize*im->ysize, - colors, - &palette, - &paletteLength, - &newData, - withAlpha - ); - break; - case 3: + case 0: + /* median cut */ + result = quantize( + p, + im->xsize * im->ysize, + colors, + &palette, + &paletteLength, + &newData, + kmeans); + break; + case 1: + /* maximum coverage */ + result = quantize2( + p, + im->xsize * im->ysize, + colors, + &palette, + &paletteLength, + &newData, + kmeans); + break; + case 2: + if (!strcmp(im->mode, "RGBA")) { + withAlpha = 1; + } + result = quantize_octree( + p, + im->xsize * im->ysize, + colors, + &palette, + &paletteLength, + &newData, + withAlpha); + break; + case 3: #ifdef HAVE_LIBIMAGEQUANT - if (!strcmp(im->mode, "RGBA")) { - withAlpha = 1; - } - result = quantize_pngquant( - p, - im->xsize, - im->ysize, - colors, - &palette, - &paletteLength, - &newData, - withAlpha - ); + if (!strcmp(im->mode, "RGBA")) { + withAlpha = 1; + } + result = quantize_pngquant( + p, + im->xsize, + im->ysize, + colors, + &palette, + &paletteLength, + &newData, + withAlpha); #else - result = -1; + result = -1; #endif - break; - default: - result = 0; - break; + break; + default: + result = 0; + break; } free(p); @@ -1748,7 +1769,7 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans) for (i = y = 0; y < im->ysize; y++) { for (x = 0; x < im->xsize; x++) { - imOut->image8[y][x] = (unsigned char) newData[i++]; + imOut->image8[y][x] = (unsigned char)newData[i++]; } } @@ -1756,14 +1777,14 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans) pp = imOut->palette->palette; - for (i = j = 0; i < (int) paletteLength; i++) { + for (i = j = 0; i < (int)paletteLength; i++) { *pp++ = palette[i].c.r; *pp++ = palette[i].c.g; *pp++ = palette[i].c.b; if (withAlpha) { - *pp++ = palette[i].c.a; + *pp++ = palette[i].c.a; } else { - *pp++ = 255; + *pp++ = 255; } } for (; i < 256; i++) { @@ -1783,14 +1804,12 @@ ImagingQuantize(Imaging im, int colors, int mode, int kmeans) return imOut; } else { - if (result == -1) { - return (Imaging) ImagingError_ValueError( + return (Imaging)ImagingError_ValueError( "dependency required by this method was not " "enabled at compile time"); } - return (Imaging) ImagingError_ValueError("quantization error"); - + return (Imaging)ImagingError_ValueError("quantization error"); } } diff --git a/src/libImaging/QuantHash.c b/src/libImaging/QuantHash.c index 6ff95d885..ea75d6037 100644 --- a/src/libImaging/QuantHash.c +++ b/src/libImaging/QuantHash.c @@ -24,290 +24,313 @@ #include "QuantHash.h" typedef struct _HashNode { - struct _HashNode *next; - HashKey_t key; - HashVal_t value; + struct _HashNode *next; + HashKey_t key; + HashVal_t value; } HashNode; struct _HashTable { - HashNode **table; - uint32_t length; - uint32_t count; - HashFunc hashFunc; - HashCmpFunc cmpFunc; - void *userData; + HashNode **table; + uint32_t length; + uint32_t count; + HashFunc hashFunc; + HashCmpFunc cmpFunc; + void *userData; }; #define MIN_LENGTH 11 #define RESIZE_FACTOR 3 -static int _hashtable_insert_node(HashTable *,HashNode *,int,int,CollisionFunc); +static int +_hashtable_insert_node(HashTable *, HashNode *, int, int, CollisionFunc); -HashTable *hashtable_new(HashFunc hf,HashCmpFunc cf) { - HashTable *h; - h=malloc(sizeof(HashTable)); - if (!h) { return NULL; } - h->hashFunc=hf; - h->cmpFunc=cf; - h->length=MIN_LENGTH; - h->count=0; - h->userData=NULL; - h->table=malloc(sizeof(HashNode *)*h->length); - if (!h->table) { free(h); return NULL; } - memset (h->table,0,sizeof(HashNode *)*h->length); - return h; +HashTable * +hashtable_new(HashFunc hf, HashCmpFunc cf) { + HashTable *h; + h = malloc(sizeof(HashTable)); + if (!h) { + return NULL; + } + h->hashFunc = hf; + h->cmpFunc = cf; + h->length = MIN_LENGTH; + h->count = 0; + h->userData = NULL; + h->table = malloc(sizeof(HashNode *) * h->length); + if (!h->table) { + free(h); + return NULL; + } + memset(h->table, 0, sizeof(HashNode *) * h->length); + return h; } -static uint32_t _findPrime(uint32_t start,int dir) { - static int unit[]={0,1,0,1,0,0,0,1,0,1,0,1,0,1,0,0}; - uint32_t t; - while (start>1) { - if (!unit[start&0x0f]) { - start+=dir; - continue; - } - for (t=2;t=sqrt((double)start)) { - break; - } - start+=dir; - } - return start; +static uint32_t +_findPrime(uint32_t start, int dir) { + static int unit[] = {0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0}; + uint32_t t; + while (start > 1) { + if (!unit[start & 0x0f]) { + start += dir; + continue; + } + for (t = 2; t < sqrt((double)start); t++) { + if (!start % t) { + break; + } + } + if (t >= sqrt((double)start)) { + break; + } + start += dir; + } + return start; } -static void _hashtable_rehash(HashTable *h,CollisionFunc cf,uint32_t newSize) { - HashNode **oldTable=h->table; - uint32_t i; - HashNode *n,*nn; - uint32_t oldSize; - oldSize=h->length; - h->table=malloc(sizeof(HashNode *)*newSize); - if (!h->table) { - h->table=oldTable; - return; - } - h->length=newSize; - h->count=0; - memset (h->table,0,sizeof(HashNode *)*h->length); - for (i=0;inext; - _hashtable_insert_node(h,n,0,0,cf); - } - } - free(oldTable); +static void +_hashtable_rehash(HashTable *h, CollisionFunc cf, uint32_t newSize) { + HashNode **oldTable = h->table; + uint32_t i; + HashNode *n, *nn; + uint32_t oldSize; + oldSize = h->length; + h->table = malloc(sizeof(HashNode *) * newSize); + if (!h->table) { + h->table = oldTable; + return; + } + h->length = newSize; + h->count = 0; + memset(h->table, 0, sizeof(HashNode *) * h->length); + for (i = 0; i < oldSize; i++) { + for (n = oldTable[i]; n; n = nn) { + nn = n->next; + _hashtable_insert_node(h, n, 0, 0, cf); + } + } + free(oldTable); } -static void _hashtable_resize(HashTable *h) { - uint32_t newSize; - uint32_t oldSize; - oldSize=h->length; - newSize=oldSize; - if (h->count*RESIZE_FACTORlength) { - newSize=_findPrime(h->length/2-1,-1); - } else if (h->length*RESIZE_FACTORcount) { - newSize=_findPrime(h->length*2+1,+1); - } - if (newSizelength; + newSize = oldSize; + if (h->count * RESIZE_FACTOR < h->length) { + newSize = _findPrime(h->length / 2 - 1, -1); + } else if (h->length * RESIZE_FACTOR < h->count) { + newSize = _findPrime(h->length * 2 + 1, +1); + } + if (newSize < MIN_LENGTH) { + newSize = oldSize; + } + if (newSize != oldSize) { + _hashtable_rehash(h, NULL, newSize); + } } -static int _hashtable_insert_node(HashTable *h,HashNode *node,int resize,int update,CollisionFunc cf) { - uint32_t hash=h->hashFunc(h,node->key)%h->length; - HashNode **n,*nv; - int i; +static int +_hashtable_insert_node( + HashTable *h, HashNode *node, int resize, int update, CollisionFunc cf) { + uint32_t hash = h->hashFunc(h, node->key) % h->length; + HashNode **n, *nv; + int i; - for (n=&(h->table[hash]);*n;n=&((*n)->next)) { - nv=*n; - i=h->cmpFunc(h,nv->key,node->key); - if (!i) { - if (cf) { - nv->key=node->key; - cf(h,&(nv->key),&(nv->value),node->key,node->value); - free(node); + for (n = &(h->table[hash]); *n; n = &((*n)->next)) { + nv = *n; + i = h->cmpFunc(h, nv->key, node->key); + if (!i) { + if (cf) { + nv->key = node->key; + cf(h, &(nv->key), &(nv->value), node->key, node->value); + free(node); + return 1; + } else { + nv->key = node->key; + nv->value = node->value; + free(node); + return 1; + } + } else if (i > 0) { + break; + } + } + if (!update) { + node->next = *n; + *n = node; + h->count++; + if (resize) { + _hashtable_resize(h); + } + return 1; + } else { + return 0; + } +} + +static int +_hashtable_insert(HashTable *h, HashKey_t key, HashVal_t val, int resize, int update) { + HashNode **n, *nv; + HashNode *t; + int i; + uint32_t hash = h->hashFunc(h, key) % h->length; + + for (n = &(h->table[hash]); *n; n = &((*n)->next)) { + nv = *n; + i = h->cmpFunc(h, nv->key, key); + if (!i) { + nv->value = val; return 1; - } else { - nv->key=node->key; - nv->value=node->value; - free(node); - return 1; - } - } else if (i>0) { - break; - } - } - if (!update) { - node->next=*n; - *n=node; - h->count++; - if (resize) { - _hashtable_resize(h); - } - return 1; - } else { - return 0; - } -} - -static int _hashtable_insert(HashTable *h,HashKey_t key,HashVal_t val,int resize,int update) { - HashNode **n,*nv; - HashNode *t; - int i; - uint32_t hash=h->hashFunc(h,key)%h->length; - - for (n=&(h->table[hash]);*n;n=&((*n)->next)) { - nv=*n; - i=h->cmpFunc(h,nv->key,key); - if (!i) { - nv->value=val; - return 1; - } else if (i>0) { - break; - } - } - if (!update) { - t=malloc(sizeof(HashNode)); - if (!t) { - return 0; - } - t->next=*n; - *n=t; - t->key=key; - t->value=val; - h->count++; - if (resize) { - _hashtable_resize(h); - } - return 1; - } else { - return 0; - } -} - -int hashtable_insert_or_update_computed(HashTable *h, - HashKey_t key, - ComputeFunc newFunc, - ComputeFunc existsFunc) { - HashNode **n,*nv; - HashNode *t; - int i; - uint32_t hash=h->hashFunc(h,key)%h->length; - - for (n=&(h->table[hash]);*n;n=&((*n)->next)) { - nv=*n; - i=h->cmpFunc(h,nv->key,key); - if (!i) { - if (existsFunc) { - existsFunc(h,nv->key,&(nv->value)); - } else { + } else if (i > 0) { + break; + } + } + if (!update) { + t = malloc(sizeof(HashNode)); + if (!t) { return 0; - } - return 1; - } else if (i>0) { - break; - } - } - t=malloc(sizeof(HashNode)); - if (!t) { - return 0; - } - t->key=key; - t->next=*n; - *n=t; - if (newFunc) { - newFunc(h,t->key,&(t->value)); - } else { - free(t); - return 0; - } - h->count++; - _hashtable_resize(h); - return 1; + } + t->next = *n; + *n = t; + t->key = key; + t->value = val; + h->count++; + if (resize) { + _hashtable_resize(h); + } + return 1; + } else { + return 0; + } } -int hashtable_insert(HashTable *h,HashKey_t key,HashVal_t val) { - return _hashtable_insert(h,key,val,1,0); +int +hashtable_insert_or_update_computed( + HashTable *h, HashKey_t key, ComputeFunc newFunc, ComputeFunc existsFunc) { + HashNode **n, *nv; + HashNode *t; + int i; + uint32_t hash = h->hashFunc(h, key) % h->length; + + for (n = &(h->table[hash]); *n; n = &((*n)->next)) { + nv = *n; + i = h->cmpFunc(h, nv->key, key); + if (!i) { + if (existsFunc) { + existsFunc(h, nv->key, &(nv->value)); + } else { + return 0; + } + return 1; + } else if (i > 0) { + break; + } + } + t = malloc(sizeof(HashNode)); + if (!t) { + return 0; + } + t->key = key; + t->next = *n; + *n = t; + if (newFunc) { + newFunc(h, t->key, &(t->value)); + } else { + free(t); + return 0; + } + h->count++; + _hashtable_resize(h); + return 1; } -void hashtable_foreach_update(HashTable *h,IteratorUpdateFunc i,void *u) { - HashNode *n; - uint32_t x; - - if (h->table) { - for (x=0;xlength;x++) { - for (n=h->table[x];n;n=n->next) { - i(h,n->key,&(n->value),u); - } - } - } +int +hashtable_insert(HashTable *h, HashKey_t key, HashVal_t val) { + return _hashtable_insert(h, key, val, 1, 0); } -void hashtable_foreach(HashTable *h,IteratorFunc i,void *u) { - HashNode *n; - uint32_t x; +void +hashtable_foreach_update(HashTable *h, IteratorUpdateFunc i, void *u) { + HashNode *n; + uint32_t x; - if (h->table) { - for (x=0;xlength;x++) { - for (n=h->table[x];n;n=n->next) { - i(h,n->key,n->value,u); - } - } - } + if (h->table) { + for (x = 0; x < h->length; x++) { + for (n = h->table[x]; n; n = n->next) { + i(h, n->key, &(n->value), u); + } + } + } } -void hashtable_free(HashTable *h) { - HashNode *n,*nn; - uint32_t i; +void +hashtable_foreach(HashTable *h, IteratorFunc i, void *u) { + HashNode *n; + uint32_t x; - if (h->table) { - for (i=0;ilength;i++) { - for (n=h->table[i];n;n=nn) { - nn=n->next; - free(n); - } - } - free(h->table); - } - free(h); + if (h->table) { + for (x = 0; x < h->length; x++) { + for (n = h->table[x]; n; n = n->next) { + i(h, n->key, n->value, u); + } + } + } } -void hashtable_rehash_compute(HashTable *h,CollisionFunc cf) { - _hashtable_rehash(h,cf,h->length); +void +hashtable_free(HashTable *h) { + HashNode *n, *nn; + uint32_t i; + + if (h->table) { + for (i = 0; i < h->length; i++) { + for (n = h->table[i]; n; n = nn) { + nn = n->next; + free(n); + } + } + free(h->table); + } + free(h); } -int hashtable_lookup(const HashTable *h,const HashKey_t key,HashVal_t *valp) { - uint32_t hash=h->hashFunc(h,key)%h->length; - HashNode *n; - int i; - - for (n=h->table[hash];n;n=n->next) { - i=h->cmpFunc(h,n->key,key); - if (!i) { - *valp=n->value; - return 1; - } else if (i>0) { - break; - } - } - return 0; +void +hashtable_rehash_compute(HashTable *h, CollisionFunc cf) { + _hashtable_rehash(h, cf, h->length); } -uint32_t hashtable_get_count(const HashTable *h) { - return h->count; +int +hashtable_lookup(const HashTable *h, const HashKey_t key, HashVal_t *valp) { + uint32_t hash = h->hashFunc(h, key) % h->length; + HashNode *n; + int i; + + for (n = h->table[hash]; n; n = n->next) { + i = h->cmpFunc(h, n->key, key); + if (!i) { + *valp = n->value; + return 1; + } else if (i > 0) { + break; + } + } + return 0; } -void *hashtable_get_user_data(const HashTable *h) { - return h->userData; +uint32_t +hashtable_get_count(const HashTable *h) { + return h->count; } -void *hashtable_set_user_data(HashTable *h,void *data) { - void *r=h->userData; - h->userData=data; - return r; +void * +hashtable_get_user_data(const HashTable *h) { + return h->userData; +} + +void * +hashtable_set_user_data(HashTable *h, void *data) { + void *r = h->userData; + h->userData = data; + return r; } diff --git a/src/libImaging/QuantHash.h b/src/libImaging/QuantHash.h index 9874114e5..fc1a99003 100644 --- a/src/libImaging/QuantHash.h +++ b/src/libImaging/QuantHash.h @@ -18,23 +18,38 @@ typedef struct _HashTable HashTable; typedef Pixel HashKey_t; typedef uint32_t HashVal_t; -typedef uint32_t (*HashFunc)(const HashTable *,const HashKey_t); -typedef int (*HashCmpFunc)(const HashTable *,const HashKey_t,const HashKey_t); -typedef void (*IteratorFunc)(const HashTable *,const HashKey_t,const HashVal_t,void *); -typedef void (*IteratorUpdateFunc)(const HashTable *,const HashKey_t,HashVal_t *,void *); -typedef void (*ComputeFunc)(const HashTable *,const HashKey_t,HashVal_t *); -typedef void (*CollisionFunc)(const HashTable *,HashKey_t *,HashVal_t *,HashKey_t,HashVal_t); +typedef uint32_t (*HashFunc)(const HashTable *, const HashKey_t); +typedef int (*HashCmpFunc)(const HashTable *, const HashKey_t, const HashKey_t); +typedef void (*IteratorFunc)( + const HashTable *, const HashKey_t, const HashVal_t, void *); +typedef void (*IteratorUpdateFunc)( + const HashTable *, const HashKey_t, HashVal_t *, void *); +typedef void (*ComputeFunc)(const HashTable *, const HashKey_t, HashVal_t *); +typedef void (*CollisionFunc)( + const HashTable *, HashKey_t *, HashVal_t *, HashKey_t, HashVal_t); -HashTable * hashtable_new(HashFunc hf,HashCmpFunc cf); -void hashtable_free(HashTable *h); -void hashtable_foreach(HashTable *h,IteratorFunc i,void *u); -void hashtable_foreach_update(HashTable *h,IteratorUpdateFunc i,void *u); -int hashtable_insert(HashTable *h,HashKey_t key,HashVal_t val); -int hashtable_lookup(const HashTable *h,const HashKey_t key,HashVal_t *valp); -int hashtable_insert_or_update_computed(HashTable *h,HashKey_t key,ComputeFunc newFunc,ComputeFunc existsFunc); -void *hashtable_set_user_data(HashTable *h,void *data); -void *hashtable_get_user_data(const HashTable *h); -uint32_t hashtable_get_count(const HashTable *h); -void hashtable_rehash_compute(HashTable *h,CollisionFunc cf); +HashTable * +hashtable_new(HashFunc hf, HashCmpFunc cf); +void +hashtable_free(HashTable *h); +void +hashtable_foreach(HashTable *h, IteratorFunc i, void *u); +void +hashtable_foreach_update(HashTable *h, IteratorUpdateFunc i, void *u); +int +hashtable_insert(HashTable *h, HashKey_t key, HashVal_t val); +int +hashtable_lookup(const HashTable *h, const HashKey_t key, HashVal_t *valp); +int +hashtable_insert_or_update_computed( + HashTable *h, HashKey_t key, ComputeFunc newFunc, ComputeFunc existsFunc); +void * +hashtable_set_user_data(HashTable *h, void *data); +void * +hashtable_get_user_data(const HashTable *h); +uint32_t +hashtable_get_count(const HashTable *h); +void +hashtable_rehash_compute(HashTable *h, CollisionFunc cf); -#endif // __QUANTHASH_H__ +#endif // __QUANTHASH_H__ diff --git a/src/libImaging/QuantHeap.c b/src/libImaging/QuantHeap.c index 6877e34a3..6fb52d890 100644 --- a/src/libImaging/QuantHeap.c +++ b/src/libImaging/QuantHeap.c @@ -25,10 +25,10 @@ #include "QuantHeap.h" struct _Heap { - void **heap; - unsigned int heapsize; - unsigned int heapcount; - HeapCmpFunc cf; + void **heap; + unsigned int heapsize; + unsigned int heapcount; + HeapCmpFunc cf; }; #define INITIAL_SIZE 256 @@ -36,127 +36,141 @@ struct _Heap { // #define DEBUG #ifdef DEBUG -static int _heap_test(Heap *); +static int +_heap_test(Heap *); #endif -void ImagingQuantHeapFree(Heap *h) { - free(h->heap); - free(h); +void +ImagingQuantHeapFree(Heap *h) { + free(h->heap); + free(h); } -static int _heap_grow(Heap *h,unsigned int newsize) { - void *newheap; - if (!newsize) { - newsize=h->heapsize<<1; - } - if (newsizeheapsize) { - return 0; - } - if (newsize > INT_MAX / sizeof(void *)){ - return 0; - } - /* malloc check ok, using calloc for overflow, also checking - above due to memcpy below*/ - newheap=calloc(newsize, sizeof(void *)); - if (!newheap) { - return 0; - } - memcpy(newheap,h->heap,sizeof(void *)*h->heapsize); - free(h->heap); - h->heap=newheap; - h->heapsize=newsize; - return 1; +static int +_heap_grow(Heap *h, unsigned int newsize) { + void *newheap; + if (!newsize) { + newsize = h->heapsize << 1; + } + if (newsize < h->heapsize) { + return 0; + } + if (newsize > INT_MAX / sizeof(void *)) { + return 0; + } + /* malloc check ok, using calloc for overflow, also checking + above due to memcpy below*/ + newheap = calloc(newsize, sizeof(void *)); + if (!newheap) { + return 0; + } + memcpy(newheap, h->heap, sizeof(void *) * h->heapsize); + free(h->heap); + h->heap = newheap; + h->heapsize = newsize; + return 1; } #ifdef DEBUG -static int _heap_test(Heap *h) { - unsigned int k; - for (k=1;k*2<=h->heapcount;k++) { - if (h->cf(h,h->heap[k],h->heap[k*2])<0) { - printf ("heap is bad\n"); - return 0; - } - if (k*2+1<=h->heapcount && h->cf(h,h->heap[k],h->heap[k*2+1])<0) { - printf ("heap is bad\n"); - return 0; - } - } - return 1; +static int +_heap_test(Heap *h) { + unsigned int k; + for (k = 1; k * 2 <= h->heapcount; k++) { + if (h->cf(h, h->heap[k], h->heap[k * 2]) < 0) { + printf("heap is bad\n"); + return 0; + } + if (k * 2 + 1 <= h->heapcount && h->cf(h, h->heap[k], h->heap[k * 2 + 1]) < 0) { + printf("heap is bad\n"); + return 0; + } + } + return 1; } #endif -int ImagingQuantHeapRemove(Heap* h,void **r) { - unsigned int k,l; - void *v; +int +ImagingQuantHeapRemove(Heap *h, void **r) { + unsigned int k, l; + void *v; - if (!h->heapcount) { - return 0; - } - *r=h->heap[1]; - v=h->heap[h->heapcount--]; - for (k=1;k*2<=h->heapcount;k=l) { - l=k*2; - if (lheapcount) { - if (h->cf(h,h->heap[l],h->heap[l+1])<0) { - l++; - } - } - if (h->cf(h,v,h->heap[l])>0) { - break; - } - h->heap[k]=h->heap[l]; - } - h->heap[k]=v; + if (!h->heapcount) { + return 0; + } + *r = h->heap[1]; + v = h->heap[h->heapcount--]; + for (k = 1; k * 2 <= h->heapcount; k = l) { + l = k * 2; + if (l < h->heapcount) { + if (h->cf(h, h->heap[l], h->heap[l + 1]) < 0) { + l++; + } + } + if (h->cf(h, v, h->heap[l]) > 0) { + break; + } + h->heap[k] = h->heap[l]; + } + h->heap[k] = v; #ifdef DEBUG - if (!_heap_test(h)) { printf ("oops - heap_remove messed up the heap\n"); exit(1); } + if (!_heap_test(h)) { + printf("oops - heap_remove messed up the heap\n"); + exit(1); + } #endif - return 1; + return 1; } -int ImagingQuantHeapAdd(Heap *h,void *val) { - int k; - if (h->heapcount==h->heapsize-1) { - _heap_grow(h,0); - } - k=++h->heapcount; - while (k!=1) { - if (h->cf(h,val,h->heap[k/2])<=0) { - break; - } - h->heap[k]=h->heap[k/2]; - k>>=1; - } - h->heap[k]=val; +int +ImagingQuantHeapAdd(Heap *h, void *val) { + int k; + if (h->heapcount == h->heapsize - 1) { + _heap_grow(h, 0); + } + k = ++h->heapcount; + while (k != 1) { + if (h->cf(h, val, h->heap[k / 2]) <= 0) { + break; + } + h->heap[k] = h->heap[k / 2]; + k >>= 1; + } + h->heap[k] = val; #ifdef DEBUG - if (!_heap_test(h)) { printf ("oops - heap_add messed up the heap\n"); exit(1); } + if (!_heap_test(h)) { + printf("oops - heap_add messed up the heap\n"); + exit(1); + } #endif - return 1; + return 1; } -int ImagingQuantHeapTop(Heap *h,void **r) { - if (!h->heapcount) { - return 0; - } - *r=h->heap[1]; - return 1; +int +ImagingQuantHeapTop(Heap *h, void **r) { + if (!h->heapcount) { + return 0; + } + *r = h->heap[1]; + return 1; } -Heap *ImagingQuantHeapNew(HeapCmpFunc cf) { - Heap *h; +Heap * +ImagingQuantHeapNew(HeapCmpFunc cf) { + Heap *h; - /* malloc check ok, small constant allocation */ - h=malloc(sizeof(Heap)); - if (!h) { - return NULL; - } - h->heapsize=INITIAL_SIZE; - /* malloc check ok, using calloc for overflow */ - h->heap=calloc(h->heapsize, sizeof(void *)); - if (!h->heap) { - free(h); - return NULL; - } - h->heapcount=0; - h->cf=cf; - return h; + /* malloc check ok, small constant allocation */ + h = malloc(sizeof(Heap)); + if (!h) { + return NULL; + } + h->heapsize = INITIAL_SIZE; + /* malloc check ok, using calloc for overflow */ + h->heap = calloc(h->heapsize, sizeof(void *)); + if (!h->heap) { + free(h); + return NULL; + } + h->heapcount = 0; + h->cf = cf; + return h; } diff --git a/src/libImaging/QuantHeap.h b/src/libImaging/QuantHeap.h index 77bf0d9d5..c5286dff2 100644 --- a/src/libImaging/QuantHeap.h +++ b/src/libImaging/QuantHeap.h @@ -16,12 +16,16 @@ typedef struct _Heap Heap; -typedef int (*HeapCmpFunc)(const Heap *,const void *,const void *); +typedef int (*HeapCmpFunc)(const Heap *, const void *, const void *); -void ImagingQuantHeapFree(Heap *); -int ImagingQuantHeapRemove(Heap *,void **); -int ImagingQuantHeapAdd(Heap *,void *); -int ImagingQuantHeapTop(Heap *,void **); +void +ImagingQuantHeapFree(Heap *); +int +ImagingQuantHeapRemove(Heap *, void **); +int +ImagingQuantHeapAdd(Heap *, void *); +int +ImagingQuantHeapTop(Heap *, void **); Heap *ImagingQuantHeapNew(HeapCmpFunc); -#endif // __QUANTHEAP_H__ +#endif // __QUANTHEAP_H__ diff --git a/src/libImaging/QuantOctree.c b/src/libImaging/QuantOctree.c index e1205acc3..b8d4d1d7c 100644 --- a/src/libImaging/QuantOctree.c +++ b/src/libImaging/QuantOctree.c @@ -31,490 +31,508 @@ #include "ImagingUtils.h" #include "QuantOctree.h" -typedef struct _ColorBucket{ - /* contains palette index when used for look up cube */ - uint32_t count; - uint64_t r; - uint64_t g; - uint64_t b; - uint64_t a; -} *ColorBucket; +typedef struct _ColorBucket { + /* contains palette index when used for look up cube */ + uint32_t count; + uint64_t r; + uint64_t g; + uint64_t b; + uint64_t a; +} * ColorBucket; -typedef struct _ColorCube{ - unsigned int rBits, gBits, bBits, aBits; - unsigned int rWidth, gWidth, bWidth, aWidth; - unsigned int rOffset, gOffset, bOffset, aOffset; +typedef struct _ColorCube { + unsigned int rBits, gBits, bBits, aBits; + unsigned int rWidth, gWidth, bWidth, aWidth; + unsigned int rOffset, gOffset, bOffset, aOffset; - unsigned long size; - ColorBucket buckets; -} *ColorCube; + unsigned long size; + ColorBucket buckets; +} * ColorCube; -#define MAX(a, b) (a)>(b) ? (a) : (b) +#define MAX(a, b) (a) > (b) ? (a) : (b) static ColorCube new_color_cube(int r, int g, int b, int a) { - ColorCube cube; + ColorCube cube; - /* malloc check ok, small constant allocation */ - cube = malloc(sizeof(struct _ColorCube)); - if (!cube) { - return NULL; + /* malloc check ok, small constant allocation */ + cube = malloc(sizeof(struct _ColorCube)); + if (!cube) { + return NULL; } - cube->rBits = MAX(r, 0); - cube->gBits = MAX(g, 0); - cube->bBits = MAX(b, 0); - cube->aBits = MAX(a, 0); + cube->rBits = MAX(r, 0); + cube->gBits = MAX(g, 0); + cube->bBits = MAX(b, 0); + cube->aBits = MAX(a, 0); - /* overflow check for size multiplication below */ - if (cube->rBits + cube->gBits + cube->bBits + cube->aBits > 31) { - free(cube); - return NULL; - } + /* overflow check for size multiplication below */ + if (cube->rBits + cube->gBits + cube->bBits + cube->aBits > 31) { + free(cube); + return NULL; + } - /* the width of the cube for each dimension */ - cube->rWidth = 1<rBits; - cube->gWidth = 1<gBits; - cube->bWidth = 1<bBits; - cube->aWidth = 1<aBits; + /* the width of the cube for each dimension */ + cube->rWidth = 1 << cube->rBits; + cube->gWidth = 1 << cube->gBits; + cube->bWidth = 1 << cube->bBits; + cube->aWidth = 1 << cube->aBits; - /* the offsets of each color */ + /* the offsets of each color */ - cube->rOffset = cube->gBits + cube->bBits + cube->aBits; - cube->gOffset = cube->bBits + cube->aBits; - cube->bOffset = cube->aBits; - cube->aOffset = 0; + cube->rOffset = cube->gBits + cube->bBits + cube->aBits; + cube->gOffset = cube->bBits + cube->aBits; + cube->bOffset = cube->aBits; + cube->aOffset = 0; - /* the number of color buckets */ - cube->size = cube->rWidth * cube->gWidth * cube->bWidth * cube->aWidth; - /* malloc check ok, overflow checked above */ - cube->buckets = calloc(cube->size, sizeof(struct _ColorBucket)); + /* the number of color buckets */ + cube->size = cube->rWidth * cube->gWidth * cube->bWidth * cube->aWidth; + /* malloc check ok, overflow checked above */ + cube->buckets = calloc(cube->size, sizeof(struct _ColorBucket)); - if (!cube->buckets) { - free(cube); - return NULL; - } - return cube; + if (!cube->buckets) { + free(cube); + return NULL; + } + return cube; } static void free_color_cube(ColorCube cube) { - if (cube != NULL) { - free(cube->buckets); - free(cube); - } + if (cube != NULL) { + free(cube->buckets); + free(cube); + } } static long -color_bucket_offset_pos(const ColorCube cube, - unsigned int r, unsigned int g, unsigned int b, unsigned int a) -{ - return r<rOffset | g<gOffset | b<bOffset | a<aOffset; +color_bucket_offset_pos( + const ColorCube cube, + unsigned int r, + unsigned int g, + unsigned int b, + unsigned int a) { + return r << cube->rOffset | g << cube->gOffset | b << cube->bOffset | + a << cube->aOffset; } static long color_bucket_offset(const ColorCube cube, const Pixel *p) { - unsigned int r = p->c.r>>(8-cube->rBits); - unsigned int g = p->c.g>>(8-cube->gBits); - unsigned int b = p->c.b>>(8-cube->bBits); - unsigned int a = p->c.a>>(8-cube->aBits); - return color_bucket_offset_pos(cube, r, g, b, a); + unsigned int r = p->c.r >> (8 - cube->rBits); + unsigned int g = p->c.g >> (8 - cube->gBits); + unsigned int b = p->c.b >> (8 - cube->bBits); + unsigned int a = p->c.a >> (8 - cube->aBits); + return color_bucket_offset_pos(cube, r, g, b, a); } static ColorBucket color_bucket_from_cube(const ColorCube cube, const Pixel *p) { - unsigned int offset = color_bucket_offset(cube, p); - return &cube->buckets[offset]; + unsigned int offset = color_bucket_offset(cube, p); + return &cube->buckets[offset]; } static void add_color_to_color_cube(const ColorCube cube, const Pixel *p) { - ColorBucket bucket = color_bucket_from_cube(cube, p); - bucket->count += 1; - bucket->r += p->c.r; - bucket->g += p->c.g; - bucket->b += p->c.b; - bucket->a += p->c.a; + ColorBucket bucket = color_bucket_from_cube(cube, p); + bucket->count += 1; + bucket->r += p->c.r; + bucket->g += p->c.g; + bucket->b += p->c.b; + bucket->a += p->c.a; } static unsigned long count_used_color_buckets(const ColorCube cube) { - unsigned long usedBuckets = 0; - unsigned long i; - for (i=0; i < cube->size; i++) { - if (cube->buckets[i].count > 0) { - usedBuckets += 1; - } - } - return usedBuckets; + unsigned long usedBuckets = 0; + unsigned long i; + for (i = 0; i < cube->size; i++) { + if (cube->buckets[i].count > 0) { + usedBuckets += 1; + } + } + return usedBuckets; } static void avg_color_from_color_bucket(const ColorBucket bucket, Pixel *dst) { - float count = bucket->count; - if (count != 0) { - dst->c.r = CLIP8((int)(bucket->r / count)); - dst->c.g = CLIP8((int)(bucket->g / count)); - dst->c.b = CLIP8((int)(bucket->b / count)); - dst->c.a = CLIP8((int)(bucket->a / count)); - } else { - dst->c.r = 0; - dst->c.g = 0; - dst->c.b = 0; - dst->c.a = 0; - } + float count = bucket->count; + if (count != 0) { + dst->c.r = CLIP8((int)(bucket->r / count)); + dst->c.g = CLIP8((int)(bucket->g / count)); + dst->c.b = CLIP8((int)(bucket->b / count)); + dst->c.a = CLIP8((int)(bucket->a / count)); + } else { + dst->c.r = 0; + dst->c.g = 0; + dst->c.b = 0; + dst->c.a = 0; + } } static int compare_bucket_count(const ColorBucket a, const ColorBucket b) { - return b->count - a->count; + return b->count - a->count; } static ColorBucket create_sorted_color_palette(const ColorCube cube) { - ColorBucket buckets; - if (cube->size > LONG_MAX / sizeof(struct _ColorBucket)) { - return NULL; - } - /* malloc check ok, calloc + overflow check above for memcpy */ - buckets = calloc(cube->size, sizeof(struct _ColorBucket)); - if (!buckets) { - return NULL; - } - memcpy(buckets, cube->buckets, sizeof(struct _ColorBucket)*cube->size); + ColorBucket buckets; + if (cube->size > LONG_MAX / sizeof(struct _ColorBucket)) { + return NULL; + } + /* malloc check ok, calloc + overflow check above for memcpy */ + buckets = calloc(cube->size, sizeof(struct _ColorBucket)); + if (!buckets) { + return NULL; + } + memcpy(buckets, cube->buckets, sizeof(struct _ColorBucket) * cube->size); - qsort(buckets, cube->size, sizeof(struct _ColorBucket), - (int (*)(void const *, void const *))&compare_bucket_count); + qsort( + buckets, + cube->size, + sizeof(struct _ColorBucket), + (int (*)(void const *, void const *)) & compare_bucket_count); - return buckets; + return buckets; } -void add_bucket_values(ColorBucket src, ColorBucket dst) { - dst->count += src->count; - dst->r += src->r; - dst->g += src->g; - dst->b += src->b; - dst->a += src->a; +void +add_bucket_values(ColorBucket src, ColorBucket dst) { + dst->count += src->count; + dst->r += src->r; + dst->g += src->g; + dst->b += src->b; + dst->a += src->a; } /* expand or shrink a given cube to level */ -static ColorCube copy_color_cube(const ColorCube cube, - unsigned int rBits, unsigned int gBits, unsigned int bBits, unsigned int aBits) -{ - unsigned int r, g, b, a; - long src_pos, dst_pos; - unsigned int src_reduce[4] = {0}, dst_reduce[4] = {0}; - unsigned int width[4]; - ColorCube result; +static ColorCube +copy_color_cube( + const ColorCube cube, + unsigned int rBits, + unsigned int gBits, + unsigned int bBits, + unsigned int aBits) { + unsigned int r, g, b, a; + long src_pos, dst_pos; + unsigned int src_reduce[4] = {0}, dst_reduce[4] = {0}; + unsigned int width[4]; + ColorCube result; - result = new_color_cube(rBits, gBits, bBits, aBits); - if (!result) { - return NULL; - } + result = new_color_cube(rBits, gBits, bBits, aBits); + if (!result) { + return NULL; + } - if (cube->rBits > rBits) { - dst_reduce[0] = cube->rBits - result->rBits; - width[0] = cube->rWidth; - } else { - src_reduce[0] = result->rBits - cube->rBits; - width[0] = result->rWidth; - } - if (cube->gBits > gBits) { - dst_reduce[1] = cube->gBits - result->gBits; - width[1] = cube->gWidth; - } else { - src_reduce[1] = result->gBits - cube->gBits; - width[1] = result->gWidth; - } - if (cube->bBits > bBits) { - dst_reduce[2] = cube->bBits - result->bBits; - width[2] = cube->bWidth; - } else { - src_reduce[2] = result->bBits - cube->bBits; - width[2] = result->bWidth; - } - if (cube->aBits > aBits) { - dst_reduce[3] = cube->aBits - result->aBits; - width[3] = cube->aWidth; - } else { - src_reduce[3] = result->aBits - cube->aBits; - width[3] = result->aWidth; - } + if (cube->rBits > rBits) { + dst_reduce[0] = cube->rBits - result->rBits; + width[0] = cube->rWidth; + } else { + src_reduce[0] = result->rBits - cube->rBits; + width[0] = result->rWidth; + } + if (cube->gBits > gBits) { + dst_reduce[1] = cube->gBits - result->gBits; + width[1] = cube->gWidth; + } else { + src_reduce[1] = result->gBits - cube->gBits; + width[1] = result->gWidth; + } + if (cube->bBits > bBits) { + dst_reduce[2] = cube->bBits - result->bBits; + width[2] = cube->bWidth; + } else { + src_reduce[2] = result->bBits - cube->bBits; + width[2] = result->bWidth; + } + if (cube->aBits > aBits) { + dst_reduce[3] = cube->aBits - result->aBits; + width[3] = cube->aWidth; + } else { + src_reduce[3] = result->aBits - cube->aBits; + width[3] = result->aWidth; + } - for (r=0; r>src_reduce[0], - g>>src_reduce[1], - b>>src_reduce[2], - a>>src_reduce[3]); - dst_pos = color_bucket_offset_pos(result, - r>>dst_reduce[0], - g>>dst_reduce[1], - b>>dst_reduce[2], - a>>dst_reduce[3]); - add_bucket_values( - &cube->buckets[src_pos], - &result->buckets[dst_pos] - ); + for (r = 0; r < width[0]; r++) { + for (g = 0; g < width[1]; g++) { + for (b = 0; b < width[2]; b++) { + for (a = 0; a < width[3]; a++) { + src_pos = color_bucket_offset_pos( + cube, + r >> src_reduce[0], + g >> src_reduce[1], + b >> src_reduce[2], + a >> src_reduce[3]); + dst_pos = color_bucket_offset_pos( + result, + r >> dst_reduce[0], + g >> dst_reduce[1], + b >> dst_reduce[2], + a >> dst_reduce[3]); + add_bucket_values( + &cube->buckets[src_pos], &result->buckets[dst_pos]); + } } - } - } - } - return result; + } + } + return result; } void subtract_color_buckets(ColorCube cube, ColorBucket buckets, long nBuckets) { - ColorBucket minuend, subtrahend; - long i; - Pixel p; - for (i=0; icount == 0) { - continue; - } + // If the subtrahend contains no buckets, there is nothing to subtract. + if (subtrahend->count == 0) { + continue; + } - avg_color_from_color_bucket(subtrahend, &p); - minuend = color_bucket_from_cube(cube, &p); - minuend->count -= subtrahend->count; - minuend->r -= subtrahend->r; - minuend->g -= subtrahend->g; - minuend->b -= subtrahend->b; - minuend->a -= subtrahend->a; - } + avg_color_from_color_bucket(subtrahend, &p); + minuend = color_bucket_from_cube(cube, &p); + minuend->count -= subtrahend->count; + minuend->r -= subtrahend->r; + minuend->g -= subtrahend->g; + minuend->b -= subtrahend->b; + minuend->a -= subtrahend->a; + } } static void set_lookup_value(const ColorCube cube, const Pixel *p, long value) { - ColorBucket bucket = color_bucket_from_cube(cube, p); - bucket->count = value; + ColorBucket bucket = color_bucket_from_cube(cube, p); + bucket->count = value; } uint64_t lookup_color(const ColorCube cube, const Pixel *p) { - ColorBucket bucket = color_bucket_from_cube(cube, p); - return bucket->count; + ColorBucket bucket = color_bucket_from_cube(cube, p); + return bucket->count; } -void add_lookup_buckets(ColorCube cube, ColorBucket palette, long nColors, long offset) { - long i; - Pixel p; - for (i=offset; i LONG_MAX - nBucketsB || - (nBucketsA+nBucketsB) > LONG_MAX / sizeof(struct _ColorBucket)) { - return NULL; - } - /* malloc check ok, overflow check above */ - result = calloc(nBucketsA + nBucketsB, sizeof(struct _ColorBucket)); - if (!result) { - return NULL; - } - memcpy(result, bucketsA, sizeof(struct _ColorBucket) * nBucketsA); - memcpy(&result[nBucketsA], bucketsB, sizeof(struct _ColorBucket) * nBucketsB); - return result; +combined_palette( + ColorBucket bucketsA, + unsigned long nBucketsA, + ColorBucket bucketsB, + unsigned long nBucketsB) { + ColorBucket result; + if (nBucketsA > LONG_MAX - nBucketsB || + (nBucketsA + nBucketsB) > LONG_MAX / sizeof(struct _ColorBucket)) { + return NULL; + } + /* malloc check ok, overflow check above */ + result = calloc(nBucketsA + nBucketsB, sizeof(struct _ColorBucket)); + if (!result) { + return NULL; + } + memcpy(result, bucketsA, sizeof(struct _ColorBucket) * nBucketsA); + memcpy(&result[nBucketsA], bucketsB, sizeof(struct _ColorBucket) * nBucketsB); + return result; } static Pixel * create_palette_array(const ColorBucket palette, unsigned int paletteLength) { - Pixel *paletteArray; - unsigned int i; + Pixel *paletteArray; + unsigned int i; - /* malloc check ok, calloc for overflow */ - paletteArray = calloc(paletteLength, sizeof(Pixel)); - if (!paletteArray) { - return NULL; - } + /* malloc check ok, calloc for overflow */ + paletteArray = calloc(paletteLength, sizeof(Pixel)); + if (!paletteArray) { + return NULL; + } - for (i=0; i 64). + /* + Create two color cubes, one fine grained with 8x16x8=1024 + colors buckets and a coarse with 4x4x4=64 color buckets. + The coarse one guarantees that there are color buckets available for + the whole color range (assuming nQuantPixels > 64). - For a quantization to 256 colors all 64 coarse colors will be used - plus the 192 most used color buckets from the fine color cube. - The average of all colors within one bucket is used as the actual - color for that bucket. + For a quantization to 256 colors all 64 coarse colors will be used + plus the 192 most used color buckets from the fine color cube. + The average of all colors within one bucket is used as the actual + color for that bucket. - For images with alpha the cubes gets a forth dimension, - 8x16x8x8 and 4x4x4x4. - */ + For images with alpha the cubes gets a forth dimension, + 8x16x8x8 and 4x4x4x4. + */ - /* create fine cube */ - fineCube = new_color_cube(cubeBits[0], cubeBits[1], - cubeBits[2], cubeBits[3]); - if (!fineCube) { - goto error; - } - for (i=0; i nQuantPixels) { - nCoarseColors = nQuantPixels; - } + /* limit to nQuantPixels */ + if (nCoarseColors > nQuantPixels) { + nCoarseColors = nQuantPixels; + } - /* how many space do we have in our palette for fine colors? */ - nFineColors = nQuantPixels - nCoarseColors; + /* how many space do we have in our palette for fine colors? */ + nFineColors = nQuantPixels - nCoarseColors; - /* create fine color palette */ - paletteBucketsFine = create_sorted_color_palette(fineCube); - if (!paletteBucketsFine) { - goto error; - } + /* create fine color palette */ + paletteBucketsFine = create_sorted_color_palette(fineCube); + if (!paletteBucketsFine) { + goto error; + } - /* remove the used fine colors from the coarse cube */ - subtract_color_buckets(coarseCube, paletteBucketsFine, nFineColors); + /* remove the used fine colors from the coarse cube */ + subtract_color_buckets(coarseCube, paletteBucketsFine, nFineColors); - /* did the subtraction cleared one or more coarse bucket? */ - while (nCoarseColors > count_used_color_buckets(coarseCube)) { - /* then we can use the free buckets for fine colors */ - nAlreadySubtracted = nFineColors; - nCoarseColors = count_used_color_buckets(coarseCube); - nFineColors = nQuantPixels - nCoarseColors; - subtract_color_buckets(coarseCube, &paletteBucketsFine[nAlreadySubtracted], - nFineColors-nAlreadySubtracted); - } + /* did the subtraction cleared one or more coarse bucket? */ + while (nCoarseColors > count_used_color_buckets(coarseCube)) { + /* then we can use the free buckets for fine colors */ + nAlreadySubtracted = nFineColors; + nCoarseColors = count_used_color_buckets(coarseCube); + nFineColors = nQuantPixels - nCoarseColors; + subtract_color_buckets( + coarseCube, + &paletteBucketsFine[nAlreadySubtracted], + nFineColors - nAlreadySubtracted); + } - /* create our palette buckets with fine and coarse combined */ - paletteBucketsCoarse = create_sorted_color_palette(coarseCube); - if (!paletteBucketsCoarse) { - goto error; - } - paletteBuckets = combined_palette(paletteBucketsCoarse, nCoarseColors, - paletteBucketsFine, nFineColors); + /* create our palette buckets with fine and coarse combined */ + paletteBucketsCoarse = create_sorted_color_palette(coarseCube); + if (!paletteBucketsCoarse) { + goto error; + } + paletteBuckets = combined_palette( + paletteBucketsCoarse, nCoarseColors, paletteBucketsFine, nFineColors); - free(paletteBucketsFine); - paletteBucketsFine = NULL; - free(paletteBucketsCoarse); - paletteBucketsCoarse = NULL; - if (!paletteBuckets) { - goto error; - } + free(paletteBucketsFine); + paletteBucketsFine = NULL; + free(paletteBucketsCoarse); + paletteBucketsCoarse = NULL; + if (!paletteBuckets) { + goto error; + } - /* add all coarse colors to our coarse lookup cube. */ - coarseLookupCube = new_color_cube(cubeBits[4], cubeBits[5], - cubeBits[6], cubeBits[7]); - if (!coarseLookupCube) { - goto error; - } - add_lookup_buckets(coarseLookupCube, paletteBuckets, nCoarseColors, 0); + /* add all coarse colors to our coarse lookup cube. */ + coarseLookupCube = + new_color_cube(cubeBits[4], cubeBits[5], cubeBits[6], cubeBits[7]); + if (!coarseLookupCube) { + goto error; + } + add_lookup_buckets(coarseLookupCube, paletteBuckets, nCoarseColors, 0); - /* expand coarse cube (64) to larger fine cube (4k). the value of each - coarse bucket is then present in the according 64 fine buckets. */ - lookupCube = copy_color_cube(coarseLookupCube, cubeBits[0], cubeBits[1], - cubeBits[2], cubeBits[3]); - if (!lookupCube) { - goto error; - } + /* expand coarse cube (64) to larger fine cube (4k). the value of each + coarse bucket is then present in the according 64 fine buckets. */ + lookupCube = copy_color_cube( + coarseLookupCube, cubeBits[0], cubeBits[1], cubeBits[2], cubeBits[3]); + if (!lookupCube) { + goto error; + } - /* add fine colors to the lookup cube */ - add_lookup_buckets(lookupCube, paletteBuckets, nFineColors, nCoarseColors); + /* add fine colors to the lookup cube */ + add_lookup_buckets(lookupCube, paletteBuckets, nFineColors, nCoarseColors); - /* create result pixels and map palette indices */ - /* malloc check ok, calloc for overflow */ - qp = calloc(nPixels, sizeof(Pixel)); - if (!qp) { - goto error; - } - map_image_pixels(pixelData, nPixels, lookupCube, qp); + /* create result pixels and map palette indices */ + /* malloc check ok, calloc for overflow */ + qp = calloc(nPixels, sizeof(Pixel)); + if (!qp) { + goto error; + } + map_image_pixels(pixelData, nPixels, lookupCube, qp); - /* convert palette buckets to RGB pixel palette */ - *palette = create_palette_array(paletteBuckets, nQuantPixels); - if (!(*palette)) { - goto error; - } + /* convert palette buckets to RGB pixel palette */ + *palette = create_palette_array(paletteBuckets, nQuantPixels); + if (!(*palette)) { + goto error; + } - *quantizedPixels = qp; - *paletteLength = nQuantPixels; + *quantizedPixels = qp; + *paletteLength = nQuantPixels; - free_color_cube(coarseCube); - free_color_cube(fineCube); - free_color_cube(lookupCube); - free_color_cube(coarseLookupCube); - free(paletteBuckets); - return 1; + free_color_cube(coarseCube); + free_color_cube(fineCube); + free_color_cube(lookupCube); + free_color_cube(coarseLookupCube); + free(paletteBuckets); + return 1; error: - /* everything is initialized to NULL - so we are safe to call free */ - free(qp); - free_color_cube(lookupCube); - free_color_cube(coarseLookupCube); - free(paletteBuckets); - free(paletteBucketsCoarse); - free(paletteBucketsFine); - free_color_cube(coarseCube); - free_color_cube(fineCube); - return 0; + /* everything is initialized to NULL + so we are safe to call free */ + free(qp); + free_color_cube(lookupCube); + free_color_cube(coarseLookupCube); + free(paletteBuckets); + free(paletteBucketsCoarse); + free(paletteBucketsFine); + free_color_cube(coarseCube); + free_color_cube(fineCube); + return 0; } diff --git a/src/libImaging/QuantOctree.h b/src/libImaging/QuantOctree.h index 968644eda..e1c504074 100644 --- a/src/libImaging/QuantOctree.h +++ b/src/libImaging/QuantOctree.h @@ -3,12 +3,7 @@ #include "QuantTypes.h" -int quantize_octree(Pixel *, - uint32_t, - uint32_t, - Pixel **, - uint32_t *, - uint32_t **, - int); +int +quantize_octree(Pixel *, uint32_t, uint32_t, Pixel **, uint32_t *, uint32_t **, int); #endif diff --git a/src/libImaging/QuantPngQuant.c b/src/libImaging/QuantPngQuant.c index 7a23ec8c5..7a36300e4 100644 --- a/src/libImaging/QuantPngQuant.c +++ b/src/libImaging/QuantPngQuant.c @@ -26,8 +26,7 @@ quantize_pngquant( Pixel **palette, uint32_t *paletteLength, uint32_t **quantizedPixels, - int withAlpha) -{ + int withAlpha) { int result = 0; liq_image *image = NULL; liq_attr *attr = NULL; @@ -41,23 +40,24 @@ quantize_pngquant( /* configure pngquant */ attr = liq_attr_create(); - if (!attr) { goto err; } + if (!attr) { + goto err; + } if (quantPixels) { liq_set_max_colors(attr, quantPixels); } /* prepare input image */ - image = liq_image_create_rgba( - attr, - pixelData, - width, - height, - 0.45455 /* gamma */); - if (!image) { goto err; } + image = liq_image_create_rgba(attr, pixelData, width, height, 0.45455 /* gamma */); + if (!image) { + goto err; + } /* quantize the image */ remap = liq_quantize_image(attr, image); - if (!remap) { goto err; } + if (!remap) { + goto err; + } liq_set_output_gamma(remap, 0.45455); liq_set_dithering_level(remap, 1); @@ -65,7 +65,9 @@ quantize_pngquant( const liq_palette *l_palette = liq_get_palette(remap); *paletteLength = l_palette->count; *palette = malloc(sizeof(Pixel) * l_palette->count); - if (!*palette) { goto err; } + if (!*palette) { + goto err; + } for (i = 0; i < l_palette->count; i++) { (*palette)[i].c.b = l_palette->entries[i].b; (*palette)[i].c.g = l_palette->entries[i].g; @@ -75,9 +77,13 @@ quantize_pngquant( /* write output pixels (pngquant uses char array) */ charMatrix = malloc(width * height); - if (!charMatrix) { goto err; } - charMatrixRows = malloc(height * sizeof(unsigned char*)); - if (!charMatrixRows) { goto err; } + if (!charMatrix) { + goto err; + } + charMatrixRows = malloc(height * sizeof(unsigned char *)); + if (!charMatrixRows) { + goto err; + } for (y = 0; y < height; y++) { charMatrixRows[y] = &charMatrix[y * width]; } @@ -87,7 +93,9 @@ quantize_pngquant( /* transcribe output pixels (pillow uses uint32_t array) */ *quantizedPixels = malloc(sizeof(uint32_t) * width * height); - if (!*quantizedPixels) { goto err; } + if (!*quantizedPixels) { + goto err; + } for (i = 0; i < width * height; i++) { (*quantizedPixels)[i] = charMatrix[i]; } @@ -106,16 +114,15 @@ err: } free(charMatrix); free(charMatrixRows); - if (!result) { + if (!result) { free(*quantizedPixels); free(*palette); } return result; } -const char* -ImagingImageQuantVersion(void) -{ +const char * +ImagingImageQuantVersion(void) { static char version[20]; int number = liq_version(); sprintf(version, "%d.%d.%d", number / 10000, (number / 100) % 100, number % 100); diff --git a/src/libImaging/QuantPngQuant.h b/src/libImaging/QuantPngQuant.h index fb0b4cc03..d65e42590 100644 --- a/src/libImaging/QuantPngQuant.h +++ b/src/libImaging/QuantPngQuant.h @@ -3,7 +3,9 @@ #include "QuantTypes.h" -int quantize_pngquant(Pixel *, +int +quantize_pngquant( + Pixel *, unsigned int, unsigned int, uint32_t, diff --git a/src/libImaging/QuantTypes.h b/src/libImaging/QuantTypes.h index 411485498..986b70806 100644 --- a/src/libImaging/QuantTypes.h +++ b/src/libImaging/QuantTypes.h @@ -20,13 +20,13 @@ typedef unsigned __int64 uint64_t; #endif typedef union { - struct { - unsigned char r,g,b,a; - } c; - struct { - unsigned char v[4]; - } a; - uint32_t v; + struct { + unsigned char r, g, b, a; + } c; + struct { + unsigned char v[4]; + } a; + uint32_t v; } Pixel; #endif diff --git a/src/libImaging/RankFilter.c b/src/libImaging/RankFilter.c index 897e4d7b6..73a6baecb 100644 --- a/src/libImaging/RankFilter.c +++ b/src/libImaging/RankFilter.c @@ -17,94 +17,98 @@ /* Fast rank algorithm (due to Wirth), based on public domain code by Nicolas Devillard, available at http://ndevilla.free.fr */ -#define SWAP(type,a,b) { register type t=(a);(a)=(b);(b)=t; } +#define SWAP(type, a, b) \ + { \ + register type t = (a); \ + (a) = (b); \ + (b) = t; \ + } -#define MakeRankFunction(type)\ -static type Rank##type(type a[], int n, int k)\ -{\ - register int i, j, l, m;\ - register type x;\ - l = 0; m = n-1;\ - while (l < m) {\ - x = a[k];\ - i = l;\ - j = m;\ - do {\ - while (a[i] < x) {\ - i++;\ - }\ - while (x < a[j]) {\ - j--;\ - }\ - if (i <= j) {\ - SWAP(type, a[i], a[j]);\ - i++; j--;\ - }\ - } while (i <= j);\ - if (j < k) {\ - l = i;\ - }\ - if (k < i) {\ - m = j;\ - }\ - }\ - return a[k];\ -} +#define MakeRankFunction(type) \ + static type Rank##type(type a[], int n, int k) { \ + register int i, j, l, m; \ + register type x; \ + l = 0; \ + m = n - 1; \ + while (l < m) { \ + x = a[k]; \ + i = l; \ + j = m; \ + do { \ + while (a[i] < x) { \ + i++; \ + } \ + while (x < a[j]) { \ + j--; \ + } \ + if (i <= j) { \ + SWAP(type, a[i], a[j]); \ + i++; \ + j--; \ + } \ + } while (i <= j); \ + if (j < k) { \ + l = i; \ + } \ + if (k < i) { \ + m = j; \ + } \ + } \ + return a[k]; \ + } -MakeRankFunction(UINT8) -MakeRankFunction(INT32) -MakeRankFunction(FLOAT32) +MakeRankFunction(UINT8) MakeRankFunction(INT32) MakeRankFunction(FLOAT32) -Imaging -ImagingRankFilter(Imaging im, int size, int rank) -{ + Imaging ImagingRankFilter(Imaging im, int size, int rank) { Imaging imOut = NULL; int x, y; int i, margin, size2; if (!im || im->bands != 1 || im->type == IMAGING_TYPE_SPECIAL) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (!(size & 1)) { - return (Imaging) ImagingError_ValueError("bad filter size"); + return (Imaging)ImagingError_ValueError("bad filter size"); } /* malloc check ok, for overflow in the define below */ - if (size > INT_MAX / size || - size > INT_MAX / (size * (int)sizeof(FLOAT32))) { - return (Imaging) ImagingError_ValueError("filter size too large"); + if (size > INT_MAX / size || size > INT_MAX / (size * (int)sizeof(FLOAT32))) { + return (Imaging)ImagingError_ValueError("filter size too large"); } size2 = size * size; - margin = (size-1) / 2; + margin = (size - 1) / 2; if (rank < 0 || rank >= size2) { - return (Imaging) ImagingError_ValueError("bad rank value"); + return (Imaging)ImagingError_ValueError("bad rank value"); } - imOut = ImagingNew(im->mode, im->xsize - 2*margin, im->ysize - 2*margin); + imOut = ImagingNew(im->mode, im->xsize - 2 * margin, im->ysize - 2 * margin); if (!imOut) { return NULL; } /* malloc check ok, checked above */ -#define RANK_BODY(type) do {\ - type* buf = malloc(size2 * sizeof(type));\ - if (!buf) {\ - goto nomemory;\ - }\ - for (y = 0; y < imOut->ysize; y++) {\ - for (x = 0; x < imOut->xsize; x++) {\ - for (i = 0; i < size; i++) {\ - memcpy(buf + i*size, &IMAGING_PIXEL_##type(im, x, y+i),\ - size * sizeof(type));\ - }\ - IMAGING_PIXEL_##type(imOut, x, y) = Rank##type(buf, size2, rank);\ - }\ - }\ - free(buf); \ -} while (0) +#define RANK_BODY(type) \ + do { \ + type *buf = malloc(size2 * sizeof(type)); \ + if (!buf) { \ + goto nomemory; \ + } \ + for (y = 0; y < imOut->ysize; y++) { \ + for (x = 0; x < imOut->xsize; x++) { \ + for (i = 0; i < size; i++) { \ + memcpy( \ + buf + i * size, \ + &IMAGING_PIXEL_##type(im, x, y + i), \ + size * sizeof(type)); \ + } \ + IMAGING_PIXEL_##type(imOut, x, y) = Rank##type(buf, size2, rank); \ + } \ + } \ + free(buf); \ + } while (0) if (im->image8) { RANK_BODY(UINT8); @@ -115,7 +119,7 @@ ImagingRankFilter(Imaging im, int size, int rank) } else { /* safety net (we shouldn't end up here) */ ImagingDelete(imOut); - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } ImagingCopyPalette(imOut, im); @@ -124,5 +128,5 @@ ImagingRankFilter(Imaging im, int size, int rank) nomemory: ImagingDelete(imOut); - return (Imaging) ImagingError_MemoryError(); + return (Imaging)ImagingError_MemoryError(); } diff --git a/src/libImaging/Raw.h b/src/libImaging/Raw.h index 4d28fa546..ab718837f 100644 --- a/src/libImaging/Raw.h +++ b/src/libImaging/Raw.h @@ -1,7 +1,6 @@ /* Raw.h */ typedef struct { - /* CONFIGURATION */ /* Distance between lines (0=no padding) */ diff --git a/src/libImaging/RawDecode.c b/src/libImaging/RawDecode.c index ca3d37149..24abe4804 100644 --- a/src/libImaging/RawDecode.c +++ b/src/libImaging/RawDecode.c @@ -13,22 +13,18 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" #include "Raw.h" - int -ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ +ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { enum { LINE = 1, SKIP }; - RAWSTATE* rawstate = state->context; + RAWSTATE *rawstate = state->context; - UINT8* ptr; + UINT8 *ptr; if (state->state == 0) { - /* Initialize context variables */ /* get size of image data and padding */ @@ -45,22 +41,19 @@ ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt /* check image orientation */ if (state->ystep < 0) { - state->y = state->ysize-1; + state->y = state->ysize - 1; state->ystep = -1; } else { state->ystep = 1; } state->state = LINE; - } ptr = buf; for (;;) { - if (state->state == SKIP) { - /* Skip padding between lines */ if (bytes < rawstate->skip) { @@ -71,7 +64,6 @@ ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt bytes -= rawstate->skip; state->state = LINE; - } if (bytes < state->bytes) { @@ -79,8 +71,10 @@ ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt } /* Unpack data */ - state->shuffle((UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, ptr, state->xsize); + state->shuffle( + (UINT8 *)im->image[state->y + state->yoff] + state->xoff * im->pixelsize, + ptr, + state->xsize); ptr += state->bytes; bytes -= state->bytes; @@ -93,7 +87,5 @@ ImagingRawDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt } state->state = SKIP; - } - } diff --git a/src/libImaging/RawEncode.c b/src/libImaging/RawEncode.c index fb4ab3346..50de8d982 100644 --- a/src/libImaging/RawEncode.c +++ b/src/libImaging/RawEncode.c @@ -17,16 +17,13 @@ * * See the README file for information on usage and redistribution. */ - #include "Imaging.h" int -ImagingRawEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) -{ - UINT8* ptr; +ImagingRawEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { + UINT8 *ptr; if (!state->state) { - /* The "count" field holds the stride, if specified. Fix things up so "bytes" is the full size, and "count" the packed size */ @@ -48,14 +45,13 @@ ImagingRawEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) /* The "ystep" field specifies the orientation */ if (state->ystep < 0) { - state->y = state->ysize-1; + state->y = state->ysize - 1; state->ystep = -1; } else { state->ystep = 1; } state->state = 1; - } if (bytes < state->bytes) { @@ -66,9 +62,10 @@ ImagingRawEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) ptr = buf; while (bytes >= state->bytes) { - - state->shuffle(ptr, (UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->xsize); + state->shuffle( + ptr, + (UINT8 *)im->image[state->y + state->yoff] + state->xoff * im->pixelsize, + state->xsize); if (state->bytes > state->count) { /* zero-pad the buffer, if necessary */ @@ -84,9 +81,7 @@ ImagingRawEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) state->errcode = IMAGING_CODEC_END; break; } - } return ptr - buf; - } diff --git a/src/libImaging/Reduce.c b/src/libImaging/Reduce.c index f6488deb2..60928d2bc 100644 --- a/src/libImaging/Reduce.c +++ b/src/libImaging/Reduce.c @@ -2,39 +2,35 @@ #include -#define ROUND_UP(f) ((int) ((f) >= 0.0 ? (f) + 0.5F : (f) - 0.5F)) - +#define ROUND_UP(f) ((int)((f) >= 0.0 ? (f) + 0.5F : (f)-0.5F)) UINT32 -division_UINT32(int divider, int result_bits) -{ +division_UINT32(int divider, int result_bits) { UINT32 max_dividend = (1 << result_bits) * divider; float max_int = (1 << 30) * 4.0; - return (UINT32) (max_int / max_dividend); + return (UINT32)(max_int / max_dividend); } - void -ImagingReduceNxN(Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale) -{ +ImagingReduceNxN(Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale) { /* The most general implementation for any xscale and yscale - */ + */ int x, y, xx, yy; UINT32 multiplier = division_UINT32(yscale * xscale, 8); UINT32 amend = yscale * xscale / 2; if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; + int yy_from = box[1] + y * yscale; for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 ss = amend; for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { UINT8 *line0 = (UINT8 *)imIn->image8[yy]; UINT8 *line1 = (UINT8 *)imIn->image8[yy + 1]; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss += line0[xx + 0] + line0[xx + 1] + - line1[xx + 0] + line1[xx + 1]; + ss += line0[xx + 0] + line0[xx + 1] + line1[xx + 0] + + line1[xx + 1]; } if (xscale & 0x01) { ss += line0[xx + 0] + line1[xx + 0]; @@ -54,125 +50,128 @@ ImagingReduceNxN(Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; + int yy_from = box[1] + y * yscale; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss3 = amend; for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { UINT8 *line0 = (UINT8 *)imIn->image[yy]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss0 += line0[xx*4 + 0] + line0[xx*4 + 4] + - line1[xx*4 + 0] + line1[xx*4 + 4]; - ss3 += line0[xx*4 + 3] + line0[xx*4 + 7] + - line1[xx*4 + 3] + line1[xx*4 + 7]; + ss0 += line0[xx * 4 + 0] + line0[xx * 4 + 4] + + line1[xx * 4 + 0] + line1[xx * 4 + 4]; + ss3 += line0[xx * 4 + 3] + line0[xx * 4 + 7] + + line1[xx * 4 + 3] + line1[xx * 4 + 7]; } if (xscale & 0x01) { - ss0 += line0[xx*4 + 0] + line1[xx*4 + 0]; - ss3 += line0[xx*4 + 3] + line1[xx*4 + 3]; + ss0 += line0[xx * 4 + 0] + line1[xx * 4 + 0]; + ss3 += line0[xx * 4 + 3] + line1[xx * 4 + 3]; } } if (yscale & 0x01) { UINT8 *line = (UINT8 *)imIn->image[yy]; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss0 += line[xx*4 + 0] + line[xx*4 + 4]; - ss3 += line[xx*4 + 3] + line[xx*4 + 7]; + ss0 += line[xx * 4 + 0] + line[xx * 4 + 4]; + ss3 += line[xx * 4 + 3] + line[xx * 4 + 7]; } if (xscale & 0x01) { - ss0 += line[xx*4 + 0]; - ss3 += line[xx*4 + 3]; + ss0 += line[xx * 4 + 0]; + ss3 += line[xx * 4 + 3]; } } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, 0, - 0, (ss3 * multiplier) >> 24); + (ss0 * multiplier) >> 24, 0, 0, (ss3 * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss1 = amend, ss2 = amend; for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { UINT8 *line0 = (UINT8 *)imIn->image[yy]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss0 += line0[xx*4 + 0] + line0[xx*4 + 4] + - line1[xx*4 + 0] + line1[xx*4 + 4]; - ss1 += line0[xx*4 + 1] + line0[xx*4 + 5] + - line1[xx*4 + 1] + line1[xx*4 + 5]; - ss2 += line0[xx*4 + 2] + line0[xx*4 + 6] + - line1[xx*4 + 2] + line1[xx*4 + 6]; + ss0 += line0[xx * 4 + 0] + line0[xx * 4 + 4] + + line1[xx * 4 + 0] + line1[xx * 4 + 4]; + ss1 += line0[xx * 4 + 1] + line0[xx * 4 + 5] + + line1[xx * 4 + 1] + line1[xx * 4 + 5]; + ss2 += line0[xx * 4 + 2] + line0[xx * 4 + 6] + + line1[xx * 4 + 2] + line1[xx * 4 + 6]; } if (xscale & 0x01) { - ss0 += line0[xx*4 + 0] + line1[xx*4 + 0]; - ss1 += line0[xx*4 + 1] + line1[xx*4 + 1]; - ss2 += line0[xx*4 + 2] + line1[xx*4 + 2]; + ss0 += line0[xx * 4 + 0] + line1[xx * 4 + 0]; + ss1 += line0[xx * 4 + 1] + line1[xx * 4 + 1]; + ss2 += line0[xx * 4 + 2] + line1[xx * 4 + 2]; } } if (yscale & 0x01) { UINT8 *line = (UINT8 *)imIn->image[yy]; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss0 += line[xx*4 + 0] + line[xx*4 + 4]; - ss1 += line[xx*4 + 1] + line[xx*4 + 5]; - ss2 += line[xx*4 + 2] + line[xx*4 + 6]; + ss0 += line[xx * 4 + 0] + line[xx * 4 + 4]; + ss1 += line[xx * 4 + 1] + line[xx * 4 + 5]; + ss2 += line[xx * 4 + 2] + line[xx * 4 + 6]; } if (xscale & 0x01) { - ss0 += line[xx*4 + 0]; - ss1 += line[xx*4 + 1]; - ss2 += line[xx*4 + 2]; + ss0 += line[xx * 4 + 0]; + ss1 += line[xx * 4 + 1]; + ss2 += line[xx * 4 + 2]; } } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, (ss1 * multiplier) >> 24, - (ss2 * multiplier) >> 24, 0); + (ss0 * multiplier) >> 24, + (ss1 * multiplier) >> 24, + (ss2 * multiplier) >> 24, + 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss1 = amend, ss2 = amend, ss3 = amend; for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { UINT8 *line0 = (UINT8 *)imIn->image[yy]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss0 += line0[xx*4 + 0] + line0[xx*4 + 4] + - line1[xx*4 + 0] + line1[xx*4 + 4]; - ss1 += line0[xx*4 + 1] + line0[xx*4 + 5] + - line1[xx*4 + 1] + line1[xx*4 + 5]; - ss2 += line0[xx*4 + 2] + line0[xx*4 + 6] + - line1[xx*4 + 2] + line1[xx*4 + 6]; - ss3 += line0[xx*4 + 3] + line0[xx*4 + 7] + - line1[xx*4 + 3] + line1[xx*4 + 7]; + ss0 += line0[xx * 4 + 0] + line0[xx * 4 + 4] + + line1[xx * 4 + 0] + line1[xx * 4 + 4]; + ss1 += line0[xx * 4 + 1] + line0[xx * 4 + 5] + + line1[xx * 4 + 1] + line1[xx * 4 + 5]; + ss2 += line0[xx * 4 + 2] + line0[xx * 4 + 6] + + line1[xx * 4 + 2] + line1[xx * 4 + 6]; + ss3 += line0[xx * 4 + 3] + line0[xx * 4 + 7] + + line1[xx * 4 + 3] + line1[xx * 4 + 7]; } if (xscale & 0x01) { - ss0 += line0[xx*4 + 0] + line1[xx*4 + 0]; - ss1 += line0[xx*4 + 1] + line1[xx*4 + 1]; - ss2 += line0[xx*4 + 2] + line1[xx*4 + 2]; - ss3 += line0[xx*4 + 3] + line1[xx*4 + 3]; + ss0 += line0[xx * 4 + 0] + line1[xx * 4 + 0]; + ss1 += line0[xx * 4 + 1] + line1[xx * 4 + 1]; + ss2 += line0[xx * 4 + 2] + line1[xx * 4 + 2]; + ss3 += line0[xx * 4 + 3] + line1[xx * 4 + 3]; } } if (yscale & 0x01) { UINT8 *line = (UINT8 *)imIn->image[yy]; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss0 += line[xx*4 + 0] + line[xx*4 + 4]; - ss1 += line[xx*4 + 1] + line[xx*4 + 5]; - ss2 += line[xx*4 + 2] + line[xx*4 + 6]; - ss3 += line[xx*4 + 3] + line[xx*4 + 7]; + ss0 += line[xx * 4 + 0] + line[xx * 4 + 4]; + ss1 += line[xx * 4 + 1] + line[xx * 4 + 5]; + ss2 += line[xx * 4 + 2] + line[xx * 4 + 6]; + ss3 += line[xx * 4 + 3] + line[xx * 4 + 7]; } if (xscale & 0x01) { - ss0 += line[xx*4 + 0]; - ss1 += line[xx*4 + 1]; - ss2 += line[xx*4 + 2]; - ss3 += line[xx*4 + 3]; + ss0 += line[xx * 4 + 0]; + ss1 += line[xx * 4 + 1]; + ss2 += line[xx * 4 + 2]; + ss3 += line[xx * 4 + 3]; } } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, (ss1 * multiplier) >> 24, - (ss2 * multiplier) >> 24, (ss3 * multiplier) >> 24); + (ss0 * multiplier) >> 24, + (ss1 * multiplier) >> 24, + (ss2 * multiplier) >> 24, + (ss3 * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -180,12 +179,10 @@ ImagingReduceNxN(Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale } } - void -ImagingReduce1xN(Imaging imOut, Imaging imIn, int box[4], int yscale) -{ +ImagingReduce1xN(Imaging imOut, Imaging imIn, int box[4], int yscale) { /* Optimized implementation for xscale = 1. - */ + */ int x, y, yy; int xscale = 1; UINT32 multiplier = division_UINT32(yscale * xscale, 8); @@ -193,9 +190,9 @@ ImagingReduce1xN(Imaging imOut, Imaging imIn, int box[4], int yscale) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; + int yy_from = box[1] + y * yscale; for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 ss = amend; for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { UINT8 *line0 = (UINT8 *)imIn->image8[yy]; @@ -211,74 +208,77 @@ ImagingReduce1xN(Imaging imOut, Imaging imIn, int box[4], int yscale) } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; + int yy_from = box[1] + y * yscale; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss3 = amend; for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { UINT8 *line0 = (UINT8 *)imIn->image[yy]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; - ss0 += line0[xx*4 + 0] + line1[xx*4 + 0]; - ss3 += line0[xx*4 + 3] + line1[xx*4 + 3]; + ss0 += line0[xx * 4 + 0] + line1[xx * 4 + 0]; + ss3 += line0[xx * 4 + 3] + line1[xx * 4 + 3]; } if (yscale & 0x01) { UINT8 *line = (UINT8 *)imIn->image[yy]; - ss0 += line[xx*4 + 0]; - ss3 += line[xx*4 + 3]; + ss0 += line[xx * 4 + 0]; + ss3 += line[xx * 4 + 3]; } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, 0, - 0, (ss3 * multiplier) >> 24); + (ss0 * multiplier) >> 24, 0, 0, (ss3 * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss1 = amend, ss2 = amend; for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { UINT8 *line0 = (UINT8 *)imIn->image[yy]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; - ss0 += line0[xx*4 + 0] + line1[xx*4 + 0]; - ss1 += line0[xx*4 + 1] + line1[xx*4 + 1]; - ss2 += line0[xx*4 + 2] + line1[xx*4 + 2]; + ss0 += line0[xx * 4 + 0] + line1[xx * 4 + 0]; + ss1 += line0[xx * 4 + 1] + line1[xx * 4 + 1]; + ss2 += line0[xx * 4 + 2] + line1[xx * 4 + 2]; } if (yscale & 0x01) { UINT8 *line = (UINT8 *)imIn->image[yy]; - ss0 += line[xx*4 + 0]; - ss1 += line[xx*4 + 1]; - ss2 += line[xx*4 + 2]; + ss0 += line[xx * 4 + 0]; + ss1 += line[xx * 4 + 1]; + ss2 += line[xx * 4 + 2]; } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, (ss1 * multiplier) >> 24, - (ss2 * multiplier) >> 24, 0); + (ss0 * multiplier) >> 24, + (ss1 * multiplier) >> 24, + (ss2 * multiplier) >> 24, + 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss1 = amend, ss2 = amend, ss3 = amend; for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { UINT8 *line0 = (UINT8 *)imIn->image[yy]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; - ss0 += line0[xx*4 + 0] + line1[xx*4 + 0]; - ss1 += line0[xx*4 + 1] + line1[xx*4 + 1]; - ss2 += line0[xx*4 + 2] + line1[xx*4 + 2]; - ss3 += line0[xx*4 + 3] + line1[xx*4 + 3]; + ss0 += line0[xx * 4 + 0] + line1[xx * 4 + 0]; + ss1 += line0[xx * 4 + 1] + line1[xx * 4 + 1]; + ss2 += line0[xx * 4 + 2] + line1[xx * 4 + 2]; + ss3 += line0[xx * 4 + 3] + line1[xx * 4 + 3]; } if (yscale & 0x01) { UINT8 *line = (UINT8 *)imIn->image[yy]; - ss0 += line[xx*4 + 0]; - ss1 += line[xx*4 + 1]; - ss2 += line[xx*4 + 2]; - ss3 += line[xx*4 + 3]; + ss0 += line[xx * 4 + 0]; + ss1 += line[xx * 4 + 1]; + ss2 += line[xx * 4 + 2]; + ss3 += line[xx * 4 + 3]; } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, (ss1 * multiplier) >> 24, - (ss2 * multiplier) >> 24, (ss3 * multiplier) >> 24); + (ss0 * multiplier) >> 24, + (ss1 * multiplier) >> 24, + (ss2 * multiplier) >> 24, + (ss3 * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -286,12 +286,10 @@ ImagingReduce1xN(Imaging imOut, Imaging imIn, int box[4], int yscale) } } - void -ImagingReduceNx1(Imaging imOut, Imaging imIn, int box[4], int xscale) -{ +ImagingReduceNx1(Imaging imOut, Imaging imIn, int box[4], int xscale) { /* Optimized implementation for yscale = 1. - */ + */ int x, y, xx; int yscale = 1; UINT32 multiplier = division_UINT32(yscale * xscale, 8); @@ -299,10 +297,10 @@ ImagingReduceNx1(Imaging imOut, Imaging imIn, int box[4], int xscale) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line = (UINT8 *)imIn->image8[yy]; for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 ss = amend; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { ss += line[xx + 0] + line[xx + 1]; @@ -315,66 +313,69 @@ ImagingReduceNx1(Imaging imOut, Imaging imIn, int box[4], int xscale) } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line = (UINT8 *)imIn->image[yy]; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss3 = amend; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss0 += line[xx*4 + 0] + line[xx*4 + 4]; - ss3 += line[xx*4 + 3] + line[xx*4 + 7]; + ss0 += line[xx * 4 + 0] + line[xx * 4 + 4]; + ss3 += line[xx * 4 + 3] + line[xx * 4 + 7]; } if (xscale & 0x01) { - ss0 += line[xx*4 + 0]; - ss3 += line[xx*4 + 3]; + ss0 += line[xx * 4 + 0]; + ss3 += line[xx * 4 + 3]; } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, 0, - 0, (ss3 * multiplier) >> 24); + (ss0 * multiplier) >> 24, 0, 0, (ss3 * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss1 = amend, ss2 = amend; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss0 += line[xx*4 + 0] + line[xx*4 + 4]; - ss1 += line[xx*4 + 1] + line[xx*4 + 5]; - ss2 += line[xx*4 + 2] + line[xx*4 + 6]; + ss0 += line[xx * 4 + 0] + line[xx * 4 + 4]; + ss1 += line[xx * 4 + 1] + line[xx * 4 + 5]; + ss2 += line[xx * 4 + 2] + line[xx * 4 + 6]; } if (xscale & 0x01) { - ss0 += line[xx*4 + 0]; - ss1 += line[xx*4 + 1]; - ss2 += line[xx*4 + 2]; + ss0 += line[xx * 4 + 0]; + ss1 += line[xx * 4 + 1]; + ss2 += line[xx * 4 + 2]; } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, (ss1 * multiplier) >> 24, - (ss2 * multiplier) >> 24, 0); + (ss0 * multiplier) >> 24, + (ss1 * multiplier) >> 24, + (ss2 * multiplier) >> 24, + 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss1 = amend, ss2 = amend, ss3 = amend; for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss0 += line[xx*4 + 0] + line[xx*4 + 4]; - ss1 += line[xx*4 + 1] + line[xx*4 + 5]; - ss2 += line[xx*4 + 2] + line[xx*4 + 6]; - ss3 += line[xx*4 + 3] + line[xx*4 + 7]; + ss0 += line[xx * 4 + 0] + line[xx * 4 + 4]; + ss1 += line[xx * 4 + 1] + line[xx * 4 + 5]; + ss2 += line[xx * 4 + 2] + line[xx * 4 + 6]; + ss3 += line[xx * 4 + 3] + line[xx * 4 + 7]; } if (xscale & 0x01) { - ss0 += line[xx*4 + 0]; - ss1 += line[xx*4 + 1]; - ss2 += line[xx*4 + 2]; - ss3 += line[xx*4 + 3]; + ss0 += line[xx * 4 + 0]; + ss1 += line[xx * 4 + 1]; + ss2 += line[xx * 4 + 2]; + ss3 += line[xx * 4 + 3]; } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, (ss1 * multiplier) >> 24, - (ss2 * multiplier) >> 24, (ss3 * multiplier) >> 24); + (ss0 * multiplier) >> 24, + (ss1 * multiplier) >> 24, + (ss2 * multiplier) >> 24, + (ss3 * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -383,10 +384,9 @@ ImagingReduceNx1(Imaging imOut, Imaging imIn, int box[4], int xscale) } void -ImagingReduce1x2(Imaging imOut, Imaging imIn, int box[4]) -{ +ImagingReduce1x2(Imaging imOut, Imaging imIn, int box[4]) { /* Optimized implementation for xscale = 1 and yscale = 2. - */ + */ int xscale = 1, yscale = 2; int x, y; UINT32 ss0, ss1, ss2, ss3; @@ -394,61 +394,53 @@ ImagingReduce1x2(Imaging imOut, Imaging imIn, int box[4]) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image8[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image8[yy + 1]; for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; - ss0 = line0[xx + 0] + - line1[xx + 0]; + int xx = box[0] + x * xscale; + ss0 = line0[xx + 0] + line1[xx + 0]; imOut->image8[y][x] = (ss0 + amend) >> 1; } } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + - line1[xx*4 + 0]; - ss3 = line0[xx*4 + 3] + - line1[xx*4 + 3]; - v = MAKE_UINT32((ss0 + amend) >> 1, 0, - 0, (ss3 + amend) >> 1); + ss0 = line0[xx * 4 + 0] + line1[xx * 4 + 0]; + ss3 = line0[xx * 4 + 3] + line1[xx * 4 + 3]; + v = MAKE_UINT32((ss0 + amend) >> 1, 0, 0, (ss3 + amend) >> 1); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + - line1[xx*4 + 0]; - ss1 = line0[xx*4 + 1] + - line1[xx*4 + 1]; - ss2 = line0[xx*4 + 2] + - line1[xx*4 + 2]; - v = MAKE_UINT32((ss0 + amend) >> 1, (ss1 + amend) >> 1, - (ss2 + amend) >> 1, 0); + ss0 = line0[xx * 4 + 0] + line1[xx * 4 + 0]; + ss1 = line0[xx * 4 + 1] + line1[xx * 4 + 1]; + ss2 = line0[xx * 4 + 2] + line1[xx * 4 + 2]; + v = MAKE_UINT32( + (ss0 + amend) >> 1, (ss1 + amend) >> 1, (ss2 + amend) >> 1, 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + - line1[xx*4 + 0]; - ss1 = line0[xx*4 + 1] + - line1[xx*4 + 1]; - ss2 = line0[xx*4 + 2] + - line1[xx*4 + 2]; - ss3 = line0[xx*4 + 3] + - line1[xx*4 + 3]; - v = MAKE_UINT32((ss0 + amend) >> 1, (ss1 + amend) >> 1, - (ss2 + amend) >> 1, (ss3 + amend) >> 1); + ss0 = line0[xx * 4 + 0] + line1[xx * 4 + 0]; + ss1 = line0[xx * 4 + 1] + line1[xx * 4 + 1]; + ss2 = line0[xx * 4 + 2] + line1[xx * 4 + 2]; + ss3 = line0[xx * 4 + 3] + line1[xx * 4 + 3]; + v = MAKE_UINT32( + (ss0 + amend) >> 1, + (ss1 + amend) >> 1, + (ss2 + amend) >> 1, + (ss3 + amend) >> 1); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -456,12 +448,10 @@ ImagingReduce1x2(Imaging imOut, Imaging imIn, int box[4]) } } - void -ImagingReduce2x1(Imaging imOut, Imaging imIn, int box[4]) -{ +ImagingReduce2x1(Imaging imOut, Imaging imIn, int box[4]) { /* Optimized implementation for xscale = 2 and yscale = 1. - */ + */ int xscale = 2, yscale = 1; int x, y; UINT32 ss0, ss1, ss2, ss3; @@ -469,49 +459,51 @@ ImagingReduce2x1(Imaging imOut, Imaging imIn, int box[4]) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image8[yy + 0]; for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; ss0 = line0[xx + 0] + line0[xx + 1]; imOut->image8[y][x] = (ss0 + amend) >> 1; } } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image[yy + 0]; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7]; - v = MAKE_UINT32((ss0 + amend) >> 1, 0, - 0, (ss3 + amend) >> 1); + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7]; + v = MAKE_UINT32((ss0 + amend) >> 1, 0, 0, (ss3 + amend) >> 1); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6]; - v = MAKE_UINT32((ss0 + amend) >> 1, (ss1 + amend) >> 1, - (ss2 + amend) >> 1, 0); + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6]; + v = MAKE_UINT32( + (ss0 + amend) >> 1, (ss1 + amend) >> 1, (ss2 + amend) >> 1, 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7]; - v = MAKE_UINT32((ss0 + amend) >> 1, (ss1 + amend) >> 1, - (ss2 + amend) >> 1, (ss3 + amend) >> 1); + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7]; + v = MAKE_UINT32( + (ss0 + amend) >> 1, + (ss1 + amend) >> 1, + (ss2 + amend) >> 1, + (ss3 + amend) >> 1); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -519,12 +511,10 @@ ImagingReduce2x1(Imaging imOut, Imaging imIn, int box[4]) } } - void -ImagingReduce2x2(Imaging imOut, Imaging imIn, int box[4]) -{ +ImagingReduce2x2(Imaging imOut, Imaging imIn, int box[4]) { /* Optimized implementation for xscale = 2 and yscale = 2. - */ + */ int xscale = 2, yscale = 2; int x, y; UINT32 ss0, ss1, ss2, ss3; @@ -532,61 +522,62 @@ ImagingReduce2x2(Imaging imOut, Imaging imIn, int box[4]) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image8[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image8[yy + 1]; for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; - ss0 = line0[xx + 0] + line0[xx + 1] + - line1[xx + 0] + line1[xx + 1]; + int xx = box[0] + x * xscale; + ss0 = line0[xx + 0] + line0[xx + 1] + line1[xx + 0] + line1[xx + 1]; imOut->image8[y][x] = (ss0 + amend) >> 2; } } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + - line1[xx*4 + 0] + line1[xx*4 + 4]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + - line1[xx*4 + 3] + line1[xx*4 + 7]; - v = MAKE_UINT32((ss0 + amend) >> 2, 0, - 0, (ss3 + amend) >> 2); + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line1[xx * 4 + 0] + + line1[xx * 4 + 4]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line1[xx * 4 + 3] + + line1[xx * 4 + 7]; + v = MAKE_UINT32((ss0 + amend) >> 2, 0, 0, (ss3 + amend) >> 2); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + - line1[xx*4 + 0] + line1[xx*4 + 4]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + - line1[xx*4 + 1] + line1[xx*4 + 5]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + - line1[xx*4 + 2] + line1[xx*4 + 6]; - v = MAKE_UINT32((ss0 + amend) >> 2, (ss1 + amend) >> 2, - (ss2 + amend) >> 2, 0); + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line1[xx * 4 + 0] + + line1[xx * 4 + 4]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line1[xx * 4 + 1] + + line1[xx * 4 + 5]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line1[xx * 4 + 2] + + line1[xx * 4 + 6]; + v = MAKE_UINT32( + (ss0 + amend) >> 2, (ss1 + amend) >> 2, (ss2 + amend) >> 2, 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + - line1[xx*4 + 0] + line1[xx*4 + 4]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + - line1[xx*4 + 1] + line1[xx*4 + 5]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + - line1[xx*4 + 2] + line1[xx*4 + 6]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + - line1[xx*4 + 3] + line1[xx*4 + 7]; - v = MAKE_UINT32((ss0 + amend) >> 2, (ss1 + amend) >> 2, - (ss2 + amend) >> 2, (ss3 + amend) >> 2); + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line1[xx * 4 + 0] + + line1[xx * 4 + 4]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line1[xx * 4 + 1] + + line1[xx * 4 + 5]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line1[xx * 4 + 2] + + line1[xx * 4 + 6]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line1[xx * 4 + 3] + + line1[xx * 4 + 7]; + v = MAKE_UINT32( + (ss0 + amend) >> 2, + (ss1 + amend) >> 2, + (ss2 + amend) >> 2, + (ss3 + amend) >> 2); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -594,12 +585,10 @@ ImagingReduce2x2(Imaging imOut, Imaging imIn, int box[4]) } } - void -ImagingReduce1x3(Imaging imOut, Imaging imIn, int box[4]) -{ +ImagingReduce1x3(Imaging imOut, Imaging imIn, int box[4]) { /* Optimized implementation for xscale = 1 and yscale = 3. - */ + */ int xscale = 1, yscale = 3; int x, y; UINT32 ss0, ss1, ss2, ss3; @@ -608,76 +597,62 @@ ImagingReduce1x3(Imaging imOut, Imaging imIn, int box[4]) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image8[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image8[yy + 1]; UINT8 *line2 = (UINT8 *)imIn->image8[yy + 2]; for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; - ss0 = line0[xx + 0] + - line1[xx + 0] + - line2[xx + 0]; + int xx = box[0] + x * xscale; + ss0 = line0[xx + 0] + line1[xx + 0] + line2[xx + 0]; imOut->image8[y][x] = ((ss0 + amend) * multiplier) >> 24; } } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; UINT8 *line2 = (UINT8 *)imIn->image[yy + 2]; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + - line1[xx*4 + 0] + - line2[xx*4 + 0]; - ss3 = line0[xx*4 + 3] + - line1[xx*4 + 3] + - line2[xx*4 + 3]; + ss0 = line0[xx * 4 + 0] + line1[xx * 4 + 0] + line2[xx * 4 + 0]; + ss3 = line0[xx * 4 + 3] + line1[xx * 4 + 3] + line2[xx * 4 + 3]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, 0, - 0, ((ss3 + amend) * multiplier) >> 24); + ((ss0 + amend) * multiplier) >> 24, + 0, + 0, + ((ss3 + amend) * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + - line1[xx*4 + 0] + - line2[xx*4 + 0]; - ss1 = line0[xx*4 + 1] + - line1[xx*4 + 1] + - line2[xx*4 + 1]; - ss2 = line0[xx*4 + 2] + - line1[xx*4 + 2] + - line2[xx*4 + 2]; + ss0 = line0[xx * 4 + 0] + line1[xx * 4 + 0] + line2[xx * 4 + 0]; + ss1 = line0[xx * 4 + 1] + line1[xx * 4 + 1] + line2[xx * 4 + 1]; + ss2 = line0[xx * 4 + 2] + line1[xx * 4 + 2] + line2[xx * 4 + 2]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, ((ss1 + amend) * multiplier) >> 24, - ((ss2 + amend) * multiplier) >> 24, 0); + ((ss0 + amend) * multiplier) >> 24, + ((ss1 + amend) * multiplier) >> 24, + ((ss2 + amend) * multiplier) >> 24, + 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + - line1[xx*4 + 0] + - line2[xx*4 + 0]; - ss1 = line0[xx*4 + 1] + - line1[xx*4 + 1] + - line2[xx*4 + 1]; - ss2 = line0[xx*4 + 2] + - line1[xx*4 + 2] + - line2[xx*4 + 2]; - ss3 = line0[xx*4 + 3] + - line1[xx*4 + 3] + - line2[xx*4 + 3]; + ss0 = line0[xx * 4 + 0] + line1[xx * 4 + 0] + line2[xx * 4 + 0]; + ss1 = line0[xx * 4 + 1] + line1[xx * 4 + 1] + line2[xx * 4 + 1]; + ss2 = line0[xx * 4 + 2] + line1[xx * 4 + 2] + line2[xx * 4 + 2]; + ss3 = line0[xx * 4 + 3] + line1[xx * 4 + 3] + line2[xx * 4 + 3]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, ((ss1 + amend) * multiplier) >> 24, - ((ss2 + amend) * multiplier) >> 24, ((ss3 + amend) * multiplier) >> 24); + ((ss0 + amend) * multiplier) >> 24, + ((ss1 + amend) * multiplier) >> 24, + ((ss2 + amend) * multiplier) >> 24, + ((ss3 + amend) * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -685,12 +660,10 @@ ImagingReduce1x3(Imaging imOut, Imaging imIn, int box[4]) } } - void -ImagingReduce3x1(Imaging imOut, Imaging imIn, int box[4]) -{ +ImagingReduce3x1(Imaging imOut, Imaging imIn, int box[4]) { /* Optimized implementation for xscale = 3 and yscale = 1. - */ + */ int xscale = 3, yscale = 1; int x, y; UINT32 ss0, ss1, ss2, ss3; @@ -699,52 +672,58 @@ ImagingReduce3x1(Imaging imOut, Imaging imIn, int box[4]) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image8[yy + 0]; for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; ss0 = line0[xx + 0] + line0[xx + 1] + line0[xx + 2]; imOut->image8[y][x] = ((ss0 + amend) * multiplier) >> 24; } } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image[yy + 0]; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + line0[xx*4 + 11]; + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line0[xx * 4 + 11]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, 0, - 0, ((ss3 + amend) * multiplier) >> 24); + ((ss0 + amend) * multiplier) >> 24, + 0, + 0, + ((ss3 + amend) * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + line0[xx*4 + 9]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + line0[xx*4 + 10]; + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line0[xx * 4 + 9]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line0[xx * 4 + 10]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, ((ss1 + amend) * multiplier) >> 24, - ((ss2 + amend) * multiplier) >> 24, 0); + ((ss0 + amend) * multiplier) >> 24, + ((ss1 + amend) * multiplier) >> 24, + ((ss2 + amend) * multiplier) >> 24, + 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + line0[xx*4 + 9]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + line0[xx*4 + 10]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + line0[xx*4 + 11]; + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line0[xx * 4 + 9]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line0[xx * 4 + 10]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line0[xx * 4 + 11]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, ((ss1 + amend) * multiplier) >> 24, - ((ss2 + amend) * multiplier) >> 24, ((ss3 + amend) * multiplier) >> 24); + ((ss0 + amend) * multiplier) >> 24, + ((ss1 + amend) * multiplier) >> 24, + ((ss2 + amend) * multiplier) >> 24, + ((ss3 + amend) * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -752,12 +731,10 @@ ImagingReduce3x1(Imaging imOut, Imaging imIn, int box[4]) } } - void -ImagingReduce3x3(Imaging imOut, Imaging imIn, int box[4]) -{ +ImagingReduce3x3(Imaging imOut, Imaging imIn, int box[4]) { /* Optimized implementation for xscale = 3 and yscale = 3. - */ + */ int xscale = 3, yscale = 3; int x, y; UINT32 ss0, ss1, ss2, ss3; @@ -766,76 +743,82 @@ ImagingReduce3x3(Imaging imOut, Imaging imIn, int box[4]) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image8[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image8[yy + 1]; UINT8 *line2 = (UINT8 *)imIn->image8[yy + 2]; for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; - ss0 = line0[xx + 0] + line0[xx + 1] + line0[xx + 2] + - line1[xx + 0] + line1[xx + 1] + line1[xx + 2] + - line2[xx + 0] + line2[xx + 1] + line2[xx + 2]; + int xx = box[0] + x * xscale; + ss0 = line0[xx + 0] + line0[xx + 1] + line0[xx + 2] + line1[xx + 0] + + line1[xx + 1] + line1[xx + 2] + line2[xx + 0] + line2[xx + 1] + + line2[xx + 2]; imOut->image8[y][x] = ((ss0 + amend) * multiplier) >> 24; } } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; UINT8 *line2 = (UINT8 *)imIn->image[yy + 2]; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8] + - line1[xx*4 + 0] + line1[xx*4 + 4] + line1[xx*4 + 8] + - line2[xx*4 + 0] + line2[xx*4 + 4] + line2[xx*4 + 8]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + line0[xx*4 + 11] + - line1[xx*4 + 3] + line1[xx*4 + 7] + line1[xx*4 + 11] + - line2[xx*4 + 3] + line2[xx*4 + 7] + line2[xx*4 + 11]; + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8] + + line1[xx * 4 + 0] + line1[xx * 4 + 4] + line1[xx * 4 + 8] + + line2[xx * 4 + 0] + line2[xx * 4 + 4] + line2[xx * 4 + 8]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line0[xx * 4 + 11] + + line1[xx * 4 + 3] + line1[xx * 4 + 7] + line1[xx * 4 + 11] + + line2[xx * 4 + 3] + line2[xx * 4 + 7] + line2[xx * 4 + 11]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, 0, - 0, ((ss3 + amend) * multiplier) >> 24); + ((ss0 + amend) * multiplier) >> 24, + 0, + 0, + ((ss3 + amend) * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8] + - line1[xx*4 + 0] + line1[xx*4 + 4] + line1[xx*4 + 8] + - line2[xx*4 + 0] + line2[xx*4 + 4] + line2[xx*4 + 8]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + line0[xx*4 + 9] + - line1[xx*4 + 1] + line1[xx*4 + 5] + line1[xx*4 + 9] + - line2[xx*4 + 1] + line2[xx*4 + 5] + line2[xx*4 + 9]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + line0[xx*4 + 10] + - line1[xx*4 + 2] + line1[xx*4 + 6] + line1[xx*4 + 10] + - line2[xx*4 + 2] + line2[xx*4 + 6] + line2[xx*4 + 10]; + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8] + + line1[xx * 4 + 0] + line1[xx * 4 + 4] + line1[xx * 4 + 8] + + line2[xx * 4 + 0] + line2[xx * 4 + 4] + line2[xx * 4 + 8]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line0[xx * 4 + 9] + + line1[xx * 4 + 1] + line1[xx * 4 + 5] + line1[xx * 4 + 9] + + line2[xx * 4 + 1] + line2[xx * 4 + 5] + line2[xx * 4 + 9]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line0[xx * 4 + 10] + + line1[xx * 4 + 2] + line1[xx * 4 + 6] + line1[xx * 4 + 10] + + line2[xx * 4 + 2] + line2[xx * 4 + 6] + line2[xx * 4 + 10]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, ((ss1 + amend) * multiplier) >> 24, - ((ss2 + amend) * multiplier) >> 24, 0); + ((ss0 + amend) * multiplier) >> 24, + ((ss1 + amend) * multiplier) >> 24, + ((ss2 + amend) * multiplier) >> 24, + 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8] + - line1[xx*4 + 0] + line1[xx*4 + 4] + line1[xx*4 + 8] + - line2[xx*4 + 0] + line2[xx*4 + 4] + line2[xx*4 + 8]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + line0[xx*4 + 9] + - line1[xx*4 + 1] + line1[xx*4 + 5] + line1[xx*4 + 9] + - line2[xx*4 + 1] + line2[xx*4 + 5] + line2[xx*4 + 9]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + line0[xx*4 + 10] + - line1[xx*4 + 2] + line1[xx*4 + 6] + line1[xx*4 + 10] + - line2[xx*4 + 2] + line2[xx*4 + 6] + line2[xx*4 + 10]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + line0[xx*4 + 11] + - line1[xx*4 + 3] + line1[xx*4 + 7] + line1[xx*4 + 11] + - line2[xx*4 + 3] + line2[xx*4 + 7] + line2[xx*4 + 11]; + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8] + + line1[xx * 4 + 0] + line1[xx * 4 + 4] + line1[xx * 4 + 8] + + line2[xx * 4 + 0] + line2[xx * 4 + 4] + line2[xx * 4 + 8]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line0[xx * 4 + 9] + + line1[xx * 4 + 1] + line1[xx * 4 + 5] + line1[xx * 4 + 9] + + line2[xx * 4 + 1] + line2[xx * 4 + 5] + line2[xx * 4 + 9]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line0[xx * 4 + 10] + + line1[xx * 4 + 2] + line1[xx * 4 + 6] + line1[xx * 4 + 10] + + line2[xx * 4 + 2] + line2[xx * 4 + 6] + line2[xx * 4 + 10]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line0[xx * 4 + 11] + + line1[xx * 4 + 3] + line1[xx * 4 + 7] + line1[xx * 4 + 11] + + line2[xx * 4 + 3] + line2[xx * 4 + 7] + line2[xx * 4 + 11]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, ((ss1 + amend) * multiplier) >> 24, - ((ss2 + amend) * multiplier) >> 24, ((ss3 + amend) * multiplier) >> 24); + ((ss0 + amend) * multiplier) >> 24, + ((ss1 + amend) * multiplier) >> 24, + ((ss2 + amend) * multiplier) >> 24, + ((ss3 + amend) * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -844,10 +827,9 @@ ImagingReduce3x3(Imaging imOut, Imaging imIn, int box[4]) } void -ImagingReduce4x4(Imaging imOut, Imaging imIn, int box[4]) -{ +ImagingReduce4x4(Imaging imOut, Imaging imIn, int box[4]) { /* Optimized implementation for xscale = 4 and yscale = 4. - */ + */ int xscale = 4, yscale = 4; int x, y; UINT32 ss0, ss1, ss2, ss3; @@ -855,13 +837,13 @@ ImagingReduce4x4(Imaging imOut, Imaging imIn, int box[4]) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image8[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image8[yy + 1]; UINT8 *line2 = (UINT8 *)imIn->image8[yy + 2]; UINT8 *line3 = (UINT8 *)imIn->image8[yy + 3]; for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; ss0 = line0[xx + 0] + line0[xx + 1] + line0[xx + 2] + line0[xx + 3] + line1[xx + 0] + line1[xx + 1] + line1[xx + 2] + line1[xx + 3] + line2[xx + 0] + line2[xx + 1] + line2[xx + 2] + line2[xx + 3] + @@ -871,69 +853,89 @@ ImagingReduce4x4(Imaging imOut, Imaging imIn, int box[4]) } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; UINT8 *line2 = (UINT8 *)imIn->image[yy + 2]; UINT8 *line3 = (UINT8 *)imIn->image[yy + 3]; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8] + line0[xx*4 + 12] + - line1[xx*4 + 0] + line1[xx*4 + 4] + line1[xx*4 + 8] + line1[xx*4 + 12] + - line2[xx*4 + 0] + line2[xx*4 + 4] + line2[xx*4 + 8] + line2[xx*4 + 12] + - line3[xx*4 + 0] + line3[xx*4 + 4] + line3[xx*4 + 8] + line3[xx*4 + 12]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + line0[xx*4 + 11] + line0[xx*4 + 15] + - line1[xx*4 + 3] + line1[xx*4 + 7] + line1[xx*4 + 11] + line1[xx*4 + 15] + - line2[xx*4 + 3] + line2[xx*4 + 7] + line2[xx*4 + 11] + line2[xx*4 + 15] + - line3[xx*4 + 3] + line3[xx*4 + 7] + line3[xx*4 + 11] + line3[xx*4 + 15]; - v = MAKE_UINT32((ss0 + amend) >> 4, 0, - 0, (ss3 + amend) >> 4); + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8] + + line0[xx * 4 + 12] + line1[xx * 4 + 0] + line1[xx * 4 + 4] + + line1[xx * 4 + 8] + line1[xx * 4 + 12] + line2[xx * 4 + 0] + + line2[xx * 4 + 4] + line2[xx * 4 + 8] + line2[xx * 4 + 12] + + line3[xx * 4 + 0] + line3[xx * 4 + 4] + line3[xx * 4 + 8] + + line3[xx * 4 + 12]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line0[xx * 4 + 11] + + line0[xx * 4 + 15] + line1[xx * 4 + 3] + line1[xx * 4 + 7] + + line1[xx * 4 + 11] + line1[xx * 4 + 15] + line2[xx * 4 + 3] + + line2[xx * 4 + 7] + line2[xx * 4 + 11] + line2[xx * 4 + 15] + + line3[xx * 4 + 3] + line3[xx * 4 + 7] + line3[xx * 4 + 11] + + line3[xx * 4 + 15]; + v = MAKE_UINT32((ss0 + amend) >> 4, 0, 0, (ss3 + amend) >> 4); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8] + line0[xx*4 + 12] + - line1[xx*4 + 0] + line1[xx*4 + 4] + line1[xx*4 + 8] + line1[xx*4 + 12] + - line2[xx*4 + 0] + line2[xx*4 + 4] + line2[xx*4 + 8] + line2[xx*4 + 12] + - line3[xx*4 + 0] + line3[xx*4 + 4] + line3[xx*4 + 8] + line3[xx*4 + 12]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + line0[xx*4 + 9] + line0[xx*4 + 13] + - line1[xx*4 + 1] + line1[xx*4 + 5] + line1[xx*4 + 9] + line1[xx*4 + 13] + - line2[xx*4 + 1] + line2[xx*4 + 5] + line2[xx*4 + 9] + line2[xx*4 + 13] + - line3[xx*4 + 1] + line3[xx*4 + 5] + line3[xx*4 + 9] + line3[xx*4 + 13]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + line0[xx*4 + 10] + line0[xx*4 + 14] + - line1[xx*4 + 2] + line1[xx*4 + 6] + line1[xx*4 + 10] + line1[xx*4 + 14] + - line2[xx*4 + 2] + line2[xx*4 + 6] + line2[xx*4 + 10] + line2[xx*4 + 14] + - line3[xx*4 + 2] + line3[xx*4 + 6] + line3[xx*4 + 10] + line3[xx*4 + 14]; - v = MAKE_UINT32((ss0 + amend) >> 4, (ss1 + amend) >> 4, - (ss2 + amend) >> 4, 0); + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8] + + line0[xx * 4 + 12] + line1[xx * 4 + 0] + line1[xx * 4 + 4] + + line1[xx * 4 + 8] + line1[xx * 4 + 12] + line2[xx * 4 + 0] + + line2[xx * 4 + 4] + line2[xx * 4 + 8] + line2[xx * 4 + 12] + + line3[xx * 4 + 0] + line3[xx * 4 + 4] + line3[xx * 4 + 8] + + line3[xx * 4 + 12]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line0[xx * 4 + 9] + + line0[xx * 4 + 13] + line1[xx * 4 + 1] + line1[xx * 4 + 5] + + line1[xx * 4 + 9] + line1[xx * 4 + 13] + line2[xx * 4 + 1] + + line2[xx * 4 + 5] + line2[xx * 4 + 9] + line2[xx * 4 + 13] + + line3[xx * 4 + 1] + line3[xx * 4 + 5] + line3[xx * 4 + 9] + + line3[xx * 4 + 13]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line0[xx * 4 + 10] + + line0[xx * 4 + 14] + line1[xx * 4 + 2] + line1[xx * 4 + 6] + + line1[xx * 4 + 10] + line1[xx * 4 + 14] + line2[xx * 4 + 2] + + line2[xx * 4 + 6] + line2[xx * 4 + 10] + line2[xx * 4 + 14] + + line3[xx * 4 + 2] + line3[xx * 4 + 6] + line3[xx * 4 + 10] + + line3[xx * 4 + 14]; + v = MAKE_UINT32( + (ss0 + amend) >> 4, (ss1 + amend) >> 4, (ss2 + amend) >> 4, 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8] + line0[xx*4 + 12] + - line1[xx*4 + 0] + line1[xx*4 + 4] + line1[xx*4 + 8] + line1[xx*4 + 12] + - line2[xx*4 + 0] + line2[xx*4 + 4] + line2[xx*4 + 8] + line2[xx*4 + 12] + - line3[xx*4 + 0] + line3[xx*4 + 4] + line3[xx*4 + 8] + line3[xx*4 + 12]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + line0[xx*4 + 9] + line0[xx*4 + 13] + - line1[xx*4 + 1] + line1[xx*4 + 5] + line1[xx*4 + 9] + line1[xx*4 + 13] + - line2[xx*4 + 1] + line2[xx*4 + 5] + line2[xx*4 + 9] + line2[xx*4 + 13] + - line3[xx*4 + 1] + line3[xx*4 + 5] + line3[xx*4 + 9] + line3[xx*4 + 13]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + line0[xx*4 + 10] + line0[xx*4 + 14] + - line1[xx*4 + 2] + line1[xx*4 + 6] + line1[xx*4 + 10] + line1[xx*4 + 14] + - line2[xx*4 + 2] + line2[xx*4 + 6] + line2[xx*4 + 10] + line2[xx*4 + 14] + - line3[xx*4 + 2] + line3[xx*4 + 6] + line3[xx*4 + 10] + line3[xx*4 + 14]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + line0[xx*4 + 11] + line0[xx*4 + 15] + - line1[xx*4 + 3] + line1[xx*4 + 7] + line1[xx*4 + 11] + line1[xx*4 + 15] + - line2[xx*4 + 3] + line2[xx*4 + 7] + line2[xx*4 + 11] + line2[xx*4 + 15] + - line3[xx*4 + 3] + line3[xx*4 + 7] + line3[xx*4 + 11] + line3[xx*4 + 15]; - v = MAKE_UINT32((ss0 + amend) >> 4, (ss1 + amend) >> 4, - (ss2 + amend) >> 4, (ss3 + amend) >> 4); + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8] + + line0[xx * 4 + 12] + line1[xx * 4 + 0] + line1[xx * 4 + 4] + + line1[xx * 4 + 8] + line1[xx * 4 + 12] + line2[xx * 4 + 0] + + line2[xx * 4 + 4] + line2[xx * 4 + 8] + line2[xx * 4 + 12] + + line3[xx * 4 + 0] + line3[xx * 4 + 4] + line3[xx * 4 + 8] + + line3[xx * 4 + 12]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line0[xx * 4 + 9] + + line0[xx * 4 + 13] + line1[xx * 4 + 1] + line1[xx * 4 + 5] + + line1[xx * 4 + 9] + line1[xx * 4 + 13] + line2[xx * 4 + 1] + + line2[xx * 4 + 5] + line2[xx * 4 + 9] + line2[xx * 4 + 13] + + line3[xx * 4 + 1] + line3[xx * 4 + 5] + line3[xx * 4 + 9] + + line3[xx * 4 + 13]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line0[xx * 4 + 10] + + line0[xx * 4 + 14] + line1[xx * 4 + 2] + line1[xx * 4 + 6] + + line1[xx * 4 + 10] + line1[xx * 4 + 14] + line2[xx * 4 + 2] + + line2[xx * 4 + 6] + line2[xx * 4 + 10] + line2[xx * 4 + 14] + + line3[xx * 4 + 2] + line3[xx * 4 + 6] + line3[xx * 4 + 10] + + line3[xx * 4 + 14]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line0[xx * 4 + 11] + + line0[xx * 4 + 15] + line1[xx * 4 + 3] + line1[xx * 4 + 7] + + line1[xx * 4 + 11] + line1[xx * 4 + 15] + line2[xx * 4 + 3] + + line2[xx * 4 + 7] + line2[xx * 4 + 11] + line2[xx * 4 + 15] + + line3[xx * 4 + 3] + line3[xx * 4 + 7] + line3[xx * 4 + 11] + + line3[xx * 4 + 15]; + v = MAKE_UINT32( + (ss0 + amend) >> 4, + (ss1 + amend) >> 4, + (ss2 + amend) >> 4, + (ss3 + amend) >> 4); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -941,12 +943,10 @@ ImagingReduce4x4(Imaging imOut, Imaging imIn, int box[4]) } } - void -ImagingReduce5x5(Imaging imOut, Imaging imIn, int box[4]) -{ +ImagingReduce5x5(Imaging imOut, Imaging imIn, int box[4]) { /* Fast special case for xscale = 5 and yscale = 5. - */ + */ int xscale = 5, yscale = 5; int x, y; UINT32 ss0, ss1, ss2, ss3; @@ -955,25 +955,27 @@ ImagingReduce5x5(Imaging imOut, Imaging imIn, int box[4]) if (imIn->image8) { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image8[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image8[yy + 1]; UINT8 *line2 = (UINT8 *)imIn->image8[yy + 2]; UINT8 *line3 = (UINT8 *)imIn->image8[yy + 3]; UINT8 *line4 = (UINT8 *)imIn->image8[yy + 4]; for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; - ss0 = line0[xx + 0] + line0[xx + 1] + line0[xx + 2] + line0[xx + 3] + line0[xx + 4] + - line1[xx + 0] + line1[xx + 1] + line1[xx + 2] + line1[xx + 3] + line1[xx + 4] + - line2[xx + 0] + line2[xx + 1] + line2[xx + 2] + line2[xx + 3] + line2[xx + 4] + - line3[xx + 0] + line3[xx + 1] + line3[xx + 2] + line3[xx + 3] + line3[xx + 4] + - line4[xx + 0] + line4[xx + 1] + line4[xx + 2] + line4[xx + 3] + line4[xx + 4]; + int xx = box[0] + x * xscale; + ss0 = line0[xx + 0] + line0[xx + 1] + line0[xx + 2] + line0[xx + 3] + + line0[xx + 4] + line1[xx + 0] + line1[xx + 1] + line1[xx + 2] + + line1[xx + 3] + line1[xx + 4] + line2[xx + 0] + line2[xx + 1] + + line2[xx + 2] + line2[xx + 3] + line2[xx + 4] + line3[xx + 0] + + line3[xx + 1] + line3[xx + 2] + line3[xx + 3] + line3[xx + 4] + + line4[xx + 0] + line4[xx + 1] + line4[xx + 2] + line4[xx + 3] + + line4[xx + 4]; imOut->image8[y][x] = ((ss0 + amend) * multiplier) >> 24; } } } else { for (y = 0; y < box[3] / yscale; y++) { - int yy = box[1] + y*yscale; + int yy = box[1] + y * yscale; UINT8 *line0 = (UINT8 *)imIn->image[yy + 0]; UINT8 *line1 = (UINT8 *)imIn->image[yy + 1]; UINT8 *line2 = (UINT8 *)imIn->image[yy + 2]; @@ -981,74 +983,116 @@ ImagingReduce5x5(Imaging imOut, Imaging imIn, int box[4]) UINT8 *line4 = (UINT8 *)imIn->image[yy + 4]; if (imIn->bands == 2) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8] + line0[xx*4 + 12] + line0[xx*4 + 16] + - line1[xx*4 + 0] + line1[xx*4 + 4] + line1[xx*4 + 8] + line1[xx*4 + 12] + line1[xx*4 + 16] + - line2[xx*4 + 0] + line2[xx*4 + 4] + line2[xx*4 + 8] + line2[xx*4 + 12] + line2[xx*4 + 16] + - line3[xx*4 + 0] + line3[xx*4 + 4] + line3[xx*4 + 8] + line3[xx*4 + 12] + line3[xx*4 + 16] + - line4[xx*4 + 0] + line4[xx*4 + 4] + line4[xx*4 + 8] + line4[xx*4 + 12] + line4[xx*4 + 16]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + line0[xx*4 + 11] + line0[xx*4 + 15] + line0[xx*4 + 19] + - line1[xx*4 + 3] + line1[xx*4 + 7] + line1[xx*4 + 11] + line1[xx*4 + 15] + line1[xx*4 + 19] + - line2[xx*4 + 3] + line2[xx*4 + 7] + line2[xx*4 + 11] + line2[xx*4 + 15] + line2[xx*4 + 19] + - line3[xx*4 + 3] + line3[xx*4 + 7] + line3[xx*4 + 11] + line3[xx*4 + 15] + line3[xx*4 + 19] + - line4[xx*4 + 3] + line4[xx*4 + 7] + line4[xx*4 + 11] + line4[xx*4 + 15] + line4[xx*4 + 19]; + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8] + + line0[xx * 4 + 12] + line0[xx * 4 + 16] + line1[xx * 4 + 0] + + line1[xx * 4 + 4] + line1[xx * 4 + 8] + line1[xx * 4 + 12] + + line1[xx * 4 + 16] + line2[xx * 4 + 0] + line2[xx * 4 + 4] + + line2[xx * 4 + 8] + line2[xx * 4 + 12] + line2[xx * 4 + 16] + + line3[xx * 4 + 0] + line3[xx * 4 + 4] + line3[xx * 4 + 8] + + line3[xx * 4 + 12] + line3[xx * 4 + 16] + line4[xx * 4 + 0] + + line4[xx * 4 + 4] + line4[xx * 4 + 8] + line4[xx * 4 + 12] + + line4[xx * 4 + 16]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line0[xx * 4 + 11] + + line0[xx * 4 + 15] + line0[xx * 4 + 19] + line1[xx * 4 + 3] + + line1[xx * 4 + 7] + line1[xx * 4 + 11] + line1[xx * 4 + 15] + + line1[xx * 4 + 19] + line2[xx * 4 + 3] + line2[xx * 4 + 7] + + line2[xx * 4 + 11] + line2[xx * 4 + 15] + line2[xx * 4 + 19] + + line3[xx * 4 + 3] + line3[xx * 4 + 7] + line3[xx * 4 + 11] + + line3[xx * 4 + 15] + line3[xx * 4 + 19] + line4[xx * 4 + 3] + + line4[xx * 4 + 7] + line4[xx * 4 + 11] + line4[xx * 4 + 15] + + line4[xx * 4 + 19]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, 0, - 0, ((ss3 + amend) * multiplier) >> 24); + ((ss0 + amend) * multiplier) >> 24, + 0, + 0, + ((ss3 + amend) * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else if (imIn->bands == 3) { for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8] + line0[xx*4 + 12] + line0[xx*4 + 16] + - line1[xx*4 + 0] + line1[xx*4 + 4] + line1[xx*4 + 8] + line1[xx*4 + 12] + line1[xx*4 + 16] + - line2[xx*4 + 0] + line2[xx*4 + 4] + line2[xx*4 + 8] + line2[xx*4 + 12] + line2[xx*4 + 16] + - line3[xx*4 + 0] + line3[xx*4 + 4] + line3[xx*4 + 8] + line3[xx*4 + 12] + line3[xx*4 + 16] + - line4[xx*4 + 0] + line4[xx*4 + 4] + line4[xx*4 + 8] + line4[xx*4 + 12] + line4[xx*4 + 16]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + line0[xx*4 + 9] + line0[xx*4 + 13] + line0[xx*4 + 17] + - line1[xx*4 + 1] + line1[xx*4 + 5] + line1[xx*4 + 9] + line1[xx*4 + 13] + line1[xx*4 + 17] + - line2[xx*4 + 1] + line2[xx*4 + 5] + line2[xx*4 + 9] + line2[xx*4 + 13] + line2[xx*4 + 17] + - line3[xx*4 + 1] + line3[xx*4 + 5] + line3[xx*4 + 9] + line3[xx*4 + 13] + line3[xx*4 + 17] + - line4[xx*4 + 1] + line4[xx*4 + 5] + line4[xx*4 + 9] + line4[xx*4 + 13] + line4[xx*4 + 17]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + line0[xx*4 + 10] + line0[xx*4 + 14] + line0[xx*4 + 18] + - line1[xx*4 + 2] + line1[xx*4 + 6] + line1[xx*4 + 10] + line1[xx*4 + 14] + line1[xx*4 + 18] + - line2[xx*4 + 2] + line2[xx*4 + 6] + line2[xx*4 + 10] + line2[xx*4 + 14] + line2[xx*4 + 18] + - line3[xx*4 + 2] + line3[xx*4 + 6] + line3[xx*4 + 10] + line3[xx*4 + 14] + line3[xx*4 + 18] + - line4[xx*4 + 2] + line4[xx*4 + 6] + line4[xx*4 + 10] + line4[xx*4 + 14] + line4[xx*4 + 18]; + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8] + + line0[xx * 4 + 12] + line0[xx * 4 + 16] + line1[xx * 4 + 0] + + line1[xx * 4 + 4] + line1[xx * 4 + 8] + line1[xx * 4 + 12] + + line1[xx * 4 + 16] + line2[xx * 4 + 0] + line2[xx * 4 + 4] + + line2[xx * 4 + 8] + line2[xx * 4 + 12] + line2[xx * 4 + 16] + + line3[xx * 4 + 0] + line3[xx * 4 + 4] + line3[xx * 4 + 8] + + line3[xx * 4 + 12] + line3[xx * 4 + 16] + line4[xx * 4 + 0] + + line4[xx * 4 + 4] + line4[xx * 4 + 8] + line4[xx * 4 + 12] + + line4[xx * 4 + 16]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line0[xx * 4 + 9] + + line0[xx * 4 + 13] + line0[xx * 4 + 17] + line1[xx * 4 + 1] + + line1[xx * 4 + 5] + line1[xx * 4 + 9] + line1[xx * 4 + 13] + + line1[xx * 4 + 17] + line2[xx * 4 + 1] + line2[xx * 4 + 5] + + line2[xx * 4 + 9] + line2[xx * 4 + 13] + line2[xx * 4 + 17] + + line3[xx * 4 + 1] + line3[xx * 4 + 5] + line3[xx * 4 + 9] + + line3[xx * 4 + 13] + line3[xx * 4 + 17] + line4[xx * 4 + 1] + + line4[xx * 4 + 5] + line4[xx * 4 + 9] + line4[xx * 4 + 13] + + line4[xx * 4 + 17]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line0[xx * 4 + 10] + + line0[xx * 4 + 14] + line0[xx * 4 + 18] + line1[xx * 4 + 2] + + line1[xx * 4 + 6] + line1[xx * 4 + 10] + line1[xx * 4 + 14] + + line1[xx * 4 + 18] + line2[xx * 4 + 2] + line2[xx * 4 + 6] + + line2[xx * 4 + 10] + line2[xx * 4 + 14] + line2[xx * 4 + 18] + + line3[xx * 4 + 2] + line3[xx * 4 + 6] + line3[xx * 4 + 10] + + line3[xx * 4 + 14] + line3[xx * 4 + 18] + line4[xx * 4 + 2] + + line4[xx * 4 + 6] + line4[xx * 4 + 10] + line4[xx * 4 + 14] + + line4[xx * 4 + 18]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, ((ss1 + amend) * multiplier) >> 24, - ((ss2 + amend) * multiplier) >> 24, 0); + ((ss0 + amend) * multiplier) >> 24, + ((ss1 + amend) * multiplier) >> 24, + ((ss2 + amend) * multiplier) >> 24, + 0); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } else { // bands == 4 for (x = 0; x < box[2] / xscale; x++) { - int xx = box[0] + x*xscale; + int xx = box[0] + x * xscale; UINT32 v; - ss0 = line0[xx*4 + 0] + line0[xx*4 + 4] + line0[xx*4 + 8] + line0[xx*4 + 12] + line0[xx*4 + 16] + - line1[xx*4 + 0] + line1[xx*4 + 4] + line1[xx*4 + 8] + line1[xx*4 + 12] + line1[xx*4 + 16] + - line2[xx*4 + 0] + line2[xx*4 + 4] + line2[xx*4 + 8] + line2[xx*4 + 12] + line2[xx*4 + 16] + - line3[xx*4 + 0] + line3[xx*4 + 4] + line3[xx*4 + 8] + line3[xx*4 + 12] + line3[xx*4 + 16] + - line4[xx*4 + 0] + line4[xx*4 + 4] + line4[xx*4 + 8] + line4[xx*4 + 12] + line4[xx*4 + 16]; - ss1 = line0[xx*4 + 1] + line0[xx*4 + 5] + line0[xx*4 + 9] + line0[xx*4 + 13] + line0[xx*4 + 17] + - line1[xx*4 + 1] + line1[xx*4 + 5] + line1[xx*4 + 9] + line1[xx*4 + 13] + line1[xx*4 + 17] + - line2[xx*4 + 1] + line2[xx*4 + 5] + line2[xx*4 + 9] + line2[xx*4 + 13] + line2[xx*4 + 17] + - line3[xx*4 + 1] + line3[xx*4 + 5] + line3[xx*4 + 9] + line3[xx*4 + 13] + line3[xx*4 + 17] + - line4[xx*4 + 1] + line4[xx*4 + 5] + line4[xx*4 + 9] + line4[xx*4 + 13] + line4[xx*4 + 17]; - ss2 = line0[xx*4 + 2] + line0[xx*4 + 6] + line0[xx*4 + 10] + line0[xx*4 + 14] + line0[xx*4 + 18] + - line1[xx*4 + 2] + line1[xx*4 + 6] + line1[xx*4 + 10] + line1[xx*4 + 14] + line1[xx*4 + 18] + - line2[xx*4 + 2] + line2[xx*4 + 6] + line2[xx*4 + 10] + line2[xx*4 + 14] + line2[xx*4 + 18] + - line3[xx*4 + 2] + line3[xx*4 + 6] + line3[xx*4 + 10] + line3[xx*4 + 14] + line3[xx*4 + 18] + - line4[xx*4 + 2] + line4[xx*4 + 6] + line4[xx*4 + 10] + line4[xx*4 + 14] + line4[xx*4 + 18]; - ss3 = line0[xx*4 + 3] + line0[xx*4 + 7] + line0[xx*4 + 11] + line0[xx*4 + 15] + line0[xx*4 + 19] + - line1[xx*4 + 3] + line1[xx*4 + 7] + line1[xx*4 + 11] + line1[xx*4 + 15] + line1[xx*4 + 19] + - line2[xx*4 + 3] + line2[xx*4 + 7] + line2[xx*4 + 11] + line2[xx*4 + 15] + line2[xx*4 + 19] + - line3[xx*4 + 3] + line3[xx*4 + 7] + line3[xx*4 + 11] + line3[xx*4 + 15] + line3[xx*4 + 19] + - line4[xx*4 + 3] + line4[xx*4 + 7] + line4[xx*4 + 11] + line4[xx*4 + 15] + line4[xx*4 + 19]; + ss0 = line0[xx * 4 + 0] + line0[xx * 4 + 4] + line0[xx * 4 + 8] + + line0[xx * 4 + 12] + line0[xx * 4 + 16] + line1[xx * 4 + 0] + + line1[xx * 4 + 4] + line1[xx * 4 + 8] + line1[xx * 4 + 12] + + line1[xx * 4 + 16] + line2[xx * 4 + 0] + line2[xx * 4 + 4] + + line2[xx * 4 + 8] + line2[xx * 4 + 12] + line2[xx * 4 + 16] + + line3[xx * 4 + 0] + line3[xx * 4 + 4] + line3[xx * 4 + 8] + + line3[xx * 4 + 12] + line3[xx * 4 + 16] + line4[xx * 4 + 0] + + line4[xx * 4 + 4] + line4[xx * 4 + 8] + line4[xx * 4 + 12] + + line4[xx * 4 + 16]; + ss1 = line0[xx * 4 + 1] + line0[xx * 4 + 5] + line0[xx * 4 + 9] + + line0[xx * 4 + 13] + line0[xx * 4 + 17] + line1[xx * 4 + 1] + + line1[xx * 4 + 5] + line1[xx * 4 + 9] + line1[xx * 4 + 13] + + line1[xx * 4 + 17] + line2[xx * 4 + 1] + line2[xx * 4 + 5] + + line2[xx * 4 + 9] + line2[xx * 4 + 13] + line2[xx * 4 + 17] + + line3[xx * 4 + 1] + line3[xx * 4 + 5] + line3[xx * 4 + 9] + + line3[xx * 4 + 13] + line3[xx * 4 + 17] + line4[xx * 4 + 1] + + line4[xx * 4 + 5] + line4[xx * 4 + 9] + line4[xx * 4 + 13] + + line4[xx * 4 + 17]; + ss2 = line0[xx * 4 + 2] + line0[xx * 4 + 6] + line0[xx * 4 + 10] + + line0[xx * 4 + 14] + line0[xx * 4 + 18] + line1[xx * 4 + 2] + + line1[xx * 4 + 6] + line1[xx * 4 + 10] + line1[xx * 4 + 14] + + line1[xx * 4 + 18] + line2[xx * 4 + 2] + line2[xx * 4 + 6] + + line2[xx * 4 + 10] + line2[xx * 4 + 14] + line2[xx * 4 + 18] + + line3[xx * 4 + 2] + line3[xx * 4 + 6] + line3[xx * 4 + 10] + + line3[xx * 4 + 14] + line3[xx * 4 + 18] + line4[xx * 4 + 2] + + line4[xx * 4 + 6] + line4[xx * 4 + 10] + line4[xx * 4 + 14] + + line4[xx * 4 + 18]; + ss3 = line0[xx * 4 + 3] + line0[xx * 4 + 7] + line0[xx * 4 + 11] + + line0[xx * 4 + 15] + line0[xx * 4 + 19] + line1[xx * 4 + 3] + + line1[xx * 4 + 7] + line1[xx * 4 + 11] + line1[xx * 4 + 15] + + line1[xx * 4 + 19] + line2[xx * 4 + 3] + line2[xx * 4 + 7] + + line2[xx * 4 + 11] + line2[xx * 4 + 15] + line2[xx * 4 + 19] + + line3[xx * 4 + 3] + line3[xx * 4 + 7] + line3[xx * 4 + 11] + + line3[xx * 4 + 15] + line3[xx * 4 + 19] + line4[xx * 4 + 3] + + line4[xx * 4 + 7] + line4[xx * 4 + 11] + line4[xx * 4 + 15] + + line4[xx * 4 + 19]; v = MAKE_UINT32( - ((ss0 + amend) * multiplier) >> 24, ((ss1 + amend) * multiplier) >> 24, - ((ss2 + amend) * multiplier) >> 24, ((ss3 + amend) * multiplier) >> 24); + ((ss0 + amend) * multiplier) >> 24, + ((ss1 + amend) * multiplier) >> 24, + ((ss2 + amend) * multiplier) >> 24, + ((ss3 + amend) * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -1056,12 +1100,10 @@ ImagingReduce5x5(Imaging imOut, Imaging imIn, int box[4]) } } - void -ImagingReduceCorners(Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale) -{ +ImagingReduceCorners(Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale) { /* Fill the last row and the last column for any xscale and yscale. - */ + */ int x, y, xx, yy; if (imIn->image8) { @@ -1070,13 +1112,13 @@ ImagingReduceCorners(Imaging imOut, Imaging imIn, int box[4], int xscale, int ys UINT32 multiplier = division_UINT32(scale, 8); UINT32 amend = scale / 2; for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; + int yy_from = box[1] + y * yscale; UINT32 ss = amend; x = box[2] / xscale; for (yy = yy_from; yy < yy_from + yscale; yy++) { UINT8 *line = (UINT8 *)imIn->image8[yy]; - for (xx = box[0] + x*xscale; xx < box[0] + box[2]; xx++) { + for (xx = box[0] + x * xscale; xx < box[0] + box[2]; xx++) { ss += line[xx + 0]; } } @@ -1089,9 +1131,9 @@ ImagingReduceCorners(Imaging imOut, Imaging imIn, int box[4], int xscale, int ys UINT32 amend = scale / 2; y = box[3] / yscale; for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 ss = amend; - for (yy = box[1] + y*yscale; yy < box[1] + box[3]; yy++) { + for (yy = box[1] + y * yscale; yy < box[1] + box[3]; yy++) { UINT8 *line = (UINT8 *)imIn->image8[yy]; for (xx = xx_from; xx < xx_from + xscale; xx++) { ss += line[xx + 0]; @@ -1107,9 +1149,9 @@ ImagingReduceCorners(Imaging imOut, Imaging imIn, int box[4], int xscale, int ys UINT32 ss = amend; x = box[2] / xscale; y = box[3] / yscale; - for (yy = box[1] + y*yscale; yy < box[1] + box[3]; yy++) { + for (yy = box[1] + y * yscale; yy < box[1] + box[3]; yy++) { UINT8 *line = (UINT8 *)imIn->image8[yy]; - for (xx = box[0] + x*xscale; xx < box[0] + box[2]; xx++) { + for (xx = box[0] + x * xscale; xx < box[0] + box[2]; xx++) { ss += line[xx + 0]; } } @@ -1121,23 +1163,25 @@ ImagingReduceCorners(Imaging imOut, Imaging imIn, int box[4], int xscale, int ys UINT32 multiplier = division_UINT32(scale, 8); UINT32 amend = scale / 2; for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; + int yy_from = box[1] + y * yscale; UINT32 v; UINT32 ss0 = amend, ss1 = amend, ss2 = amend, ss3 = amend; x = box[2] / xscale; for (yy = yy_from; yy < yy_from + yscale; yy++) { UINT8 *line = (UINT8 *)imIn->image[yy]; - for (xx = box[0] + x*xscale; xx < box[0] + box[2]; xx++) { - ss0 += line[xx*4 + 0]; - ss1 += line[xx*4 + 1]; - ss2 += line[xx*4 + 2]; - ss3 += line[xx*4 + 3]; + for (xx = box[0] + x * xscale; xx < box[0] + box[2]; xx++) { + ss0 += line[xx * 4 + 0]; + ss1 += line[xx * 4 + 1]; + ss2 += line[xx * 4 + 2]; + ss3 += line[xx * 4 + 3]; } } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, (ss1 * multiplier) >> 24, - (ss2 * multiplier) >> 24, (ss3 * multiplier) >> 24); + (ss0 * multiplier) >> 24, + (ss1 * multiplier) >> 24, + (ss2 * multiplier) >> 24, + (ss3 * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -1147,21 +1191,23 @@ ImagingReduceCorners(Imaging imOut, Imaging imIn, int box[4], int xscale, int ys UINT32 amend = scale / 2; y = box[3] / yscale; for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; + int xx_from = box[0] + x * xscale; UINT32 v; UINT32 ss0 = amend, ss1 = amend, ss2 = amend, ss3 = amend; - for (yy = box[1] + y*yscale; yy < box[1] + box[3]; yy++) { + for (yy = box[1] + y * yscale; yy < box[1] + box[3]; yy++) { UINT8 *line = (UINT8 *)imIn->image[yy]; for (xx = xx_from; xx < xx_from + xscale; xx++) { - ss0 += line[xx*4 + 0]; - ss1 += line[xx*4 + 1]; - ss2 += line[xx*4 + 2]; - ss3 += line[xx*4 + 3]; + ss0 += line[xx * 4 + 0]; + ss1 += line[xx * 4 + 1]; + ss2 += line[xx * 4 + 2]; + ss3 += line[xx * 4 + 3]; } } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, (ss1 * multiplier) >> 24, - (ss2 * multiplier) >> 24, (ss3 * multiplier) >> 24); + (ss0 * multiplier) >> 24, + (ss1 * multiplier) >> 24, + (ss2 * multiplier) >> 24, + (ss3 * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } @@ -1173,265 +1219,262 @@ ImagingReduceCorners(Imaging imOut, Imaging imIn, int box[4], int xscale, int ys UINT32 ss0 = amend, ss1 = amend, ss2 = amend, ss3 = amend; x = box[2] / xscale; y = box[3] / yscale; - for (yy = box[1] + y*yscale; yy < box[1] + box[3]; yy++) { + for (yy = box[1] + y * yscale; yy < box[1] + box[3]; yy++) { UINT8 *line = (UINT8 *)imIn->image[yy]; - for (xx = box[0] + x*xscale; xx < box[0] + box[2]; xx++) { - ss0 += line[xx*4 + 0]; - ss1 += line[xx*4 + 1]; - ss2 += line[xx*4 + 2]; - ss3 += line[xx*4 + 3]; + for (xx = box[0] + x * xscale; xx < box[0] + box[2]; xx++) { + ss0 += line[xx * 4 + 0]; + ss1 += line[xx * 4 + 1]; + ss2 += line[xx * 4 + 2]; + ss3 += line[xx * 4 + 3]; } } v = MAKE_UINT32( - (ss0 * multiplier) >> 24, (ss1 * multiplier) >> 24, - (ss2 * multiplier) >> 24, (ss3 * multiplier) >> 24); + (ss0 * multiplier) >> 24, + (ss1 * multiplier) >> 24, + (ss2 * multiplier) >> 24, + (ss3 * multiplier) >> 24); memcpy(imOut->image[y] + x * sizeof(v), &v, sizeof(v)); } } } - void -ImagingReduceNxN_32bpc(Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale) -{ +ImagingReduceNxN_32bpc( + Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale) { /* The most general implementation for any xscale and yscale - */ + */ int x, y, xx, yy; double multiplier = 1.0 / (yscale * xscale); - switch(imIn->type) { - case IMAGING_TYPE_INT32: - for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; - for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; - double ss = 0; - for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { - INT32 *line0 = (INT32 *)imIn->image32[yy]; - INT32 *line1 = (INT32 *)imIn->image32[yy + 1]; - for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss += line0[xx + 0] + line0[xx + 1] + - line1[xx + 0] + line1[xx + 1]; + switch (imIn->type) { + case IMAGING_TYPE_INT32: + for (y = 0; y < box[3] / yscale; y++) { + int yy_from = box[1] + y * yscale; + for (x = 0; x < box[2] / xscale; x++) { + int xx_from = box[0] + x * xscale; + double ss = 0; + for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { + INT32 *line0 = (INT32 *)imIn->image32[yy]; + INT32 *line1 = (INT32 *)imIn->image32[yy + 1]; + for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { + ss += line0[xx + 0] + line0[xx + 1] + line1[xx + 0] + + line1[xx + 1]; + } + if (xscale & 0x01) { + ss += line0[xx + 0] + line1[xx + 0]; + } } - if (xscale & 0x01) { - ss += line0[xx + 0] + line1[xx + 0]; + if (yscale & 0x01) { + INT32 *line = (INT32 *)imIn->image32[yy]; + for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { + ss += line[xx + 0] + line[xx + 1]; + } + if (xscale & 0x01) { + ss += line[xx + 0]; + } } + IMAGING_PIXEL_I(imOut, x, y) = ROUND_UP(ss * multiplier); } - if (yscale & 0x01) { - INT32 *line = (INT32 *)imIn->image32[yy]; - for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss += line[xx + 0] + line[xx + 1]; - } - if (xscale & 0x01) { - ss += line[xx + 0]; - } - } - IMAGING_PIXEL_I(imOut, x, y) = ROUND_UP(ss * multiplier); } - } - break; + break; - case IMAGING_TYPE_FLOAT32: - for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; - for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; - double ss = 0; - for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { - FLOAT32 *line0 = (FLOAT32 *)imIn->image32[yy]; - FLOAT32 *line1 = (FLOAT32 *)imIn->image32[yy + 1]; - for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss += line0[xx + 0] + line0[xx + 1] + - line1[xx + 0] + line1[xx + 1]; + case IMAGING_TYPE_FLOAT32: + for (y = 0; y < box[3] / yscale; y++) { + int yy_from = box[1] + y * yscale; + for (x = 0; x < box[2] / xscale; x++) { + int xx_from = box[0] + x * xscale; + double ss = 0; + for (yy = yy_from; yy < yy_from + yscale - 1; yy += 2) { + FLOAT32 *line0 = (FLOAT32 *)imIn->image32[yy]; + FLOAT32 *line1 = (FLOAT32 *)imIn->image32[yy + 1]; + for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { + ss += line0[xx + 0] + line0[xx + 1] + line1[xx + 0] + + line1[xx + 1]; + } + if (xscale & 0x01) { + ss += line0[xx + 0] + line1[xx + 0]; + } } - if (xscale & 0x01) { - ss += line0[xx + 0] + line1[xx + 0]; + if (yscale & 0x01) { + FLOAT32 *line = (FLOAT32 *)imIn->image32[yy]; + for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { + ss += line[xx + 0] + line[xx + 1]; + } + if (xscale & 0x01) { + ss += line[xx + 0]; + } } + IMAGING_PIXEL_F(imOut, x, y) = ss * multiplier; } - if (yscale & 0x01) { - FLOAT32 *line = (FLOAT32 *)imIn->image32[yy]; - for (xx = xx_from; xx < xx_from + xscale - 1; xx += 2) { - ss += line[xx + 0] + line[xx + 1]; - } - if (xscale & 0x01) { - ss += line[xx + 0]; - } - } - IMAGING_PIXEL_F(imOut, x, y) = ss * multiplier; } - } - break; + break; } } - void -ImagingReduceCorners_32bpc(Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale) -{ +ImagingReduceCorners_32bpc( + Imaging imOut, Imaging imIn, int box[4], int xscale, int yscale) { /* Fill the last row and the last column for any xscale and yscale. - */ + */ int x, y, xx, yy; - switch(imIn->type) { - case IMAGING_TYPE_INT32: - if (box[2] % xscale) { - double multiplier = 1.0 / ((box[2] % xscale) * yscale); - for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; + switch (imIn->type) { + case IMAGING_TYPE_INT32: + if (box[2] % xscale) { + double multiplier = 1.0 / ((box[2] % xscale) * yscale); + for (y = 0; y < box[3] / yscale; y++) { + int yy_from = box[1] + y * yscale; + double ss = 0; + x = box[2] / xscale; + for (yy = yy_from; yy < yy_from + yscale; yy++) { + INT32 *line = (INT32 *)imIn->image32[yy]; + for (xx = box[0] + x * xscale; xx < box[0] + box[2]; xx++) { + ss += line[xx + 0]; + } + } + IMAGING_PIXEL_I(imOut, x, y) = ROUND_UP(ss * multiplier); + } + } + if (box[3] % yscale) { + double multiplier = 1.0 / (xscale * (box[3] % yscale)); + y = box[3] / yscale; + for (x = 0; x < box[2] / xscale; x++) { + int xx_from = box[0] + x * xscale; + double ss = 0; + for (yy = box[1] + y * yscale; yy < box[1] + box[3]; yy++) { + INT32 *line = (INT32 *)imIn->image32[yy]; + for (xx = xx_from; xx < xx_from + xscale; xx++) { + ss += line[xx + 0]; + } + } + IMAGING_PIXEL_I(imOut, x, y) = ROUND_UP(ss * multiplier); + } + } + if (box[2] % xscale && box[3] % yscale) { + double multiplier = 1.0 / ((box[2] % xscale) * (box[3] % yscale)); double ss = 0; x = box[2] / xscale; - for (yy = yy_from; yy < yy_from + yscale; yy++) { + y = box[3] / yscale; + for (yy = box[1] + y * yscale; yy < box[1] + box[3]; yy++) { INT32 *line = (INT32 *)imIn->image32[yy]; - for (xx = box[0] + x*xscale; xx < box[0] + box[2]; xx++) { + for (xx = box[0] + x * xscale; xx < box[0] + box[2]; xx++) { ss += line[xx + 0]; } } IMAGING_PIXEL_I(imOut, x, y) = ROUND_UP(ss * multiplier); } - } - if (box[3] % yscale) { - double multiplier = 1.0 / (xscale * (box[3] % yscale)); - y = box[3] / yscale; - for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; - double ss = 0; - for (yy = box[1] + y*yscale; yy < box[1] + box[3]; yy++) { - INT32 *line = (INT32 *)imIn->image32[yy]; - for (xx = xx_from; xx < xx_from + xscale; xx++) { - ss += line[xx + 0]; - } - } - IMAGING_PIXEL_I(imOut, x, y) = ROUND_UP(ss * multiplier); - } - } - if (box[2] % xscale && box[3] % yscale) { - double multiplier = 1.0 / ((box[2] % xscale) * (box[3] % yscale)); - double ss = 0; - x = box[2] / xscale; - y = box[3] / yscale; - for (yy = box[1] + y*yscale; yy < box[1] + box[3]; yy++) { - INT32 *line = (INT32 *)imIn->image32[yy]; - for (xx = box[0] + x*xscale; xx < box[0] + box[2]; xx++) { - ss += line[xx + 0]; - } - } - IMAGING_PIXEL_I(imOut, x, y) = ROUND_UP(ss * multiplier); - } - break; + break; - case IMAGING_TYPE_FLOAT32: - if (box[2] % xscale) { - double multiplier = 1.0 / ((box[2] % xscale) * yscale); - for (y = 0; y < box[3] / yscale; y++) { - int yy_from = box[1] + y*yscale; + case IMAGING_TYPE_FLOAT32: + if (box[2] % xscale) { + double multiplier = 1.0 / ((box[2] % xscale) * yscale); + for (y = 0; y < box[3] / yscale; y++) { + int yy_from = box[1] + y * yscale; + double ss = 0; + x = box[2] / xscale; + for (yy = yy_from; yy < yy_from + yscale; yy++) { + FLOAT32 *line = (FLOAT32 *)imIn->image32[yy]; + for (xx = box[0] + x * xscale; xx < box[0] + box[2]; xx++) { + ss += line[xx + 0]; + } + } + IMAGING_PIXEL_F(imOut, x, y) = ss * multiplier; + } + } + if (box[3] % yscale) { + double multiplier = 1.0 / (xscale * (box[3] % yscale)); + y = box[3] / yscale; + for (x = 0; x < box[2] / xscale; x++) { + int xx_from = box[0] + x * xscale; + double ss = 0; + for (yy = box[1] + y * yscale; yy < box[1] + box[3]; yy++) { + FLOAT32 *line = (FLOAT32 *)imIn->image32[yy]; + for (xx = xx_from; xx < xx_from + xscale; xx++) { + ss += line[xx + 0]; + } + } + IMAGING_PIXEL_F(imOut, x, y) = ss * multiplier; + } + } + if (box[2] % xscale && box[3] % yscale) { + double multiplier = 1.0 / ((box[2] % xscale) * (box[3] % yscale)); double ss = 0; x = box[2] / xscale; - for (yy = yy_from; yy < yy_from + yscale; yy++) { + y = box[3] / yscale; + for (yy = box[1] + y * yscale; yy < box[1] + box[3]; yy++) { FLOAT32 *line = (FLOAT32 *)imIn->image32[yy]; - for (xx = box[0] + x*xscale; xx < box[0] + box[2]; xx++) { + for (xx = box[0] + x * xscale; xx < box[0] + box[2]; xx++) { ss += line[xx + 0]; } } IMAGING_PIXEL_F(imOut, x, y) = ss * multiplier; } - } - if (box[3] % yscale) { - double multiplier = 1.0 / (xscale * (box[3] % yscale)); - y = box[3] / yscale; - for (x = 0; x < box[2] / xscale; x++) { - int xx_from = box[0] + x*xscale; - double ss = 0; - for (yy = box[1] + y*yscale; yy < box[1] + box[3]; yy++) { - FLOAT32 *line = (FLOAT32 *)imIn->image32[yy]; - for (xx = xx_from; xx < xx_from + xscale; xx++) { - ss += line[xx + 0]; - } - } - IMAGING_PIXEL_F(imOut, x, y) = ss * multiplier; - } - } - if (box[2] % xscale && box[3] % yscale) { - double multiplier = 1.0 / ((box[2] % xscale) * (box[3] % yscale)); - double ss = 0; - x = box[2] / xscale; - y = box[3] / yscale; - for (yy = box[1] + y*yscale; yy < box[1] + box[3]; yy++) { - FLOAT32 *line = (FLOAT32 *)imIn->image32[yy]; - for (xx = box[0] + x*xscale; xx < box[0] + box[2]; xx++) { - ss += line[xx + 0]; - } - } - IMAGING_PIXEL_F(imOut, x, y) = ss * multiplier; - } - break; + break; } } - Imaging -ImagingReduce(Imaging imIn, int xscale, int yscale, int box[4]) -{ +ImagingReduce(Imaging imIn, int xscale, int yscale, int box[4]) { ImagingSectionCookie cookie; Imaging imOut = NULL; if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "1") == 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (imIn->type == IMAGING_TYPE_SPECIAL) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } - imOut = ImagingNewDirty(imIn->mode, - (box[2] + xscale - 1) / xscale, - (box[3] + yscale - 1) / yscale); - if ( ! imOut) { + imOut = ImagingNewDirty( + imIn->mode, (box[2] + xscale - 1) / xscale, (box[3] + yscale - 1) / yscale); + if (!imOut) { return NULL; } ImagingSectionEnter(&cookie); - switch(imIn->type) { - case IMAGING_TYPE_UINT8: - if (xscale == 1) { - if (yscale == 2) { - ImagingReduce1x2(imOut, imIn, box); - } else if (yscale == 3) { - ImagingReduce1x3(imOut, imIn, box); + switch (imIn->type) { + case IMAGING_TYPE_UINT8: + if (xscale == 1) { + if (yscale == 2) { + ImagingReduce1x2(imOut, imIn, box); + } else if (yscale == 3) { + ImagingReduce1x3(imOut, imIn, box); + } else { + ImagingReduce1xN(imOut, imIn, box, yscale); + } + } else if (yscale == 1) { + if (xscale == 2) { + ImagingReduce2x1(imOut, imIn, box); + } else if (xscale == 3) { + ImagingReduce3x1(imOut, imIn, box); + } else { + ImagingReduceNx1(imOut, imIn, box, xscale); + } + } else if (xscale == yscale && xscale <= 5) { + if (xscale == 2) { + ImagingReduce2x2(imOut, imIn, box); + } else if (xscale == 3) { + ImagingReduce3x3(imOut, imIn, box); + } else if (xscale == 4) { + ImagingReduce4x4(imOut, imIn, box); + } else { + ImagingReduce5x5(imOut, imIn, box); + } } else { - ImagingReduce1xN(imOut, imIn, box, yscale); + ImagingReduceNxN(imOut, imIn, box, xscale, yscale); } - } else if (yscale == 1) { - if (xscale == 2) { - ImagingReduce2x1(imOut, imIn, box); - } else if (xscale == 3) { - ImagingReduce3x1(imOut, imIn, box); - } else { - ImagingReduceNx1(imOut, imIn, box, xscale); - } - } else if (xscale == yscale && xscale <= 5) { - if (xscale == 2) { - ImagingReduce2x2(imOut, imIn, box); - } else if (xscale == 3) { - ImagingReduce3x3(imOut, imIn, box); - } else if (xscale == 4) { - ImagingReduce4x4(imOut, imIn, box); - } else { - ImagingReduce5x5(imOut, imIn, box); - } - } else { - ImagingReduceNxN(imOut, imIn, box, xscale, yscale); - } - ImagingReduceCorners(imOut, imIn, box, xscale, yscale); - break; + ImagingReduceCorners(imOut, imIn, box, xscale, yscale); + break; - case IMAGING_TYPE_INT32: - case IMAGING_TYPE_FLOAT32: - ImagingReduceNxN_32bpc(imOut, imIn, box, xscale, yscale); + case IMAGING_TYPE_INT32: + case IMAGING_TYPE_FLOAT32: + ImagingReduceNxN_32bpc(imOut, imIn, box, xscale, yscale); - ImagingReduceCorners_32bpc(imOut, imIn, box, xscale, yscale); - break; + ImagingReduceCorners_32bpc(imOut, imIn, box, xscale, yscale); + break; } ImagingSectionLeave(&cookie); diff --git a/src/libImaging/Resample.c b/src/libImaging/Resample.c index b12e023f8..cf79d8a4e 100644 --- a/src/libImaging/Resample.c +++ b/src/libImaging/Resample.c @@ -2,36 +2,34 @@ #include - -#define ROUND_UP(f) ((int) ((f) >= 0.0 ? (f) + 0.5F : (f) - 0.5F)) - +#define ROUND_UP(f) ((int)((f) >= 0.0 ? (f) + 0.5F : (f)-0.5F)) struct filter { double (*filter)(double x); double support; }; -static inline double box_filter(double x) -{ +static inline double +box_filter(double x) { if (x > -0.5 && x <= 0.5) { return 1.0; } return 0.0; } -static inline double bilinear_filter(double x) -{ +static inline double +bilinear_filter(double x) { if (x < 0.0) { x = -x; } if (x < 1.0) { - return 1.0-x; + return 1.0 - x; } return 0.0; } -static inline double hamming_filter(double x) -{ +static inline double +hamming_filter(double x) { if (x < 0.0) { x = -x; } @@ -45,15 +43,16 @@ static inline double hamming_filter(double x) return sin(x) / x * (0.54f + 0.46f * cos(x)); } -static inline double bicubic_filter(double x) -{ - /* https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm */ +static inline double +bicubic_filter(double x) { + /* https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm + */ #define a -0.5 if (x < 0.0) { x = -x; } if (x < 1.0) { - return ((a + 2.0) * x - (a + 3.0)) * x*x + 1; + return ((a + 2.0) * x - (a + 3.0)) * x * x + 1; } if (x < 2.0) { return (((x - 5) * x + 8) * x - 4) * a; @@ -62,8 +61,8 @@ static inline double bicubic_filter(double x) #undef a } -static inline double sinc_filter(double x) -{ +static inline double +sinc_filter(double x) { if (x == 0.0) { return 1.0; } @@ -71,21 +70,20 @@ static inline double sinc_filter(double x) return sin(x) / x; } -static inline double lanczos_filter(double x) -{ +static inline double +lanczos_filter(double x) { /* truncated sinc */ if (-3.0 <= x && x < 3.0) { - return sinc_filter(x) * sinc_filter(x/3); + return sinc_filter(x) * sinc_filter(x / 3); } return 0.0; } -static struct filter BOX = { box_filter, 0.5 }; -static struct filter BILINEAR = { bilinear_filter, 1.0 }; -static struct filter HAMMING = { hamming_filter, 1.0 }; -static struct filter BICUBIC = { bicubic_filter, 2.0 }; -static struct filter LANCZOS = { lanczos_filter, 3.0 }; - +static struct filter BOX = {box_filter, 0.5}; +static struct filter BILINEAR = {bilinear_filter, 1.0}; +static struct filter HAMMING = {hamming_filter, 1.0}; +static struct filter BICUBIC = {bicubic_filter, 2.0}; +static struct filter LANCZOS = {lanczos_filter, 3.0}; /* 8 bits for result. Filter can have negative areas. In one cases the sum of the coefficients will be negative, @@ -93,102 +91,102 @@ static struct filter LANCZOS = { lanczos_filter, 3.0 }; two extra bits for overflow and int type. */ #define PRECISION_BITS (32 - 8 - 2) - /* Handles values form -640 to 639. */ UINT8 _clip8_lookups[1280] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, - 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, - 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, - 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, + 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, + 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, + 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, + 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, + 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, + 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, + 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, + 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, + 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, + 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, }; UINT8 *clip8_lookups = &_clip8_lookups[640]; -static inline UINT8 clip8(int in) -{ +static inline UINT8 +clip8(int in) { return clip8_lookups[in >> PRECISION_BITS]; } - int -precompute_coeffs(int inSize, float in0, float in1, int outSize, - struct filter *filterp, int **boundsp, double **kkp) { +precompute_coeffs( + int inSize, + float in0, + float in1, + int outSize, + struct filter *filterp, + int **boundsp, + double **kkp) { double support, scale, filterscale; double center, ww, ss; int xx, x, ksize, xmin, xmax; @@ -196,7 +194,7 @@ precompute_coeffs(int inSize, float in0, float in1, int outSize, double *kk, *k; /* prepare for horizontal stretch */ - filterscale = scale = (double) (in1 - in0) / outSize; + filterscale = scale = (double)(in1 - in0) / outSize; if (filterscale < 1.0) { filterscale = 1.0; } @@ -205,7 +203,7 @@ precompute_coeffs(int inSize, float in0, float in1, int outSize, support = filterp->support * filterscale; /* maximum number of coeffs */ - ksize = (int) ceil(support) * 2 + 1; + ksize = (int)ceil(support) * 2 + 1; // check for overflow if (outSize > INT_MAX / (ksize * (int)sizeof(double))) { @@ -216,14 +214,14 @@ precompute_coeffs(int inSize, float in0, float in1, int outSize, /* coefficient buffer */ /* malloc check ok, overflow checked above */ kk = malloc(outSize * ksize * sizeof(double)); - if ( ! kk) { + if (!kk) { ImagingError_MemoryError(); return 0; } /* malloc check ok, ksize*sizeof(double) > 2*sizeof(int) */ bounds = malloc(outSize * 2 * sizeof(int)); - if ( ! bounds) { + if (!bounds) { free(kk); ImagingError_MemoryError(); return 0; @@ -234,12 +232,12 @@ precompute_coeffs(int inSize, float in0, float in1, int outSize, ww = 0.0; ss = 1.0 / filterscale; // Round the value - xmin = (int) (center - support + 0.5); + xmin = (int)(center - support + 0.5); if (xmin < 0) { xmin = 0; } // Round the value - xmax = (int) (center + support + 0.5); + xmax = (int)(center + support + 0.5); if (xmax > inSize) { xmax = inSize; } @@ -267,38 +265,33 @@ precompute_coeffs(int inSize, float in0, float in1, int outSize, return ksize; } - void -normalize_coeffs_8bpc(int outSize, int ksize, double *prekk) -{ +normalize_coeffs_8bpc(int outSize, int ksize, double *prekk) { int x; INT32 *kk; // use the same buffer for normalized coefficients - kk = (INT32 *) prekk; + kk = (INT32 *)prekk; for (x = 0; x < outSize * ksize; x++) { if (prekk[x] < 0) { - kk[x] = (int) (-0.5 + prekk[x] * (1 << PRECISION_BITS)); + kk[x] = (int)(-0.5 + prekk[x] * (1 << PRECISION_BITS)); } else { - kk[x] = (int) (0.5 + prekk[x] * (1 << PRECISION_BITS)); + kk[x] = (int)(0.5 + prekk[x] * (1 << PRECISION_BITS)); } } } - - void -ImagingResampleHorizontal_8bpc(Imaging imOut, Imaging imIn, int offset, - int ksize, int *bounds, double *prekk) -{ +ImagingResampleHorizontal_8bpc( + Imaging imOut, Imaging imIn, int offset, int ksize, int *bounds, double *prekk) { ImagingSectionCookie cookie; int ss0, ss1, ss2, ss3; int xx, yy, x, xmin, xmax; INT32 *k, *kk; // use the same buffer for normalized coefficients - kk = (INT32 *) prekk; + kk = (INT32 *)prekk; normalize_coeffs_8bpc(imOut->xsize, ksize, prekk); ImagingSectionEnter(&cookie); @@ -308,9 +301,9 @@ ImagingResampleHorizontal_8bpc(Imaging imOut, Imaging imIn, int offset, xmin = bounds[xx * 2 + 0]; xmax = bounds[xx * 2 + 1]; k = &kk[xx * ksize]; - ss0 = 1 << (PRECISION_BITS -1); + ss0 = 1 << (PRECISION_BITS - 1); for (x = 0; x < xmax; x++) { - ss0 += ((UINT8) imIn->image8[yy + offset][x + xmin]) * k[x]; + ss0 += ((UINT8)imIn->image8[yy + offset][x + xmin]) * k[x]; } imOut->image8[yy][xx] = clip8(ss0); } @@ -323,10 +316,12 @@ ImagingResampleHorizontal_8bpc(Imaging imOut, Imaging imIn, int offset, xmin = bounds[xx * 2 + 0]; xmax = bounds[xx * 2 + 1]; k = &kk[xx * ksize]; - ss0 = ss3 = 1 << (PRECISION_BITS -1); + ss0 = ss3 = 1 << (PRECISION_BITS - 1); for (x = 0; x < xmax; x++) { - ss0 += ((UINT8) imIn->image[yy + offset][(x + xmin)*4 + 0]) * k[x]; - ss3 += ((UINT8) imIn->image[yy + offset][(x + xmin)*4 + 3]) * k[x]; + ss0 += ((UINT8)imIn->image[yy + offset][(x + xmin) * 4 + 0]) * + k[x]; + ss3 += ((UINT8)imIn->image[yy + offset][(x + xmin) * 4 + 3]) * + k[x]; } v = MAKE_UINT32(clip8(ss0), 0, 0, clip8(ss3)); memcpy(imOut->image[yy] + xx * sizeof(v), &v, sizeof(v)); @@ -339,11 +334,14 @@ ImagingResampleHorizontal_8bpc(Imaging imOut, Imaging imIn, int offset, xmin = bounds[xx * 2 + 0]; xmax = bounds[xx * 2 + 1]; k = &kk[xx * ksize]; - ss0 = ss1 = ss2 = 1 << (PRECISION_BITS -1); + ss0 = ss1 = ss2 = 1 << (PRECISION_BITS - 1); for (x = 0; x < xmax; x++) { - ss0 += ((UINT8) imIn->image[yy + offset][(x + xmin)*4 + 0]) * k[x]; - ss1 += ((UINT8) imIn->image[yy + offset][(x + xmin)*4 + 1]) * k[x]; - ss2 += ((UINT8) imIn->image[yy + offset][(x + xmin)*4 + 2]) * k[x]; + ss0 += ((UINT8)imIn->image[yy + offset][(x + xmin) * 4 + 0]) * + k[x]; + ss1 += ((UINT8)imIn->image[yy + offset][(x + xmin) * 4 + 1]) * + k[x]; + ss2 += ((UINT8)imIn->image[yy + offset][(x + xmin) * 4 + 2]) * + k[x]; } v = MAKE_UINT32(clip8(ss0), clip8(ss1), clip8(ss2), 0); memcpy(imOut->image[yy] + xx * sizeof(v), &v, sizeof(v)); @@ -356,12 +354,16 @@ ImagingResampleHorizontal_8bpc(Imaging imOut, Imaging imIn, int offset, xmin = bounds[xx * 2 + 0]; xmax = bounds[xx * 2 + 1]; k = &kk[xx * ksize]; - ss0 = ss1 = ss2 = ss3 = 1 << (PRECISION_BITS -1); + ss0 = ss1 = ss2 = ss3 = 1 << (PRECISION_BITS - 1); for (x = 0; x < xmax; x++) { - ss0 += ((UINT8) imIn->image[yy + offset][(x + xmin)*4 + 0]) * k[x]; - ss1 += ((UINT8) imIn->image[yy + offset][(x + xmin)*4 + 1]) * k[x]; - ss2 += ((UINT8) imIn->image[yy + offset][(x + xmin)*4 + 2]) * k[x]; - ss3 += ((UINT8) imIn->image[yy + offset][(x + xmin)*4 + 3]) * k[x]; + ss0 += ((UINT8)imIn->image[yy + offset][(x + xmin) * 4 + 0]) * + k[x]; + ss1 += ((UINT8)imIn->image[yy + offset][(x + xmin) * 4 + 1]) * + k[x]; + ss2 += ((UINT8)imIn->image[yy + offset][(x + xmin) * 4 + 2]) * + k[x]; + ss3 += ((UINT8)imIn->image[yy + offset][(x + xmin) * 4 + 3]) * + k[x]; } v = MAKE_UINT32(clip8(ss0), clip8(ss1), clip8(ss2), clip8(ss3)); memcpy(imOut->image[yy] + xx * sizeof(v), &v, sizeof(v)); @@ -372,18 +374,16 @@ ImagingResampleHorizontal_8bpc(Imaging imOut, Imaging imIn, int offset, ImagingSectionLeave(&cookie); } - void -ImagingResampleVertical_8bpc(Imaging imOut, Imaging imIn, int offset, - int ksize, int *bounds, double *prekk) -{ +ImagingResampleVertical_8bpc( + Imaging imOut, Imaging imIn, int offset, int ksize, int *bounds, double *prekk) { ImagingSectionCookie cookie; int ss0, ss1, ss2, ss3; int xx, yy, y, ymin, ymax; INT32 *k, *kk; // use the same buffer for normalized coefficients - kk = (INT32 *) prekk; + kk = (INT32 *)prekk; normalize_coeffs_8bpc(imOut->ysize, ksize, prekk); ImagingSectionEnter(&cookie); @@ -393,9 +393,9 @@ ImagingResampleVertical_8bpc(Imaging imOut, Imaging imIn, int offset, ymin = bounds[yy * 2 + 0]; ymax = bounds[yy * 2 + 1]; for (xx = 0; xx < imOut->xsize; xx++) { - ss0 = 1 << (PRECISION_BITS -1); + ss0 = 1 << (PRECISION_BITS - 1); for (y = 0; y < ymax; y++) { - ss0 += ((UINT8) imIn->image8[y + ymin][xx]) * k[y]; + ss0 += ((UINT8)imIn->image8[y + ymin][xx]) * k[y]; } imOut->image8[yy][xx] = clip8(ss0); } @@ -408,10 +408,10 @@ ImagingResampleVertical_8bpc(Imaging imOut, Imaging imIn, int offset, ymax = bounds[yy * 2 + 1]; for (xx = 0; xx < imOut->xsize; xx++) { UINT32 v; - ss0 = ss3 = 1 << (PRECISION_BITS -1); + ss0 = ss3 = 1 << (PRECISION_BITS - 1); for (y = 0; y < ymax; y++) { - ss0 += ((UINT8) imIn->image[y + ymin][xx*4 + 0]) * k[y]; - ss3 += ((UINT8) imIn->image[y + ymin][xx*4 + 3]) * k[y]; + ss0 += ((UINT8)imIn->image[y + ymin][xx * 4 + 0]) * k[y]; + ss3 += ((UINT8)imIn->image[y + ymin][xx * 4 + 3]) * k[y]; } v = MAKE_UINT32(clip8(ss0), 0, 0, clip8(ss3)); memcpy(imOut->image[yy] + xx * sizeof(v), &v, sizeof(v)); @@ -424,11 +424,11 @@ ImagingResampleVertical_8bpc(Imaging imOut, Imaging imIn, int offset, ymax = bounds[yy * 2 + 1]; for (xx = 0; xx < imOut->xsize; xx++) { UINT32 v; - ss0 = ss1 = ss2 = 1 << (PRECISION_BITS -1); + ss0 = ss1 = ss2 = 1 << (PRECISION_BITS - 1); for (y = 0; y < ymax; y++) { - ss0 += ((UINT8) imIn->image[y + ymin][xx*4 + 0]) * k[y]; - ss1 += ((UINT8) imIn->image[y + ymin][xx*4 + 1]) * k[y]; - ss2 += ((UINT8) imIn->image[y + ymin][xx*4 + 2]) * k[y]; + ss0 += ((UINT8)imIn->image[y + ymin][xx * 4 + 0]) * k[y]; + ss1 += ((UINT8)imIn->image[y + ymin][xx * 4 + 1]) * k[y]; + ss2 += ((UINT8)imIn->image[y + ymin][xx * 4 + 2]) * k[y]; } v = MAKE_UINT32(clip8(ss0), clip8(ss1), clip8(ss2), 0); memcpy(imOut->image[yy] + xx * sizeof(v), &v, sizeof(v)); @@ -441,12 +441,12 @@ ImagingResampleVertical_8bpc(Imaging imOut, Imaging imIn, int offset, ymax = bounds[yy * 2 + 1]; for (xx = 0; xx < imOut->xsize; xx++) { UINT32 v; - ss0 = ss1 = ss2 = ss3 = 1 << (PRECISION_BITS -1); + ss0 = ss1 = ss2 = ss3 = 1 << (PRECISION_BITS - 1); for (y = 0; y < ymax; y++) { - ss0 += ((UINT8) imIn->image[y + ymin][xx*4 + 0]) * k[y]; - ss1 += ((UINT8) imIn->image[y + ymin][xx*4 + 1]) * k[y]; - ss2 += ((UINT8) imIn->image[y + ymin][xx*4 + 2]) * k[y]; - ss3 += ((UINT8) imIn->image[y + ymin][xx*4 + 3]) * k[y]; + ss0 += ((UINT8)imIn->image[y + ymin][xx * 4 + 0]) * k[y]; + ss1 += ((UINT8)imIn->image[y + ymin][xx * 4 + 1]) * k[y]; + ss2 += ((UINT8)imIn->image[y + ymin][xx * 4 + 2]) * k[y]; + ss3 += ((UINT8)imIn->image[y + ymin][xx * 4 + 3]) * k[y]; } v = MAKE_UINT32(clip8(ss0), clip8(ss1), clip8(ss2), clip8(ss3)); memcpy(imOut->image[yy] + xx * sizeof(v), &v, sizeof(v)); @@ -457,18 +457,16 @@ ImagingResampleVertical_8bpc(Imaging imOut, Imaging imIn, int offset, ImagingSectionLeave(&cookie); } - void -ImagingResampleHorizontal_32bpc(Imaging imOut, Imaging imIn, int offset, - int ksize, int *bounds, double *kk) -{ +ImagingResampleHorizontal_32bpc( + Imaging imOut, Imaging imIn, int offset, int ksize, int *bounds, double *kk) { ImagingSectionCookie cookie; double ss; int xx, yy, x, xmin, xmax; double *k; ImagingSectionEnter(&cookie); - switch(imIn->type) { + switch (imIn->type) { case IMAGING_TYPE_INT32: for (yy = 0; yy < imOut->ysize; yy++) { for (xx = 0; xx < imOut->xsize; xx++) { @@ -502,18 +500,16 @@ ImagingResampleHorizontal_32bpc(Imaging imOut, Imaging imIn, int offset, ImagingSectionLeave(&cookie); } - void -ImagingResampleVertical_32bpc(Imaging imOut, Imaging imIn, int offset, - int ksize, int *bounds, double *kk) -{ +ImagingResampleVertical_32bpc( + Imaging imOut, Imaging imIn, int offset, int ksize, int *bounds, double *kk) { ImagingSectionCookie cookie; double ss; int xx, yy, y, ymin, ymax; double *k; ImagingSectionEnter(&cookie); - switch(imIn->type) { + switch (imIn->type) { case IMAGING_TYPE_INT32: for (yy = 0; yy < imOut->ysize; yy++) { ymin = bounds[yy * 2 + 0]; @@ -547,36 +543,36 @@ ImagingResampleVertical_32bpc(Imaging imOut, Imaging imIn, int offset, ImagingSectionLeave(&cookie); } - -typedef void (*ResampleFunction)(Imaging imOut, Imaging imIn, int offset, - int ksize, int *bounds, double *kk); - +typedef void (*ResampleFunction)( + Imaging imOut, Imaging imIn, int offset, int ksize, int *bounds, double *kk); Imaging -ImagingResampleInner(Imaging imIn, int xsize, int ysize, - struct filter *filterp, float box[4], - ResampleFunction ResampleHorizontal, - ResampleFunction ResampleVertical); - +ImagingResampleInner( + Imaging imIn, + int xsize, + int ysize, + struct filter *filterp, + float box[4], + ResampleFunction ResampleHorizontal, + ResampleFunction ResampleVertical); Imaging -ImagingResample(Imaging imIn, int xsize, int ysize, int filter, float box[4]) -{ +ImagingResample(Imaging imIn, int xsize, int ysize, int filter, float box[4]) { struct filter *filterp; ResampleFunction ResampleHorizontal; ResampleFunction ResampleVertical; if (strcmp(imIn->mode, "P") == 0 || strcmp(imIn->mode, "1") == 0) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } if (imIn->type == IMAGING_TYPE_SPECIAL) { - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } else if (imIn->image8) { ResampleHorizontal = ImagingResampleHorizontal_8bpc; ResampleVertical = ImagingResampleVertical_8bpc; } else { - switch(imIn->type) { + switch (imIn->type) { case IMAGING_TYPE_UINT8: ResampleHorizontal = ImagingResampleHorizontal_8bpc; ResampleVertical = ImagingResampleVertical_8bpc; @@ -587,44 +583,44 @@ ImagingResample(Imaging imIn, int xsize, int ysize, int filter, float box[4]) ResampleVertical = ImagingResampleVertical_32bpc; break; default: - return (Imaging) ImagingError_ModeError(); + return (Imaging)ImagingError_ModeError(); } } /* check filter */ switch (filter) { - case IMAGING_TRANSFORM_BOX: - filterp = &BOX; - break; - case IMAGING_TRANSFORM_BILINEAR: - filterp = &BILINEAR; - break; - case IMAGING_TRANSFORM_HAMMING: - filterp = &HAMMING; - break; - case IMAGING_TRANSFORM_BICUBIC: - filterp = &BICUBIC; - break; - case IMAGING_TRANSFORM_LANCZOS: - filterp = &LANCZOS; - break; - default: - return (Imaging) ImagingError_ValueError( - "unsupported resampling filter" - ); + case IMAGING_TRANSFORM_BOX: + filterp = &BOX; + break; + case IMAGING_TRANSFORM_BILINEAR: + filterp = &BILINEAR; + break; + case IMAGING_TRANSFORM_HAMMING: + filterp = &HAMMING; + break; + case IMAGING_TRANSFORM_BICUBIC: + filterp = &BICUBIC; + break; + case IMAGING_TRANSFORM_LANCZOS: + filterp = &LANCZOS; + break; + default: + return (Imaging)ImagingError_ValueError("unsupported resampling filter"); } - return ImagingResampleInner(imIn, xsize, ysize, filterp, box, - ResampleHorizontal, ResampleVertical); + return ImagingResampleInner( + imIn, xsize, ysize, filterp, box, ResampleHorizontal, ResampleVertical); } - Imaging -ImagingResampleInner(Imaging imIn, int xsize, int ysize, - struct filter *filterp, float box[4], - ResampleFunction ResampleHorizontal, - ResampleFunction ResampleVertical) -{ +ImagingResampleInner( + Imaging imIn, + int xsize, + int ysize, + struct filter *filterp, + float box[4], + ResampleFunction ResampleHorizontal, + ResampleFunction ResampleVertical) { Imaging imTemp = NULL; Imaging imOut = NULL; @@ -637,15 +633,15 @@ ImagingResampleInner(Imaging imIn, int xsize, int ysize, need_horizontal = xsize != imIn->xsize || box[0] || box[2] != xsize; need_vertical = ysize != imIn->ysize || box[1] || box[3] != ysize; - ksize_horiz = precompute_coeffs(imIn->xsize, box[0], box[2], xsize, - filterp, &bounds_horiz, &kk_horiz); - if ( ! ksize_horiz) { + ksize_horiz = precompute_coeffs( + imIn->xsize, box[0], box[2], xsize, filterp, &bounds_horiz, &kk_horiz); + if (!ksize_horiz) { return NULL; } - ksize_vert = precompute_coeffs(imIn->ysize, box[1], box[3], ysize, - filterp, &bounds_vert, &kk_vert); - if ( ! ksize_vert) { + ksize_vert = precompute_coeffs( + imIn->ysize, box[1], box[3], ysize, filterp, &bounds_vert, &kk_vert); + if (!ksize_vert) { free(bounds_horiz); free(kk_horiz); return NULL; @@ -654,8 +650,7 @@ ImagingResampleInner(Imaging imIn, int xsize, int ysize, // First used row in the source image ybox_first = bounds_vert[0]; // Last used row in the source image - ybox_last = bounds_vert[ysize*2 - 2] + bounds_vert[ysize*2 - 1]; - + ybox_last = bounds_vert[ysize * 2 - 2] + bounds_vert[ysize * 2 - 1]; /* two-pass resize, horizontal pass */ if (need_horizontal) { @@ -666,12 +661,12 @@ ImagingResampleInner(Imaging imIn, int xsize, int ysize, imTemp = ImagingNewDirty(imIn->mode, xsize, ybox_last - ybox_first); if (imTemp) { - ResampleHorizontal(imTemp, imIn, ybox_first, - ksize_horiz, bounds_horiz, kk_horiz); + ResampleHorizontal( + imTemp, imIn, ybox_first, ksize_horiz, bounds_horiz, kk_horiz); } free(bounds_horiz); free(kk_horiz); - if ( ! imTemp) { + if (!imTemp) { free(bounds_vert); free(kk_vert); return NULL; @@ -688,15 +683,14 @@ ImagingResampleInner(Imaging imIn, int xsize, int ysize, imOut = ImagingNewDirty(imIn->mode, imIn->xsize, ysize); if (imOut) { /* imIn can be the original image or horizontally resampled one */ - ResampleVertical(imOut, imIn, 0, - ksize_vert, bounds_vert, kk_vert); + ResampleVertical(imOut, imIn, 0, ksize_vert, bounds_vert, kk_vert); } /* it's safe to call ImagingDelete with empty value if previous step was not performed. */ ImagingDelete(imTemp); free(bounds_vert); free(kk_vert); - if ( ! imOut) { + if (!imOut) { return NULL; } } else { @@ -706,7 +700,7 @@ ImagingResampleInner(Imaging imIn, int xsize, int ysize, } /* none of the previous steps are performed, copying */ - if ( ! imOut) { + if (!imOut) { imOut = ImagingCopy(imIn); } diff --git a/src/libImaging/Sgi.h b/src/libImaging/Sgi.h index 8015d6661..39dd68825 100644 --- a/src/libImaging/Sgi.h +++ b/src/libImaging/Sgi.h @@ -1,7 +1,6 @@ /* Sgi.h */ typedef struct { - /* CONFIGURATION */ /* Number of bytes per channel per pixel */ diff --git a/src/libImaging/SgiRleDecode.c b/src/libImaging/SgiRleDecode.c index 9a8814b50..c19231e02 100644 --- a/src/libImaging/SgiRleDecode.c +++ b/src/libImaging/SgiRleDecode.c @@ -20,18 +20,17 @@ #define RLE_COPY_FLAG 0x80 #define RLE_MAX_RUN 0x7f -static void read4B(UINT32* dest, UINT8* buf) -{ +static void +read4B(UINT32 *dest, UINT8 *buf) { *dest = (UINT32)((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]); } -static int expandrow(UINT8* dest, UINT8* src, int n, int z, int xsize) -{ +static int +expandrow(UINT8 *dest, UINT8 *src, int n, int z, int xsize) { UINT8 pixel, count; int x = 0; - for (;n > 0; n--) - { + for (; n > 0; n--) { pixel = *src++; if (n == 1 && pixel != 0) { return n; @@ -45,34 +44,31 @@ static int expandrow(UINT8* dest, UINT8* src, int n, int z, int xsize) } x += count; if (pixel & RLE_COPY_FLAG) { - while(count--) { + while (count--) { *dest = *src++; dest += z; } - } - else { + } else { pixel = *src++; while (count--) { *dest = pixel; dest += z; } } - } return 0; } -static int expandrow2(UINT8* dest, const UINT8* src, int n, int z, int xsize) -{ +static int +expandrow2(UINT8 *dest, const UINT8 *src, int n, int z, int xsize) { UINT8 pixel, count; int x = 0; - for (;n > 0; n--) - { + for (; n > 0; n--) { pixel = src[1]; - src+=2; + src += 2; if (n == 1 && pixel != 0) { return n; } @@ -85,42 +81,37 @@ static int expandrow2(UINT8* dest, const UINT8* src, int n, int z, int xsize) } x += count; if (pixel & RLE_COPY_FLAG) { - while(count--) { + while (count--) { memcpy(dest, src, 2); src += 2; dest += z * 2; } - } - else { + } else { while (count--) { memcpy(dest, src, 2); dest += z * 2; } - src+=2; + src += 2; } } return 0; } - int -ImagingSgiRleDecode(Imaging im, ImagingCodecState state, - UINT8* buf, Py_ssize_t bytes) -{ +ImagingSgiRleDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { UINT8 *ptr; SGISTATE *c; int err = 0; int status; /* size check */ - if (im->xsize > INT_MAX / im->bands || - im->ysize > INT_MAX / im->bands) { + if (im->xsize > INT_MAX / im->bands || im->ysize > INT_MAX / im->bands) { state->errcode = IMAGING_CODEC_MEMORY; return -1; } /* Get all data from File descriptor */ - c = (SGISTATE*)state->context; + c = (SGISTATE *)state->context; _imaging_seek_pyFd(state->fd, 0L, SEEK_END); c->bufsize = _imaging_tell_pyFd(state->fd); c->bufsize -= SGI_HEADER_SIZE; @@ -130,7 +121,7 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, each with 4 bytes per element of tablen Check here before we allocate any memory */ - if (c->bufsize < 8*c->tablen) { + if (c->bufsize < 8 * c->tablen) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } @@ -141,8 +132,7 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, return -1; } _imaging_seek_pyFd(state->fd, SGI_HEADER_SIZE, SEEK_SET); - _imaging_read_pyFd(state->fd, (char*)ptr, c->bufsize); - + _imaging_read_pyFd(state->fd, (char *)ptr, c->bufsize); /* decoder initialization */ state->count = 0; @@ -160,28 +150,27 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, state->buffer = calloc(im->xsize * im->bands, sizeof(UINT8) * 2); c->starttab = calloc(c->tablen, sizeof(UINT32)); c->lengthtab = calloc(c->tablen, sizeof(UINT32)); - if (!state->buffer || - !c->starttab || - !c->lengthtab) { + if (!state->buffer || !c->starttab || !c->lengthtab) { err = IMAGING_CODEC_MEMORY; goto sgi_finish_decode; } /* populate offsets table */ - for (c->tabindex = 0, c->bufindex = 0; c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4) { + for (c->tabindex = 0, c->bufindex = 0; c->tabindex < c->tablen; + c->tabindex++, c->bufindex += 4) { read4B(&c->starttab[c->tabindex], &ptr[c->bufindex]); } /* populate lengths table */ - for (c->tabindex = 0, c->bufindex = c->tablen * sizeof(UINT32); c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4) { + for (c->tabindex = 0, c->bufindex = c->tablen * sizeof(UINT32); + c->tabindex < c->tablen; + c->tabindex++, c->bufindex += 4) { read4B(&c->lengthtab[c->tabindex], &ptr[c->bufindex]); } state->count += c->tablen * sizeof(UINT32) * 2; /* read compressed rows */ - for (c->rowno = 0; c->rowno < im->ysize; c->rowno++, state->y += state->ystep) - { - for (c->channo = 0; c->channo < im->bands; c->channo++) - { + for (c->rowno = 0; c->rowno < im->ysize; c->rowno++, state->y += state->ystep) { + for (c->channo = 0; c->channo < im->bands; c->channo++) { c->rleoffset = c->starttab[c->rowno + c->channo * im->ysize]; c->rlelength = c->lengthtab[c->rowno + c->channo * im->ysize]; c->rleoffset -= SGI_HEADER_SIZE; @@ -192,11 +181,20 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, } /* row decompression */ - if (c->bpc ==1) { - status = expandrow(&state->buffer[c->channo], &ptr[c->rleoffset], c->rlelength, im->bands, im->xsize); - } - else { - status = expandrow2(&state->buffer[c->channo * 2], &ptr[c->rleoffset], c->rlelength, im->bands, im->xsize); + if (c->bpc == 1) { + status = expandrow( + &state->buffer[c->channo], + &ptr[c->rleoffset], + c->rlelength, + im->bands, + im->xsize); + } else { + status = expandrow2( + &state->buffer[c->channo * 2], + &ptr[c->rleoffset], + c->rlelength, + im->bands, + im->xsize); } if (status == -1) { state->errcode = IMAGING_CODEC_OVERRUN; @@ -209,19 +207,18 @@ ImagingSgiRleDecode(Imaging im, ImagingCodecState state, } /* store decompressed data in image */ - state->shuffle((UINT8*)im->image[state->y], state->buffer, im->xsize); - + state->shuffle((UINT8 *)im->image[state->y], state->buffer, im->xsize); } c->bufsize++; -sgi_finish_decode: ; +sgi_finish_decode:; free(c->starttab); free(c->lengthtab); free(ptr); - if (err != 0){ - state->errcode=err; + if (err != 0) { + state->errcode = err; return -1; } return state->count - c->bufsize; diff --git a/src/libImaging/Storage.c b/src/libImaging/Storage.c index c9a24e6aa..76750aaf7 100644 --- a/src/libImaging/Storage.c +++ b/src/libImaging/Storage.c @@ -34,11 +34,9 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" #include - int ImagingNewCount = 0; /* -------------------------------------------------------------------- @@ -46,18 +44,17 @@ int ImagingNewCount = 0; */ Imaging -ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) -{ +ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) { Imaging im; /* linesize overflow check, roughly the current largest space req'd */ if (xsize > (INT_MAX / 4) - 1) { - return (Imaging) ImagingError_MemoryError(); + return (Imaging)ImagingError_MemoryError(); } - im = (Imaging) calloc(1, size); + im = (Imaging)calloc(1, size); if (!im) { - return (Imaging) ImagingError_MemoryError(); + return (Imaging)ImagingError_MemoryError(); } /* Setup image descriptor */ @@ -115,8 +112,9 @@ ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) im->linesize = xsize * 4; im->type = IMAGING_TYPE_INT32; - } else if (strcmp(mode, "I;16") == 0 || strcmp(mode, "I;16L") == 0 \ - || strcmp(mode, "I;16B") == 0 || strcmp(mode, "I;16N") == 0) { + } else if ( + strcmp(mode, "I;16") == 0 || strcmp(mode, "I;16L") == 0 || + strcmp(mode, "I;16B") == 0 || strcmp(mode, "I;16N") == 0) { /* EXPERIMENTAL */ /* 16-bit raw integer images */ im->bands = 1; @@ -135,7 +133,7 @@ ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) /* 15-bit reversed true colour */ im->bands = 1; im->pixelsize = 2; - im->linesize = (xsize*2 + 3) & -4; + im->linesize = (xsize * 2 + 3) & -4; im->type = IMAGING_TYPE_SPECIAL; } else if (strcmp(mode, "BGR;16") == 0) { @@ -143,7 +141,7 @@ ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) /* 16-bit reversed true colour */ im->bands = 1; im->pixelsize = 2; - im->linesize = (xsize*2 + 3) & -4; + im->linesize = (xsize * 2 + 3) & -4; im->type = IMAGING_TYPE_SPECIAL; } else if (strcmp(mode, "BGR;24") == 0) { @@ -151,7 +149,7 @@ ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) /* 24-bit reversed true colour */ im->bands = 1; im->pixelsize = 3; - im->linesize = (xsize*3 + 3) & -4; + im->linesize = (xsize * 3 + 3) & -4; im->type = IMAGING_TYPE_SPECIAL; } else if (strcmp(mode, "BGR;32") == 0) { @@ -159,7 +157,7 @@ ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) /* 32-bit reversed true colour */ im->bands = 1; im->pixelsize = 4; - im->linesize = (xsize*4 + 3) & -4; + im->linesize = (xsize * 4 + 3) & -4; im->type = IMAGING_TYPE_SPECIAL; } else if (strcmp(mode, "RGBX") == 0) { @@ -204,7 +202,7 @@ ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) } else { free(im); - return (Imaging) ImagingError_ValueError("unrecognized image mode"); + return (Imaging)ImagingError_ValueError("unrecognized image mode"); } /* Setup image descriptor */ @@ -212,21 +210,23 @@ ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) /* Pointer array (allocate at least one line, to avoid MemoryError exceptions on platforms where calloc(0, x) returns NULL) */ - im->image = (char **) calloc((ysize > 0) ? ysize : 1, sizeof(void *)); + im->image = (char **)calloc((ysize > 0) ? ysize : 1, sizeof(void *)); - if ( ! im->image) { + if (!im->image) { free(im); - return (Imaging) ImagingError_MemoryError(); + return (Imaging)ImagingError_MemoryError(); } /* Initialize alias pointers to pixel data. */ switch (im->pixelsize) { - case 1: case 2: case 3: - im->image8 = (UINT8 **) im->image; - break; - case 4: - im->image32 = (INT32 **) im->image; - break; + case 1: + case 2: + case 3: + im->image8 = (UINT8 **)im->image; + break; + case 4: + im->image32 = (INT32 **)im->image; + break; } ImagingDefaultArena.stats_new_count += 1; @@ -235,15 +235,13 @@ ImagingNewPrologueSubtype(const char *mode, int xsize, int ysize, int size) } Imaging -ImagingNewPrologue(const char *mode, int xsize, int ysize) -{ +ImagingNewPrologue(const char *mode, int xsize, int ysize) { return ImagingNewPrologueSubtype( mode, xsize, ysize, sizeof(struct ImagingMemoryInstance)); } void -ImagingDelete(Imaging im) -{ +ImagingDelete(Imaging im) { if (!im) { return; } @@ -263,7 +261,6 @@ ImagingDelete(Imaging im) free(im); } - /* Array Storage Type */ /* ------------------ */ /* Allocate image as an array of line buffers. */ @@ -271,17 +268,20 @@ ImagingDelete(Imaging im) #define IMAGING_PAGE_SIZE (4096) struct ImagingMemoryArena ImagingDefaultArena = { - 1, // alignment - 16*1024*1024, // block_size - 0, // blocks_max - 0, // blocks_cached - NULL, // blocks_pool - 0, 0, 0, 0, 0 // Stats + 1, // alignment + 16 * 1024 * 1024, // block_size + 0, // blocks_max + 0, // blocks_cached + NULL, // blocks_pool + 0, + 0, + 0, + 0, + 0 // Stats }; int -ImagingMemorySetBlocksMax(ImagingMemoryArena arena, int blocks_max) -{ +ImagingMemorySetBlocksMax(ImagingMemoryArena arena, int blocks_max) { void *p; /* Free already cached blocks */ ImagingMemoryClearCache(arena, blocks_max); @@ -291,14 +291,14 @@ ImagingMemorySetBlocksMax(ImagingMemoryArena arena, int blocks_max) arena->blocks_pool = NULL; } else if (arena->blocks_pool != NULL) { p = realloc(arena->blocks_pool, sizeof(*arena->blocks_pool) * blocks_max); - if ( ! p) { + if (!p) { // Leave previous blocks_max value return 0; } arena->blocks_pool = p; } else { arena->blocks_pool = calloc(sizeof(*arena->blocks_pool), blocks_max); - if ( ! arena->blocks_pool) { + if (!arena->blocks_pool) { return 0; } } @@ -308,8 +308,7 @@ ImagingMemorySetBlocksMax(ImagingMemoryArena arena, int blocks_max) } void -ImagingMemoryClearCache(ImagingMemoryArena arena, int new_size) -{ +ImagingMemoryClearCache(ImagingMemoryArena arena, int new_size) { while (arena->blocks_cached > new_size) { arena->blocks_cached -= 1; free(arena->blocks_pool[arena->blocks_cached].ptr); @@ -318,8 +317,7 @@ ImagingMemoryClearCache(ImagingMemoryArena arena, int new_size) } ImagingMemoryBlock -memory_get_block(ImagingMemoryArena arena, int requested_size, int dirty) -{ +memory_get_block(ImagingMemoryArena arena, int requested_size, int dirty) { ImagingMemoryBlock block = {NULL, 0}; if (arena->blocks_cached > 0) { @@ -327,16 +325,16 @@ memory_get_block(ImagingMemoryArena arena, int requested_size, int dirty) arena->blocks_cached -= 1; block = arena->blocks_pool[arena->blocks_cached]; // Reallocate if needed - if (block.size != requested_size){ + if (block.size != requested_size) { block.ptr = realloc(block.ptr, requested_size); } - if ( ! block.ptr) { + if (!block.ptr) { // Can't allocate, free previous pointer (it is still valid) free(arena->blocks_pool[arena->blocks_cached].ptr); arena->stats_freed_blocks += 1; return block; } - if ( ! dirty) { + if (!dirty) { memset(block.ptr, 0, requested_size); } arena->stats_reused_blocks += 1; @@ -356,9 +354,8 @@ memory_get_block(ImagingMemoryArena arena, int requested_size, int dirty) } void -memory_return_block(ImagingMemoryArena arena, ImagingMemoryBlock block) -{ - if (arena->blocks_cached < arena->blocks_max) { +memory_return_block(ImagingMemoryArena arena, ImagingMemoryBlock block) { + if (arena->blocks_cached < arena->blocks_max) { // Reduce block size if (block.size > arena->block_size) { block.size = arena->block_size; @@ -372,15 +369,13 @@ memory_return_block(ImagingMemoryArena arena, ImagingMemoryBlock block) } } - static void -ImagingDestroyArray(Imaging im) -{ +ImagingDestroyArray(Imaging im) { int y = 0; if (im->blocks) { while (im->blocks[y].ptr) { - memory_return_block(&ImagingDefaultArena, im->blocks[y]); + memory_return_block(&ImagingDefaultArena, im->blocks[y]); y += 1; } free(im->blocks); @@ -388,8 +383,7 @@ ImagingDestroyArray(Imaging im) } Imaging -ImagingAllocateArray(Imaging im, int dirty, int block_size) -{ +ImagingAllocateArray(Imaging im, int dirty, int block_size) { int y, line_in_block, current_block; ImagingMemoryArena arena = &ImagingDefaultArena; ImagingMemoryBlock block = {NULL, 0}; @@ -397,7 +391,7 @@ ImagingAllocateArray(Imaging im, int dirty, int block_size) char *aligned_ptr = NULL; /* 0-width or 0-height image. No need to do anything */ - if ( ! im->linesize || ! im->ysize) { + if (!im->linesize || !im->ysize) { return im; } @@ -412,8 +406,8 @@ ImagingAllocateArray(Imaging im, int dirty, int block_size) /* One extra pointer is always NULL */ im->blocks = calloc(sizeof(*im->blocks), blocks_count + 1); - if ( ! im->blocks) { - return (Imaging) ImagingError_MemoryError(); + if (!im->blocks) { + return (Imaging)ImagingError_MemoryError(); } /* Allocate image as an array of lines */ @@ -428,9 +422,9 @@ ImagingAllocateArray(Imaging im, int dirty, int block_size) } required = lines_remaining * aligned_linesize + arena->alignment - 1; block = memory_get_block(arena, required, dirty); - if ( ! block.ptr) { + if (!block.ptr) { ImagingDestroyArray(im); - return (Imaging) ImagingError_MemoryError(); + return (Imaging)ImagingError_MemoryError(); } im->blocks[current_block] = block; /* Bulletproof code from libc _int_memalign */ @@ -454,42 +448,38 @@ ImagingAllocateArray(Imaging im, int dirty, int block_size) return im; } - /* Block Storage Type */ /* ------------------ */ /* Allocate image as a single block. */ static void -ImagingDestroyBlock(Imaging im) -{ +ImagingDestroyBlock(Imaging im) { if (im->block) { free(im->block); } } Imaging -ImagingAllocateBlock(Imaging im) -{ +ImagingAllocateBlock(Imaging im) { Py_ssize_t y, i; /* overflow check for malloc */ - if (im->linesize && - im->ysize > INT_MAX / im->linesize) { - return (Imaging) ImagingError_MemoryError(); + if (im->linesize && im->ysize > INT_MAX / im->linesize) { + return (Imaging)ImagingError_MemoryError(); } if (im->ysize * im->linesize <= 0) { /* some platforms return NULL for malloc(0); this fix prevents MemoryError on zero-sized images on such platforms */ - im->block = (char *) malloc(1); + im->block = (char *)malloc(1); } else { /* malloc check ok, overflow check above */ - im->block = (char *) calloc(im->ysize, im->linesize); + im->block = (char *)calloc(im->ysize, im->linesize); } - if ( ! im->block) { - return (Imaging) ImagingError_MemoryError(); + if (!im->block) { + return (Imaging)ImagingError_MemoryError(); } for (y = i = 0; y < im->ysize; y++) { @@ -507,16 +497,15 @@ ImagingAllocateBlock(Imaging im) */ Imaging -ImagingNewInternal(const char* mode, int xsize, int ysize, int dirty) -{ +ImagingNewInternal(const char *mode, int xsize, int ysize, int dirty) { Imaging im; if (xsize < 0 || ysize < 0) { - return (Imaging) ImagingError_ValueError("bad image size"); + return (Imaging)ImagingError_ValueError("bad image size"); } im = ImagingNewPrologue(mode, xsize, ysize); - if ( ! im) { + if (!im) { return NULL; } @@ -536,28 +525,25 @@ ImagingNewInternal(const char* mode, int xsize, int ysize, int dirty) } Imaging -ImagingNew(const char* mode, int xsize, int ysize) -{ +ImagingNew(const char *mode, int xsize, int ysize) { return ImagingNewInternal(mode, xsize, ysize, 0); } Imaging -ImagingNewDirty(const char* mode, int xsize, int ysize) -{ +ImagingNewDirty(const char *mode, int xsize, int ysize) { return ImagingNewInternal(mode, xsize, ysize, 1); } Imaging -ImagingNewBlock(const char* mode, int xsize, int ysize) -{ +ImagingNewBlock(const char *mode, int xsize, int ysize) { Imaging im; if (xsize < 0 || ysize < 0) { - return (Imaging) ImagingError_ValueError("bad image size"); + return (Imaging)ImagingError_ValueError("bad image size"); } im = ImagingNewPrologue(mode, xsize, ysize); - if ( ! im) { + if (!im) { return NULL; } @@ -570,15 +556,13 @@ ImagingNewBlock(const char* mode, int xsize, int ysize) } Imaging -ImagingNew2Dirty(const char* mode, Imaging imOut, Imaging imIn) -{ +ImagingNew2Dirty(const char *mode, Imaging imOut, Imaging imIn) { /* allocate or validate output image */ if (imOut) { /* make sure images match */ - if (strcmp(imOut->mode, mode) != 0 - || imOut->xsize != imIn->xsize - || imOut->ysize != imIn->ysize) { + if (strcmp(imOut->mode, mode) != 0 || imOut->xsize != imIn->xsize || + imOut->ysize != imIn->ysize) { return ImagingError_Mismatch(); } } else { @@ -593,8 +577,7 @@ ImagingNew2Dirty(const char* mode, Imaging imOut, Imaging imIn) } void -ImagingCopyPalette(Imaging destination, Imaging source) -{ +ImagingCopyPalette(Imaging destination, Imaging source) { if (source->palette) { if (destination->palette) { ImagingPaletteDelete(destination->palette); diff --git a/src/libImaging/SunRleDecode.c b/src/libImaging/SunRleDecode.c index acb39133a..9d8e1292a 100644 --- a/src/libImaging/SunRleDecode.c +++ b/src/libImaging/SunRleDecode.c @@ -15,37 +15,30 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - int -ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ +ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { int n; - UINT8* ptr; + UINT8 *ptr; UINT8 extra_data = 0; UINT8 extra_bytes = 0; ptr = buf; for (;;) { - if (bytes < 1) { return ptr - buf; } if (ptr[0] == 0x80) { - if (bytes < 2) { break; } n = ptr[1]; - if (n == 0) { - /* Literal 0x80 (2 bytes) */ n = 1; @@ -55,7 +48,6 @@ ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes -= 2; } else { - /* Run (3 bytes) */ if (bytes < 3) { break; @@ -84,7 +76,7 @@ ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t n += 1; if (state->x + n > state->bytes) { - extra_bytes = n; /* full value */ + extra_bytes = n; /* full value */ n = state->bytes - state->x; extra_bytes -= n; extra_data = ptr[2]; @@ -94,11 +86,9 @@ ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t ptr += 3; bytes -= 3; - } } else { - /* Literal byte */ n = 1; @@ -106,18 +96,18 @@ ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t ptr += 1; bytes -= 1; - } for (;;) { state->x += n; if (state->x >= state->bytes) { - /* Got a full line, unpack it */ - state->shuffle((UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->buffer, - state->xsize); + state->shuffle( + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->buffer, + state->xsize); state->x = 0; @@ -132,7 +122,7 @@ ImagingSunRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t } if (state->x > 0) { - break; // assert + break; // assert } if (extra_bytes >= state->bytes) { diff --git a/src/libImaging/TgaRleDecode.c b/src/libImaging/TgaRleDecode.c index b1364e004..273ecdffd 100644 --- a/src/libImaging/TgaRleDecode.c +++ b/src/libImaging/TgaRleDecode.c @@ -14,43 +14,35 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - int -ImagingTgaRleDecode(Imaging im, ImagingCodecState state, - UINT8* buf, Py_ssize_t bytes) -{ +ImagingTgaRleDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { int n, depth; - UINT8* ptr; + UINT8 *ptr; ptr = buf; if (state->state == 0) { - /* check image orientation */ if (state->ystep < 0) { - state->y = state->ysize-1; + state->y = state->ysize - 1; state->ystep = -1; } else { state->ystep = 1; } state->state = 1; - } depth = state->count; for (;;) { - if (bytes < 1) { return ptr - buf; } if (ptr[0] & 0x80) { - /* Run (1 + pixelsize bytes) */ if (bytes < 1 + depth) { @@ -69,7 +61,7 @@ ImagingTgaRleDecode(Imaging im, ImagingCodecState state, } else { int i; for (i = 0; i < n; i += depth) { - memcpy(state->buffer + state->x + i, ptr+1, depth); + memcpy(state->buffer + state->x + i, ptr + 1, depth); } } @@ -77,7 +69,6 @@ ImagingTgaRleDecode(Imaging im, ImagingCodecState state, bytes -= 1 + depth; } else { - /* Literal (1+n+1 bytes block) */ n = depth * (ptr[0] + 1); @@ -94,17 +85,17 @@ ImagingTgaRleDecode(Imaging im, ImagingCodecState state, ptr += 1 + n; bytes -= 1 + n; - } state->x += n; if (state->x >= state->bytes) { - /* Got a full line, unpack it */ - state->shuffle((UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->buffer, - state->xsize); + state->shuffle( + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->buffer, + state->xsize); state->x = 0; @@ -114,9 +105,7 @@ ImagingTgaRleDecode(Imaging im, ImagingCodecState state, /* End of file (errcode = 0) */ return -1; } - } - } return ptr - buf; diff --git a/src/libImaging/TgaRleEncode.c b/src/libImaging/TgaRleEncode.c index c65dcf5ec..aa7e7b96d 100644 --- a/src/libImaging/TgaRleEncode.c +++ b/src/libImaging/TgaRleEncode.c @@ -4,18 +4,15 @@ #include #include - -static int comparePixels(const UINT8* buf, int x, int bytesPerPixel) -{ +static int +comparePixels(const UINT8 *buf, int x, int bytesPerPixel) { buf += x * bytesPerPixel; return memcmp(buf, buf + bytesPerPixel, bytesPerPixel) == 0; } - int -ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) -{ - UINT8* dst; +ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { + UINT8 *dst; int bytesPerPixel; if (state->state == 0) { @@ -40,7 +37,7 @@ ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) * excluding the 1-byte descriptor. */ if (state->count == 0) { - UINT8* row; + UINT8 *row; UINT8 descriptor; int startX; @@ -64,8 +61,8 @@ ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) if (state->x == 0) { state->shuffle( state->buffer, - (UINT8*)im->image[state->y + state->yoff] - + state->xoff * im->pixelsize, + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, state->xsize); } @@ -149,9 +146,7 @@ ImagingTgaRleEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) } memcpy( - dst, - state->buffer + (state->x * bytesPerPixel - state->count), - flushCount); + dst, state->buffer + (state->x * bytesPerPixel - state->count), flushCount); dst += flushCount; bytes -= flushCount; diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c index 5cbbe7380..7f14b5a34 100644 --- a/src/libImaging/TiffDecode.c +++ b/src/libImaging/TiffDecode.c @@ -23,7 +23,8 @@ /* Convert C file descriptor to WinApi HFILE if LibTiff was compiled with tif_win32.c * * This cast is safe, as the top 32-bits of HFILE are guaranteed to be zero, - * see https://docs.microsoft.com/en-us/windows/win32/winprog64/interprocess-communication + * see + * https://docs.microsoft.com/en-us/windows/win32/winprog64/interprocess-communication */ #ifndef USE_WIN32_FILEIO #define fd_to_tiff_fd(fd) (fd) @@ -31,16 +32,23 @@ #define fd_to_tiff_fd(fd) ((int)_get_osfhandle(fd)) #endif -void dump_state(const TIFFSTATE *state){ - TRACE(("State: Location %u size %d eof %d data: %p ifd: %d\n", (uint)state->loc, - (int)state->size, (uint)state->eof, state->data, state->ifd)); +void +dump_state(const TIFFSTATE *state) { + TRACE( + ("State: Location %u size %d eof %d data: %p ifd: %d\n", + (uint)state->loc, + (int)state->size, + (uint)state->eof, + state->data, + state->ifd)); } /* procs for TIFFOpenClient */ -tsize_t _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) { +tsize_t +_tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) { TIFFSTATE *state = (TIFFSTATE *)hdata; tsize_t to_read; @@ -53,11 +61,12 @@ tsize_t _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) { _TIFFmemcpy(buf, (UINT8 *)state->data + state->loc, to_read); state->loc += (toff_t)to_read; - TRACE( ("location: %u\n", (uint)state->loc)); + TRACE(("location: %u\n", (uint)state->loc)); return to_read; } -tsize_t _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) { +tsize_t +_tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) { TIFFSTATE *state = (TIFFSTATE *)hdata; tsize_t to_write; @@ -65,14 +74,14 @@ tsize_t _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) { dump_state(state); to_write = min(size, state->size - (tsize_t)state->loc); - if (state->flrealloc && size>to_write) { + if (state->flrealloc && size > to_write) { tdata_t new_data; - tsize_t newsize=state->size; + tsize_t newsize = state->size; while (newsize < (size + state->size)) { - if (newsize > INT_MAX - 64*1024){ + if (newsize > INT_MAX - 64 * 1024) { return 0; } - newsize += 64*1024; + newsize += 64 * 1024; // newsize*=2; // UNDONE, by 64k chunks? } TRACE(("Reallocing in write to %d bytes\n", (int)newsize)); @@ -97,27 +106,29 @@ tsize_t _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) { return to_write; } -toff_t _tiffSeekProc(thandle_t hdata, toff_t off, int whence) { +toff_t +_tiffSeekProc(thandle_t hdata, toff_t off, int whence) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffSeekProc: off: %u whence: %d \n", (uint)off, whence)); dump_state(state); switch (whence) { - case 0: - state->loc = off; - break; - case 1: - state->loc += off; - break; - case 2: - state->loc = state->eof + off; - break; + case 0: + state->loc = off; + break; + case 1: + state->loc += off; + break; + case 2: + state->loc = state->eof + off; + break; } dump_state(state); return state->loc; } -int _tiffCloseProc(thandle_t hdata) { +int +_tiffCloseProc(thandle_t hdata) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffCloseProc \n")); @@ -126,8 +137,8 @@ int _tiffCloseProc(thandle_t hdata) { return 0; } - -toff_t _tiffSizeProc(thandle_t hdata) { +toff_t +_tiffSizeProc(thandle_t hdata) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffSizeProc \n")); @@ -136,7 +147,8 @@ toff_t _tiffSizeProc(thandle_t hdata) { return (toff_t)state->size; } -int _tiffMapProc(thandle_t hdata, tdata_t* pbase, toff_t* psize) { +int +_tiffMapProc(thandle_t hdata, tdata_t *pbase, toff_t *psize) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffMapProc input size: %u, data: %p\n", (uint)*psize, *pbase)); @@ -148,25 +160,41 @@ int _tiffMapProc(thandle_t hdata, tdata_t* pbase, toff_t* psize) { return (1); } -int _tiffNullMapProc(thandle_t hdata, tdata_t* pbase, toff_t* psize) { - (void) hdata; (void) pbase; (void) psize; +int +_tiffNullMapProc(thandle_t hdata, tdata_t *pbase, toff_t *psize) { + (void)hdata; + (void)pbase; + (void)psize; return (0); } -void _tiffUnmapProc(thandle_t hdata, tdata_t base, toff_t size) { +void +_tiffUnmapProc(thandle_t hdata, tdata_t base, toff_t size) { TRACE(("_tiffUnMapProc\n")); - (void) hdata; (void) base; (void) size; + (void)hdata; + (void)base; + (void)size; } -int ImagingLibTiffInit(ImagingCodecState state, int fp, uint32 offset) { +int +ImagingLibTiffInit(ImagingCodecState state, int fp, uint32 offset) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; TRACE(("initing libtiff\n")); - TRACE(("filepointer: %d \n", fp)); - TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, - state->x, state->y, state->ystep)); - TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, - state->xoff, state->yoff)); + TRACE(("filepointer: %d \n", fp)); + TRACE( + ("State: count %d, state %d, x %d, y %d, ystep %d\n", + state->count, + state->state, + state->x, + state->y, + state->ystep)); + TRACE( + ("State: xsize %d, ysize %d, xoff %d, yoff %d \n", + state->xsize, + state->ysize, + state->xoff, + state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("State: context %p \n", state->context)); @@ -180,12 +208,12 @@ int ImagingLibTiffInit(ImagingCodecState state, int fp, uint32 offset) { return 1; } - -int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { +int +_decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { // To avoid dealing with YCbCr subsampling, let libtiff handle it // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle // all of the conversion. Metadata read from the TIFFRGBAImage could - // be different from the metadata that the base tiff returns. + // be different from the metadata that the base tiff returns. INT32 strip_row; UINT8 *new_data; @@ -211,8 +239,12 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { img.col_offset = 0; if (state->xsize != img.width || state->ysize != img.height) { - TRACE(("Inconsistent Image Error: %d =? %d, %d =? %d", - state->xsize, img.width, state->ysize, img.height)); + TRACE( + ("Inconsistent Image Error: %d =? %d, %d =? %d", + state->xsize, + img.width, + state->ysize, + img.height)); state->errcode = IMAGING_CODEC_BROKEN; goto decodeycbcr_err; } @@ -221,9 +253,9 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { if (INT_MAX / 4 < img.width) { state->errcode = IMAGING_CODEC_MEMORY; goto decodeycbcr_err; - } - - // TiffRGBAImages are 32bits/pixel. + } + + // TiffRGBAImages are 32bits/pixel. row_byte_size = img.width * 4; /* overflow check for realloc */ @@ -238,7 +270,7 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { /* realloc to fit whole strip */ /* malloc check above */ - new_data = realloc (state->buffer, state->bytes); + new_data = realloc(state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; goto decodeycbcr_err; @@ -247,11 +279,12 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { state->buffer = new_data; for (; state->y < state->ysize; state->y += rows_per_strip) { - img.row_offset = state->y; + img.row_offset = state->y; rows_to_read = min(rows_per_strip, img.height - state->y); - if (TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read) == -1) { - TRACE(("Decode Error, y: %d\n", state->y )); + if (TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read) == + -1) { + TRACE(("Decode Error, y: %d\n", state->y)); state->errcode = IMAGING_CODEC_BROKEN; goto decodeycbcr_err; } @@ -259,20 +292,24 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { TRACE(("Decoded strip for row %d \n", state->y)); // iterate over each row in the strip and stuff data into image - for (strip_row = 0; strip_row < min((INT32) rows_per_strip, state->ysize - state->y); strip_row++) { + for (strip_row = 0; + strip_row < min((INT32)rows_per_strip, state->ysize - state->y); + strip_row++) { TRACE(("Writing data into line %d ; \n", state->y + strip_row)); - // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); - // TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); + // UINT8 * bbb = state->buffer + strip_row * (state->bytes / + // rows_per_strip); TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], + // ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); - state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] + - state->xoff * im->pixelsize, - state->buffer + strip_row * row_byte_size, - state->xsize); + state->shuffle( + (UINT8 *)im->image[state->y + state->yoff + strip_row] + + state->xoff * im->pixelsize, + state->buffer + strip_row * row_byte_size, + state->xsize); } } - decodeycbcr_err: +decodeycbcr_err: TIFFRGBAImageEnd(&img); if (state->errcode != 0) { return -1; @@ -280,7 +317,8 @@ int _decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { return 0; } -int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { +int +_decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { INT32 strip_row; UINT8 *new_data; UINT32 rows_per_strip, row_byte_size; @@ -307,7 +345,8 @@ int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { if (TIFFStripSize(tiff) > state->bytes) { // If the strip size as expected by LibTiff isn't what we're expecting, abort. - // man: TIFFStripSize returns the equivalent size for a strip of data as it would be returned in a + // man: TIFFStripSize returns the equivalent size for a strip of data as it + // would be returned in a // call to TIFFReadEncodedStrip ... state->errcode = IMAGING_CODEC_MEMORY; @@ -316,7 +355,7 @@ int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { /* realloc to fit whole strip */ /* malloc check above */ - new_data = realloc (state->buffer, state->bytes); + new_data = realloc(state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; return -1; @@ -325,7 +364,11 @@ int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { state->buffer = new_data; for (; state->y < state->ysize; state->y += rows_per_strip) { - if (TIFFReadEncodedStrip(tiff, TIFFComputeStrip(tiff, state->y, 0), (tdata_t)state->buffer, -1) == -1) { + if (TIFFReadEncodedStrip( + tiff, + TIFFComputeStrip(tiff, state->y, 0), + (tdata_t)state->buffer, + -1) == -1) { TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, state->y, 0))); state->errcode = IMAGING_CODEC_BROKEN; return -1; @@ -334,46 +377,80 @@ int _decodeStrip(Imaging im, ImagingCodecState state, TIFF *tiff) { TRACE(("Decoded strip for row %d \n", state->y)); // iterate over each row in the strip and stuff data into image - for (strip_row = 0; strip_row < min((INT32) rows_per_strip, state->ysize - state->y); strip_row++) { + for (strip_row = 0; + strip_row < min((INT32)rows_per_strip, state->ysize - state->y); + strip_row++) { TRACE(("Writing data into line %d ; \n", state->y + strip_row)); - // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); - // TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); + // UINT8 * bbb = state->buffer + strip_row * (state->bytes / + // rows_per_strip); TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], + // ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); - state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] + - state->xoff * im->pixelsize, - state->buffer + strip_row * row_byte_size, - state->xsize); + state->shuffle( + (UINT8 *)im->image[state->y + state->yoff + strip_row] + + state->xoff * im->pixelsize, + state->buffer + strip_row * row_byte_size, + state->xsize); } } return 0; } -int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t bytes) { +int +ImagingLibTiffDecode( + Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = "tempfile.tif"; char *mode = "r"; TIFF *tiff; - uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR + uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR int isYCbCr = 0; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE(("in decoder: bytes %d\n", bytes)); - TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, - state->x, state->y, state->ystep)); - TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, - state->xoff, state->yoff)); + TRACE( + ("State: count %d, state %d, x %d, y %d, ystep %d\n", + state->count, + state->state, + state->x, + state->y, + state->ystep)); + TRACE( + ("State: xsize %d, ysize %d, xoff %d, yoff %d \n", + state->xsize, + state->ysize, + state->xoff, + state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); - TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); - TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); - TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", - im->mode, im->type, im->bands, im->xsize, im->ysize)); - TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n", - im->image8, im->image32, im->image, im->block)); - TRACE(("Image: pixelsize: %d, linesize %d \n", - im->pixelsize, im->linesize)); + TRACE( + ("Buffer: %p: %c%c%c%c\n", + buffer, + (char)buffer[0], + (char)buffer[1], + (char)buffer[2], + (char)buffer[3])); + TRACE( + ("State->Buffer: %c%c%c%c\n", + (char)state->buffer[0], + (char)state->buffer[1], + (char)state->buffer[2], + (char)state->buffer[3])); + TRACE( + ("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", + im->mode, + im->type, + im->bands, + im->xsize, + im->ysize)); + TRACE( + ("Image: image8 %p, image32 %p, image %p, block %p \n", + im->image8, + im->image32, + im->image, + im->block)); + TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; @@ -387,54 +464,59 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { - TRACE(("Opening using fd: %d\n",clientstate->fp)); - lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end. + TRACE(("Opening using fd: %d\n", clientstate->fp)); + lseek(clientstate->fp, 0, SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(fd_to_tiff_fd(clientstate->fp), filename, mode); } else { TRACE(("Opening from string\n")); - tiff = TIFFClientOpen(filename, mode, - (thandle_t) clientstate, - _tiffReadProc, _tiffWriteProc, - _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, - _tiffMapProc, _tiffUnmapProc); + tiff = TIFFClientOpen( + filename, + mode, + (thandle_t)clientstate, + _tiffReadProc, + _tiffWriteProc, + _tiffSeekProc, + _tiffCloseProc, + _tiffSizeProc, + _tiffMapProc, + _tiffUnmapProc); } - if (!tiff){ + if (!tiff) { TRACE(("Error, didn't get the tiff\n")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } - if (clientstate->ifd){ + if (clientstate->ifd) { int rv; uint32 ifdoffset = clientstate->ifd; TRACE(("reading tiff ifd %u\n", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); - if (!rv){ + if (!rv) { TRACE(("error in TIFFSetSubDirectory")); goto decode_err; } } - TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); isYCbCr = photometric == PHOTOMETRIC_YCBCR; - + if (TIFFIsTiled(tiff)) { INT32 x, y, tile_y; - UINT32 tile_width, tile_length, current_tile_length, current_line, current_tile_width, row_byte_size; + UINT32 tile_width, tile_length, current_tile_length, current_line, + current_tile_width, row_byte_size; UINT8 *new_data; TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length); /* overflow check for row_byte_size calculation */ - if ((UINT32) INT_MAX / state->bits < tile_width) { + if ((UINT32)INT_MAX / state->bits < tile_width) { state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } - if (isYCbCr) { row_byte_size = tile_width * 4; /* sanity check, we use this value in shuffle below */ @@ -443,7 +525,8 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ goto decode_err; } } else { - // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size + // We could use TIFFTileSize, but for YCbCr data it returns subsampled data + // size row_byte_size = (tile_width * state->bits + 7) / 8; } @@ -456,14 +539,15 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ state->bytes = row_byte_size * tile_length; if (TIFFTileSize(tiff) > state->bytes) { - // If the strip size as expected by LibTiff isn't what we're expecting, abort. + // If the strip size as expected by LibTiff isn't what we're expecting, + // abort. state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } /* realloc to fit whole tile */ /* malloc check above */ - new_data = realloc (state->buffer, state->bytes); + new_data = realloc(state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; @@ -492,14 +576,19 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ TRACE(("Read tile at %dx%d; \n\n", x, y)); - current_tile_width = min((INT32) tile_width, state->xsize - x); - current_tile_length = min((INT32) tile_length, state->ysize - y); + current_tile_width = min((INT32)tile_width, state->xsize - x); + current_tile_length = min((INT32)tile_length, state->ysize - y); // iterate over each line in the tile and stuff data into image for (tile_y = 0; tile_y < current_tile_length; tile_y++) { - TRACE(("Writing tile data at %dx%d using tile_width: %d; \n", tile_y + y, x, current_tile_width)); + TRACE( + ("Writing tile data at %dx%d using tile_width: %d; \n", + tile_y + y, + x, + current_tile_width)); // UINT8 * bbb = state->buffer + tile_y * row_byte_size; - // TRACE(("chars: %x%x%x%x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); + // TRACE(("chars: %x%x%x%x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], + // ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); /* * For some reason the TIFFReadRGBATile() function * chooses the lower left corner as the origin. @@ -512,24 +601,23 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ } else { current_line = tile_y; } - - state->shuffle((UINT8*) im->image[tile_y + y] + x * im->pixelsize, - state->buffer + current_line * row_byte_size, - current_tile_width - ); + + state->shuffle( + (UINT8 *)im->image[tile_y + y] + x * im->pixelsize, + state->buffer + current_line * row_byte_size, + current_tile_width); } } } } else { if (!isYCbCr) { _decodeStrip(im, state, tiff); - } - else { + } else { _decodeStripYCbCr(im, state, tiff); } } - decode_err: +decode_err: TIFFClose(tiff); TRACE(("Done Decoding, Returning \n")); // Returning -1 here to force ImageFile.load to break, rather than @@ -537,7 +625,8 @@ int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ return -1; } -int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { +int +ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { // Open the FD or the pointer as a tiff file, for writing. // We may have to do some monkeying around to make this really work. // If we have a fp, then we're good. @@ -546,21 +635,30 @@ int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { // Going to have to deal with the directory as well. TIFFSTATE *clientstate = (TIFFSTATE *)state->context; - int bufsize = 64*1024; + int bufsize = 64 * 1024; char *mode = "w"; TRACE(("initing libtiff\n")); - TRACE(("Filename %s, filepointer: %d \n", filename, fp)); - TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, - state->x, state->y, state->ystep)); - TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, - state->xoff, state->yoff)); + TRACE(("Filename %s, filepointer: %d \n", filename, fp)); + TRACE( + ("State: count %d, state %d, x %d, y %d, ystep %d\n", + state->count, + state->state, + state->x, + state->y, + state->ystep)); + TRACE( + ("State: xsize %d, ysize %d, xoff %d, yoff %d \n", + state->xsize, + state->ysize, + state->xoff, + state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("State: context %p \n", state->context)); clientstate->loc = 0; clientstate->size = 0; - clientstate->eof =0; + clientstate->eof = 0; clientstate->data = 0; clientstate->flrealloc = 0; clientstate->fp = fp; @@ -568,27 +666,33 @@ int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { state->state = 0; if (fp) { - TRACE(("Opening using fd: %d for writing \n",clientstate->fp)); + TRACE(("Opening using fd: %d for writing \n", clientstate->fp)); clientstate->tiff = TIFFFdOpen(fd_to_tiff_fd(clientstate->fp), filename, mode); } else { - // malloc a buffer to write the tif, we're going to need to realloc or something if we need bigger. + // malloc a buffer to write the tif, we're going to need to realloc or something + // if we need bigger. TRACE(("Opening a buffer for writing \n")); /* malloc check ok, small constant allocation */ clientstate->data = malloc(bufsize); clientstate->size = bufsize; - clientstate->flrealloc=1; + clientstate->flrealloc = 1; if (!clientstate->data) { TRACE(("Error, couldn't allocate a buffer of size %d\n", bufsize)); return 0; } - clientstate->tiff = TIFFClientOpen(filename, mode, - (thandle_t) clientstate, - _tiffReadProc, _tiffWriteProc, - _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, - _tiffNullMapProc, _tiffUnmapProc); /*force no mmap*/ - + clientstate->tiff = TIFFClientOpen( + filename, + mode, + (thandle_t)clientstate, + _tiffReadProc, + _tiffWriteProc, + _tiffSeekProc, + _tiffCloseProc, + _tiffSizeProc, + _tiffNullMapProc, + _tiffUnmapProc); /*force no mmap*/ } if (!clientstate->tiff) { @@ -597,10 +701,11 @@ int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { } return 1; - } -int ImagingLibTiffMergeFieldInfo(ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length){ +int +ImagingLibTiffMergeFieldInfo( + ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length) { // Refer to libtiff docs (http://www.simplesystems.org/libtiff/addingtags.html) TIFFSTATE *clientstate = (TIFFSTATE *)state->context; uint32 n; @@ -615,8 +720,14 @@ int ImagingLibTiffMergeFieldInfo(ImagingCodecState state, TIFFDataType field_typ int passcount = 0; TIFFFieldInfo info[] = { - { key, readcount, writecount, field_type, FIELD_CUSTOM, 1, passcount, "CustomField" } - }; + {key, + readcount, + writecount, + field_type, + FIELD_CUSTOM, + 1, + passcount, + "CustomField"}}; if (is_var_length) { info[0].field_writecount = -1; @@ -629,7 +740,8 @@ int ImagingLibTiffMergeFieldInfo(ImagingCodecState state, TIFFDataType field_typ n = sizeof(info) / sizeof(info[0]); // Test for libtiff 4.0 or later, excluding libtiff 3.9.6 and 3.9.7 -#if TIFFLIB_VERSION >= 20111221 && TIFFLIB_VERSION != 20120218 && TIFFLIB_VERSION != 20120922 +#if TIFFLIB_VERSION >= 20111221 && TIFFLIB_VERSION != 20120218 && \ + TIFFLIB_VERSION != 20120922 status = TIFFMergeFieldInfo(clientstate->tiff, info, n); #else TIFFMergeFieldInfo(clientstate->tiff, info, n); @@ -637,7 +749,8 @@ int ImagingLibTiffMergeFieldInfo(ImagingCodecState state, TIFFDataType field_typ return status; } -int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...){ +int +ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...) { // after tif_dir.c->TIFFSetField. TIFFSTATE *clientstate = (TIFFSTATE *)state->context; va_list ap; @@ -649,8 +762,8 @@ int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...){ return status; } - -int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes) { +int +ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int bytes) { /* One shot encoder. Encode everything to the tiff in the clientstate. If we're running off of a FD, then run once, we're good, everything ends up in the file, we close and we're done. @@ -664,35 +777,65 @@ int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int TIFF *tiff = clientstate->tiff; TRACE(("in encoder: bytes %d\n", bytes)); - TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, - state->x, state->y, state->ystep)); - TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, - state->xoff, state->yoff)); + TRACE( + ("State: count %d, state %d, x %d, y %d, ystep %d\n", + state->count, + state->state, + state->x, + state->y, + state->ystep)); + TRACE( + ("State: xsize %d, ysize %d, xoff %d, yoff %d \n", + state->xsize, + state->ysize, + state->xoff, + state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); - TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); - TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); - TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", - im->mode, im->type, im->bands, im->xsize, im->ysize)); - TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n", - im->image8, im->image32, im->image, im->block)); - TRACE(("Image: pixelsize: %d, linesize %d \n", - im->pixelsize, im->linesize)); + TRACE( + ("Buffer: %p: %c%c%c%c\n", + buffer, + (char)buffer[0], + (char)buffer[1], + (char)buffer[2], + (char)buffer[3])); + TRACE( + ("State->Buffer: %c%c%c%c\n", + (char)state->buffer[0], + (char)state->buffer[1], + (char)state->buffer[2], + (char)state->buffer[3])); + TRACE( + ("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", + im->mode, + im->type, + im->bands, + im->xsize, + im->ysize)); + TRACE( + ("Image: image8 %p, image32 %p, image %p, block %p \n", + im->image8, + im->image32, + im->image, + im->block)); + TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize)); dump_state(clientstate); if (state->state == 0) { TRACE(("Encoding line bt line")); - while(state->y < state->ysize){ - state->shuffle(state->buffer, - (UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, - state->xsize); + while (state->y < state->ysize) { + state->shuffle( + state->buffer, + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->xsize); - if (TIFFWriteScanline(tiff, (tdata_t)(state->buffer), (uint32)state->y, 0) == -1) { + if (TIFFWriteScanline( + tiff, (tdata_t)(state->buffer), (uint32)state->y, 0) == -1) { TRACE(("Encode Error, row %d\n", state->y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); - if (!clientstate->fp){ + if (!clientstate->fp) { free(clientstate->data); } return -1; @@ -701,7 +844,7 @@ int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int } if (state->y == state->ysize) { - state->state=1; + state->state = 1; TRACE(("Flushing \n")); if (!TIFFFlush(tiff)) { @@ -709,7 +852,7 @@ int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int // likely reason is memory. state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); - if (!clientstate->fp){ + if (!clientstate->fp) { free(clientstate->data); } return -1; @@ -718,13 +861,19 @@ int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int TIFFClose(tiff); // reset the clientstate metadata to use it to read out the buffer. clientstate->loc = 0; - clientstate->size = clientstate->eof; // redundant? + clientstate->size = clientstate->eof; // redundant? } } if (state->state == 1 && !clientstate->fp) { int read = (int)_tiffReadProc(clientstate, (tdata_t)buffer, (tsize_t)bytes); - TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); + TRACE( + ("Buffer: %p: %c%c%c%c\n", + buffer, + (char)buffer[0], + (char)buffer[1], + (char)buffer[2], + (char)buffer[3])); if (clientstate->loc == clientstate->eof) { TRACE(("Hit EOF, calling an end, freeing data")); state->errcode = IMAGING_CODEC_END; @@ -737,9 +886,8 @@ int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int return 0; } -const char* -ImagingTiffVersion(void) -{ +const char * +ImagingTiffVersion(void) { return TIFFGetVersion(); } diff --git a/src/libImaging/TiffDecode.h b/src/libImaging/TiffDecode.h index 3d27e65b6..2c3d88caa 100644 --- a/src/libImaging/TiffDecode.h +++ b/src/libImaging/TiffDecode.h @@ -20,8 +20,8 @@ */ #ifndef min -#define min(x,y) (( x > y ) ? y : x ) -#define max(x,y) (( x < y ) ? y : x ) +#define min(x, y) ((x > y) ? y : x) +#define max(x, y) ((x < y) ? y : x) #endif #ifndef _PIL_LIBTIFF_ @@ -32,22 +32,24 @@ typedef struct { toff_t loc; /* toff_t == uint32 */ tsize_t size; /* tsize_t == int32 */ int fp; - uint32 ifd; /* offset of the ifd, used for multipage - * Should be uint32 for libtiff 3.9.x - * uint64 for libtiff 4.0.x - */ - TIFF *tiff; /* Used in write */ + uint32 ifd; /* offset of the ifd, used for multipage + * Should be uint32 for libtiff 3.9.x + * uint64 for libtiff 4.0.x + */ + TIFF *tiff; /* Used in write */ toff_t eof; - int flrealloc;/* may we realloc */ + int flrealloc; /* may we realloc */ } TIFFSTATE; - - -extern int ImagingLibTiffInit(ImagingCodecState state, int fp, uint32 offset); -extern int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp); -extern int ImagingLibTiffMergeFieldInfo(ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length); -extern int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...); - +extern int +ImagingLibTiffInit(ImagingCodecState state, int fp, uint32 offset); +extern int +ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp); +extern int +ImagingLibTiffMergeFieldInfo( + ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length); +extern int +ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...); /* Trace debugging diff --git a/src/libImaging/Unpack.c b/src/libImaging/Unpack.c index 917da6ab3..b4ba283b2 100644 --- a/src/libImaging/Unpack.c +++ b/src/libImaging/Unpack.c @@ -46,20 +46,28 @@ /* byte-swapping macros */ -#define C16N\ - (tmp[0]=in[0], tmp[1]=in[1]); -#define C16S\ - (tmp[1]=in[0], tmp[0]=in[1]); -#define C32N\ - (tmp[0]=in[0], tmp[1]=in[1], tmp[2]=in[2], tmp[3]=in[3]); -#define C32S\ - (tmp[3]=in[0], tmp[2]=in[1], tmp[1]=in[2], tmp[0]=in[3]); -#define C64N\ - (tmp[0]=in[0], tmp[1]=in[1], tmp[2]=in[2], tmp[3]=in[3],\ - tmp[4]=in[4], tmp[5]=in[5], tmp[6]=in[6], tmp[7]=in[7]); -#define C64S\ - (tmp[7]=in[0], tmp[6]=in[1], tmp[5]=in[2], tmp[4]=in[3],\ - tmp[3]=in[4], tmp[2]=in[5], tmp[1]=in[6], tmp[0]=in[7]); +#define C16N (tmp[0] = in[0], tmp[1] = in[1]); +#define C16S (tmp[1] = in[0], tmp[0] = in[1]); +#define C32N (tmp[0] = in[0], tmp[1] = in[1], tmp[2] = in[2], tmp[3] = in[3]); +#define C32S (tmp[3] = in[0], tmp[2] = in[1], tmp[1] = in[2], tmp[0] = in[3]); +#define C64N \ + (tmp[0] = in[0], \ + tmp[1] = in[1], \ + tmp[2] = in[2], \ + tmp[3] = in[3], \ + tmp[4] = in[4], \ + tmp[5] = in[5], \ + tmp[6] = in[6], \ + tmp[7] = in[7]); +#define C64S \ + (tmp[7] = in[0], \ + tmp[6] = in[1], \ + tmp[5] = in[2], \ + tmp[4] = in[3], \ + tmp[3] = in[4], \ + tmp[2] = in[5], \ + tmp[1] = in[6], \ + tmp[0] = in[7]); #ifdef WORDS_BIGENDIAN #define C16B C16N @@ -80,111 +88,163 @@ /* bit-swapping */ static UINT8 BITFLIP[] = { - 0, 128, 64, 192, 32, 160, 96, 224, 16, 144, 80, 208, 48, 176, 112, - 240, 8, 136, 72, 200, 40, 168, 104, 232, 24, 152, 88, 216, 56, 184, - 120, 248, 4, 132, 68, 196, 36, 164, 100, 228, 20, 148, 84, 212, 52, - 180, 116, 244, 12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, - 60, 188, 124, 252, 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82, - 210, 50, 178, 114, 242, 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, - 90, 218, 58, 186, 122, 250, 6, 134, 70, 198, 38, 166, 102, 230, 22, - 150, 86, 214, 54, 182, 118, 246, 14, 142, 78, 206, 46, 174, 110, 238, - 30, 158, 94, 222, 62, 190, 126, 254, 1, 129, 65, 193, 33, 161, 97, - 225, 17, 145, 81, 209, 49, 177, 113, 241, 9, 137, 73, 201, 41, 169, - 105, 233, 25, 153, 89, 217, 57, 185, 121, 249, 5, 133, 69, 197, 37, - 165, 101, 229, 21, 149, 85, 213, 53, 181, 117, 245, 13, 141, 77, 205, - 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253, 3, 131, 67, - 195, 35, 163, 99, 227, 19, 147, 83, 211, 51, 179, 115, 243, 11, 139, - 75, 203, 43, 171, 107, 235, 27, 155, 91, 219, 59, 187, 123, 251, 7, - 135, 71, 199, 39, 167, 103, 231, 23, 151, 87, 215, 55, 183, 119, 247, - 15, 143, 79, 207, 47, 175, 111, 239, 31, 159, 95, 223, 63, 191, 127, - 255 -}; + 0, 128, 64, 192, 32, 160, 96, 224, 16, 144, 80, 208, 48, 176, 112, 240, + 8, 136, 72, 200, 40, 168, 104, 232, 24, 152, 88, 216, 56, 184, 120, 248, + 4, 132, 68, 196, 36, 164, 100, 228, 20, 148, 84, 212, 52, 180, 116, 244, + 12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252, + 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82, 210, 50, 178, 114, 242, + 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250, + 6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86, 214, 54, 182, 118, 246, + 14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254, + 1, 129, 65, 193, 33, 161, 97, 225, 17, 145, 81, 209, 49, 177, 113, 241, + 9, 137, 73, 201, 41, 169, 105, 233, 25, 153, 89, 217, 57, 185, 121, 249, + 5, 133, 69, 197, 37, 165, 101, 229, 21, 149, 85, 213, 53, 181, 117, 245, + 13, 141, 77, 205, 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253, + 3, 131, 67, 195, 35, 163, 99, 227, 19, 147, 83, 211, 51, 179, 115, 243, + 11, 139, 75, 203, 43, 171, 107, 235, 27, 155, 91, 219, 59, 187, 123, 251, + 7, 135, 71, 199, 39, 167, 103, 231, 23, 151, 87, 215, 55, 183, 119, 247, + 15, 143, 79, 207, 47, 175, 111, 239, 31, 159, 95, 223, 63, 191, 127, 255}; /* Unpack to "1" image */ static void -unpack1(UINT8* out, const UINT8* in, int pixels) -{ +unpack1(UINT8 *out, const UINT8 *in, int pixels) { /* bits (msb first, white is non-zero) */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = (byte & 128) ? 255 : 0; byte <<= 1; - case 7: *out++ = (byte & 128) ? 255 : 0; byte <<= 1; - case 6: *out++ = (byte & 128) ? 255 : 0; byte <<= 1; - case 5: *out++ = (byte & 128) ? 255 : 0; byte <<= 1; - case 4: *out++ = (byte & 128) ? 255 : 0; byte <<= 1; - case 3: *out++ = (byte & 128) ? 255 : 0; byte <<= 1; - case 2: *out++ = (byte & 128) ? 255 : 0; byte <<= 1; - case 1: *out++ = (byte & 128) ? 255 : 0; + default: + *out++ = (byte & 128) ? 255 : 0; + byte <<= 1; + case 7: + *out++ = (byte & 128) ? 255 : 0; + byte <<= 1; + case 6: + *out++ = (byte & 128) ? 255 : 0; + byte <<= 1; + case 5: + *out++ = (byte & 128) ? 255 : 0; + byte <<= 1; + case 4: + *out++ = (byte & 128) ? 255 : 0; + byte <<= 1; + case 3: + *out++ = (byte & 128) ? 255 : 0; + byte <<= 1; + case 2: + *out++ = (byte & 128) ? 255 : 0; + byte <<= 1; + case 1: + *out++ = (byte & 128) ? 255 : 0; } pixels -= 8; } } static void -unpack1I(UINT8* out, const UINT8* in, int pixels) -{ +unpack1I(UINT8 *out, const UINT8 *in, int pixels) { /* bits (msb first, white is zero) */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = (byte & 128) ? 0 : 255; byte <<= 1; - case 7: *out++ = (byte & 128) ? 0 : 255; byte <<= 1; - case 6: *out++ = (byte & 128) ? 0 : 255; byte <<= 1; - case 5: *out++ = (byte & 128) ? 0 : 255; byte <<= 1; - case 4: *out++ = (byte & 128) ? 0 : 255; byte <<= 1; - case 3: *out++ = (byte & 128) ? 0 : 255; byte <<= 1; - case 2: *out++ = (byte & 128) ? 0 : 255; byte <<= 1; - case 1: *out++ = (byte & 128) ? 0 : 255; + default: + *out++ = (byte & 128) ? 0 : 255; + byte <<= 1; + case 7: + *out++ = (byte & 128) ? 0 : 255; + byte <<= 1; + case 6: + *out++ = (byte & 128) ? 0 : 255; + byte <<= 1; + case 5: + *out++ = (byte & 128) ? 0 : 255; + byte <<= 1; + case 4: + *out++ = (byte & 128) ? 0 : 255; + byte <<= 1; + case 3: + *out++ = (byte & 128) ? 0 : 255; + byte <<= 1; + case 2: + *out++ = (byte & 128) ? 0 : 255; + byte <<= 1; + case 1: + *out++ = (byte & 128) ? 0 : 255; } pixels -= 8; } } static void -unpack1R(UINT8* out, const UINT8* in, int pixels) -{ +unpack1R(UINT8 *out, const UINT8 *in, int pixels) { /* bits (lsb first, white is non-zero) */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = (byte & 1) ? 255 : 0; byte >>= 1; - case 7: *out++ = (byte & 1) ? 255 : 0; byte >>= 1; - case 6: *out++ = (byte & 1) ? 255 : 0; byte >>= 1; - case 5: *out++ = (byte & 1) ? 255 : 0; byte >>= 1; - case 4: *out++ = (byte & 1) ? 255 : 0; byte >>= 1; - case 3: *out++ = (byte & 1) ? 255 : 0; byte >>= 1; - case 2: *out++ = (byte & 1) ? 255 : 0; byte >>= 1; - case 1: *out++ = (byte & 1) ? 255 : 0; + default: + *out++ = (byte & 1) ? 255 : 0; + byte >>= 1; + case 7: + *out++ = (byte & 1) ? 255 : 0; + byte >>= 1; + case 6: + *out++ = (byte & 1) ? 255 : 0; + byte >>= 1; + case 5: + *out++ = (byte & 1) ? 255 : 0; + byte >>= 1; + case 4: + *out++ = (byte & 1) ? 255 : 0; + byte >>= 1; + case 3: + *out++ = (byte & 1) ? 255 : 0; + byte >>= 1; + case 2: + *out++ = (byte & 1) ? 255 : 0; + byte >>= 1; + case 1: + *out++ = (byte & 1) ? 255 : 0; } pixels -= 8; } } static void -unpack1IR(UINT8* out, const UINT8* in, int pixels) -{ +unpack1IR(UINT8 *out, const UINT8 *in, int pixels) { /* bits (lsb first, white is zero) */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = (byte & 1) ? 0 : 255; byte >>= 1; - case 7: *out++ = (byte & 1) ? 0 : 255; byte >>= 1; - case 6: *out++ = (byte & 1) ? 0 : 255; byte >>= 1; - case 5: *out++ = (byte & 1) ? 0 : 255; byte >>= 1; - case 4: *out++ = (byte & 1) ? 0 : 255; byte >>= 1; - case 3: *out++ = (byte & 1) ? 0 : 255; byte >>= 1; - case 2: *out++ = (byte & 1) ? 0 : 255; byte >>= 1; - case 1: *out++ = (byte & 1) ? 0 : 255; + default: + *out++ = (byte & 1) ? 0 : 255; + byte >>= 1; + case 7: + *out++ = (byte & 1) ? 0 : 255; + byte >>= 1; + case 6: + *out++ = (byte & 1) ? 0 : 255; + byte >>= 1; + case 5: + *out++ = (byte & 1) ? 0 : 255; + byte >>= 1; + case 4: + *out++ = (byte & 1) ? 0 : 255; + byte >>= 1; + case 3: + *out++ = (byte & 1) ? 0 : 255; + byte >>= 1; + case 2: + *out++ = (byte & 1) ? 0 : 255; + byte >>= 1; + case 1: + *out++ = (byte & 1) ? 0 : 255; } pixels -= 8; } } static void -unpack18(UINT8* out, const UINT8* in, int pixels) -{ +unpack18(UINT8 *out, const UINT8 *in, int pixels) { /* Unpack a '|b1' image, which is a numpy boolean. 1 == true, 0==false, in bytes */ @@ -194,160 +254,188 @@ unpack18(UINT8* out, const UINT8* in, int pixels) } } - - /* Unpack to "L" image */ static void -unpackL2(UINT8* out, const UINT8* in, int pixels) -{ +unpackL2(UINT8 *out, const UINT8 *in, int pixels) { /* nibbles (msb first, white is non-zero) */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = ((byte >> 6) & 0x03U) * 0x55U; byte <<= 2; - case 3: *out++ = ((byte >> 6) & 0x03U) * 0x55U; byte <<= 2; - case 2: *out++ = ((byte >> 6) & 0x03U) * 0x55U; byte <<= 2; - case 1: *out++ = ((byte >> 6) & 0x03U) * 0x55U; + default: + *out++ = ((byte >> 6) & 0x03U) * 0x55U; + byte <<= 2; + case 3: + *out++ = ((byte >> 6) & 0x03U) * 0x55U; + byte <<= 2; + case 2: + *out++ = ((byte >> 6) & 0x03U) * 0x55U; + byte <<= 2; + case 1: + *out++ = ((byte >> 6) & 0x03U) * 0x55U; } pixels -= 4; } } static void -unpackL2I(UINT8* out, const UINT8* in, int pixels) -{ +unpackL2I(UINT8 *out, const UINT8 *in, int pixels) { /* nibbles (msb first, white is zero) */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); byte <<= 2; - case 3: *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); byte <<= 2; - case 2: *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); byte <<= 2; - case 1: *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); + default: + *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); + byte <<= 2; + case 3: + *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); + byte <<= 2; + case 2: + *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); + byte <<= 2; + case 1: + *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); } pixels -= 4; } } static void -unpackL2R(UINT8* out, const UINT8* in, int pixels) -{ +unpackL2R(UINT8 *out, const UINT8 *in, int pixels) { /* nibbles (bit order reversed, white is non-zero) */ while (pixels > 0) { UINT8 byte = *in++; byte = BITFLIP[byte]; switch (pixels) { - default: *out++ = ((byte >> 6) & 0x03U) * 0x55U; byte <<= 2; - case 3: *out++ = ((byte >> 6) & 0x03U) * 0x55U; byte <<= 2; - case 2: *out++ = ((byte >> 6) & 0x03U) * 0x55U; byte <<= 2; - case 1: *out++ = ((byte >> 6) & 0x03U) * 0x55U; + default: + *out++ = ((byte >> 6) & 0x03U) * 0x55U; + byte <<= 2; + case 3: + *out++ = ((byte >> 6) & 0x03U) * 0x55U; + byte <<= 2; + case 2: + *out++ = ((byte >> 6) & 0x03U) * 0x55U; + byte <<= 2; + case 1: + *out++ = ((byte >> 6) & 0x03U) * 0x55U; } pixels -= 4; } } static void -unpackL2IR(UINT8* out, const UINT8* in, int pixels) -{ +unpackL2IR(UINT8 *out, const UINT8 *in, int pixels) { /* nibbles (bit order reversed, white is zero) */ while (pixels > 0) { UINT8 byte = *in++; byte = BITFLIP[byte]; switch (pixels) { - default: *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); byte <<= 2; - case 3: *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); byte <<= 2; - case 2: *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); byte <<= 2; - case 1: *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); + default: + *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); + byte <<= 2; + case 3: + *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); + byte <<= 2; + case 2: + *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); + byte <<= 2; + case 1: + *out++ = 0xFFU - (UINT8)(((byte >> 6) & 0x03U) * 0x55U); } pixels -= 4; } } static void -unpackL4(UINT8* out, const UINT8* in, int pixels) -{ +unpackL4(UINT8 *out, const UINT8 *in, int pixels) { /* nibbles (msb first, white is non-zero) */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = ((byte >> 4) & 0x0FU) * 0x11U; byte <<= 4; - case 1: *out++ = ((byte >> 4) & 0x0FU) * 0x11U; + default: + *out++ = ((byte >> 4) & 0x0FU) * 0x11U; + byte <<= 4; + case 1: + *out++ = ((byte >> 4) & 0x0FU) * 0x11U; } pixels -= 2; } } static void -unpackL4I(UINT8* out, const UINT8* in, int pixels) -{ +unpackL4I(UINT8 *out, const UINT8 *in, int pixels) { /* nibbles (msb first, white is zero) */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = 0xFFU - (UINT8)(((byte >> 4) & 0x0FU) * 0x11U); byte <<= 4; - case 1: *out++ = 0xFFU - (UINT8)(((byte >> 4) & 0x0FU) * 0x11U); + default: + *out++ = 0xFFU - (UINT8)(((byte >> 4) & 0x0FU) * 0x11U); + byte <<= 4; + case 1: + *out++ = 0xFFU - (UINT8)(((byte >> 4) & 0x0FU) * 0x11U); } pixels -= 2; } } static void -unpackL4R(UINT8* out, const UINT8* in, int pixels) -{ +unpackL4R(UINT8 *out, const UINT8 *in, int pixels) { /* nibbles (bit order reversed, white is non-zero) */ while (pixels > 0) { UINT8 byte = *in++; byte = BITFLIP[byte]; switch (pixels) { - default: *out++ = ((byte >> 4) & 0x0FU) * 0x11U; byte <<= 4; - case 1: *out++ = ((byte >> 4) & 0x0FU) * 0x11U; + default: + *out++ = ((byte >> 4) & 0x0FU) * 0x11U; + byte <<= 4; + case 1: + *out++ = ((byte >> 4) & 0x0FU) * 0x11U; } pixels -= 2; } } static void -unpackL4IR(UINT8* out, const UINT8* in, int pixels) -{ +unpackL4IR(UINT8 *out, const UINT8 *in, int pixels) { /* nibbles (bit order reversed, white is zero) */ while (pixels > 0) { UINT8 byte = *in++; byte = BITFLIP[byte]; switch (pixels) { - default: *out++ = 0xFFU - (UINT8)(((byte >> 4) & 0x0FU) * 0x11U); byte <<= 4; - case 1: *out++ = 0xFFU - (UINT8)(((byte >> 4) & 0x0FU) * 0x11U); + default: + *out++ = 0xFFU - (UINT8)(((byte >> 4) & 0x0FU) * 0x11U); + byte <<= 4; + case 1: + *out++ = 0xFFU - (UINT8)(((byte >> 4) & 0x0FU) * 0x11U); } pixels -= 2; } } static void -unpackLA(UINT8* _out, const UINT8* in, int pixels) -{ +unpackLA(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* LA, pixel interleaved */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[0], in[0], in[0], in[1]); memcpy(_out, &iv, sizeof(iv)); - in += 2; _out += 4; + in += 2; + _out += 4; } } static void -unpackLAL(UINT8* _out, const UINT8* in, int pixels) -{ +unpackLAL(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* LA, line interleaved */ - for (i = 0; i < pixels; i++, _out+=4) { - UINT32 iv = MAKE_UINT32(in[i], in[i], in[i], in[i+pixels]); + for (i = 0; i < pixels; i++, _out += 4) { + UINT32 iv = MAKE_UINT32(in[i], in[i], in[i], in[i + pixels]); memcpy(_out, &iv, sizeof(iv)); } } static void -unpackLI(UINT8* out, const UINT8* in, int pixels) -{ +unpackLI(UINT8 *out, const UINT8 *in, int pixels) { /* negative */ int i; for (i = 0; i < pixels; i++) { @@ -356,8 +444,7 @@ unpackLI(UINT8* out, const UINT8* in, int pixels) } static void -unpackLR(UINT8* out, const UINT8* in, int pixels) -{ +unpackLR(UINT8 *out, const UINT8 *in, int pixels) { int i; /* RGB, bit reversed */ for (i = 0; i < pixels; i++) { @@ -366,8 +453,7 @@ unpackLR(UINT8* out, const UINT8* in, int pixels) } static void -unpackL16(UINT8* out, const UINT8* in, int pixels) -{ +unpackL16(UINT8 *out, const UINT8 *in, int pixels) { /* int16 (upper byte, little endian) */ int i; for (i = 0; i < pixels; i++) { @@ -377,8 +463,7 @@ unpackL16(UINT8* out, const UINT8* in, int pixels) } static void -unpackL16B(UINT8* out, const UINT8* in, int pixels) -{ +unpackL16B(UINT8 *out, const UINT8 *in, int pixels) { int i; /* int16 (upper byte, big endian) */ for (i = 0; i < pixels; i++) { @@ -387,66 +472,86 @@ unpackL16B(UINT8* out, const UINT8* in, int pixels) } } - /* Unpack to "P" image */ static void -unpackP1(UINT8* out, const UINT8* in, int pixels) -{ +unpackP1(UINT8 *out, const UINT8 *in, int pixels) { /* bits */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = (byte >> 7) & 1; byte <<= 1; - case 7: *out++ = (byte >> 7) & 1; byte <<= 1; - case 6: *out++ = (byte >> 7) & 1; byte <<= 1; - case 5: *out++ = (byte >> 7) & 1; byte <<= 1; - case 4: *out++ = (byte >> 7) & 1; byte <<= 1; - case 3: *out++ = (byte >> 7) & 1; byte <<= 1; - case 2: *out++ = (byte >> 7) & 1; byte <<= 1; - case 1: *out++ = (byte >> 7) & 1; + default: + *out++ = (byte >> 7) & 1; + byte <<= 1; + case 7: + *out++ = (byte >> 7) & 1; + byte <<= 1; + case 6: + *out++ = (byte >> 7) & 1; + byte <<= 1; + case 5: + *out++ = (byte >> 7) & 1; + byte <<= 1; + case 4: + *out++ = (byte >> 7) & 1; + byte <<= 1; + case 3: + *out++ = (byte >> 7) & 1; + byte <<= 1; + case 2: + *out++ = (byte >> 7) & 1; + byte <<= 1; + case 1: + *out++ = (byte >> 7) & 1; } pixels -= 8; } } static void -unpackP2(UINT8* out, const UINT8* in, int pixels) -{ +unpackP2(UINT8 *out, const UINT8 *in, int pixels) { /* bit pairs */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = (byte >> 6) & 3; byte <<= 2; - case 3: *out++ = (byte >> 6) & 3; byte <<= 2; - case 2: *out++ = (byte >> 6) & 3; byte <<= 2; - case 1: *out++ = (byte >> 6) & 3; + default: + *out++ = (byte >> 6) & 3; + byte <<= 2; + case 3: + *out++ = (byte >> 6) & 3; + byte <<= 2; + case 2: + *out++ = (byte >> 6) & 3; + byte <<= 2; + case 1: + *out++ = (byte >> 6) & 3; } pixels -= 4; } } static void -unpackP4(UINT8* out, const UINT8* in, int pixels) -{ +unpackP4(UINT8 *out, const UINT8 *in, int pixels) { /* nibbles */ while (pixels > 0) { UINT8 byte = *in++; switch (pixels) { - default: *out++ = (byte >> 4) & 15; byte <<= 4; - case 1: *out++ = (byte >> 4) & 15; + default: + *out++ = (byte >> 4) & 15; + byte <<= 4; + case 1: + *out++ = (byte >> 4) & 15; } pixels -= 2; } } static void -unpackP2L(UINT8* out, const UINT8* in, int pixels) -{ +unpackP2L(UINT8 *out, const UINT8 *in, int pixels) { int i, j, m, s; /* bit layers */ m = 128; - s = (pixels+7)/8; + s = (pixels + 7) / 8; for (i = j = 0; i < pixels; i++) { out[i] = ((in[j] & m) ? 1 : 0) + ((in[j + s] & m) ? 2 : 0); if ((m >>= 1) == 0) { @@ -457,15 +562,14 @@ unpackP2L(UINT8* out, const UINT8* in, int pixels) } static void -unpackP4L(UINT8* out, const UINT8* in, int pixels) -{ +unpackP4L(UINT8 *out, const UINT8 *in, int pixels) { int i, j, m, s; /* bit layers (trust the optimizer ;-) */ m = 128; - s = (pixels+7)/8; + s = (pixels + 7) / 8; for (i = j = 0; i < pixels; i++) { out[i] = ((in[j] & m) ? 1 : 0) + ((in[j + s] & m) ? 2 : 0) + - ((in[j + 2*s] & m) ? 4 : 0) + ((in[j + 3*s] & m) ? 8 : 0); + ((in[j + 2 * s] & m) ? 4 : 0) + ((in[j + 3 * s] & m) ? 8 : 0); if ((m >>= 1) == 0) { m = 128; j++; @@ -473,403 +577,410 @@ unpackP4L(UINT8* out, const UINT8* in, int pixels) } } - /* Unpack to "RGB" image */ void -ImagingUnpackRGB(UINT8* _out, const UINT8* in, int pixels) -{ +ImagingUnpackRGB(UINT8 *_out, const UINT8 *in, int pixels) { int i = 0; /* RGB triplets */ - for (; i < pixels-1; i++) { + for (; i < pixels - 1; i++) { UINT32 iv; memcpy(&iv, in, sizeof(iv)); iv |= MASK_UINT32_CHANNEL_3; memcpy(_out, &iv, sizeof(iv)); - in += 3; _out += 4; + in += 3; + _out += 4; } for (; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[0], in[1], in[2], 255); memcpy(_out, &iv, sizeof(iv)); - in += 3; _out += 4; + in += 3; + _out += 4; } } void -unpackRGB16L(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGB16L(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* 16-bit RGB triplets, little-endian order */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[1], in[3], in[5], 255); memcpy(_out, &iv, sizeof(iv)); - in += 6; _out += 4; + in += 6; + _out += 4; } } void -unpackRGB16B(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGB16B(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* 16-bit RGB triplets, big-endian order */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[0], in[2], in[4], 255); memcpy(_out, &iv, sizeof(iv)); - in += 6; _out += 4; + in += 6; + _out += 4; } } static void -unpackRGBL(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBL(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGB, line interleaved */ - for (i = 0; i < pixels; i++, _out+=4) { - UINT32 iv = MAKE_UINT32(in[i], in[i+pixels], in[i+pixels+pixels], 255); + for (i = 0; i < pixels; i++, _out += 4) { + UINT32 iv = MAKE_UINT32(in[i], in[i + pixels], in[i + pixels + pixels], 255); memcpy(_out, &iv, sizeof(iv)); } } static void -unpackRGBR(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBR(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGB, bit reversed */ for (i = 0; i < pixels; i++) { - UINT32 iv = MAKE_UINT32(BITFLIP[in[0]], BITFLIP[in[1]], - BITFLIP[in[2]], 255); + UINT32 iv = MAKE_UINT32(BITFLIP[in[0]], BITFLIP[in[1]], BITFLIP[in[2]], 255); memcpy(_out, &iv, sizeof(iv)); - in += 3; _out += 4; + in += 3; + _out += 4; } } void -ImagingUnpackBGR(UINT8* _out, const UINT8* in, int pixels) -{ +ImagingUnpackBGR(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGB, reversed bytes */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[2], in[1], in[0], 255); memcpy(_out, &iv, sizeof(iv)); - in += 3; _out += 4; + in += 3; + _out += 4; } } void -ImagingUnpackRGB15(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackRGB15(UINT8 *out, const UINT8 *in, int pixels) { int i, pixel; /* RGB, 5 bits per pixel */ for (i = 0; i < pixels; i++) { pixel = in[0] + (in[1] << 8); out[R] = (pixel & 31) * 255 / 31; - out[G] = ((pixel>>5) & 31) * 255 / 31; - out[B] = ((pixel>>10) & 31) * 255 / 31; + out[G] = ((pixel >> 5) & 31) * 255 / 31; + out[B] = ((pixel >> 10) & 31) * 255 / 31; out[A] = 255; - out += 4; in += 2; + out += 4; + in += 2; } } void -ImagingUnpackRGBA15(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackRGBA15(UINT8 *out, const UINT8 *in, int pixels) { int i, pixel; /* RGB, 5/5/5/1 bits per pixel */ for (i = 0; i < pixels; i++) { pixel = in[0] + (in[1] << 8); out[R] = (pixel & 31) * 255 / 31; - out[G] = ((pixel>>5) & 31) * 255 / 31; - out[B] = ((pixel>>10) & 31) * 255 / 31; - out[A] = (pixel>>15) * 255; - out += 4; in += 2; + out[G] = ((pixel >> 5) & 31) * 255 / 31; + out[B] = ((pixel >> 10) & 31) * 255 / 31; + out[A] = (pixel >> 15) * 255; + out += 4; + in += 2; } } void -ImagingUnpackBGR15(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackBGR15(UINT8 *out, const UINT8 *in, int pixels) { int i, pixel; /* RGB, reversed bytes, 5 bits per pixel */ for (i = 0; i < pixels; i++) { pixel = in[0] + (in[1] << 8); out[B] = (pixel & 31) * 255 / 31; - out[G] = ((pixel>>5) & 31) * 255 / 31; - out[R] = ((pixel>>10) & 31) * 255 / 31; + out[G] = ((pixel >> 5) & 31) * 255 / 31; + out[R] = ((pixel >> 10) & 31) * 255 / 31; out[A] = 255; - out += 4; in += 2; + out += 4; + in += 2; } } void -ImagingUnpackBGRA15(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackBGRA15(UINT8 *out, const UINT8 *in, int pixels) { int i, pixel; /* RGB, reversed bytes, 5/5/5/1 bits per pixel */ for (i = 0; i < pixels; i++) { pixel = in[0] + (in[1] << 8); out[B] = (pixel & 31) * 255 / 31; - out[G] = ((pixel>>5) & 31) * 255 / 31; - out[R] = ((pixel>>10) & 31) * 255 / 31; - out[A] = (pixel>>15) * 255; - out += 4; in += 2; + out[G] = ((pixel >> 5) & 31) * 255 / 31; + out[R] = ((pixel >> 10) & 31) * 255 / 31; + out[A] = (pixel >> 15) * 255; + out += 4; + in += 2; } } void -ImagingUnpackRGB16(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackRGB16(UINT8 *out, const UINT8 *in, int pixels) { int i, pixel; /* RGB, 5/6/5 bits per pixel */ for (i = 0; i < pixels; i++) { pixel = in[0] + (in[1] << 8); out[R] = (pixel & 31) * 255 / 31; - out[G] = ((pixel>>5) & 63) * 255 / 63; - out[B] = ((pixel>>11) & 31) * 255 / 31; + out[G] = ((pixel >> 5) & 63) * 255 / 63; + out[B] = ((pixel >> 11) & 31) * 255 / 31; out[A] = 255; - out += 4; in += 2; + out += 4; + in += 2; } } void -ImagingUnpackBGR16(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackBGR16(UINT8 *out, const UINT8 *in, int pixels) { int i, pixel; /* RGB, reversed bytes, 5/6/5 bits per pixel */ for (i = 0; i < pixels; i++) { pixel = in[0] + (in[1] << 8); out[B] = (pixel & 31) * 255 / 31; - out[G] = ((pixel>>5) & 63) * 255 / 63; - out[R] = ((pixel>>11) & 31) * 255 / 31; + out[G] = ((pixel >> 5) & 63) * 255 / 63; + out[R] = ((pixel >> 11) & 31) * 255 / 31; out[A] = 255; - out += 4; in += 2; + out += 4; + in += 2; } } void -ImagingUnpackRGB4B(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackRGB4B(UINT8 *out, const UINT8 *in, int pixels) { int i, pixel; /* RGB, 4 bits per pixel */ for (i = 0; i < pixels; i++) { pixel = in[0] + (in[1] << 8); out[R] = (pixel & 15) * 17; - out[G] = ((pixel>>4) & 15) * 17; - out[B] = ((pixel>>8) & 15) * 17; + out[G] = ((pixel >> 4) & 15) * 17; + out[B] = ((pixel >> 8) & 15) * 17; out[A] = 255; - out += 4; in += 2; + out += 4; + in += 2; } } void -ImagingUnpackRGBA4B(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackRGBA4B(UINT8 *out, const UINT8 *in, int pixels) { int i, pixel; /* RGBA, 4 bits per pixel */ for (i = 0; i < pixels; i++) { pixel = in[0] + (in[1] << 8); out[R] = (pixel & 15) * 17; - out[G] = ((pixel>>4) & 15) * 17; - out[B] = ((pixel>>8) & 15) * 17; - out[A] = ((pixel>>12) & 15) * 17; - out += 4; in += 2; + out[G] = ((pixel >> 4) & 15) * 17; + out[B] = ((pixel >> 8) & 15) * 17; + out[A] = ((pixel >> 12) & 15) * 17; + out += 4; + in += 2; } } static void -ImagingUnpackBGRX(UINT8* _out, const UINT8* in, int pixels) -{ +ImagingUnpackBGRX(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGB, reversed bytes with padding */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[2], in[1], in[0], 255); memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } static void -ImagingUnpackXRGB(UINT8* _out, const UINT8* in, int pixels) -{ +ImagingUnpackXRGB(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGB, leading pad */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[1], in[2], in[3], 255); memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } static void -ImagingUnpackXBGR(UINT8* _out, const UINT8* in, int pixels) -{ +ImagingUnpackXBGR(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGB, reversed bytes, leading pad */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[3], in[2], in[1], 255); memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } /* Unpack to "RGBA" image */ static void -unpackRGBALA(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBALA(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* greyscale with alpha */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[0], in[0], in[0], in[1]); memcpy(_out, &iv, sizeof(iv)); - in += 2; _out += 4; + in += 2; + _out += 4; } } static void -unpackRGBALA16B(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBALA16B(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* 16-bit greyscale with alpha, big-endian */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[0], in[0], in[0], in[2]); memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } static void -unpackRGBa16L(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBa16L(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* premultiplied 16-bit RGBA, little-endian */ for (i = 0; i < pixels; i++) { int a = in[7]; UINT32 iv; - if ( ! a) { + if (!a) { iv = 0; } else if (a == 255) { iv = MAKE_UINT32(in[1], in[3], in[5], a); } else { - iv = MAKE_UINT32(CLIP8(in[1] * 255 / a), - CLIP8(in[3] * 255 / a), - CLIP8(in[5] * 255 / a), a); + iv = MAKE_UINT32( + CLIP8(in[1] * 255 / a), + CLIP8(in[3] * 255 / a), + CLIP8(in[5] * 255 / a), + a); } memcpy(_out, &iv, sizeof(iv)); - in += 8; _out += 4; + in += 8; + _out += 4; } } static void -unpackRGBa16B(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBa16B(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* premultiplied 16-bit RGBA, big-endian */ for (i = 0; i < pixels; i++) { int a = in[6]; UINT32 iv; - if ( ! a) { + if (!a) { iv = 0; } else if (a == 255) { iv = MAKE_UINT32(in[0], in[2], in[4], a); } else { - iv = MAKE_UINT32(CLIP8(in[0] * 255 / a), - CLIP8(in[2] * 255 / a), - CLIP8(in[4] * 255 / a), a); + iv = MAKE_UINT32( + CLIP8(in[0] * 255 / a), + CLIP8(in[2] * 255 / a), + CLIP8(in[4] * 255 / a), + a); } memcpy(_out, &iv, sizeof(iv)); - in += 8; _out += 4; + in += 8; + _out += 4; } } static void -unpackRGBa(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBa(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* premultiplied RGBA */ for (i = 0; i < pixels; i++) { int a = in[3]; UINT32 iv; - if ( ! a) { + if (!a) { iv = 0; } else if (a == 255) { iv = MAKE_UINT32(in[0], in[1], in[2], a); } else { - iv = MAKE_UINT32(CLIP8(in[0] * 255 / a), - CLIP8(in[1] * 255 / a), - CLIP8(in[2] * 255 / a), a); + iv = MAKE_UINT32( + CLIP8(in[0] * 255 / a), + CLIP8(in[1] * 255 / a), + CLIP8(in[2] * 255 / a), + a); } memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } static void -unpackRGBaskip1(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBaskip1(UINT8 *_out, const UINT8 *in, int pixels) { int i; - UINT32* out = (UINT32*) _out; + UINT32 *out = (UINT32 *)_out; /* premultiplied RGBA */ for (i = 0; i < pixels; i++) { int a = in[3]; - if ( ! a) { + if (!a) { out[i] = 0; } else if (a == 255) { out[i] = MAKE_UINT32(in[0], in[1], in[2], a); } else { - out[i] = MAKE_UINT32(CLIP8(in[0] * 255 / a), - CLIP8(in[1] * 255 / a), - CLIP8(in[2] * 255 / a), a); + out[i] = MAKE_UINT32( + CLIP8(in[0] * 255 / a), + CLIP8(in[1] * 255 / a), + CLIP8(in[2] * 255 / a), + a); } in += 5; } } static void -unpackRGBaskip2(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBaskip2(UINT8 *_out, const UINT8 *in, int pixels) { int i; - UINT32* out = (UINT32*) _out; + UINT32 *out = (UINT32 *)_out; /* premultiplied RGBA */ for (i = 0; i < pixels; i++) { int a = in[3]; - if ( ! a) { + if (!a) { out[i] = 0; } else if (a == 255) { out[i] = MAKE_UINT32(in[0], in[1], in[2], a); } else { - out[i] = MAKE_UINT32(CLIP8(in[0] * 255 / a), - CLIP8(in[1] * 255 / a), - CLIP8(in[2] * 255 / a), a); + out[i] = MAKE_UINT32( + CLIP8(in[0] * 255 / a), + CLIP8(in[1] * 255 / a), + CLIP8(in[2] * 255 / a), + a); } in += 6; } } static void -unpackBGRa(UINT8* _out, const UINT8* in, int pixels) -{ +unpackBGRa(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* premultiplied BGRA */ for (i = 0; i < pixels; i++) { int a = in[3]; UINT32 iv; - if ( ! a) { + if (!a) { iv = 0; } else if (a == 255) { iv = MAKE_UINT32(in[2], in[1], in[0], a); } else { - iv = MAKE_UINT32(CLIP8(in[2] * 255 / a), - CLIP8(in[1] * 255 / a), - CLIP8(in[0] * 255 / a), a); + iv = MAKE_UINT32( + CLIP8(in[2] * 255 / a), + CLIP8(in[1] * 255 / a), + CLIP8(in[0] * 255 / a), + a); } memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } static void -unpackRGBAI(UINT8* out, const UINT8* in, int pixels) -{ +unpackRGBAI(UINT8 *out, const UINT8 *in, int pixels) { int i; /* RGBA, inverted RGB bytes (FlashPix) */ for (i = 0; i < pixels; i++) { @@ -877,28 +988,30 @@ unpackRGBAI(UINT8* out, const UINT8* in, int pixels) out[G] = ~in[1]; out[B] = ~in[2]; out[A] = in[3]; - out += 4; in += 4; + out += 4; + in += 4; } } static void -unpackRGBAL(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBAL(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGBA, line interleaved */ - for (i = 0; i < pixels; i++, _out+=4) { - UINT32 iv = MAKE_UINT32(in[i], in[i+pixels], in[i+pixels+pixels], - in[i+pixels+pixels+pixels]); + for (i = 0; i < pixels; i++, _out += 4) { + UINT32 iv = MAKE_UINT32( + in[i], + in[i + pixels], + in[i + pixels + pixels], + in[i + pixels + pixels + pixels]); memcpy(_out, &iv, sizeof(iv)); } } void -unpackRGBA16L(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBA16L(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* 16-bit RGBA, little-endian order */ - for (i = 0; i < pixels; i++, _out+=4) { + for (i = 0; i < pixels; i++, _out += 4) { UINT32 iv = MAKE_UINT32(in[1], in[3], in[5], in[7]); memcpy(_out, &iv, sizeof(iv)); in += 8; @@ -906,11 +1019,10 @@ unpackRGBA16L(UINT8* _out, const UINT8* in, int pixels) } void -unpackRGBA16B(UINT8* _out, const UINT8* in, int pixels) -{ +unpackRGBA16B(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* 16-bit RGBA, big-endian order */ - for (i = 0; i < pixels; i++, _out+=4) { + for (i = 0; i < pixels; i++, _out += 4) { UINT32 iv = MAKE_UINT32(in[0], in[2], in[4], in[6]); memcpy(_out, &iv, sizeof(iv)); in += 8; @@ -918,53 +1030,52 @@ unpackRGBA16B(UINT8* _out, const UINT8* in, int pixels) } static void -unpackARGB(UINT8* _out, const UINT8* in, int pixels) -{ +unpackARGB(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGBA, leading pad */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[1], in[2], in[3], in[0]); memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } static void -unpackABGR(UINT8* _out, const UINT8* in, int pixels) -{ +unpackABGR(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGBA, reversed bytes */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[3], in[2], in[1], in[0]); memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } static void -unpackBGRA(UINT8* _out, const UINT8* in, int pixels) -{ +unpackBGRA(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* RGBA, reversed bytes */ for (i = 0; i < pixels; i++) { UINT32 iv = MAKE_UINT32(in[2], in[1], in[0], in[3]); memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } - /* Unpack to "CMYK" image */ static void -unpackCMYKI(UINT8* _out, const UINT8* in, int pixels) -{ +unpackCMYKI(UINT8 *_out, const UINT8 *in, int pixels) { int i; /* CMYK, inverted bytes (Photoshop 2.5) */ for (i = 0; i < pixels; i++) { UINT32 iv = ~MAKE_UINT32(in[0], in[1], in[2], in[3]); memcpy(_out, &iv, sizeof(iv)); - in += 4; _out += 4; + in += 4; + _out += 4; } } @@ -980,8 +1091,7 @@ unpackCMYKI(UINT8* _out, const UINT8* in, int pixels) internally, and we'll unshift for saving and whatnot. */ void -ImagingUnpackLAB(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackLAB(UINT8 *out, const UINT8 *in, int pixels) { int i; /* LAB triplets */ for (i = 0; i < pixels; i++) { @@ -989,32 +1099,34 @@ ImagingUnpackLAB(UINT8* out, const UINT8* in, int pixels) out[1] = in[1] ^ 128; /* signed in outside world */ out[2] = in[2] ^ 128; out[3] = 255; - out += 4; in += 3; + out += 4; + in += 3; } } static void -unpackI16N_I16B(UINT8* out, const UINT8* in, int pixels){ +unpackI16N_I16B(UINT8 *out, const UINT8 *in, int pixels) { int i; - UINT8* tmp = (UINT8*) out; + UINT8 *tmp = (UINT8 *)out; for (i = 0; i < pixels; i++) { C16B; - in += 2; tmp += 2; + in += 2; + tmp += 2; } - } static void -unpackI16N_I16(UINT8* out, const UINT8* in, int pixels){ +unpackI16N_I16(UINT8 *out, const UINT8 *in, int pixels) { int i; - UINT8* tmp = (UINT8*) out; + UINT8 *tmp = (UINT8 *)out; for (i = 0; i < pixels; i++) { C16L; - in += 2; tmp += 2; + in += 2; + tmp += 2; } } static void -unpackI12_I16(UINT8* out, const UINT8* in, int pixels){ +unpackI12_I16(UINT8 *out, const UINT8 *in, int pixels) { /* Fillorder 1/MSB -> LittleEndian, for 12bit integer greyscale tiffs. According to the TIFF spec: @@ -1036,103 +1148,100 @@ unpackI12_I16(UINT8* out, const UINT8* in, int pixels){ int i; UINT16 pixel; #ifdef WORDS_BIGENDIAN - UINT8* tmp = (UINT8 *)&pixel; + UINT8 *tmp = (UINT8 *)&pixel; #endif - for (i = 0; i < pixels-1; i+=2) { - pixel = (((UINT16) in[0]) << 4 ) + (in[1] >>4); + for (i = 0; i < pixels - 1; i += 2) { + pixel = (((UINT16)in[0]) << 4) + (in[1] >> 4); #ifdef WORDS_BIGENDIAN - out[0] = tmp[1]; out[1] = tmp[0]; + out[0] = tmp[1]; + out[1] = tmp[0]; #else memcpy(out, &pixel, sizeof(pixel)); #endif - out+=2; - pixel = (((UINT16) (in[1] & 0x0F)) << 8) + in[2]; + out += 2; + pixel = (((UINT16)(in[1] & 0x0F)) << 8) + in[2]; #ifdef WORDS_BIGENDIAN - out[0] = tmp[1]; out[1] = tmp[0]; + out[0] = tmp[1]; + out[1] = tmp[0]; #else memcpy(out, &pixel, sizeof(pixel)); #endif - in += 3; out+=2; + in += 3; + out += 2; } - if (i == pixels-1) { - pixel = (((UINT16) in[0]) << 4 ) + (in[1] >>4); + if (i == pixels - 1) { + pixel = (((UINT16)in[0]) << 4) + (in[1] >> 4); #ifdef WORDS_BIGENDIAN - out[0] = tmp[1]; out[1] = tmp[0]; + out[0] = tmp[1]; + out[1] = tmp[0]; #else memcpy(out, &pixel, sizeof(pixel)); #endif } } - static void -copy1(UINT8* out, const UINT8* in, int pixels) -{ +copy1(UINT8 *out, const UINT8 *in, int pixels) { /* L, P */ memcpy(out, in, pixels); } static void -copy2(UINT8* out, const UINT8* in, int pixels) -{ +copy2(UINT8 *out, const UINT8 *in, int pixels) { /* I;16 */ - memcpy(out, in, pixels*2); + memcpy(out, in, pixels * 2); } static void -copy4(UINT8* out, const UINT8* in, int pixels) -{ +copy4(UINT8 *out, const UINT8 *in, int pixels) { /* RGBA, CMYK quadruples */ memcpy(out, in, 4 * pixels); } static void -copy4skip1(UINT8* _out, const UINT8* in, int pixels) -{ +copy4skip1(UINT8 *_out, const UINT8 *in, int pixels) { int i; for (i = 0; i < pixels; i++) { memcpy(_out, in, 4); - in += 5; _out += 4; + in += 5; + _out += 4; } } static void -copy4skip2(UINT8* _out, const UINT8* in, int pixels) -{ +copy4skip2(UINT8 *_out, const UINT8 *in, int pixels) { int i; for (i = 0; i < pixels; i++) { memcpy(_out, in, 4); - in += 6; _out += 4; + in += 6; + _out += 4; } } - /* Unpack to "I" and "F" images */ -#define UNPACK_RAW(NAME, GET, INTYPE, OUTTYPE)\ -static void NAME(UINT8* out_, const UINT8* in, int pixels)\ -{\ - int i;\ - OUTTYPE* out = (OUTTYPE*) out_;\ - for (i = 0; i < pixels; i++, in += sizeof(INTYPE)) {\ - out[i] = (OUTTYPE) ((INTYPE) GET);\ - }\ -} +#define UNPACK_RAW(NAME, GET, INTYPE, OUTTYPE) \ + static void NAME(UINT8 *out_, const UINT8 *in, int pixels) { \ + int i; \ + OUTTYPE *out = (OUTTYPE *)out_; \ + for (i = 0; i < pixels; i++, in += sizeof(INTYPE)) { \ + out[i] = (OUTTYPE)((INTYPE)GET); \ + } \ + } -#define UNPACK(NAME, COPY, INTYPE, OUTTYPE)\ -static void NAME(UINT8* out_, const UINT8* in, int pixels)\ -{\ - int i;\ - OUTTYPE* out = (OUTTYPE*) out_;\ - INTYPE tmp_;\ - UINT8* tmp = (UINT8*) &tmp_;\ - for (i = 0; i < pixels; i++, in += sizeof(INTYPE)) {\ - COPY;\ - out[i] = (OUTTYPE) tmp_;\ - }\ -} +#define UNPACK(NAME, COPY, INTYPE, OUTTYPE) \ + static void NAME(UINT8 *out_, const UINT8 *in, int pixels) { \ + int i; \ + OUTTYPE *out = (OUTTYPE *)out_; \ + INTYPE tmp_; \ + UINT8 *tmp = (UINT8 *)&tmp_; \ + for (i = 0; i < pixels; i++, in += sizeof(INTYPE)) { \ + COPY; \ + out[i] = (OUTTYPE)tmp_; \ + } \ + } UNPACK_RAW(unpackI8, in[0], UINT8, INT32) UNPACK_RAW(unpackI8S, in[0], INT8, INT32) @@ -1172,12 +1281,10 @@ UNPACK(unpackF64BF, C64B, FLOAT64, FLOAT32) UNPACK(unpackF64NF, C64N, FLOAT64, FLOAT32) #endif - /* Misc. unpackers */ static void -band0(UINT8* out, const UINT8* in, int pixels) -{ +band0(UINT8 *out, const UINT8 *in, int pixels) { int i; /* band 0 only */ for (i = 0; i < pixels; i++) { @@ -1187,8 +1294,7 @@ band0(UINT8* out, const UINT8* in, int pixels) } static void -band1(UINT8* out, const UINT8* in, int pixels) -{ +band1(UINT8 *out, const UINT8 *in, int pixels) { int i; /* band 1 only */ for (i = 0; i < pixels; i++) { @@ -1198,8 +1304,7 @@ band1(UINT8* out, const UINT8* in, int pixels) } static void -band2(UINT8* out, const UINT8* in, int pixels) -{ +band2(UINT8 *out, const UINT8 *in, int pixels) { int i; /* band 2 only */ for (i = 0; i < pixels; i++) { @@ -1209,8 +1314,7 @@ band2(UINT8* out, const UINT8* in, int pixels) } static void -band3(UINT8* out, const UINT8* in, int pixels) -{ +band3(UINT8 *out, const UINT8 *in, int pixels) { /* band 3 only */ int i; for (i = 0; i < pixels; i++) { @@ -1220,8 +1324,7 @@ band3(UINT8* out, const UINT8* in, int pixels) } static void -band0I(UINT8* out, const UINT8* in, int pixels) -{ +band0I(UINT8 *out, const UINT8 *in, int pixels) { int i; /* band 0 only */ for (i = 0; i < pixels; i++) { @@ -1231,8 +1334,7 @@ band0I(UINT8* out, const UINT8* in, int pixels) } static void -band1I(UINT8* out, const UINT8* in, int pixels) -{ +band1I(UINT8 *out, const UINT8 *in, int pixels) { int i; /* band 1 only */ for (i = 0; i < pixels; i++) { @@ -1242,8 +1344,7 @@ band1I(UINT8* out, const UINT8* in, int pixels) } static void -band2I(UINT8* out, const UINT8* in, int pixels) -{ +band2I(UINT8 *out, const UINT8 *in, int pixels) { int i; /* band 2 only */ for (i = 0; i < pixels; i++) { @@ -1253,8 +1354,7 @@ band2I(UINT8* out, const UINT8* in, int pixels) } static void -band3I(UINT8* out, const UINT8* in, int pixels) -{ +band3I(UINT8 *out, const UINT8 *in, int pixels) { /* band 3 only */ int i; for (i = 0; i < pixels; i++) { @@ -1264,8 +1364,8 @@ band3I(UINT8* out, const UINT8* in, int pixels) } static struct { - const char* mode; - const char* rawmode; + const char *mode; + const char *rawmode; int bits; ImagingShuffler unpack; } unpackers[] = { @@ -1282,244 +1382,242 @@ static struct { /* exception: rawmodes "I" and "F" are always native endian byte order */ /* bilevel */ - {"1", "1", 1, unpack1}, - {"1", "1;I", 1, unpack1I}, - {"1", "1;R", 1, unpack1R}, - {"1", "1;IR", 1, unpack1IR}, - {"1", "1;8", 8, unpack18}, + {"1", "1", 1, unpack1}, + {"1", "1;I", 1, unpack1I}, + {"1", "1;R", 1, unpack1R}, + {"1", "1;IR", 1, unpack1IR}, + {"1", "1;8", 8, unpack18}, /* greyscale */ - {"L", "L;2", 2, unpackL2}, - {"L", "L;2I", 2, unpackL2I}, - {"L", "L;2R", 2, unpackL2R}, - {"L", "L;2IR", 2, unpackL2IR}, + {"L", "L;2", 2, unpackL2}, + {"L", "L;2I", 2, unpackL2I}, + {"L", "L;2R", 2, unpackL2R}, + {"L", "L;2IR", 2, unpackL2IR}, - {"L", "L;4", 4, unpackL4}, - {"L", "L;4I", 4, unpackL4I}, - {"L", "L;4R", 4, unpackL4R}, - {"L", "L;4IR", 4, unpackL4IR}, + {"L", "L;4", 4, unpackL4}, + {"L", "L;4I", 4, unpackL4I}, + {"L", "L;4R", 4, unpackL4R}, + {"L", "L;4IR", 4, unpackL4IR}, - {"L", "L", 8, copy1}, - {"L", "L;I", 8, unpackLI}, - {"L", "L;R", 8, unpackLR}, - {"L", "L;16", 16, unpackL16}, - {"L", "L;16B", 16, unpackL16B}, + {"L", "L", 8, copy1}, + {"L", "L;I", 8, unpackLI}, + {"L", "L;R", 8, unpackLR}, + {"L", "L;16", 16, unpackL16}, + {"L", "L;16B", 16, unpackL16B}, /* greyscale w. alpha */ - {"LA", "LA", 16, unpackLA}, - {"LA", "LA;L", 16, unpackLAL}, + {"LA", "LA", 16, unpackLA}, + {"LA", "LA;L", 16, unpackLAL}, /* greyscale w. alpha premultiplied */ - {"La", "La", 16, unpackLA}, + {"La", "La", 16, unpackLA}, /* palette */ - {"P", "P;1", 1, unpackP1}, - {"P", "P;2", 2, unpackP2}, - {"P", "P;2L", 2, unpackP2L}, - {"P", "P;4", 4, unpackP4}, - {"P", "P;4L", 4, unpackP4L}, - {"P", "P", 8, copy1}, - {"P", "P;R", 8, unpackLR}, + {"P", "P;1", 1, unpackP1}, + {"P", "P;2", 2, unpackP2}, + {"P", "P;2L", 2, unpackP2L}, + {"P", "P;4", 4, unpackP4}, + {"P", "P;4L", 4, unpackP4L}, + {"P", "P", 8, copy1}, + {"P", "P;R", 8, unpackLR}, /* palette w. alpha */ - {"PA", "PA", 16, unpackLA}, - {"PA", "PA;L", 16, unpackLAL}, + {"PA", "PA", 16, unpackLA}, + {"PA", "PA;L", 16, unpackLAL}, /* true colour */ - {"RGB", "RGB", 24, ImagingUnpackRGB}, - {"RGB", "RGB;L", 24, unpackRGBL}, - {"RGB", "RGB;R", 24, unpackRGBR}, - {"RGB", "RGB;16L", 48, unpackRGB16L}, - {"RGB", "RGB;16B", 48, unpackRGB16B}, - {"RGB", "BGR", 24, ImagingUnpackBGR}, - {"RGB", "RGB;15", 16, ImagingUnpackRGB15}, - {"RGB", "BGR;15", 16, ImagingUnpackBGR15}, - {"RGB", "RGB;16", 16, ImagingUnpackRGB16}, - {"RGB", "BGR;16", 16, ImagingUnpackBGR16}, - {"RGB", "RGB;4B", 16, ImagingUnpackRGB4B}, - {"RGB", "BGR;5", 16, ImagingUnpackBGR15}, /* compat */ - {"RGB", "RGBX", 32, copy4}, - {"RGB", "RGBX;L", 32, unpackRGBAL}, - {"RGB", "RGBA;L", 32, unpackRGBAL}, - {"RGB", "BGRX", 32, ImagingUnpackBGRX}, - {"RGB", "XRGB", 32, ImagingUnpackXRGB}, - {"RGB", "XBGR", 32, ImagingUnpackXBGR}, - {"RGB", "YCC;P", 24, ImagingUnpackYCC}, - {"RGB", "R", 8, band0}, - {"RGB", "G", 8, band1}, - {"RGB", "B", 8, band2}, + {"RGB", "RGB", 24, ImagingUnpackRGB}, + {"RGB", "RGB;L", 24, unpackRGBL}, + {"RGB", "RGB;R", 24, unpackRGBR}, + {"RGB", "RGB;16L", 48, unpackRGB16L}, + {"RGB", "RGB;16B", 48, unpackRGB16B}, + {"RGB", "BGR", 24, ImagingUnpackBGR}, + {"RGB", "RGB;15", 16, ImagingUnpackRGB15}, + {"RGB", "BGR;15", 16, ImagingUnpackBGR15}, + {"RGB", "RGB;16", 16, ImagingUnpackRGB16}, + {"RGB", "BGR;16", 16, ImagingUnpackBGR16}, + {"RGB", "RGB;4B", 16, ImagingUnpackRGB4B}, + {"RGB", "BGR;5", 16, ImagingUnpackBGR15}, /* compat */ + {"RGB", "RGBX", 32, copy4}, + {"RGB", "RGBX;L", 32, unpackRGBAL}, + {"RGB", "RGBA;L", 32, unpackRGBAL}, + {"RGB", "BGRX", 32, ImagingUnpackBGRX}, + {"RGB", "XRGB", 32, ImagingUnpackXRGB}, + {"RGB", "XBGR", 32, ImagingUnpackXBGR}, + {"RGB", "YCC;P", 24, ImagingUnpackYCC}, + {"RGB", "R", 8, band0}, + {"RGB", "G", 8, band1}, + {"RGB", "B", 8, band2}, /* true colour w. alpha */ - {"RGBA", "LA", 16, unpackRGBALA}, - {"RGBA", "LA;16B", 32, unpackRGBALA16B}, - {"RGBA", "RGBA", 32, copy4}, - {"RGBA", "RGBAX", 40, copy4skip1}, - {"RGBA", "RGBAXX", 48, copy4skip2}, - {"RGBA", "RGBa", 32, unpackRGBa}, - {"RGBA", "RGBaX", 40, unpackRGBaskip1}, - {"RGBA", "RGBaXX", 48, unpackRGBaskip2}, - {"RGBA", "RGBa;16L", 64, unpackRGBa16L}, - {"RGBA", "RGBa;16B", 64, unpackRGBa16B}, - {"RGBA", "BGRa", 32, unpackBGRa}, - {"RGBA", "RGBA;I", 32, unpackRGBAI}, - {"RGBA", "RGBA;L", 32, unpackRGBAL}, - {"RGBA", "RGBA;15", 16, ImagingUnpackRGBA15}, - {"RGBA", "BGRA;15", 16, ImagingUnpackBGRA15}, - {"RGBA", "RGBA;4B", 16, ImagingUnpackRGBA4B}, - {"RGBA", "RGBA;16L", 64, unpackRGBA16L}, - {"RGBA", "RGBA;16B", 64, unpackRGBA16B}, - {"RGBA", "BGRA", 32, unpackBGRA}, - {"RGBA", "ARGB", 32, unpackARGB}, - {"RGBA", "ABGR", 32, unpackABGR}, - {"RGBA", "YCCA;P", 32, ImagingUnpackYCCA}, - {"RGBA", "R", 8, band0}, - {"RGBA", "G", 8, band1}, - {"RGBA", "B", 8, band2}, - {"RGBA", "A", 8, band3}, + {"RGBA", "LA", 16, unpackRGBALA}, + {"RGBA", "LA;16B", 32, unpackRGBALA16B}, + {"RGBA", "RGBA", 32, copy4}, + {"RGBA", "RGBAX", 40, copy4skip1}, + {"RGBA", "RGBAXX", 48, copy4skip2}, + {"RGBA", "RGBa", 32, unpackRGBa}, + {"RGBA", "RGBaX", 40, unpackRGBaskip1}, + {"RGBA", "RGBaXX", 48, unpackRGBaskip2}, + {"RGBA", "RGBa;16L", 64, unpackRGBa16L}, + {"RGBA", "RGBa;16B", 64, unpackRGBa16B}, + {"RGBA", "BGRa", 32, unpackBGRa}, + {"RGBA", "RGBA;I", 32, unpackRGBAI}, + {"RGBA", "RGBA;L", 32, unpackRGBAL}, + {"RGBA", "RGBA;15", 16, ImagingUnpackRGBA15}, + {"RGBA", "BGRA;15", 16, ImagingUnpackBGRA15}, + {"RGBA", "RGBA;4B", 16, ImagingUnpackRGBA4B}, + {"RGBA", "RGBA;16L", 64, unpackRGBA16L}, + {"RGBA", "RGBA;16B", 64, unpackRGBA16B}, + {"RGBA", "BGRA", 32, unpackBGRA}, + {"RGBA", "ARGB", 32, unpackARGB}, + {"RGBA", "ABGR", 32, unpackABGR}, + {"RGBA", "YCCA;P", 32, ImagingUnpackYCCA}, + {"RGBA", "R", 8, band0}, + {"RGBA", "G", 8, band1}, + {"RGBA", "B", 8, band2}, + {"RGBA", "A", 8, band3}, #ifdef WORDS_BIGENDIAN - {"RGB", "RGB;16N", 48, unpackRGB16B}, - {"RGBA", "RGBa;16N", 64, unpackRGBa16B}, - {"RGBA", "RGBA;16N", 64, unpackRGBA16B}, - {"RGBX", "RGBX;16N", 64, unpackRGBA16B}, + {"RGB", "RGB;16N", 48, unpackRGB16B}, + {"RGBA", "RGBa;16N", 64, unpackRGBa16B}, + {"RGBA", "RGBA;16N", 64, unpackRGBA16B}, + {"RGBX", "RGBX;16N", 64, unpackRGBA16B}, #else - {"RGB", "RGB;16N", 48, unpackRGB16L}, - {"RGBA", "RGBa;16N", 64, unpackRGBa16L}, - {"RGBA", "RGBA;16N", 64, unpackRGBA16L}, - {"RGBX", "RGBX;16N", 64, unpackRGBA16B}, + {"RGB", "RGB;16N", 48, unpackRGB16L}, + {"RGBA", "RGBa;16N", 64, unpackRGBa16L}, + {"RGBA", "RGBA;16N", 64, unpackRGBA16L}, + {"RGBX", "RGBX;16N", 64, unpackRGBA16B}, #endif /* true colour w. alpha premultiplied */ - {"RGBa", "RGBa", 32, copy4}, - {"RGBa", "BGRa", 32, unpackBGRA}, - {"RGBa", "aRGB", 32, unpackARGB}, - {"RGBa", "aBGR", 32, unpackABGR}, + {"RGBa", "RGBa", 32, copy4}, + {"RGBa", "BGRa", 32, unpackBGRA}, + {"RGBa", "aRGB", 32, unpackARGB}, + {"RGBa", "aBGR", 32, unpackABGR}, /* true colour w. padding */ - {"RGBX", "RGB", 24, ImagingUnpackRGB}, - {"RGBX", "RGB;L", 24, unpackRGBL}, - {"RGBX", "RGB;16B", 48, unpackRGB16B}, - {"RGBX", "BGR", 24, ImagingUnpackBGR}, - {"RGBX", "RGB;15", 16, ImagingUnpackRGB15}, - {"RGBX", "BGR;15", 16, ImagingUnpackBGR15}, - {"RGBX", "RGB;4B", 16, ImagingUnpackRGB4B}, - {"RGBX", "BGR;5", 16, ImagingUnpackBGR15}, /* compat */ - {"RGBX", "RGBX", 32, copy4}, - {"RGBX", "RGBXX", 40, copy4skip1}, - {"RGBX", "RGBXXX", 48, copy4skip2}, - {"RGBX", "RGBX;L", 32, unpackRGBAL}, - {"RGBX", "RGBX;16L", 64, unpackRGBA16L}, - {"RGBX", "RGBX;16B", 64, unpackRGBA16B}, - {"RGBX", "BGRX", 32, ImagingUnpackBGRX}, - {"RGBX", "XRGB", 32, ImagingUnpackXRGB}, - {"RGBX", "XBGR", 32, ImagingUnpackXBGR}, - {"RGBX", "YCC;P", 24, ImagingUnpackYCC}, - {"RGBX", "R", 8, band0}, - {"RGBX", "G", 8, band1}, - {"RGBX", "B", 8, band2}, - {"RGBX", "X", 8, band3}, + {"RGBX", "RGB", 24, ImagingUnpackRGB}, + {"RGBX", "RGB;L", 24, unpackRGBL}, + {"RGBX", "RGB;16B", 48, unpackRGB16B}, + {"RGBX", "BGR", 24, ImagingUnpackBGR}, + {"RGBX", "RGB;15", 16, ImagingUnpackRGB15}, + {"RGBX", "BGR;15", 16, ImagingUnpackBGR15}, + {"RGBX", "RGB;4B", 16, ImagingUnpackRGB4B}, + {"RGBX", "BGR;5", 16, ImagingUnpackBGR15}, /* compat */ + {"RGBX", "RGBX", 32, copy4}, + {"RGBX", "RGBXX", 40, copy4skip1}, + {"RGBX", "RGBXXX", 48, copy4skip2}, + {"RGBX", "RGBX;L", 32, unpackRGBAL}, + {"RGBX", "RGBX;16L", 64, unpackRGBA16L}, + {"RGBX", "RGBX;16B", 64, unpackRGBA16B}, + {"RGBX", "BGRX", 32, ImagingUnpackBGRX}, + {"RGBX", "XRGB", 32, ImagingUnpackXRGB}, + {"RGBX", "XBGR", 32, ImagingUnpackXBGR}, + {"RGBX", "YCC;P", 24, ImagingUnpackYCC}, + {"RGBX", "R", 8, band0}, + {"RGBX", "G", 8, band1}, + {"RGBX", "B", 8, band2}, + {"RGBX", "X", 8, band3}, /* colour separation */ - {"CMYK", "CMYK", 32, copy4}, - {"CMYK", "CMYKX", 40, copy4skip1}, - {"CMYK", "CMYKXX", 48, copy4skip2}, - {"CMYK", "CMYK;I", 32, unpackCMYKI}, - {"CMYK", "CMYK;L", 32, unpackRGBAL}, - {"CMYK", "CMYK;16L", 64, unpackRGBA16L}, - {"CMYK", "CMYK;16B", 64, unpackRGBA16B}, - {"CMYK", "C", 8, band0}, - {"CMYK", "M", 8, band1}, - {"CMYK", "Y", 8, band2}, - {"CMYK", "K", 8, band3}, - {"CMYK", "C;I", 8, band0I}, - {"CMYK", "M;I", 8, band1I}, - {"CMYK", "Y;I", 8, band2I}, - {"CMYK", "K;I", 8, band3I}, + {"CMYK", "CMYK", 32, copy4}, + {"CMYK", "CMYKX", 40, copy4skip1}, + {"CMYK", "CMYKXX", 48, copy4skip2}, + {"CMYK", "CMYK;I", 32, unpackCMYKI}, + {"CMYK", "CMYK;L", 32, unpackRGBAL}, + {"CMYK", "CMYK;16L", 64, unpackRGBA16L}, + {"CMYK", "CMYK;16B", 64, unpackRGBA16B}, + {"CMYK", "C", 8, band0}, + {"CMYK", "M", 8, band1}, + {"CMYK", "Y", 8, band2}, + {"CMYK", "K", 8, band3}, + {"CMYK", "C;I", 8, band0I}, + {"CMYK", "M;I", 8, band1I}, + {"CMYK", "Y;I", 8, band2I}, + {"CMYK", "K;I", 8, band3I}, #ifdef WORDS_BIGENDIAN - {"CMYK", "CMYK;16N", 64, unpackRGBA16B}, + {"CMYK", "CMYK;16N", 64, unpackRGBA16B}, #else - {"CMYK", "CMYK;16N", 64, unpackRGBA16L}, + {"CMYK", "CMYK;16N", 64, unpackRGBA16L}, #endif /* video (YCbCr) */ - {"YCbCr", "YCbCr", 24, ImagingUnpackRGB}, - {"YCbCr", "YCbCr;L", 24, unpackRGBL}, - {"YCbCr", "YCbCrX", 32, copy4}, - {"YCbCr", "YCbCrK", 32, copy4}, + {"YCbCr", "YCbCr", 24, ImagingUnpackRGB}, + {"YCbCr", "YCbCr;L", 24, unpackRGBL}, + {"YCbCr", "YCbCrX", 32, copy4}, + {"YCbCr", "YCbCrK", 32, copy4}, /* LAB Color */ - {"LAB", "LAB", 24, ImagingUnpackLAB}, - {"LAB", "L", 8, band0}, - {"LAB", "A", 8, band1}, - {"LAB", "B", 8, band2}, + {"LAB", "LAB", 24, ImagingUnpackLAB}, + {"LAB", "L", 8, band0}, + {"LAB", "A", 8, band1}, + {"LAB", "B", 8, band2}, /* HSV Color */ - {"HSV", "HSV", 24, ImagingUnpackRGB}, - {"HSV", "H", 8, band0}, - {"HSV", "S", 8, band1}, - {"HSV", "V", 8, band2}, + {"HSV", "HSV", 24, ImagingUnpackRGB}, + {"HSV", "H", 8, band0}, + {"HSV", "S", 8, band1}, + {"HSV", "V", 8, band2}, /* integer variations */ - {"I", "I", 32, copy4}, - {"I", "I;8", 8, unpackI8}, - {"I", "I;8S", 8, unpackI8S}, - {"I", "I;16", 16, unpackI16}, - {"I", "I;16S", 16, unpackI16S}, - {"I", "I;16B", 16, unpackI16B}, - {"I", "I;16BS", 16, unpackI16BS}, - {"I", "I;16N", 16, unpackI16N}, - {"I", "I;16NS", 16, unpackI16NS}, - {"I", "I;32", 32, unpackI32}, - {"I", "I;32S", 32, unpackI32S}, - {"I", "I;32B", 32, unpackI32B}, - {"I", "I;32BS", 32, unpackI32BS}, - {"I", "I;32N", 32, unpackI32N}, - {"I", "I;32NS", 32, unpackI32NS}, + {"I", "I", 32, copy4}, + {"I", "I;8", 8, unpackI8}, + {"I", "I;8S", 8, unpackI8S}, + {"I", "I;16", 16, unpackI16}, + {"I", "I;16S", 16, unpackI16S}, + {"I", "I;16B", 16, unpackI16B}, + {"I", "I;16BS", 16, unpackI16BS}, + {"I", "I;16N", 16, unpackI16N}, + {"I", "I;16NS", 16, unpackI16NS}, + {"I", "I;32", 32, unpackI32}, + {"I", "I;32S", 32, unpackI32S}, + {"I", "I;32B", 32, unpackI32B}, + {"I", "I;32BS", 32, unpackI32BS}, + {"I", "I;32N", 32, unpackI32N}, + {"I", "I;32NS", 32, unpackI32NS}, /* floating point variations */ - {"F", "F", 32, copy4}, - {"F", "F;8", 8, unpackF8}, - {"F", "F;8S", 8, unpackF8S}, - {"F", "F;16", 16, unpackF16}, - {"F", "F;16S", 16, unpackF16S}, - {"F", "F;16B", 16, unpackF16B}, - {"F", "F;16BS", 16, unpackF16BS}, - {"F", "F;16N", 16, unpackF16N}, - {"F", "F;16NS", 16, unpackF16NS}, - {"F", "F;32", 32, unpackF32}, - {"F", "F;32S", 32, unpackF32S}, - {"F", "F;32B", 32, unpackF32B}, - {"F", "F;32BS", 32, unpackF32BS}, - {"F", "F;32N", 32, unpackF32N}, - {"F", "F;32NS", 32, unpackF32NS}, - {"F", "F;32F", 32, unpackF32F}, - {"F", "F;32BF", 32, unpackF32BF}, - {"F", "F;32NF", 32, unpackF32NF}, + {"F", "F", 32, copy4}, + {"F", "F;8", 8, unpackF8}, + {"F", "F;8S", 8, unpackF8S}, + {"F", "F;16", 16, unpackF16}, + {"F", "F;16S", 16, unpackF16S}, + {"F", "F;16B", 16, unpackF16B}, + {"F", "F;16BS", 16, unpackF16BS}, + {"F", "F;16N", 16, unpackF16N}, + {"F", "F;16NS", 16, unpackF16NS}, + {"F", "F;32", 32, unpackF32}, + {"F", "F;32S", 32, unpackF32S}, + {"F", "F;32B", 32, unpackF32B}, + {"F", "F;32BS", 32, unpackF32BS}, + {"F", "F;32N", 32, unpackF32N}, + {"F", "F;32NS", 32, unpackF32NS}, + {"F", "F;32F", 32, unpackF32F}, + {"F", "F;32BF", 32, unpackF32BF}, + {"F", "F;32NF", 32, unpackF32NF}, #ifdef FLOAT64 - {"F", "F;64F", 64, unpackF64F}, - {"F", "F;64BF", 64, unpackF64BF}, - {"F", "F;64NF", 64, unpackF64NF}, + {"F", "F;64F", 64, unpackF64F}, + {"F", "F;64BF", 64, unpackF64BF}, + {"F", "F;64NF", 64, unpackF64NF}, #endif /* storage modes */ - {"I;16", "I;16", 16, copy2}, - {"I;16B", "I;16B", 16, copy2}, - {"I;16L", "I;16L", 16, copy2}, + {"I;16", "I;16", 16, copy2}, + {"I;16B", "I;16B", 16, copy2}, + {"I;16L", "I;16L", 16, copy2}, - {"I;16", "I;16N", 16, unpackI16N_I16}, // LibTiff native->image endian. - {"I;16L", "I;16N", 16, unpackI16N_I16}, // LibTiff native->image endian. - {"I;16B", "I;16N", 16, unpackI16N_I16B}, + {"I;16", "I;16N", 16, unpackI16N_I16}, // LibTiff native->image endian. + {"I;16L", "I;16N", 16, unpackI16N_I16}, // LibTiff native->image endian. + {"I;16B", "I;16N", 16, unpackI16N_I16B}, - {"I;16", "I;12", 12, unpackI12_I16}, // 12 bit Tiffs stored in 16bits. + {"I;16", "I;12", 12, unpackI12_I16}, // 12 bit Tiffs stored in 16bits. {NULL} /* sentinel */ }; - ImagingShuffler -ImagingFindUnpacker(const char* mode, const char* rawmode, int* bits_out) -{ +ImagingFindUnpacker(const char *mode, const char *rawmode, int *bits_out) { int i; /* find a suitable pixel unpacker */ diff --git a/src/libImaging/UnpackYCC.c b/src/libImaging/UnpackYCC.c index d6bce17ad..0b177bdd4 100644 --- a/src/libImaging/UnpackYCC.c +++ b/src/libImaging/UnpackYCC.c @@ -13,150 +13,151 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - /* Tables generated by pcdtables.py, based on transforms taken from the "Colour Space Conversions FAQ" by Roberts/Ford. */ -static INT16 L[] = { 0, 1, 3, 4, 5, 7, 8, 10, 11, 12, 14, 15, 16, 18, -19, 20, 22, 23, 24, 26, 27, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41, -42, 43, 45, 46, 48, 49, 50, 52, 53, 54, 56, 57, 58, 60, 61, 62, 64, -65, 67, 68, 69, 71, 72, 73, 75, 76, 77, 79, 80, 82, 83, 84, 86, 87, -88, 90, 91, 92, 94, 95, 96, 98, 99, 101, 102, 103, 105, 106, 107, 109, -110, 111, 113, 114, 115, 117, 118, 120, 121, 122, 124, 125, 126, 128, -129, 130, 132, 133, 134, 136, 137, 139, 140, 141, 143, 144, 145, 147, -148, 149, 151, 152, 153, 155, 156, 158, 159, 160, 162, 163, 164, 166, -167, 168, 170, 171, 173, 174, 175, 177, 178, 179, 181, 182, 183, 185, -186, 187, 189, 190, 192, 193, 194, 196, 197, 198, 200, 201, 202, 204, -205, 206, 208, 209, 211, 212, 213, 215, 216, 217, 219, 220, 221, 223, -224, 225, 227, 228, 230, 231, 232, 234, 235, 236, 238, 239, 240, 242, -243, 245, 246, 247, 249, 250, 251, 253, 254, 255, 257, 258, 259, 261, -262, 264, 265, 266, 268, 269, 270, 272, 273, 274, 276, 277, 278, 280, -281, 283, 284, 285, 287, 288, 289, 291, 292, 293, 295, 296, 297, 299, -300, 302, 303, 304, 306, 307, 308, 310, 311, 312, 314, 315, 317, 318, -319, 321, 322, 323, 325, 326, 327, 329, 330, 331, 333, 334, 336, 337, -338, 340, 341, 342, 344, 345, 346 }; +static INT16 L[] = { + 0, 1, 3, 4, 5, 7, 8, 10, 11, 12, 14, 15, 16, 18, 19, 20, + 22, 23, 24, 26, 27, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41, 42, + 43, 45, 46, 48, 49, 50, 52, 53, 54, 56, 57, 58, 60, 61, 62, 64, + 65, 67, 68, 69, 71, 72, 73, 75, 76, 77, 79, 80, 82, 83, 84, 86, + 87, 88, 90, 91, 92, 94, 95, 96, 98, 99, 101, 102, 103, 105, 106, 107, + 109, 110, 111, 113, 114, 115, 117, 118, 120, 121, 122, 124, 125, 126, 128, 129, + 130, 132, 133, 134, 136, 137, 139, 140, 141, 143, 144, 145, 147, 148, 149, 151, + 152, 153, 155, 156, 158, 159, 160, 162, 163, 164, 166, 167, 168, 170, 171, 173, + 174, 175, 177, 178, 179, 181, 182, 183, 185, 186, 187, 189, 190, 192, 193, 194, + 196, 197, 198, 200, 201, 202, 204, 205, 206, 208, 209, 211, 212, 213, 215, 216, + 217, 219, 220, 221, 223, 224, 225, 227, 228, 230, 231, 232, 234, 235, 236, 238, + 239, 240, 242, 243, 245, 246, 247, 249, 250, 251, 253, 254, 255, 257, 258, 259, + 261, 262, 264, 265, 266, 268, 269, 270, 272, 273, 274, 276, 277, 278, 280, 281, + 283, 284, 285, 287, 288, 289, 291, 292, 293, 295, 296, 297, 299, 300, 302, 303, + 304, 306, 307, 308, 310, 311, 312, 314, 315, 317, 318, 319, 321, 322, 323, 325, + 326, 327, 329, 330, 331, 333, 334, 336, 337, 338, 340, 341, 342, 344, 345, 346}; -static INT16 CB[] = { -345, -343, -341, -338, -336, -334, -332, -329, --327, -325, -323, -321, -318, -316, -314, -312, -310, -307, -305, --303, -301, -298, -296, -294, -292, -290, -287, -285, -283, -281, --278, -276, -274, -272, -270, -267, -265, -263, -261, -258, -256, --254, -252, -250, -247, -245, -243, -241, -239, -236, -234, -232, --230, -227, -225, -223, -221, -219, -216, -214, -212, -210, -207, --205, -203, -201, -199, -196, -194, -192, -190, -188, -185, -183, --181, -179, -176, -174, -172, -170, -168, -165, -163, -161, -159, --156, -154, -152, -150, -148, -145, -143, -141, -139, -137, -134, --132, -130, -128, -125, -123, -121, -119, -117, -114, -112, -110, --108, -105, -103, -101, -99, -97, -94, -92, -90, -88, -85, -83, -81, --79, -77, -74, -72, -70, -68, -66, -63, -61, -59, -57, -54, -52, -50, --48, -46, -43, -41, -39, -37, -34, -32, -30, -28, -26, -23, -21, -19, --17, -15, -12, -10, -8, -6, -3, -1, 0, 2, 4, 7, 9, 11, 13, 16, 18, 20, -22, 24, 27, 29, 31, 33, 35, 38, 40, 42, 44, 47, 49, 51, 53, 55, 58, -60, 62, 64, 67, 69, 71, 73, 75, 78, 80, 82, 84, 86, 89, 91, 93, 95, -98, 100, 102, 104, 106, 109, 111, 113, 115, 118, 120, 122, 124, 126, -129, 131, 133, 135, 138, 140, 142, 144, 146, 149, 151, 153, 155, 157, -160, 162, 164, 166, 169, 171, 173, 175, 177, 180, 182, 184, 186, 189, -191, 193, 195, 197, 200, 202, 204, 206, 208, 211, 213, 215, 217, 220 }; +static INT16 CB[] = { + -345, -343, -341, -338, -336, -334, -332, -329, -327, -325, -323, -321, -318, -316, + -314, -312, -310, -307, -305, -303, -301, -298, -296, -294, -292, -290, -287, -285, + -283, -281, -278, -276, -274, -272, -270, -267, -265, -263, -261, -258, -256, -254, + -252, -250, -247, -245, -243, -241, -239, -236, -234, -232, -230, -227, -225, -223, + -221, -219, -216, -214, -212, -210, -207, -205, -203, -201, -199, -196, -194, -192, + -190, -188, -185, -183, -181, -179, -176, -174, -172, -170, -168, -165, -163, -161, + -159, -156, -154, -152, -150, -148, -145, -143, -141, -139, -137, -134, -132, -130, + -128, -125, -123, -121, -119, -117, -114, -112, -110, -108, -105, -103, -101, -99, + -97, -94, -92, -90, -88, -85, -83, -81, -79, -77, -74, -72, -70, -68, + -66, -63, -61, -59, -57, -54, -52, -50, -48, -46, -43, -41, -39, -37, + -34, -32, -30, -28, -26, -23, -21, -19, -17, -15, -12, -10, -8, -6, + -3, -1, 0, 2, 4, 7, 9, 11, 13, 16, 18, 20, 22, 24, + 27, 29, 31, 33, 35, 38, 40, 42, 44, 47, 49, 51, 53, 55, + 58, 60, 62, 64, 67, 69, 71, 73, 75, 78, 80, 82, 84, 86, + 89, 91, 93, 95, 98, 100, 102, 104, 106, 109, 111, 113, 115, 118, + 120, 122, 124, 126, 129, 131, 133, 135, 138, 140, 142, 144, 146, 149, + 151, 153, 155, 157, 160, 162, 164, 166, 169, 171, 173, 175, 177, 180, + 182, 184, 186, 189, 191, 193, 195, 197, 200, 202, 204, 206, 208, 211, + 213, 215, 217, 220}; -static INT16 GB[] = { 67, 67, 66, 66, 65, 65, 65, 64, 64, 63, 63, 62, -62, 62, 61, 61, 60, 60, 59, 59, 59, 58, 58, 57, 57, 56, 56, 56, 55, -55, 54, 54, 53, 53, 52, 52, 52, 51, 51, 50, 50, 49, 49, 49, 48, 48, -47, 47, 46, 46, 46, 45, 45, 44, 44, 43, 43, 43, 42, 42, 41, 41, 40, -40, 40, 39, 39, 38, 38, 37, 37, 37, 36, 36, 35, 35, 34, 34, 34, 33, -33, 32, 32, 31, 31, 31, 30, 30, 29, 29, 28, 28, 28, 27, 27, 26, 26, -25, 25, 25, 24, 24, 23, 23, 22, 22, 22, 21, 21, 20, 20, 19, 19, 19, -18, 18, 17, 17, 16, 16, 15, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, -11, 10, 10, 9, 9, 9, 8, 8, 7, 7, 6, 6, 6, 5, 5, 4, 4, 3, 3, 3, 2, 2, -1, 1, 0, 0, 0, 0, 0, -1, -1, -2, -2, -2, -3, -3, -4, -4, -5, -5, -5, --6, -6, -7, -7, -8, -8, -8, -9, -9, -10, -10, -11, -11, -11, -12, -12, --13, -13, -14, -14, -14, -15, -15, -16, -16, -17, -17, -18, -18, -18, --19, -19, -20, -20, -21, -21, -21, -22, -22, -23, -23, -24, -24, -24, --25, -25, -26, -26, -27, -27, -27, -28, -28, -29, -29, -30, -30, -30, --31, -31, -32, -32, -33, -33, -33, -34, -34, -35, -35, -36, -36, -36, --37, -37, -38, -38, -39, -39, -39, -40, -40, -41, -41, -42 }; +static INT16 GB[] = { + 67, 67, 66, 66, 65, 65, 65, 64, 64, 63, 63, 62, 62, 62, 61, 61, + 60, 60, 59, 59, 59, 58, 58, 57, 57, 56, 56, 56, 55, 55, 54, 54, + 53, 53, 52, 52, 52, 51, 51, 50, 50, 49, 49, 49, 48, 48, 47, 47, + 46, 46, 46, 45, 45, 44, 44, 43, 43, 43, 42, 42, 41, 41, 40, 40, + 40, 39, 39, 38, 38, 37, 37, 37, 36, 36, 35, 35, 34, 34, 34, 33, + 33, 32, 32, 31, 31, 31, 30, 30, 29, 29, 28, 28, 28, 27, 27, 26, + 26, 25, 25, 25, 24, 24, 23, 23, 22, 22, 22, 21, 21, 20, 20, 19, + 19, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14, 14, 13, 13, 12, + 12, 12, 11, 11, 10, 10, 9, 9, 9, 8, 8, 7, 7, 6, 6, 6, + 5, 5, 4, 4, 3, 3, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, + -1, -1, -2, -2, -2, -3, -3, -4, -4, -5, -5, -5, -6, -6, -7, -7, + -8, -8, -8, -9, -9, -10, -10, -11, -11, -11, -12, -12, -13, -13, -14, -14, + -14, -15, -15, -16, -16, -17, -17, -18, -18, -18, -19, -19, -20, -20, -21, -21, + -21, -22, -22, -23, -23, -24, -24, -24, -25, -25, -26, -26, -27, -27, -27, -28, + -28, -29, -29, -30, -30, -30, -31, -31, -32, -32, -33, -33, -33, -34, -34, -35, + -35, -36, -36, -36, -37, -37, -38, -38, -39, -39, -39, -40, -40, -41, -41, -42}; -static INT16 CR[] = { -249, -247, -245, -243, -241, -239, -238, -236, --234, -232, -230, -229, -227, -225, -223, -221, -219, -218, -216, --214, -212, -210, -208, -207, -205, -203, -201, -199, -198, -196, --194, -192, -190, -188, -187, -185, -183, -181, -179, -178, -176, --174, -172, -170, -168, -167, -165, -163, -161, -159, -157, -156, --154, -152, -150, -148, -147, -145, -143, -141, -139, -137, -136, --134, -132, -130, -128, -127, -125, -123, -121, -119, -117, -116, --114, -112, -110, -108, -106, -105, -103, -101, -99, -97, -96, -94, --92, -90, -88, -86, -85, -83, -81, -79, -77, -76, -74, -72, -70, -68, --66, -65, -63, -61, -59, -57, -55, -54, -52, -50, -48, -46, -45, -43, --41, -39, -37, -35, -34, -32, -30, -28, -26, -25, -23, -21, -19, -17, --15, -14, -12, -10, -8, -6, -4, -3, -1, 0, 2, 4, 5, 7, 9, 11, 13, 15, -16, 18, 20, 22, 24, 26, 27, 29, 31, 33, 35, 36, 38, 40, 42, 44, 46, -47, 49, 51, 53, 55, 56, 58, 60, 62, 64, 66, 67, 69, 71, 73, 75, 77, -78, 80, 82, 84, 86, 87, 89, 91, 93, 95, 97, 98, 100, 102, 104, 106, -107, 109, 111, 113, 115, 117, 118, 120, 122, 124, 126, 128, 129, 131, -133, 135, 137, 138, 140, 142, 144, 146, 148, 149, 151, 153, 155, 157, -158, 160, 162, 164, 166, 168, 169, 171, 173, 175, 177, 179, 180, 182, -184, 186, 188, 189, 191, 193, 195, 197, 199, 200, 202, 204, 206, 208, -209, 211, 213, 215 }; +static INT16 CR[] = { + -249, -247, -245, -243, -241, -239, -238, -236, -234, -232, -230, -229, -227, -225, + -223, -221, -219, -218, -216, -214, -212, -210, -208, -207, -205, -203, -201, -199, + -198, -196, -194, -192, -190, -188, -187, -185, -183, -181, -179, -178, -176, -174, + -172, -170, -168, -167, -165, -163, -161, -159, -157, -156, -154, -152, -150, -148, + -147, -145, -143, -141, -139, -137, -136, -134, -132, -130, -128, -127, -125, -123, + -121, -119, -117, -116, -114, -112, -110, -108, -106, -105, -103, -101, -99, -97, + -96, -94, -92, -90, -88, -86, -85, -83, -81, -79, -77, -76, -74, -72, + -70, -68, -66, -65, -63, -61, -59, -57, -55, -54, -52, -50, -48, -46, + -45, -43, -41, -39, -37, -35, -34, -32, -30, -28, -26, -25, -23, -21, + -19, -17, -15, -14, -12, -10, -8, -6, -4, -3, -1, 0, 2, 4, + 5, 7, 9, 11, 13, 15, 16, 18, 20, 22, 24, 26, 27, 29, + 31, 33, 35, 36, 38, 40, 42, 44, 46, 47, 49, 51, 53, 55, + 56, 58, 60, 62, 64, 66, 67, 69, 71, 73, 75, 77, 78, 80, + 82, 84, 86, 87, 89, 91, 93, 95, 97, 98, 100, 102, 104, 106, + 107, 109, 111, 113, 115, 117, 118, 120, 122, 124, 126, 128, 129, 131, + 133, 135, 137, 138, 140, 142, 144, 146, 148, 149, 151, 153, 155, 157, + 158, 160, 162, 164, 166, 168, 169, 171, 173, 175, 177, 179, 180, 182, + 184, 186, 188, 189, 191, 193, 195, 197, 199, 200, 202, 204, 206, 208, + 209, 211, 213, 215}; -static INT16 GR[] = { 127, 126, 125, 124, 123, 122, 121, 121, 120, 119, -118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 108, 107, 106, -105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 95, 94, 93, 92, 91, -90, 89, 88, 87, 86, 85, 84, 83, 83, 82, 81, 80, 79, 78, 77, 76, 75, -74, 73, 72, 71, 70, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, -58, 57, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 45, 44, -43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 32, 31, 30, 29, 28, -27, 26, 25, 24, 23, 22, 21, 20, 19, 19, 18, 17, 16, 15, 14, 13, 12, -11, 10, 9, 8, 7, 6, 6, 5, 4, 3, 2, 1, 0, 0, -1, -2, -3, -4, -5, -5, --6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -18, -19, --20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -31, -32, --33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, -44, -44, -45, --46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -56, -57, -58, --59, -60, -61, -62, -63, -64, -65, -66, -67, -68, -69, -69, -70, -71, --72, -73, -74, -75, -76, -77, -78, -79, -80, -81, -82, -82, -83, -84, --85, -86, -87, -88, -89, -90, -91, -92, -93, -94, -94, -95, -96, -97, --98, -99, -100, -101, -102, -103, -104, -105, -106, -107, -107, -108 }; +static INT16 GR[] = { + 127, 126, 125, 124, 123, 122, 121, 121, 120, 119, 118, 117, 116, 115, 114, + 113, 112, 111, 110, 109, 108, 108, 107, 106, 105, 104, 103, 102, 101, 100, + 99, 98, 97, 96, 95, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, + 85, 84, 83, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, + 71, 70, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, + 57, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 45, + 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 32, 31, + 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 19, 18, 17, + 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 6, 5, 4, 3, + 2, 1, 0, 0, -1, -2, -3, -4, -5, -5, -6, -7, -8, -9, -10, + -11, -12, -13, -14, -15, -16, -17, -18, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -31, -32, -33, -34, -35, -36, -37, -38, + -39, -40, -41, -42, -43, -44, -44, -45, -46, -47, -48, -49, -50, -51, -52, + -53, -54, -55, -56, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, + -67, -68, -69, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -79, -80, + -81, -82, -82, -83, -84, -85, -86, -87, -88, -89, -90, -91, -92, -93, -94, + -94, -95, -96, -97, -98, -99, -100, -101, -102, -103, -104, -105, -106, -107, -107, + -108}; #define R 0 #define G 1 #define B 2 #define A 3 -#define YCC2RGB(rgb, y, cb, cr) {\ - int l = L[y];\ - int r = l + CR[cr];\ - int g = l + GR[cr] + GB[cb];\ - int b = l + CB[cb];\ - rgb[0] = (r <= 0) ? 0 : (r >= 255) ? 255 : r;\ - rgb[1] = (g <= 0) ? 0 : (g >= 255) ? 255 : g;\ - rgb[2] = (b <= 0) ? 0 : (b >= 255) ? 255 : b;\ -} +#define YCC2RGB(rgb, y, cb, cr) \ + { \ + int l = L[y]; \ + int r = l + CR[cr]; \ + int g = l + GR[cr] + GB[cb]; \ + int b = l + CB[cb]; \ + rgb[0] = (r <= 0) ? 0 : (r >= 255) ? 255 : r; \ + rgb[1] = (g <= 0) ? 0 : (g >= 255) ? 255 : g; \ + rgb[2] = (b <= 0) ? 0 : (b >= 255) ? 255 : b; \ + } void -ImagingUnpackYCC(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackYCC(UINT8 *out, const UINT8 *in, int pixels) { int i; /* PhotoYCC triplets */ for (i = 0; i < pixels; i++) { YCC2RGB(out, in[0], in[1], in[2]); out[A] = 255; - out += 4; in += 3; + out += 4; + in += 3; } } void -ImagingUnpackYCCA(UINT8* out, const UINT8* in, int pixels) -{ +ImagingUnpackYCCA(UINT8 *out, const UINT8 *in, int pixels) { int i; /* PhotoYCC triplets plus premultiplied alpha */ for (i = 0; i < pixels; i++) { /* Divide by alpha */ UINT8 rgb[3]; - rgb[0] = (in[3] == 0) ? 0 : (((int) in[0] * 255) / in[3]); - rgb[1] = (in[3] == 0) ? 0 : (((int) in[1] * 255) / in[3]); - rgb[2] = (in[3] == 0) ? 0 : (((int) in[2] * 255) / in[3]); + rgb[0] = (in[3] == 0) ? 0 : (((int)in[0] * 255) / in[3]); + rgb[1] = (in[3] == 0) ? 0 : (((int)in[1] * 255) / in[3]); + rgb[2] = (in[3] == 0) ? 0 : (((int)in[2] * 255) / in[3]); /* Convert non-multiplied data to RGB */ YCC2RGB(out, rgb[0], rgb[1], rgb[2]); out[A] = in[3]; - out += 4; in += 4; + out += 4; + in += 4; } } diff --git a/src/libImaging/UnsharpMask.c b/src/libImaging/UnsharpMask.c index 59e595e82..643ced49f 100644 --- a/src/libImaging/UnsharpMask.c +++ b/src/libImaging/UnsharpMask.c @@ -8,26 +8,22 @@ #include "Imaging.h" - typedef UINT8 pixel[4]; - -static inline UINT8 clip8(int in) -{ +static inline UINT8 +clip8(int in) { if (in >= 255) { - return 255; + return 255; } if (in <= 0) { return 0; } - return (UINT8) in; + return (UINT8)in; } - Imaging -ImagingUnsharpMask(Imaging imOut, Imaging imIn, float radius, int percent, - int threshold) -{ +ImagingUnsharpMask( + Imaging imOut, Imaging imIn, float radius, int percent, int threshold) { ImagingSectionCookie cookie; Imaging result; @@ -53,8 +49,7 @@ ImagingUnsharpMask(Imaging imOut, Imaging imIn, float radius, int percent, ImagingSectionEnter(&cookie); for (y = 0; y < imIn->ysize; y++) { - if (imIn->image8) - { + if (imIn->image8) { lineIn8 = imIn->image8[y]; lineOut8 = imOut->image8[y]; for (x = 0; x < imIn->xsize; x++) { @@ -74,20 +69,24 @@ ImagingUnsharpMask(Imaging imOut, Imaging imIn, float radius, int percent, for (x = 0; x < imIn->xsize; x++) { /* compare in/out pixels, apply sharpening */ diff = lineIn[x][0] - lineOut[x][0]; - lineOut[x][0] = abs(diff) > threshold ? - clip8(lineIn[x][0] + diff * percent / 100) : lineIn[x][0]; + lineOut[x][0] = abs(diff) > threshold + ? clip8(lineIn[x][0] + diff * percent / 100) + : lineIn[x][0]; diff = lineIn[x][1] - lineOut[x][1]; - lineOut[x][1] = abs(diff) > threshold ? - clip8(lineIn[x][1] + diff * percent / 100) : lineIn[x][1]; + lineOut[x][1] = abs(diff) > threshold + ? clip8(lineIn[x][1] + diff * percent / 100) + : lineIn[x][1]; diff = lineIn[x][2] - lineOut[x][2]; - lineOut[x][2] = abs(diff) > threshold ? - clip8(lineIn[x][2] + diff * percent / 100) : lineIn[x][2]; + lineOut[x][2] = abs(diff) > threshold + ? clip8(lineIn[x][2] + diff * percent / 100) + : lineIn[x][2]; diff = lineIn[x][3] - lineOut[x][3]; - lineOut[x][3] = abs(diff) > threshold ? - clip8(lineIn[x][3] + diff * percent / 100) : lineIn[x][3]; + lineOut[x][3] = abs(diff) > threshold + ? clip8(lineIn[x][3] + diff * percent / 100) + : lineIn[x][3]; } } } diff --git a/src/libImaging/XbmDecode.c b/src/libImaging/XbmDecode.c index 607f1058a..d6690de3d 100644 --- a/src/libImaging/XbmDecode.c +++ b/src/libImaging/XbmDecode.c @@ -13,19 +13,19 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" -#define HEX(v) ((v >= '0' && v <= '9') ? v - '0' :\ - (v >= 'a' && v <= 'f') ? v - 'a' + 10 :\ - (v >= 'A' && v <= 'F') ? v - 'A' + 10 : 0) +#define HEX(v) \ + ((v >= '0' && v <= '9') ? v - '0' \ + : (v >= 'a' && v <= 'f') ? v - 'a' + 10 \ + : (v >= 'A' && v <= 'F') ? v - 'A' + 10 \ + : 0) int -ImagingXbmDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ +ImagingXbmDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { enum { BYTE = 1, SKIP }; - UINT8* ptr; + UINT8 *ptr; if (!state->state) { state->state = SKIP; @@ -34,9 +34,7 @@ ImagingXbmDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt ptr = buf; for (;;) { - if (state->state == SKIP) { - /* Skip forward until next 'x' */ while (bytes > 0) { @@ -52,20 +50,17 @@ ImagingXbmDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt } state->state = BYTE; - } if (bytes < 3) { return ptr - buf; } - state->buffer[state->x] = (HEX(ptr[1])<<4) + HEX(ptr[2]); + state->buffer[state->x] = (HEX(ptr[1]) << 4) + HEX(ptr[2]); if (++state->x >= state->bytes) { - /* Got a full line, unpack it */ - state->shuffle((UINT8*) im->image[state->y], state->buffer, - state->xsize); + state->shuffle((UINT8 *)im->image[state->y], state->buffer, state->xsize); state->x = 0; @@ -79,7 +74,5 @@ ImagingXbmDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt bytes -= 3; state->state = SKIP; - } - } diff --git a/src/libImaging/XbmEncode.c b/src/libImaging/XbmEncode.c index d1bc086db..eec4c0d84 100644 --- a/src/libImaging/XbmEncode.c +++ b/src/libImaging/XbmEncode.c @@ -13,25 +13,20 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" - int -ImagingXbmEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) -{ +ImagingXbmEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { const char *hex = "0123456789abcdef"; - UINT8* ptr = buf; + UINT8 *ptr = buf; int i, n; if (!state->state) { - /* 8 pixels are stored in no more than 6 bytes */ - state->bytes = 6*(state->xsize+7)/8; + state->bytes = 6 * (state->xsize + 7) / 8; state->state = 1; - } if (bytes < state->bytes) { @@ -42,60 +37,54 @@ ImagingXbmEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) ptr = buf; while (bytes >= state->bytes) { + state->shuffle( + state->buffer, + (UINT8 *)im->image[state->y + state->yoff] + state->xoff * im->pixelsize, + state->xsize); - state->shuffle(state->buffer, - (UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, state->xsize); - - if (state->y < state->ysize-1) { - + if (state->y < state->ysize - 1) { /* any line but the last */ for (n = 0; n < state->xsize; n += 8) { - - i = state->buffer[n/8]; + i = state->buffer[n / 8]; *ptr++ = '0'; *ptr++ = 'x'; - *ptr++ = hex[(i>>4)&15]; - *ptr++ = hex[i&15]; + *ptr++ = hex[(i >> 4) & 15]; + *ptr++ = hex[i & 15]; *ptr++ = ','; bytes -= 5; - if (++state->count >= 79/5) { + if (++state->count >= 79 / 5) { *ptr++ = '\n'; bytes--; state->count = 0; } - } state->y++; } else { - /* last line */ for (n = 0; n < state->xsize; n += 8) { - - i = state->buffer[n/8]; + i = state->buffer[n / 8]; *ptr++ = '0'; *ptr++ = 'x'; - *ptr++ = hex[(i>>4)&15]; - *ptr++ = hex[i&15]; + *ptr++ = hex[(i >> 4) & 15]; + *ptr++ = hex[i & 15]; - if (n < state->xsize-8) { + if (n < state->xsize - 8) { *ptr++ = ','; - if (++state->count >= 79/5) { - *ptr++ = '\n'; - bytes--; - state->count = 0; + if (++state->count >= 79 / 5) { + *ptr++ = '\n'; + bytes--; + state->count = 0; } } else { *ptr++ = '\n'; } bytes -= 5; - } state->errcode = IMAGING_CODEC_END; diff --git a/src/libImaging/ZipCodecs.h b/src/libImaging/ZipCodecs.h index b05c93bb4..50218b6c6 100644 --- a/src/libImaging/ZipCodecs.h +++ b/src/libImaging/ZipCodecs.h @@ -7,19 +7,15 @@ * Copyright (c) Fredrik Lundh 1996. */ - #include "zlib.h" - /* modes */ #define ZIP_PNG 0 /* continuous, filtered image data */ #define ZIP_PNG_PALETTE 1 /* non-continuous data, disable filtering */ #define ZIP_TIFF_PREDICTOR 2 /* TIFF, with predictor */ #define ZIP_TIFF 3 /* TIFF, without predictor */ - typedef struct { - /* CONFIGURATION */ /* Codec mode */ @@ -34,29 +30,29 @@ typedef struct { int compress_type; /* Predefined dictionary (experimental) */ - char* dictionary; + char *dictionary; int dictionary_size; /* PRIVATE CONTEXT (set by decoder/encoder) */ - z_stream z_stream; /* (de)compression stream */ + z_stream z_stream; /* (de)compression stream */ - UINT8* previous; /* previous line (allocated) */ + UINT8 *previous; /* previous line (allocated) */ - int last_output; /* # bytes last output by inflate */ + int last_output; /* # bytes last output by inflate */ /* Compressor specific stuff */ - UINT8* prior; /* filter storage (allocated) */ - UINT8* up; - UINT8* average; - UINT8* paeth; + UINT8 *prior; /* filter storage (allocated) */ + UINT8 *up; + UINT8 *average; + UINT8 *paeth; - UINT8* output; /* output data */ + UINT8 *output; /* output data */ - int prefix; /* size of filter prefix (0 for TIFF data) */ + int prefix; /* size of filter prefix (0 for TIFF data) */ - int interlaced; /* is the image interlaced? (PNG) */ + int interlaced; /* is the image interlaced? (PNG) */ - int pass; /* current pass of the interlaced image (PNG) */ + int pass; /* current pass of the interlaced image (PNG) */ } ZIPSTATE; diff --git a/src/libImaging/ZipDecode.c b/src/libImaging/ZipDecode.c index a09ee82f7..874967834 100644 --- a/src/libImaging/ZipDecode.c +++ b/src/libImaging/ZipDecode.c @@ -15,23 +15,22 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" -#ifdef HAVE_LIBZ +#ifdef HAVE_LIBZ #include "ZipCodecs.h" -static const int OFFSET[] = { 7, 3, 3, 1, 1, 0, 0 }; -static const int STARTING_COL[] = { 0, 4, 0, 2, 0, 1, 0 }; -static const int STARTING_ROW[] = { 0, 0, 4, 0, 2, 0, 1 }; -static const int COL_INCREMENT[] = { 8, 8, 4, 4, 2, 2, 1 }; -static const int ROW_INCREMENT[] = { 8, 8, 8, 4, 4, 2, 2 }; +static const int OFFSET[] = {7, 3, 3, 1, 1, 0, 0}; +static const int STARTING_COL[] = {0, 4, 0, 2, 0, 1, 0}; +static const int STARTING_ROW[] = {0, 0, 4, 0, 2, 0, 1}; +static const int COL_INCREMENT[] = {8, 8, 4, 4, 2, 2, 1}; +static const int ROW_INCREMENT[] = {8, 8, 8, 4, 4, 2, 2}; /* Get the length in bytes of a scanline in the pass specified, * for interlaced images */ -static int get_row_len(ImagingCodecState state, int pass) -{ +static int +get_row_len(ImagingCodecState state, int pass) { int row_len = (state->xsize + OFFSET[pass]) / COL_INCREMENT[pass]; return ((row_len * state->bits) + 7) / 8; } @@ -41,17 +40,15 @@ static int get_row_len(ImagingCodecState state, int pass) /* -------------------------------------------------------------------- */ int -ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) -{ - ZIPSTATE* context = (ZIPSTATE*) state->context; +ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { + ZIPSTATE *context = (ZIPSTATE *)state->context; int err; int n; - UINT8* ptr; + UINT8 *ptr; int i, bpp; int row_len; if (!state->state) { - /* Initialization */ if (context->mode == ZIP_PNG || context->mode == ZIP_PNG_PALETTE) { context->prefix = 1; /* PNG */ @@ -66,8 +63,8 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt prefix, and allocate a buffer to hold the previous line */ free(state->buffer); /* malloc check ok, overflow checked above */ - state->buffer = (UINT8*) malloc(state->bytes+1); - context->previous = (UINT8*) malloc(state->bytes+1); + state->buffer = (UINT8 *)malloc(state->bytes + 1); + context->previous = (UINT8 *)malloc(state->bytes + 1); if (!state->buffer || !context->previous) { state->errcode = IMAGING_CODEC_MEMORY; return -1; @@ -76,12 +73,12 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt context->last_output = 0; /* Initialize to black */ - memset(context->previous, 0, state->bytes+1); + memset(context->previous, 0, state->bytes + 1); /* Setup decompression context */ - context->z_stream.zalloc = (alloc_func) NULL; - context->z_stream.zfree = (free_func) NULL; - context->z_stream.opaque = (voidpf) NULL; + context->z_stream.zalloc = (alloc_func)NULL; + context->z_stream.zfree = (free_func)NULL; + context->z_stream.opaque = (voidpf)NULL; err = inflateInit(&context->z_stream); if (err < 0) { @@ -98,7 +95,6 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt /* Ready to decode */ state->state = 1; - } if (context->interlaced) { @@ -113,10 +109,8 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt /* Decompress what we've got this far */ while (context->z_stream.avail_in > 0) { - context->z_stream.next_out = state->buffer + context->last_output; - context->z_stream.avail_out = - row_len + context->prefix - context->last_output; + context->z_stream.avail_out = row_len + context->prefix - context->last_output; err = inflate(&context->z_stream, Z_NO_FLUSH); @@ -144,74 +138,74 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt /* Apply predictor */ switch (context->mode) { - case ZIP_PNG: - switch (state->buffer[0]) { - case 0: + case ZIP_PNG: + switch (state->buffer[0]) { + case 0: + break; + case 1: + /* prior */ + bpp = (state->bits + 7) / 8; + for (i = bpp + 1; i <= row_len; i++) { + state->buffer[i] += state->buffer[i - bpp]; + } + break; + case 2: + /* up */ + for (i = 1; i <= row_len; i++) { + state->buffer[i] += context->previous[i]; + } + break; + case 3: + /* average */ + bpp = (state->bits + 7) / 8; + for (i = 1; i <= bpp; i++) { + state->buffer[i] += context->previous[i] / 2; + } + for (; i <= row_len; i++) { + state->buffer[i] += + (state->buffer[i - bpp] + context->previous[i]) / 2; + } + break; + case 4: + /* paeth filtering */ + bpp = (state->bits + 7) / 8; + for (i = 1; i <= bpp; i++) { + state->buffer[i] += context->previous[i]; + } + for (; i <= row_len; i++) { + int a, b, c; + int pa, pb, pc; + + /* fetch pixels */ + a = state->buffer[i - bpp]; + b = context->previous[i]; + c = context->previous[i - bpp]; + + /* distances to surrounding pixels */ + pa = abs(b - c); + pb = abs(a - c); + pc = abs(a + b - 2 * c); + + /* pick predictor with the shortest distance */ + state->buffer[i] += (pa <= pb && pa <= pc) ? a + : (pb <= pc) ? b + : c; + } + break; + default: + state->errcode = IMAGING_CODEC_UNKNOWN; + free(context->previous); + context->previous = NULL; + inflateEnd(&context->z_stream); + return -1; + } break; - case 1: - /* prior */ + case ZIP_TIFF_PREDICTOR: bpp = (state->bits + 7) / 8; - for (i = bpp+1; i <= row_len; i++) { - state->buffer[i] += state->buffer[i-bpp]; + for (i = bpp + 1; i <= row_len; i++) { + state->buffer[i] += state->buffer[i - bpp]; } break; - case 2: - /* up */ - for (i = 1; i <= row_len; i++) { - state->buffer[i] += context->previous[i]; - } - break; - case 3: - /* average */ - bpp = (state->bits + 7) / 8; - for (i = 1; i <= bpp; i++) { - state->buffer[i] += context->previous[i]/2; - } - for (; i <= row_len; i++) { - state->buffer[i] += - (state->buffer[i-bpp] + context->previous[i])/2; - } - break; - case 4: - /* paeth filtering */ - bpp = (state->bits + 7) / 8; - for (i = 1; i <= bpp; i++) { - state->buffer[i] += context->previous[i]; - } - for (; i <= row_len; i++) { - int a, b, c; - int pa, pb, pc; - - /* fetch pixels */ - a = state->buffer[i-bpp]; - b = context->previous[i]; - c = context->previous[i-bpp]; - - /* distances to surrounding pixels */ - pa = abs(b - c); - pb = abs(a - c); - pc = abs(a + b - 2*c); - - /* pick predictor with the shortest distance */ - state->buffer[i] += - (pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c; - - } - break; - default: - state->errcode = IMAGING_CODEC_UNKNOWN; - free(context->previous); - context->previous = NULL; - inflateEnd(&context->z_stream); - return -1; - } - break; - case ZIP_TIFF_PREDICTOR: - bpp = (state->bits + 7) / 8; - for (i = bpp+1; i <= row_len; i++) { - state->buffer[i] += state->buffer[i-bpp]; - } - break; } /* Stuff data into the image */ @@ -220,20 +214,22 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt if (state->bits >= 8) { /* Stuff pixels in their correct location, one by one */ for (i = 0; i < row_len; i += ((state->bits + 7) / 8)) { - state->shuffle((UINT8*) im->image[state->y] + - col * im->pixelsize, - state->buffer + context->prefix + i, 1); + state->shuffle( + (UINT8 *)im->image[state->y] + col * im->pixelsize, + state->buffer + context->prefix + i, + 1); col += COL_INCREMENT[context->pass]; } } else { /* Handle case with more than a pixel in each byte */ - int row_bits = ((state->xsize + OFFSET[context->pass]) - / COL_INCREMENT[context->pass]) * state->bits; + int row_bits = ((state->xsize + OFFSET[context->pass]) / + COL_INCREMENT[context->pass]) * + state->bits; for (i = 0; i < row_bits; i += state->bits) { UINT8 byte = *(state->buffer + context->prefix + (i / 8)); byte <<= (i % 8); - state->shuffle((UINT8*) im->image[state->y] + - col * im->pixelsize, &byte, 1); + state->shuffle( + (UINT8 *)im->image[state->y] + col * im->pixelsize, &byte, 1); col += COL_INCREMENT[context->pass]; } } @@ -250,13 +246,14 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt row_len = get_row_len(state, context->pass); /* Since we're moving to the "first" line, the previous line * should be black to make filters work correctly */ - memset(state->buffer, 0, state->bytes+1); + memset(state->buffer, 0, state->bytes + 1); } } else { - state->shuffle((UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, - state->buffer + context->prefix, - state->xsize); + state->shuffle( + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->buffer + context->prefix, + state->xsize); state->y++; } @@ -264,7 +261,6 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt context->last_output = 0; if (state->y >= state->ysize || err == Z_STREAM_END) { - /* The image and the data should end simultaneously */ /* if (state->y < state->ysize || err != Z_STREAM_END) state->errcode = IMAGING_CODEC_BROKEN; */ @@ -273,26 +269,23 @@ ImagingZipDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t byt context->previous = NULL; inflateEnd(&context->z_stream); return -1; /* end of file (errcode=0) */ - } /* Swap buffer pointers */ ptr = state->buffer; state->buffer = context->previous; context->previous = ptr; - } return bytes; /* consumed all of it */ - } - -int ImagingZipDecodeCleanup(ImagingCodecState state){ +int +ImagingZipDecodeCleanup(ImagingCodecState state) { /* called to free the decompression engine when the decode terminates due to a corrupt or truncated image */ - ZIPSTATE* context = (ZIPSTATE*) state->context; + ZIPSTATE *context = (ZIPSTATE *)state->context; /* Clean up */ if (context->previous) { diff --git a/src/libImaging/ZipEncode.c b/src/libImaging/ZipEncode.c index 4e862af57..edbce3682 100644 --- a/src/libImaging/ZipEncode.c +++ b/src/libImaging/ZipEncode.c @@ -14,25 +14,22 @@ * See the README file for information on usage and redistribution. */ - #include "Imaging.h" -#ifdef HAVE_LIBZ +#ifdef HAVE_LIBZ #include "ZipCodecs.h" int -ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) -{ - ZIPSTATE* context = (ZIPSTATE*) state->context; +ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) { + ZIPSTATE *context = (ZIPSTATE *)state->context; int err; int compress_level, compress_type; - UINT8* ptr; + UINT8 *ptr; int i, bpp, s, sum; ImagingSectionCookie cookie; if (!state->state) { - /* Initialization */ /* Valid modes are ZIP_PNG, ZIP_PNG_PALETTE, and ZIP_TIFF */ @@ -47,14 +44,14 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) and allocate filter buffers */ free(state->buffer); /* malloc check ok, overflow checked above */ - state->buffer = (UINT8*) malloc(state->bytes+1); - context->previous = (UINT8*) malloc(state->bytes+1); - context->prior = (UINT8*) malloc(state->bytes+1); - context->up = (UINT8*) malloc(state->bytes+1); - context->average = (UINT8*) malloc(state->bytes+1); - context->paeth = (UINT8*) malloc(state->bytes+1); - if (!state->buffer || !context->previous || !context->prior || - !context->up || !context->average || !context->paeth) { + state->buffer = (UINT8 *)malloc(state->bytes + 1); + context->previous = (UINT8 *)malloc(state->bytes + 1); + context->prior = (UINT8 *)malloc(state->bytes + 1); + context->up = (UINT8 *)malloc(state->bytes + 1); + context->average = (UINT8 *)malloc(state->bytes + 1); + context->paeth = (UINT8 *)malloc(state->bytes + 1); + if (!state->buffer || !context->previous || !context->prior || !context->up || + !context->average || !context->paeth) { free(context->paeth); free(context->average); free(context->up); @@ -72,7 +69,7 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) context->paeth[0] = 4; /* Initialise previous buffer to black */ - memset(context->previous, 0, state->bytes+1); + memset(context->previous, 0, state->bytes + 1); /* Setup compression context */ context->z_stream.zalloc = (alloc_func)0; @@ -81,33 +78,37 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) context->z_stream.next_in = 0; context->z_stream.avail_in = 0; - compress_level = (context->optimize) ? Z_BEST_COMPRESSION - : context->compress_level; + compress_level = + (context->optimize) ? Z_BEST_COMPRESSION : context->compress_level; if (context->compress_type == -1) { - compress_type = (context->mode == ZIP_PNG) ? Z_FILTERED - : Z_DEFAULT_STRATEGY; + compress_type = + (context->mode == ZIP_PNG) ? Z_FILTERED : Z_DEFAULT_STRATEGY; } else { compress_type = context->compress_type; } - err = deflateInit2(&context->z_stream, - /* compression level */ - compress_level, - /* compression method */ - Z_DEFLATED, - /* compression memory resources */ - 15, 9, - /* compression strategy (image data are filtered)*/ - compress_type); + err = deflateInit2( + &context->z_stream, + /* compression level */ + compress_level, + /* compression method */ + Z_DEFLATED, + /* compression memory resources */ + 15, + 9, + /* compression strategy (image data are filtered)*/ + compress_type); if (err < 0) { state->errcode = IMAGING_CODEC_CONFIG; return -1; } if (context->dictionary && context->dictionary_size > 0) { - err = deflateSetDictionary(&context->z_stream, (unsigned char *)context->dictionary, - context->dictionary_size); + err = deflateSetDictionary( + &context->z_stream, + (unsigned char *)context->dictionary, + context->dictionary_size); if (err < 0) { state->errcode = IMAGING_CODEC_CONFIG; return -1; @@ -116,7 +117,6 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) /* Ready to decode */ state->state = 1; - } /* Setup the destination buffer */ @@ -147,203 +147,194 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) ImagingSectionEnter(&cookie); for (;;) { - switch (state->state) { + case 1: - case 1: - - /* Compress image data */ - while (context->z_stream.avail_out > 0) { - - if (state->y >= state->ysize) { - /* End of image; now flush compressor buffers */ - state->state = 2; - break; - - } - - /* Stuff image data into the compressor */ - state->shuffle(state->buffer+1, - (UINT8*) im->image[state->y + state->yoff] + - state->xoff * im->pixelsize, - state->xsize); - - state->y++; - - context->output = state->buffer; - - if (context->mode == ZIP_PNG) { - - /* Filter the image data. For each line, select - the filter that gives the least total distance - from zero for the filtered data (taken from - LIBPNG) */ - - bpp = (state->bits + 7) / 8; - - /* 0. No filter */ - for (i = 1, sum = 0; i <= state->bytes; i++) { - UINT8 v = state->buffer[i]; - sum += (v < 128) ? v : 256 - v; + /* Compress image data */ + while (context->z_stream.avail_out > 0) { + if (state->y >= state->ysize) { + /* End of image; now flush compressor buffers */ + state->state = 2; + break; } - /* 2. Up. We'll test this first to save time when - an image line is identical to the one above. */ - if (sum > 0) { - for (i = 1, s = 0; i <= state->bytes; i++) { - UINT8 v = state->buffer[i] - context->previous[i]; - context->up[i] = v; - s += (v < 128) ? v : 256 - v; - } - if (s < sum) { - context->output = context->up; - sum = s; /* 0 if line was duplicated */ - } - } + /* Stuff image data into the compressor */ + state->shuffle( + state->buffer + 1, + (UINT8 *)im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, + state->xsize); - /* 1. Prior */ - if (sum > 0) { - for (i = 1, s = 0; i <= bpp; i++) { + state->y++; + + context->output = state->buffer; + + if (context->mode == ZIP_PNG) { + /* Filter the image data. For each line, select + the filter that gives the least total distance + from zero for the filtered data (taken from + LIBPNG) */ + + bpp = (state->bits + 7) / 8; + + /* 0. No filter */ + for (i = 1, sum = 0; i <= state->bytes; i++) { UINT8 v = state->buffer[i]; - context->prior[i] = v; - s += (v < 128) ? v : 256 - v; + sum += (v < 128) ? v : 256 - v; } - for (; i <= state->bytes; i++) { - UINT8 v = state->buffer[i] - state->buffer[i-bpp]; - context->prior[i] = v; - s += (v < 128) ? v : 256 - v; + + /* 2. Up. We'll test this first to save time when + an image line is identical to the one above. */ + if (sum > 0) { + for (i = 1, s = 0; i <= state->bytes; i++) { + UINT8 v = state->buffer[i] - context->previous[i]; + context->up[i] = v; + s += (v < 128) ? v : 256 - v; + } + if (s < sum) { + context->output = context->up; + sum = s; /* 0 if line was duplicated */ + } } - if (s < sum) { - context->output = context->prior; - sum = s; /* 0 if line is solid */ + + /* 1. Prior */ + if (sum > 0) { + for (i = 1, s = 0; i <= bpp; i++) { + UINT8 v = state->buffer[i]; + context->prior[i] = v; + s += (v < 128) ? v : 256 - v; + } + for (; i <= state->bytes; i++) { + UINT8 v = state->buffer[i] - state->buffer[i - bpp]; + context->prior[i] = v; + s += (v < 128) ? v : 256 - v; + } + if (s < sum) { + context->output = context->prior; + sum = s; /* 0 if line is solid */ + } + } + + /* 3. Average (not very common in real-life images, + so its only used with the optimize option) */ + if (context->optimize && sum > 0) { + for (i = 1, s = 0; i <= bpp; i++) { + UINT8 v = state->buffer[i] - context->previous[i] / 2; + context->average[i] = v; + s += (v < 128) ? v : 256 - v; + } + for (; i <= state->bytes; i++) { + UINT8 v = + state->buffer[i] - + (state->buffer[i - bpp] + context->previous[i]) / 2; + context->average[i] = v; + s += (v < 128) ? v : 256 - v; + } + if (s < sum) { + context->output = context->average; + sum = s; + } + } + + /* 4. Paeth */ + if (sum > 0) { + for (i = 1, s = 0; i <= bpp; i++) { + UINT8 v = state->buffer[i] - context->previous[i]; + context->paeth[i] = v; + s += (v < 128) ? v : 256 - v; + } + for (; i <= state->bytes; i++) { + UINT8 v; + int a, b, c; + int pa, pb, pc; + + /* fetch pixels */ + a = state->buffer[i - bpp]; + b = context->previous[i]; + c = context->previous[i - bpp]; + + /* distances to surrounding pixels */ + pa = abs(b - c); + pb = abs(a - c); + pc = abs(a + b - 2 * c); + + /* pick predictor with the shortest distance */ + v = state->buffer[i] - ((pa <= pb && pa <= pc) ? a + : (pb <= pc) ? b + : c); + context->paeth[i] = v; + s += (v < 128) ? v : 256 - v; + } + if (s < sum) { + context->output = context->paeth; + sum = s; + } } } - /* 3. Average (not very common in real-life images, - so its only used with the optimize option) */ - if (context->optimize && sum > 0) { - for (i = 1, s = 0; i <= bpp; i++) { - UINT8 v = state->buffer[i] - context->previous[i]/2; - context->average[i] = v; - s += (v < 128) ? v : 256 - v; - } - for (; i <= state->bytes; i++) { - UINT8 v = state->buffer[i] - - (state->buffer[i-bpp] + context->previous[i])/2; - context->average[i] = v; - s += (v < 128) ? v : 256 - v; - } - if (s < sum) { - context->output = context->average; - sum = s; + /* Compress this line */ + context->z_stream.next_in = context->output; + context->z_stream.avail_in = state->bytes + 1; + + err = deflate(&context->z_stream, Z_NO_FLUSH); + + if (err < 0) { + /* Something went wrong inside the compression library */ + if (err == Z_DATA_ERROR) { + state->errcode = IMAGING_CODEC_BROKEN; + } else if (err == Z_MEM_ERROR) { + state->errcode = IMAGING_CODEC_MEMORY; + } else { + state->errcode = IMAGING_CODEC_CONFIG; } + free(context->paeth); + free(context->average); + free(context->up); + free(context->prior); + free(context->previous); + deflateEnd(&context->z_stream); + ImagingSectionLeave(&cookie); + return -1; } - /* 4. Paeth */ - if (sum > 0) { - for (i = 1, s = 0; i <= bpp; i++) { - UINT8 v = state->buffer[i] - context->previous[i]; - context->paeth[i] = v; - s += (v < 128) ? v : 256 - v; - } - for (; i <= state->bytes; i++) { - UINT8 v; - int a, b, c; - int pa, pb, pc; - - /* fetch pixels */ - a = state->buffer[i-bpp]; - b = context->previous[i]; - c = context->previous[i-bpp]; - - /* distances to surrounding pixels */ - pa = abs(b - c); - pb = abs(a - c); - pc = abs(a + b - 2*c); - - /* pick predictor with the shortest distance */ - v = state->buffer[i] - - ((pa <= pb && pa <= pc) ? a : - (pb <= pc) ? b : c); - context->paeth[i] = v; - s += (v < 128) ? v : 256 - v; - } - if (s < sum) { - context->output = context->paeth; - sum = s; - } - } - } - - /* Compress this line */ - context->z_stream.next_in = context->output; - context->z_stream.avail_in = state->bytes+1; - - err = deflate(&context->z_stream, Z_NO_FLUSH); - - if (err < 0) { - /* Something went wrong inside the compression library */ - if (err == Z_DATA_ERROR) { - state->errcode = IMAGING_CODEC_BROKEN; - } else if (err == Z_MEM_ERROR) { - state->errcode = IMAGING_CODEC_MEMORY; - } else { - state->errcode = IMAGING_CODEC_CONFIG; - } - free(context->paeth); - free(context->average); - free(context->up); - free(context->prior); - free(context->previous); - deflateEnd(&context->z_stream); - ImagingSectionLeave(&cookie); - return -1; - } - - /* Swap buffer pointers */ - ptr = state->buffer; - state->buffer = context->previous; - context->previous = ptr; - - } - - if (context->z_stream.avail_out == 0) { - break; /* Buffer full */ - } - - case 2: - - /* End of image data; flush compressor buffers */ - - while (context->z_stream.avail_out > 0) { - - err = deflate(&context->z_stream, Z_FINISH); - - if (err == Z_STREAM_END) { - - free(context->paeth); - free(context->average); - free(context->up); - free(context->prior); - free(context->previous); - - deflateEnd(&context->z_stream); - - state->errcode = IMAGING_CODEC_END; - - break; + /* Swap buffer pointers */ + ptr = state->buffer; + state->buffer = context->previous; + context->previous = ptr; } if (context->z_stream.avail_out == 0) { break; /* Buffer full */ } - } + case 2: + /* End of image data; flush compressor buffers */ + + while (context->z_stream.avail_out > 0) { + err = deflate(&context->z_stream, Z_FINISH); + + if (err == Z_STREAM_END) { + free(context->paeth); + free(context->average); + free(context->up); + free(context->prior); + free(context->previous); + + deflateEnd(&context->z_stream); + + state->errcode = IMAGING_CODEC_END; + + break; + } + + if (context->z_stream.avail_out == 0) { + break; /* Buffer full */ + } + } } ImagingSectionLeave(&cookie); return bytes - context->z_stream.avail_out; - } /* Should never ever arrive here... */ @@ -358,21 +349,18 @@ ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) int ImagingZipEncodeCleanup(ImagingCodecState state) { - ZIPSTATE* context = (ZIPSTATE*) state->context; + ZIPSTATE *context = (ZIPSTATE *)state->context; if (context->dictionary) { - free (context->dictionary); + free(context->dictionary); context->dictionary = NULL; } return -1; } - - -const char* -ImagingZipVersion(void) -{ +const char * +ImagingZipVersion(void) { return zlibVersion(); } diff --git a/src/libImaging/codec_fd.c b/src/libImaging/codec_fd.c index 5cde31cdc..526168110 100644 --- a/src/libImaging/codec_fd.c +++ b/src/libImaging/codec_fd.c @@ -1,10 +1,8 @@ #include "Python.h" #include "Imaging.h" - Py_ssize_t -_imaging_read_pyFd(PyObject *fd, char* dest, Py_ssize_t bytes) -{ +_imaging_read_pyFd(PyObject *fd, char *dest, Py_ssize_t bytes) { /* dest should be a buffer bytes long, returns length of read -1 on error */ @@ -29,16 +27,13 @@ _imaging_read_pyFd(PyObject *fd, char* dest, Py_ssize_t bytes) Py_DECREF(result); return length; - err: +err: Py_DECREF(result); return -1; - } Py_ssize_t -_imaging_write_pyFd(PyObject *fd, char* src, Py_ssize_t bytes) -{ - +_imaging_write_pyFd(PyObject *fd, char *src, Py_ssize_t bytes) { PyObject *result; PyObject *byteObj; @@ -49,24 +44,20 @@ _imaging_write_pyFd(PyObject *fd, char* src, Py_ssize_t bytes) Py_DECREF(result); return bytes; - } int -_imaging_seek_pyFd(PyObject *fd, Py_ssize_t offset, int whence) -{ +_imaging_seek_pyFd(PyObject *fd, Py_ssize_t offset, int whence) { PyObject *result; result = PyObject_CallMethod(fd, "seek", "ni", offset, whence); Py_DECREF(result); return 0; - } Py_ssize_t -_imaging_tell_pyFd(PyObject *fd) -{ +_imaging_tell_pyFd(PyObject *fd) { PyObject *result; Py_ssize_t location; diff --git a/src/libImaging/raqm.h b/src/libImaging/raqm.h index eae1f43b7..5f865853a 100644 --- a/src/libImaging/raqm.h +++ b/src/libImaging/raqm.h @@ -63,8 +63,7 @@ typedef struct _raqm raqm_t; * * Since: 0.1 */ -typedef enum -{ +typedef enum { RAQM_DIRECTION_DEFAULT, RAQM_DIRECTION_RTL, RAQM_DIRECTION_LTR, @@ -106,73 +105,50 @@ typedef struct raqm_glyph_t_01 { uint32_t cluster; } raqm_glyph_t_01; +raqm_t * +raqm_create(void); raqm_t * -raqm_create (void); - -raqm_t * -raqm_reference (raqm_t *rq); +raqm_reference(raqm_t *rq); void -raqm_destroy (raqm_t *rq); +raqm_destroy(raqm_t *rq); bool -raqm_set_text (raqm_t *rq, - const uint32_t *text, - size_t len); +raqm_set_text(raqm_t *rq, const uint32_t *text, size_t len); bool -raqm_set_text_utf8 (raqm_t *rq, - const char *text, - size_t len); +raqm_set_text_utf8(raqm_t *rq, const char *text, size_t len); bool -raqm_set_par_direction (raqm_t *rq, - raqm_direction_t dir); +raqm_set_par_direction(raqm_t *rq, raqm_direction_t dir); bool -raqm_set_language (raqm_t *rq, - const char *lang, - size_t start, - size_t len); +raqm_set_language(raqm_t *rq, const char *lang, size_t start, size_t len); bool -raqm_add_font_feature (raqm_t *rq, - const char *feature, - int len); +raqm_add_font_feature(raqm_t *rq, const char *feature, int len); bool -raqm_set_freetype_face (raqm_t *rq, - FT_Face face); +raqm_set_freetype_face(raqm_t *rq, FT_Face face); bool -raqm_set_freetype_face_range (raqm_t *rq, - FT_Face face, - size_t start, - size_t len); +raqm_set_freetype_face_range(raqm_t *rq, FT_Face face, size_t start, size_t len); bool -raqm_set_freetype_load_flags (raqm_t *rq, - int flags); +raqm_set_freetype_load_flags(raqm_t *rq, int flags); bool -raqm_layout (raqm_t *rq); +raqm_layout(raqm_t *rq); raqm_glyph_t * -raqm_get_glyphs (raqm_t *rq, - size_t *length); +raqm_get_glyphs(raqm_t *rq, size_t *length); bool -raqm_index_to_position (raqm_t *rq, - size_t *index, - int *x, - int *y); +raqm_index_to_position(raqm_t *rq, size_t *index, int *x, int *y); bool -raqm_position_to_index (raqm_t *rq, - int x, - int y, - size_t *index); +raqm_position_to_index(raqm_t *rq, int x, int y, size_t *index); #ifdef __cplusplus } diff --git a/src/map.c b/src/map.c index df2718ed7..2636a684b 100644 --- a/src/map.c +++ b/src/map.c @@ -23,17 +23,18 @@ #include "libImaging/Imaging.h" /* compatibility wrappers (defined in _imaging.c) */ -extern int PyImaging_CheckBuffer(PyObject* buffer); -extern int PyImaging_GetBuffer(PyObject* buffer, Py_buffer *view); +extern int +PyImaging_CheckBuffer(PyObject *buffer); +extern int +PyImaging_GetBuffer(PyObject *buffer, Py_buffer *view); /* -------------------------------------------------------------------- */ /* Standard mapper */ typedef struct { - PyObject_HEAD - char* base; - int size; - int offset; + PyObject_HEAD char *base; + int size; + int offset; #ifdef _WIN32 HANDLE hFile; HANDLE hMap; @@ -42,9 +43,8 @@ typedef struct { static PyTypeObject ImagingMapperType; -ImagingMapperObject* -PyImaging_MapperNew(const char* filename, int readonly) -{ +ImagingMapperObject * +PyImaging_MapperNew(const char *filename, int readonly) { ImagingMapperObject *mapper; if (PyType_Ready(&ImagingMapperType) < 0) { @@ -61,14 +61,15 @@ PyImaging_MapperNew(const char* filename, int readonly) #ifdef _WIN32 mapper->hFile = (HANDLE)-1; - mapper->hMap = (HANDLE)-1; + mapper->hMap = (HANDLE)-1; /* FIXME: currently supports readonly mappings only */ mapper->hFile = CreateFile( filename, GENERIC_READ, FILE_SHARE_READ, - NULL, OPEN_EXISTING, + NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (mapper->hFile == (HANDLE)-1) { @@ -77,10 +78,7 @@ PyImaging_MapperNew(const char* filename, int readonly) return NULL; } - mapper->hMap = CreateFileMapping( - mapper->hFile, NULL, - PAGE_READONLY, - 0, 0, NULL); + mapper->hMap = CreateFileMapping(mapper->hFile, NULL, PAGE_READONLY, 0, 0, NULL); if (mapper->hMap == (HANDLE)-1) { CloseHandle(mapper->hFile); PyErr_SetString(PyExc_OSError, "cannot map file"); @@ -88,10 +86,7 @@ PyImaging_MapperNew(const char* filename, int readonly) return NULL; } - mapper->base = (char*) MapViewOfFile( - mapper->hMap, - FILE_MAP_READ, - 0, 0, 0); + mapper->base = (char *)MapViewOfFile(mapper->hMap, FILE_MAP_READ, 0, 0, 0); mapper->size = GetFileSize(mapper->hFile, 0); #endif @@ -100,8 +95,7 @@ PyImaging_MapperNew(const char* filename, int readonly) } static void -mapping_dealloc(ImagingMapperObject* mapper) -{ +mapping_dealloc(ImagingMapperObject *mapper) { #ifdef _WIN32 if (mapper->base != 0) { UnmapViewOfFile(mapper->base); @@ -121,10 +115,9 @@ mapping_dealloc(ImagingMapperObject* mapper) /* -------------------------------------------------------------------- */ /* standard file operations */ -static PyObject* -mapping_read(ImagingMapperObject* mapper, PyObject* args) -{ - PyObject* buf; +static PyObject * +mapping_read(ImagingMapperObject *mapper, PyObject *args) { + PyObject *buf; int size = -1; if (!PyArg_ParseTuple(args, "|i", &size)) { @@ -152,9 +145,8 @@ mapping_read(ImagingMapperObject* mapper, PyObject* args) return buf; } -static PyObject* -mapping_seek(ImagingMapperObject* mapper, PyObject* args) -{ +static PyObject * +mapping_seek(ImagingMapperObject *mapper, PyObject *args) { int offset; int whence = 0; if (!PyArg_ParseTuple(args, "i|i", &offset, &whence)) { @@ -183,27 +175,26 @@ mapping_seek(ImagingMapperObject* mapper, PyObject* args) /* -------------------------------------------------------------------- */ /* map entire image */ -extern PyObject*PyImagingNew(Imaging im); +extern PyObject * +PyImagingNew(Imaging im); static void -ImagingDestroyMap(Imaging im) -{ +ImagingDestroyMap(Imaging im) { return; /* nothing to do! */ } -static PyObject* -mapping_readimage(ImagingMapperObject* mapper, PyObject* args) -{ +static PyObject * +mapping_readimage(ImagingMapperObject *mapper, PyObject *args) { int y, size; Imaging im; - char* mode; + char *mode; int xsize; int ysize; int stride; int orientation; - if (!PyArg_ParseTuple(args, "s(ii)ii", &mode, &xsize, &ysize, - &stride, &orientation)) { + if (!PyArg_ParseTuple( + args, "s(ii)ii", &mode, &xsize, &ysize, &stride, &orientation)) { return NULL; } @@ -237,7 +228,7 @@ mapping_readimage(ImagingMapperObject* mapper, PyObject* args) } } else { for (y = 0; y < ysize; y++) { - im->image[ysize-y-1] = mapper->base + mapper->offset + y * stride; + im->image[ysize - y - 1] = mapper->base + mapper->offset + y * stride; } } @@ -258,48 +249,46 @@ static struct PyMethodDef methods[] = { }; static PyTypeObject ImagingMapperType = { - PyVarObject_HEAD_INIT(NULL, 0) - "ImagingMapper", /*tp_name*/ - sizeof(ImagingMapperObject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)mapping_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ + PyVarObject_HEAD_INIT(NULL, 0) "ImagingMapper", /*tp_name*/ + sizeof(ImagingMapperObject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)mapping_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ }; -PyObject* -PyImaging_Mapper(PyObject* self, PyObject* args) -{ - char* filename; +PyObject * +PyImaging_Mapper(PyObject *self, PyObject *args) { + char *filename; if (!PyArg_ParseTuple(args, "s", &filename)) { return NULL; } - return (PyObject*) PyImaging_MapperNew(filename, 1); + return (PyObject *)PyImaging_MapperNew(filename, 1); } /* -------------------------------------------------------------------- */ @@ -307,36 +296,43 @@ PyImaging_Mapper(PyObject* self, PyObject* args) typedef struct ImagingBufferInstance { struct ImagingMemoryInstance im; - PyObject* target; + PyObject *target; Py_buffer view; } ImagingBufferInstance; static void -mapping_destroy_buffer(Imaging im) -{ - ImagingBufferInstance* buffer = (ImagingBufferInstance*) im; +mapping_destroy_buffer(Imaging im) { + ImagingBufferInstance *buffer = (ImagingBufferInstance *)im; PyBuffer_Release(&buffer->view); Py_XDECREF(buffer->target); } -PyObject* -PyImaging_MapBuffer(PyObject* self, PyObject* args) -{ +PyObject * +PyImaging_MapBuffer(PyObject *self, PyObject *args) { Py_ssize_t y, size; Imaging im; - PyObject* target; + PyObject *target; Py_buffer view; - char* mode; - char* codec; + char *mode; + char *codec; Py_ssize_t offset; int xsize, ysize; int stride; int ystep; - if (!PyArg_ParseTuple(args, "O(ii)sn(sii)", &target, &xsize, &ysize, - &codec, &offset, &mode, &stride, &ystep)) { + if (!PyArg_ParseTuple( + args, + "O(ii)sn(sii)", + &target, + &xsize, + &ysize, + &codec, + &offset, + &mode, + &stride, + &ystep)) { return NULL; } @@ -360,7 +356,7 @@ PyImaging_MapBuffer(PyObject* self, PyObject* args) return NULL; } - size = (Py_ssize_t) ysize * stride; + size = (Py_ssize_t)ysize * stride; if (offset > PY_SSIZE_T_MAX - size) { PyErr_SetString(PyExc_MemoryError, "Integer overflow in offset"); @@ -383,8 +379,7 @@ PyImaging_MapBuffer(PyObject* self, PyObject* args) return NULL; } - im = ImagingNewPrologueSubtype( - mode, xsize, ysize, sizeof(ImagingBufferInstance)); + im = ImagingNewPrologueSubtype(mode, xsize, ysize, sizeof(ImagingBufferInstance)); if (!im) { PyBuffer_Release(&view); return NULL; @@ -393,20 +388,19 @@ PyImaging_MapBuffer(PyObject* self, PyObject* args) /* setup file pointers */ if (ystep > 0) { for (y = 0; y < ysize; y++) { - im->image[y] = (char*)view.buf + offset + y * stride; + im->image[y] = (char *)view.buf + offset + y * stride; } } else { for (y = 0; y < ysize; y++) { - im->image[ysize-y-1] = (char*)view.buf + offset + y * stride; + im->image[ysize - y - 1] = (char *)view.buf + offset + y * stride; } } im->destroy = mapping_destroy_buffer; Py_INCREF(target); - ((ImagingBufferInstance*) im)->target = target; - ((ImagingBufferInstance*) im)->view = view; + ((ImagingBufferInstance *)im)->target = target; + ((ImagingBufferInstance *)im)->view = view; return PyImagingNew(im); } - diff --git a/src/outline.c b/src/outline.c index a109189e1..ba3e056cc 100644 --- a/src/outline.c +++ b/src/outline.c @@ -21,22 +21,19 @@ #include "libImaging/Imaging.h" - /* -------------------------------------------------------------------- */ /* Class */ typedef struct { - PyObject_HEAD - ImagingOutline outline; + PyObject_HEAD ImagingOutline outline; } OutlineObject; static PyTypeObject OutlineType; #define PyOutline_Check(op) (Py_TYPE(op) == &OutlineType) -static OutlineObject* -_outline_new(void) -{ +static OutlineObject * +_outline_new(void) { OutlineObject *self; if (PyType_Ready(&OutlineType) < 0) { @@ -54,43 +51,37 @@ _outline_new(void) } static void -_outline_dealloc(OutlineObject* self) -{ +_outline_dealloc(OutlineObject *self) { ImagingOutlineDelete(self->outline); PyObject_Del(self); } ImagingOutline -PyOutline_AsOutline(PyObject* outline) -{ +PyOutline_AsOutline(PyObject *outline) { if (PyOutline_Check(outline)) { - return ((OutlineObject*) outline)->outline; + return ((OutlineObject *)outline)->outline; } return NULL; } - /* -------------------------------------------------------------------- */ /* Factories */ -PyObject* -PyOutline_Create(PyObject* self, PyObject* args) -{ +PyObject * +PyOutline_Create(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":outline")) { return NULL; } - return (PyObject*) _outline_new(); + return (PyObject *)_outline_new(); } - /* -------------------------------------------------------------------- */ /* Methods */ -static PyObject* -_outline_move(OutlineObject* self, PyObject* args) -{ +static PyObject * +_outline_move(OutlineObject *self, PyObject *args) { float x0, y0; if (!PyArg_ParseTuple(args, "ff", &x0, &y0)) { return NULL; @@ -102,9 +93,8 @@ _outline_move(OutlineObject* self, PyObject* args) return Py_None; } -static PyObject* -_outline_line(OutlineObject* self, PyObject* args) -{ +static PyObject * +_outline_line(OutlineObject *self, PyObject *args) { float x1, y1; if (!PyArg_ParseTuple(args, "ff", &x1, &y1)) { return NULL; @@ -116,9 +106,8 @@ _outline_line(OutlineObject* self, PyObject* args) return Py_None; } -static PyObject* -_outline_curve(OutlineObject* self, PyObject* args) -{ +static PyObject * +_outline_curve(OutlineObject *self, PyObject *args) { float x1, y1, x2, y2, x3, y3; if (!PyArg_ParseTuple(args, "ffffff", &x1, &y1, &x2, &y2, &x3, &y3)) { return NULL; @@ -130,9 +119,8 @@ _outline_curve(OutlineObject* self, PyObject* args) return Py_None; } -static PyObject* -_outline_close(OutlineObject* self, PyObject* args) -{ +static PyObject * +_outline_close(OutlineObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":close")) { return NULL; } @@ -143,11 +131,10 @@ _outline_close(OutlineObject* self, PyObject* args) return Py_None; } -static PyObject* -_outline_transform(OutlineObject* self, PyObject* args) -{ +static PyObject * +_outline_transform(OutlineObject *self, PyObject *args) { double a[6]; - if (!PyArg_ParseTuple(args, "(dddddd)", a+0, a+1, a+2, a+3, a+4, a+5)) { + if (!PyArg_ParseTuple(args, "(dddddd)", a + 0, a + 1, a + 2, a + 3, a + 4, a + 5)) { return NULL; } @@ -167,35 +154,34 @@ static struct PyMethodDef _outline_methods[] = { }; static PyTypeObject OutlineType = { - PyVarObject_HEAD_INIT(NULL, 0) - "Outline", /*tp_name*/ - sizeof(OutlineObject), /*tp_size*/ - 0, /*tp_itemsize*/ + PyVarObject_HEAD_INIT(NULL, 0) "Outline", /*tp_name*/ + sizeof(OutlineObject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - (destructor)_outline_dealloc,/*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - _outline_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ + (destructor)_outline_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + _outline_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ }; diff --git a/src/path.c b/src/path.c index 62e7e15b5..8d1f68e84 100644 --- a/src/path.c +++ b/src/path.c @@ -25,37 +25,36 @@ * See the README file for information on usage and redistribution. */ - #include "Python.h" #include "libImaging/Imaging.h" #include /* compatibility wrappers (defined in _imaging.c) */ -extern int PyImaging_CheckBuffer(PyObject* buffer); -extern int PyImaging_GetBuffer(PyObject* buffer, Py_buffer *view); +extern int +PyImaging_CheckBuffer(PyObject *buffer); +extern int +PyImaging_GetBuffer(PyObject *buffer, Py_buffer *view); /* -------------------------------------------------------------------- */ /* Class */ /* -------------------------------------------------------------------- */ typedef struct { - PyObject_HEAD - Py_ssize_t count; + PyObject_HEAD Py_ssize_t count; double *xy; int index; /* temporary use, e.g. in decimate */ } PyPathObject; static PyTypeObject PyPathType; -static double* -alloc_array(Py_ssize_t count) -{ - double* xy; +static double * +alloc_array(Py_ssize_t count) { + double *xy; if (count < 0) { return ImagingError_MemoryError(); } - if ((unsigned long long)count > (SIZE_MAX / (2 * sizeof(double))) - 1 ) { + if ((unsigned long long)count > (SIZE_MAX / (2 * sizeof(double))) - 1) { return ImagingError_MemoryError(); } xy = malloc(2 * count * sizeof(double) + 1); @@ -65,14 +64,13 @@ alloc_array(Py_ssize_t count) return xy; } -static PyPathObject* -path_new(Py_ssize_t count, double* xy, int duplicate) -{ +static PyPathObject * +path_new(Py_ssize_t count, double *xy, int duplicate) { PyPathObject *path; if (duplicate) { /* duplicate path */ - double* p = alloc_array(count); + double *p = alloc_array(count); if (!p) { return NULL; } @@ -98,8 +96,7 @@ path_new(Py_ssize_t count, double* xy, int duplicate) } static void -path_dealloc(PyPathObject* path) -{ +path_dealloc(PyPathObject *path) { free(path->xy); PyObject_Del(path); } @@ -111,14 +108,13 @@ path_dealloc(PyPathObject* path) #define PyPath_Check(op) (Py_TYPE(op) == &PyPathType) Py_ssize_t -PyPath_Flatten(PyObject* data, double **pxy) -{ +PyPath_Flatten(PyObject *data, double **pxy) { Py_ssize_t i, j, n; double *xy; if (PyPath_Check(data)) { /* This was another path object. */ - PyPathObject *path = (PyPathObject*) data; + PyPathObject *path = (PyPathObject *)data; xy = alloc_array(path->count); if (!xy) { return -1; @@ -132,13 +128,13 @@ PyPath_Flatten(PyObject* data, double **pxy) /* Assume the buffer contains floats */ Py_buffer buffer; if (PyImaging_GetBuffer(data, &buffer) == 0) { - float *ptr = (float*) buffer.buf; + float *ptr = (float *)buffer.buf; n = buffer.len / (2 * sizeof(float)); xy = alloc_array(n); if (!xy) { return -1; } - for (i = 0; i < n+n; i++) { + for (i = 0; i < n + n; i++) { xy[i] = ptr[i]; } *pxy = xy; @@ -174,7 +170,7 @@ PyPath_Flatten(PyObject* data, double **pxy) if (PyFloat_Check(op)) { xy[j++] = PyFloat_AS_DOUBLE(op); } else if (PyLong_Check(op)) { - xy[j++] = (float) PyLong_AS_LONG(op); + xy[j++] = (float)PyLong_AS_LONG(op); } else if (PyNumber_Check(op)) { xy[j++] = PyFloat_AsDouble(op); } else if (PyArg_ParseTuple(op, "dd", &x, &y)) { @@ -192,7 +188,7 @@ PyPath_Flatten(PyObject* data, double **pxy) if (PyFloat_Check(op)) { xy[j++] = PyFloat_AS_DOUBLE(op); } else if (PyLong_Check(op)) { - xy[j++] = (float) PyLong_AS_LONG(op); + xy[j++] = (float)PyLong_AS_LONG(op); } else if (PyNumber_Check(op)) { xy[j++] = PyFloat_AsDouble(op); } else if (PyArg_ParseTuple(op, "dd", &x, &y)) { @@ -209,8 +205,7 @@ PyPath_Flatten(PyObject* data, double **pxy) PyObject *op = PySequence_GetItem(data, i); if (!op) { /* treat IndexError as end of sequence */ - if (PyErr_Occurred() && - PyErr_ExceptionMatches(PyExc_IndexError)) { + if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_IndexError)) { PyErr_Clear(); break; } else { @@ -221,7 +216,7 @@ PyPath_Flatten(PyObject* data, double **pxy) if (PyFloat_Check(op)) { xy[j++] = PyFloat_AS_DOUBLE(op); } else if (PyLong_Check(op)) { - xy[j++] = (float) PyLong_AS_LONG(op); + xy[j++] = (float)PyLong_AS_LONG(op); } else if (PyNumber_Check(op)) { xy[j++] = PyFloat_AsDouble(op); } else if (PyArg_ParseTuple(op, "dd", &x, &y)) { @@ -243,23 +238,20 @@ PyPath_Flatten(PyObject* data, double **pxy) } *pxy = xy; - return j/2; + return j / 2; } - /* -------------------------------------------------------------------- */ /* Factories */ /* -------------------------------------------------------------------- */ -PyObject* -PyPath_Create(PyObject* self, PyObject* args) -{ - PyObject* data; +PyObject * +PyPath_Create(PyObject *self, PyObject *args) { + PyObject *data; Py_ssize_t count; double *xy; if (PyArg_ParseTuple(args, "n:Path", &count)) { - /* number of vertices */ xy = alloc_array(count); if (!xy) { @@ -267,7 +259,6 @@ PyPath_Create(PyObject* self, PyObject* args) } } else { - /* sequence or other path */ PyErr_Clear(); if (!PyArg_ParseTuple(args, "O", &data)) { @@ -280,17 +271,15 @@ PyPath_Create(PyObject* self, PyObject* args) } } - return (PyObject*) path_new(count, xy, 0); + return (PyObject *)path_new(count, xy, 0); } - /* -------------------------------------------------------------------- */ /* Methods */ /* -------------------------------------------------------------------- */ -static PyObject* -path_compact(PyPathObject* self, PyObject* args) -{ +static PyObject * +path_compact(PyPathObject *self, PyObject *args) { /* Simple-minded method to shorten path. A point is removed if the city block distance to the previous point is less than the given distance */ @@ -307,9 +296,10 @@ path_compact(PyPathObject* self, PyObject* args) /* remove bogus vertices */ for (i = j = 1; i < self->count; i++) { - if (fabs(xy[j+j-2]-xy[i+i]) + fabs(xy[j+j-1]-xy[i+i+1]) >= cityblock) { - xy[j+j] = xy[i+i]; - xy[j+j+1] = xy[i+i+1]; + if (fabs(xy[j + j - 2] - xy[i + i]) + fabs(xy[j + j - 1] - xy[i + i + 1]) >= + cityblock) { + xy[j + j] = xy[i + i]; + xy[j + j + 1] = xy[i + i + 1]; j++; } } @@ -324,9 +314,8 @@ path_compact(PyPathObject* self, PyObject* args) return Py_BuildValue("i", i); /* number of removed vertices */ } -static PyObject* -path_getbbox(PyPathObject* self, PyObject* args) -{ +static PyObject * +path_getbbox(PyPathObject *self, PyObject *args) { /* Find bounding box */ Py_ssize_t i; double *xy; @@ -342,26 +331,25 @@ path_getbbox(PyPathObject* self, PyObject* args) y0 = y1 = xy[1]; for (i = 1; i < self->count; i++) { - if (xy[i+i] < x0) { - x0 = xy[i+i]; + if (xy[i + i] < x0) { + x0 = xy[i + i]; } - if (xy[i+i] > x1) { - x1 = xy[i+i]; + if (xy[i + i] > x1) { + x1 = xy[i + i]; } - if (xy[i+i+1] < y0) { - y0 = xy[i+i+1]; + if (xy[i + i + 1] < y0) { + y0 = xy[i + i + 1]; } - if (xy[i+i+1] > y1) { - y1 = xy[i+i+1]; + if (xy[i + i + 1] > y1) { + y1 = xy[i + i + 1]; } } return Py_BuildValue("dddd", x0, y0, x1, y1); } -static PyObject* -path_getitem(PyPathObject* self, Py_ssize_t i) -{ +static PyObject * +path_getitem(PyPathObject *self, Py_ssize_t i) { if (i < 0) { i = self->count + i; } @@ -370,12 +358,11 @@ path_getitem(PyPathObject* self, Py_ssize_t i) return NULL; } - return Py_BuildValue("dd", self->xy[i+i], self->xy[i+i+1]); + return Py_BuildValue("dd", self->xy[i + i], self->xy[i + i + 1]); } -static PyObject* -path_getslice(PyPathObject* self, Py_ssize_t ilow, Py_ssize_t ihigh) -{ +static PyObject * +path_getslice(PyPathObject *self, Py_ssize_t ilow, Py_ssize_t ihigh) { /* adjust arguments */ if (ilow < 0) { ilow = 0; @@ -391,22 +378,20 @@ path_getslice(PyPathObject* self, Py_ssize_t ilow, Py_ssize_t ihigh) ihigh = self->count; } - return (PyObject*) path_new(ihigh - ilow, self->xy + ilow * 2, 1); + return (PyObject *)path_new(ihigh - ilow, self->xy + ilow * 2, 1); } static Py_ssize_t -path_len(PyPathObject* self) -{ +path_len(PyPathObject *self) { return self->count; } -static PyObject* -path_map(PyPathObject* self, PyObject* args) -{ +static PyObject * +path_map(PyPathObject *self, PyObject *args) { /* Map coordinate set through function */ Py_ssize_t i; double *xy; - PyObject* function; + PyObject *function; if (!PyArg_ParseTuple(args, "O:map", &function)) { return NULL; @@ -416,15 +401,15 @@ path_map(PyPathObject* self, PyObject* args) /* apply function to coordinate set */ for (i = 0; i < self->count; i++) { - double x = xy[i+i]; - double y = xy[i+i+1]; - PyObject* item = PyObject_CallFunction(function, "dd", x, y); + double x = xy[i + i]; + double y = xy[i + i + 1]; + PyObject *item = PyObject_CallFunction(function, "dd", x, y); if (!item || !PyArg_ParseTuple(item, "dd", &x, &y)) { Py_XDECREF(item); return NULL; } - xy[i+i] = x; - xy[i+i+1] = y; + xy[i + i] = x; + xy[i + i + 1] = y; Py_DECREF(item); } @@ -433,23 +418,20 @@ path_map(PyPathObject* self, PyObject* args) } static int -path_setitem(PyPathObject* self, Py_ssize_t i, PyObject* op) -{ - double* xy; +path_setitem(PyPathObject *self, Py_ssize_t i, PyObject *op) { + double *xy; if (i < 0 || i >= self->count) { - PyErr_SetString(PyExc_IndexError, - "path assignment index out of range"); + PyErr_SetString(PyExc_IndexError, "path assignment index out of range"); return -1; } if (op == NULL) { - PyErr_SetString(PyExc_TypeError, - "cannot delete from path"); + PyErr_SetString(PyExc_TypeError, "cannot delete from path"); return -1; } - xy = &self->xy[i+i]; + xy = &self->xy[i + i]; if (!PyArg_ParseTuple(op, "dd", &xy[0], &xy[1])) { return -1; @@ -458,9 +440,8 @@ path_setitem(PyPathObject* self, Py_ssize_t i, PyObject* op) return 0; } -static PyObject* -path_tolist(PyPathObject* self, PyObject* args) -{ +static PyObject * +path_tolist(PyPathObject *self, PyObject *args) { PyObject *list; Py_ssize_t i; @@ -470,9 +451,9 @@ path_tolist(PyPathObject* self, PyObject* args) } if (flat) { - list = PyList_New(self->count*2); - for (i = 0; i < self->count*2; i++) { - PyObject* item; + list = PyList_New(self->count * 2); + for (i = 0; i < self->count * 2; i++) { + PyObject *item; item = PyFloat_FromDouble(self->xy[i]); if (!item) { goto error; @@ -482,8 +463,8 @@ path_tolist(PyPathObject* self, PyObject* args) } else { list = PyList_New(self->count); for (i = 0; i < self->count; i++) { - PyObject* item; - item = Py_BuildValue("dd", self->xy[i+i], self->xy[i+i+1]); + PyObject *item; + item = Py_BuildValue("dd", self->xy[i + i], self->xy[i + i + 1]); if (!item) { goto error; } @@ -498,9 +479,8 @@ error: return NULL; } -static PyObject* -path_transform(PyPathObject* self, PyObject* args) -{ +static PyObject * +path_transform(PyPathObject *self, PyObject *args) { /* Apply affine transform to coordinate set */ Py_ssize_t i; double *xy; @@ -508,9 +488,8 @@ path_transform(PyPathObject* self, PyObject* args) double wrap = 0.0; - if (!PyArg_ParseTuple(args, "(dddddd)|d:transform", - &a, &b, &c, &d, &e, &f, - &wrap)) { + if (!PyArg_ParseTuple( + args, "(dddddd)|d:transform", &a, &b, &c, &d, &e, &f, &wrap)) { return NULL; } @@ -520,23 +499,23 @@ path_transform(PyPathObject* self, PyObject* args) if (b == 0.0 && d == 0.0) { /* scaling */ for (i = 0; i < self->count; i++) { - xy[i+i] = a*xy[i+i]+c; - xy[i+i+1] = e*xy[i+i+1]+f; + xy[i + i] = a * xy[i + i] + c; + xy[i + i + 1] = e * xy[i + i + 1] + f; } } else { /* affine transform */ for (i = 0; i < self->count; i++) { - double x = xy[i+i]; - double y = xy[i+i+1]; - xy[i+i] = a*x+b*y+c; - xy[i+i+1] = d*x+e*y+f; + double x = xy[i + i]; + double y = xy[i + i + 1]; + xy[i + i] = a * x + b * y + c; + xy[i + i + 1] = d * x + e * y + f; } } /* special treatment of geographical map data */ if (wrap != 0.0) { for (i = 0; i < self->count; i++) { - xy[i+i] = fmod(xy[i+i], wrap); + xy[i + i] = fmod(xy[i + i], wrap); } } @@ -553,19 +532,15 @@ static struct PyMethodDef methods[] = { {NULL, NULL} /* sentinel */ }; -static PyObject* -path_getattr_id(PyPathObject* self, void* closure) -{ - return Py_BuildValue("n", (Py_ssize_t) self->xy); +static PyObject * +path_getattr_id(PyPathObject *self, void *closure) { + return Py_BuildValue("n", (Py_ssize_t)self->xy); } -static struct PyGetSetDef getsetters[] = { - { "id", (getter) path_getattr_id }, - { NULL } -}; +static struct PyGetSetDef getsetters[] = {{"id", (getter)path_getattr_id}, {NULL}}; -static PyObject* -path_subscript(PyPathObject* self, PyObject* item) { +static PyObject * +path_subscript(PyPathObject *self, PyObject *item) { if (PyIndex_Check(item)) { Py_ssize_t i; i = PyNumber_AsSsize_t(item, PyExc_IndexError); @@ -584,71 +559,64 @@ path_subscript(PyPathObject* self, PyObject* item) { if (slicelength <= 0) { double *xy = alloc_array(0); - return (PyObject*) path_new(0, xy, 0); - } - else if (step == 1) { + return (PyObject *)path_new(0, xy, 0); + } else if (step == 1) { return path_getslice(self, start, stop); - } - else { + } else { PyErr_SetString(PyExc_TypeError, "slice steps not supported"); return NULL; } - } - else { - PyErr_Format(PyExc_TypeError, - "Path indices must be integers, not %.200s", - Py_TYPE(item)->tp_name); + } else { + PyErr_Format( + PyExc_TypeError, + "Path indices must be integers, not %.200s", + Py_TYPE(item)->tp_name); return NULL; } } static PySequenceMethods path_as_sequence = { - (lenfunc)path_len, /*sq_length*/ - (binaryfunc)0, /*sq_concat*/ - (ssizeargfunc)0, /*sq_repeat*/ - (ssizeargfunc)path_getitem, /*sq_item*/ - (ssizessizeargfunc)path_getslice, /*sq_slice*/ - (ssizeobjargproc)path_setitem, /*sq_ass_item*/ - (ssizessizeobjargproc)0, /*sq_ass_slice*/ + (lenfunc)path_len, /*sq_length*/ + (binaryfunc)0, /*sq_concat*/ + (ssizeargfunc)0, /*sq_repeat*/ + (ssizeargfunc)path_getitem, /*sq_item*/ + (ssizessizeargfunc)path_getslice, /*sq_slice*/ + (ssizeobjargproc)path_setitem, /*sq_ass_item*/ + (ssizessizeobjargproc)0, /*sq_ass_slice*/ }; static PyMappingMethods path_as_mapping = { - (lenfunc)path_len, - (binaryfunc)path_subscript, - NULL -}; + (lenfunc)path_len, (binaryfunc)path_subscript, NULL}; static PyTypeObject PyPathType = { - PyVarObject_HEAD_INIT(NULL, 0) - "Path", /*tp_name*/ - sizeof(PyPathObject), /*tp_size*/ - 0, /*tp_itemsize*/ + PyVarObject_HEAD_INIT(NULL, 0) "Path", /*tp_name*/ + sizeof(PyPathObject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - (destructor)path_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number */ - &path_as_sequence, /*tp_as_sequence */ - &path_as_mapping, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - methods, /*tp_methods*/ - 0, /*tp_members*/ - getsetters, /*tp_getset*/ + (destructor)path_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number */ + &path_as_sequence, /*tp_as_sequence */ + &path_as_mapping, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + methods, /*tp_methods*/ + 0, /*tp_members*/ + getsetters, /*tp_getset*/ }; -