Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

feat(codecs): decode legacy PCX images and palettes (#3692) (#3701)

Nigel Ihza Firdausye54adc250c5c
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index 0b1a366a6..f6695717b 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -21,8 +21,8 @@ mod recovery_tests;
/// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts.
const OPEN_EXTS: &[&str] = &[
"pcraft", "pdn", "ora", "kra", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm",
- "pgm", "ppm", "pam", "pfm", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr",
- "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
+ "pgm", "ppm", "pam", "pfm", "pcx", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf",
+ "abr", "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
diff --git a/crates/codecs/src/codecs/mod.rs b/crates/codecs/src/codecs/mod.rs
index ea70ccc2b..22845d930 100644
--- a/crates/codecs/src/codecs/mod.rs
+++ b/crates/codecs/src/codecs/mod.rs
@@ -5,6 +5,7 @@ pub(crate) mod fits;
pub(crate) mod gif_frames;
pub(crate) mod heif;
pub(crate) mod jpeg;
+pub(crate) mod pcx;
pub(crate) mod png;
pub(crate) mod pnm;
pub(crate) mod tiff;
diff --git a/crates/codecs/src/codecs/pcx.rs b/crates/codecs/src/codecs/pcx.rs
new file mode 100644
index 000000000..43a3e9730
--- /dev/null
+++ b/crates/codecs/src/codecs/pcx.rs
@@ -0,0 +1,118 @@
+//! ZSoft PCX (Paintbrush) reader: strictly bounded scanline RLE, 16/256-colour
+//! palettes and 8-bit three-plane RGB. Read-only: modern saves should use PNG.
+
+use crate::SampleType;
+use crate::error::CodecError;
+use crate::format::Format;
+use crate::image::{ChannelLayout, Image};
+use crate::options::Limits;
+
+const HEADER: usize = 128;
+
+fn bad(reason: impl std::fmt::Display) -> CodecError {
+ CodecError::malformed(Format::Pcx, reason)
+}
+fn le16(b: &[u8], i: usize) -> u16 {
+ u16::from_le_bytes([b[i], b[i + 1]])
+}
+
+/// PCX lacks a strong magic number. Require plausible complete header fields before
+/// identifying it, rather than classifying every file starting with 0x0a as PCX.
+pub(crate) fn looks_like_pcx(b: &[u8]) -> bool {
+ if b.len() < HEADER || b[0] != 0x0a || !matches!(b[1], 0 | 2 | 3 | 5) || b[2] != 1 {
+ return false;
+ }
+ let bits = b[3];
+ let planes = b[65];
+ let stride = u32::from(le16(b, 66));
+ let (x0, y0, x1, y1) = (le16(b, 4), le16(b, 6), le16(b, 8), le16(b, 10));
+ if x1 < x0 || y1 < y0 || !matches!(bits, 1 | 2 | 4 | 8) || !(1..=4).contains(&planes) {
+ return false;
+ }
+ let width = u32::from(x1 - x0) + 1;
+ let min_stride = (width * u32::from(bits)).div_ceil(8);
+ stride >= min_stride && stride > 0 && (bits != 8 || matches!(planes, 1 | 3)) && (bits == 8 || u32::from(bits) * u32::from(planes) <= 4)
+}
+
+/// Read one compressed plane's row. RLE packets never cross a scanline.
+fn read_row(b: &[u8], pos: &mut usize, out: &mut [u8]) -> Result<(), CodecError> {
+ let mut n = 0;
+ while n < out.len() {
+ let code = *b.get(*pos).ok_or_else(|| bad("truncated pixel RLE"))?;
+ *pos += 1;
+ let (count, value) = if code >= 0xc0 {
+ let count = usize::from(code & 0x3f);
+ let value = *b.get(*pos).ok_or_else(|| bad("truncated RLE packet"))?;
+ *pos += 1;
+ (count, value)
+ } else {
+ (1, code)
+ };
+ if count == 0 || count > out.len() - n {
+ return Err(bad("RLE packet crosses a scanline or has zero length"));
+ }
+ out[n..n + count].fill(value);
+ n += count;
+ }
+ Ok(())
+}
+
+pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result<Image, CodecError> {
+ if !looks_like_pcx(b) {
+ return Err(bad("invalid PCX header or unsupported pixel layout"));
+ }
+ let (w, h) = (u32::from(le16(b, 8) - le16(b, 4)) + 1, u32::from(le16(b, 10) - le16(b, 6)) + 1);
+ limits.check(w, h, ChannelLayout::Rgb, SampleType::U8)?;
+ let (bits, planes, stride) = (usize::from(b[3]), usize::from(b[65]), usize::from(le16(b, 66)));
+ let row_len = stride.checked_mul(planes).ok_or_else(|| bad("row size overflow"))?;
+ let total = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(3)).ok_or_else(|| bad("pixel size overflow"))?;
+ // The last 769 bytes are the optional VGA palette for 8-bit indexed images.
+ let vga = bits == 8 && planes == 1 && b.len() >= HEADER + 769 && b[b.len() - 769] == 0x0c;
+ if bits == 8 && planes == 1 && !vga && le16(b, 68) != 2 {
+ return Err(bad("8-bit indexed PCX has no 256-colour palette"));
+ }
+ let image_end = if vga { b.len() - 769 } else { b.len() };
+ let mut row = vec![0u8; row_len];
+ let mut pixels = vec![0u8; total];
+ let mut p = HEADER;
+ let width = w as usize;
+ for y in 0..h as usize {
+ for plane in row.chunks_mut(stride) {
+ read_row(&b[..image_end], &mut p, plane)?;
+ }
+ for x in 0..width {
+ let rgb = if bits == 8 && planes == 3 {
+ [row[x], row[stride + x], row[2 * stride + x]]
+ } else {
+ let index = if bits == 8 {
+ usize::from(row[x])
+ } else {
+ let bit = x * bits;
+ let shift = 8 - bits - (bit % 8);
+ let mask = (1usize << bits) - 1;
+ (0..planes).fold(0usize, |v, plane| {
+ let sample = (usize::from(row[plane * stride + bit / 8]) >> shift) & mask;
+ v | sample << (plane * bits)
+ })
+ };
+ if vga {
+ let o = image_end + 1 + index * 3;
+ [b[o], b[o + 1], b[o + 2]]
+ } else if bits == 8 {
+ let g = index as u8;
+ [g, g, g] // palette-info 2: gray scale
+ } else {
+ let o = 16 + index * 3;
+ [b[o], b[o + 1], b[o + 2]]
+ }
+ };
+ pixels[(y * width + x) * 3..(y * width + x + 1) * 3].copy_from_slice(&rgb);
+ }
+ }
+ let mut image = Image::from_u8(w, h, ChannelLayout::Rgb, pixels)?;
+ let (xdpi, ydpi) = (le16(b, 12), le16(b, 14));
+ if xdpi > 0 && ydpi > 0 {
+ image.meta.dpi = Some((f32::from(xdpi), f32::from(ydpi)));
+ }
+ Ok(image)
+}
diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rs
index 3d3fa5426..ddb758714 100644
--- a/crates/codecs/src/format.rs
+++ b/crates/codecs/src/format.rs
@@ -15,6 +15,8 @@ pub enum Format {
Ico,
/// Netpbm family: PBM/PGM/PPM (P1–P6), PAM (P7) and PFM (`PF`/`Pf`).
Pnm,
+ /// ZSoft Paintbrush: 1/2/4-bit planar palettes, 8-bit indexed and 24-bit RGB.
+ Pcx,
Qoi,
OpenExr,
/// Radiance RGBE.
@@ -56,6 +58,10 @@ pub struct FormatCaps {
/// Formats that are enabled but intentionally not symmetric, with the reason.
/// The test-suite asserts that every other enabled format is read+write.
pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[
+ (
+ Format::Pcx,
+ "PCX is supported for opening legacy paint and clipart assets. New files should use PNG; writing obsolete indexed and planar variants is intentionally not provided.",
+ ),
(
Format::Avif,
"AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \
@@ -78,7 +84,7 @@ const ALL_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::C
impl Format {
/// Every format known to the crate (enabled or not).
- pub const ALL: [Format; 15] = [
+ pub const ALL: [Format; 16] = [
Format::Png,
Format::Jpeg,
Format::Tiff,
@@ -88,6 +94,7 @@ impl Format {
Format::Tga,
Format::Ico,
Format::Pnm,
+ Format::Pcx,
Format::Qoi,
Format::OpenExr,
Format::Hdr,
@@ -117,6 +124,7 @@ impl Format {
Format::Tga => "TGA",
Format::Ico => "ICO",
Format::Pnm => "Netpbm",
+ Format::Pcx => "PCX",
Format::Qoi => "QOI",
Format::OpenExr => "OpenEXR",
Format::Hdr => "Radiance HDR",
@@ -139,6 +147,7 @@ impl Format {
Format::Tga => &["tga", "icb", "vda", "vst"],
Format::Ico => &["ico"],
Format::Pnm => &["pnm", "pbm", "pgm", "ppm", "pam", "pfm"],
+ Format::Pcx => &["pcx"],
Format::Qoi => &["qoi"],
Format::OpenExr => &["exr"],
Format::Hdr => &["hdr"],
@@ -159,6 +168,7 @@ impl Format {
Format::Tga => "image/x-tga",
Format::Ico => "image/x-icon",
Format::Pnm => "image/x-portable-anymap",
+ Format::Pcx => "image/x-pcx",
Format::Qoi => "image/qoi",
Format::OpenExr => "image/x-exr",
Format::Hdr => "image/vnd.radiance",
@@ -207,6 +217,7 @@ pub fn caps(format: Format) -> FormatCaps {
Format::Tga => FormatCaps { layouts: RGB_GRAY, ..base },
Format::Ico => FormatCaps { layouts: &[L::Rgba], ..base },
Format::Pnm => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, ..base },
+ Format::Pcx => FormatCaps { read: true, write: false, layouts: &[L::Rgb], alpha: false, ..base },
Format::Qoi => base,
Format::OpenExr => FormatCaps { depths: &[S::F16, S::F32], layouts: RGB_GRAY, ..base },
Format::Hdr => FormatCaps { depths: &[S::F32], layouts: &[L::Rgb], alpha: false, lossy: true, ..base },
@@ -266,6 +277,9 @@ pub fn detect(bytes: &[u8]) -> Option<Format> {
if b.starts_with(b"SIMPLE =") {
return Some(Format::Fits);
}
+ if crate::codecs::pcx::looks_like_pcx(b) {
+ return Some(Format::Pcx);
+ }
if looks_like_tga(b) {
return Some(Format::Tga);
}
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 424ec0b8a..8278ac0d6 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -43,7 +43,7 @@ pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_
pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding};
pub use half::f16;
-use crate::codecs::{exr, fits, heif, jpeg, png, pnm, tiff, via_image, webp};
+use crate::codecs::{exr, fits, heif, jpeg, pcx, png, pnm, tiff, via_image, webp};
/// Detect the format and decode with default [`Limits`].
pub fn decode(bytes: &[u8]) -> Result<Image, CodecError> {
@@ -74,6 +74,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res
Format::Tiff => tiff::decode(bytes, l),
Format::WebP => webp::decode(bytes, l),
Format::Pnm => pnm::decode(bytes, l),
+ Format::Pcx => pcx::decode(bytes, l),
Format::Fits => fits::decode(bytes, l),
Format::OpenExr => exr::decode(bytes, l),
Format::Heif => heif::decode(bytes, l, opts.keep_orientation),
@@ -216,6 +217,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result<Vec
Format::Tiff => tiff::encode(image, plan, opts),
Format::WebP => webp::encode(image, plan, opts),
Format::Pnm => pnm::encode(image, plan, opts),
+ Format::Pcx => Err(CodecError::unsupported(format, "PCX is import-only; save as PNG instead")),
Format::Fits => fits::encode(image, plan, opts),
Format::OpenExr => exr::encode(image, plan, opts),
Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")),
diff --git a/crates/codecs/tests/pcx.rs b/crates/codecs/tests/pcx.rs
new file mode 100644
index 000000000..89661cb8e
--- /dev/null
+++ b/crates/codecs/tests/pcx.rs
@@ -0,0 +1,100 @@
+use photocraft_codecs::{ChannelLayout, CodecError, Format, SampleType, caps, decode, decode_as, detect, encode, from_extension};
+
+fn header(bits: u8, planes: u8, width: u16, height: u16, stride: u16) -> Vec<u8> {
+ let mut b = vec![0u8; 128];
+ b[0] = 0x0a; // ZSoft
+ b[1] = 5; // PC Paintbrush 3.0+
+ b[2] = 1; // RLE
+ b[3] = bits;
+ b[8..10].copy_from_slice(&(width - 1).to_le_bytes());
+ b[10..12].copy_from_slice(&(height - 1).to_le_bytes());
+ b[12..14].copy_from_slice(&300u16.to_le_bytes());
+ b[14..16].copy_from_slice(&150u16.to_le_bytes());
+ b[65] = planes;
+ b[66..68].copy_from_slice(&stride.to_le_bytes());
+ b[68..70].copy_from_slice(&1u16.to_le_bytes());
+ b
+}
+
+fn rle_row(out: &mut Vec<u8>, row: &[u8]) {
+ for &value in row {
+ if value >= 0xc0 {
+ out.extend_from_slice(&[0xc1, value]);
+ } else {
+ out.push(value);
+ }
+ }
+}
+
+#[test]
+fn pcx_is_readable_but_not_writable() {
+ assert_eq!(from_extension("archive.PCX"), Some(Format::Pcx));
+ assert!(caps(Format::Pcx).read && !caps(Format::Pcx).write);
+ let img = photocraft_codecs::Image::from_u8(1, 1, ChannelLayout::Rgb, vec![0, 0, 0]).unwrap();
+ assert!(matches!(encode(&img, Format::Pcx, &Default::default()), Err(CodecError::Unsupported { .. })));
+}
+
+#[test]
+fn decodes_three_plane_rgb_and_keeps_dpi() {
+ let mut b = header(8, 3, 2, 1, 2);
+ for row in [&[255, 0][..], &[0, 255][..], &[0, 0][..]] {
+ rle_row(&mut b, row);
+ }
+ assert_eq!(detect(&b), Some(Format::Pcx));
+ let im = decode(&b).unwrap();
+ assert_eq!(im.layout(), ChannelLayout::Rgb);
+ assert_eq!(im.sample_type(), SampleType::U8);
+ assert_eq!(im.dimensions(), (2, 1));
+ assert_eq!(im.data(), &[255, 0, 0, 0, 255, 0]);
+ assert_eq!(im.meta.dpi, Some((300.0, 150.0)));
+}
+
+#[test]
+fn decodes_256_colour_vga_palette() {
+ let mut b = header(8, 1, 2, 1, 2);
+ rle_row(&mut b, &[1, 2]);
+ b.push(0x0c);
+ let mut palette = vec![0; 256 * 3];
+ palette[3..6].copy_from_slice(&[255, 0, 0]);
+ palette[6..9].copy_from_slice(&[0, 255, 0]);
+ b.extend(palette);
+ assert_eq!(decode(&b).unwrap().data(), &[255, 0, 0, 0, 255, 0]);
+}
+
+#[test]
+fn decodes_4bit_and_monochrome_palettes() {
+ let mut four = header(4, 1, 2, 1, 2);
+ four[16 + 3..16 + 6].copy_from_slice(&[255, 0, 0]);
+ four[16 + 6..16 + 9].copy_from_slice(&[0, 0, 255]);
+ rle_row(&mut four, &[0x12, 0]);
+ assert_eq!(decode(&four).unwrap().data(), &[255, 0, 0, 0, 0, 255]);
+
+ let mut one = header(1, 1, 2, 1, 2);
+ one[16 + 3..16 + 6].copy_from_slice(&[255, 0, 0]);
+ rle_row(&mut one, &[0x80, 0]);
+ assert_eq!(decode(&one).unwrap().data(), &[255, 0, 0, 0, 0, 0]);
+}
+
+#[test]
+fn rejects_truncated_and_overshooting_rle_without_panicking() {
+ let mut b = header(8, 3, 2, 1, 2);
+ assert!(decode_as(Format::Pcx, &b).is_err(), "header alone is truncated");
+ b.extend([0xc5, 0xff]); // a five-pixel run cannot cross a two-byte row
+ assert!(decode_as(Format::Pcx, &b).is_err());
+ let mut b = header(8, 3, 2, 1, 2);
+ b.extend([0xc1]); // missing run value
+ assert!(decode_as(Format::Pcx, &b).is_err());
+ let mut b = header(8, 3, 2, 1, 2);
+ b[66..68].copy_from_slice(&0u16.to_le_bytes());
+ assert_eq!(detect(&b), None, "invalid stride is not a PCX signature");
+}
+
+#[test]
+fn refuses_headers_that_exceed_allocation_budget() {
+ let mut b = header(8, 3, 3000, 3000, 3000);
+ // The default decoder rejects the allocation before reading any scanline.
+ let opts = photocraft_codecs::DecodeOptions { limits: photocraft_codecs::Limits { max_alloc: 1024, ..Default::default() }, ..Default::default() };
+ assert!(matches!(photocraft_codecs::decode_as_with(Format::Pcx, &b, &opts), Err(CodecError::LimitExceeded(_))));
+ b[2] = 0;
+ assert_eq!(detect(&b), None, "unsupported uncompressed encoding");
+}