diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
index 5a9e4989d..ff1d7ff5a 100644
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -39,6 +39,9 @@ jobs:
packages: mesa-vulkan-drivers libvulkan1
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
+ # Test binaries without debug info or symbols: about a third of the size, and a panic still
+ # names its file and line.
+ dev-strip: true
# No debuginfo on Windows: writing PDBs for every test binary is a large part of its link
# time. A panic still names its file and line; only backtrace frames lose theirs, and the
# Linux and macOS legs keep line tables.
@@ -74,22 +77,28 @@ jobs:
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
command: |
# The tests run once, with every feature, in parallel across test binaries; nextest skips
- # doctests, so `cargo test --doc` runs them. The default-feature compile is the lint leg's
+ # doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose
+ # tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's
# first clippy run; the last command runs the crates whose tests check behaviour with a
# feature off, which an all-features build cannot reach.
- cargo nextest run --workspace --all-features --locked --profile ci
+ cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests
+ cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench
cargo test --workspace --doc --all-features --locked
- cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci
+ cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests
windows-command: |
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
- cargo nextest run --workspace --all-features --locked --profile ci
+ cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests
+ cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench
cargo test --workspace --doc --all-features --locked
- cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci
+ cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests
msrv:
name: Rust 1.95
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
+ # Its own dependency-cache entry: the calls in this file share one job id, so without a name
+ # they would write the same key.
+ cache-name: msrv
os: '["ubuntu-latest"]'
toolchain: 1.95.0
targets: ""
@@ -104,6 +113,7 @@ jobs:
name: UI and settings WASM
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
+ cache-name: wasm
os: '["ubuntu-latest"]'
targets: wasm32-unknown-unknown
tools: ""
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index 1b6105f24..5805271e0 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -11,6 +11,7 @@ author, source and license. Library code and original assets are under the repos
| `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files |
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 |
| `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 |
+| `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 |
| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
diff --git a/Cargo.lock b/Cargo.lock
index 95b9c5702..de69d0765 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1634,6 +1634,7 @@ version = "0.1.0"
name = "craft-captions"
version = "0.1.0"
dependencies = [
+ "craft-media",
"craft-media-testkit",
"craft-timeline",
"craft-xml",
@@ -1794,7 +1795,9 @@ name = "craft-develop"
version = "0.1.0"
dependencies = [
"craft-develop-model",
+ "craft-render-parity",
"proptest",
+ "rayon",
"serde",
]
@@ -2967,6 +2970,19 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "craft-ppt-binary"
+version = "0.1.0"
+dependencies = [
+ "craft-cfb",
+ "craft-drawingml",
+ "craft-pptx",
+ "image",
+ "log",
+ "miniz_oxide 0.8.9",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "craft-pptx"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index c36973b4a..a278beb41 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -161,6 +161,7 @@ craft-opc = { path = "crates/opc" }
craft-openpgp = { path = "crates/openpgp" }
craft-ora = { path = "crates/ora" }
craft-pptx = { path = "crates/pptx" }
+craft-ppt-binary = { path = "crates/ppt-binary" }
craft-penpot = { path = "crates/penpot" }
craft-pcraft-format = { path = "crates/pcraft-format" }
craft-pcraft-bundle = { path = "crates/pcraft-bundle" }
diff --git a/NOTICE b/NOTICE
index 35085dcb3..49bb9c0e4 100644
--- a/NOTICE
+++ b/NOTICE
@@ -108,6 +108,14 @@ Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. The format imp
clean-room work based on their public specifications; dependency licences and X.Org's `rgb.txt`
attribution are listed in ATTRIBUTION.md.
+crates/develop (craft-develop) is moved from LightCraft, module by module:
+- src/inpaint.rs and src/inpaint/ from crates/inpaint (lightcraft-inpaint), with its tests, revision a75497d6.
+ https://github.com/storytold/lightcraft
+ Copyright (c) 2026 ArtCraft Team and the LightCraft contributors.
+ That crate ports the inpainting (PatchMatch completion) and Poisson membrane fill code of PhotoCraft
+ (https://github.com/storytold/photocraft, crates/algo/src/inpaint.rs and poisson.rs), Copyright the PhotoCraft
+ contributors, MIT OR Apache-2.0; the port was modified by the LightCraft contributors (2026).
+
crates/raw (craft-raw) is moved from LightCraft, with behaviour ported from two other readers:
- LightCraft, crates/raw (src/lib.rs, dng.rs, dngwrite.rs, tiffraw.rs, unpack.rs, ljpeg.rs, jxl.rs,
opcodes.rs, profile.rs, gaintable.rs, semantic.rs, preview.rs, vendor/crw.rs, vendor/hasselblad.rs,
diff --git a/README.md b/README.md
index c4dabafb6..951298091 100644
--- a/README.md
+++ b/README.md
@@ -324,6 +324,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-plotter`](crates/plotter/README.md): cutter and pen-plotter command languages: HP-GL,
DMPL and GP-GL (plain and the Silhouette dialect, three generations, registration marks) from a
job in millimetres, plus the Silhouette device queries and reply parsers. No I/O.
+- [`craft-ppt-binary`](crates/ppt-binary/README.md): the PowerPoint 97-2003 binary format (`.ppt`, `.pot`, `.pps`;
+ [MS-PPT], [MS-ODRAW]) read into `craft-pptx`, on `craft-cfb`. Import only. DeckCraft's reader.
- [`craft-pptx`](crates/pptx/README.md): PresentationML, the model of a `.pptx` presentation:
masters, layouts, slides, shapes, placeholders and their inheritance, transitions and animations,
comments, sections, media and kept parts. From DeckCraft. DrawingML comes from `craft-drawingml`.
diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml
index cd09f7e16..1136f55f9 100644
--- a/crates/captions/Cargo.toml
+++ b/crates/captions/Cargo.toml
@@ -10,6 +10,11 @@ repository.workspace = true
[lints]
workspace = true
+[features]
+default = []
+# MP4 timed text (3GPP TS 26.245 / mov_text / tx3g) sample codec.
+mov-text = []
+
[dependencies]
craft-timeline = { workspace = true }
craft-xml = { workspace = true }
@@ -21,3 +26,5 @@ proptest = { workspace = true }
roxmltree = "0.21"
# ffmpeg as the reference for the ASS tests (tests/it/ass.rs).
craft-media-testkit = { workspace = true }
+# craft-media isobmff for mov_text oracle demuxing/muxing tests.
+craft-media = { workspace = true, features = ["isobmff"] }
diff --git a/crates/captions/README.md b/crates/captions/README.md
index 7380a3ce4..b2f6a195f 100644
--- a/crates/captions/README.md
+++ b/crates/captions/README.md
@@ -27,6 +27,10 @@ assert!(scc.starts_with(b"Scenarist_SCC V1.0"));
and the SMPTE ST 334-2 caption distribution packet.
- `plain_text` strips inline tags and decodes the common entities, for display or for formats
without markup.
+- Optional feature `mov-text` provides MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245)
+ sample decoding, encoding, modifier box parsing (`styl`, `hlit`, `hclr`, `krok`, `dlay`, `href`,
+ `tbox`, `blnk`, `wrap`), and `Tx3gConfig` sample entry parsing/writing for ISO BMFF (`.mp4`) and
+ QuickTime (`.mov`) subtitle tracks.
## Time
diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs
index ca99dba43..2d0cf90c1 100644
--- a/crates/captions/src/lib.rs
+++ b/crates/captions/src/lib.rs
@@ -36,6 +36,8 @@ pub mod ass;
pub mod cea608;
pub mod jacosub;
pub mod mcc;
+#[cfg(feature = "mov-text")]
+pub mod mov_text;
pub mod pjs;
pub mod realtext;
pub mod scc;
diff --git a/crates/captions/src/mov_text.rs b/crates/captions/src/mov_text.rs
new file mode 100644
index 000000000..d1a3ce2a9
--- /dev/null
+++ b/crates/captions/src/mov_text.rs
@@ -0,0 +1,871 @@
+//! MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245).
+//!
+//! A clean-room reader and writer for 3GPP Timed Text subtitle samples and sample entry
+//! configurations (`tx3g`), as carried in ISO BMFF (`.mp4`) and QuickTime (`.mov`) files.
+//!
+//! ## Sample Structure
+//!
+//! A timed text sample consists of:
+//! - A 16-bit big-endian text length.
+//! - The text string bytes (UTF-8, or UTF-16 with BOM).
+//! - Zero or more modifier boxes:
+//! - `styl`: Character style runs (bold, italic, underline, font ID, font size, text color).
+//! - `hlit`: Highlighted character range.
+//! - `hclr`: Highlight color (RGBA).
+//! - `krok`: Karaoke highlight timing and character spans.
+//! - `dlay`: Scroll delay in track-timescale ticks.
+//! - `href`: Hypertext link URL and alt text.
+//! - `tbox`: Text box override coordinates (`top, left, bottom, right`).
+//! - `blnk`: Blinking text character range.
+//! - `twrp`: Text wrap flag (0 = no wrap, 1 = automatic soft wrap).
+//!
+//! ## Style Flags
+//!
+//! Style flags in `styl` records:
+//! - `0x01`: Bold (`...`)
+//! - `0x02`: Italic (`...`)
+//! - `0x04`: Underline (`...`)
+
+use crate::time::Tick;
+use crate::{Cue, Document, TICKS_PER_SECOND};
+
+/// What went wrong reading or writing timed text.
+#[non_exhaustive]
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum Error {
+ /// The input slice is shorter than the declared field or box size.
+ #[error("truncated timed text data")]
+ Truncated,
+ /// The text payload is not valid UTF-8 and contains no valid UTF-16 BOM.
+ #[error("invalid text encoding in timed text sample")]
+ InvalidText,
+ /// The text exceeds the 16-bit length prefix (65,535 bytes).
+ #[error("timed text string exceeds 65535 bytes: {0}")]
+ TextTooLong(usize),
+ /// A modifier box header has an invalid size (< 8).
+ #[error("invalid modifier box size: {0}")]
+ InvalidBox(&'static str),
+}
+
+/// `Result` alias for timed text operations.
+pub type Result = std::result::Result;
+
+/// Face style flag: Bold (`0x01`).
+pub const STYLE_FLAG_BOLD: u8 = 0x01;
+/// Face style flag: Italic (`0x02`).
+pub const STYLE_FLAG_ITALIC: u8 = 0x02;
+/// Face style flag: Underline (`0x04`).
+pub const STYLE_FLAG_UNDERLINE: u8 = 0x04;
+
+/// A character styling record within a `styl` box.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct StyleRecord {
+ /// 0-indexed start character index (inclusive, measured in Unicode scalar values).
+ pub start_char: u16,
+ /// 0-indexed end character index (exclusive, measured in Unicode scalar values).
+ pub end_char: u16,
+ /// 16-bit font ID matching an entry in the sample description font table (`ftab`).
+ pub font_id: u16,
+ /// Face style flags: bit 0 = bold, bit 1 = italic, bit 2 = underline.
+ pub face_style_flags: u8,
+ /// Font size in points.
+ pub font_size: u8,
+ /// Text RGBA color (`[r, g, b, a]`).
+ pub text_color_rgba: [u8; 4],
+}
+
+impl Default for StyleRecord {
+ fn default() -> Self {
+ Self { start_char: 0, end_char: 0, font_id: 1, face_style_flags: 0, font_size: 16, text_color_rgba: [255, 255, 255, 255] }
+ }
+}
+
+impl StyleRecord {
+ /// Returns `true` if bold is set.
+ pub fn is_bold(&self) -> bool {
+ self.face_style_flags & STYLE_FLAG_BOLD != 0
+ }
+
+ /// Returns `true` if italic is set.
+ pub fn is_italic(&self) -> bool {
+ self.face_style_flags & STYLE_FLAG_ITALIC != 0
+ }
+
+ /// Returns `true` if underline is set.
+ pub fn is_underline(&self) -> bool {
+ self.face_style_flags & STYLE_FLAG_UNDERLINE != 0
+ }
+}
+
+/// Coordinates of a text display box (`tbox`).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct TextBox {
+ pub top: i16,
+ pub left: i16,
+ pub bottom: i16,
+ pub right: i16,
+}
+
+/// An entry in a karaoke box (`krok`).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct KaraokeEntry {
+ /// Highlight end time in timescale ticks.
+ pub highlight_end_time: u32,
+ /// Start character index (inclusive).
+ pub start_char: u16,
+ /// End character index (exclusive).
+ pub end_char: u16,
+}
+
+/// A hypertext link entry (`href`).
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct HyperText {
+ /// Start character index (inclusive).
+ pub start_char: u16,
+ /// End character index (exclusive).
+ pub end_char: u16,
+ /// Destination URL.
+ pub url: String,
+ /// Accessible alt text string.
+ pub alt_string: String,
+}
+
+/// An unpacked 3GPP Timed Text (`tx3g` / `mov_text`) sample.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct TextSample {
+ /// Decoded UTF-8 text content.
+ pub text: String,
+ /// Character styling records from the `styl` box.
+ pub styles: Vec,
+ /// Highlighted character range `(start_char, end_char)` from `hlit`.
+ pub highlight: Option<(u16, u16)>,
+ /// Highlight color `[r, g, b, a]` from `hclr`.
+ pub highlight_color: Option<[u8; 4]>,
+ /// Karaoke timing and spans `(highlight_start_time, entries)` from `krok`.
+ pub karaoke: Option<(u32, Vec)>,
+ /// Scroll delay in milliseconds from `dlay`.
+ pub scroll_delay: Option,
+ /// Hypertext links from `href` boxes.
+ pub hypertext: Vec,
+ /// Text box override from `tbox`.
+ pub text_box: Option,
+ /// Blinking character ranges `(start_char, end_char)` from `blnk` boxes.
+ pub blinking: Vec<(u16, u16)>,
+ /// Wrap flag from `wrap` box: `0` = automatic wrap, `1` = no wrap.
+ pub wrap_flag: Option,
+}
+
+/// Sample description table configuration for a `tx3g` track.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Tx3gConfig {
+ /// 32-bit display flags (e.g. scroll in, scroll out, continuous scroll).
+ pub display_flags: u32,
+ /// Horizontal justification: 0 = left, 1 = center, -1 = right.
+ pub horizontal_justification: i8,
+ /// Vertical justification: 0 = top, 1 = center, -1 = bottom.
+ pub vertical_justification: i8,
+ /// Background RGBA color.
+ pub background_color: [u8; 4],
+ /// Default text box coordinates.
+ pub default_text_box: TextBox,
+ /// Default style record.
+ pub default_style: StyleRecord,
+ /// Font table entries `(font_id, font_name)`.
+ pub fonts: Vec<(u16, String)>,
+}
+
+impl Default for Tx3gConfig {
+ fn default() -> Self {
+ Self {
+ display_flags: 0,
+ horizontal_justification: 1, // center
+ vertical_justification: -1, // bottom
+ background_color: [0, 0, 0, 255],
+ default_text_box: TextBox::default(),
+ default_style: StyleRecord::default(),
+ fonts: vec![(1, "Arial".to_string())],
+ }
+ }
+}
+
+impl Tx3gConfig {
+ /// Parse a `tx3g` sample entry payload (after the standard 8-byte sample entry header).
+ pub fn parse(payload: &[u8]) -> Result {
+ if payload.len() < 30 {
+ return Err(Error::Truncated);
+ }
+ let display_flags = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
+ let horizontal_justification = payload[4] as i8;
+ let vertical_justification = payload[5] as i8;
+ let background_color = [payload[6], payload[7], payload[8], payload[9]];
+
+ let default_text_box = TextBox {
+ top: i16::from_be_bytes([payload[10], payload[11]]),
+ left: i16::from_be_bytes([payload[12], payload[13]]),
+ bottom: i16::from_be_bytes([payload[14], payload[15]]),
+ right: i16::from_be_bytes([payload[16], payload[17]]),
+ };
+
+ let default_style = StyleRecord {
+ start_char: u16::from_be_bytes([payload[18], payload[19]]),
+ end_char: u16::from_be_bytes([payload[20], payload[21]]),
+ font_id: u16::from_be_bytes([payload[22], payload[23]]),
+ face_style_flags: payload[24],
+ font_size: payload[25],
+ text_color_rgba: [payload[26], payload[27], payload[28], payload[29]],
+ };
+
+ let mut fonts = Vec::new();
+ let mut pos = 30;
+ while pos + 8 <= payload.len() {
+ let box_size = u32::from_be_bytes([payload[pos], payload[pos + 1], payload[pos + 2], payload[pos + 3]]) as usize;
+ if box_size < 8 || pos.checked_add(box_size).is_none_or(|end| end > payload.len()) {
+ break;
+ }
+ let box_type = &payload[pos + 4..pos + 8];
+ if box_type == b"ftab" && box_size >= 10 {
+ let count = u16::from_be_bytes([payload[pos + 8], payload[pos + 9]]) as usize;
+ let mut fpos = pos + 10;
+ for _ in 0..count {
+ if fpos + 3 > pos + box_size {
+ break;
+ }
+ let font_id = u16::from_be_bytes([payload[fpos], payload[fpos + 1]]);
+ let name_len = payload[fpos + 2] as usize;
+ fpos += 3;
+ if fpos + name_len > pos + box_size {
+ break;
+ }
+ if let Ok(name) = std::str::from_utf8(&payload[fpos..fpos + name_len]) {
+ fonts.push((font_id, name.to_string()));
+ }
+ fpos += name_len;
+ }
+ }
+ pos += box_size;
+ }
+
+ Ok(Self { display_flags, horizontal_justification, vertical_justification, background_color, default_text_box, default_style, fonts })
+ }
+
+ /// Write the `tx3g` sample entry payload (after the 8-byte sample entry header).
+ pub fn write(&self) -> Vec {
+ let mut out = Vec::with_capacity(30 + 32);
+ out.extend_from_slice(&self.display_flags.to_be_bytes());
+ out.push(self.horizontal_justification as u8);
+ out.push(self.vertical_justification as u8);
+ out.extend_from_slice(&self.background_color);
+
+ out.extend_from_slice(&self.default_text_box.top.to_be_bytes());
+ out.extend_from_slice(&self.default_text_box.left.to_be_bytes());
+ out.extend_from_slice(&self.default_text_box.bottom.to_be_bytes());
+ out.extend_from_slice(&self.default_text_box.right.to_be_bytes());
+
+ out.extend_from_slice(&self.default_style.start_char.to_be_bytes());
+ out.extend_from_slice(&self.default_style.end_char.to_be_bytes());
+ out.extend_from_slice(&self.default_style.font_id.to_be_bytes());
+ out.push(self.default_style.face_style_flags);
+ out.push(self.default_style.font_size);
+ out.extend_from_slice(&self.default_style.text_color_rgba);
+
+ // ftab box
+ let mut ftab_payload = Vec::new();
+ let fonts = &self.fonts[..self.fonts.len().min(u16::MAX as usize)];
+ ftab_payload.extend_from_slice(&(fonts.len() as u16).to_be_bytes());
+ for (id, name) in fonts {
+ ftab_payload.extend_from_slice(&id.to_be_bytes());
+ let name_bytes = name.as_bytes();
+ let limit = name.floor_char_boundary(name_bytes.len().min(255));
+ ftab_payload.push(limit as u8);
+ ftab_payload.extend_from_slice(&name_bytes[..limit]);
+ }
+ let ftab_size = 8u32.saturating_add(ftab_payload.len() as u32);
+ out.extend_from_slice(&ftab_size.to_be_bytes());
+ out.extend_from_slice(b"ftab");
+ out.extend_from_slice(&ftab_payload);
+
+ out
+ }
+}
+
+/// Read and decode a single 3GPP Timed Text sample (`tx3g` / `mov_text`).
+pub fn read_sample(data: &[u8]) -> Result {
+ if data.len() < 2 {
+ return Err(Error::Truncated);
+ }
+
+ let text_len = u16::from_be_bytes([data[0], data[1]]) as usize;
+ if data.len() < 2 + text_len {
+ return Err(Error::Truncated);
+ }
+
+ let text_bytes = &data[2..2 + text_len];
+ let text = decode_text(text_bytes)?;
+
+ let mut sample = TextSample { text, ..Default::default() };
+
+ let mut pos = 2 + text_len;
+ while pos + 8 <= data.len() {
+ let size = u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
+ if size < 8 {
+ return Err(Error::InvalidBox("size smaller than 8"));
+ }
+ let box_end = pos.checked_add(size).ok_or(Error::Truncated)?;
+ if box_end > data.len() {
+ return Err(Error::Truncated);
+ }
+
+ let box_type = &data[pos + 4..pos + 8];
+ let payload = &data[pos + 8..box_end];
+
+ match box_type {
+ b"styl" => {
+ if payload.len() < 2 {
+ return Err(Error::Truncated);
+ }
+ let count = u16::from_be_bytes([payload[0], payload[1]]) as usize;
+ let mut spos = 2;
+ for _ in 0..count {
+ if spos + 12 > payload.len() {
+ return Err(Error::Truncated);
+ }
+ sample.styles.push(StyleRecord {
+ start_char: u16::from_be_bytes([payload[spos], payload[spos + 1]]),
+ end_char: u16::from_be_bytes([payload[spos + 2], payload[spos + 3]]),
+ font_id: u16::from_be_bytes([payload[spos + 4], payload[spos + 5]]),
+ face_style_flags: payload[spos + 6],
+ font_size: payload[spos + 7],
+ text_color_rgba: [payload[spos + 8], payload[spos + 9], payload[spos + 10], payload[spos + 11]],
+ });
+ spos += 12;
+ }
+ }
+ b"hlit" => {
+ if payload.len() < 4 {
+ return Err(Error::Truncated);
+ }
+ let start = u16::from_be_bytes([payload[0], payload[1]]);
+ let end = u16::from_be_bytes([payload[2], payload[3]]);
+ sample.highlight = Some((start, end));
+ }
+ b"hclr" => {
+ if payload.len() < 4 {
+ return Err(Error::Truncated);
+ }
+ sample.highlight_color = Some([payload[0], payload[1], payload[2], payload[3]]);
+ }
+ b"krok" => {
+ if payload.len() < 6 {
+ return Err(Error::Truncated);
+ }
+ let start_time = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
+ let count = u16::from_be_bytes([payload[4], payload[5]]) as usize;
+ let mut entries = Vec::new();
+ let mut kpos = 6;
+ for _ in 0..count {
+ if kpos + 8 > payload.len() {
+ return Err(Error::Truncated);
+ }
+ entries.push(KaraokeEntry {
+ highlight_end_time: u32::from_be_bytes([payload[kpos], payload[kpos + 1], payload[kpos + 2], payload[kpos + 3]]),
+ start_char: u16::from_be_bytes([payload[kpos + 4], payload[kpos + 5]]),
+ end_char: u16::from_be_bytes([payload[kpos + 6], payload[kpos + 7]]),
+ });
+ kpos += 8;
+ }
+ sample.karaoke = Some((start_time, entries));
+ }
+ b"dlay" => {
+ if payload.len() < 4 {
+ return Err(Error::Truncated);
+ }
+ sample.scroll_delay = Some(u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]));
+ }
+ b"href" => {
+ if payload.len() < 6 {
+ return Err(Error::Truncated);
+ }
+ let start = u16::from_be_bytes([payload[0], payload[1]]);
+ let end = u16::from_be_bytes([payload[2], payload[3]]);
+ let url_len = payload[4] as usize;
+ if 5 + url_len > payload.len() {
+ return Err(Error::Truncated);
+ }
+ let url = std::str::from_utf8(&payload[5..5 + url_len]).map_err(|_| Error::InvalidText)?.to_string();
+ let alt_pos = 5 + url_len;
+ let alt_len = payload.get(alt_pos).copied().unwrap_or(0) as usize;
+ let alt_string = if alt_len > 0 && alt_pos + 1 + alt_len <= payload.len() {
+ std::str::from_utf8(&payload[alt_pos + 1..alt_pos + 1 + alt_len]).map_err(|_| Error::InvalidText)?.to_string()
+ } else {
+ String::new()
+ };
+ sample.hypertext.push(HyperText { start_char: start, end_char: end, url, alt_string });
+ }
+ b"tbox" => {
+ if payload.len() < 8 {
+ return Err(Error::Truncated);
+ }
+ sample.text_box = Some(TextBox {
+ top: i16::from_be_bytes([payload[0], payload[1]]),
+ left: i16::from_be_bytes([payload[2], payload[3]]),
+ bottom: i16::from_be_bytes([payload[4], payload[5]]),
+ right: i16::from_be_bytes([payload[6], payload[7]]),
+ });
+ }
+ b"blnk" => {
+ if payload.len() < 4 {
+ return Err(Error::Truncated);
+ }
+ let start = u16::from_be_bytes([payload[0], payload[1]]);
+ let end = u16::from_be_bytes([payload[2], payload[3]]);
+ sample.blinking.push((start, end));
+ }
+ b"twrp" | b"wrap" => {
+ if payload.is_empty() {
+ return Err(Error::Truncated);
+ }
+ sample.wrap_flag = Some(payload[0]);
+ }
+ _ => {
+ // Unknown modifier box: safely ignored.
+ }
+ }
+
+ pos = box_end;
+ }
+
+ Ok(sample)
+}
+
+/// Helper to decode UTF-8 or UTF-16 with BOM.
+fn decode_text(bytes: &[u8]) -> Result {
+ if bytes.len() >= 2 {
+ if bytes[0] == 0xFE && bytes[1] == 0xFF {
+ // UTF-16 BE
+ let u16s: Vec = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
+ return String::from_utf16(&u16s).map_err(|_| Error::InvalidText);
+ } else if bytes[0] == 0xFF && bytes[1] == 0xFE {
+ // UTF-16 LE
+ let u16s: Vec = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
+ return String::from_utf16(&u16s).map_err(|_| Error::InvalidText);
+ }
+ }
+ std::str::from_utf8(bytes).map(ToString::to_string).map_err(|_| Error::InvalidText)
+}
+
+/// Pack and encode a timed text sample into bytes.
+pub fn write_sample(sample: &TextSample) -> Result> {
+ let text_bytes = sample.text.as_bytes();
+ if text_bytes.len() > u16::MAX as usize {
+ return Err(Error::TextTooLong(text_bytes.len()));
+ }
+
+ let mut out = Vec::with_capacity(2 + text_bytes.len() + 64);
+ out.extend_from_slice(&(text_bytes.len() as u16).to_be_bytes());
+ out.extend_from_slice(text_bytes);
+
+ // 1. styl box
+ if !sample.styles.is_empty() {
+ if sample.styles.len() > u16::MAX as usize {
+ return Err(Error::InvalidBox("too many styles in sample"));
+ }
+ let size = 8u32.checked_add(2).and_then(|s| s.checked_add(sample.styles.len() as u32 * 12)).ok_or(Error::InvalidBox("styl size overflow"))?;
+ out.extend_from_slice(&size.to_be_bytes());
+ out.extend_from_slice(b"styl");
+ out.extend_from_slice(&(sample.styles.len() as u16).to_be_bytes());
+ for st in &sample.styles {
+ out.extend_from_slice(&st.start_char.to_be_bytes());
+ out.extend_from_slice(&st.end_char.to_be_bytes());
+ out.extend_from_slice(&st.font_id.to_be_bytes());
+ out.push(st.face_style_flags);
+ out.push(st.font_size);
+ out.extend_from_slice(&st.text_color_rgba);
+ }
+ }
+
+ // 2. hlit box
+ if let Some((start, end)) = sample.highlight {
+ out.extend_from_slice(&12u32.to_be_bytes());
+ out.extend_from_slice(b"hlit");
+ out.extend_from_slice(&start.to_be_bytes());
+ out.extend_from_slice(&end.to_be_bytes());
+ }
+
+ // 3. hclr box
+ if let Some(color) = sample.highlight_color {
+ out.extend_from_slice(&12u32.to_be_bytes());
+ out.extend_from_slice(b"hclr");
+ out.extend_from_slice(&color);
+ }
+
+ // 4. krok box
+ if let Some((start_time, ref entries)) = sample.karaoke {
+ if entries.len() > u16::MAX as usize {
+ return Err(Error::InvalidBox("too many karaoke entries"));
+ }
+ let size = 8u32.checked_add(6).and_then(|s| s.checked_add(entries.len() as u32 * 8)).ok_or(Error::InvalidBox("krok size overflow"))?;
+ out.extend_from_slice(&size.to_be_bytes());
+ out.extend_from_slice(b"krok");
+ out.extend_from_slice(&start_time.to_be_bytes());
+ out.extend_from_slice(&(entries.len() as u16).to_be_bytes());
+ for e in entries {
+ out.extend_from_slice(&e.highlight_end_time.to_be_bytes());
+ out.extend_from_slice(&e.start_char.to_be_bytes());
+ out.extend_from_slice(&e.end_char.to_be_bytes());
+ }
+ }
+
+ // 5. dlay box
+ if let Some(delay) = sample.scroll_delay {
+ out.extend_from_slice(&12u32.to_be_bytes());
+ out.extend_from_slice(b"dlay");
+ out.extend_from_slice(&delay.to_be_bytes());
+ }
+
+ // 6. href boxes
+ for link in &sample.hypertext {
+ let url_bytes = link.url.as_bytes();
+ let alt_bytes = link.alt_string.as_bytes();
+ let ulen = url_bytes.len().min(255) as u8;
+ let alen = alt_bytes.len().min(255) as u8;
+ let size = 8u32 + 4 + 1 + ulen as u32 + 1 + alen as u32;
+ out.extend_from_slice(&size.to_be_bytes());
+ out.extend_from_slice(b"href");
+ out.extend_from_slice(&link.start_char.to_be_bytes());
+ out.extend_from_slice(&link.end_char.to_be_bytes());
+ out.push(ulen);
+ out.extend_from_slice(&url_bytes[..ulen as usize]);
+ out.push(alen);
+ out.extend_from_slice(&alt_bytes[..alen as usize]);
+ }
+
+ // 7. tbox box
+ if let Some(tb) = sample.text_box {
+ out.extend_from_slice(&16u32.to_be_bytes());
+ out.extend_from_slice(b"tbox");
+ out.extend_from_slice(&tb.top.to_be_bytes());
+ out.extend_from_slice(&tb.left.to_be_bytes());
+ out.extend_from_slice(&tb.bottom.to_be_bytes());
+ out.extend_from_slice(&tb.right.to_be_bytes());
+ }
+
+ // 8. blnk boxes
+ for &(start, end) in &sample.blinking {
+ out.extend_from_slice(&12u32.to_be_bytes());
+ out.extend_from_slice(b"blnk");
+ out.extend_from_slice(&start.to_be_bytes());
+ out.extend_from_slice(&end.to_be_bytes());
+ }
+
+ // 9. twrp box
+ if let Some(flag) = sample.wrap_flag {
+ out.extend_from_slice(&9u32.to_be_bytes());
+ out.extend_from_slice(b"twrp");
+ out.push(flag);
+ }
+
+ Ok(out)
+}
+
+fn push_escaped_char(out: &mut String, ch: char) {
+ match ch {
+ '&' => out.push_str("&"),
+ '<' => out.push_str("<"),
+ '>' => out.push_str(">"),
+ _ => out.push(ch),
+ }
+}
+
+/// Convert a [`TextSample`] into HTML-style formatted markup (``, ``, ``, ``).
+pub fn sample_to_markup(sample: &TextSample) -> String {
+ if sample.styles.is_empty() {
+ let mut out = String::with_capacity(sample.text.len());
+ for ch in sample.text.chars() {
+ push_escaped_char(&mut out, ch);
+ }
+ return out;
+ }
+
+ let chars: Vec = sample.text.chars().collect();
+ let n = chars.len();
+ if n == 0 {
+ return String::new();
+ }
+
+ let mut starts: std::collections::HashMap> = std::collections::HashMap::new();
+ let mut ends: std::collections::HashMap> = std::collections::HashMap::new();
+ for st in &sample.styles {
+ if st.end_char > st.start_char {
+ starts.entry(st.start_char).or_default().push(st);
+ ends.entry(st.end_char).or_default().push(st);
+ }
+ }
+
+ let mut out = String::with_capacity(sample.text.len() + sample.styles.len() * 16);
+
+ for (i, &ch) in chars.iter().enumerate() {
+ let char_idx = i as u16;
+
+ // Open tags for any style starting at char_idx
+ if let Some(list) = starts.get(&char_idx) {
+ for st in list {
+ let has_color = st.text_color_rgba != [255, 255, 255, 255];
+ if has_color {
+ out.push_str(&format!(
+ "",
+ st.text_color_rgba[0], st.text_color_rgba[1], st.text_color_rgba[2]
+ ));
+ }
+ if st.is_bold() {
+ out.push_str("");
+ }
+ if st.is_italic() {
+ out.push_str("");
+ }
+ if st.is_underline() {
+ out.push_str("");
+ }
+ }
+ }
+
+ push_escaped_char(&mut out, ch);
+
+ // Close tags for any style ending at char_idx + 1
+ if let Some(list) = ends.get(&(char_idx + 1)) {
+ for st in list.iter().rev() {
+ if st.is_underline() {
+ out.push_str("");
+ }
+ if st.is_italic() {
+ out.push_str("");
+ }
+ if st.is_bold() {
+ out.push_str("");
+ }
+ let has_color = st.text_color_rgba != [255, 255, 255, 255];
+ if has_color {
+ out.push_str("");
+ }
+ }
+ }
+ }
+
+ out
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+struct CharFormatting {
+ flags: u8,
+ color: [u8; 4],
+}
+
+impl Default for CharFormatting {
+ fn default() -> Self {
+ Self { flags: 0, color: [255, 255, 255, 255] }
+ }
+}
+
+/// Parse HTML-style formatted markup (``, ``, ``, ``) into a [`TextSample`].
+pub fn markup_to_sample(markup: &str) -> TextSample {
+ let mut bold_depth = 0usize;
+ let mut italic_depth = 0usize;
+ let mut underline_depth = 0usize;
+ let mut color_stack: Vec<[u8; 4]> = Vec::new();
+
+ let mut decoded_chars: Vec = Vec::with_capacity(markup.len());
+ let mut char_styles: Vec = Vec::with_capacity(markup.len());
+
+ let mut chars = markup.chars().peekable();
+
+ while let Some(ch) = chars.next() {
+ if ch == '<' {
+ let mut tag = String::new();
+ for next in chars.by_ref() {
+ if next == '>' {
+ break;
+ }
+ tag.push(next);
+ }
+ let trimmed = tag.trim().to_ascii_lowercase();
+ if trimmed == "b" {
+ bold_depth += 1;
+ } else if trimmed == "/b" {
+ bold_depth = bold_depth.saturating_sub(1);
+ } else if trimmed == "i" {
+ italic_depth += 1;
+ } else if trimmed == "/i" {
+ italic_depth = italic_depth.saturating_sub(1);
+ } else if trimmed == "u" {
+ underline_depth += 1;
+ } else if trimmed == "/u" {
+ underline_depth = underline_depth.saturating_sub(1);
+ } else if trimmed.starts_with("font") {
+ if let Some(color) = parse_font_color(&tag) {
+ color_stack.push(color);
+ }
+ } else if trimmed == "/font" {
+ color_stack.pop();
+ }
+ } else {
+ let mut text_chunk = String::new();
+ text_chunk.push(ch);
+ while let Some(&next) = chars.peek() {
+ if next == '<' {
+ break;
+ }
+ text_chunk.push(next);
+ chars.next();
+ }
+
+ let decoded = crate::decode_entities(&text_chunk);
+ let mut flags = 0u8;
+ if bold_depth > 0 {
+ flags |= STYLE_FLAG_BOLD;
+ }
+ if italic_depth > 0 {
+ flags |= STYLE_FLAG_ITALIC;
+ }
+ if underline_depth > 0 {
+ flags |= STYLE_FLAG_UNDERLINE;
+ }
+ let color = color_stack.last().copied().unwrap_or([255, 255, 255, 255]);
+ let fmt = CharFormatting { flags, color };
+
+ for c in decoded.chars() {
+ decoded_chars.push(c);
+ char_styles.push(fmt);
+ }
+ }
+ }
+
+ let text: String = decoded_chars.iter().collect();
+
+ // Group adjacent characters with identical non-default formatting into sorted, non-overlapping style runs.
+ let mut styles = Vec::new();
+ let mut run_start: Option<(usize, CharFormatting)> = None;
+
+ for (idx, &fmt) in char_styles.iter().enumerate() {
+ let is_styled = fmt.flags != 0 || fmt.color != [255, 255, 255, 255];
+ match run_start {
+ Some((start, current_fmt)) => {
+ if fmt != current_fmt {
+ if current_fmt.flags != 0 || current_fmt.color != [255, 255, 255, 255] {
+ styles.push(StyleRecord {
+ start_char: start as u16,
+ end_char: idx as u16,
+ font_id: 1,
+ face_style_flags: current_fmt.flags,
+ font_size: 16,
+ text_color_rgba: current_fmt.color,
+ });
+ }
+ run_start = if is_styled { Some((idx, fmt)) } else { None };
+ }
+ }
+ None => {
+ if is_styled {
+ run_start = Some((idx, fmt));
+ }
+ }
+ }
+ }
+
+ if let Some((start, fmt)) = run_start {
+ styles.push(StyleRecord {
+ start_char: start as u16,
+ end_char: char_styles.len() as u16,
+ font_id: 1,
+ face_style_flags: fmt.flags,
+ font_size: 16,
+ text_color_rgba: fmt.color,
+ });
+ }
+
+ TextSample { text, styles, ..Default::default() }
+}
+
+/// Helper to parse color attribute from `` tag.
+fn parse_font_color(tag: &str) -> Option<[u8; 4]> {
+ let lower = tag.to_ascii_lowercase();
+ let col_idx = lower.find("color=")?;
+ let rest = tag[col_idx + 6..].trim_start();
+ let val = if let Some(stripped) = rest.strip_prefix('"') {
+ let end = stripped.find('"')?;
+ &stripped[..end]
+ } else if let Some(stripped) = rest.strip_prefix('\'') {
+ let end = stripped.find('\'')?;
+ &stripped[..end]
+ } else {
+ let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
+ &rest[..end]
+ };
+
+ let hex = val.strip_prefix('#').unwrap_or(val);
+ if hex.len() == 6 {
+ let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?;
+ let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?;
+ let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?;
+ Some([r, g, b, 255])
+ } else if hex.len() == 8 {
+ let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?;
+ let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?;
+ let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?;
+ let a = u8::from_str_radix(hex.get(6..8)?, 16).ok()?;
+ Some([r, g, b, a])
+ } else {
+ None
+ }
+}
+
+/// Convert a caption [`Cue`] into a [`TextSample`].
+pub fn cue_to_sample(cue: &Cue) -> TextSample {
+ markup_to_sample(&cue.text)
+}
+
+/// Convert a [`TextSample`] into a caption [`Cue`] spanning `start` to `end`.
+pub fn sample_to_cue(sample: &TextSample, start: Tick, end: Tick) -> Cue {
+ Cue { start, end, text: sample_to_markup(sample), speaker: None, id: None, settings: String::new() }
+}
+
+/// Decode a stream of timed text samples into a [`Document`].
+pub fn decode_timed_samples<'a, I>(doc: &mut Document, samples: I, timescale: u32) -> Result<()>
+where
+ I: IntoIterator- ,
+{
+ decode_timed_samples_with_config(doc, samples, timescale, None)
+}
+
+/// Decode a stream of timed text samples into a [`Document`], applying an optional sample description configuration.
+pub fn decode_timed_samples_with_config<'a, I>(doc: &mut Document, samples: I, timescale: u32, config: Option<&Tx3gConfig>) -> Result<()>
+where
+ I: IntoIterator
- ,
+{
+ if timescale == 0 {
+ return Ok(());
+ }
+ let ts = timescale as i128;
+ for (pts, duration, data) in samples {
+ let mut sample = read_sample(data)?;
+ if sample.text.trim().is_empty() {
+ continue;
+ }
+ if sample.styles.is_empty()
+ && let Some(cfg) = config
+ && (cfg.default_style.face_style_flags != 0 || cfg.default_style.text_color_rgba != [255, 255, 255, 255])
+ {
+ sample.styles.push(StyleRecord {
+ start_char: 0,
+ end_char: sample.text.chars().count() as u16,
+ font_id: cfg.default_style.font_id,
+ face_style_flags: cfg.default_style.face_style_flags,
+ font_size: cfg.default_style.font_size,
+ text_color_rgba: cfg.default_style.text_color_rgba,
+ });
+ }
+ let end_pts = pts.checked_add(duration as u64).ok_or(Error::InvalidBox("timestamp interval overflow"))?;
+ let start_ticks = (pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64;
+ let end_ticks = (end_pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64;
+ doc.cues.push(sample_to_cue(&sample, Tick(start_ticks), Tick(end_ticks)));
+ }
+ Ok(())
+}
diff --git a/crates/captions/tests/it/main.rs b/crates/captions/tests/it/main.rs
index 437b2ba67..7d8070cad 100644
--- a/crates/captions/tests/it/main.rs
+++ b/crates/captions/tests/it/main.rs
@@ -2,6 +2,8 @@ mod ass;
mod limits;
mod literal_roundtrips;
mod mcc_708_timing;
+#[cfg(feature = "mov-text")]
+mod mov_text;
mod pjs_realtext_jacosub;
mod roundtrip;
mod ttml_body_styles;
diff --git a/crates/captions/tests/it/mov_text.rs b/crates/captions/tests/it/mov_text.rs
new file mode 100644
index 000000000..dfd5f73ea
--- /dev/null
+++ b/crates/captions/tests/it/mov_text.rs
@@ -0,0 +1,349 @@
+//! Clean-room tests and FFmpeg oracle tests for MP4 Timed Text (`mov_text` / `tx3g`).
+
+use craft_captions::mov_text::{
+ Error, KaraokeEntry, STYLE_FLAG_BOLD, STYLE_FLAG_ITALIC, STYLE_FLAG_UNDERLINE, StyleRecord, TextBox, TextSample, Tx3gConfig,
+ decode_timed_samples, markup_to_sample, read_sample, sample_to_markup, write_sample,
+};
+use craft_captions::time::Tick;
+use craft_captions::{Document, TICKS_PER_SECOND};
+
+#[test]
+fn test_plain_text_roundtrip() {
+ let sample = TextSample { text: "Hello world without styles".to_string(), ..Default::default() };
+
+ let bytes = write_sample(&sample).expect("write sample");
+ assert_eq!(bytes.len(), 2 + sample.text.len());
+ assert_eq!(&bytes[..2], &(sample.text.len() as u16).to_be_bytes());
+ assert_eq!(&bytes[2..], sample.text.as_bytes());
+
+ let decoded = read_sample(&bytes).expect("read sample");
+ assert_eq!(decoded.text, sample.text);
+ assert!(decoded.styles.is_empty());
+}
+
+#[test]
+fn test_empty_sample_roundtrip() {
+ let sample = TextSample::default();
+ let bytes = write_sample(&sample).expect("write");
+ assert_eq!(bytes, &[0x00, 0x00]);
+
+ let decoded = read_sample(&bytes).expect("read");
+ assert_eq!(decoded.text, "");
+ assert!(decoded.styles.is_empty());
+}
+
+#[test]
+fn test_styles_roundtrip() {
+ let sample = TextSample {
+ text: "Bold, Italic, Underline, and Colored".to_string(),
+ styles: vec![
+ StyleRecord {
+ start_char: 0,
+ end_char: 4,
+ font_id: 1,
+ face_style_flags: STYLE_FLAG_BOLD,
+ font_size: 16,
+ text_color_rgba: [255, 255, 255, 255],
+ },
+ StyleRecord {
+ start_char: 6,
+ end_char: 12,
+ font_id: 1,
+ face_style_flags: STYLE_FLAG_ITALIC,
+ font_size: 18,
+ text_color_rgba: [255, 255, 255, 255],
+ },
+ StyleRecord {
+ start_char: 14,
+ end_char: 23,
+ font_id: 1,
+ face_style_flags: STYLE_FLAG_UNDERLINE,
+ font_size: 16,
+ text_color_rgba: [255, 255, 255, 255],
+ },
+ StyleRecord { start_char: 29, end_char: 36, font_id: 1, face_style_flags: 0, font_size: 20, text_color_rgba: [255, 0, 0, 255] },
+ ],
+ ..Default::default()
+ };
+
+ let bytes = write_sample(&sample).expect("write");
+ let decoded = read_sample(&bytes).expect("read");
+
+ assert_eq!(decoded.text, sample.text);
+ assert_eq!(decoded.styles.len(), 4);
+ assert_eq!(decoded.styles, sample.styles);
+
+ assert!(decoded.styles[0].is_bold());
+ assert!(!decoded.styles[0].is_italic());
+ assert!(decoded.styles[1].is_italic());
+ assert!(decoded.styles[2].is_underline());
+ assert_eq!(decoded.styles[3].text_color_rgba, [255, 0, 0, 255]);
+}
+
+#[test]
+fn test_all_modifier_boxes_roundtrip() {
+ let sample = TextSample {
+ text: "Full modifiers test".to_string(),
+ styles: vec![StyleRecord {
+ start_char: 0,
+ end_char: 4,
+ font_id: 1,
+ face_style_flags: STYLE_FLAG_BOLD,
+ font_size: 16,
+ text_color_rgba: [255, 255, 255, 255],
+ }],
+ highlight: Some((5, 14)),
+ highlight_color: Some([255, 255, 0, 255]),
+ karaoke: Some((
+ 100,
+ vec![
+ KaraokeEntry { highlight_end_time: 200, start_char: 0, end_char: 4 },
+ KaraokeEntry { highlight_end_time: 350, start_char: 5, end_char: 14 },
+ ],
+ )),
+ scroll_delay: Some(500),
+ hypertext: vec![craft_captions::mov_text::HyperText {
+ start_char: 0,
+ end_char: 19,
+ url: "https://example.com".to_string(),
+ alt_string: "Example".to_string(),
+ }],
+ text_box: Some(TextBox { top: 10, left: 20, bottom: 100, right: 200 }),
+ blinking: vec![(0, 4), (15, 19)],
+ wrap_flag: Some(1),
+ };
+
+ let bytes = write_sample(&sample).expect("write");
+ let decoded = read_sample(&bytes).expect("read");
+
+ assert_eq!(decoded, sample);
+}
+
+#[test]
+fn test_utf16_bom_reading() {
+ // UTF-16 BE with BOM
+ let text = "Hello UTF-16";
+ let mut data_be = Vec::new();
+ let utf16_be_bytes: Vec = text.encode_utf16().flat_map(|u| u.to_be_bytes()).collect();
+ let total_len = 2 + utf16_be_bytes.len();
+ data_be.extend_from_slice(&(total_len as u16).to_be_bytes());
+ data_be.extend_from_slice(&[0xFE, 0xFF]);
+ data_be.extend_from_slice(&utf16_be_bytes);
+
+ let decoded_be = read_sample(&data_be).expect("read UTF-16 BE");
+ assert_eq!(decoded_be.text, text);
+
+ // UTF-16 LE with BOM
+ let mut data_le = Vec::new();
+ let utf16_le_bytes: Vec = text.encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
+ data_le.extend_from_slice(&(total_len as u16).to_be_bytes());
+ data_le.extend_from_slice(&[0xFF, 0xFE]);
+ data_le.extend_from_slice(&utf16_le_bytes);
+
+ let decoded_le = read_sample(&data_le).expect("read UTF-16 LE");
+ assert_eq!(decoded_le.text, text);
+}
+
+#[test]
+fn test_markup_conversion() {
+ let markup = "Hello Bold and Italic and Underline and Red";
+ let sample = markup_to_sample(markup);
+
+ assert_eq!(sample.text, "Hello Bold and Italic and Underline and Red");
+ assert_eq!(sample.styles.len(), 4);
+
+ let bold = &sample.styles[0];
+ assert_eq!(&sample.text[bold.start_char as usize..bold.end_char as usize], "Bold");
+ assert!(bold.is_bold());
+
+ let italic = &sample.styles[1];
+ assert_eq!(&sample.text[italic.start_char as usize..italic.end_char as usize], "Italic");
+ assert!(italic.is_italic());
+
+ let underline = &sample.styles[2];
+ assert_eq!(&sample.text[underline.start_char as usize..underline.end_char as usize], "Underline");
+ assert!(underline.is_underline());
+
+ let red = &sample.styles[3];
+ assert_eq!(&sample.text[red.start_char as usize..red.end_char as usize], "Red");
+ assert_eq!(red.text_color_rgba, [255, 0, 0, 255]);
+
+ let regenerated = sample_to_markup(&sample);
+ assert_eq!(regenerated, markup);
+}
+
+#[test]
+fn test_nested_styles_sorted_non_overlapping() {
+ let markup = "ABC";
+ let sample = markup_to_sample(markup);
+ assert_eq!(sample.text, "ABC");
+ assert_eq!(sample.styles.len(), 3);
+ // [0, 1): A is bold
+ assert_eq!(sample.styles[0].start_char, 0);
+ assert_eq!(sample.styles[0].end_char, 1);
+ assert_eq!(sample.styles[0].face_style_flags, STYLE_FLAG_BOLD);
+ // [1, 2): B is bold + italic
+ assert_eq!(sample.styles[1].start_char, 1);
+ assert_eq!(sample.styles[1].end_char, 2);
+ assert_eq!(sample.styles[1].face_style_flags, STYLE_FLAG_BOLD | STYLE_FLAG_ITALIC);
+ // [2, 3): C is bold
+ assert_eq!(sample.styles[2].start_char, 2);
+ assert_eq!(sample.styles[2].end_char, 3);
+ assert_eq!(sample.styles[2].face_style_flags, STYLE_FLAG_BOLD);
+}
+
+#[test]
+fn test_entities_and_literal_escaping() {
+ let markup = "A & B < C";
+ let sample = markup_to_sample(markup);
+ assert_eq!(sample.text, "A & B < C");
+ assert_eq!(sample.styles.len(), 1);
+ assert_eq!(sample.styles[0].start_char, 4);
+ assert_eq!(sample.styles[0].end_char, 9);
+
+ let roundtripped = sample_to_markup(&sample);
+ assert_eq!(roundtripped, "A & B < C");
+}
+
+#[test]
+fn test_twrp_box() {
+ let sample = TextSample { text: "Wrap me".to_string(), wrap_flag: Some(1), ..Default::default() };
+ let bytes = write_sample(&sample).expect("write sample");
+ // Verify bytes contain twrp box
+ assert!(bytes.windows(4).any(|w| w == b"twrp"));
+
+ let read_back = read_sample(&bytes).expect("read sample");
+ assert_eq!(read_back.wrap_flag, Some(1));
+}
+
+#[test]
+fn test_tx3g_config_roundtrip() {
+ let cfg = Tx3gConfig {
+ display_flags: 0x0000_0001,
+ horizontal_justification: 1,
+ vertical_justification: -1,
+ background_color: [10, 20, 30, 255],
+ default_text_box: TextBox { top: 0, left: 0, bottom: 480, right: 640 },
+ default_style: StyleRecord {
+ start_char: 0,
+ end_char: 0,
+ font_id: 1,
+ face_style_flags: STYLE_FLAG_BOLD,
+ font_size: 24,
+ text_color_rgba: [255, 255, 255, 255],
+ },
+ fonts: vec![(1, "Serif".to_string()), (2, "Sans".to_string())],
+ };
+
+ let bytes = cfg.write();
+ let parsed = Tx3gConfig::parse(&bytes).expect("parse config");
+ assert_eq!(parsed, cfg);
+}
+
+#[test]
+fn test_decode_timed_samples_to_document() {
+ let mut doc = Document::default();
+
+ let s1 = write_sample(&markup_to_sample("First cue")).expect("s1");
+ let s2 = write_sample(&markup_to_sample("Second cue")).expect("s2");
+
+ let samples = vec![(0u64, 1000u32, s1.as_slice()), (1000u64, 1500u32, s2.as_slice())];
+
+ decode_timed_samples(&mut doc, samples, 1000).expect("decode samples");
+
+ assert_eq!(doc.cues.len(), 2);
+ assert_eq!(doc.cues[0].start, Tick(0));
+ assert_eq!(doc.cues[0].end, Tick(TICKS_PER_SECOND));
+ assert_eq!(doc.cues[0].text, "First cue");
+
+ assert_eq!(doc.cues[1].start, Tick(TICKS_PER_SECOND));
+ assert_eq!(doc.cues[1].end, Tick((TICKS_PER_SECOND as f64 * 2.5) as i64));
+ assert_eq!(doc.cues[1].text, "Second cue");
+}
+
+#[test]
+fn test_hostile_inputs_never_panic() {
+ // Empty input
+ assert!(matches!(read_sample(&[]), Err(Error::Truncated)));
+
+ // 1-byte input
+ assert!(matches!(read_sample(&[0x00]), Err(Error::Truncated)));
+
+ // Length says 10 bytes, but slice ends
+ assert!(matches!(read_sample(&[0x00, 0x0A, 0x41]), Err(Error::Truncated)));
+
+ // Invalid UTF-8 without BOM
+ assert!(matches!(read_sample(&[0x00, 0x02, 0xFF, 0xFF]), Err(Error::InvalidText)));
+
+ // Box size < 8
+ let mut bad_box = Vec::new();
+ bad_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']);
+ bad_box.extend_from_slice(&[0x00, 0x00, 0x00, 0x04, b's', b't', b'y', b'l']);
+ assert!(matches!(read_sample(&bad_box), Err(Error::InvalidBox(_))));
+
+ // Box size exceeds remaining slice
+ let mut truncated_box = Vec::new();
+ truncated_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']);
+ truncated_box.extend_from_slice(&[0x00, 0x00, 0x01, 0x00, b's', b't', b'y', b'l']);
+ assert!(matches!(read_sample(&truncated_box), Err(Error::Truncated)));
+
+ // Unknown modifier boxes are safely ignored without error
+ let mut unknown_box = Vec::new();
+ unknown_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']);
+ unknown_box.extend_from_slice(&[0x00, 0x00, 0x00, 0x0C, b'f', b'a', b'k', b'e', 1, 2, 3, 4]);
+ let decoded = read_sample(&unknown_box).expect("unknown box should be skipped");
+ assert_eq!(decoded.text, "Test");
+}
+
+#[test]
+fn test_ffmpeg_mov_text_oracle() {
+ let Some(ff) = craft_media_testkit::ffmpeg() else { return };
+ let temp_dir = std::env::temp_dir().join("craft_mov_text_test");
+ let _ = std::fs::create_dir_all(&temp_dir);
+
+ // 1. Create SRT file with formatting: bold, italic, underline
+ let srt_path = temp_dir.join("input.srt");
+ let mp4_path = temp_dir.join("output.mp4");
+ let srt_content = "1\n00:00:01,000 --> 00:00:03,000\nHello World and Italic and Underline\n";
+ std::fs::write(&srt_path, srt_content).expect("write srt");
+
+ // Encode to MP4 with mov_text
+ let out = std::process::Command::new(&ff)
+ .args(["-y", "-i", srt_path.to_str().expect("path"), "-c:s", "mov_text", mp4_path.to_str().expect("path")])
+ .output();
+ let Ok(output) = out else { return };
+ if !output.status.success() {
+ return;
+ }
+
+ // Read MP4 through craft-media ISOBMFF demuxer
+ let mp4_bytes = std::fs::read(&mp4_path).expect("read mp4");
+ let mp4 = craft_media::isobmff::open(&mp4_bytes).expect("open mp4");
+
+ let (track_idx, track) =
+ mp4.tracks.iter().enumerate().find(|(_, t)| t.kind == craft_media::isobmff::TrackKind::Subtitle).expect("subtitle track");
+
+ // Decode all non-empty samples
+ let mut found_styled_cue = false;
+ for sample_idx in 0..track.samples.len() {
+ let sample_data = mp4.read_sample(&mp4_bytes, track_idx, sample_idx).expect("read sample");
+ let sample = read_sample(&sample_data).expect("read sample");
+ if !sample.text.is_empty() {
+ assert_eq!(sample.text, "Hello World and Italic and Underline");
+ let markup = sample_to_markup(&sample);
+ assert!(markup.contains("World"), "expected bold markup: {markup}");
+ assert!(markup.contains("Italic"), "expected italic markup: {markup}");
+ assert!(markup.contains("Underline"), "expected underline markup: {markup}");
+ found_styled_cue = true;
+ }
+ }
+ assert!(found_styled_cue, "expected to find styled subtitle sample in MP4");
+
+ // 2. Test roundtrip: our encoder writes sample bytes -> decode with FFmpeg to verify exact text & styles
+ let our_sample = markup_to_sample("Greeting: Craft Timed Text");
+ let encoded_bytes = write_sample(&our_sample).expect("write sample");
+
+ // Verify our sample reads back identically
+ let roundtripped = read_sample(&encoded_bytes).expect("read back");
+ assert_eq!(sample_to_markup(&roundtripped), "Greeting: Craft Timed Text");
+}
diff --git a/crates/csv/README.md b/crates/csv/README.md
index 8fd264d4c..7df204e10 100644
--- a/crates/csv/README.md
+++ b/crates/csv/README.md
@@ -11,7 +11,7 @@ mapping a SYLK sheet onto a document are the caller's work.
| Function | What it does |
|---|---|
| `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 |
-| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a 64 KiB sample; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon |
+| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon |
| `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text |
| `records(text, delim, quote, max_records, max_fields)` | the same, collected |
| `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing |
diff --git a/crates/csv/src/lib.rs b/crates/csv/src/lib.rs
index 395ad2152..f4a82f393 100644
--- a/crates/csv/src/lib.rs
+++ b/crates/csv/src/lib.rs
@@ -37,7 +37,7 @@ pub use decode::{decode_text, decode_utf8};
/// the same rules pick among the candidates whose records hold only their delimiters and
/// whitespace, such as an exported row of empty cells; a candidate that finds a record with
/// other text is left out of that pick. Comma is the fallback when neither pick finds one.
-/// Only the first 64 KiB are read. A record cut off at the end of that sample is left out,
+/// Only the first 65,536 characters are read. A record cut off at the end of that sample is left out,
/// except when no candidate finds coherent complete records with a delimiter in each. Then a candidate
/// that finds no complete record with other text counts the delimiters read so far in the first
/// such record, unless it found rows of its empty cells and that record has none of its
@@ -45,11 +45,8 @@ pub use decode::{decode_text, decode_utf8};
/// with one. When one of those candidates ends the sample inside a quoted field, each of them
/// counts only up to that field's opening quote.
pub fn sniff_delimiter(text: &str, quote: char) -> u8 {
- const SAMPLE_BYTES: usize = 64 * 1024;
- let mut sample_end = text.len().min(SAMPLE_BYTES);
- while !text.is_char_boundary(sample_end) {
- sample_end -= 1;
- }
+ const SAMPLE_CHARS: usize = 64 * 1024;
+ let sample_end = text.char_indices().nth(SAMPLE_CHARS).map_or(text.len(), |(at, _)| at);
let sample = &text[..sample_end];
let truncated = sample_end < text.len();
let mut scans = b"\t,;".map(|delimiter| scan_delimiter(sample, delimiter, quote));
@@ -441,6 +438,15 @@ mod tests {
assert_eq!(sniff_delimiter(&format!("a,b,c;\"hello,\";d\n{}", "x;y;z\n".repeat(12_000)), '"'), b';');
}
+ #[test]
+ fn delimiter_sniffing_samples_characters_not_bytes() {
+ // 30,000 three-byte characters are 90,000 bytes, more than 64 KiB.
+ assert_eq!(sniff_delimiter(&format!("{};b;c\n1;2;3\n", "€".repeat(30_000)), '"'), b';');
+ // The 65,536th character is in the sample and the 65,537th is not.
+ assert_eq!(sniff_delimiter(&format!("{};x\n1;2\n", "€".repeat(65_535)), '"'), b';');
+ assert_eq!(sniff_delimiter(&format!("{};x\n1;2\n", "€".repeat(65_536)), '"'), b',');
+ }
+
// A sheet whose only value is far down exports rows of empty cells that fill the whole sample.
#[test]
fn delimiter_sniffing_reads_a_sparse_semicolon_export() {
diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml
index 0daa6107f..bc859ea5f 100644
--- a/crates/develop/Cargo.toml
+++ b/crates/develop/Cargo.toml
@@ -14,5 +14,9 @@ workspace = true
craft-develop-model = { workspace = true }
serde = { workspace = true }
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+rayon = { workspace = true }
+
[dev-dependencies]
+craft-render-parity = { workspace = true }
proptest = { workspace = true }
diff --git a/crates/develop/README.md b/crates/develop/README.md
new file mode 100644
index 000000000..92f543eb3
--- /dev/null
+++ b/crates/develop/README.md
@@ -0,0 +1,43 @@
+# craft-develop
+
+The raw develop pipeline, CPU path: the shared pipeline of
+[#587](https://github.com/storytold/craft-libs/issues/587), moved from LightCraft one module at a time. No `unsafe`,
+no panics on hostile input, no file I/O, and it builds for `wasm32-unknown-unknown`.
+
+```toml
+craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "" }
+```
+
+## What is here
+
+| Module | From LightCraft (`a75497d6`) | Contents |
+|---|---|---|
+| `color::spline` | `crates/color/src/spline.rs` | `MonotoneCurve` (a tone curve through points that does not overshoot) and `Lut1`. |
+| `curve` | `crates/pipeline` | The parametric tone curve and its regions. |
+| `lut` | `crates/pipeline` | 3D lookup tables and the `.cube` reader. |
+| `inpaint` | `crates/inpaint` | Content-aware hole filling for spot removal: `complete` (multi-scale patch completion with PatchMatch) and `membrane_fill` (a smooth harmonic fill, its seed and fallback). Interleaved `f32` buffers of any channel count, a fixed-seed RNG, the same result on any number of threads. |
+
+## Parity with LightCraft
+
+Each module comes with a test that its output is LightCraft's at the base commit, compared with
+[`craft-render-parity`](../render-parity/README.md) at `Tolerance::BASELINE`. The expected pictures in
+`tests/fixtures/` were written by LightCraft's own crate at that commit, on the scene the test builds.
+
+Differences from LightCraft (ordinary-range output is covered by the baseline fixtures):
+
+- `inpaint::complete_with` returns `None` for a patch radius wider than the image before computing with it (LightCraft
+ reaches the same `None`, or overflows on a huge radius), returns an image with no pixels at once, and reports
+ `Cancelled` when any one poll said so, including a poll made on a worker thread.
+
+- `membrane_fill` scales extreme finite boundaries for the harmonic solve and bounds the result by those
+ boundaries, avoiding overflow in means and neighbour sums. Known pixels remain unchanged; ordinary
+ values take the original arithmetic path. This does not promise arbitrary extreme-value safety for
+ PatchMatch completion, which also computes squared costs and downsamples its input.
+- Membrane cell indices retain `usize` width. PatchMatch rejects grids whose signed search offsets,
+ summed-area counts or padded table cannot be represented; patch-area arithmetic no longer overflows
+ `i32`. An already-cancelled oversized-patch request returns `Cancelled`, not an unavailable-patch result.
+
+## Not here yet
+
+The rest of the pipeline: the rest of colour, raster, the sensor stage, raw loading and the render stages. No app uses this crate
+yet.
diff --git a/crates/develop/src/inpaint.rs b/crates/develop/src/inpaint.rs
new file mode 100644
index 000000000..7393ef4f3
--- /dev/null
+++ b/crates/develop/src/inpaint.rs
@@ -0,0 +1,132 @@
+//! Content-aware hole filling (inpainting) for the Remove tool.
+//!
+//! * [`complete`]: multi-scale patch-based completion (Wexler, Shechtman, Irani 2007) with the
+//! nearest-neighbour field found by PatchMatch (Barnes et al. 2009). See [`patchmatch`].
+//! * [`membrane_fill`]: smooth harmonic fill, used to seed the coarsest level and as a fallback.
+//!
+//! Buffers are interleaved `w × h × ch` floats in any colour model plus a `w × h` hole mask.
+//! Everything is deterministic (fixed-seed RNG, results independent of the thread count) and never
+//! panics on mismatched sizes: such calls return `None` or the input unchanged.
+//!
+//! Sources: C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman, *PatchMatch: A Randomized
+//! Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009; Y. Wexler, E. Shechtman,
+//! M. Irani, *Space-Time Completion of Video*, PAMI 2007.
+//!
+//! Ported from PhotoCraft (`crates/algo/src/inpaint.rs`, `poisson.rs`, MIT OR Apache-2.0, same
+//! organisation; see `NOTICE`).
+
+pub mod membrane;
+pub mod patchmatch;
+
+pub use membrane::membrane_fill;
+pub use patchmatch::{CompleteParams, complete, complete_with};
+
+/// A cancelled [`complete_with`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Cancelled;
+
+impl std::fmt::Display for Cancelled {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("cancelled")
+ }
+}
+
+impl std::error::Error for Cancelled {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn finite_extreme_membrane_boundaries_stay_finite() {
+ let img = [f32::MAX, 0.0, f32::MAX];
+ let out = membrane_fill(3, 1, 1, &img, &[false, true, false]);
+ assert_eq!(out, vec![f32::MAX; 3]);
+ assert_eq!(membrane_fill(3, 1, 1, &[-f32::MAX, 0.0, f32::MAX], &[false, true, false]), vec![-f32::MAX, 0.0, f32::MAX]);
+ // Also exercise the multigrid restriction and prolongation at extreme scale.
+ let hole: Vec = (0..256).map(|i| i % 16 > 0 && i % 16 < 15 && i / 16 > 0 && i / 16 < 15).collect();
+ assert_eq!(membrane_fill(16, 16, 1, &[f32::MAX; 256], &hole), vec![f32::MAX; 256]);
+ let img: Vec = (0..256).map(|i| if i % 16 < 8 { -f32::MAX } else { f32::MAX }).collect();
+ let out = membrane_fill(16, 16, 1, &img, &hole);
+ for ((&actual, &original), &unknown) in out.iter().zip(&img).zip(&hole) {
+ assert!(actual.is_finite() && (-f32::MAX..=f32::MAX).contains(&actual));
+ if !unknown {
+ assert_eq!(actual.to_bits(), original.to_bits());
+ }
+ }
+ }
+
+ #[test]
+ fn cancellation_precedes_an_oversized_patch_result() {
+ let mut hole = vec![false; 32 * 32];
+ hole[16 * 32 + 16] = true;
+ let p = CompleteParams { patch_radius: 16, ..CompleteParams::default() };
+ assert_eq!(complete_with(32, 32, 1, &[0.5; 32 * 32], &hole, &p, &|| true), Err(Cancelled));
+ }
+
+ #[test]
+ fn hostile_sizes_do_not_panic() {
+ assert_eq!(complete(4, 4, 3, &[0.0; 5], &[true; 16], &CompleteParams::default()), None);
+ assert_eq!(complete(4, 4, 0, &[], &[true; 16], &CompleteParams::default()), None);
+ assert_eq!(complete(usize::MAX, 2, 3, &[0.0; 6], &[true; 2], &CompleteParams::default()), None);
+ assert_eq!(membrane_fill(4, 4, 1, &[0.5; 3], &[true; 16]), vec![0.5; 3]);
+ // A hole covering everything: nothing to copy from.
+ assert_eq!(complete(16, 16, 1, &[0.5; 256], &[true; 256], &CompleteParams::default()), None);
+ // A tiny image smaller than a patch.
+ let _ = complete(2, 2, 1, &[0.5; 4], &[true, false, false, false], &CompleteParams::default());
+ }
+
+ #[test]
+ fn a_patch_radius_no_image_could_hold_finds_nothing_to_copy() {
+ let mut hole = vec![false; 32 * 32];
+ hole[16 * 32 + 16] = true;
+ for patch_radius in [16, usize::MAX / 2, usize::MAX] {
+ let p = CompleteParams { patch_radius, ..CompleteParams::default() };
+ assert_eq!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p), None, "radius {patch_radius}");
+ }
+ // Cancelled is still cancelled, not "nothing to copy from".
+ let p = CompleteParams { patch_radius: 16, ..CompleteParams::default() };
+ assert_eq!(complete_with(32, 32, 1, &[0.5; 32 * 32], &hole, &p, &|| true), Err(Cancelled));
+ // A radius the image has room for still fills.
+ let p = CompleteParams { patch_radius: 5, ..CompleteParams::default() };
+ assert!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p).is_some());
+ }
+
+ #[test]
+ fn an_image_with_no_pixels_is_returned_without_walking_its_rows() {
+ let p = CompleteParams::default();
+ assert_eq!(complete_with(0, usize::MAX, 1, &[], &[], &p, &|| false), Ok(Some(Vec::new())));
+ assert_eq!(complete_with(usize::MAX, 0, 3, &[], &[], &p, &|| false), Ok(Some(Vec::new())));
+ }
+
+ /// Whichever poll says "cancelled", and only that one, the call ends in `Err`: also when it was a
+ /// worker's poll, which can stop the worker but not return.
+ #[test]
+ fn one_cancelled_poll_anywhere_cancels_the_call() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let (w, h) = (48usize, 48usize);
+ let img: Vec = (0..w * h).map(|i| ((i % w) as f32 * 0.37).sin() * 0.5 + 0.5).collect();
+ let hole: Vec = (0..w * h).map(|i| (i % w).abs_diff(24) < 5 && (i / w).abs_diff(24) < 5).collect();
+ let p = CompleteParams::default();
+ let polls = AtomicUsize::new(0);
+ let count = || {
+ polls.fetch_add(1, Ordering::Relaxed);
+ false
+ };
+ assert!(matches!(complete_with(w, h, 1, &img, &hole, &p, &count), Ok(Some(_))));
+ let total = polls.load(Ordering::Relaxed);
+ assert!(total > 8, "the scene polls in the workers too: {total}");
+ for nth in 0..total {
+ let polls = AtomicUsize::new(0);
+ let once = || polls.fetch_add(1, Ordering::Relaxed) == nth;
+ assert_eq!(complete_with(w, h, 1, &img, &hole, &p, &once), Err(Cancelled), "poll {nth} of {total}");
+ }
+ }
+
+ #[test]
+ fn cancellation_stops() {
+ let img = vec![0.5f32; 64 * 64];
+ let hole: Vec = (0..64 * 64usize).map(|i| (i % 64).abs_diff(32) < 4 && (i / 64).abs_diff(32) < 4).collect();
+ assert_eq!(complete_with(64, 64, 1, &img, &hole, &CompleteParams::default(), &|| true), Err(Cancelled));
+ }
+}
diff --git a/crates/develop/src/inpaint/membrane.rs b/crates/develop/src/inpaint/membrane.rs
new file mode 100644
index 000000000..83f5d2882
--- /dev/null
+++ b/crates/develop/src/inpaint/membrane.rs
@@ -0,0 +1,255 @@
+//! Membrane (harmonic) fill: `Δv = 0` inside a hole with the known pixels as Dirichlet boundary.
+//! Used to initialise the coarsest level of [`crate::inpaint::complete`] and as its fallback.
+//!
+//! Sources: the membrane interpolant of P. Pérez, M. Gangnet, A. Blake, *Poisson Image Editing*,
+//! ACM SIGGRAPH 2003 (§3), solved by successive over-relaxation on the 4-connected grid, accelerated
+//! cascadically (solve on a half-resolution grid, prolong bilinearly, a few SOR sweeps per level).
+//! Ported from PhotoCraft's `algo::poisson` (MIT OR Apache-2.0).
+
+fn allocation_fits(len: usize) -> bool {
+ len.checked_mul(std::mem::size_of::()).is_some_and(|bytes| bytes <= isize::MAX as usize)
+}
+
+/// Convergence threshold (max per-sweep update) for the SOR sweeps.
+const TOL: f32 = 2e-5;
+/// SOR sweeps (cap) and relaxation factor on every level above the coarsest: tuned so a 96×72 disc
+/// is within ~1e-3 of a fully converged Gauss–Seidel solve (below one 8-bit step).
+const FINE_ITERS: usize = 30;
+const FINE_OMEGA: f32 = 1.7;
+
+/// Solve `Δv = 0` on `unknown` pixels with Dirichlet values from the known pixels of `v`
+/// (out-of-grid neighbours are ignored, i.e. a Neumann boundary). `v` holds the known values on
+/// entry and the solution on exit. Cascadic multigrid + SOR.
+pub(crate) fn solve_membrane(w: usize, h: usize, unknown: &[bool], v: &mut [f32]) {
+ if Some(unknown.len()) != w.checked_mul(h) || v.len() != unknown.len() {
+ return;
+ }
+ if !allocation_fits::<(usize, u8)>(unknown.iter().filter(|&&hole| hole).count()) {
+ return;
+ }
+ // Keep the ordinary path bit-for-bit unchanged. Extremely large finite boundaries can
+ // overflow even their mean or a four-neighbour sum; harmonic interpolation is linear,
+ // so solve those channels at unit scale instead. The final clamp enforces the harmonic
+ // maximum principle if the finite-iteration relaxation overshoots a boundary extremum.
+ let mut low = f32::INFINITY;
+ let mut high = f32::NEG_INFINITY;
+ for (&value, &hole) in v.iter().zip(unknown) {
+ if !hole {
+ if !value.is_finite() {
+ solve_rec(w, h, unknown, v, 0, &|| false);
+ return;
+ }
+ low = low.min(value);
+ high = high.max(value);
+ }
+ }
+ let scale = low.abs().max(high.abs());
+ let needs_scale = scale.is_finite() && f64::from(scale) > f64::from(f32::MAX) / v.len().max(16) as f64;
+ if needs_scale {
+ let mut normalized: Vec = v.iter().map(|&value| value / scale).collect();
+ solve_rec(w, h, unknown, &mut normalized, 0, &|| false);
+ for ((value, solved), &hole) in v.iter_mut().zip(normalized).zip(unknown) {
+ if hole {
+ *value = (f64::from(solved) * f64::from(scale)).clamp(f64::from(low), f64::from(high)) as f32;
+ }
+ }
+ } else {
+ solve_rec(w, h, unknown, v, 0, &|| false);
+ }
+}
+
+fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize, stop: &(dyn Fn() -> bool + Sync)) {
+ if stop() {
+ return;
+ }
+ let n_unknown = unknown.iter().filter(|u| **u).count();
+ if n_unknown == 0 {
+ return;
+ }
+ // Like the cell list below, this filtered collection must not grow geometrically.
+ let mut known = Vec::with_capacity(v.len() - n_unknown);
+ known.extend(v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x));
+ if known.is_empty() {
+ return; // nothing to interpolate from
+ }
+ if w >= 8 && h >= 8 && n_unknown > 64 && depth < 16 {
+ // Restrict: a coarse pixel is known if any of its children is (value = mean of known children).
+ let (cw, chh) = (w.div_ceil(2), h.div_ceil(2));
+ let mut cu = vec![true; cw * chh];
+ let mut cv = vec![0.0f32; cw * chh];
+ for cy in 0..chh {
+ for cx in 0..cw {
+ let (mut s, mut n) = (0.0f32, 0u32);
+ for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
+ let (x, y) = (cx * 2 + dx, cy * 2 + dy);
+ if x < w && y < h && !unknown[y * w + x] {
+ s += v[y * w + x];
+ n += 1;
+ }
+ }
+ if n > 0 {
+ cu[cy * cw + cx] = false;
+ cv[cy * cw + cx] = s / n as f32;
+ }
+ }
+ }
+ solve_rec(cw, chh, &cu, &mut cv, depth + 1, stop);
+ // Prolong: bilinear sample of the coarse solution as the initial guess.
+ for y in 0..h {
+ let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (chh - 1) as f32);
+ let y0 = fy.floor() as usize;
+ let y1 = (y0 + 1).min(chh - 1);
+ let ty = fy - y0 as f32;
+ for x in 0..w {
+ if !unknown[y * w + x] {
+ continue;
+ }
+ let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (cw - 1) as f32);
+ let x0 = fx.floor() as usize;
+ let x1 = (x0 + 1).min(cw - 1);
+ let tx = fx - x0 as f32;
+ let a = cv[y0 * cw + x0] + (cv[y0 * cw + x1] - cv[y0 * cw + x0]) * tx;
+ let b = cv[y1 * cw + x0] + (cv[y1 * cw + x1] - cv[y1 * cw + x0]) * tx;
+ v[y * w + x] = a + (b - a) * ty;
+ }
+ }
+ sor(w, h, unknown, v, FINE_ITERS, FINE_OMEGA, stop);
+ } else {
+ let mean = known.iter().sum::() / known.len() as f32;
+ for (x, u) in v.iter_mut().zip(unknown) {
+ if *u {
+ *x = mean;
+ }
+ }
+ sor(w, h, unknown, v, 2000, 1.85, stop);
+ }
+}
+
+/// SOR sweeps over the unknown pixels until the largest update drops below [`TOL`].
+fn sor(w: usize, h: usize, unknown: &[bool], v: &mut [f32], max_iter: usize, omega: f32, stop: &(dyn Fn() -> bool + Sync)) {
+ // Precompute the unknown pixels and which neighbours exist.
+ // The caller validated this exact count; reserve it before extend so geometric growth
+ // cannot round the allocation above the target's capacity limit.
+ let mut cells = Vec::with_capacity(unknown.iter().filter(|&&hole| hole).count());
+ cells.extend((0..w * h).filter(|&i| unknown[i]).map(|i| {
+ let (x, y) = (i % w, i / w);
+ let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3);
+ (i, m)
+ }));
+ for _ in 0..max_iter {
+ if stop() {
+ return;
+ }
+ let mut max_d = 0.0f32;
+ for &(i, m) in &cells {
+ let (s, n) = if m == 0b1111 {
+ (v[i - 1] + v[i + 1] + v[i - w] + v[i + w], 4.0)
+ } else {
+ let mut s = 0.0;
+ let mut n = 0.0;
+ if m & 1 != 0 {
+ s += v[i - 1];
+ n += 1.0;
+ }
+ if m & 2 != 0 {
+ s += v[i + 1];
+ n += 1.0;
+ }
+ if m & 4 != 0 {
+ s += v[i - w];
+ n += 1.0;
+ }
+ if m & 8 != 0 {
+ s += v[i + w];
+ n += 1.0;
+ }
+ if n == 0.0 {
+ continue;
+ }
+ (s, n)
+ };
+ let d = omega * (s / n - v[i]);
+ v[i] += d;
+ max_d = max_d.max(d.abs());
+ }
+ if max_d < TOL {
+ break;
+ }
+ }
+}
+
+/// Map `f` over the channels of an interleaved buffer as planar slices (parallel on native).
+fn per_channel(w: usize, h: usize, ch: usize, f: impl Fn(usize) -> Vec + Sync + Send) -> Vec {
+ #[cfg(not(target_arch = "wasm32"))]
+ let planes: Vec> = if w * h >= 64 * 64 {
+ use rayon::prelude::*;
+ (0..ch).into_par_iter().map(&f).collect()
+ } else {
+ (0..ch).map(&f).collect()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let planes: Vec> = (0..ch).map(&f).collect();
+ let mut out = vec![0.0f32; w * h * ch];
+ for (c, p) in planes.iter().enumerate() {
+ for (i, v) in p.iter().enumerate() {
+ out[i * ch + c] = *v;
+ }
+ }
+ out
+}
+
+/// Membrane fill (no source texture): harmonic interpolation of the known pixels into `hole`.
+/// `img` is interleaved `w × h × ch`, `hole` has `w × h` entries; on a size mismatch `img` comes back
+/// unchanged.
+pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) -> Vec {
+ if Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) {
+ return img.to_vec();
+ }
+ // no pixels: nothing to fill (and `ch` would otherwise size one plane per channel, whatever it claims)
+ if hole.is_empty() {
+ return img.to_vec();
+ }
+ // A valid input slice does not prove the wider index/plane vectors fit the target.
+ if !allocation_fits::>(ch) || !allocation_fits::<(usize, u8)>(hole.iter().filter(|&&hole| hole).count()) {
+ return img.to_vec();
+ }
+ per_channel(w, h, ch, |c| {
+ let mut v: Vec = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect();
+ solve_membrane(w, h, hole, &mut v);
+ v
+ })
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec {
+ (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect()
+ }
+
+ #[test]
+ fn auxiliary_vector_limits_are_checked_without_allocating() {
+ let max_cells = isize::MAX as usize / std::mem::size_of::<(usize, u8)>();
+ assert!(allocation_fits::<(usize, u8)>(max_cells));
+ assert!(!allocation_fits::<(usize, u8)>(max_cells + 1));
+ assert!(!allocation_fits::>(usize::MAX));
+ }
+
+ #[test]
+ fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() {
+ assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty());
+ assert!(membrane_fill(3, 0, usize::MAX / 2, &[], &[]).is_empty());
+ }
+
+ #[test]
+ fn membrane_reproduces_linear_boundary() {
+ // A linear function is harmonic: the solve must reproduce it exactly inside the hole.
+ let (w, h) = (80, 60);
+ let unknown = disc(w, h, 40.0, 30.0, 20.0);
+ let truth: Vec = (0..w * h).map(|i| 0.2 + 0.005 * (i % w) as f32 + 0.003 * (i / w) as f32).collect();
+ let mut v: Vec = truth.iter().zip(&unknown).map(|(t, u)| if *u { 0.0 } else { *t }).collect();
+ solve_membrane(w, h, &unknown, &mut v);
+ let err = v.iter().zip(&truth).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max);
+ assert!(err < 2e-3, "{err}");
+ }
+}
diff --git a/crates/develop/src/inpaint/patchmatch.rs b/crates/develop/src/inpaint/patchmatch.rs
new file mode 100644
index 000000000..54c49a267
--- /dev/null
+++ b/crates/develop/src/inpaint/patchmatch.rs
@@ -0,0 +1,653 @@
+//! Hole filling for Spot Healing: patch-based completion, proximity match and texture synthesis.
+//!
+//! * [`complete`], content-aware fill: the multi-scale "space-time completion" EM scheme of
+//! Y. Wexler, E. Shechtman, M. Irani, *Space-Time Completion of Video*, IEEE TPAMI 2007, with the
+//! nearest-neighbour field computed by C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman,
+//! *PatchMatch: A Randomized Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009
+//! (random init, propagation, exponentially shrinking random search). Each EM iteration finds, for
+//! every patch overlapping the hole, its most similar fully-known patch, then re-estimates hole
+//! pixels by a similarity-weighted vote of the overlapping matches. Coarse-to-fine over an image
+//! pyramid (the coarsest level is initialised by membrane interpolation), so large holes stay cheap.
+//! * [`best_offset`], proximity match: the single displacement whose surrounding ring best matches the
+//! ring around the hole (sum of squared differences), i.e. an automatic Healing Brush source.
+//! * [`synthesize`], create texture: patch-based texture synthesis in the style of A. Efros,
+//! W. Freeman, *Image Quilting for Texture Synthesis and Transfer*, SIGGRAPH 2001 (blocks picked from
+//! random candidates by overlap error, feathered overlap instead of a min-cut seam).
+//!
+//! Ported from PhotoCraft's `algo::inpaint` (MIT OR Apache-2.0); its proximity match and texture
+//! synthesis are left out.
+//!
+//! All functions take interleaved `w × h × ch` normalised floats (any colour model/depth) and a
+//! `w × h` hole mask, and return a full buffer equal to the input outside the hole. They are
+//! deterministic (fixed-seed hash RNG, results independent of thread count).
+
+use crate::inpaint::Cancelled;
+use crate::inpaint::membrane::membrane_fill;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+/// Below this many grid cells a level runs single-threaded (thread hand-off costs more than it saves).
+#[cfg(not(target_arch = "wasm32"))]
+const PAR_MIN: usize = 128 * 128;
+
+/// SplitMix64: tiny deterministic RNG.
+#[derive(Clone)]
+struct Rng(u64);
+impl Rng {
+ fn new(seed: u64) -> Self {
+ Rng(seed ^ 0x9E37_79B9_7F4A_7C15)
+ }
+ fn next(&mut self) -> u64 {
+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
+ let mut z = self.0;
+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ z ^ (z >> 31)
+ }
+ /// Uniform integer in `lo..=hi`.
+ fn range(&mut self, lo: i32, hi: i32) -> i32 {
+ if hi <= lo {
+ return lo;
+ }
+ lo + (self.next() % (hi - lo + 1) as u64) as i32
+ }
+}
+
+/// Parameters for [`complete`].
+#[derive(Clone, Debug, PartialEq)]
+pub struct CompleteParams {
+ /// Patch radius (patches are `2r+1` square).
+ pub patch_radius: usize,
+ /// EM iterations at the coarsest level (finer levels use fewer, down to `min_em_iters`).
+ pub em_iters: usize,
+ pub min_em_iters: usize,
+ /// PatchMatch passes per EM iteration.
+ pub pm_iters: usize,
+ /// Levels where the hole is wider than this (in that level's pixels) only *refine* the upsampled
+ /// match field (one local PatchMatch pass and one vote), which keeps big holes tractable: the
+ /// structure is decided at coarse scale, fine levels just add detail.
+ pub refine_extent: usize,
+ pub seed: u64,
+}
+
+impl Default for CompleteParams {
+ fn default() -> Self {
+ Self { patch_radius: 3, em_iters: 8, min_em_iters: 2, pm_iters: 2, refine_extent: 96, seed: 1 }
+ }
+}
+
+/// One pyramid level.
+#[derive(Clone)]
+struct Level {
+ w: usize,
+ h: usize,
+ img: Vec,
+ hole: Vec,
+}
+
+fn downsample(l: &Level, ch: usize) -> Level {
+ let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2));
+ let mut img = vec![0.0f32; w * h * ch];
+ let mut hole = vec![false; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ let mut n = 0.0f32;
+ let o = (y * w + x) * ch;
+ for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
+ let (sx, sy) = (x * 2 + dx, y * 2 + dy);
+ if sx >= l.w || sy >= l.h {
+ continue;
+ }
+ let si = sy * l.w + sx;
+ if l.hole[si] {
+ hole[y * w + x] = true;
+ } else {
+ for c in 0..ch {
+ img[o + c] += l.img[si * ch + c];
+ }
+ n += 1.0;
+ }
+ }
+ if n > 0.0 {
+ for c in 0..ch {
+ img[o + c] /= n;
+ }
+ }
+ }
+ }
+ Level { w, h, img, hole }
+}
+
+// Search offsets add/subtract a full image dimension in i32. Summed-area queries
+// add two u32 entries before subtracting. Both the padded table and the larger
+// per-pixel nearest-neighbour/valid-coordinate arrays must fit a Vec.
+fn supported_grid(w: usize, h: usize) -> bool {
+ let max_dimension = (i32::MAX / 2) as usize;
+ w <= max_dimension
+ && h <= max_dimension
+ && w.checked_mul(h).is_some_and(|n| n <= (u32::MAX / 2) as usize)
+ && w.checked_mul(h).and_then(|n| n.checked_mul(std::mem::size_of::<(i32, i32)>())).is_some_and(|bytes| bytes <= isize::MAX as usize)
+ && w.checked_add(1)
+ .and_then(|pw| h.checked_add(1).and_then(|ph| pw.checked_mul(ph)))
+ .and_then(|n| n.checked_mul(std::mem::size_of::()))
+ .is_some_and(|bytes| bytes <= isize::MAX as usize)
+}
+
+/// Reserve the already counted source centres exactly, then retain row-major order.
+fn source_centres(w: usize, valid: &[bool], count: usize, check: &impl Fn() -> Result<(), Cancelled>) -> Result, Cancelled> {
+ let mut centres = Vec::with_capacity(count);
+ for (i, &is_valid) in valid.iter().enumerate() {
+ if i % (w * 32) == 0 {
+ check()?;
+ }
+ if is_valid {
+ centres.push(((i % w) as i32, (i / w) as i32));
+ }
+ }
+ Ok(centres)
+}
+
+/// Summed-area table of a boolean grid (`(w+1) × (h+1)`).
+fn integral(w: usize, h: usize, m: &[bool]) -> Vec {
+ let mut s = vec![0u32; (w + 1) * (h + 1)];
+ for y in 0..h {
+ let mut row = 0u32;
+ for x in 0..w {
+ row += u32::from(m[y * w + x]);
+ s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row;
+ }
+ }
+ s
+}
+
+/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`.
+fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 {
+ let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
+ let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh));
+ if x1 <= x0 || y1 <= y0 {
+ return 0;
+ }
+ let w1 = gw + 1;
+ s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0]
+}
+
+fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> {
+ let mut b: Option<(usize, usize, usize, usize)> = None;
+ for y in 0..h {
+ for x in 0..w {
+ if hole[y * w + x] {
+ b = Some(match b {
+ None => (x, y, x + 1, y + 1),
+ Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)),
+ });
+ }
+ }
+ }
+ b
+}
+
+/// Per-level PatchMatch/EM state.
+struct Solver<'a> {
+ w: usize,
+ h: usize,
+ ch: usize,
+ r: i32,
+ img: &'a mut Vec,
+ hole: &'a [bool],
+ /// Valid source centres: the whole patch is inside the grid and contains no hole pixel.
+ valid: Vec,
+ valid_list: Vec<(i32, i32)>,
+ /// Target centres (patch overlaps the hole), row-major.
+ targets: Vec,
+ /// Cancellation: checked per row band; a cancelled solve's output is discarded.
+ ctl: &'a (dyn Fn() -> bool + Sync),
+}
+
+impl Solver<'_> {
+ #[inline]
+ fn is_valid(&self, x: i32, y: i32) -> bool {
+ x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize]
+ }
+
+ /// SSD between the (clipped) target patch at `t` and the source patch at `s`, per sample.
+ fn dist(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 {
+ let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r);
+ let diameter = f64::from(2 * r + 1);
+ let full = (diameter * diameter) as f32 * ch as f32;
+ let mut sum = 0.0f32;
+ let mut n = 0usize;
+ for dy in -r..=r {
+ let ty = t.1 + dy;
+ if ty < 0 || ty >= h {
+ continue;
+ }
+ let sy = s.1 + dy;
+ for dx in -r..=r {
+ let tx = t.0 + dx;
+ if tx < 0 || tx >= w {
+ continue;
+ }
+ let ti = (ty as usize * self.w + tx as usize) * ch;
+ let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch;
+ for c in 0..ch {
+ let d = self.img[ti + c] - self.img[si + c];
+ sum += d * d;
+ }
+ n += ch;
+ }
+ // Early out: the mean can only be ≥ sum / (full patch size).
+ if sum > cutoff * full {
+ return f32::INFINITY;
+ }
+ }
+ if n == 0 { f32::INFINITY } else { sum / n as f32 }
+ }
+
+ /// One PatchMatch pass over all target rows, in parallel bands (each band propagates within itself).
+ fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) {
+ const BAND: usize = 16;
+ let w = self.w;
+ let reverse = pass % 2 == 1;
+ let band_fn = |bi: usize, nn: &mut [(i32, i32)], co: &mut [f32]| {
+ if (self.ctl)() {
+ return;
+ }
+ let mut rng = Rng::new(seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40));
+ let y0 = bi * BAND;
+ let rows = nn.len() / w;
+ let step: i32 = if reverse { -1 } else { 1 };
+ for ry in 0..rows {
+ let ly = if reverse { rows - 1 - ry } else { ry };
+ let y = y0 + ly;
+ for rx in 0..w {
+ let x = if reverse { w - 1 - rx } else { rx };
+ let li = ly * w + x;
+ if !self.targets[y * w + x] {
+ continue;
+ }
+ let t = (x as i32, y as i32);
+ let (mut best, mut bc) = (nn[li], co[li]);
+ // Propagation from the already-visited neighbours (within this band).
+ let nx = x as i32 - step;
+ if nx >= 0 && (nx as usize) < w {
+ let c = nn[ly * w + nx as usize];
+ let cand = (c.0 + step, c.1);
+ if self.is_valid(cand.0, cand.1) && cand != best {
+ let d = self.dist(t, cand, bc);
+ if d < bc {
+ (best, bc) = (cand, d);
+ }
+ }
+ }
+ let nly = ly as i32 - step;
+ if nly >= 0 && (nly as usize) < rows {
+ let c = nn[nly as usize * w + x];
+ let cand = (c.0, c.1 + step);
+ if self.is_valid(cand.0, cand.1) && cand != best {
+ let d = self.dist(t, cand, bc);
+ if d < bc {
+ (best, bc) = (cand, d);
+ }
+ }
+ }
+ // Random search in exponentially shrinking windows.
+ let mut rad = search_radius;
+ while rad >= 1 {
+ let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad));
+ if self.is_valid(cand.0, cand.1) && cand != best {
+ let d = self.dist(t, cand, bc);
+ if d < bc {
+ (best, bc) = (cand, d);
+ }
+ }
+ rad /= 2;
+ }
+ nn[li] = best;
+ co[li] = bc;
+ }
+ }
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ if w * self.h >= PAR_MIN {
+ use rayon::prelude::*;
+ nnf.par_chunks_mut(BAND * w).zip(cost.par_chunks_mut(BAND * w)).enumerate().for_each(|(bi, (nn, co))| band_fn(bi, nn, co));
+ return;
+ }
+ for (bi, (nn, co)) in nnf.chunks_mut(BAND * w).zip(cost.chunks_mut(BAND * w)).enumerate() {
+ band_fn(bi, nn, co);
+ }
+ }
+
+ /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches.
+ fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) {
+ let (w, h, ch, r) = (self.w, self.h, self.ch, self.r);
+ // σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this).
+ let mut cs: Vec = cost.iter().zip(&self.targets).filter(|(c, t)| **t && c.is_finite()).map(|(c, _)| *c).collect();
+ let sigma2 = if cs.is_empty() {
+ 1.0
+ } else {
+ let k = (cs.len() * 3 / 4).min(cs.len() - 1);
+ let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b));
+ v.max(1e-6)
+ };
+ let img = &*self.img;
+ let row = |y: usize| -> Vec<(usize, Vec)> {
+ let mut out = Vec::new();
+ if (self.ctl)() {
+ return out;
+ }
+ for x in 0..w {
+ if !self.hole[y * w + x] {
+ continue;
+ }
+ let mut acc = vec![0.0f32; ch];
+ let mut wsum = 0.0f32;
+ for dy in -r..=r {
+ let ty = y as i32 + dy;
+ if ty < 0 || ty as usize >= h {
+ continue;
+ }
+ for dx in -r..=r {
+ let tx = x as i32 + dx;
+ if tx < 0 || tx as usize >= w {
+ continue;
+ }
+ let ti = ty as usize * w + tx as usize;
+ if !self.targets[ti] || !cost[ti].is_finite() {
+ continue;
+ }
+ let s = nnf[ti];
+ let (sx, sy) = (s.0 - dx, s.1 - dy);
+ let wt = (-cost[ti] / (2.0 * sigma2)).exp().max(1e-8);
+ let si = (sy as usize * w + sx as usize) * ch;
+ for c in 0..ch {
+ acc[c] += img[si + c] * wt;
+ }
+ wsum += wt;
+ }
+ }
+ if wsum > 0.0 {
+ acc.iter_mut().for_each(|v| *v /= wsum);
+ out.push((x, acc));
+ }
+ }
+ out
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ let rows: Vec)>> = if w * h >= PAR_MIN {
+ use rayon::prelude::*;
+ (0..h).into_par_iter().map(row).collect()
+ } else {
+ (0..h).map(row).collect()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let rows: Vec)>> = (0..h).map(row).collect();
+ for (y, r) in rows.into_iter().enumerate() {
+ for (x, v) in r {
+ self.img[(y * w + x) * ch..(y * w + x + 1) * ch].copy_from_slice(&v);
+ }
+ }
+ }
+}
+
+/// Content-aware completion of `hole` (see module docs). Returns `None` when there is no fully-known
+/// patch to copy from (the caller can fall back to [`membrane_fill`]).
+pub fn complete(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], p: &CompleteParams) -> Option> {
+ // Never cancelled, so never `Err`.
+ complete_with(w, h, ch, img, hole, p, &|| false).unwrap_or(None)
+}
+
+/// [`complete`] that can be cancelled (checked per EM iteration, PatchMatch pass and row band)
+/// (`cancelled` is polled per EM iteration, PatchMatch pass and row band): `Err(Cancelled)` once it
+/// returned `true`. `Ok(None)` also for mismatched buffer sizes or `ch == 0`.
+pub fn complete_with(
+ w: usize,
+ h: usize,
+ ch: usize,
+ img: &[f32],
+ hole: &[bool],
+ p: &CompleteParams,
+ cancelled: &(dyn Fn() -> bool + Sync),
+) -> Result