Delegate Krita parsing and tile decoding

This commit is contained in:
Dylan M. Taylor committed 2026-11-13 01:33:49 -05:00
1 parent 5bdfb5914a
commit ad5d4d84ad
5 files changed
+144 -497

No files matched your search

+139 -178
View File
@@ -1,86 +1,55 @@
//! Krita (`.kra`, `.krz`) import. Layout observed from files Krita writes (no Krita code used):
//! a ZIP whose first, stored entry is `mimetype` = `application/x-krita`, a `maindoc.xml` node
//! tree, one tiled pixel file per paint layer and mask under `<image name>/layers/`, the
//! image's ICC profile in `<image name>/annotations/icc`, and Krita's rendering in
//! `mergedimage.png`.
//!
//! Tiled pixel files are a short text header (`VERSION 2`, `TILEWIDTH`, `TILEHEIGHT`,
//! `PIXELSIZE`, `DATA <tiles>`) followed by, per tile, a `x,y,LZF,<bytes>` line and that many
//! bytes: a flag (1 = LZF-compressed, 0 = raw) and the tile's pixels stored as byte planes
//! (every pixel's first byte, then every pixel's second byte, ...). RGB pixels are in
//! Krita's BGRA order, 16-bit samples little-endian.
//!
//! Imported: paint layers (8 and 16-bit RGBA and gray), groups (isolated and pass-through),
//! names, visibility, opacity, blend modes, locks, layer offsets and transparency masks.
//! Every other node kind (vector, filter, fill, file and clone layers, filter, transform and
//! colorize masks) is left out with a warning; Krita's merged image still shows their look.
//! Documents in a colour space we don't read open as Krita's merged image, flagged as a preview.
//! Krita import. `craft-kra` owns the archive, XML and tile formats; this module maps its
//! neutral document representation into PhotoCraft's layer model.
#[cfg(test)]
mod tests;
mod tiles;
use photocraft_color::{BlendMode, PixelFormat};
use std::collections::HashSet;
use craft_kra::tiles::{Space, TileFile};
use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};
use photocraft_doc::{Document, Layer, LayerContent, LayerMask};
use photocraft_format::zip::ZipReader;
use photocraft_geom::Size;
use photocraft_geom::{Size, TILE_SIZE};
use photocraft_raster::{Interrupt, Surface};
use crate::ora::{MAX_NODES, MAX_PIXEL_BYTES, MAX_SIDE, Warnings, krita_blend};
use crate::ora::{MAX_NODES, MAX_PIXEL_BYTES, Warnings, krita_blend};
use crate::{ImportResult, IoError};
use tiles::{Space, TileFile};
type Result<T> = std::result::Result<T, IoError>;
/// The `mimetype` entry of a Krita archive.
pub(crate) const MIMETYPE: &[u8] = b"application/x-krita";
#[cfg(test)]
const MIMETYPE: &[u8] = craft_kra::MIMETYPE;
pub(crate) const EXTENSIONS: [&str; 2] = craft_kra::EXTENSIONS;
const MAX_MAINDOC: usize = 32 << 20;
const MAX_LAYER_FILE: usize = 1 << 30;
fn invalid(message: impl Into<String>) -> IoError {
IoError::Kra(message.into())
}
fn map_error(error: craft_kra::Error) -> IoError {
match error {
craft_kra::Error::Invalid(message) => invalid(message),
craft_kra::Error::Unsupported(message) => IoError::Unsupported(message),
}
}
/// `true` for a Krita archive (by its `mimetype` entry).
pub(crate) fn is_kra(bytes: &[u8]) -> bool {
craft_kra::is_kra(bytes)
}
fn attr<'a>(node: roxmltree::Node<'a, '_>, name: &str) -> Option<&'a str> {
node.attribute(name).map(str::trim)
}
fn number(node: roxmltree::Node<'_, '_>, name: &str, default: f64) -> Result<f64> {
match attr(node, name) {
None | Some("") => Ok(default),
Some(v) => v.parse::<f64>().ok().filter(|v| v.is_finite()).ok_or_else(|| invalid(format!("invalid {name} attribute `{v}`"))),
fn model(space: Space) -> (ColorMode, SampleType) {
match space {
Space::Rgba8 => (ColorMode::Rgb, SampleType::U8),
Space::Rgba16 => (ColorMode::Rgb, SampleType::U16),
Space::Gray8 | Space::Alpha8 => (ColorMode::Grayscale, SampleType::U8),
Space::Gray16 => (ColorMode::Grayscale, SampleType::U16),
}
}
fn offset(node: roxmltree::Node<'_, '_>, name: &str) -> Result<i32> {
let v = number(node, name, 0.0)?.round();
if v.abs() > f64::from(MAX_SIDE) * 4.0 {
return Err(invalid(format!("{name} offset {v} is out of range")));
}
Ok(v as i32)
}
fn truthy(node: roxmltree::Node<'_, '_>, name: &str) -> bool {
matches!(attr(node, name), Some("1" | "true"))
}
/// Child elements named `tag` inside the node's `<container>` element (`layers` or `masks`).
fn children<'a, 'i>(node: roxmltree::Node<'a, 'i>, container: &str, tag: &'static str) -> impl Iterator<Item = roxmltree::Node<'a, 'i>> {
node.children().filter(move |c| c.has_tag_name(container)).flat_map(move |c| c.children().filter(move |n| n.has_tag_name(tag)))
}
struct Reader<'a, 'c> {
zip: ZipReader<'a>,
archive: craft_kra::Archive<'a>,
ctl: &'c Interrupt<'c>,
/// `<image name>/layers/`.
dir: String,
/// The document's pixel format (layers in another supported space are converted to it).
fmt: PixelFormat,
nodes: usize,
budget: usize,
@@ -88,49 +57,87 @@ struct Reader<'a, 'c> {
}
impl Reader<'_, '_> {
fn file(&self, name: &str) -> Result<Option<Vec<u8>>> {
let path = format!("{}{name}", self.dir);
match self.zip.find(&path) {
None => Ok(None),
Some(e) => self.zip.read(e, MAX_LAYER_FILE).map(Some).map_err(|err| invalid(format!("{path}: {err}"))),
/// Reserve for decoded pixels and the raster backing tiles they occupy.
fn decoded_bytes(file: &TileFile<'_>, bpp: usize, dx: i32, dy: i32) -> Result<usize> {
let overflow = || invalid("tile size overflow");
let logical =
file.tiles().len().checked_mul(file.width).and_then(|n| n.checked_mul(file.height)).and_then(|n| n.checked_mul(bpp)).ok_or_else(overflow)?;
let (w, h) = (i32::try_from(file.width).map_err(|_| overflow())?, i32::try_from(file.height).map_err(|_| overflow())?);
let mut backing = HashSet::new();
let side = TILE_SIZE;
for tile in file.tiles() {
let (x, y) = (tile.x.checked_add(dx).ok_or_else(overflow)?, tile.y.checked_add(dy).ok_or_else(overflow)?);
let (x1, y1) = (x.checked_add(w - 1).ok_or_else(overflow)?, y.checked_add(h - 1).ok_or_else(overflow)?);
for col in x.div_euclid(side)..=x1.div_euclid(side) {
for row in y.div_euclid(side)..=y1.div_euclid(side) {
backing.insert((col, row));
}
}
}
let tile_bytes = (side as usize).checked_mul(side as usize).and_then(|n| n.checked_mul(bpp)).ok_or_else(overflow)?;
Ok(logical.max(backing.len().checked_mul(tile_bytes).ok_or_else(overflow)?))
}
/// The default pixel Krita stores next to a tiled file, decoded to `space` samples.
fn default_pixel(&self, name: &str, space: Space) -> Result<Option<Vec<f32>>> {
let Some(bytes) = self.file(&format!("{name}.defaultpixel"))? else { return Ok(None) };
if bytes.len() != space.pixel_size() {
return Err(invalid(format!("{name}.defaultpixel has {} bytes, expected {}", bytes.len(), space.pixel_size())));
}
Ok(Some(space.normalised(&bytes)))
}
/// A tiled pixel file in `space` as a surface in `fmt`, offset by (`dx`, `dy`).
fn surface(&mut self, name: &str, space: Space, fmt: PixelFormat, dx: i32, dy: i32) -> Result<Option<Surface>> {
let Some(bytes) = self.file(name)? else { return Ok(None) };
let file = TileFile::parse(&bytes)?;
let Some(bytes) = self.archive.layer_file(name).map_err(map_error)? else { return Ok(None) };
let file = TileFile::parse(&bytes).map_err(map_error)?;
if file.pixel_size != space.pixel_size() {
return Err(invalid(format!("{name}: pixel size {} does not match its colour space", file.pixel_size)));
}
let cost = file.decoded_bytes(fmt.bytes_per_pixel(), dx, dy)?;
self.budget = self.budget.checked_sub(cost).ok_or_else(|| invalid("decoded layers exceed the 1 GiB limit"))?;
let mut surface = match self.default_pixel(name, space)? {
Some(px) if px.iter().any(|v| *v != 0.0) => Surface::with_default(fmt, &space.to_format(&px, fmt)),
self.budget = self
.budget
.checked_sub(Self::decoded_bytes(&file, fmt.bytes_per_pixel(), dx, dy)?)
.ok_or_else(|| invalid("decoded layers exceed the 1 GiB limit"))?;
let mut surface = match self.archive.default_pixel(name, space).map_err(map_error)? {
Some(rgba) if rgba.iter().any(|v| *v != 0.0) => Surface::with_default(fmt, &photocraft_raster::from_rgba(&fmt, rgba)),
_ => Surface::new(fmt),
};
file.decode_into(&mut surface, space, dx, dy, self.ctl)?;
let n = file.width.checked_mul(file.height).ok_or_else(|| invalid("tile size overflow"))?;
let expected = n.checked_mul(file.pixel_size).ok_or_else(|| invalid("tile size overflow"))?;
let mut source = Vec::new();
let mut converted = Vec::new();
let native = PixelFormat::new(model(space).0, model(space).1, true);
for tile in file.tiles() {
self.ctl.check().map_err(|_| IoError::Cancelled)?;
file.decode(tile, &mut source).map_err(map_error)?;
if source.len() != expected {
return Err(invalid("decoded tile has an unexpected size"));
}
if fmt == native {
space.samples(&source, &mut converted);
} else {
converted.clear();
let mut encoded = vec![0; fmt.bytes_per_pixel()];
for px in source.chunks_exact(space.pixel_size()) {
let rgba = space.rgba(px);
let samples = photocraft_raster::from_rgba(&fmt, rgba);
photocraft_raster::encode_pixel(&fmt, &samples, &mut encoded);
converted.extend_from_slice(&encoded);
}
}
let (x, y) = (
tile.x.checked_add(dx).ok_or_else(|| invalid("tile offset overflow"))?,
tile.y.checked_add(dy).ok_or_else(|| invalid("tile offset overflow"))?,
);
let rect = photocraft_geom::Rect::from_xywh(x, y, file.width as u32, file.height as u32);
if converted.len() != n * fmt.bytes_per_pixel() || rect.width() as usize != file.width || rect.height() as usize != file.height {
return Err(invalid("tile does not fit its position"));
}
surface.write_interleaved(rect, &converted);
}
surface.prune();
Ok(Some(surface))
}
fn props(&mut self, node: roxmltree::Node<'_, '_>, layer: &mut Layer) -> Result<()> {
layer.name = attr(node, "name").filter(|n| !n.is_empty()).map_or_else(|| format!("Layer {}", self.nodes), str::to_string);
layer.visible = attr(node, "visible") != Some("0");
layer.opacity = (number(node, "opacity", 255.0)? / 255.0).clamp(0.0, 1.0) as f32;
if truthy(node, "locked") {
fn props(&mut self, node: &craft_kra::Node, layer: &mut Layer) {
layer.name = node.name.as_deref().filter(|n| !n.is_empty()).map_or_else(|| format!("Layer {}", self.nodes), str::to_string);
layer.visible = node.visible;
layer.opacity = (node.opacity / 255.0).clamp(0.0, 1.0) as f32;
if node.locked {
layer.locks.all = true;
}
let op = attr(node, "compositeop").unwrap_or("normal");
let op = node.composite_op.as_deref().unwrap_or("normal");
layer.blend = match krita_blend(op) {
Some((mode, approx)) => {
if approx {
@@ -143,26 +150,22 @@ impl Reader<'_, '_> {
BlendMode::Normal
}
};
if attr(node, "channelflags").is_some_and(|f| f.contains('0')) {
if node.channel_flags.as_deref().is_some_and(|f| f.contains('0')) {
self.warnings.layer(&layer.name, "channel locks (Krita's per-channel blending) are ignored");
}
if truthy(node, "inheritalpha") {
if node.inherit_alpha {
self.warnings.layer(&layer.name, "Inherit Alpha is not supported; these layers blend normally");
}
if attr(node, "keyframes").is_some_and(|k| !k.is_empty()) {
if node.keyframes.as_deref().is_some_and(|k| !k.is_empty()) {
self.warnings.layer(&layer.name, "animated layers open with the frame Krita saved in the layer");
}
Ok(())
}
/// The node's transparency masks, combined into one layer mask.
fn masks(&mut self, node: roxmltree::Node<'_, '_>, layer: &mut Layer, dx: i32, dy: i32) -> Result<()> {
for mask in children(node, "masks", "mask") {
fn masks(&mut self, node: &craft_kra::Node, layer: &mut Layer, dx: i32, dy: i32) -> Result<()> {
for mask in &node.masks {
self.ctl.check().map_err(|_| IoError::Cancelled)?;
let kind = attr(mask, "nodetype").unwrap_or("");
match kind {
match mask.node_type.as_str() {
"transparencymask" => {}
// A layer's local selection: not part of its look.
"selectionmask" => continue,
other => {
let what = match other {
@@ -179,44 +182,40 @@ impl Reader<'_, '_> {
self.warnings.layer(&layer.name, "only the first transparency mask of a layer is kept");
continue;
}
let Some(file) = attr(mask, "filename") else { continue };
let (mx, my) = (dx.saturating_add(offset(mask, "x")?), dy.saturating_add(offset(mask, "y")?));
let Some(file) = mask.filename.as_deref() else { continue };
let (mx, my) = (dx.saturating_add(mask.x), dy.saturating_add(mask.y));
match self.surface(&format!("{file}.pixelselection"), Space::Alpha8, PixelFormat::GRAY8, mx, my)? {
Some(surface) => {
layer.mask = Some(LayerMask { surface, enabled: attr(mask, "visible") != Some("0"), ..LayerMask::reveal_all() });
}
Some(surface) => layer.mask = Some(LayerMask { surface, enabled: mask.visible, ..LayerMask::reveal_all() }),
None => self.warnings.layer(&layer.name, "a transparency mask's pixels are missing from the file"),
}
}
Ok(())
}
/// The `<layers>` of `node`, bottom-to-top (maindoc.xml lists the topmost first).
fn layers(&mut self, node: roxmltree::Node<'_, '_>, depth: usize, dx: i32, dy: i32) -> Result<Vec<Layer>> {
fn layers(&mut self, nodes: &[craft_kra::Node], depth: usize, dx: i32, dy: i32) -> Result<Vec<Layer>> {
if depth > photocraft_doc::MAX_GROUP_DEPTH {
return Err(IoError::Unsupported(format!("layer groups nested deeper than {}", photocraft_doc::MAX_GROUP_DEPTH)));
}
let mut out = Vec::new();
for child in children(node, "layers", "layer") {
for child in nodes {
self.ctl.check().map_err(|_| IoError::Cancelled)?;
self.nodes += 1;
if self.nodes > MAX_NODES {
return Err(invalid(format!("more than {MAX_NODES} layers")));
}
let (x, y) = (dx.saturating_add(offset(child, "x")?), dy.saturating_add(offset(child, "y")?));
let kind = attr(child, "nodetype").unwrap_or("");
let mut layer = match kind {
let (x, y) = (dx.saturating_add(child.x), dy.saturating_add(child.y));
let mut layer = match child.node_type.as_str() {
"paintlayer" => {
let mut layer = Layer::raster("", self.fmt);
self.props(child, &mut layer)?;
let space = attr(child, "colorspacename").and_then(Space::from_name);
match (space, attr(child, "filename")) {
self.props(child, &mut layer);
let space = child.colorspace_name.as_deref().and_then(Space::from_name);
match (space, child.filename.as_deref()) {
(Some(space), Some(file)) => match self.surface(file, space, self.fmt, x, y)? {
Some(s) => layer.content = LayerContent::Raster(s),
Some(surface) => layer.content = LayerContent::Raster(surface),
None => self.warnings.layer(&layer.name, "the layer's pixels are missing from the file; it opens empty"),
},
(None, _) => {
let cs = attr(child, "colorspacename").unwrap_or("?");
let cs = child.colorspace_name.as_deref().unwrap_or("?");
self.warnings.layer(&layer.name, &format!("layers in Krita's {cs} colour space are not supported and were left out"));
continue;
}
@@ -226,24 +225,22 @@ impl Reader<'_, '_> {
}
"grouplayer" => {
let mut layer = Layer::group("", Vec::new());
self.props(child, &mut layer)?;
if truthy(child, "passthrough") {
self.props(child, &mut layer);
if child.passthrough {
if layer.blend != BlendMode::Normal {
self.warnings.layer(&layer.name, "a pass-through group's blend mode is ignored, as in Krita");
}
layer.blend = BlendMode::PassThrough;
}
// A group's own x/y is not applied to its children: Krita moves a group by
// moving their pixels, and its merged image ignores the group offset.
let kids = self.layers(child, depth + 1, dx, dy)?;
if let LayerContent::Group(g) = &mut layer.content {
g.children = kids;
g.expanded = !truthy(child, "collapsed");
let kids = self.layers(&child.layers, depth + 1, dx, dy)?;
if let LayerContent::Group(group) = &mut layer.content {
group.children = kids;
group.expanded = !child.collapsed;
}
layer
}
other => {
let name = attr(child, "name").unwrap_or(other).to_string();
let name = child.name.as_deref().unwrap_or(other);
let what = match other {
"shapelayer" => "vector layers",
"adjustmentlayer" => "filter layers",
@@ -252,7 +249,7 @@ impl Reader<'_, '_> {
"clonelayer" => "clone layers",
_ => "unknown layer kinds",
};
self.warnings.layer(&name, &format!("Krita {what} are not supported yet and were left out"));
self.warnings.layer(name, &format!("Krita {what} are not supported yet and were left out"));
continue;
}
};
@@ -265,77 +262,41 @@ impl Reader<'_, '_> {
}
/// Krita's merged image as a one-layer stand-in, for documents we can't read layer by layer.
fn preview(name: &str, zip: &ZipReader<'_>, why: String) -> Result<ImportResult> {
let png = zip.read_by_name("mergedimage.png", MAX_LAYER_FILE).map_err(|e| invalid(format!("{why}, and the merged image can't be read: {e}")))?;
let mut r = crate::flat::import_flat(name, &png)?;
r.document.name = name.to_string();
r.warnings.insert(0, format!("{why}; the file opens as Krita's merged image, without its layers"));
r.source_read_only = true;
r.preview_only = true;
Ok(r)
fn preview(name: &str, archive: &mut craft_kra::Archive<'_>, why: String) -> Result<ImportResult> {
let png = archive.merged_image().map_err(map_error)?.ok_or_else(|| invalid(format!("{why}, and the merged image is missing")))?;
let mut result = crate::flat::import_flat(name, &png)?;
result.document.name = name.to_string();
result.warnings.insert(0, format!("{why}; the file opens as Krita's merged image, without its layers"));
result.source_read_only = true;
result.preview_only = true;
Ok(result)
}
pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result<ImportResult> {
let zip = ZipReader::new(bytes).map_err(|e| invalid(e.to_string()))?;
let mime = zip.read_by_name("mimetype", 256).map_err(|e| invalid(e.to_string()))?;
if mime.trim_ascii() != MIMETYPE {
return Err(invalid("the archive's mimetype is not application/x-krita"));
}
let xml = zip.read_by_name("maindoc.xml", MAX_MAINDOC).map_err(|e| invalid(e.to_string()))?;
let xml = std::str::from_utf8(&xml).map_err(|_| invalid("maindoc.xml is not UTF-8"))?;
// maindoc.xml declares Krita's DTD by public id; Krita writes no internal subset, which
// `xml::parse` refuses (its entities could hide nesting from the depth check).
let opts = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };
let tree = crate::xml::parse(xml, opts).map_err(|e| invalid(format!("maindoc.xml: {e}")))?;
let image = tree.root_element().children().find(|n| n.has_tag_name("IMAGE")).ok_or_else(|| invalid("maindoc.xml has no IMAGE"))?;
let side = |a: &str| -> Result<u32> {
let v = number(image, a, 0.0)?;
if !(1.0..=f64::from(MAX_SIDE)).contains(&v) || v.fract() != 0.0 {
return Err(invalid(format!("image {a} {v} must be a whole number of pixels from 1 to {MAX_SIDE}")));
}
Ok(v as u32)
let mut archive = craft_kra::Archive::open(bytes).map_err(map_error)?;
let image = archive.image().clone();
let Some(space) = Space::from_name(&image.colorspace_name) else {
return preview(name, &mut archive, format!("Krita's {} colour space is not supported yet", image.colorspace_name));
};
let (w, h) = (side("width")?, side("height")?);
if (w as usize).saturating_mul(h as usize).saturating_mul(8) > MAX_PIXEL_BYTES {
return Err(invalid("the canvas exceeds the 1 GiB pixel limit"));
}
let cs = attr(image, "colorspacename").unwrap_or("");
let Some(space) = Space::from_name(cs) else {
return preview(name, &zip, format!("Krita's {cs} colour space is not supported yet"));
};
let (mode, depth) = space.model();
let image_name = attr(image, "name").unwrap_or("");
let mut reader = Reader {
zip,
ctl,
dir: format!("{image_name}/layers/"),
fmt: PixelFormat::new(mode, depth, true),
nodes: 0,
budget: MAX_PIXEL_BYTES,
warnings: Warnings::default(),
};
let layers = reader.layers(image, 1, 0, 0)?;
let (mode, depth) = model(space);
let mut reader = Reader { archive, ctl, fmt: PixelFormat::new(mode, depth, true), nodes: 0, budget: MAX_PIXEL_BYTES, warnings: Warnings::default() };
let layers = reader.layers(&image.layers, 1, 0, 0)?;
ctl.progress(0.9);
let mut document = Document::new(name, Size::new(w, h), mode, depth);
let mut document = Document::new(name, Size::new(image.width, image.height), mode, depth);
document.layers = layers;
let icc = format!("{image_name}/annotations/icc");
if let Some(e) = reader.zip.find(&icc) {
let profile = reader.zip.read(e, 16 << 20).map_err(|err| invalid(format!("{icc}: {err}")))?;
if !profile.is_empty() {
document.icc_profile = Some(std::sync::Arc::new(profile));
}
if let Some(profile) = reader.archive.icc_profile().map_err(map_error)? {
document.icc_profile = Some(std::sync::Arc::new(profile));
}
let (xres, yres) = (number(image, "x-res", 72.0)?, number(image, "y-res", 72.0)?);
if xres > 0.0 && xres < 1.0e6 {
document.resolution_dpi = xres as f32;
if let Some(w) = crate::unequal_resolution_warning(xres, yres) {
reader.warnings.note(&w);
if image.x_res > 0.0 && image.x_res < 1.0e6 {
document.resolution_dpi = image.x_res as f32;
if let Some(warning) = crate::unequal_resolution_warning(image.x_res, image.y_res) {
reader.warnings.note(&warning);
}
}
if document.layers.is_empty() {
reader.warnings.note("no layers of the Krita document could be imported");
}
if image.children().any(|n| n.has_tag_name("assistants") || n.has_tag_name("ReferenceImages")) {
if image.assistants || image.reference_images {
reader.warnings.note("drawing assistants and reference images were left out");
}
Ok(ImportResult { document, warnings: reader.warnings.finish(), source_read_only: true, preview_only: false })
+1 -1
View File
@@ -1,5 +1,5 @@
use super::tiles::{Space, lzf_decompress};
use super::*;
use craft_kra::tiles::{Space, lzf_decompress};
use photocraft_codecs::{ChannelLayout, Format, Image, SampleType as CSample};
use photocraft_color::{ColorMode, SampleType};
use photocraft_format::zip::ZipWriter;
-308
View File
@@ -1,308 +0,0 @@
//! Krita's tiled pixel files and the LZF compression inside them.
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_geom::Rect;
use photocraft_raster::{Interrupt, Surface};
use super::{Result, invalid};
use crate::IoError;
/// The pixel layouts we read, by Krita colour-space id. Samples are straight (unpremultiplied).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Space {
/// `RGBA`: B, G, R, A bytes.
Rgba8,
/// `RGBA16`: B, G, R, A as little-endian u16.
Rgba16,
/// `GRAYA`: gray, alpha bytes.
Gray8,
/// `GRAYAU16`: gray, alpha as little-endian u16.
Gray16,
/// Masks and selections: one byte.
Alpha8,
}
impl Space {
pub(crate) fn from_name(name: &str) -> Option<Space> {
Some(match name {
"RGBA" => Space::Rgba8,
"RGBA16" => Space::Rgba16,
"GRAYA" => Space::Gray8,
"GRAYAU16" => Space::Gray16,
_ => return None,
})
}
pub(crate) fn pixel_size(self) -> usize {
match self {
Space::Rgba8 => 4,
Space::Rgba16 => 8,
Space::Gray8 => 2,
Space::Gray16 => 4,
Space::Alpha8 => 1,
}
}
/// The document colour mode and depth for an image in this space.
pub(crate) fn model(self) -> (ColorMode, SampleType) {
match self {
Space::Rgba8 => (ColorMode::Rgb, SampleType::U8),
Space::Rgba16 => (ColorMode::Rgb, SampleType::U16),
Space::Gray8 | Space::Alpha8 => (ColorMode::Grayscale, SampleType::U8),
Space::Gray16 => (ColorMode::Grayscale, SampleType::U16),
}
}
/// The surface format whose bytes [`Self::convert`] writes directly.
fn native(self) -> PixelFormat {
match self {
Space::Alpha8 => PixelFormat::GRAY8,
s => {
let (mode, depth) = s.model();
PixelFormat::new(mode, depth, true)
}
}
}
/// One interleaved Krita pixel as straight RGBA (0..1).
fn rgba(self, px: &[u8]) -> [f32; 4] {
let b = |i: usize| f32::from(px.get(i).copied().unwrap_or(0)) / 255.0;
let w = |i: usize| f32::from(u16::from_le_bytes([px.get(i).copied().unwrap_or(0), px.get(i + 1).copied().unwrap_or(0)])) / 65535.0;
match self {
Space::Rgba8 => [b(2), b(1), b(0), b(3)],
Space::Rgba16 => [w(4), w(2), w(0), w(6)],
Space::Gray8 => [b(0), b(0), b(0), b(1)],
Space::Gray16 => [w(0), w(0), w(0), w(2)],
Space::Alpha8 => [b(0), b(0), b(0), 1.0],
}
}
/// A default pixel's samples (Krita order, 0..1), for [`Self::to_format`].
pub(crate) fn normalised(self, px: &[u8]) -> Vec<f32> {
self.rgba(px).to_vec()
}
/// RGBA samples from [`Self::normalised`] as `fmt`'s channels.
pub(crate) fn to_format(self, rgba: &[f32], fmt: PixelFormat) -> Vec<f32> {
let p = [0, 1, 2, 3].map(|i| rgba.get(i).copied().unwrap_or(0.0));
photocraft_raster::from_rgba(&fmt, p)
}
/// Interleaved Krita pixels as encoded `fmt` bytes.
fn convert(self, src: &[u8], fmt: PixelFormat, out: &mut Vec<u8>) {
out.clear();
let ps = self.pixel_size();
if fmt == self.native() {
for px in src.chunks_exact(ps) {
match self {
Space::Rgba8 => out.extend([2, 1, 0, 3].map(|i| px.get(i).copied().unwrap_or(0))),
Space::Rgba16 => {
for i in [4, 2, 0, 6] {
let v = u16::from_le_bytes([px.get(i).copied().unwrap_or(0), px.get(i + 1).copied().unwrap_or(0)]);
out.extend(v.to_ne_bytes());
}
}
Space::Gray16 => {
for i in [0, 2] {
let v = u16::from_le_bytes([px.get(i).copied().unwrap_or(0), px.get(i + 1).copied().unwrap_or(0)]);
out.extend(v.to_ne_bytes());
}
}
Space::Gray8 | Space::Alpha8 => out.extend_from_slice(px),
}
}
return;
}
let mut enc = vec![0; fmt.bytes_per_pixel()];
for px in src.chunks_exact(ps) {
let v = photocraft_raster::from_rgba(&fmt, self.rgba(px));
photocraft_raster::encode_pixel(&fmt, &v, &mut enc);
out.extend_from_slice(&enc);
}
}
}
/// LZF decompression (the liblzf format) into exactly `expected` bytes.
pub(crate) fn lzf_decompress(src: &[u8], expected: usize) -> Result<Vec<u8>> {
let bad = || invalid("corrupt LZF tile data");
let mut out = Vec::with_capacity(expected);
let mut ip = 0;
while ip < src.len() {
let ctrl = usize::from(*src.get(ip).ok_or_else(bad)?);
ip += 1;
if ctrl < 32 {
let len = ctrl + 1;
let lit = src.get(ip..ip + len).ok_or_else(bad)?;
if out.len() + len > expected {
return Err(bad());
}
out.extend_from_slice(lit);
ip += len;
} else {
let mut len = ctrl >> 5;
if len == 7 {
len += usize::from(*src.get(ip).ok_or_else(bad)?);
ip += 1;
}
len += 2;
let back = ((ctrl & 0x1f) << 8) + usize::from(*src.get(ip).ok_or_else(bad)?) + 1;
ip += 1;
let start = out.len().checked_sub(back).ok_or_else(bad)?;
if out.len() + len > expected {
return Err(bad());
}
// Back-references may overlap the bytes they produce, so copy one at a time.
for i in start..start + len {
let b = *out.get(i).ok_or_else(bad)?;
out.push(b);
}
}
}
if out.len() != expected {
return Err(invalid(format!("LZF tile data decodes to {} bytes, expected {expected}", out.len())));
}
Ok(out)
}
/// A parsed tiled pixel file (`VERSION 2`), borrowing the tile payloads.
pub(crate) struct TileFile<'a> {
pub(crate) width: usize,
pub(crate) height: usize,
pub(crate) pixel_size: usize,
tiles: Vec<(i32, i32, &'a [u8])>,
}
fn line<'a>(bytes: &'a [u8], pos: &mut usize) -> Result<&'a str> {
let rest = bytes.get(*pos..).ok_or_else(|| invalid("truncated tile file"))?;
let end = rest.iter().take(256).position(|b| *b == b'\n').ok_or_else(|| invalid("truncated or malformed tile file header"))?;
*pos += end + 1;
std::str::from_utf8(rest.get(..end).unwrap_or_default()).map_err(|_| invalid("tile file header is not text"))
}
fn header_value(bytes: &[u8], pos: &mut usize, key: &str, max: usize) -> Result<usize> {
let l = line(bytes, pos)?;
let v = l.strip_prefix(key).map(str::trim).ok_or_else(|| invalid(format!("tile file: expected {key}, found `{l}`")))?;
v.parse::<usize>().ok().filter(|v| (1..=max).contains(v)).ok_or_else(|| invalid(format!("tile file: invalid {key} `{v}`")))
}
impl<'a> TileFile<'a> {
pub(crate) fn parse(bytes: &'a [u8]) -> Result<TileFile<'a>> {
let mut pos = 0;
let version = line(bytes, &mut pos)?;
if version.trim() != "VERSION 2" {
return Err(IoError::Unsupported(format!("Krita tile file `{}` (only VERSION 2, Krita 2.0 and later)", version.trim())));
}
let width = header_value(bytes, &mut pos, "TILEWIDTH", 1024)?;
let height = header_value(bytes, &mut pos, "TILEHEIGHT", 1024)?;
let pixel_size = header_value(bytes, &mut pos, "PIXELSIZE", 64)?;
let l = line(bytes, &mut pos)?;
let count = l
.strip_prefix("DATA")
.map(str::trim)
.and_then(|v| v.parse::<usize>().ok())
.ok_or_else(|| invalid(format!("tile file: invalid DATA line `{l}`")))?;
// Every tile needs at least a header line and a flag byte.
if count > bytes.len() / 8 + 1 {
return Err(invalid("tile count exceeds the file size"));
}
let mut tiles = Vec::with_capacity(count);
for _ in 0..count {
let l = line(bytes, &mut pos)?;
let mut f = l.split(',');
let (x, y, method, len) = (f.next(), f.next(), f.next(), f.next());
let coord = |v: Option<&str>| v.and_then(|v| v.trim().parse::<i32>().ok()).filter(|v| v.unsigned_abs() <= super::MAX_SIDE * 4);
let (Some(x), Some(y), Some("LZF"), Some(len), None) =
(coord(x), coord(y), method.map(str::trim), len.and_then(|v| v.trim().parse::<usize>().ok()), f.next())
else {
return Err(invalid(format!("tile file: malformed tile header `{l}`")));
};
let data = bytes.get(pos..pos.checked_add(len).ok_or_else(|| invalid("tile size overflow"))?).ok_or_else(|| invalid("truncated tile data"))?;
pos += len;
tiles.push((x, y, data));
}
Ok(TileFile { width, height, pixel_size, tiles })
}
/// Bytes the decoded tiles take at `bpp` bytes per pixel: the larger of their own pixels and
/// the whole 256×256 backing tiles they land in (a surface stores no less than a tile, so
/// sparse tiles at distinct positions retain far more than they hold).
pub(crate) fn decoded_bytes(&self, bpp: usize, dx: i32, dy: i32) -> Result<usize> {
let overflow = || invalid("tile size overflow");
let logical = self.tiles.len().checked_mul(self.width * self.height).and_then(|n| n.checked_mul(bpp)).ok_or_else(overflow)?;
let side = photocraft_geom::TILE_SIZE;
let (w, h) = (i32::try_from(self.width.max(1)).map_err(|_| overflow())?, i32::try_from(self.height.max(1)).map_err(|_| overflow())?);
let mut backing = std::collections::HashSet::new();
for &(x, y, _) in &self.tiles {
// The tile lands at its offset position and covers every backing tile its box overlaps.
let (x, y) = (x.checked_add(dx).ok_or_else(overflow)?, y.checked_add(dy).ok_or_else(overflow)?);
let (x1, y1) = (x.checked_add(w - 1).ok_or_else(overflow)?, y.checked_add(h - 1).ok_or_else(overflow)?);
for c in x.div_euclid(side)..=x1.div_euclid(side) {
for r in y.div_euclid(side)..=y1.div_euclid(side) {
backing.insert((c, r));
}
}
}
let tile_bytes = (side as usize).checked_mul(side as usize).and_then(|n| n.checked_mul(bpp)).ok_or_else(overflow)?;
Ok(logical.max(backing.len().checked_mul(tile_bytes).ok_or_else(overflow)?))
}
/// Writes every tile into `surface` (format `surface.format()`), offset by (`dx`, `dy`).
pub(crate) fn decode_into(&self, surface: &mut Surface, space: Space, dx: i32, dy: i32, ctl: &Interrupt<'_>) -> Result<()> {
let fmt = surface.format();
let n = self.width * self.height;
let expected = n * self.pixel_size;
let mut interleaved = vec![0u8; expected];
let mut out = Vec::new();
for &(x, y, data) in &self.tiles {
ctl.check().map_err(|_| IoError::Cancelled)?;
let (flag, payload) = data.split_first().ok_or_else(|| invalid("empty tile"))?;
match flag {
1 => {
// LZF tiles hold byte planes: byte k of pixel i is at k * n + i.
let planar = lzf_decompress(payload, expected)?;
for (k, plane) in planar.chunks_exact(n).enumerate() {
for (i, b) in plane.iter().enumerate() {
if let Some(slot) = interleaved.get_mut(i * self.pixel_size + k) {
*slot = *b;
}
}
}
}
// Raw tiles (written when LZF doesn't shrink them) are already interleaved.
0 if payload.len() == expected => interleaved.copy_from_slice(payload),
0 => return Err(invalid("raw tile has the wrong size")),
f => return Err(invalid(format!("unknown tile compression flag {f}"))),
}
space.convert(&interleaved, fmt, &mut out);
let (x0, y0) =
(x.checked_add(dx).ok_or_else(|| invalid("tile offset overflow"))?, y.checked_add(dy).ok_or_else(|| invalid("tile offset overflow"))?);
let rect = Rect::from_xywh(x0, y0, self.width as u32, self.height as u32);
if rect.width() as usize != self.width || rect.height() as usize != self.height || out.len() != n * fmt.bytes_per_pixel() {
return Err(invalid("tile does not fit its position"));
}
surface.write_interleaved(rect, &out);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn file(positions: &[(i32, i32)]) -> TileFile<'static> {
TileFile { width: 64, height: 64, pixel_size: 4, tiles: positions.iter().map(|&(x, y)| (x, y, &[][..])).collect() }
}
#[test]
fn sparse_tiles_are_charged_for_the_backing_tiles_they_land_in() {
// Sixteen 64×64 tiles that fill one 256×256 backing tile cost what they hold.
let dense: Vec<_> = (0..4).flat_map(|y| (0..4).map(move |x| (x * 64, y * 64))).collect();
assert_eq!(file(&dense).decoded_bytes(4, 0, 0).unwrap(), 16 * 64 * 64 * 4);
// The same number far apart each take a whole backing tile: 16 × 256 × 256 × 4.
let sparse: Vec<_> = (0..16).map(|i| (i * 10_240, 0)).collect();
assert_eq!(file(&sparse).decoded_bytes(4, 0, 0).unwrap(), 16 * 256 * 256 * 4);
}
#[test]
fn the_placement_offset_and_tile_extent_decide_the_backing_tiles() {
// One 64×64 tile straddling a backing-tile corner once offset touches four.
assert_eq!(file(&[(0, 0)]).decoded_bytes(4, 224, 224).unwrap(), 4 * 256 * 256 * 4);
// A tile wider than a backing tile reaches the ones between its corners.
let wide = TileFile { width: 1024, height: 1, pixel_size: 4, tiles: vec![(0, 0, &[][..])] };
assert_eq!(wide.decoded_bytes(4, 0, 0).unwrap(), 4 * 256 * 256 * 4);
}
}
-6
View File
@@ -38,12 +38,6 @@ fn invalid(message: impl Into<String>) -> IoError {
IoError::Ora(message.into())
}
/// The payload of a ZIP's first entry when it is a stored file named `mimetype`, which is how
/// OpenRaster and Krita mark their archives (so the type is readable without unzipping).
pub(crate) fn zip_mimetype(bytes: &[u8]) -> Option<&[u8]> {
craft_ora::zip_mimetype(bytes)
}
/// `true` for an OpenRaster archive (by its `mimetype` entry).
pub(crate) fn is_ora(bytes: &[u8]) -> bool {
craft_ora::is_ora(bytes)
+4 -4
View File
@@ -468,13 +468,13 @@ fn truncated_and_corrupted_files_never_panic() {
#[test]
fn zip_mimetype_reads_only_a_leading_stored_entry() {
assert_eq!(zip_mimetype(&archive("<image/>", &[])), Some(MIMETYPE));
assert_eq!(zip_mimetype(b"PK\x03\x04"), None);
assert_eq!(zip_mimetype(&[]), None);
assert_eq!(craft_ora::zip_mimetype(&archive("<image/>", &[])), Some(MIMETYPE));
assert_eq!(craft_ora::zip_mimetype(b"PK\x03\x04"), None);
assert_eq!(craft_ora::zip_mimetype(&[]), None);
let mut z = ZipWriter::new();
z.add("stack.xml", b"x").unwrap();
z.add("mimetype", MIMETYPE).unwrap();
assert_eq!(zip_mimetype(&z.finish().unwrap()), None);
assert_eq!(craft_ora::zip_mimetype(&z.finish().unwrap()), None);
}
#[test]