lastpng 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. lastpng-0.2.1/.gitignore +4 -0
  2. lastpng-0.2.1/LICENSE +21 -0
  3. lastpng-0.2.1/PKG-INFO +92 -0
  4. lastpng-0.2.1/README.md +79 -0
  5. lastpng-0.2.1/decoder/Cargo.lock +102 -0
  6. lastpng-0.2.1/decoder/Cargo.toml +14 -0
  7. lastpng-0.2.1/decoder/src/lib.rs +380 -0
  8. lastpng-0.2.1/hatch_build.py +93 -0
  9. lastpng-0.2.1/licenses/fdeflate-LICENSE-MIT +25 -0
  10. lastpng-0.2.1/licenses/libdeflate-COPYING +22 -0
  11. lastpng-0.2.1/pyproject.toml +40 -0
  12. lastpng-0.2.1/rust/Cargo.lock +128 -0
  13. lastpng-0.2.1/rust/Cargo.toml +37 -0
  14. lastpng-0.2.1/rust/build.rs +25 -0
  15. lastpng-0.2.1/rust/include/lastpng.h +75 -0
  16. lastpng-0.2.1/rust/models/higher.f32le +0 -0
  17. lastpng-0.2.1/rust/native/row_deflate.c +235 -0
  18. lastpng-0.2.1/rust/src/deflate.rs +184 -0
  19. lastpng-0.2.1/rust/src/encode.rs +218 -0
  20. lastpng-0.2.1/rust/src/ffi.rs +258 -0
  21. lastpng-0.2.1/rust/src/lib.rs +1627 -0
  22. lastpng-0.2.1/rust/src/palette.rs +292 -0
  23. lastpng-0.2.1/rust/src/row_deflate.rs +144 -0
  24. lastpng-0.2.1/rust/src/row_model.rs +771 -0
  25. lastpng-0.2.1/rust/src/tiny.rs +167 -0
  26. lastpng-0.2.1/rust/src/ultrafast.rs +222 -0
  27. lastpng-0.2.1/rust/vendor/fdeflate-LICENSE-MIT +25 -0
  28. lastpng-0.2.1/rust/vendor/libdeflate/COPYING +22 -0
  29. lastpng-0.2.1/rust/vendor/libdeflate/README.md +9 -0
  30. lastpng-0.2.1/rust/vendor/libdeflate/common_defs.h +735 -0
  31. lastpng-0.2.1/rust/vendor/libdeflate/lib/adler32.c +162 -0
  32. lastpng-0.2.1/rust/vendor/libdeflate/lib/arm/adler32_impl.h +365 -0
  33. lastpng-0.2.1/rust/vendor/libdeflate/lib/arm/cpu_features.c +292 -0
  34. lastpng-0.2.1/rust/vendor/libdeflate/lib/arm/cpu_features.h +214 -0
  35. lastpng-0.2.1/rust/vendor/libdeflate/lib/arm/matchfinder_impl.h +78 -0
  36. lastpng-0.2.1/rust/vendor/libdeflate/lib/bt_matchfinder.h +229 -0
  37. lastpng-0.2.1/rust/vendor/libdeflate/lib/bt_matchfinder_search.h +127 -0
  38. lastpng-0.2.1/rust/vendor/libdeflate/lib/cpu_features_common.h +93 -0
  39. lastpng-0.2.1/rust/vendor/libdeflate/lib/deflate_compress.c +4237 -0
  40. lastpng-0.2.1/rust/vendor/libdeflate/lib/deflate_compress.h +15 -0
  41. lastpng-0.2.1/rust/vendor/libdeflate/lib/deflate_constants.h +56 -0
  42. lastpng-0.2.1/rust/vendor/libdeflate/lib/deflate_write_sequences.h +67 -0
  43. lastpng-0.2.1/rust/vendor/libdeflate/lib/hc_matchfinder.h +401 -0
  44. lastpng-0.2.1/rust/vendor/libdeflate/lib/ht_matchfinder.h +263 -0
  45. lastpng-0.2.1/rust/vendor/libdeflate/lib/lib_common.h +106 -0
  46. lastpng-0.2.1/rust/vendor/libdeflate/lib/matchfinder_common.h +224 -0
  47. lastpng-0.2.1/rust/vendor/libdeflate/lib/riscv/matchfinder_impl.h +97 -0
  48. lastpng-0.2.1/rust/vendor/libdeflate/lib/utils.c +141 -0
  49. lastpng-0.2.1/rust/vendor/libdeflate/lib/x86/adler32_impl.h +136 -0
  50. lastpng-0.2.1/rust/vendor/libdeflate/lib/x86/adler32_template.h +518 -0
  51. lastpng-0.2.1/rust/vendor/libdeflate/lib/x86/cpu_features.c +213 -0
  52. lastpng-0.2.1/rust/vendor/libdeflate/lib/x86/cpu_features.h +170 -0
  53. lastpng-0.2.1/rust/vendor/libdeflate/lib/x86/matchfinder_impl.h +122 -0
  54. lastpng-0.2.1/rust/vendor/libdeflate/lib/zlib_compress.c +82 -0
  55. lastpng-0.2.1/rust/vendor/libdeflate/lib/zlib_constants.h +21 -0
  56. lastpng-0.2.1/rust/vendor/libdeflate/libdeflate.h +412 -0
  57. lastpng-0.2.1/src/LastPNGImagePlugin.py +487 -0
  58. lastpng-0.2.1/tests/test_native_loading.py +42 -0
  59. lastpng-0.2.1/tests/test_pillow_plugin.py +1014 -0
@@ -0,0 +1,4 @@
1
+ /target/
2
+ /python/dist/
3
+ /python/decoder/target/
4
+ __pycache__
lastpng-0.2.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aleksandr Karpinskii
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
lastpng-0.2.1/PKG-INFO ADDED
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.5
2
+ Name: lastpng
3
+ Version: 0.2.1
4
+ Summary: A vibe-coded, blazingly fast PNG compressor for Pillow
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ License-File: licenses/fdeflate-LICENSE-MIT
8
+ License-File: licenses/libdeflate-COPYING
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: cffi>=1.17
11
+ Requires-Dist: pillow<=13.0.0,>=11
12
+ Description-Content-Type: text/markdown
13
+
14
+ # LastPNG for Pillow
15
+
16
+ LastPNG makes reading and saving PNG images in Pillow faster and optimizes file size by choosing the palette, bit depth, and color type automatically. Output remains standard PNG, preserving visible colors and transparency; RGB values in fully transparent pixels may change. Reading supports PNG and APNG, with Pillow handling metadata and animation composition.
17
+
18
+ ## Installation
19
+
20
+ Requires Python ≥3.10 and Pillow ≥11, ≤13.0.0.
21
+
22
+ ```sh
23
+ pip install lastpng
24
+ ```
25
+
26
+ Wheels bundle the native libraries; no separate libdeflate or Windows VC Redistributable installation is needed.
27
+
28
+ ## Usage
29
+
30
+ ```python
31
+ from PIL import Image
32
+ import LastPNGImagePlugin
33
+
34
+ # Select LastPNG explicitly when saving.
35
+ with Image.open("input.png") as image:
36
+ image.save("output.png", format="LASTPNG", level=3)
37
+
38
+ # Use Rust decoding and LastPNG encoding by default throughout the process.
39
+ LastPNGImagePlugin.register_as_default()
40
+ with Image.open("input.png") as image:
41
+ image.save("output.png", level=3)
42
+ ```
43
+
44
+ Use `register_as_default(encoder=False)` to enable only Rust decoding and keep the current PNG encoder.
45
+
46
+ Choose a compression level from 1 (fastest) to 6 (experimental, highest effort). The default is 3.
47
+
48
+ ### Save options
49
+
50
+ Supports `pnginfo`, `icc_profile`, `transparency`, `dpi`, and `exif`. An ICC profile preserves the input color family.
51
+
52
+ In `pnginfo`, IHDR, PLTE, tRNS, IDAT, IEND, bKGD, hIST, sBIT, eXIf, and iCCP raise `ValueError`. LastPNG selects the output representation; use `exif=` for EXIF and `icc_profile=` for an uncompressed ICC profile.
53
+
54
+ For a unitless pixel aspect ratio or exact pixels-per-metre values, pass one `pHYs` chunk in `pnginfo`; it is written before IDAT. Combining it with `dpi` raises `ValueError`.
55
+
56
+ HDR `mDCV` (24 bytes) and `cLLI` (8 bytes) are accepted once each through `pnginfo` and written before PLTE and IDAT. `mDCV` requires `cICP`, in either input order.
57
+
58
+ ## Limitations and behavior
59
+
60
+ ### Formats and compatibility
61
+
62
+ Encoding supports single images in modes `1`, `L`, `I;16`, `P`, `RGB`, `LA`, and `RGBA`. APNG saving uses Pillow's encoder. Decoding supports Adam7 interlacing and APNG.
63
+
64
+ Supports CPython with Pillow major versions 11, 12, and 13. Unsupported versions raise an error when importing the plugin.
65
+
66
+ ### Image access and animation
67
+
68
+ Keep the image unchanged until `save()` returns. Serialize loading, seeking, and pixel access on the same image object.
69
+
70
+ APNG decoding streams frames on demand, reading frame data once during forward playback, including gzip streams. Initialization may reread large headers; rewinding or retrying a failed native decode rereads the stream. Keep the file open while frames are needed.
71
+
72
+ Pillow's animation limitations apply, including unsupported `I;16` blending with `OP_OVER`. Reopen the image after errors in Pillow metadata processing, frame transitions, or composition.
73
+
74
+ ### Damaged PNGs
75
+
76
+ With `PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True`, decoding tolerates early EOF, missing rows, and damaged compressed data. Complete rows (including Adam7 pass rows) are retained; unrecovered pixels remain zero or retain the existing APNG canvas. CRC and Adler-32 checks are disabled, but Pillow still validates headers, metadata, and APNG frame controls and sequences.
77
+
78
+ Recovered pixels may differ from Pillow's zlib decoder. Rust's structural checks and static PNG memory limits can reject files Pillow accepts. For APNG, Rust's internal allocation budget is disabled; Pillow controls destination image allocation.
79
+
80
+ Without truncated loading, corrupt static PNG IDAT checksums or a missing chunk header after frame data cause errors that Pillow may tolerate during `load()`. APNG fdAT CRC errors are accepted, as in Pillow.
81
+
82
+ ## Building from source
83
+
84
+ A Rust toolchain and a C compiler are required. From the repository root:
85
+
86
+ ```sh
87
+ python -m pip install ./python # Install from the checkout.
88
+
89
+ # Build an sdist and wheel in python/dist/.
90
+ python -m pip install build
91
+ python -m build ./python
92
+ ```
@@ -0,0 +1,79 @@
1
+ # LastPNG for Pillow
2
+
3
+ LastPNG makes reading and saving PNG images in Pillow faster and optimizes file size by choosing the palette, bit depth, and color type automatically. Output remains standard PNG, preserving visible colors and transparency; RGB values in fully transparent pixels may change. Reading supports PNG and APNG, with Pillow handling metadata and animation composition.
4
+
5
+ ## Installation
6
+
7
+ Requires Python ≥3.10 and Pillow ≥11, ≤13.0.0.
8
+
9
+ ```sh
10
+ pip install lastpng
11
+ ```
12
+
13
+ Wheels bundle the native libraries; no separate libdeflate or Windows VC Redistributable installation is needed.
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ from PIL import Image
19
+ import LastPNGImagePlugin
20
+
21
+ # Select LastPNG explicitly when saving.
22
+ with Image.open("input.png") as image:
23
+ image.save("output.png", format="LASTPNG", level=3)
24
+
25
+ # Use Rust decoding and LastPNG encoding by default throughout the process.
26
+ LastPNGImagePlugin.register_as_default()
27
+ with Image.open("input.png") as image:
28
+ image.save("output.png", level=3)
29
+ ```
30
+
31
+ Use `register_as_default(encoder=False)` to enable only Rust decoding and keep the current PNG encoder.
32
+
33
+ Choose a compression level from 1 (fastest) to 6 (experimental, highest effort). The default is 3.
34
+
35
+ ### Save options
36
+
37
+ Supports `pnginfo`, `icc_profile`, `transparency`, `dpi`, and `exif`. An ICC profile preserves the input color family.
38
+
39
+ In `pnginfo`, IHDR, PLTE, tRNS, IDAT, IEND, bKGD, hIST, sBIT, eXIf, and iCCP raise `ValueError`. LastPNG selects the output representation; use `exif=` for EXIF and `icc_profile=` for an uncompressed ICC profile.
40
+
41
+ For a unitless pixel aspect ratio or exact pixels-per-metre values, pass one `pHYs` chunk in `pnginfo`; it is written before IDAT. Combining it with `dpi` raises `ValueError`.
42
+
43
+ HDR `mDCV` (24 bytes) and `cLLI` (8 bytes) are accepted once each through `pnginfo` and written before PLTE and IDAT. `mDCV` requires `cICP`, in either input order.
44
+
45
+ ## Limitations and behavior
46
+
47
+ ### Formats and compatibility
48
+
49
+ Encoding supports single images in modes `1`, `L`, `I;16`, `P`, `RGB`, `LA`, and `RGBA`. APNG saving uses Pillow's encoder. Decoding supports Adam7 interlacing and APNG.
50
+
51
+ Supports CPython with Pillow major versions 11, 12, and 13. Unsupported versions raise an error when importing the plugin.
52
+
53
+ ### Image access and animation
54
+
55
+ Keep the image unchanged until `save()` returns. Serialize loading, seeking, and pixel access on the same image object.
56
+
57
+ APNG decoding streams frames on demand, reading frame data once during forward playback, including gzip streams. Initialization may reread large headers; rewinding or retrying a failed native decode rereads the stream. Keep the file open while frames are needed.
58
+
59
+ Pillow's animation limitations apply, including unsupported `I;16` blending with `OP_OVER`. Reopen the image after errors in Pillow metadata processing, frame transitions, or composition.
60
+
61
+ ### Damaged PNGs
62
+
63
+ With `PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True`, decoding tolerates early EOF, missing rows, and damaged compressed data. Complete rows (including Adam7 pass rows) are retained; unrecovered pixels remain zero or retain the existing APNG canvas. CRC and Adler-32 checks are disabled, but Pillow still validates headers, metadata, and APNG frame controls and sequences.
64
+
65
+ Recovered pixels may differ from Pillow's zlib decoder. Rust's structural checks and static PNG memory limits can reject files Pillow accepts. For APNG, Rust's internal allocation budget is disabled; Pillow controls destination image allocation.
66
+
67
+ Without truncated loading, corrupt static PNG IDAT checksums or a missing chunk header after frame data cause errors that Pillow may tolerate during `load()`. APNG fdAT CRC errors are accepted, as in Pillow.
68
+
69
+ ## Building from source
70
+
71
+ A Rust toolchain and a C compiler are required. From the repository root:
72
+
73
+ ```sh
74
+ python -m pip install ./python # Install from the checkout.
75
+
76
+ # Build an sdist and wheel in python/dist/.
77
+ python -m pip install build
78
+ python -m build ./python
79
+ ```
@@ -0,0 +1,102 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "adler2"
7
+ version = "2.0.1"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10
+
11
+ [[package]]
12
+ name = "bitflags"
13
+ version = "2.13.2"
14
+ source = "registry+https://github.com/rust-lang/crates.io-index"
15
+ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
16
+
17
+ [[package]]
18
+ name = "cfg-if"
19
+ version = "1.0.5"
20
+ source = "registry+https://github.com/rust-lang/crates.io-index"
21
+ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
22
+
23
+ [[package]]
24
+ name = "crc32fast"
25
+ version = "1.5.6"
26
+ source = "registry+https://github.com/rust-lang/crates.io-index"
27
+ checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
28
+ dependencies = [
29
+ "cfg-if",
30
+ ]
31
+
32
+ [[package]]
33
+ name = "fdeflate"
34
+ version = "0.3.7"
35
+ source = "registry+https://github.com/rust-lang/crates.io-index"
36
+ checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
37
+ dependencies = [
38
+ "simd-adler32",
39
+ ]
40
+
41
+ [[package]]
42
+ name = "flate2"
43
+ version = "1.1.11"
44
+ source = "registry+https://github.com/rust-lang/crates.io-index"
45
+ checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
46
+ dependencies = [
47
+ "crc32fast",
48
+ "miniz_oxide 0.9.1",
49
+ "zlib-rs",
50
+ ]
51
+
52
+ [[package]]
53
+ name = "lastpng_decoder"
54
+ version = "0.1.0"
55
+ dependencies = [
56
+ "png",
57
+ ]
58
+
59
+ [[package]]
60
+ name = "miniz_oxide"
61
+ version = "0.8.9"
62
+ source = "registry+https://github.com/rust-lang/crates.io-index"
63
+ checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
64
+ dependencies = [
65
+ "adler2",
66
+ "simd-adler32",
67
+ ]
68
+
69
+ [[package]]
70
+ name = "miniz_oxide"
71
+ version = "0.9.1"
72
+ source = "registry+https://github.com/rust-lang/crates.io-index"
73
+ checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
74
+ dependencies = [
75
+ "adler2",
76
+ "simd-adler32",
77
+ ]
78
+
79
+ [[package]]
80
+ name = "png"
81
+ version = "0.18.1"
82
+ source = "registry+https://github.com/rust-lang/crates.io-index"
83
+ checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
84
+ dependencies = [
85
+ "bitflags",
86
+ "crc32fast",
87
+ "fdeflate",
88
+ "flate2",
89
+ "miniz_oxide 0.8.9",
90
+ ]
91
+
92
+ [[package]]
93
+ name = "simd-adler32"
94
+ version = "0.3.10"
95
+ source = "registry+https://github.com/rust-lang/crates.io-index"
96
+ checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
97
+
98
+ [[package]]
99
+ name = "zlib-rs"
100
+ version = "0.6.9"
101
+ source = "registry+https://github.com/rust-lang/crates.io-index"
102
+ checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
@@ -0,0 +1,14 @@
1
+ [package]
2
+ name = "lastpng_decoder"
3
+ version = "0.1.0"
4
+ edition = "2024"
5
+ publish = false
6
+
7
+ [lib]
8
+ crate-type = ["cdylib"]
9
+
10
+ [dependencies]
11
+ png = "=0.18.1"
12
+
13
+ [profile.release]
14
+ strip = "none"
@@ -0,0 +1,380 @@
1
+ use png::{BitDepth, ColorType};
2
+ use std::error::Error;
3
+ use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
4
+ use std::slice;
5
+
6
+ fn unpack_low<const BITS: usize>(row: &mut [u8], width: usize, scale: u8) {
7
+ let per_byte = 8 / BITS;
8
+ let mask = (1u8 << BITS) - 1;
9
+ for x in (0..width).rev() {
10
+ let shift = (per_byte - 1 - x % per_byte) * BITS;
11
+ row[x] = ((row[x / per_byte] >> shift) & mask) * scale;
12
+ }
13
+ }
14
+
15
+ // Pillow stores one byte per low-depth sample and four bytes per LA/RGB(A) pixel.
16
+ fn unpack(row: &mut [u8], width: usize, color: ColorType, depth: BitDepth) {
17
+ if matches!(depth, BitDepth::One | BitDepth::Two | BitDepth::Four) {
18
+ let scale = if color == ColorType::Indexed {
19
+ 1
20
+ } else {
21
+ 255 / ((1u8 << depth as u8) - 1)
22
+ };
23
+ match depth {
24
+ BitDepth::One => unpack_low::<1>(row, width, scale),
25
+ BitDepth::Two => unpack_low::<2>(row, width, scale),
26
+ BitDepth::Four => unpack_low::<4>(row, width, scale),
27
+ _ => unreachable!(),
28
+ }
29
+ } else if color == ColorType::Rgb {
30
+ for x in (0..width).rev() {
31
+ let rgb = [row[3 * x], row[3 * x + 1], row[3 * x + 2], 255];
32
+ row[4 * x..4 * x + 4].copy_from_slice(&rgb);
33
+ }
34
+ } else if color == ColorType::GrayscaleAlpha {
35
+ for x in (0..width).rev() {
36
+ let l = row[2 * x];
37
+ let a = row[2 * x + 1];
38
+ row[4 * x..4 * x + 4].copy_from_slice(&[l, l, l, a]);
39
+ }
40
+ } else if depth == BitDepth::Sixteen {
41
+ for pair in row.chunks_exact_mut(2) {
42
+ pair.swap(0, 1);
43
+ }
44
+ }
45
+ }
46
+
47
+ fn image_row<T>(
48
+ result: Result<Option<T>, png::DecodingError>,
49
+ allow_truncated: bool,
50
+ ) -> Result<Option<T>, Box<dyn Error>> {
51
+ match result {
52
+ Ok(Some(row)) => Ok(Some(row)),
53
+ _ if allow_truncated => Ok(None),
54
+ Ok(None) => Err("missing PNG row".into()),
55
+ Err(error) => Err(error.into()),
56
+ }
57
+ }
58
+
59
+ fn png_reader<R: BufRead + Seek>(
60
+ input: R,
61
+ allow_truncated: bool,
62
+ limits: png::Limits,
63
+ ) -> Result<png::Reader<R>, Box<dyn Error>> {
64
+ let mut decoder = png::Decoder::new_with_limits(input, limits);
65
+ decoder.set_ignore_text_chunk(true);
66
+ decoder.set_ignore_iccp_chunk(true);
67
+ decoder.ignore_checksums(allow_truncated);
68
+ let header = decoder.read_header_info()?;
69
+ let mut transform = png::Transformations::IDENTITY;
70
+ if header.color_type != ColorType::Grayscale && header.bit_depth == BitDepth::Sixteen {
71
+ transform |= png::Transformations::STRIP_16;
72
+ }
73
+ decoder.set_transformations(transform);
74
+ Ok(decoder.read_info()?)
75
+ }
76
+
77
+ // Each address is an exclusively writable Pillow row of at least stride bytes.
78
+ unsafe fn pillow_rows<R: BufRead + Seek>(
79
+ reader: &mut png::Reader<R>,
80
+ rows: &[*mut u8],
81
+ width: u32,
82
+ stride: usize,
83
+ allow_truncated: bool,
84
+ ) -> Result<(), Box<dyn Error>> {
85
+ let info = reader.info();
86
+ let (frame_width, frame_height) = info
87
+ .frame_control
88
+ .as_ref()
89
+ .map_or((info.width, info.height), |frame| {
90
+ (frame.width, frame.height)
91
+ });
92
+ if frame_width != width || frame_height as usize != rows.len() {
93
+ return Err("PNG dimensions do not match the destination".into());
94
+ }
95
+ let (color, depth) = reader.output_color_type();
96
+ let pixel_bytes = match color {
97
+ ColorType::Rgb | ColorType::Rgba | ColorType::GrayscaleAlpha => 4,
98
+ ColorType::Grayscale if depth == BitDepth::Sixteen => 2,
99
+ ColorType::Grayscale | ColorType::Indexed => 1,
100
+ };
101
+ let width = width as usize;
102
+ if width.checked_mul(pixel_bytes) != Some(stride)
103
+ || stride > isize::MAX as usize
104
+ || rows.iter().any(|p| p.is_null())
105
+ {
106
+ return Err("invalid destination rows".into());
107
+ }
108
+ if reader.info().interlaced && allow_truncated {
109
+ // Only complete pass rows are committed. Other pixels retain their contents.
110
+ let mut scratch = vec![0; stride];
111
+ for (x0, y0, dx, dy) in [
112
+ (0, 0, 8, 8),
113
+ (4, 0, 8, 8),
114
+ (0, 4, 4, 8),
115
+ (2, 0, 4, 4),
116
+ (0, 2, 2, 4),
117
+ (1, 0, 2, 2),
118
+ (0, 1, 1, 2),
119
+ ] {
120
+ if width <= x0 {
121
+ continue;
122
+ }
123
+ let count = (width - x0).div_ceil(dx);
124
+ for y in (y0..rows.len()).step_by(dy) {
125
+ let Some(pass) = image_row(reader.next_interlaced_row(), true)? else {
126
+ return Ok(());
127
+ };
128
+ let raw = pass.data();
129
+ scratch[..raw.len()].copy_from_slice(raw);
130
+ unpack(&mut scratch[..count * pixel_bytes], count, color, depth);
131
+ let row = unsafe { slice::from_raw_parts_mut(rows[y], stride) };
132
+ for (x, pixel) in (x0..width)
133
+ .step_by(dx)
134
+ .zip(scratch.chunks_exact(pixel_bytes))
135
+ {
136
+ row[x * pixel_bytes..(x + 1) * pixel_bytes].copy_from_slice(pixel);
137
+ }
138
+ }
139
+ }
140
+ } else if reader.info().interlaced {
141
+ let size = reader.output_buffer_size().ok_or("PNG frame too large")?;
142
+ let mut frame = Vec::new();
143
+ frame.try_reserve_exact(size)?;
144
+ frame.resize(size, 0);
145
+ let info = reader.next_frame(&mut frame)?;
146
+ if info.width as usize != width || info.height as usize != rows.len() {
147
+ return Err("unexpected PNG subframe".into());
148
+ }
149
+ // png 0.18.1 expands Adam7 passes with the canvas stride, even for subframes.
150
+ let source_stride = reader
151
+ .output_line_size(reader.info().width)
152
+ .ok_or("PNG row too large")?;
153
+ for (&ptr, raw) in rows.iter().zip(frame.chunks_exact(source_stride)) {
154
+ let row = unsafe { slice::from_raw_parts_mut(ptr, stride) };
155
+ row[..info.line_size].copy_from_slice(&raw[..info.line_size]);
156
+ unpack(row, width, color, depth);
157
+ }
158
+ } else if color == ColorType::Rgb {
159
+ // RGB transparency stays in Pillow metadata. Only expand the pixel layout.
160
+ for &ptr in rows {
161
+ let Some(raw) = image_row(reader.next_row(), allow_truncated)? else {
162
+ return Ok(());
163
+ };
164
+ let row = unsafe { slice::from_raw_parts_mut(ptr, stride) };
165
+ for (rgb, pixel) in raw
166
+ .data()
167
+ .as_chunks::<3>()
168
+ .0
169
+ .iter()
170
+ .zip(row.as_chunks_mut::<4>().0)
171
+ {
172
+ *pixel = [rgb[0], rgb[1], rgb[2], 255];
173
+ }
174
+ }
175
+ } else {
176
+ for &ptr in rows {
177
+ let row = unsafe { slice::from_raw_parts_mut(ptr, stride) };
178
+ if image_row(reader.read_row(row), allow_truncated)?.is_none() {
179
+ return Ok(());
180
+ }
181
+ unpack(row, width, color, depth);
182
+ }
183
+ }
184
+ if let Err(error) = reader.read_row(&mut [])
185
+ && !allow_truncated
186
+ {
187
+ return Err(error.into());
188
+ }
189
+ Ok(())
190
+ }
191
+
192
+ // Private wheel ABI. The plugin pins input and destination while this call runs.
193
+ #[unsafe(no_mangle)]
194
+ unsafe extern "C" fn lastpng_decode_pillow_rows(
195
+ data: *const u8,
196
+ len: usize,
197
+ rows: *const *mut u8,
198
+ width: u32,
199
+ height: u32,
200
+ stride: usize,
201
+ allow_truncated: u8,
202
+ error: &mut [u8; 256],
203
+ ) -> i32 {
204
+ ffi_result(error, || unsafe {
205
+ pillow_rows(
206
+ &mut png_reader(
207
+ Cursor::new(slice::from_raw_parts(data, len)),
208
+ allow_truncated != 0,
209
+ png::Limits::default(),
210
+ )?,
211
+ slice::from_raw_parts(rows, height as usize),
212
+ width,
213
+ stride,
214
+ allow_truncated != 0,
215
+ )
216
+ })
217
+ .map_or(-1, |()| 0)
218
+ }
219
+
220
+ type StreamIo = unsafe extern "C" fn(i64, i32, *mut u8, usize) -> i64;
221
+
222
+ struct PythonStream {
223
+ io: StreamIo,
224
+ position: u64,
225
+ }
226
+
227
+ impl Read for PythonStream {
228
+ fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
229
+ let offset = i64::try_from(self.position).map_err(io::Error::other)?;
230
+ let count = unsafe { (self.io)(offset, 0, buffer.as_mut_ptr(), buffer.len()) };
231
+ if count < 0 {
232
+ return Err(io::Error::other("Python PNG stream read failed"));
233
+ }
234
+ let count = count as usize;
235
+ if count > buffer.len() {
236
+ return Err(io::Error::other("invalid Python PNG stream read length"));
237
+ }
238
+ self.position += count as u64;
239
+ Ok(count)
240
+ }
241
+ }
242
+
243
+ impl Seek for PythonStream {
244
+ fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
245
+ self.position = match from {
246
+ SeekFrom::Start(position) => position,
247
+ SeekFrom::Current(offset) => self
248
+ .position
249
+ .checked_add_signed(offset)
250
+ .ok_or_else(|| io::Error::other("invalid PNG stream position"))?,
251
+ SeekFrom::End(offset) => {
252
+ let position = unsafe { (self.io)(offset, 2, std::ptr::null_mut(), 0) };
253
+ u64::try_from(position)
254
+ .map_err(|_| io::Error::other("Python PNG stream seek failed"))?
255
+ }
256
+ };
257
+ Ok(self.position)
258
+ }
259
+ }
260
+
261
+ struct APngDecoder {
262
+ reader: png::Reader<BufReader<PythonStream>>,
263
+ frame: u32,
264
+ allow_truncated: bool,
265
+ }
266
+
267
+ // The plugin keeps the callback and its Python file alive until the Reader is freed.
268
+ #[unsafe(no_mangle)]
269
+ unsafe extern "C" fn lastpng_apng_new(
270
+ stream_io: StreamIo,
271
+ frame: u32,
272
+ allow_truncated: u8,
273
+ error: &mut [u8; 256],
274
+ ) -> *mut APngDecoder {
275
+ ffi_result(error, || {
276
+ // png 0.18.1 debits its budget cumulatively for each animation frame.
277
+ // Pillow controls the destination allocation; do not cap animation length.
278
+ let mut reader = png_reader(
279
+ BufReader::with_capacity(
280
+ 8192,
281
+ PythonStream {
282
+ io: stream_io,
283
+ position: 0,
284
+ },
285
+ ),
286
+ allow_truncated != 0,
287
+ png::Limits { bytes: usize::MAX },
288
+ )?;
289
+ for _ in 0..frame {
290
+ reader.next_frame_info()?;
291
+ }
292
+ Ok(Box::into_raw(Box::new(APngDecoder {
293
+ reader,
294
+ frame,
295
+ allow_truncated: allow_truncated != 0,
296
+ })))
297
+ })
298
+ .unwrap_or(std::ptr::null_mut())
299
+ }
300
+
301
+ #[unsafe(no_mangle)]
302
+ unsafe extern "C" fn lastpng_apng_free(decoder: *mut APngDecoder) {
303
+ drop(unsafe { Box::from_raw(decoder) });
304
+ }
305
+
306
+ // The handle and destination remain exclusively borrowed throughout this call.
307
+ #[unsafe(no_mangle)]
308
+ unsafe extern "C" fn lastpng_apng_pillow_rows(
309
+ decoder: &mut APngDecoder,
310
+ frame: u32,
311
+ rows: *const *mut u8,
312
+ width: u32,
313
+ height: u32,
314
+ stride: usize,
315
+ error: &mut [u8; 256],
316
+ ) -> i32 {
317
+ ffi_result(error, || unsafe {
318
+ if frame < decoder.frame {
319
+ return Err("APNG reader must be recreated before rewinding".into());
320
+ }
321
+ while decoder.frame < frame {
322
+ decoder.reader.next_frame_info()?;
323
+ decoder.frame += 1;
324
+ }
325
+ pillow_rows(
326
+ &mut decoder.reader,
327
+ slice::from_raw_parts(rows, height as usize),
328
+ width,
329
+ stride,
330
+ decoder.allow_truncated,
331
+ )
332
+ })
333
+ .map_or(-1, |()| 0)
334
+ }
335
+
336
+ fn ffi_result<T>(
337
+ error: &mut [u8; 256],
338
+ operation: impl FnOnce() -> Result<T, Box<dyn Error>>,
339
+ ) -> Option<T> {
340
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(operation));
341
+ let message = match result {
342
+ Ok(Ok(value)) => return Some(value),
343
+ Ok(Err(e)) => e.to_string(),
344
+ Err(_) => "internal PNG decoder panic".into(),
345
+ };
346
+ let n = message.len().min(error.len() - 1);
347
+ error[..n].copy_from_slice(&message.as_bytes()[..n]);
348
+ error[n] = 0;
349
+ None
350
+ }
351
+
352
+ #[cfg(test)]
353
+ mod tests {
354
+ use super::*;
355
+
356
+ #[test]
357
+ fn low_depth_rows_preserve_indices_and_scale_gray_at_byte_boundaries() {
358
+ for depth in [BitDepth::One, BitDepth::Two, BitDepth::Four] {
359
+ let bits = depth as usize;
360
+ let mask = (1u8 << bits) - 1;
361
+ for color in [ColorType::Indexed, ColorType::Grayscale] {
362
+ let scale = if color == ColorType::Indexed {
363
+ 1
364
+ } else {
365
+ 255 / mask
366
+ };
367
+ for width in 1usize..=33 {
368
+ for byte in 0..=255u8 {
369
+ let mut row = vec![byte; width];
370
+ unpack(&mut row, width, color, depth);
371
+ for (x, &sample) in row.iter().enumerate() {
372
+ let shift = 8 - bits - x * bits % 8;
373
+ assert_eq!(sample, ((byte >> shift) & mask) * scale);
374
+ }
375
+ }
376
+ }
377
+ }
378
+ }
379
+ }
380
+ }