Merge current main into reviewed PSD stack [skip ci]

This commit is contained in:
FredApps
2026-11-19 12:35:06 +01:00
79 changed files with 13661 additions and 112 deletions
+15 -5
View File
@@ -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: ""
+1
View File
@@ -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 |
Generated
+16
View File
@@ -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"
+1
View File
@@ -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" }
+8
View File
@@ -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,
+2
View File
@@ -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`.
+7
View File
@@ -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"] }
+4
View File
@@ -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
+2
View File
@@ -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;
+871
View File
@@ -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 (`<b>...</b>`)
//! - `0x02`: Italic (`<i>...</i>`)
//! - `0x04`: Underline (`<u>...</u>`)
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<T> = std::result::Result<T, Error>;
/// 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<StyleRecord>,
/// 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<KaraokeEntry>)>,
/// Scroll delay in milliseconds from `dlay`.
pub scroll_delay: Option<u32>,
/// Hypertext links from `href` boxes.
pub hypertext: Vec<HyperText>,
/// Text box override from `tbox`.
pub text_box: Option<TextBox>,
/// 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<u8>,
}
/// 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<Self> {
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<u8> {
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<TextSample> {
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<String> {
if bytes.len() >= 2 {
if bytes[0] == 0xFE && bytes[1] == 0xFF {
// UTF-16 BE
let u16s: Vec<u16> = 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<u16> = 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<Vec<u8>> {
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("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
_ => out.push(ch),
}
}
/// Convert a [`TextSample`] into HTML-style formatted markup (`<b>`, `<i>`, `<u>`, `<font color="...">`).
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<char> = sample.text.chars().collect();
let n = chars.len();
if n == 0 {
return String::new();
}
let mut starts: std::collections::HashMap<u16, Vec<&StyleRecord>> = std::collections::HashMap::new();
let mut ends: std::collections::HashMap<u16, Vec<&StyleRecord>> = 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!(
"<font color=\"#{:02x}{:02x}{:02x}\">",
st.text_color_rgba[0], st.text_color_rgba[1], st.text_color_rgba[2]
));
}
if st.is_bold() {
out.push_str("<b>");
}
if st.is_italic() {
out.push_str("<i>");
}
if st.is_underline() {
out.push_str("<u>");
}
}
}
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("</u>");
}
if st.is_italic() {
out.push_str("</i>");
}
if st.is_bold() {
out.push_str("</b>");
}
let has_color = st.text_color_rgba != [255, 255, 255, 255];
if has_color {
out.push_str("</font>");
}
}
}
}
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 (`<b>`, `<i>`, `<u>`, `<font color="...">`) 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<char> = Vec::with_capacity(markup.len());
let mut char_styles: Vec<CharFormatting> = 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 `<font color="...">` 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<Item = (u64, u32, &'a [u8])>,
{
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<Item = (u64, u32, &'a [u8])>,
{
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(())
}
+2
View File
@@ -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;
+349
View File
@@ -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<u8> = 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<u8> = 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 <b>Bold</b> and <i>Italic</i> and <u>Underline</u> and <font color=\"#ff0000\">Red</font>";
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 = "<b>A<i>B</i>C</b>";
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 &amp; <b>B &lt; C</b>";
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 &amp; <b>B &lt; C</b>");
}
#[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 <b>cue</b>")).expect("s1");
let s2 = write_sample(&markup_to_sample("Second <i>cue</i>")).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 <b>cue</b>");
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 <i>cue</i>");
}
#[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 <b>World</b> and <i>Italic</i> and <u>Underline</u>\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("<b>World</b>"), "expected bold markup: {markup}");
assert!(markup.contains("<i>Italic</i>"), "expected italic markup: {markup}");
assert!(markup.contains("<u>Underline</u>"), "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: <b>Craft</b> <i>Timed</i> <u>Text</u>");
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: <b>Craft</b> <i>Timed</i> <u>Text</u>");
}
+1 -1
View File
@@ -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 |
+12 -6
View File
@@ -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() {
+4
View File
@@ -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 }
+43
View File
@@ -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 = "<commit>" }
```
## 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.
+132
View File
@@ -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<bool> = (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<f32> = (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<f32> = (0..w * h).map(|i| ((i % w) as f32 * 0.37).sin() * 0.5 + 0.5).collect();
let hole: Vec<bool> = (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<bool> = (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));
}
}
+255
View File
@@ -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<T>(len: usize) -> bool {
len.checked_mul(std::mem::size_of::<T>()).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<f32> = 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::<f32>() / 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<f32> + Sync + Send) -> Vec<f32> {
#[cfg(not(target_arch = "wasm32"))]
let planes: Vec<Vec<f32>> = 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<Vec<f32>> = (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<f32> {
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::<Vec<f32>>(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<f32> = (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<bool> {
(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::<Vec<f32>>(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<f32> = (0..w * h).map(|i| 0.2 + 0.005 * (i % w) as f32 + 0.003 * (i / w) as f32).collect();
let mut v: Vec<f32> = 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}");
}
}
+653
View File
@@ -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<f32>,
hole: Vec<bool>,
}
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::<u32>()))
.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<Vec<(i32, i32)>, 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<u32> {
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<f32>,
hole: &'a [bool],
/// Valid source centres: the whole patch is inside the grid and contains no hole pixel.
valid: Vec<bool>,
valid_list: Vec<(i32, i32)>,
/// Target centres (patch overlaps the hole), row-major.
targets: Vec<bool>,
/// 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<f32> = 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<f32>)> {
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<Vec<(usize, Vec<f32>)>> = 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<Vec<(usize, Vec<f32>)>> = (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<Vec<f32>> {
// 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<Option<Vec<f32>>, Cancelled> {
// The workers poll `cancelled` too and can only stop early, not return an error. One `true` from it,
// wherever it was seen, is kept, so the next check out here ends the call and a half-finished pass
// is never returned as a result.
let seen = AtomicBool::new(false);
let cancelled: &(dyn Fn() -> bool + Sync) = &|| {
if !seen.load(Ordering::Relaxed) && cancelled() {
seen.store(true, Ordering::Relaxed);
}
seen.load(Ordering::Relaxed)
};
let check = || if cancelled() { Err(Cancelled) } else { Ok(()) };
if ch == 0 || Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) {
return Ok(None);
}
// No pixels (a zero width or height, whatever the other is): nothing to scan and nothing to fill.
if hole.is_empty() {
return Ok(Some(img.to_vec()));
}
if !supported_grid(w, h) {
check()?;
return Ok(None);
}
let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Ok(Some(img.to_vec())) };
let r = p.patch_radius.max(1);
// A patch wider than the image has no place to be copied from, which is the `None` the search below
// would reach anyway. Said here, before `2 * r + 1` and `r as i32` can overflow on an absurd radius.
if r > (w.min(h) - 1) / 2 {
check()?;
return Ok(None);
}
let psz = 2 * r + 1;
// Pyramid: shrink until the hole is a few patches across.
let mut levels = vec![Level { w, h, img: img.to_vec(), hole: hole.to_vec() }];
let mut ext = (bx1 - bx0).max(by1 - by0);
let mut exts = vec![ext];
while let Some(l) = levels.last() {
check()?;
if ext <= 2 * psz || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz {
break;
}
let d = downsample(l, ch);
levels.push(d);
ext = ext.div_ceil(2);
exts.push(ext);
}
let nlev = levels.len();
let mut nnf: Vec<(i32, i32)> = Vec::new();
let mut prev: Option<(usize, usize, Vec<f32>)> = None;
for li in (0..nlev).rev() {
check()?;
let Level { w: lw, h: lh, img: mut limg, hole: lhole } = levels[li].clone();
// Initialise the hole: membrane at the coarsest level, upsampled result elsewhere.
match &prev {
None => limg = membrane_fill(lw, lh, ch, &limg, &lhole),
Some((pw, ph, pimg)) => {
for y in 0..lh {
for x in 0..lw {
if lhole[y * lw + x] {
let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1));
let (d, s) = ((y * lw + x) * ch, (sy * pw + sx) * ch);
limg[d..d + ch].copy_from_slice(&pimg[s..s + ch]);
}
}
}
}
}
let ri = r as i32;
let hs = integral(lw, lh, &lhole);
let mut valid = vec![false; lw * lh];
let mut valid_count = 0;
let mut targets = vec![false; lw * lh];
for y in 0..lh as i32 {
if y % 32 == 0 {
check()?;
}
for x in 0..lw as i32 {
let cnt = window_count(&hs, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1);
let inside = x >= ri && y >= ri && x + ri < lw as i32 && y + ri < lh as i32;
let i = y as usize * lw + x as usize;
if inside && cnt == 0 {
valid[i] = true;
valid_count += 1;
}
targets[i] = cnt > 0;
}
}
if valid_count == 0 {
if li == 0 {
return Ok(None);
}
prev = Some((lw, lh, limg));
nnf.clear();
continue;
}
let valid_list = source_centres(lw, &valid, valid_count, &check)?;
let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets, ctl: cancelled };
// NNF init: upsampled from the coarser level where possible, random otherwise.
let mut rng = Rng::new(p.seed ^ (li as u64) << 20);
let pw_prev = prev.as_ref().map_or(0, |p| p.0);
let old = std::mem::take(&mut nnf);
let mut new_nnf = vec![(0i32, 0i32); lw * lh];
for y in 0..lh {
if y % 32 == 0 {
check()?;
}
for x in 0..lw {
if !solver.targets[y * lw + x] {
continue;
}
let mut cand = None;
if !old.is_empty() && pw_prev > 0 {
let pi = (y / 2) * pw_prev + (x / 2);
if let Some(&(sx, sy)) = old.get(pi) {
let c = (sx * 2 + (x % 2) as i32, sy * 2 + (y % 2) as i32);
if solver.is_valid(c.0, c.1) {
cand = Some(c);
}
}
}
new_nnf[y * lw + x] = cand.unwrap_or_else(|| solver.valid_list[(rng.next() % solver.valid_list.len() as u64) as usize]);
}
}
nnf = new_nnf;
let refine_only = li + 1 < nlev && exts[li] > p.refine_extent;
let em = if li + 1 == nlev {
p.em_iters
} else if refine_only {
1
} else {
(p.em_iters >> (nlev - 1 - li)).max(p.min_em_iters)
};
let pm_iters = if refine_only { 1 } else { p.pm_iters };
let full_search = (lw.max(lh)) as i32;
let mut cost = vec![f32::INFINITY; lw * lh];
for it in 0..em {
// Costs change as hole pixels are re-estimated: refresh before each PatchMatch.
for (i, c) in cost.iter_mut().enumerate() {
if i % (lw * 32).max(1) == 0 {
check()?;
}
if solver.targets[i] {
*c = solver.dist(((i % lw) as i32, (i / lw) as i32), nnf[i], f32::INFINITY);
}
}
// Wide random search on coarse levels / first iteration, local refinement afterwards.
let radius = if refine_only {
2
} else if li + 1 == nlev || it == 0 {
full_search
} else {
(4 * psz).min(full_search as usize) as i32
};
for pass in 0..pm_iters {
check()?;
solver.patchmatch(&mut nnf, &mut cost, pass + it * pm_iters, p.seed.wrapping_add((li * 1000 + it) as u64), radius);
}
check()?;
solver.vote(&nnf, &cost);
check()?;
}
prev = Some((lw, lh, limg));
}
Ok(prev.map(|(_, _, img)| img))
}
/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the
/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the
#[cfg(test)]
mod tests {
use super::*;
/// Smooth gradient plus deterministic fine noise.
fn texture(w: usize, h: usize) -> Vec<f32> {
let mut rng = Rng::new(7);
(0..w * h)
.flat_map(|i| {
let (x, y) = ((i % w) as f32, (i / w) as f32);
let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02;
[0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n]
})
.collect()
}
fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec<bool> {
(0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect()
}
fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 {
let (mut e, mut n) = (0.0f32, 0);
for (i, hh) in hole.iter().enumerate() {
if *hh {
for c in 0..ch {
e += (a[i * ch + c] - b[i * ch + c]).powi(2);
n += 1;
}
}
}
(e / n as f32).sqrt()
}
#[test]
fn grid_limits_reject_narrowing_and_integral_overflow_without_allocating() {
assert!(supported_grid(32, 32));
assert!(supported_grid(16_384, 8_192));
assert_eq!(supported_grid(20_000, 20_000), usize::BITS > 32);
assert!(!supported_grid(i32::MAX as usize, 1));
assert!(!supported_grid(65_536, 65_536));
assert!(!supported_grid(usize::MAX, usize::MAX));
}
#[test]
fn completion_fills_blemish_from_texture() {
let (w, h, ch) = (96, 96, 3);
let clean = texture(w, h);
let hole = disc(w, h, 48.0, 48.0, 9.0);
let mut dirty = clean.clone();
for (i, hh) in hole.iter().enumerate() {
if *hh {
dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]);
}
}
let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap();
let before = hole_rmse(&dirty, &clean, &hole, ch);
let after = hole_rmse(&out, &clean, &hole, ch);
assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}");
// Outside the hole untouched.
assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b));
// Deterministic.
assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap());
}
#[test]
fn completion_continues_structure() {
// Vertical stripes: the filled hole should keep the stripes (not a blur).
let (w, h, ch) = (80, 80, 1);
let clean: Vec<f32> = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect();
let hole = disc(w, h, 40.0, 40.0, 7.0);
let dirty: Vec<f32> = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect();
let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap();
let err = hole_rmse(&out, &clean, &hole, ch);
assert!(err < 0.15, "{err}");
}
}
+5 -1
View File
@@ -1,5 +1,9 @@
//! Raw develop pipeline (CPU path), extracted from LightCraft.
//! The raw develop pipeline, CPU path: the shared pipeline of craft-libs#587, moved from LightCraft one module at a
//! time. See the README for what is here so far.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod color;
pub mod curve;
pub mod inpaint;
pub mod lut;
Binary file not shown.
Binary file not shown.
+60
View File
@@ -0,0 +1,60 @@
//! Parity with LightCraft (craft-libs#587): the hole fills of one scene are what `lightcraft-inpaint` at
//! `a75497d6` gave for it. The fixtures in `tests/fixtures/` are that crate's `complete` (default parameters) and
//! `membrane_fill` on [`scene`], three little-endian `f32` per pixel, row by row.
#![allow(clippy::unwrap_used, clippy::expect_used)]
use craft_develop::inpaint::{CompleteParams, complete, membrane_fill};
use craft_render_parity::{Image, Tolerance, compare};
const W: usize = 96;
const H: usize = 72;
/// A ramp with stripes and a weave, and two holes in it: a rectangle and a disc.
fn scene() -> (Vec<f32>, Vec<bool>) {
let mut img = Vec::with_capacity(W * H * 3);
let mut hole = Vec::with_capacity(W * H);
for y in 0..H {
for x in 0..W {
let (fx, fy) = (x as f32 / W as f32, y as f32 / H as f32);
let stripe = if (x / 6 + y / 9) % 2 == 0 { 0.12 } else { 0.0 };
let weave = if (x * 3 + y * 5) % 7 < 2 { 0.05 } else { 0.0 };
img.extend([0.15 + 0.6 * fx + stripe, 0.2 + 0.5 * fy + weave, 0.7 - 0.4 * fx * fy + stripe * 0.5]);
let (dx, dy) = (x as i32 - 60, y as i32 - 44);
hole.push((20..38).contains(&x) && (14..30).contains(&y) || dx * dx + dy * dy <= 81);
}
}
(img, hole)
}
fn fixture(bytes: &[u8]) -> Vec<f32> {
bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect()
}
fn assert_parity(expected: &[u8], actual: &[f32]) {
let expected = fixture(expected);
let report = compare(&Image::new(W as u32, H as u32, &expected).unwrap(), &Image::new(W as u32, H as u32, actual).unwrap()).unwrap();
assert!(report.within(&Tolerance::BASELINE), "{report}: {:?}", report.exceeded(&Tolerance::BASELINE));
}
#[test]
fn completion_matches_lightcraft() {
let (img, hole) = scene();
let filled = complete(W, H, 3, &img, &hole, &CompleteParams::default()).expect("a completion");
assert_ne!(filled, img, "the holes were filled");
assert_parity(include_bytes!("fixtures/inpaint-complete.f32le"), &filled);
}
#[test]
fn membrane_fill_matches_lightcraft() {
let (img, hole) = scene();
assert_parity(include_bytes!("fixtures/inpaint-membrane.f32le"), &membrane_fill(W, H, 3, &img, &hole));
}
/// The comparison can fail: the unfilled scene is not within tolerance of the filled one.
#[test]
fn the_unfilled_scene_is_not_at_parity() {
let (img, _) = scene();
let expected = fixture(include_bytes!("fixtures/inpaint-complete.f32le"));
let report = compare(&Image::new(W as u32, H as u32, &expected).unwrap(), &Image::new(W as u32, H as u32, &img).unwrap()).unwrap();
assert!(!report.within(&Tolerance::BASELINE));
}
+10 -1
View File
@@ -26,8 +26,17 @@ fn known_formats_separate_build_disabled_and_unsupported_operations() {
#[cfg(not(feature = "raster-codecs"))]
assert_eq!(jpeg.read, Availability::BuildDisabled);
// Whether this build reads JPEG XL is craft-image-codecs' `jxl` feature to decide, and this
// crate cannot see that through `cfg!`: a workspace build turns it on without this crate
// selecting anything, which is how a plain equality here failed every `--all-features` gate.
// The codec's own answer is the one to check against, so a wrong read status is still caught.
#[cfg(feature = "raster-codecs")]
assert!(matches!(Format::Jxl.capabilities().read, Availability::Available | Availability::Unsupported));
{
let codec = Format::Jxl.raster_codec();
assert!(codec.is_some(), "JXL is handled by craft-image-codecs and must map to one of its formats");
let expected = if codec.is_some_and(|codec| codec.caps().read) { Availability::Available } else { Availability::Unsupported };
assert_eq!(Format::Jxl.capabilities().read, expected);
}
#[cfg(not(feature = "raster-codecs"))]
assert_eq!(Format::Jxl.capabilities().read, Availability::Unsupported);
#[cfg(not(feature = "raster-codecs"))]
+11
View File
@@ -924,6 +924,17 @@ mod tests {
assert_eq!(jpeg_frame(&file), Some(JpegFrame::Ls));
}
#[test]
fn a_walk_that_found_another_frame_header_stays_at_it() {
// SOI, a comment with two bytes of text, then a baseline frame header.
let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xC0, 0, 11];
let mut pos = 0;
assert_eq!(jpeg_frame_from(&file, &mut pos), Some(JpegFrame::Other));
assert_eq!(pos, 8);
assert_eq!(jpeg_frame_from(&file, &mut pos), Some(JpegFrame::Other));
assert_eq!(pos, 8);
}
#[test]
fn interleaved_scans_and_tables_are_unsupported() {
let img = image(8, 4, ChannelLayout::Rgb, false, 2);
+2 -1
View File
@@ -108,7 +108,8 @@ pub struct DecodeOptions {
pub limits: Limits,
/// Keep the pixels as stored instead of applying the EXIF / TIFF
/// orientation (by default they are turned upright and the metadata's
/// orientation is rewritten to 1).
/// orientation is rewritten to 1). JPEG XL ignores this: `craft-jxl` applies the codestream's
/// orientation while rendering, so a JPEG XL image is always upright with orientation 1.
pub keep_orientation: bool,
}
+7 -14
View File
@@ -422,17 +422,13 @@ fn a_stuffed_zero_where_a_marker_should_be_is_jpeg() {
}
#[test]
fn a_detector_that_found_a_jpeg_frame_does_not_walk_again() {
fn a_detector_that_found_a_jpeg_frame_keeps_answering_jpeg() {
// SOI, a comment with two bytes of text, then a baseline frame header.
let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xC0, 0, 11];
let mut detector = PrefixDetector::new();
assert_eq!(detector.detect(&file[..10]), Detection::Format(Format::Jpeg));
assert_eq!(detector.detect(&file), detect_prefix(&file));
assert_eq!(detector.detect(&file), Detection::Format(Format::Jpeg));
// With an SOF55 marker where the comment marker was, a walk from the SOI finds JPEG-LS. The
// detector starts at the baseline frame header it stopped at and still answers JPEG.
let mut changed = file;
changed[3] = 0xF7;
assert_eq!(detect_prefix(&changed), Detection::Format(Format::JpegLs));
assert_eq!(detector.detect(&changed), Detection::Format(Format::Jpeg));
}
#[test]
@@ -440,14 +436,11 @@ fn a_detector_keeps_its_place_between_calls() {
// SOI, a comment with two bytes of text, then an SOF55 frame header.
let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xF7, 0, 11];
let mut detector = PrefixDetector::new();
assert_eq!(detector.detect(&file[..5]), Detection::NeedBytes(6));
assert_eq!(detector.detect(&file[..9]), Detection::NeedBytes(10));
// The next call starts at the frame header's marker and does not read the bytes before it
// again: with them cleared, the detector still finds JPEG-LS, while a walk from the start
// finds no SOI.
let mut cleared = file;
cleared[..8].fill(0);
assert_ne!(detect_prefix(&cleared), Detection::Format(Format::JpegLs));
assert_eq!(detector.detect(&cleared), Detection::Format(Format::JpegLs));
// Each call extends the previous prefix, and the answer matches a walk from the SOI.
assert_eq!(detector.detect(&file), detect_prefix(&file));
assert_eq!(detect_prefix(&file), Detection::Format(Format::JpegLs));
}
#[cfg(feature = "sunraster")]
+97 -28
View File
@@ -47,26 +47,66 @@ fn box_at(bytes: &[u8], at: usize) -> Option<BoxSpan> {
Some(BoxSpan { start: at, header, end: end.min(bytes.len()) })
}
/// Every box of the container, in order, up to the first one that cannot be read.
fn boxes(bytes: &[u8]) -> Vec<BoxSpan> {
let mut found = Vec::new();
let mut at = 0;
while let Some(span) = box_at(bytes, at) {
at = span.end;
found.push(span);
if at >= bytes.len() {
break;
}
}
found
/// The boxes of the container, in order, up to the first one that cannot be read. One box at a
/// time: a file of eight-byte boxes must not cost three times its size in spans.
struct Boxes<'a> {
bytes: &'a [u8],
at: usize,
done: bool,
}
/// Inflates `compressed`, or `None` when it is broken or would pass `cap` bytes.
pub(crate) fn inflate_capped(compressed: &[u8], cap: usize) -> Option<Vec<u8>> {
impl<'a> Boxes<'a> {
fn new(bytes: &'a [u8]) -> Self {
Self { bytes, at: 0, done: false }
}
/// Where the next box would start: the end of the last one read, or 0 before the first.
fn end(&self) -> usize {
self.at
}
}
impl Iterator for Boxes<'_> {
type Item = BoxSpan;
fn next(&mut self) -> Option<BoxSpan> {
if self.done {
return None;
}
let Some(span) = box_at(self.bytes, self.at) else {
self.done = true;
return None;
};
self.at = span.end;
self.done = self.at >= self.bytes.len();
Some(span)
}
}
/// Whether the Brotli stream header asks for a window of at most 16 MiB. The decoder reserves its
/// whole ring buffer up front, outside the output cap, so a header that declares a large window
/// (RFC 7932 §9.1 and the large-window extension) could ask for a gigabyte from a few bytes.
fn window_is_small(compressed: &[u8]) -> bool {
let Some(first) = compressed.first() else { return true };
let wide = first & 1 == 1;
let long_form = (first >> 1) & 7;
let short_form = (first >> 4) & 7;
!(wide && long_form == 0 && short_form == 1)
}
/// Inflates `compressed`. `Err` carries how many bytes were produced before it was refused
/// (broken stream, over `cap`, or a large window), so the caller can charge the work to its budget.
pub(crate) fn inflate_capped(compressed: &[u8], cap: usize) -> Result<Vec<u8>, usize> {
if !window_is_small(compressed) {
return Err(0);
}
let mut out = Vec::new();
let limit = u64::try_from(cap).ok()?.checked_add(1)?;
brotli_decompressor::Decompressor::new(compressed, 4096).take(limit).read_to_end(&mut out).ok()?;
(out.len() <= cap).then_some(out)
let limit = u64::try_from(cap).ok().and_then(|c| c.checked_add(1)).ok_or(0_usize)?;
let read = brotli_decompressor::Decompressor::new(compressed, 4096).take(limit).read_to_end(&mut out);
if read.is_err() || out.len() > cap {
return Err(out.len());
}
Ok(out)
}
/// A plain box of type `kind` holding `data`.
@@ -92,9 +132,18 @@ fn unwrap_brob(span: &BoxSpan, bytes: &[u8], budget: &mut usize) -> Option<Vec<u
if inner == BROB {
return None;
}
let inflated = inflate_capped(compressed, *budget)?;
*budget -= inflated.len();
Some(plain_box(inner, &inflated))
match inflate_capped(compressed, *budget) {
Ok(inflated) => {
*budget -= inflated.len();
Some(plain_box(inner, &inflated))
}
Err(produced) => {
// The work was done even though the box is dropped: charge it, so a file of many
// over-cap streams cannot make the decoder inflate the whole budget once per box.
*budget = budget.saturating_sub(produced);
None
}
}
}
/// `bytes` with every `brob` box inflated, `cap` bytes in all (or removed), or `None` when the file is
@@ -103,20 +152,20 @@ pub(crate) fn sanitize(bytes: &[u8], cap: usize) -> Option<Vec<u8>> {
if !bytes.starts_with(SIGNATURE) {
return None;
}
let spans = boxes(bytes);
if !spans.iter().any(|s| s.kind(bytes) == BROB) {
if !Boxes::new(bytes).any(|s| s.kind(bytes) == BROB) {
return None;
}
let mut budget = cap;
let mut out = Vec::with_capacity(bytes.len());
for span in &spans {
let mut walk = Boxes::new(bytes);
for span in walk.by_ref() {
match (span.kind(bytes) == BROB, bytes.get(span.start..span.end)) {
(true, _) => out.extend(unwrap_brob(span, bytes, &mut budget).unwrap_or_default()),
(true, _) => out.extend(unwrap_brob(&span, bytes, &mut budget).unwrap_or_default()),
(false, Some(whole)) => out.extend_from_slice(whole),
(false, None) => {}
}
}
out.extend_from_slice(bytes.get(spans.last().map_or(0, |s| s.end)..).unwrap_or(&[]));
out.extend_from_slice(bytes.get(walk.end()..).unwrap_or(&[]));
Some(out)
}
@@ -146,9 +195,9 @@ mod tests {
#[test]
fn a_bomb_passes_the_cap_and_a_real_packet_does_not() {
assert_eq!(inflate_capped(&EXIF_BR, BROB_CAP).as_deref(), Some(&b"II*\0\x08\0\0\0hello exif"[..]));
assert!(inflate_capped(&BOMB_BR, BROB_CAP).is_none());
assert!(inflate_capped(&BOMB_BR[..20], BROB_CAP).is_none(), "a cut stream is not a result");
assert_eq!(inflate_capped(&EXIF_BR, BROB_CAP).as_deref(), Ok(&b"II*\0\x08\0\0\0hello exif"[..]));
assert!(inflate_capped(&BOMB_BR, BROB_CAP).is_err());
assert!(inflate_capped(&BOMB_BR[..20], BROB_CAP).is_err(), "a cut stream is not a result");
}
#[test]
@@ -188,6 +237,26 @@ mod tests {
assert!(out.len() < SIGNATURE.len() + 2 * (exif + 8) + 1);
}
#[test]
fn an_over_cap_box_uses_up_the_budget_of_the_boxes_after_it() {
let boxes = [brob_of(b"xml ", &BOMB_BR), brob_of(b"Exif", &EXIF_BR)];
assert_eq!(sanitize(&container(&boxes), 64).unwrap(), container(&[]), "the later packet is dropped too");
}
#[test]
fn a_stream_that_declares_a_large_window_is_refused_before_decoding() {
// WBITS bits 1, 000, 001: the large-window marker.
assert_eq!(inflate_capped(&[0x11, 0, 0, 0], BROB_CAP), Err(0));
assert!(window_is_small(&EXIF_BR) && window_is_small(&BOMB_BR) && window_is_small(&[]));
}
#[test]
fn a_long_run_of_tiny_boxes_is_walked_without_a_list_of_spans() {
let boxes: Vec<Vec<u8>> = (0..1000).map(|_| plain_box(b"free", b"")).collect();
assert!(sanitize(&container(&boxes), BROB_CAP).is_none(), "no brob box: used as it is");
assert_eq!(Boxes::new(&container(&boxes)).count(), 1001, "the signature box and the 1000 others");
}
#[test]
fn a_cut_off_file_keeps_its_tail_verbatim() {
let mut file = container(&[brob_of(b"Exif", &EXIF_BR)]);
+11 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-media"
description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, and Ogg, AVI and MPEG-TS/PS demuxers."
description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, an MPEG-TS/PS demuxer and MPEG-TS muxer, and Ogg and AVI demuxers."
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -22,7 +22,8 @@ matroska = []
avi = []
# MXF demuxer and writer (`craft_media::mxf`); the writer formats dates with chrono.
mxf = ["dep:chrono"]
# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`).
# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`), and the
# transport stream writer (`craft_media::mpegts::mux`).
mpegts = []
# Sierra VMD (Video and Music Data) demuxer (`craft_media::vmd`).
vmd = []
@@ -69,6 +70,14 @@ required-features = ["matroska"]
name = "oracle_mpegts"
required-features = ["mpegts"]
[[test]]
name = "mpegts_mux_fuzz"
required-features = ["mpegts"]
[[test]]
name = "mpegts_mux_readback"
required-features = ["mpegts"]
[[test]]
name = "oracle_mux"
required-features = ["isobmff"]
+115 -3
View File
@@ -1,8 +1,9 @@
# craft-media
Media containers and bit-level I/O for the Craft apps: an MSB-first bit reader and writer,
clean-room ISO BMFF (MP4), QuickTime (MOV), Matroska (MKV, WebM), MXF and AVI demuxers and muxers, and
Ogg, MPEG-2 Systems (transport and program stream) and Sierra VMD demuxers, written from the public specifications. No `unsafe`, no panics on malformed
clean-room ISO BMFF (MP4), QuickTime (MOV), Matroska (MKV, WebM), MXF and AVI demuxers and muxers,
an MPEG-2 Systems (transport and program stream) demuxer and transport stream muxer, and Ogg and
Sierra VMD demuxers, written from the public specifications. No `unsafe`, no panics on malformed
input, builds for `wasm32-unknown-unknown`. Dependencies: `thiserror` (for `isobmff`), `chrono`
(for `mxf`), `serde` (optional).
@@ -549,7 +550,8 @@ FourCC, size, frame rate, packet count, audio format and duration.
A clean-room MPEG-2 Systems demuxer from FilmCraft's `filmcraft-mpegts`
(storytold/filmcraft@4bec22b): transport streams (188-byte, 192-byte BDAV / M2TS, 204-byte) and
program streams (MPEG-1/2 PS, VOB, MOD). No GPL/LGPL code (FFmpeg, libavformat) was consulted;
FFmpeg is a fixture generator and test oracle only. No muxer, no decoding.
FFmpeg is a fixture generator and test oracle only. No decoding. The transport stream writer is
`mpegts::mux` ([below](#transport-stream-writer)).
```rust
use craft_media::mpegts::{Kind, open};
@@ -637,6 +639,116 @@ helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares ten ffmpeg-made fi
and HEVC video; MP2, ADTS and LATM AAC, AC-3, E-AC-3, Blu-ray and DVD LPCM; TS, M2TS, VOB and
MPEG-1 system streams) with ffprobe's packets: unit counts, sizes, timestamps and key flags.
### Transport stream writer
`mpegts::mux::Muxer` writes one program to any `std::io::Write` as frames arrive, so the same code
writes `.ts` files, HLS segments and SRT payloads. Its `Codec`, `Stream` and `Error` types are its
own, separate from the demuxer's.
```rust
use craft_media::mpegts::mux::{Codec, Config, Frame, Muxer, Stream};
let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)];
let mut ts = Muxer::new(Vec::new(), Config::default(), &streams)?;
let idr = [0, 0, 0, 1, 0x65, 0x88, 0x84];
ts.write_frame(0, &Frame { data: &idr, pts: 90_000, dts: None, key: true })?;
let bytes = ts.finish()?;
assert_eq!(bytes.len() % 188, 0);
```
- A program association section and a program map section, each ending with its CRC-32. They are
written at the start, every `Config::psi_interval`, before every video keyframe when
`Config::psi_before_keyframes` is set, and before the first frame after `Muxer::replace_writer`
or `Muxer::discontinuity`.
- One PES packet per frame, with PTS and, when it differs from the PTS, DTS:
| `Codec` | stream_type | stream_id | Frames passed in |
|---|---|---|---|
| `H264` | 0x1B | 0xE0 | Annex B access units; an access unit delimiter is added when missing |
| `Hevc` | 0x24 | 0xE0 | Annex B access units; an access unit delimiter is added when missing |
| `Mpeg2Video` | 0x02 | 0xE0 | MPEG-2 pictures from their first start code |
| `Mpeg1Video` | 0x01 | 0xE0 | MPEG-1 pictures from their first start code |
| `Mpeg4Part2` | 0x10 | 0xE0 | MPEG-4 Part 2 visual frames from their first start code |
| `Av1(Av1Config)` | 0x06 | 0xBD | temporal units in the low overhead format (every OBU has `obu_size`) |
| `AacAdts` | 0x0F | 0xC0 | ADTS frames; their `frame_length` fields must tile the frame |
| `Aac { .. }` | 0x0F | 0xC0 | raw AAC frames; the writer adds the ADTS header |
| `Opus { channels }` | 0x06 | 0xBD | Opus access units, 1 to 8 channels; the writer adds the Opus control header |
| `OpusMapped(OpusMapping)` | 0x06 | 0xBD | Opus multistream access units with an explicit channel mapping |
| `Ac3` | 0x81 | 0xBD | AC-3 sync frames |
| `Eac3` | 0x87 | 0xBD | E-AC-3 sync frames (bsid 11 to 16) |
| `MpegAudio { low_sample_rate }` | 0x03 or 0x04 | 0xC0 | MPEG audio frames, layers I to III, whose version matches the stream type |
`Codec::aac_from_asc` turns an AudioSpecificConfig into the `Aac` fields, and refuses one that
an ADTS header cannot carry (frameLengthFlag 1, for one). An `Opus { channels }` access unit is
one Opus packet for 1 or 2 channels. For 3 to 8 channels it holds the streams of mapping family 1
in the order that table 4-3 of the Opus transport draft gives, and every stream but the last uses
the self-delimited framing of RFC 6716 Appendix B. `OpusMapped` takes any other layout.
- Descriptors in the program map section: a registration descriptor `AC-3` or `EAC3` on AC-3 and
E-AC-3 streams; a registration descriptor `Opus` and an extension descriptor (tag 0x7F,
extension tag 0x80) on Opus streams, whose channel_config_code is the channel count for
`Opus { channels }` and 0x81 with the mapping family, stream counts and channel mapping for
`OpusMapped`; a registration descriptor `AV01` and the AV1 video descriptor (tag 0x80) built
from `Av1Config` (`Av1Config::from_av1c` reads an AV1CodecConfigurationRecord); and an
ISO 639 language descriptor on any stream that has a language.
- For AV1, each OBU follows the start code 0x000001 with emulation prevention bytes, temporal
delimiters and padding OBUs that end with a zero byte are left out, and each PES packet holds
one temporal unit. A keyframe must carry a
sequence header, and tile list OBUs are refused.
- For Opus, `Muxer::write_frame_with_trim` writes the control header's start and end trims (each
at most 8 191 samples, `MAX_OPUS_TRIM`). A start trim is allowed only while every earlier frame
of the stream was trimmed whole, 65 535 samples in all.
- The PCR on `Config::pcr_pid`: one of the streams' PIDs, or a PID that carries only PCRs. PCRs
are never more than `Config::pcr_interval` apart (at most 100 ms, H.222.0 §2.7.2). The PCR is
the largest DTS so far minus `Config::pcr_delay`, 1 to 90 000 ticks (`MAX_PCR_DELAY`, the
one-second limit of §2.4.2.6). A live output calls `Muxer::advance` while no frames arrive; its
time is on the DTS scale, so the PCR it writes is that time minus `pcr_delay`.
- A continuity counter per PID, the random access indicator on keyframes, adaptation field
stuffing, and timestamps written modulo 2^33. `Muxer::discontinuity` starts a new time base:
the next packet of every stream PID and of the PCR PID sets the discontinuity_indicator
(§2.4.3.5), and timestamps may then go back.
Packets go to the output in batches of `Config::batch_packets` (7 by default, 1 316 bytes, one UDP
datagram), each in one `write` call, and the rest of a batch at the end of every `write_frame` and
`advance` unless `Config::hold_packets` is set. The batch is allocated once, in `Muxer::new`. After
an `Error::Io` the output may hold part of a packet; `Stats::packets` counts only whole packets.
`Muxer::replace_writer` returns the old output in a `Segment` (packet and frame counts, first and
last PTS, whether it starts with a keyframe, any error from its last packets), and the new output
starts with the PAT, the PMT and a PCR. `Muxer::replace_writer_continuing` swaps the output
without adding them.
Frames are checked before anything is written. A stream's DTS must not go back, a video stream's
DTS must increase, a DTS may not be after its PTS, and a frame may be at most `pcr_delay` behind
the largest DTS written so far (`Error::Timestamp`). Audio frames must fit in one PES packet, and
video frames are at most `MAX_VIDEO_FRAME` (`MAX_UNIT_BYTES`, counting the start codes and escape
bytes the writer adds; `Error::FrameTooLarge`). A program has 1 to 32 streams on PIDs 0x0010 to
0x1FFE (`Error::BadPid`, `Error::DuplicatePid`), and its program map section is at most 1 021 bytes
(`Error::PsiTooLarge`). A gap in the timeline longer than `MAX_PCR_FILL` PCR intervals gets one PCR
at its end and is counted in `Stats::pcr_gaps`.
`Config::default()`: program 1 with its PMT on PID 0x1000, the PCR on the first video stream (or
the first stream) every 40 ms and 700 ms behind the DTS, the PAT and PMT every 100 ms and before
keyframes, and writes of 7 packets.
Gaps: one program per stream; no null packets (no constant bit rate); not written: LPCM (H.222.0
defines no LPCM stream type for transport streams), AAC in LATM, DTS, subtitles and teletext. The
demuxer reads Opus and AV1 streams as `Unknown(6)` and MPEG-4 Part 2 as `Unknown(0x10)`, one unit
per PES packet.
Specifications: the ones above, and Opus Interactive Audio Codec Transport Multiplexing Standard,
draft TS V0.1.3 (2015-10), for the Opus control header and descriptors; RFC 6716 for Opus packet
durations and self-delimited framing; Carriage of AV1 in MPEG-2 TS (Alliance for Open Media
working draft) and the AV1 Bitstream & Decoding Process Specification for AV1; ISO/IEC 14496-3
for the AudioSpecificConfig; ATSC A/52 for the AC-3 and E-AC-3 stream types and registration
descriptors.
Tests: `tests/mpegts_mux_readback.rs` reads the output back with the demuxer: streams, codecs,
languages, every frame's bytes, PTS and DTS, keyframes and the PCR range, with no continuity or
CRC warnings, including AV1 units, Opus with an explicit mapping and a start trim, both sides of a
discontinuity, and the output that follows an I/O error. `tests/mpegts_mux_fuzz.rs` muxes random
programs and timelines with idle gaps and output swaps and reads them back, and feeds random bytes
to every codec. Unit tests check every PES header's fixed bits, the sections' CRC, and that every
refused frame writes nothing.
## `mxf`
A clean-room MXF demuxer and writer from FilmCraft's `filmcraft-mxf` (storytold/filmcraft@4bec22b):
+1 -1
View File
@@ -11,7 +11,7 @@
//! - `avi` (feature `avi`): a clean-room AVI (RIFF) and OpenDML demuxer.
//! - `mxf` (feature `mxf`, enables `chrono`): a clean-room MXF demuxer and writer (OP1a, OP-Atom).
//! - `mpegts` (feature `mpegts`): a clean-room MPEG-2 Systems demuxer (transport streams and
//! program streams).
//! program streams) and transport stream writer.
//! - `vmd` (feature `vmd`): a clean-room Sierra VMD (Video and Music Data) demuxer.
//! - [`Container`] and [`CodecId`] (no feature): the identifiers the codec crates report a file's
//! container and codec with.
+2
View File
@@ -15,6 +15,7 @@
//! reference and field structure. That index is the seeking table.
//! - Units are read back on demand by re-reading the file from the unit's first packet, so the
//! index costs a few dozen bytes per access unit.
//! - [`mux`] writes one program as a transport stream to any `io::Write`, frame by frame.
//!
//! The module does no decoding. No dependencies beyond `std`, no `unsafe`, builds for
//! `wasm32-unknown-unknown`.
@@ -26,6 +27,7 @@
mod es;
pub use es::{FrameInfo, frame_bytes, frame_info, sei_has_recovery_point};
pub mod mux;
mod pes;
mod ps;
mod ts;
+232
View File
@@ -0,0 +1,232 @@
//! AV1 in a transport stream (Carriage of AV1 in MPEG-2 TS, §3): each OBU after the start code
//! 0x000001, with emulation prevention so that 0x000000, 0x000001, 0x000002 and 0x000003 never
//! appear inside it. Temporal delimiters are left out, and so are padding OBUs that end with a
//! zero byte (an empty one included), which decoders ignore.
use super::Error;
const OBU_SEQUENCE_HEADER: u8 = 1;
const OBU_TEMPORAL_DELIMITER: u8 = 2;
const OBU_TILE_LIST: u8 = 8;
const OBU_PADDING: u8 = 15;
struct Obu {
/// Bytes from the OBU header to the end of its payload.
len: usize,
kind: u8,
}
/// The OBU at the start of `d`.
fn obu(d: &[u8]) -> Result<Obu, Error> {
let &h = d.first().ok_or(Error::BadFrame("an AV1 frame ends inside an OBU header"))?;
if h & 0x80 != 0 {
return Err(Error::BadFrame("an AV1 OBU has its forbidden bit set"));
}
if h & 0x02 == 0 {
return Err(Error::BadFrame("AV1 OBUs must carry obu_size (the low overhead bitstream format)"));
}
let mut at = 1 + usize::from(h & 0x04 != 0);
let mut size: u64 = 0;
for i in 0..8 {
let &b = d.get(at).ok_or(Error::BadFrame("an AV1 frame ends inside an OBU header"))?;
at += 1;
size |= u64::from(b & 0x7F) << (7 * i);
if b & 0x80 == 0 {
break;
}
if i == 7 {
return Err(Error::BadFrame("an AV1 obu_size is longer than eight bytes"));
}
}
let len = usize::try_from(size).ok().filter(|&s| s <= u32::MAX as usize).and_then(|s| at.checked_add(s)).filter(|&l| l <= d.len());
let len = len.ok_or(Error::BadFrame("an AV1 OBU runs past the end of the frame"))?;
Ok(Obu { len, kind: (h >> 3) & 0x0F })
}
/// The OBU `bytes` (as `obu` found it) is not written: a temporal delimiter, or a padding OBU
/// that ends with a zero byte.
fn left_out(o: &Obu, bytes: &[u8]) -> bool {
o.kind == OBU_TEMPORAL_DELIMITER || (o.kind == OBU_PADDING && bytes.last() == Some(&0))
}
/// Emulation prevention bytes `bytes` needs after a start code.
fn escapes(bytes: &[u8]) -> usize {
let (mut n, mut zeros) = (0, 0u8);
for &b in bytes {
if zeros >= 2 && b <= 3 {
n += 1;
zeros = 0;
}
zeros = if b == 0 { zeros + 1 } else { 0 };
}
n
}
/// Checks a temporal unit and returns the bytes it takes in the PES packet: start codes, OBUs
/// and emulation prevention bytes.
pub(crate) fn check(data: &[u8], key: bool) -> Result<usize, Error> {
let (mut at, mut body, mut seq, mut any) = (0, 0usize, false, false);
while at < data.len() {
let o = obu(&data[at..])?;
let bytes = &data[at..at + o.len];
at += o.len;
if left_out(&o, bytes) {
continue;
}
match o.kind {
OBU_TILE_LIST => return Err(Error::BadFrame("tile list OBUs are not carried in a transport stream")),
OBU_SEQUENCE_HEADER => seq = true,
_ => {}
}
if bytes.last() == Some(&0) {
return Err(Error::BadFrame("an AV1 OBU ends with a zero byte, which the next start code would turn into a forbidden sequence"));
}
body = body.saturating_add(3 + bytes.len() + escapes(bytes));
any = true;
}
if !any {
return Err(Error::BadFrame("the AV1 frame holds only temporal delimiters and padding"));
}
if key && !seq {
return Err(Error::BadFrame("an AV1 keyframe must carry a sequence header"));
}
Ok(body)
}
/// Writes a checked temporal unit in start code form, a packet at a time.
pub(crate) struct Escaper<'a> {
data: &'a [u8],
at: usize,
/// End of the OBU being written.
end: usize,
/// Start code bytes still to write.
start_code: u8,
zeros: u8,
}
impl<'a> Escaper<'a> {
pub(crate) fn new(data: &'a [u8]) -> Self {
Self { data, at: 0, end: 0, start_code: 0, zeros: 0 }
}
/// Fills `out` as far as the temporal unit goes; returns the bytes written.
pub(crate) fn fill(&mut self, out: &mut [u8]) -> usize {
let mut n = 0;
while n < out.len() {
if self.start_code > 0 {
out[n] = u8::from(self.start_code == 1);
self.start_code -= 1;
n += 1;
} else if self.at < self.end {
let b = self.data[self.at];
if self.zeros >= 2 && b <= 3 {
out[n] = 3;
self.zeros = 0;
} else {
out[n] = b;
self.at += 1;
self.zeros = if b == 0 { self.zeros + 1 } else { 0 };
}
n += 1;
} else {
let rest = self.data.get(self.at..).unwrap_or(&[]);
let Ok(o) = obu(rest) else { break };
if left_out(&o, &rest[..o.len]) {
self.at += o.len;
continue;
}
self.end = self.at + o.len;
self.start_code = 3;
self.zeros = 0;
}
}
n
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Removes start codes and emulation prevention bytes: the OBUs back.
fn unescape(es: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut zeros = 0;
let mut i = 0;
while i < es.len() {
if es[i..].starts_with(&[0, 0, 1]) {
i += 3;
zeros = 0;
continue;
}
let b = es[i];
i += 1;
if zeros >= 2 && b == 3 {
zeros = 0;
continue;
}
zeros = if b == 0 { zeros + 1 } else { 0 };
out.push(b);
}
out
}
fn write(data: &[u8], chunk: usize) -> Vec<u8> {
let mut e = Escaper::new(data);
let mut out = Vec::new();
loop {
let mut b = vec![0u8; chunk];
let n = e.fill(&mut b);
out.extend_from_slice(&b[..n]);
if n < chunk {
return out;
}
}
}
#[test]
fn obus_get_start_codes_and_escapes() {
// a temporal delimiter, a sequence header, a frame OBU whose payload holds every
// sequence that needs an escape
let tu = [0x12, 0x00, 0x0A, 0x03, 0x00, 0x00, 0x01, 0x32, 0x0A, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0x7F];
let body = check(&tu, true).unwrap();
for chunk in [1, 2, 5, 184] {
let es = write(&tu, chunk);
assert_eq!(es.len(), body, "chunk {chunk}");
assert!(es.starts_with(&[0, 0, 1, 0x0A, 0x03, 0x00, 0x00, 0x03, 0x01, 0, 0, 1, 0x32]));
for w in es[3..].windows(3) {
assert!(!(w[0] == 0 && w[1] == 0 && w[2] <= 2) || w == [0, 0, 1], "{es:02X?}");
}
assert_eq!(unescape(&es), tu[2..].to_vec());
}
}
#[test]
fn padding_that_ends_with_a_zero_byte_is_left_out() {
// a sequence header, an empty padding OBU, a frame OBU, a padding OBU ending in 0x00,
// and a padding OBU that is written
let tu = [0x0A, 0x01, 0x05, 0x7A, 0x00, 0x32, 0x01, 0x07, 0x7A, 0x02, 0x09, 0x00, 0x7A, 0x01, 0x09];
let body = check(&tu, true).unwrap();
for chunk in [1, 2, 5, 184] {
let es = write(&tu, chunk);
assert_eq!(es.len(), body, "chunk {chunk}");
assert_eq!(es, [0, 0, 1, 0x0A, 0x01, 0x05, 0, 0, 1, 0x32, 0x01, 0x07, 0, 0, 1, 0x7A, 0x01, 0x09], "chunk {chunk}");
}
}
#[test]
fn bad_temporal_units_are_refused() {
assert!(check(&[0x12, 0x00], false).is_err(), "only a temporal delimiter");
assert!(check(&[0x32, 0x01, 0x05], true).is_err(), "a keyframe without a sequence header");
assert!(check(&[0x32, 0x01, 0x05], false).is_ok());
assert!(check(&[0x30, 0x05], false).is_err(), "no obu_size");
assert!(check(&[0xB2, 0x01, 0x05], false).is_err(), "forbidden bit");
assert!(check(&[0x32, 0x05, 0x05], false).is_err(), "past the end");
assert!(check(&[0x32, 0x01, 0x00], false).is_err(), "ends with a zero byte");
assert!(check(&[0x42, 0x01, 0x05], false).is_err(), "tile list");
assert!(check(&[0x7A, 0x00], false).is_err(), "only empty padding");
assert!(check(&[0x7A, 0x02, 0x05, 0x00], false).is_err(), "only padding that ends with a zero byte");
assert!(check(&[0x32, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01], false).is_err(), "a nine-byte size");
assert!(check(&[0x32, 0x80, 0x80, 0x80, 0x80, 0x10], false).is_err(), "over 2^32 - 1");
}
}
File diff suppressed because it is too large Load Diff
+389
View File
@@ -0,0 +1,389 @@
//! PES packet headers (H.222.0 §2.4.3.6), the adaptation field's PCR (§2.4.3.4), and the bytes
//! written ahead of a frame: access unit delimiters, ADTS headers and Opus control headers.
use super::{Codec, Error, MAX_VIDEO_FRAME, OpusTrim, av1};
/// 2^33: PTS, DTS and the PCR base are 33-bit counters.
pub(crate) const WRAP_90K: i64 = 1 << 33;
/// Largest PES header this writer produces: 9 bytes, PTS and DTS.
pub(crate) const HEADER_MAX: usize = 19;
/// Largest prefix: an Opus control header for a 65 535-byte packet (2 bytes, 257 size bytes, a
/// start and an end trim).
pub(crate) const PREFIX_MAX: usize = 2 + 0xFFFF / 255 + 1 + 4;
/// What [`prepare`] found: the prefix it wrote, and the bytes the frame takes after it.
pub(crate) struct Prepared {
pub(crate) prefix_len: usize,
pub(crate) body_len: usize,
}
/// Most frame bytes `codec` allows when the PES header has `header` bytes after
/// PES_packet_length and an Opus control header carries `trim` trim bytes.
pub(crate) fn data_limit(codec: Codec, header: usize, trim: usize) -> usize {
let room = 0xFFFF - header;
match codec {
c if c.is_video() => MAX_VIDEO_FRAME,
// ADTS frame_length is 13 bits
Codec::Aac { .. } => (0x1FFF - 7).min(room - 7),
Codec::Opus { .. } | Codec::OpusMapped(_) => {
// the control header takes 3 bytes, a size byte per 255 bytes, and the trims
let budget = room - 3 - trim;
let mut l = budget * 255 / 256;
while l + 1 + (l + 1) / 255 <= budget {
l += 1;
}
while l + l / 255 > budget {
l -= 1;
}
l
}
_ => room,
}
}
/// Samples per channel at 48 kHz in an Opus packet, from its table of contents (RFC 6716 §3.1).
pub(crate) fn opus_samples(data: &[u8]) -> Option<u32> {
let toc = *data.first()?;
let config = usize::from(toc >> 3);
let frame = match config {
0..=11 => [480, 960, 1920, 2880][config % 4],
12..=15 => [480, 960][config % 2],
_ => [120, 240, 480, 960][config % 4],
};
let count = match toc & 3 {
0 => 1,
1 | 2 => 2,
_ => u32::from(*data.get(1)? & 0x3F),
};
Some(frame * count)
}
/// Checks that an ADTS frame or a run of them fills `data` exactly.
fn check_adts(data: &[u8]) -> Result<(), Error> {
let mut at = 0;
while at < data.len() {
let f = &data[at..];
let &[0xFF, b1, _, b3, b4, b5, _, ..] = f else { return Err(Error::BadFrame("an AAC frame must start with an ADTS header")) };
if b1 & 0xF6 != 0xF0 {
return Err(Error::BadFrame("an AAC frame must start with an ADTS header"));
}
let header = if b1 & 1 == 0 { 9 } else { 7 };
let len = usize::from(b3 & 3) << 11 | usize::from(b4) << 3 | usize::from(b5 >> 5);
if len < header || len > f.len() {
return Err(Error::BadFrame("an ADTS frame_length does not match the frame"));
}
at += len;
}
Ok(())
}
/// A 33-bit timestamp with its 4-bit prefix and marker bits (§2.4.3.7).
fn timestamp(prefix: u8, v: i64) -> [u8; 5] {
let v = v.rem_euclid(WRAP_90K);
[prefix << 4 | ((v >> 29) & 0x0E) as u8 | 1, (v >> 22) as u8, ((v >> 14) & 0xFE) as u8 | 1, (v >> 7) as u8, ((v << 1) & 0xFE) as u8 | 1]
}
/// Writes a PES header into `out` and returns its length. `length` is the PES_packet_length field
/// (0 for an unbounded video packet).
pub(crate) fn header(out: &mut [u8; HEADER_MAX], stream_id: u8, length: u16, pts: i64, dts: Option<i64>) -> usize {
let [hi, lo] = length.to_be_bytes();
// '10', not scrambled, no priority, data_alignment_indicator set, not copyrighted, a copy
out[..7].copy_from_slice(&[0, 0, 1, stream_id, hi, lo, 0x84]);
match dts {
Some(dts) => {
out[7] = 0xC0;
out[8] = 10;
out[9..14].copy_from_slice(&timestamp(3, pts));
out[14..19].copy_from_slice(&timestamp(1, dts));
19
}
None => {
out[7] = 0x80;
out[8] = 5;
out[9..14].copy_from_slice(&timestamp(2, pts));
14
}
}
}
/// The six program_clock_reference bytes for a 27 MHz clock value: the 33-bit base (clock / 300),
/// six reserved bits, and the 9-bit extension (clock % 300).
pub(crate) fn pcr(clock: i64) -> [u8; 6] {
let v = clock.rem_euclid(WRAP_90K * 300);
let (base, ext) = (v / 300, v % 300);
[(base >> 25) as u8, (base >> 17) as u8, (base >> 9) as u8, (base >> 1) as u8, ((base & 1) << 7) as u8 | 0x7E | (ext >> 8) as u8, ext as u8]
}
/// The first NAL unit's first header byte, when `data` starts with an Annex B start code.
fn first_nal(data: &[u8]) -> Option<u8> {
let at = if data.starts_with(&[0, 0, 1]) {
3
} else if data.starts_with(&[0, 0, 0, 1]) {
4
} else {
return None;
};
data.get(at).copied()
}
/// Checks that `data` is a frame of `codec`, writes what goes in front of it into `out`, and
/// returns the prefix length and the bytes the frame itself takes.
pub(crate) fn prepare(codec: Codec, data: &[u8], key: bool, trim: OpusTrim, out: &mut [u8; PREFIX_MAX]) -> Result<Prepared, Error> {
if let Codec::Av1(_) = codec {
return Ok(Prepared { prefix_len: 0, body_len: av1::check(data, key)? });
}
let prefix_len = prefix(codec, data, trim, out)?;
Ok(Prepared { prefix_len, body_len: data.len() })
}
/// Checks a frame of a codec carried as it is and writes its prefix. Returns the prefix length.
fn prefix(codec: Codec, data: &[u8], trim: OpusTrim, out: &mut [u8; PREFIX_MAX]) -> Result<usize, Error> {
match codec {
Codec::H264 => {
let nal = first_nal(data).ok_or(Error::BadFrame("an H.264 frame must start with an Annex B start code"))?;
if nal & 0x1F == 9 {
return Ok(0);
}
// access unit delimiter, primary_pic_type 7 (any slice type) (H.222.0 §2.14)
out[..6].copy_from_slice(&[0, 0, 0, 1, 0x09, 0xF0]);
Ok(6)
}
Codec::Hevc => {
let nal = first_nal(data).ok_or(Error::BadFrame("an HEVC frame must start with an Annex B start code"))?;
if (nal >> 1) & 0x3F == 35 {
return Ok(0);
}
// access unit delimiter (nal_unit_type 35), pic_type 2 (any slice type) (H.222.0 §2.17)
out[..7].copy_from_slice(&[0, 0, 0, 1, 0x46, 0x01, 0x50]);
Ok(7)
}
Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 => {
first_nal(data).ok_or(Error::BadFrame("an MPEG video frame must start with a start code"))?;
Ok(0)
}
Codec::AacAdts => {
check_adts(data)?;
Ok(0)
}
Codec::Aac { object_type, sample_rate_index, channels } => {
let len = data.len() + 7;
if len > 0x1FFF {
return Err(Error::FrameTooLarge { size: data.len(), limit: 0x1FFF - 7 });
}
// ADTS fixed and variable header (ISO/IEC 13818-7 §6.2): MPEG-4, no CRC, buffer
// fullness 0x7FF (variable rate), one raw data block
out[..7].copy_from_slice(&[
0xFF,
0xF1,
(object_type - 1) << 6 | sample_rate_index << 2 | channels >> 2,
(channels & 3) << 6 | (len >> 11) as u8,
(len >> 3) as u8,
((len & 7) as u8) << 5 | 0x1F,
0xFC,
]);
Ok(7)
}
Codec::Opus { .. } | Codec::OpusMapped(_) => {
// opus_control_header: the 11-bit prefix 0x3FF, the trim flags, no extension, the
// payload size as 0xFF bytes and a last byte, then the trims (3 reserved bits and
// 13 bits each)
let n = data.len() / 255;
let trims = if trim.start > 0 { 2 } else { 0 } + if trim.end > 0 { 2 } else { 0 };
if 3 + n + trims > PREFIX_MAX {
return Err(Error::FrameTooLarge { size: data.len(), limit: data_limit(codec, 8, trims) });
}
out[0] = 0x7F;
out[1] = 0xE0 | if trim.start > 0 { 0x10 } else { 0 } | if trim.end > 0 { 0x08 } else { 0 };
out[2..2 + n].fill(0xFF);
out[2 + n] = (data.len() % 255) as u8;
let mut at = 3 + n;
for t in [trim.start, trim.end] {
if t > 0 {
out[at..at + 2].copy_from_slice(&(t & 0x1FFF).to_be_bytes());
at += 2;
}
}
Ok(at)
}
Codec::Ac3 => match data {
[0x0B, 0x77, ..] => Ok(0),
_ => Err(Error::BadFrame("an AC-3 frame must start with its sync word")),
},
Codec::Eac3 => match data {
// bsid, the top five bits of byte 5, is 11 to 16 for E-AC-3 (ATSC A/52)
[0x0B, 0x77, _, _, _, b5, ..] if (11..=16).contains(&(b5 >> 3)) => Ok(0),
_ => Err(Error::BadFrame("an E-AC-3 frame must start with its sync word and a bsid of 11 to 16")),
},
Codec::MpegAudio { low_sample_rate } => match data {
[0xFF, b, ..] if b & 0xE0 == 0xE0 => {
// version: 3 MPEG-1, 2 MPEG-2, 0 MPEG 2.5, 1 reserved; layer 0 is reserved
let version = (b >> 3) & 3;
if version == 1 || (b >> 1) & 3 == 0 {
return Err(Error::BadFrame("the MPEG audio frame header has a reserved version or layer"));
}
if (version == 3) == low_sample_rate {
return Err(Error::BadFrame("the MPEG audio frame's version does not match the stream's low_sample_rate"));
}
Ok(0)
}
_ => Err(Error::BadFrame("an MPEG audio frame must start with its sync word")),
},
Codec::Av1(_) => Err(Error::BadFrame("AV1 frames are not carried with a prefix")),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Reads a 33-bit timestamp back from its five bytes.
fn read(b: &[u8]) -> i64 {
(((b[0] >> 1) & 7) as i64) << 30 | (b[1] as i64) << 22 | ((b[2] >> 1) as i64) << 15 | (b[3] as i64) << 7 | (b[4] >> 1) as i64
}
#[test]
fn timestamps_carry_their_prefix_and_markers() {
for v in [0, 1, 90_000, (1 << 32) + 12_345, WRAP_90K - 1] {
let b = timestamp(2, v);
assert_eq!(b[0] >> 4, 2);
assert_eq!([b[0] & 1, b[2] & 1, b[4] & 1], [1, 1, 1]);
assert_eq!(read(&b), v);
}
assert_eq!(read(&timestamp(2, WRAP_90K + 5)), 5, "wraps at 2^33");
assert_eq!(read(&timestamp(2, -1)), WRAP_90K - 1);
}
#[test]
fn headers_hold_pts_and_dts() {
let mut h = [0u8; HEADER_MAX];
assert_eq!(header(&mut h, 0xE0, 0, 3000, Some(0)), 19);
assert_eq!(&h[..9], &[0, 0, 1, 0xE0, 0, 0, 0x84, 0xC0, 10]);
assert_eq!((h[9] >> 4, read(&h[9..14]), h[14] >> 4, read(&h[14..19])), (3, 3000, 1, 0));
assert_eq!(header(&mut h, 0xC0, 300, 7, None), 14);
assert_eq!(&h[4..9], &[1, 44, 0x84, 0x80, 5]);
}
#[test]
fn pcr_splits_base_and_extension() {
let clock = 123_456_789i64 * 300 + 299;
let b = pcr(clock);
let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64;
let ext = ((b[4] & 1) as i64) << 8 | b[5] as i64;
assert_eq!((base, ext, b[4] & 0x7E), (123_456_789, 299, 0x7E));
}
const NO_TRIM: OpusTrim = OpusTrim { start: 0, end: 0 };
#[test]
fn access_unit_delimiters_are_added_once() {
let mut p = [0u8; PREFIX_MAX];
assert_eq!(prefix(Codec::H264, &[0, 0, 0, 1, 0x65, 0x88], NO_TRIM, &mut p).unwrap(), 6);
assert_eq!(prefix(Codec::H264, &[0, 0, 1, 0x09, 0xF0, 0, 0, 1, 0x65], NO_TRIM, &mut p).unwrap(), 0);
assert_eq!(prefix(Codec::Hevc, &[0, 0, 0, 1, 0x26, 0x01], NO_TRIM, &mut p).unwrap(), 7);
assert_eq!(prefix(Codec::Hevc, &[0, 0, 1, 0x46, 0x01, 0x50], NO_TRIM, &mut p).unwrap(), 0);
assert!(matches!(prefix(Codec::H264, &[0x65, 0x88], NO_TRIM, &mut p), Err(Error::BadFrame(_))));
assert!(matches!(prefix(Codec::H264, &[0, 0, 1], NO_TRIM, &mut p), Err(Error::BadFrame(_))));
}
#[test]
fn opus_control_header_codes_the_size_and_trims() {
let mut p = [0u8; PREFIX_MAX];
let opus = Codec::Opus { channels: 2 };
assert_eq!(prefix(opus, &[0xFC; 254], NO_TRIM, &mut p).unwrap(), 3);
assert_eq!(&p[..3], &[0x7F, 0xE0, 254]);
assert_eq!(prefix(opus, &[0xFC; 510], NO_TRIM, &mut p).unwrap(), 5);
assert_eq!(&p[..5], &[0x7F, 0xE0, 0xFF, 0xFF, 0]);
assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 312, end: 0 }, &mut p).unwrap(), 5);
assert_eq!(&p[..5], &[0x7F, 0xF0, 10, 0x01, 0x38]);
assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 1, end: 8191 }, &mut p).unwrap(), 7);
assert_eq!(&p[..7], &[0x7F, 0xF8, 10, 0, 1, 0x1F, 0xFF]);
assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 0, end: 2 }, &mut p).unwrap(), 5);
assert_eq!(&p[..5], &[0x7F, 0xE8, 10, 0, 2]);
}
#[test]
fn opus_limits_match_the_pes_length() {
for (header, trim) in [(8, 0), (13, 0), (8, 4), (13, 2)] {
let l = data_limit(Codec::Opus { channels: 2 }, header, trim);
let body = |n: usize| header + 3 + n / 255 + trim + n;
assert!(body(l) <= 0xFFFF && body(l + 1) > 0xFFFF, "{header} {trim}: {l}");
}
assert_eq!(data_limit(Codec::Ac3, 8, 0), 0xFFFF - 8);
assert_eq!(data_limit(Codec::Mpeg4Part2, 13, 0), MAX_VIDEO_FRAME);
}
#[test]
fn opus_durations_from_the_table_of_contents() {
assert_eq!(opus_samples(&[0xFC]), Some(960), "CELT 20 ms, one frame");
assert_eq!(opus_samples(&[0x08 | 1]), Some(1920), "SILK 20 ms, two frames");
assert_eq!(opus_samples(&[0x18 | 3, 3]), Some(3 * 2880), "SILK 60 ms, three frames");
assert_eq!(opus_samples(&[0x80]), Some(120), "CELT 2.5 ms");
assert_eq!(opus_samples(&[0x03]), None);
assert_eq!(opus_samples(&[]), None);
}
#[test]
fn adts_header_for_raw_aac() {
let mut p = [0u8; PREFIX_MAX];
let codec = Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 };
assert_eq!(prefix(codec, &[0; 100], NO_TRIM, &mut p).unwrap(), 7);
// AAC LC, 48 kHz, 2 channels, 107 bytes
assert_eq!(&p[..7], &[0xFF, 0xF1, 0x4C, 0x80, 0x0D, 0x7F, 0xFC]);
assert!(matches!(prefix(codec, &[0; 8185], NO_TRIM, &mut p), Err(Error::FrameTooLarge { .. })));
assert_eq!(data_limit(codec, 8, 0), 8184);
}
fn adts(len: usize) -> Vec<u8> {
let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC];
v.resize(len, 0x11);
v
}
#[test]
fn adts_frame_lengths_must_tile_the_frame() {
let mut p = [0u8; PREFIX_MAX];
assert_eq!(prefix(Codec::AacAdts, &adts(100), NO_TRIM, &mut p).unwrap(), 0);
let two = [adts(100), adts(57)].concat();
assert_eq!(prefix(Codec::AacAdts, &two, NO_TRIM, &mut p).unwrap(), 0);
let mut short = adts(100);
short.pop();
assert!(matches!(prefix(Codec::AacAdts, &short, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "one byte short");
let mut long = adts(100);
long.push(0);
assert!(matches!(prefix(Codec::AacAdts, &long, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "a trailing byte");
let mut zero = adts(100);
zero[3] &= 0xFC;
zero[4] = 0;
zero[5] &= 0x1F;
assert!(matches!(prefix(Codec::AacAdts, &zero, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "frame_length 0");
// a header with a CRC is 9 bytes, so a frame_length of 8 does not hold it
let mut crc = adts(8);
crc[1] = 0xF0;
assert!(matches!(prefix(Codec::AacAdts, &crc, NO_TRIM, &mut p), Err(Error::BadFrame(_))));
}
#[test]
fn mpeg_audio_versions_match_the_stream_type() {
let mut p = [0u8; PREFIX_MAX];
let (mpeg1, mpeg2, mpeg25, reserved) = ([0xFF, 0xFB, 0x90], [0xFF, 0xF3, 0x90], [0xFF, 0xE3, 0x90], [0xFF, 0xEB, 0x90]);
let high = Codec::MpegAudio { low_sample_rate: false };
let low = Codec::MpegAudio { low_sample_rate: true };
assert!(prefix(high, &mpeg1, NO_TRIM, &mut p).is_ok());
assert!(prefix(low, &mpeg2, NO_TRIM, &mut p).is_ok());
assert!(prefix(low, &mpeg25, NO_TRIM, &mut p).is_ok());
assert!(prefix(low, &mpeg1, NO_TRIM, &mut p).is_err());
assert!(prefix(high, &mpeg2, NO_TRIM, &mut p).is_err());
assert!(prefix(high, &reserved, NO_TRIM, &mut p).is_err());
assert!(prefix(high, &[0xFF, 0xF9, 0x90], NO_TRIM, &mut p).is_err(), "layer 0");
}
#[test]
fn eac3_needs_its_bsid() {
let mut p = [0u8; PREFIX_MAX];
assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34, 16 << 3], NO_TRIM, &mut p).is_ok());
assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34, 8 << 3], NO_TRIM, &mut p).is_err(), "AC-3's bsid");
assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34], NO_TRIM, &mut p).is_err());
}
}
+216
View File
@@ -0,0 +1,216 @@
//! Program specific information: the program association section and the program map section
//! (H.222.0 §2.4.4), each ending with the CRC-32 of Annex A that the demuxer checks.
pub(crate) use super::super::ts::crc32_mpeg as crc32;
use super::{Codec, Error, OpusMapping, Stream};
/// Largest `section_length` of a program association or program map section (§2.4.4.3, §2.4.4.8).
pub(crate) const MAX_SECTION_LENGTH: usize = 1021;
/// Writes `section_length` into bytes 1 and 2 and appends the CRC. `s` holds the section from
/// `table_id` up to the CRC.
fn finish(mut s: Vec<u8>) -> Result<Vec<u8>, Error> {
let length = s.len() + 4 - 3;
if length > MAX_SECTION_LENGTH {
return Err(Error::PsiTooLarge { length });
}
s[1] = 0xB0 | (length >> 8) as u8;
s[2] = length as u8;
let crc = crc32(&s);
s.extend_from_slice(&crc.to_be_bytes());
Ok(s)
}
/// The program association section with one program.
pub(crate) fn pat(transport_stream_id: u16, program_number: u16, pmt_pid: u16) -> Result<Vec<u8>, Error> {
let mut s = vec![0x00, 0, 0];
s.extend_from_slice(&transport_stream_id.to_be_bytes());
// reserved, version_number 0, current_next_indicator 1; section_number 0, last_section_number 0
s.extend_from_slice(&[0xC1, 0x00, 0x00]);
s.extend_from_slice(&program_number.to_be_bytes());
s.extend_from_slice(&(0xE000 | pmt_pid).to_be_bytes());
finish(s)
}
/// The program map section.
pub(crate) fn pmt(program_number: u16, pcr_pid: u16, streams: &[Stream]) -> Result<Vec<u8>, Error> {
let mut s = vec![0x02, 0, 0];
s.extend_from_slice(&program_number.to_be_bytes());
s.extend_from_slice(&[0xC1, 0x00, 0x00]);
s.extend_from_slice(&(0xE000 | pcr_pid).to_be_bytes());
// program_info_length 0
s.extend_from_slice(&[0xF0, 0x00]);
for st in streams {
s.push(st.codec.stream_type());
s.extend_from_slice(&(0xE000 | st.pid).to_be_bytes());
let at = s.len();
s.extend_from_slice(&[0xF0, 0x00]);
descriptors(st, &mut s);
let len = s.len() - at - 2;
s[at] = 0xF0 | (len >> 8) as u8;
s[at + 1] = len as u8;
}
finish(s)
}
/// The elementary stream descriptors of one stream.
fn descriptors(st: &Stream, s: &mut Vec<u8>) {
match st.codec {
// registration_descriptor (§2.6.8) with the format identifier "AC-3"
Codec::Ac3 => s.extend_from_slice(&[0x05, 4, b'A', b'C', b'-', b'3']),
// registration "EAC3" (ATSC A/52) with stream type 0x87
Codec::Eac3 => s.extend_from_slice(&[0x05, 4, b'E', b'A', b'C', b'3']),
Codec::Opus { channels } => {
// registration_descriptor "Opus", then the Opus audio descriptor as an extension
// descriptor (tag 0x7F) whose channel_config_code is the channel count (1 to 8)
s.extend_from_slice(&[0x05, 4, b'O', b'p', b'u', b's']);
s.extend_from_slice(&[0x7F, 2, OPUS_DESCRIPTOR_EXTENSION, channels]);
}
Codec::OpusMapped(m) => {
s.extend_from_slice(&[0x05, 4, b'O', b'p', b'u', b's']);
let mut body = [0u8; 10];
let n = opus_explicit(&m, &mut body);
s.extend_from_slice(&[0x7F, 1 + n as u8, OPUS_DESCRIPTOR_EXTENSION]);
s.extend_from_slice(&body[..n]);
}
Codec::Av1(c) => {
// registration_descriptor "AV01" first, then the AV1 video descriptor (tag 0x80)
// (Carriage of AV1 in MPEG-2 TS, §2)
s.extend_from_slice(&[0x05, 4, b'A', b'V', b'0', b'1']);
let b = |v: bool, shift: u8| u8::from(v) << shift;
s.extend_from_slice(&[
0x80,
4,
0x81,
c.seq_profile << 5 | c.seq_level_idx_0,
b(c.seq_tier_0, 7)
| b(c.high_bitdepth, 6)
| b(c.twelve_bit, 5)
| b(c.monochrome, 4)
| b(c.chroma_subsampling_x, 3)
| b(c.chroma_subsampling_y, 2)
| c.chroma_sample_position,
// hdr_wcg_idc, then reserved zeros and no initial_presentation_delay
c.hdr_wcg_idc << 6,
]);
}
_ => {}
}
if let Some(lang) = st.language {
// ISO_639_language_descriptor (§2.6.18), audio_type 0 (undefined)
s.extend_from_slice(&[0x0A, 4, lang[0], lang[1], lang[2], 0]);
}
}
/// `descriptor_tag_extension` of the Opus audio descriptor. The Opus transport draft leaves the
/// value open; 0x80 is the value in use for it.
pub(crate) const OPUS_DESCRIPTOR_EXTENSION: u8 = 0x80;
/// Bits needed for the values 0 to `n - 1`: ceil(log2(n)).
fn bits_for(n: u32) -> u32 {
if n <= 1 { 0 } else { 32 - (n - 1).leading_zeros() }
}
/// The opus_audio_descriptor body for an explicit channel configuration (channel_config_code
/// 0x81): channel_count, mapping_family and, for a family above 0, stream_count_minus_one,
/// coupled_stream_count and the channel mapping in as few bits as the draft gives each, padded
/// with zero bits to a byte. Returns its length.
fn opus_explicit(m: &OpusMapping, out: &mut [u8; 10]) -> usize {
out[..3].copy_from_slice(&[0x81, m.channels, m.family]);
if m.family == 0 {
return 3;
}
let (ch, streams, coupled) = (u32::from(m.channels), u32::from(m.streams), u32::from(m.coupled));
let mut acc: u64 = 0;
let mut bits = 0;
let mut put = |v: u32, n: u32| {
acc = acc << n | u64::from(v & ((1 << n) - 1));
bits += n;
};
put(streams - 1, bits_for(ch));
put(coupled, bits_for(streams + 1));
let width = bits_for(streams + coupled + 1);
for &c in &m.mapping[..usize::from(m.channels)] {
put(if c == 255 { (1 << width) - 1 } else { u32::from(c) }, width);
}
let bytes = bits.div_ceil(8) as usize;
let acc = acc << (bytes as u32 * 8 - bits);
for (i, o) in out[3..3 + bytes].iter_mut().enumerate() {
*o = (acc >> (8 * (bytes - 1 - i))) as u8;
}
3 + bytes
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn crc_check_value() {
// the CRC-32/MPEG-2 check value of the ASCII digits 1 to 9
assert_eq!(crc32(b"123456789"), 0x0376_E6E7);
}
#[test]
fn sections_end_with_a_crc_over_the_whole_section() {
let pat = pat(7, 1, 0x1000).unwrap();
assert_eq!(pat.len(), 16);
assert_eq!(crc32(&pat), 0);
assert_eq!(&pat[..3], &[0x00, 0xB0, 13]);
assert_eq!(&pat[8..12], &[0x00, 0x01, 0xF0, 0x00]);
let st = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Opus { channels: 2 }).with_language(*b"eng")];
let pmt = pmt(1, 0x100, &st).unwrap();
assert_eq!(crc32(&pmt), 0);
assert_eq!(pmt.len(), 3 + ((pmt[1] as usize & 0x0F) << 8 | pmt[2] as usize));
assert_eq!(&pmt[8..10], &[0xE1, 0x00], "PCR_PID");
assert_eq!(&pmt[12..17], &[0x1B, 0xE1, 0x00, 0xF0, 0x00], "H.264 without descriptors");
assert_eq!(&pmt[17..22], &[0x06, 0xE1, 0x01, 0xF0, 16]);
}
#[test]
fn a_section_past_the_length_limit_is_refused() {
let st: Vec<Stream> = (0..200).map(|i| Stream::new(0x100 + i, Codec::Ac3).with_language(*b"eng")).collect();
assert!(matches!(pmt(1, 0x100, &st), Err(Error::PsiTooLarge { .. })));
}
/// The descriptors of one stream's PMT entry.
fn stream_descriptors(codec: Codec) -> Vec<u8> {
let pmt = pmt(1, 0x100, &[Stream::new(0x100, codec)]).unwrap();
let len = ((pmt[15] as usize & 0x0F) << 8) | pmt[16] as usize;
pmt[17..17 + len].to_vec()
}
#[test]
fn explicit_opus_mappings_pack_their_fields() {
// 6 channels, family 1, 4 streams, 2 coupled: 3 + 3 + 6 * 3 = 24 bits
let m = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] };
let d = stream_descriptors(Codec::OpusMapped(m));
let want = 0b011 << 21 | 0b010 << 18 | 0b000_100_001_010_011_101;
assert_eq!(&d[6..], &[0x7F, 7, 0x80, 0x81, 6, 1, (want >> 16) as u8, (want >> 8) as u8, want as u8]);
// 3 channels, family 255, 3 streams, none coupled, one silent: 2 + 2 + 3 * 2 = 10 bits
let m = OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [2, 255, 0, 0, 0, 0, 0, 0] };
let d = stream_descriptors(Codec::OpusMapped(m));
assert_eq!(&d[6..], &[0x7F, 6, 0x80, 0x81, 3, 255, 0b10_00_10_11, 0b00_000000]);
// family 0 carries no stream fields
let m = OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] };
assert_eq!(&stream_descriptors(Codec::OpusMapped(m))[6..], &[0x7F, 4, 0x80, 0x81, 2, 0]);
}
#[test]
fn av1_and_eac3_descriptors() {
let c = crate::mpegts::mux::Av1Config {
seq_profile: 1,
seq_level_idx_0: 8,
seq_tier_0: false,
high_bitdepth: true,
twelve_bit: false,
monochrome: false,
chroma_subsampling_x: false,
chroma_subsampling_y: false,
chroma_sample_position: 0,
hdr_wcg_idc: 3,
};
assert_eq!(stream_descriptors(Codec::Av1(c)), [0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x28, 0x40, 0xC0]);
assert_eq!(stream_descriptors(Codec::Eac3), [0x05, 4, b'E', b'A', b'C', b'3']);
}
}
+915
View File
@@ -0,0 +1,915 @@
use super::*;
use std::cell::RefCell;
use std::rc::Rc;
const WIDE_OPUS: OpusMapping = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] };
/// One packet's header fields.
#[derive(Debug, Clone, Copy)]
struct Pk {
pid: u16,
pusi: bool,
cc: u8,
payload: bool,
rai: bool,
disc: bool,
pcr: Option<i64>,
}
fn walk(ts: &[u8]) -> Vec<Pk> {
assert_eq!(ts.len() % PACKET_SIZE, 0);
ts.chunks(PACKET_SIZE)
.map(|p| {
assert_eq!(p[0], 0x47);
let afc = p[3] >> 4 & 3;
let (mut rai, mut disc, mut pcr) = (false, false, None);
if afc & 2 != 0 {
let len = p[4] as usize;
assert!(len <= 183);
if afc == 2 {
assert_eq!(len, 183);
}
if len > 0 {
rai = p[5] & 0x40 != 0;
disc = p[5] & 0x80 != 0;
if p[5] & 0x10 != 0 {
let b = &p[6..12];
let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64;
pcr = Some(base * 300 + (((b[4] & 1) as i64) << 8 | b[5] as i64));
}
}
}
Pk { pid: ((p[1] & 0x1F) as u16) << 8 | p[2] as u16, pusi: p[1] & 0x40 != 0, cc: p[3] & 0x0F, payload: afc & 1 != 0, rai, disc, pcr }
})
.collect()
}
fn h264(key: bool) -> Vec<u8> {
if key {
vec![0, 0, 0, 1, 0x67, 0x42, 0, 0x1E, 0, 0, 0, 1, 0x68, 0xCE, 0, 0, 1, 0x65, 0x88, 0x84, 0x21]
} else {
vec![0, 0, 0, 1, 0x41, 0x9A, 0x11]
}
}
fn mux(cfg: Config, streams: &[Stream], f: impl FnOnce(&mut Muxer<Vec<u8>>)) -> Vec<u8> {
let mut m = Muxer::new(Vec::new(), cfg, streams).unwrap();
f(&mut m);
m.finish().unwrap()
}
#[test]
fn starts_with_pat_pmt_and_a_pcr_on_the_first_frame() {
let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| {
m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap();
});
let pk = walk(&ts);
assert_eq!(pk.len(), 3);
assert_eq!((pk[0].pid, pk[0].pusi), (0, true));
assert_eq!((pk[1].pid, pk[1].pusi), (0x1000, true));
assert_eq!((pk[2].pid, pk[2].pusi, pk[2].rai), (0x100, true, true));
assert_eq!(pk[2].pcr, Some((90_000 - 63_000) * 300));
// the payload ends the packet: the access unit delimiter, then the frame
let frame = h264(true);
let p = &ts[2 * PACKET_SIZE..];
assert_eq!(&p[PACKET_SIZE - frame.len()..PACKET_SIZE], &frame[..]);
assert_eq!(&p[PACKET_SIZE - frame.len() - 6 - 14..PACKET_SIZE - frame.len() - 6][..4], &[0, 0, 1, 0xE0]);
assert_eq!(&p[PACKET_SIZE - frame.len() - 6..PACKET_SIZE - frame.len()], &[0, 0, 0, 1, 9, 0xF0]);
}
#[test]
fn every_stuffing_length_fills_the_packet() {
// frames whose PES packet ends at every offset of a packet, with and without a PCR
for n in 1..=400usize {
let ts = mux(Config { pcr_pid: Some(0x200), ..Config::default() }, &[Stream::new(0x100, Codec::MpegAudio { low_sample_rate: false })], |m| {
let mut data = vec![0u8; n];
data[0] = 0xFF;
if n > 1 {
data[1] = 0xFB;
}
if n == 1 {
assert!(matches!(m.write_frame(0, &Frame { data: &data, pts: 90_000, dts: None, key: true }), Err(Error::BadFrame(_))));
return;
}
m.write_frame(0, &Frame { data: &data, pts: 90_000, dts: None, key: true }).unwrap();
m.write_frame(0, &Frame { data: &data, pts: 92_000, dts: None, key: false }).unwrap();
});
if n == 1 {
continue;
}
let pk = walk(&ts);
let mut payload = 0;
for (p, raw) in pk.iter().zip(ts.chunks(PACKET_SIZE)) {
if p.pid == 0x100 {
let start = if raw[3] & 0x20 != 0 { 5 + raw[4] as usize } else { 4 };
payload += PACKET_SIZE - start;
}
}
assert_eq!(payload, 2 * (14 + n), "{n}");
}
}
#[test]
fn continuity_counters_count_payload_packets_per_pid() {
let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| {
let big = {
let mut v = h264(true);
v.resize(10_000, 0x55);
v
};
for k in 0..40i64 {
m.write_frame(0, &Frame { data: &big, pts: 90_000 + k * 3000, dts: None, key: k % 10 == 0 }).unwrap();
m.write_frame(1, &Frame { data: &[0x0B, 0x77, 1, 2, 3], pts: 90_000 + k * 3000, dts: None, key: true }).unwrap();
}
});
let mut last: std::collections::HashMap<u16, u8> = Default::default();
for p in walk(&ts) {
if let Some(&c) = last.get(&p.pid) {
let want = if p.payload { (c + 1) & 0x0F } else { c };
assert_eq!(p.cc, want, "PID {:#x}", p.pid);
}
last.insert(p.pid, p.cc);
}
}
#[test]
fn pcr_never_lapses_past_the_interval() {
for interval in [900u32, 3600, MAX_PCR_INTERVAL] {
// video on 0x100 carries the PCR; a 2 s gap in the video is filled from the audio clock
let ts =
mux(Config { pcr_interval: interval, ..Config::default() }, &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| {
let mut t = 90_000i64;
for k in 0..200i64 {
if !(50..110).contains(&k) {
m.write_frame(0, &Frame { data: &h264(k == 0), pts: t, dts: None, key: k == 0 }).unwrap();
}
m.write_frame(1, &Frame { data: &[0x0B, 0x77, 0], pts: t, dts: None, key: true }).unwrap();
t += 3000;
}
});
let pcrs: Vec<i64> = walk(&ts).iter().filter(|p| p.pid == 0x100).filter_map(|p| p.pcr).collect();
assert!(pcrs.len() > 1);
for w in pcrs.windows(2) {
assert!(w[1] > w[0], "PCR goes forward");
assert!(w[1] - w[0] <= i64::from(interval) * 300, "interval {interval}: {} apart", w[1] - w[0]);
}
}
}
#[test]
fn pcr_on_a_pid_of_its_own_and_through_advance() {
let mut m = Muxer::new(Vec::new(), Config { pcr_pid: Some(0x1FF), ..Config::default() }, &[Stream::new(0x101, Codec::Ac3)]).unwrap();
assert_eq!(m.pcr_pid(), 0x1FF);
m.advance(63_000).unwrap();
m.advance(63_000 + 90_000).unwrap();
m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000 + 90_000, dts: None, key: true }).unwrap();
let st = m.stats();
let ts = m.finish().unwrap();
let pk = walk(&ts);
let pcrs: Vec<i64> = pk.iter().filter(|p| p.pid == 0x1FF).map(|p| p.pcr.unwrap()).collect();
assert_eq!(pcrs.first(), Some(&0));
assert_eq!(pcrs.last(), Some(&(90_000 * 300)));
assert!(pcrs.windows(2).all(|w| w[1] - w[0] <= 3600 * 300));
assert!(pk.iter().filter(|p| p.pid == 0x1FF).all(|p| !p.payload && p.cc == 0));
assert_eq!(st.pcrs as usize, pcrs.len());
assert_eq!(pcrs.len(), 26, "one PCR, 24 to fill the second, one at its end");
// at the start, then every 100 ms of the gap, the last one at its end
assert_eq!(st.psi, 11);
let mut last_psi = None;
let mut pcr = 0;
for p in &pk {
if let Some(v) = p.pcr {
pcr = v;
}
if p.pid == 0 {
if let Some(l) = last_psi {
assert!(pcr - l <= (9000 + 3600) * 300, "PAT {} after the last", pcr - l);
}
last_psi = Some(pcr);
}
}
assert_eq!(st.bytes(), ts.len() as u64);
}
#[test]
fn a_pcr_packet_before_the_first_payload_keeps_the_counter_continuous() {
// the audio frame comes first, so the video PID carries a PCR-only packet before its first
// payload packet
let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| {
m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap();
m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap();
});
let video: Vec<Pk> = walk(&ts).into_iter().filter(|p| p.pid == 0x100).collect();
assert_eq!(video.len(), 2);
assert!(!video[0].payload && video[0].pcr.is_some());
assert!(video[1].payload);
assert_eq!(video[1].cc, (video[0].cc + 1) & 0x0F);
}
#[test]
fn a_long_gap_is_closed_by_one_pcr() {
let mut m = Muxer::new(Vec::new(), Config { pcr_interval: 1, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap();
m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000, dts: None, key: true }).unwrap();
m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000 + 90_000, dts: None, key: true }).unwrap();
assert_eq!(m.stats().pcr_gaps, 1);
let pcrs: Vec<i64> = walk(&m.finish().unwrap()).iter().filter_map(|p| p.pcr).collect();
assert_eq!(pcrs.len() as u32, 2 + MAX_PCR_FILL);
assert_eq!(pcrs.last(), Some(&(90_000 * 300)));
}
#[test]
fn psi_repeats_on_keyframes_and_new_writers() {
let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap();
m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap();
m.write_frame(0, &Frame { data: &h264(false), pts: 93_000, dts: None, key: false }).unwrap();
assert_eq!(m.stats().psi, 1);
m.write_frame(0, &Frame { data: &h264(true), pts: 96_000, dts: None, key: true }).unwrap();
assert_eq!(m.stats().psi, 2);
let first = m.replace_writer(Vec::new()).writer;
m.write_frame(0, &Frame { data: &h264(false), pts: 99_000, dts: None, key: false }).unwrap();
let second = m.finish().unwrap();
let pk = walk(&second);
assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "a new segment starts with the PAT and PMT");
let pk_first = walk(&first);
let last_video = pk_first.iter().rev().find(|p| p.pid == 0x100).unwrap().cc;
assert_eq!(pk.iter().find(|p| p.pid == 0x100).unwrap().cc, (last_video + 1) & 0x0F, "counters carry on");
}
#[test]
fn a_keyframe_after_a_gap_follows_the_tables_directly() {
let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| {
m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap();
// the gap reaches past the table interval and several PCR intervals
m.write_frame(0, &Frame { data: &h264(true), pts: 110_000, dts: None, key: true }).unwrap();
});
let pk = walk(&ts);
let keys: Vec<usize> = pk.iter().enumerate().filter(|(_, p)| p.pid == 0x100 && p.rai).map(|(i, _)| i).collect();
assert_eq!(keys.len(), 2);
for k in keys {
assert_eq!((pk[k - 2].pid, pk[k - 1].pid), (0, 0x1000), "the PAT and PMT right before the keyframe at packet {k}");
}
assert!(pk.iter().any(|p| p.pid == 0x100 && !p.payload), "PCR-only packets fill the gap");
// a packet the caller writes between the tables and a keyframe brings the tables again
let mut null = [0xFF; PACKET_SIZE];
null[..4].copy_from_slice(&[0x47, 0x1F, 0xFF, 0x10]);
let cfg = Config { pcr_interval: 9_000, psi_interval: 3_600, ..Config::default() };
let ts = mux(cfg, &[Stream::new(0x100, Codec::H264)], |m| {
m.advance(90_000).unwrap();
// the tables fall due here and the PCR does not, so the tables are the last packets
m.advance(93_600).unwrap();
m.get_mut().extend_from_slice(&null);
m.write_frame(0, &Frame { data: &h264(true), pts: 93_600, dts: None, key: true }).unwrap();
});
let pk = walk(&ts);
let k = pk.iter().position(|p| p.pid == 0x100 && p.rai).unwrap();
assert_eq!((pk[k - 3].pid, pk[k - 2].pid, pk[k - 1].pid), (0x1FFF, 0, 0x1000));
}
#[test]
fn tables_lost_with_a_failed_write_come_again_before_a_keyframe() {
let cfg = Config { pcr_interval: 9_000, psi_interval: 3_600, ..Config::default() };
// the second write fails: the one at the end of the second advance
let mut m = Muxer::new(Flaky { fail_on: Some(2), calls: 0, data: Vec::new() }, cfg, &[Stream::new(0x100, Codec::H264)]).unwrap();
m.advance(90_000).unwrap();
// the tables fall due and are dropped with the failed batch
assert!(matches!(m.advance(93_600), Err(Error::Io(_))));
m.write_frame(0, &Frame { data: &h264(true), pts: 93_600, dts: None, key: true }).unwrap();
let pk = walk(&m.finish().unwrap().data);
let k = pk.iter().position(|p| p.pid == 0x100 && p.rai).unwrap();
assert_eq!((pk[k - 2].pid, pk[k - 1].pid), (0, 0x1000));
}
#[test]
fn every_new_segment_carries_a_pcr() {
for pcr_pid in [None, Some(0x1F0)] {
let mut m = Muxer::new(Vec::new(), Config { pcr_pid, ..Config::default() }, &[Stream::new(0x100, Codec::H264)]).unwrap();
m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap();
m.replace_writer(Vec::new());
// a frame within the PCR interval
m.write_frame(0, &Frame { data: &h264(false), pts: 90_001, dts: None, key: false }).unwrap();
let segment = m.replace_writer(Vec::new()).writer;
m.advance(91_000).unwrap();
let third = m.finish().unwrap();
let want = pcr_pid.unwrap_or(0x100);
for (n, ts) in [segment, third].iter().enumerate() {
let pk = walk(ts);
assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "{pcr_pid:?} segment {n}");
assert!(pk.iter().any(|p| p.pid == want && p.pcr.is_some()), "{pcr_pid:?} segment {n} has a PCR");
}
}
}
#[test]
fn a_segment_after_an_idle_gap_starts_with_the_tables() {
let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap();
m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap();
m.replace_writer(Vec::new());
m.advance(180_000).unwrap();
let pk = walk(&m.finish().unwrap());
assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000));
assert!(pk.len() > 10, "the gap is filled with PCRs");
}
#[test]
fn short_table_intervals_hold_in_idle_gaps() {
let mut m = Muxer::new(Vec::new(), Config { psi_interval: 900, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap();
m.advance(63_000).unwrap();
m.advance(63_000 + 90_000).unwrap();
// every 900 ticks: at the start, 99 times inside the second, and at its end
assert_eq!(m.stats().psi, 101);
// a table interval of one tick fills at most MAX_PCR_FILL repeats per gap, and the PCRs still
// fill the gap
let mut m = Muxer::new(Vec::new(), Config { psi_interval: 1, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap();
m.advance(63_000).unwrap();
m.advance(63_000 + 90_000).unwrap();
assert_eq!(m.stats().psi, 2 + u64::from(MAX_PCR_FILL));
assert_eq!((m.stats().pcrs, m.stats().pcr_gaps), (26, 0));
}
#[test]
fn frames_behind_the_sent_clock_are_refused() {
let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)]).unwrap();
m.write_frame(0, &Frame { data: &h264(true), pts: 900_000, dts: None, key: true }).unwrap();
// the clock is 900 000 - 63 000: audio up to the PCR delay behind the video is fine
m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_000, dts: None, key: true }).unwrap();
let before = m.get_ref().len();
assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_001, dts: None, key: true }), Err(Error::Timestamp(_))));
m.advance(2_000_000).unwrap();
let after = m.get_ref().len();
assert!(after > before);
assert!(matches!(m.write_frame(0, &Frame { data: &h264(false), pts: 1_000_000, dts: None, key: false }), Err(Error::Timestamp(_))));
assert_eq!(m.get_ref().len(), after, "nothing is written for a refused frame");
}
#[test]
fn timestamps_and_dts() {
let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| {
m.write_frame(0, &Frame { data: &h264(true), pts: (1 << 33) + 6000, dts: Some((1 << 33) + 3000), key: true }).unwrap();
});
let p = &ts[2 * PACKET_SIZE..];
let start = 5 + p[4] as usize;
let h = &p[start..];
assert_eq!(&h[..9], &[0, 0, 1, 0xE0, 0, (3 + 10 + 6 + h264(true).len()) as u8, 0x84, 0xC0, 10]);
assert_eq!(h[9] >> 4, 3);
assert_eq!(h[14] >> 4, 1);
}
#[test]
fn bad_frames_and_timestamps_write_nothing() {
let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]).unwrap();
fn f(data: &[u8], pts: i64, dts: Option<i64>) -> Frame<'_> {
Frame { data, pts, dts, key: true }
}
assert!(matches!(m.write_frame(2, &f(&h264(true), 90_000, None)), Err(Error::NoSuchStream(2))));
assert!(matches!(m.write_frame(0, &f(&[], 90_000, None)), Err(Error::EmptyFrame)));
assert!(matches!(m.write_frame(0, &f(&h264(true), 90_000, Some(90_001))), Err(Error::Timestamp(_))));
assert!(matches!(m.write_frame(0, &f(&[0x65, 0x88], 90_000, None)), Err(Error::BadFrame(_))));
assert!(matches!(m.write_frame(1, &f(&[0xFF, 0xF1, 0, 0, 0, 0], 90_000, None)), Err(Error::BadFrame(_))));
// ten ADTS frames of 7000 bytes: each is valid, together they pass the PES length
let one = {
let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (7000 >> 11) as u8, (7000 >> 3) as u8, ((7000 & 7) as u8) << 5 | 0x1F, 0xFC];
v.resize(7000, 0x11);
v
};
let long_adts = one.repeat(10);
assert!(matches!(m.write_frame(1, &f(&long_adts, 90_000, None)), Err(Error::FrameTooLarge { limit: 65_527, .. })));
assert!(matches!(m.write_frame(0, &f(&h264(true), i64::MIN, None)), Err(Error::Timestamp(_))));
assert!(m.get_ref().is_empty());
m.write_frame(0, &f(&h264(true), 90_000, None)).unwrap();
assert!(matches!(m.write_frame(0, &f(&h264(true), 80_000, None)), Err(Error::Timestamp(_))));
// video has no PES length limit
let mut big = h264(true);
big.resize(200_000, 1);
m.write_frame(0, &f(&big, 93_000, None)).unwrap();
}
#[test]
fn settings_are_checked() {
let one = [Stream::new(0x100, Codec::H264)];
let bad = |cfg: Config, streams: &[Stream]| matches!(Muxer::new(Vec::new(), cfg, streams), Err(Error::Config(_)));
let err = |cfg: Config, streams: &[Stream]| Muxer::new(Vec::new(), cfg, streams).err();
let d = Config::default();
assert!(bad(d, &[]));
assert!(bad(d, &[Stream::new(0x100, Codec::H264); MAX_STREAMS + 1]));
assert!(bad(Config { program_number: 0, ..d }, &one));
assert!(matches!(err(Config { pmt_pid: 0x0F, ..d }, &one), Some(Error::BadPid(0x0F))));
assert!(matches!(err(Config { pmt_pid: 0x1FFF, ..d }, &one), Some(Error::BadPid(0x1FFF))));
assert!(bad(Config { pcr_interval: 0, ..d }, &one));
assert!(bad(Config { pcr_interval: MAX_PCR_INTERVAL + 1, ..d }, &one));
assert!(bad(Config { psi_interval: 0, ..d }, &one));
assert!(bad(Config { batch_packets: 0, ..d }, &one));
assert!(bad(Config { batch_packets: MAX_BATCH_PACKETS + 1, ..d }, &one));
assert!(matches!(err(Config { pcr_delay: 0, ..d }, &one), Some(Error::PcrDelay(0))));
assert!(matches!(err(Config { pcr_delay: MAX_PCR_DELAY + 1, ..d }, &one), Some(Error::PcrDelay(90_001))));
assert!(err(Config { pcr_delay: MAX_PCR_DELAY, ..d }, &one).is_none());
assert!(err(Config { pcr_delay: 1, ..d }, &one).is_none());
assert!(matches!(err(Config { pcr_pid: Some(0x1000), ..d }, &one), Some(Error::DuplicatePid(0x1000))));
assert!(matches!(err(Config { pcr_pid: Some(0x2000), ..d }, &one), Some(Error::BadPid(0x2000))));
assert!(matches!(err(d, &[Stream::new(0x0005, Codec::H264)]), Some(Error::BadPid(5))));
assert!(matches!(err(d, &[Stream::new(0x1000, Codec::H264)]), Some(Error::DuplicatePid(0x1000))));
assert!(matches!(err(d, &[Stream::new(0x100, Codec::H264), Stream::new(0x100, Codec::Ac3)]), Some(Error::DuplicatePid(0x100))));
assert!(!bad(Config { pcr_pid: Some(0x1FFE), ..d }, &one));
}
#[test]
fn stream_settings_are_checked() {
let bad = |cfg: Config, streams: &[Stream]| matches!(Muxer::new(Vec::new(), cfg, streams), Err(Error::Config(_)));
let err = |cfg: Config, streams: &[Stream]| Muxer::new(Vec::new(), cfg, streams).err();
let d = Config::default();
// the widest program fits: 32 streams of the longest descriptors
let wide: Vec<Stream> = (0..MAX_STREAMS as u16).map(|i| Stream::new(0x100 + i, Codec::OpusMapped(WIDE_OPUS)).with_language(*b"eng")).collect();
assert!(err(d, &wide).is_none());
assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { streams: 7, ..WIDE_OPUS }))]));
assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { coupled: 5, ..WIDE_OPUS }))]));
assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [0, 1, 2, 3, 4, 10, 0, 0], ..WIDE_OPUS }))]));
assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 0, ..WIDE_OPUS }))]));
assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 2, ..WIDE_OPUS }))]), "a reserved family");
assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 255, ..WIDE_OPUS }))]));
let stereo = OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] };
assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(stereo))]));
assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { coupled: 255, ..stereo }))]), "no overflow");
assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [1, 0, 0, 0, 0, 0, 0, 0], ..stereo }))]), "swapped");
assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [0, 1, 2, 3, 4, 255, 0, 0], ..WIDE_OPUS }))]));
let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap();
assert!(!bad(d, &[Stream::new(0x100, Codec::Av1(av1))]));
assert!(bad(d, &[Stream::new(0x100, Codec::Av1(Av1Config { seq_profile: 3, ..av1 }))]));
assert!(Av1Config::from_av1c(&[0x01, 0x08, 0x0C, 0x00]).is_err());
assert!(Av1Config::from_av1c(&[0x81, 0x08, 0x0C]).is_err());
assert!(bad(d, &[Stream::new(0x100, Codec::Opus { channels: 0 })]));
assert!(bad(d, &[Stream::new(0x100, Codec::Opus { channels: 9 })]));
assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 0, sample_rate_index: 3, channels: 2 })]));
assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 2, sample_rate_index: 13, channels: 2 })]));
assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 0 })]));
assert!(bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"e1g")]));
assert!(bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"ENG")]));
assert!(!bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"eng")]));
// the first video stream carries the PCR by default
let m = Muxer::new(Vec::new(), d, &[Stream::new(0x101, Codec::Ac3), Stream::new(0x100, Codec::H264)]).unwrap();
assert_eq!(m.pcr_pid(), 0x100);
}
#[test]
fn wide_programs_split_the_pmt_across_packets() {
let streams: Vec<Stream> = (0..MAX_STREAMS as u16).map(|i| Stream::new(0x100 + i, Codec::Opus { channels: 2 }).with_language(*b"eng")).collect();
let ts = mux(Config::default(), &streams, |m| {
m.write_frame(0, &Frame { data: &[0xFC, 1], pts: 90_000, dts: None, key: true }).unwrap();
});
let pk = walk(&ts);
let pmt: Vec<_> = pk.iter().filter(|p| p.pid == 0x1000).collect();
assert_eq!(pmt.len(), 4, "32 stream entries of 21 bytes");
assert!(pmt[0].pusi && pmt[1..].iter().all(|p| !p.pusi));
assert_eq!(pmt.iter().map(|p| p.cc).collect::<Vec<_>>(), [0, 1, 2, 3]);
let mut section: Vec<u8> =
ts.chunks(PACKET_SIZE).zip(&pk).filter(|(_, p)| p.pid == 0x1000).flat_map(|(raw, p)| raw[if p.pusi { 5 } else { 4 }..].to_vec()).collect();
let len = 3 + ((section[1] as usize & 0x0F) << 8 | section[2] as usize);
section.truncate(len);
assert_eq!(psi::crc32(&section), 0);
}
/// An output that records the length of every write call.
#[derive(Clone, Default)]
struct Calls(Rc<RefCell<Vec<usize>>>);
impl Write for Calls {
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
self.0.borrow_mut().push(b.len());
Ok(b.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
/// Video and audio for `seconds`, a 2 s GOP at 30 frames a second, in DTS order: (stream, frame).
fn av_timeline(seconds: i64) -> Vec<(usize, Vec<u8>, i64, bool)> {
let mut v = Vec::new();
for k in 0..seconds * 30 {
let key = k % 60 == 0;
let mut f = h264(key);
f.resize(if key { 3000 } else { 700 }, 0x55);
v.push((0, f, 90_000 + k * 3000, key));
}
for k in 0..seconds * 1000 / 32 {
v.push((1, vec![0x0B, 0x77, 0, 0, 0x08, 0x40, 0x40, 1, 2, 3], 90_000 + k * 2880, true));
}
v.sort_by_key(|f| f.2);
v
}
fn av_streams() -> [Stream; 2] {
[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)]
}
#[test]
fn packets_go_out_in_batches() {
for hold in [false, true] {
let calls = Calls::default();
let mut m = Muxer::new(calls.clone(), Config { hold_packets: hold, ..Config::default() }, &av_streams()).unwrap();
for (s, f, t, key) in av_timeline(2) {
m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap();
}
let before = m.stats();
m.flush().unwrap();
let st = m.stats();
// held packets are counted once the output takes them
assert_eq!(before.packets == st.packets, !hold);
m.finish().unwrap();
let lens = calls.0.borrow();
assert!(lens.iter().all(|&n| n % PACKET_SIZE == 0 && n > 0 && n <= 7 * PACKET_SIZE), "{lens:?}");
assert_eq!(lens.iter().sum::<usize>() as u64, st.bytes());
if hold {
assert!(lens[..lens.len() - 1].iter().all(|&n| n == 7 * PACKET_SIZE), "held: full batches only");
} else {
assert!(lens.len() as u64 >= st.frames, "a write at the end of every call");
}
}
}
#[test]
fn held_packets_reach_the_old_writer_before_a_swap() {
let cfg = Config { hold_packets: true, batch_packets: 348, ..Config::default() };
let mut m = Muxer::new(Vec::new(), cfg, &av_streams()).unwrap();
let mut segments = Vec::new();
for (s, f, t, key) in av_timeline(10) {
if s == 0 && key && t > 90_000 {
segments.push(m.replace_writer(Vec::new()));
}
m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap();
}
// held packets count once they reach the output
let held = m.stats();
let last = m.replace_writer(Vec::new());
let st = m.stats();
assert!(held.packets < st.packets);
segments.push(last);
assert_eq!(segments.len(), 5, "a 2 s GOP over 10 s");
let mut packets = 0;
let mut frames = 0;
for (n, seg) in segments.iter().enumerate() {
assert!(seg.error.is_none());
assert_eq!(seg.writer.len() as u64, seg.packets * PACKET_SIZE as u64, "segment {n}");
assert!(seg.starts_with_keyframe, "segment {n}");
let pk = walk(&seg.writer);
assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "segment {n}");
assert!(pk[2].pid == 0x100 && pk[2].pcr.is_some() && pk[2].rai, "segment {n}: the keyframe with a PCR");
assert_eq!(seg.first_pts, Some(90_000 + n as i64 * 180_000));
assert!(seg.last_pts.unwrap() < 90_000 + (n as i64 + 1) * 180_000);
packets += seg.packets;
frames += seg.frames;
}
assert_eq!((packets, frames), (st.packets, st.frames));
// a segment cut before a frame that is not a keyframe says so
let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap();
m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap();
assert!(m.replace_writer(Vec::new()).starts_with_keyframe);
m.write_frame(0, &Frame { data: &h264(false), pts: 93_000, dts: None, key: false }).unwrap();
assert!(!m.replace_writer(Vec::new()).starts_with_keyframe);
}
#[test]
fn a_continuing_swap_leaves_the_packets_unchanged() {
let one = mux(Config::default(), &av_streams(), |m| {
for (s, f, t, key) in av_timeline(3) {
m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap();
}
});
let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap();
let mut parts = Vec::new();
for (n, (s, f, t, key)) in av_timeline(3).into_iter().enumerate() {
if n % 7 == 6 {
parts.push(m.replace_writer_continuing(Vec::new()).writer);
}
m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap();
}
parts.push(m.finish().unwrap());
assert!(parts.len() > 10);
assert_eq!(parts.concat(), one);
}
#[test]
fn a_discontinuity_starts_a_new_time_base() {
for pcr_pid in [None, Some(0x1F0)] {
let mut m = Muxer::new(Vec::new(), Config { pcr_pid, ..Config::default() }, &av_streams()).unwrap();
for (s, f, t, key) in av_timeline(2) {
m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap();
}
let before = m.stats().packets as usize;
m.discontinuity();
// the encoder restarts at a smaller timestamp, the audio first this time
m.write_frame(1, &Frame { data: &[0x0B, 0x77, 9], pts: 100_000, dts: None, key: true }).unwrap();
m.write_frame(0, &Frame { data: &h264(true), pts: 100_000, dts: None, key: true }).unwrap();
m.write_frame(0, &Frame { data: &h264(false), pts: 103_000, dts: None, key: false }).unwrap();
let ts = m.finish().unwrap();
let pk = walk(&ts);
assert!(pk[..before].iter().all(|p| !p.disc));
let after = &pk[before..];
assert_eq!((after[0].pid, after[1].pid), (0, 0x1000), "{pcr_pid:?}: the tables first");
let pcr_on = pcr_pid.unwrap_or(0x100);
let first_pcr = after.iter().find(|p| p.pcr.is_some()).unwrap();
assert_eq!((first_pcr.pid, first_pcr.disc, first_pcr.pcr), (pcr_on, true, Some((100_000 - 63_000) * 300)), "{pcr_pid:?}");
for pid in [0x100, 0x101] {
let first = after.iter().find(|p| p.pid == pid).unwrap();
assert!(first.disc, "{pcr_pid:?}: PID {pid:#x}");
assert_eq!(after.iter().filter(|p| p.pid == pid && p.disc).count(), 1, "{pcr_pid:?}: once on PID {pid:#x}");
}
}
}
#[test]
fn the_clock_after_advance_is_on_the_dts_scale() {
let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap();
m.advance(900_000).unwrap();
let pcrs: Vec<i64> = walk(m.get_ref()).iter().filter_map(|p| p.pcr).collect();
assert_eq!(pcrs, [(900_000 - 63_000) * 300]);
let before = m.get_ref().len();
assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_001, dts: None, key: true }), Err(Error::Timestamp(_))));
assert_eq!(m.get_ref().len(), before);
m.write_frame(0, &Frame { data: &h264(true), pts: 900_000 - 63_000, dts: None, key: true }).unwrap();
}
#[test]
fn streams_may_skew_by_the_pcr_delay() {
let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap();
// video 500 ms ahead of the audio
for k in 0..30i64 {
m.write_frame(0, &Frame { data: &h264(k == 0), pts: 135_000 + k * 3000, dts: None, key: k == 0 }).unwrap();
m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000 + k * 3000, dts: None, key: true }).unwrap();
}
// 800 ms behind the video is refused
let before = m.get_ref().len();
m.write_frame(0, &Frame { data: &h264(false), pts: 900_000, dts: None, key: false }).unwrap();
let mid = m.get_ref().len();
assert!(mid > before);
assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 72_000, dts: None, key: true }), Err(Error::Timestamp(_))));
assert_eq!(m.get_ref().len(), mid);
}
#[test]
fn video_decoding_times_must_increase() {
let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap();
m.write_frame(0, &Frame { data: &h264(true), pts: 93_000, dts: Some(90_000), key: true }).unwrap();
let before = m.get_ref().len();
assert!(matches!(m.write_frame(0, &Frame { data: &h264(false), pts: 96_000, dts: Some(90_000), key: false }), Err(Error::Timestamp(_))));
assert_eq!(m.get_ref().len(), before);
// audio frames may share a time
m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap();
m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap();
}
#[test]
fn video_frames_past_the_reader_limit_are_refused() {
let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap();
// zeroed pages are not touched before the size check
let mut big = vec![0u8; MAX_VIDEO_FRAME + 1];
big[..5].copy_from_slice(&[0, 0, 0, 1, 0x65]);
assert!(matches!(
m.write_frame(0, &Frame { data: &big, pts: 90_000, dts: None, key: true }),
Err(Error::FrameTooLarge { limit: MAX_VIDEO_FRAME, .. })
));
assert_eq!(m.stats(), Stats::default());
assert!(m.get_ref().is_empty());
// an AV1 frame under the limit whose escapes take it over
let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap();
let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::Av1(av1))]).unwrap();
let mut tu = vec![0x0A, 0x05, 0x00, 0x00, 0x00, 0x02, 0x7F, 0x32];
let payload = MAX_VIDEO_FRAME - 100;
let mut n = payload;
while n >= 0x80 {
tu.push((n & 0x7F) as u8 | 0x80);
n >>= 7;
}
tu.push(n as u8);
tu.resize(tu.len() + payload, 0);
*tu.last_mut().unwrap() = 1;
assert!(tu.len() <= MAX_VIDEO_FRAME);
assert!(matches!(
m.write_frame(0, &Frame { data: &tu, pts: 90_000, dts: None, key: true }),
Err(Error::FrameTooLarge { limit: MAX_VIDEO_FRAME, size }) if size > MAX_VIDEO_FRAME
));
assert!(m.get_ref().is_empty());
}
#[test]
fn audio_specific_configs_become_adts_fields() {
let asc = |b: [u8; 2]| Codec::aac_from_asc(&b);
assert_eq!(asc([0x11, 0x90]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 });
assert_eq!(asc([0x12, 0x08]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 4, channels: 1 });
assert_eq!(asc([0x11, 0xB0]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 6 });
assert_eq!(asc([0x11, 0xB8]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 7 });
assert!(asc([0x17, 0x80]).is_err(), "explicit sampling frequency");
assert!(asc([0x29, 0x90]).is_err(), "SBR");
assert!(asc([0x11, 0x80]).is_err(), "channel configuration 0");
assert!(asc([0x11, 0x94]).is_err(), "frameLengthFlag 1");
assert!(Codec::aac_from_asc(&[0x11]).is_err());
}
#[test]
fn opus_trims_follow_the_draft_rules() {
let opus = [Stream::new(0x100, Codec::Opus { channels: 2 }), Stream::new(0x101, Codec::Ac3)];
let mut m = Muxer::new(Vec::new(), Config::default(), &opus).unwrap();
// 8 CELT frames of 20 ms: 7680 samples
let au = [0xFF, 8, 0x11, 0x22];
let f = |k: i64| Frame { data: &au, pts: 90_000 + k * 14_400, dts: None, key: true };
assert!(matches!(m.write_frame_with_trim(1, &f(0), OpusTrim { start: 1, end: 0 }), Err(Error::BadFrame(_))), "not Opus");
assert!(matches!(m.write_frame_with_trim(0, &f(0), OpusTrim { start: 7681, end: 0 }), Err(Error::BadFrame(_))), "longer than the unit");
assert!(matches!(m.write_frame_with_trim(0, &f(0), OpusTrim { start: 8192, end: 0 }), Err(Error::BadFrame(_))), "13 bits");
assert!(m.get_ref().is_empty());
// whole units may be discarded at the start, 65 535 samples in all
for k in 0..8 {
m.write_frame_with_trim(0, &f(k), OpusTrim { start: 7680, end: 0 }).unwrap();
}
assert!(matches!(m.write_frame_with_trim(0, &f(8), OpusTrim { start: 7680, end: 0 }), Err(Error::BadFrame(_))));
m.write_frame_with_trim(0, &f(8), OpusTrim { start: 312, end: 0 }).unwrap();
// the lead-in is over
assert!(matches!(m.write_frame_with_trim(0, &f(9), OpusTrim { start: 1, end: 0 }), Err(Error::BadFrame(_))));
m.write_frame(0, &f(9)).unwrap();
m.write_frame_with_trim(0, &f(10), OpusTrim { start: 0, end: 100 }).unwrap();
// a restarted encoder trims its own start again
m.discontinuity();
m.write_frame_with_trim(0, &f(0), OpusTrim { start: 312, end: 0 }).unwrap();
m.write_frame_with_trim(0, &f(1), OpusTrim { start: 0, end: 100 }).unwrap();
let ts = m.finish().unwrap();
// the last unit's control header: end trim flag, size 4, end_trim 100
let last = ts.chunks(PACKET_SIZE).rev().find(|p| p[1] & 0x40 != 0 && (u16::from(p[1] & 0x1F) << 8 | u16::from(p[2])) == 0x100).unwrap();
let pes = &last[5 + last[4] as usize..];
assert_eq!(&pes[14..19], &[0x7F, 0xE8, 4, 0, 100]);
}
/// Each stream PID's PES packets: (random access indicator of the first packet, bytes).
fn pes_of(ts: &[u8], pids: &[u16]) -> std::collections::HashMap<u16, Vec<(bool, Vec<u8>)>> {
let mut out: std::collections::HashMap<u16, Vec<(bool, Vec<u8>)>> = Default::default();
for (raw, p) in ts.chunks(PACKET_SIZE).zip(walk(ts)) {
if !pids.contains(&p.pid) || !p.payload {
continue;
}
let start = if raw[3] & 0x20 != 0 { 5 + raw[4] as usize } else { 4 };
let list = out.entry(p.pid).or_default();
if p.pusi {
list.push((p.rai, Vec::new()));
}
list.last_mut().unwrap().1.extend_from_slice(&raw[start..]);
}
out
}
/// Reads a timestamp, checking its prefix and marker bits.
fn read_ts(b: &[u8], prefix: u8) -> i64 {
assert_eq!(b[0] >> 4, prefix);
assert_eq!([b[0] & 1, b[2] & 1, b[4] & 1], [1, 1, 1], "marker bits");
(((b[0] >> 1) & 7) as i64) << 30 | (b[1] as i64) << 22 | ((b[2] >> 1) as i64) << 15 | (b[3] as i64) << 7 | (b[4] >> 1) as i64
}
#[test]
fn pes_headers_hold_their_fixed_bits_lengths_and_keyframes() {
let streams = [
Stream::new(0x100, Codec::H264),
Stream::new(0x101, Codec::Ac3),
Stream::new(0x102, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }),
];
let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap();
let mut frames: [Vec<(bool, i64, i64)>; 3] = Default::default();
let mut outputs = Vec::new();
for k in 0..120i64 {
if k % 40 == 0 && k > 0 {
outputs.push(m.replace_writer(Vec::new()).writer);
}
let key = k % 20 == 0;
let mut v = h264(key);
v.resize(if key { 30_000 } else { 70_000 + (k as usize * 997) % 9000 }, 0x55);
let dts = 90_000 + k * 3000;
let pts = dts + if key { 0 } else { 6000 };
m.write_frame(0, &Frame { data: &v, pts, dts: Some(dts), key }).unwrap();
frames[0].push((key, pts, dts));
m.write_frame(1, &Frame { data: &[0x0B, 0x77, 1, 2, 3], pts: dts, dts: None, key: true }).unwrap();
frames[1].push((true, dts, dts));
m.write_frame(2, &Frame { data: &vec![7; 1 + (k as usize * 31) % 1500], pts: dts, dts: None, key: true }).unwrap();
frames[2].push((true, dts, dts));
}
outputs.push(m.finish().unwrap());
let mut seen = [0usize; 3];
for ts in &outputs {
for (pid, list) in pes_of(ts, &[0x100, 0x101, 0x102]) {
let s = usize::from(pid - 0x100);
for (rai, pes) in list {
let (key, pts, dts) = frames[s][seen[s]];
seen[s] += 1;
assert_eq!(&pes[..3], &[0, 0, 1]);
assert_eq!(pes[3], streams[s].codec.stream_id());
assert_eq!(pes[6], 0x84, "'10', data_alignment_indicator");
let length = usize::from(pes[4]) << 8 | usize::from(pes[5]);
if s == 0 && pes.len() - 6 > 0xFFFF {
assert_eq!(length, 0);
} else {
assert_eq!(length, pes.len() - 6, "PID {pid:#x}");
}
assert_eq!(rai, key, "PID {pid:#x}");
if pts == dts {
assert_eq!((pes[7], pes[8]), (0x80, 5));
assert_eq!(read_ts(&pes[9..14], 2), pts);
} else {
assert_eq!((pes[7], pes[8]), (0xC0, 10));
assert_eq!((read_ts(&pes[9..14], 3), read_ts(&pes[14..19], 1)), (pts, dts));
}
}
}
}
assert_eq!(seen, [120, 120, 120]);
}
/// An output that fails on one write call.
struct Flaky {
fail_on: Option<usize>,
calls: usize,
data: Vec<u8>,
}
impl Write for Flaky {
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
self.calls += 1;
if Some(self.calls) == self.fail_on {
return Err(io::Error::other("upload failed"));
}
self.data.extend_from_slice(b);
Ok(b.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn a_new_writer_recovers_from_an_io_error() {
let mut m = Muxer::new(Flaky { fail_on: Some(3), calls: 0, data: Vec::new() }, Config::default(), &av_streams()).unwrap();
let mut failed = false;
let mut recovered = None;
for (s, f, t, key) in av_timeline(2) {
match m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }) {
Ok(()) => {}
Err(Error::Io(_)) if !failed => {
failed = true;
let old = m.replace_writer(Flaky { fail_on: None, calls: 0, data: Vec::new() });
assert_eq!(old.writer.data.len() % PACKET_SIZE, 0);
recovered = Some(m.stats().packets);
}
Err(e) => panic!("{e}"),
}
}
assert!(failed && recovered.is_some());
let ts = m.finish().unwrap().data;
let pk = walk(&ts);
assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000));
assert!(pk.iter().take(4).any(|p| p.pcr.is_some()), "a PCR right after the tables");
// counters run on within the new output
let mut last: std::collections::HashMap<u16, u8> = Default::default();
for p in &pk {
if let Some(&c) = last.get(&p.pid) {
assert_eq!(p.cc, if p.payload { (c + 1) & 0x0F } else { c });
}
last.insert(p.pid, p.cc);
}
}
/// An output that takes `take` bytes in all and then fails.
struct Short {
take: usize,
data: Vec<u8>,
}
impl Write for Short {
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
if self.data.len() >= self.take {
return Err(io::Error::other("disk full"));
}
// at most 100 bytes a call, so a batch goes out in several calls
let n = b.len().min(100).min(self.take - self.data.len());
self.data.extend_from_slice(&b[..n]);
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn packet_counts_hold_only_what_the_output_took() {
let take = 5 * PACKET_SIZE + 50;
let mut m = Muxer::new(Short { take, data: Vec::new() }, Config::default(), &av_streams()).unwrap();
let mut failed = false;
for (s, f, t, key) in av_timeline(1) {
if m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).is_err() {
failed = true;
break;
}
}
assert!(failed);
assert_eq!(m.stats().packets, 5);
let seg = m.replace_writer(Short { take: usize::MAX, data: Vec::new() });
assert_eq!((seg.packets, seg.writer.data.len()), (5, take));
// the new output takes a partial write in several calls and counts every packet
m.write_frame(0, &Frame { data: &h264(true), pts: 200_000, dts: None, key: true }).unwrap();
let st = m.stats();
let seg = m.replace_writer(Short { take: 0, data: Vec::new() });
assert_eq!(seg.writer.data.len() as u64, seg.packets * PACKET_SIZE as u64);
assert_eq!(st.packets, 5 + seg.packets);
}
+260
View File
@@ -0,0 +1,260 @@
//! Frames for the read-back tests, and a packet-level check of what the muxer wrote.
#![allow(dead_code)]
use std::collections::HashMap;
use craft_media::mpegts::mux::{Codec, Frame, Muxer, PACKET_SIZE};
/// A frame queued for the muxer, with the bytes the demuxer should give back for it.
pub struct Item {
pub stream: usize,
pub data: Vec<u8>,
pub pts: i64,
pub dts: i64,
pub key: bool,
pub expect: Vec<u8>,
}
/// Writes `items` in DTS order (stable, so equal DTS keep their order).
pub fn write_all(m: &mut Muxer<Vec<u8>>, items: &mut [Item]) {
items.sort_by_key(|i| i.dts);
for i in items.iter() {
let dts = (i.dts != i.pts).then_some(i.dts);
m.write_frame(i.stream, &Frame { data: &i.data, pts: i.pts, dts, key: i.key }).unwrap();
}
}
pub fn h264(key: bool, disposable: bool, size: usize, seed: u8) -> Vec<u8> {
let mut v = if key {
vec![0, 0, 0, 1, 0x67, 0x42, 0xC0, 0x1E, 0xDA, 0, 0, 0, 1, 0x68, 0xCE, 0x3C, 0x80, 0, 0, 1, 0x65, 0x88, 0x84]
} else if disposable {
vec![0, 0, 0, 1, 0x01, 0x9E]
} else {
vec![0, 0, 0, 1, 0x41, 0x9A]
};
fill(&mut v, size, seed);
v
}
pub fn hevc(key: bool, size: usize, seed: u8) -> Vec<u8> {
let mut v = if key {
vec![0, 0, 0, 1, 0x40, 0x01, 0x0C, 0, 0, 0, 1, 0x42, 0x01, 0x01, 0, 0, 0, 1, 0x44, 0x01, 0xC1, 0, 0, 1, 0x26, 0x01, 0xAF]
} else {
vec![0, 0, 0, 1, 0x02, 0x01, 0xD0]
};
fill(&mut v, size, seed);
v
}
/// An MPEG-2 picture (I with a sequence and GOP header, or P), `size` bytes.
pub fn mpeg2(key: bool, temporal_reference: u16, size: usize, seed: u8) -> Vec<u8> {
let mut v = Vec::new();
if key {
v.extend_from_slice(&[0, 0, 1, 0xB3, 0x14, 0x00, 0xF0, 0x13, 0xFF, 0xFF, 0xE0, 0x18]);
v.extend_from_slice(&[0, 0, 1, 0xB8, 0x00, 0x08, 0x00, 0x00]);
}
let pct: u8 = if key { 1 } else { 2 };
let tr = temporal_reference & 0x3FF;
v.extend_from_slice(&[0, 0, 1, 0x00, (tr >> 2) as u8, ((tr & 3) as u8) << 6 | pct << 3 | 0x07, 0xFF, 0xF8]);
v.extend_from_slice(&[0, 0, 1, 0x01, 0x12]);
fill(&mut v, size, seed);
v
}
/// Pads with bytes that never form a start code.
pub fn fill(v: &mut Vec<u8>, size: usize, seed: u8) {
let mut x = seed as u32 | 1;
while v.len() < size {
x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
v.push(((x >> 16) as u8).max(1));
}
}
/// An ADTS frame: AAC LC, 48 kHz, 2 channels, `payload` bytes after the header.
pub fn adts(payload: usize, seed: u8) -> Vec<u8> {
let len = payload + 7;
let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC];
fill(&mut v, len, seed);
v
}
/// An AC-3 sync frame: 48 kHz, 64 kbit/s, 256 bytes.
pub fn ac3(seed: u8) -> Vec<u8> {
let mut v = vec![0x0B, 0x77, 0, 0, 0x08, 0x40, 0x40];
fill(&mut v, 256, seed);
v
}
/// An MPEG-1 Layer III frame (48 kHz, 128 kbit/s, 384 bytes), or with `low` an MPEG-2 one
/// (24 kHz, 64 kbit/s, 192 bytes).
pub fn mp3(low: bool, seed: u8) -> Vec<u8> {
let (mut v, size) = if low { (vec![0xFF, 0xF3, 0x84, 0x44], 192) } else { (vec![0xFF, 0xFB, 0x94, 0x44], 384) };
fill(&mut v, size, seed);
v
}
/// An E-AC-3 sync frame: independent substream 0, 256 bytes, 48 kHz, six blocks, 2/0, bsid 16.
pub fn eac3(seed: u8) -> Vec<u8> {
let mut v = vec![0x0B, 0x77, 0x00, 0x7F, 0x34, 0x80];
fill(&mut v, 256, seed);
v
}
/// An MPEG-4 Part 2 frame: a visual object sequence, visual object, video object layer and an
/// I-VOP, or a P-VOP alone.
pub fn mpeg4(key: bool, size: usize, seed: u8) -> Vec<u8> {
let mut v = if key {
vec![0, 0, 1, 0xB0, 0x01, 0, 0, 1, 0xB5, 0x09, 0, 0, 1, 0x00, 0, 0, 1, 0x20, 0x00, 0x84, 0x40, 0, 0, 1, 0xB6, 0x10]
} else {
vec![0, 0, 1, 0xB6, 0x50]
};
fill(&mut v, size, seed);
v
}
pub fn leb128(mut n: usize, v: &mut Vec<u8>) {
loop {
let b = (n & 0x7F) as u8;
n >>= 7;
if n == 0 {
v.push(b);
return;
}
v.push(b | 0x80);
}
}
/// An AV1 temporal unit in the low overhead format: a temporal delimiter, a sequence header on
/// keyframes, and a frame OBU whose payload holds sequences that need emulation prevention.
pub fn av1(key: bool, size: usize, seed: u8) -> Vec<u8> {
let mut v = vec![0x12, 0x00];
if key {
v.extend_from_slice(&[0x0A, 0x05, 0x00, 0x00, 0x00, 0x02, 0x7F]);
}
let mut payload = vec![0, 0, 1, 0, 0, 3, 0, 0, 0];
fill(&mut payload, size, seed);
v.push(0x32);
leb128(payload.len(), &mut v);
v.extend_from_slice(&payload);
v
}
/// The OBUs of a temporal unit without its temporal delimiters.
pub fn av1_without_delimiters(tu: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut at = 0;
while at < tu.len() {
let h = tu[at];
let mut i = at + 1 + usize::from(h & 4 != 0);
let (mut size, mut shift) = (0usize, 0);
loop {
let b = tu[i];
i += 1;
size |= usize::from(b & 0x7F) << shift;
shift += 7;
if b & 0x80 == 0 {
break;
}
}
if (h >> 3) & 0x0F != 2 {
out.extend_from_slice(&tu[at..i + size]);
}
at = i + size;
}
out
}
/// Takes the start codes and emulation prevention bytes out of an AV1 PES payload, checking
/// that no 0x000000, 0x000001 or 0x000002 appears inside an OBU and that every 0x000003 is
/// followed by 0x00 to 0x03.
pub fn av1_unescape(es: &[u8]) -> Vec<u8> {
assert!(es.starts_with(&[0, 0, 1]));
let mut out = Vec::new();
let (mut zeros, mut i) = (0, 0);
while i < es.len() {
if zeros == 0 && es[i..].starts_with(&[0, 0, 1]) {
i += 3;
continue;
}
let b = es[i];
i += 1;
if zeros >= 2 {
assert!(b >= 3, "0x0000{b:02X} inside an OBU");
zeros = 0;
if b == 3 {
assert!(es.get(i).is_some_and(|&n| n <= 3), "0x000003 followed by a byte that needs no escape");
continue;
}
out.push(b);
continue;
}
zeros = if b == 0 { zeros + 1 } else { 0 };
out.push(b);
}
out
}
/// The Opus control header and packet the demuxer gives back for an Opus frame.
pub fn opus_unit(packet: &[u8]) -> Vec<u8> {
let mut v = vec![0x7F, 0xE0];
v.extend(std::iter::repeat_n(0xFF, packet.len() / 255));
v.push((packet.len() % 255) as u8);
v.extend_from_slice(packet);
v
}
/// What the demuxer gives back for a video frame: an access unit delimiter first.
pub fn with_aud(codec: Codec, data: &[u8]) -> Vec<u8> {
let mut v = match codec {
Codec::H264 => vec![0, 0, 0, 1, 0x09, 0xF0],
Codec::Hevc => vec![0, 0, 0, 1, 0x46, 0x01, 0x50],
_ => Vec::new(),
};
v.extend_from_slice(data);
v
}
/// Checks the packet layer: sync bytes, continuity counters, adaptation fields, and the PCR on
/// `pcr_pid` never more than `limit` (27 MHz) apart. Returns the PCRs.
pub fn check_packets(ts: &[u8], pcr_pid: u16, limit: i64) -> Vec<i64> {
assert_eq!(ts.len() % PACKET_SIZE, 0);
let mut cc: HashMap<u16, u8> = HashMap::new();
let mut pcrs = Vec::new();
for p in ts.chunks(PACKET_SIZE) {
assert_eq!(p[0], 0x47);
assert_eq!(p[1] & 0x80, 0, "transport error indicator");
assert_eq!(p[3] & 0xC0, 0, "scrambling");
let pid = ((p[1] & 0x1F) as u16) << 8 | p[2] as u16;
let afc = p[3] >> 4 & 3;
assert_ne!(afc, 0);
let payload = afc & 1 != 0;
if let Some(&c) = cc.get(&pid) {
assert_eq!(p[3] & 0x0F, if payload { (c + 1) & 0x0F } else { c }, "continuity on PID {pid:#x}");
}
cc.insert(pid, p[3] & 0x0F);
if afc & 2 != 0 {
let len = p[4] as usize;
assert!(if payload { len <= 182 } else { len == 183 });
if len > 0 && p[5] & 0x10 != 0 {
assert!(len >= 7, "PCR flag in an adaptation field of {len} byte{}", if len == 1 { "" } else { "s" });
assert_eq!(pid, pcr_pid, "a PCR off the PCR PID");
let b = &p[6..12];
assert_eq!(b[4] & 0x7E, 0x7E, "reserved bits");
let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64;
let ext = ((b[4] & 1) as i64) << 8 | b[5] as i64;
assert!(ext < 300);
pcrs.push(base * 300 + ext);
}
if len > 1 {
assert!(p[6 + if p[5] & 0x10 != 0 { 6 } else { 0 }..5 + len].iter().all(|&b| b == 0xFF), "stuffing bytes");
}
}
}
let wrap = (1i64 << 33) * 300;
for w in pcrs.windows(2) {
let d = (w[1] - w[0]).rem_euclid(wrap);
assert!(d > 0 && d <= limit, "PCRs {} apart (limit {limit})", d);
}
pcrs
}
+229
View File
@@ -0,0 +1,229 @@
//! Random programs, frames and timelines: the packet layer stays valid, and every frame reads back
//! with the demuxer, across random idle gaps and output swaps. Random bytes for every codec never
//! panic.
// Test code: a failed unwrap is a failed test.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod mpegts_mux;
use craft_media::mpegts;
use craft_media::mpegts::mux::{Av1Config, Codec, Config, Error, Frame, MAX_PCR_DELAY, MAX_PCR_INTERVAL, Muxer, OpusMapping, OpusTrim, Stream};
use mpegts_mux::*;
use proptest::prelude::*;
/// One step of a plan: (stream, size, DTS step, PTS offset, key, idle time before it, cut before
/// it: 0 none, 1 a new segment, 2 a continuing swap).
type Step = (usize, usize, i64, i64, bool, Option<i64>, u8);
#[derive(Debug, Clone)]
struct Plan {
pcr_interval: u32,
pcr_own: bool,
pcr_delay: u32,
psi_interval: u32,
psi_before_keyframes: bool,
batch_packets: u16,
hold_packets: bool,
frames: Vec<Step>,
}
/// The streams of the read-back property, in the order of `Step`'s stream index.
const STREAMS: usize = 8;
fn plan() -> impl Strategy<Value = Plan> {
let step = (0usize..STREAMS, 1usize..4000, 1i64..12_000, 0i64..9000, any::<bool>(), prop::option::weighted(0.2, 0i64..40_000), 0u8..3);
(
1u32..=MAX_PCR_INTERVAL,
any::<bool>(),
1u32..=MAX_PCR_DELAY,
1u32..200_000,
any::<bool>(),
1u16..400,
any::<bool>(),
prop::collection::vec(step, 5..60),
)
.prop_map(|(pcr_interval, pcr_own, pcr_delay, psi_interval, psi_before_keyframes, batch_packets, hold_packets, frames)| Plan {
pcr_interval,
pcr_own,
pcr_delay,
psi_interval,
psi_before_keyframes,
batch_packets,
hold_packets,
frames,
})
}
/// A frame of stream `s` and the bytes the demuxer gives back for it.
fn frame(s: usize, size: usize, key: bool, n: usize) -> (Vec<u8>, Vec<u8>) {
let seed = n as u8;
match s {
0 => {
let d = h264(key, false, size.max(30), seed);
let e = with_aud(Codec::H264, &d);
(d, e)
}
1 => {
let mut d = vec![0xFC];
fill(&mut d, size.min(1500), seed);
let e = opus_unit(&d);
(d, e)
}
2 => {
let mut d = Vec::new();
fill(&mut d, size.min(2000), seed);
let len = d.len() + 7;
let mut e = vec![0xFF, 0xF1, 0x50, 0x40 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC];
e.extend_from_slice(&d);
(d, e)
}
3 => {
let d = hevc(key, size.max(40), seed);
let e = with_aud(Codec::Hevc, &d);
(d, e)
}
4 => (ac3(seed), ac3(seed)),
5 => (eac3(seed), eac3(seed)),
6 => (mp3(false, seed), mp3(false, seed)),
_ => {
let d = mpeg2(key, (n % 1024) as u16, size.max(40), seed);
(d.clone(), d)
}
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn random_programs_read_back(p in plan()) {
let streams = [
Stream::new(0x100, Codec::H264),
Stream::new(0x101, Codec::Opus { channels: 2 }),
Stream::new(0x102, Codec::Aac { object_type: 2, sample_rate_index: 4, channels: 1 }),
Stream::new(0x103, Codec::Hevc),
Stream::new(0x104, Codec::Ac3),
Stream::new(0x105, Codec::Eac3),
Stream::new(0x106, Codec::MpegAudio { low_sample_rate: false }),
Stream::new(0x107, Codec::Mpeg2Video),
];
let cfg = Config {
pcr_interval: p.pcr_interval,
pcr_pid: p.pcr_own.then_some(0x1F0),
pcr_delay: p.pcr_delay,
psi_interval: p.psi_interval,
psi_before_keyframes: p.psi_before_keyframes,
batch_packets: p.batch_packets,
hold_packets: p.hold_packets,
..Config::default()
};
let mut m = Muxer::new(Vec::new(), cfg, &streams).unwrap();
let mut t = 100_000i64;
let mut want: [Vec<(Vec<u8>, i64, i64)>; STREAMS] = Default::default();
let mut segments = Vec::new();
let mut restarted = false;
for (n, &(s, size, step, offset, key, idle, cut)) in p.frames.iter().enumerate() {
if let Some(idle) = idle {
// an idle gap that ends no later than the next frame's DTS
m.advance(t + idle.min(step)).unwrap();
}
t += step;
match cut {
1 => {
segments.push((true, m.replace_writer(Vec::new())));
restarted = true;
}
2 => segments.push((false, m.replace_writer_continuing(Vec::new()))),
_ => {}
}
let (data, expect) = frame(s, size, key, n);
let pts = if matches!(s, 0 | 3 | 7) { t + offset } else { t };
m.write_frame(s, &Frame { data: &data, pts, dts: Some(t), key }).unwrap();
want[s].push((expect, pts, t));
}
let pcr_pid = m.pcr_pid();
m.flush().unwrap();
let stats = m.stats();
let last = m.finish().unwrap();
// an output that follows `replace_writer` starts with the PAT
let mut parts: Vec<Vec<u8>> = Vec::new();
let mut fresh = false;
for (restart, seg) in segments {
prop_assert!(seg.error.is_none());
prop_assert_eq!(seg.writer.len() as u64, seg.packets * 188);
if fresh && !seg.writer.is_empty() {
prop_assert_eq!((seg.writer[1] & 0x1F, seg.writer[2]), (0, 0));
}
fresh = restart;
parts.push(seg.writer);
}
if fresh && !last.is_empty() {
prop_assert_eq!((last[1] & 0x1F, last[2]), (0, 0));
}
parts.push(last);
let ts = parts.concat();
prop_assert_eq!(ts.len() as u64, stats.bytes());
if stats.pcr_gaps == 0 && !restarted {
check_packets(&ts, pcr_pid, i64::from(p.pcr_interval) * 300);
}
let file = mpegts::open(&ts).unwrap();
prop_assert!(file.warnings.is_empty(), "{:?}", file.warnings);
for (k, w) in want.iter().enumerate() {
let units = &file.streams[k].units;
prop_assert_eq!(units.len(), w.len(), "stream {}", k);
for (n, (u, (bytes, pts, dts))) in units.iter().zip(w).enumerate() {
prop_assert_eq!(u.pts, Some(*pts));
prop_assert_eq!(u.dts.or(u.pts), Some(*dts));
prop_assert_eq!(&file.read_unit(&ts, k, n).unwrap(), bytes);
}
}
}
#[test]
fn random_bytes_never_panic(
codec in 0usize..14,
frames in prop::collection::vec((prop::collection::vec(any::<u8>(), 0..3000), any::<i64>(), prop::option::of(any::<i64>()), any::<bool>(), any::<u16>(), any::<u16>()), 1..30),
interval in 0u32..20_000,
) {
let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap();
let mapped = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] };
let codec = [
Codec::H264,
Codec::Hevc,
Codec::Mpeg2Video,
Codec::AacAdts,
Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 },
Codec::Opus { channels: 2 },
Codec::Ac3,
Codec::MpegAudio { low_sample_rate: false },
Codec::MpegAudio { low_sample_rate: true },
Codec::Mpeg1Video,
Codec::Mpeg4Part2,
Codec::Av1(av1),
Codec::Eac3,
Codec::OpusMapped(mapped),
][codec];
let cfg = Config { pcr_interval: interval, ..Config::default() };
let Ok(mut m) = Muxer::new(Vec::new(), cfg, &[Stream::new(0x100, codec)]) else {
prop_assert!(interval == 0 || interval > MAX_PCR_INTERVAL);
return Ok(());
};
for (n, (data, pts, dts, key, start, end)) in frames.iter().enumerate() {
let trim = if n % 3 == 0 { OpusTrim { start: *start, end: *end } } else { OpusTrim::default() };
match m.write_frame_with_trim(0, &Frame { data, pts: *pts, dts: *dts, key: *key }, trim) {
Ok(()) | Err(Error::BadFrame(_) | Error::EmptyFrame | Error::Timestamp(_) | Error::FrameTooLarge { .. }) => {}
Err(e) => prop_assert!(false, "{e}"),
}
let _ = m.advance(*pts);
if n % 7 == 6 {
m.discontinuity();
}
}
let ts = m.finish().unwrap();
prop_assert_eq!(ts.len() % 188, 0);
// the demuxer recognizes a transport stream by five sync bytes in a row
if ts.len() >= 5 * 188 {
prop_assert!(mpegts::open(&ts).is_ok());
}
}
}
+356
View File
@@ -0,0 +1,356 @@
//! The transport stream writer's output read back with the demuxer: streams, codecs, every
//! frame's bytes and timestamps, keyframes, the PCR, and no continuity or CRC warnings.
// Test code: a failed unwrap is a failed test.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod mpegts_mux;
use craft_media::mpegts::mux::{Av1Config, Codec, Config, Error, Frame, MAX_PCR_INTERVAL, Muxer, OpusMapping, Stream};
use craft_media::mpegts::{self, Codec as Demuxed, StreamId};
use mpegts_mux::*;
const DELAY: i64 = 63_000;
/// Muxes `items`, reads the file back and compares every unit. Returns the file and the PCRs.
fn round_trip(cfg: Config, streams: &[Stream], items: &mut [Item], want: &[Demuxed]) -> (Vec<u8>, Vec<i64>) {
let mut m = Muxer::new(Vec::new(), cfg, streams).unwrap();
write_all(&mut m, items);
let pcr_pid = m.pcr_pid();
let stats = m.stats();
let ts = m.finish().unwrap();
assert_eq!(stats.bytes(), ts.len() as u64);
assert_eq!(stats.frames, items.len() as u64);
let pcrs = check_packets(&ts, pcr_pid, i64::from(cfg.pcr_interval) * 300);
let file = mpegts::open(&ts).unwrap();
assert_eq!(file.format, mpegts::Format::Ts { packet_size: 188, sync_offset: 0 });
assert!(file.warnings.is_empty(), "{:?}", file.warnings);
assert_eq!(file.program, Some(cfg.program_number));
assert_eq!(file.streams.len(), streams.len());
assert!(file.pcr_range.is_some());
for (s, (st, codec)) in file.streams.iter().zip(streams.iter().zip(want)) {
assert_eq!(s.id, StreamId::Pid(st.pid));
assert_eq!(&s.codec, codec, "PID {:#x}", st.pid);
assert_eq!(s.stream_type, st.codec.stream_type());
assert_eq!(s.language, st.language.map(|l| String::from_utf8(l.to_vec()).unwrap()));
}
for (k, _) in streams.iter().enumerate() {
let mine: Vec<&Item> = items.iter().filter(|i| i.stream == k).collect();
let units = &file.streams[k].units;
assert_eq!(units.len(), mine.len(), "stream {k}");
for (n, (u, i)) in units.iter().zip(&mine).enumerate() {
assert_eq!(u.pts, Some(i.pts), "stream {k} unit {n}");
assert_eq!(u.dts.or(u.pts), Some(i.dts), "stream {k} unit {n}");
if streams[k].codec.is_video() && !matches!(want[k], Demuxed::Unknown(_)) {
assert_eq!(u.key, i.key, "stream {k} unit {n}");
}
assert_eq!(file.read_unit(&ts, k, n).unwrap(), i.expect, "stream {k} unit {n}");
}
}
(ts, pcrs)
}
#[test]
fn every_codec_in_one_program() {
let streams = [
Stream::new(0x100, Codec::H264),
Stream::new(0x101, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }).with_language(*b"eng"),
Stream::new(0x102, Codec::Opus { channels: 2 }).with_language(*b"deu"),
Stream::new(0x103, Codec::Ac3),
Stream::new(0x104, Codec::MpegAudio { low_sample_rate: false }),
];
let mut items = Vec::new();
let t0 = 90_000;
for k in 0..90i64 {
// decode order I P B B P B B ...: P pictures shown 3 frames later, B pictures 1 later
let key = k % 30 == 0;
let (disposable, show) = match k % 3 {
0 => (false, 3),
_ => (true, 1),
};
let size = if key { 9000 } else { 300 + (k as usize * 37) % 2000 };
let data = h264(key, disposable && !key, size, k as u8);
let dts = t0 + k * 3000;
items.push(Item { stream: 0, expect: with_aud(Codec::H264, &data), data, pts: dts + show * 3000, dts, key });
}
for k in 0..140i64 {
let raw = {
let mut v = Vec::new();
fill(&mut v, 200 + (k as usize * 13) % 600, k as u8);
v
};
let mut expect = adts(0, 0)[..7].to_vec();
let len = raw.len() + 7;
expect[3] = 0x80 | (len >> 11) as u8;
expect[4] = (len >> 3) as u8;
expect[5] = ((len & 7) as u8) << 5 | 0x1F;
expect.extend_from_slice(&raw);
items.push(Item { stream: 1, data: raw, pts: t0 + k * 1920, dts: t0 + k * 1920, key: true, expect });
}
for k in 0..150i64 {
let mut p = vec![0xFC];
fill(&mut p, 1 + (k as usize * 41) % 700, k as u8);
items.push(Item { stream: 2, expect: opus_unit(&p), data: p, pts: t0 + k * 1800, dts: t0 + k * 1800, key: true });
}
for k in 0..90i64 {
let f = ac3(k as u8);
items.push(Item { stream: 3, expect: f.clone(), data: f, pts: t0 + k * 2880, dts: t0 + k * 2880, key: true });
}
for k in 0..120i64 {
let f = mp3(false, k as u8);
items.push(Item { stream: 4, expect: f.clone(), data: f, pts: t0 + k * 2160, dts: t0 + k * 2160, key: true });
}
let want = [Demuxed::H264, Demuxed::AacAdts, Demuxed::Unknown(6), Demuxed::Ac3, Demuxed::MpegAudio];
let (ts, pcrs) = round_trip(Config::default(), &streams, &mut items, &want);
let file = mpegts::open(&ts).unwrap();
assert_eq!(file.pcr_range, Some((pcrs[0], *pcrs.last().unwrap())));
assert_eq!(pcrs[0], (t0 - DELAY) * 300);
// the frames' own headers read back with the demuxer's frame parser
let aac = file.read_unit(&ts, 1, 0).unwrap();
assert_eq!(mpegts::frame_info(&Demuxed::AacAdts, &aac).map(|i| (i.sample_rate, i.channels)), Some((48_000, 2)));
}
#[test]
fn hevc_with_adts_and_a_pcr_pid_of_its_own() {
let streams = [Stream::new(0x1FFE, Codec::Hevc), Stream::new(0x0010, Codec::AacAdts)];
let cfg = Config { pcr_pid: Some(0x0011), pcr_interval: MAX_PCR_INTERVAL, psi_interval: 45_000, ..Config::default() };
let mut items = Vec::new();
for k in 0..60i64 {
let key = k % 20 == 0;
let data = hevc(key, if key { 20_000 } else { 700 }, k as u8);
let t = 70_000 + k * 3003;
items.push(Item { stream: 0, expect: with_aud(Codec::Hevc, &data), data, pts: t, dts: t, key });
}
for k in 0..95i64 {
let f = adts(150 + k as usize, k as u8);
let t = 70_000 + k * 1920;
items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true });
}
let (ts, _) = round_trip(cfg, &streams, &mut items, &[Demuxed::Hevc, Demuxed::AacAdts]);
let file = mpegts::open(&ts).unwrap();
assert!(file.pcr_range.is_some(), "the demuxer reads the PCR from the PMT's PCR_PID");
}
#[test]
fn mpeg2_video_and_low_rate_mpeg_audio() {
let streams = [Stream::new(0x200, Codec::Mpeg2Video), Stream::new(0x201, Codec::MpegAudio { low_sample_rate: true })];
let mut items = Vec::new();
for k in 0..50i64 {
let key = k % 12 == 0;
let data = mpeg2(key, (k % 12) as u16, if key { 4000 } else { 900 }, k as u8);
let t = 100_000 + k * 3600;
items.push(Item { stream: 0, expect: data.clone(), data, pts: t, dts: t, key });
}
for k in 0..70i64 {
let f = mp3(true, k as u8);
let t = 100_000 + k * 2160;
items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true });
}
round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg2Video, Demuxed::MpegAudio]);
}
#[test]
fn timestamps_run_past_the_33_bit_wrap() {
let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Opus { channels: 1 })];
let start = (1i64 << 33) - 90_000;
let mut items = Vec::new();
for k in 0..90i64 {
let data = h264(k == 0, false, 500, k as u8);
let t = start + k * 3000;
items.push(Item { stream: 0, expect: with_aud(Codec::H264, &data), data, pts: t, dts: t, key: k == 0 });
}
for k in 0..140i64 {
let p = vec![0x08, k as u8 | 1, 0x55];
let t = start + k * 1800;
items.push(Item { stream: 1, expect: opus_unit(&p), data: p, pts: t, dts: t, key: true });
}
round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Unknown(6)]);
}
#[test]
fn eac3_mpeg1_video_and_mpeg4_part2() {
let streams =
[Stream::new(0x100, Codec::Mpeg1Video), Stream::new(0x101, Codec::Eac3).with_language(*b"spa"), Stream::new(0x102, Codec::Mpeg4Part2)];
let mut items = Vec::new();
for k in 0..50i64 {
let key = k % 12 == 0;
let data = mpeg2(key, (k % 12) as u16, if key { 4000 } else { 900 }, k as u8);
let t = 100_000 + k * 3600;
items.push(Item { stream: 0, expect: data.clone(), data, pts: t, dts: t, key });
let data = mpeg4(key, if key { 3000 } else { 600 }, k as u8);
items.push(Item { stream: 2, expect: data.clone(), data, pts: t, dts: t, key });
}
for k in 0..60i64 {
let f = eac3(k as u8);
let t = 100_000 + k * 2880;
items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true });
}
round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg1Video, Demuxed::Eac3, Demuxed::Unknown(0x10)]);
}
#[test]
fn av1_reads_back_as_its_obus() {
let config = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap();
let streams = [Stream::new(0x100, Codec::Av1(config)), Stream::new(0x101, Codec::Opus { channels: 2 })];
let mut tus = Vec::new();
let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap();
for k in 0..60i64 {
let key = k % 30 == 0;
let tu = av1(key, if key { 20_000 } else { 300 + (k as usize * 113) % 3000 }, k as u8);
let t = 90_000 + k * 3000;
m.write_frame(0, &Frame { data: &tu, pts: t, dts: None, key }).unwrap();
m.write_frame(1, &Frame { data: &[0xFC, k as u8 | 1], pts: t, dts: None, key: true }).unwrap();
tus.push((tu, t));
}
let ts = m.finish().unwrap();
check_packets(&ts, 0x100, 3600 * 300);
let file = mpegts::open(&ts).unwrap();
assert!(file.warnings.is_empty(), "{:?}", file.warnings);
assert_eq!(file.streams[0].codec, Demuxed::Unknown(6));
assert_eq!(file.streams[0].stream_type, 0x06);
let units = &file.streams[0].units;
assert_eq!(units.len(), tus.len());
for (n, (u, (tu, t))) in units.iter().zip(&tus).enumerate() {
assert_eq!(u.pts, Some(*t));
let es = file.read_unit(&ts, 0, n).unwrap();
assert_eq!(av1_unescape(&es), av1_without_delimiters(tu), "unit {n}");
}
}
#[test]
fn opus_with_an_explicit_mapping_and_trims() {
let mapping = OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [0, 1, 2, 0, 0, 0, 0, 0] };
let streams = [Stream::new(0x100, Codec::OpusMapped(mapping))];
let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap();
let mut want = Vec::new();
for k in 0..20i64 {
// three streams of 20 ms: two self-delimited packets, then the last one
let au = [0xFC, 1, 0x55, 0xFC, 1, 0x66, 0xFC, 0x77];
let trim = if k == 0 { craft_media::mpegts::mux::OpusTrim { start: 312, end: 0 } } else { Default::default() };
let t = 90_000 + k * 1800;
m.write_frame_with_trim(0, &Frame { data: &au, pts: t, dts: None, key: true }, trim).unwrap();
let mut unit = if k == 0 { vec![0x7F, 0xF0, 8] } else { vec![0x7F, 0xE0, 8] };
if k == 0 {
unit.extend_from_slice(&312u16.to_be_bytes());
}
unit.extend_from_slice(&au);
want.push(unit);
}
let ts = m.finish().unwrap();
let file = mpegts::open(&ts).unwrap();
assert!(file.warnings.is_empty(), "{:?}", file.warnings);
assert_eq!(file.streams[0].units.len(), want.len());
for (n, w) in want.iter().enumerate() {
assert_eq!(&file.read_unit(&ts, 0, n).unwrap(), w);
}
}
#[test]
fn a_discontinuity_reads_back_in_both_time_bases() {
let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)];
let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap();
let mut want: [Vec<(Vec<u8>, i64)>; 2] = Default::default();
for (part, start) in [(0, 900_000i64), (1, 200_000)] {
if part == 1 {
m.discontinuity();
}
for k in 0..30i64 {
let data = h264(k == 0, false, 400, k as u8);
let t = start + k * 3000;
m.write_frame(0, &Frame { data: &data, pts: t, dts: None, key: k == 0 }).unwrap();
want[0].push((with_aud(Codec::H264, &data), t));
let f = adts(100, k as u8);
m.write_frame(1, &Frame { data: &f, pts: t, dts: None, key: true }).unwrap();
want[1].push((f, t));
}
}
let ts = m.finish().unwrap();
let file = mpegts::open(&ts).unwrap();
for (k, w) in want.iter().enumerate() {
let units = &file.streams[k].units;
assert_eq!(units.len(), w.len(), "stream {k}");
for (n, (u, (bytes, t))) in units.iter().zip(w).enumerate() {
assert_eq!(u.pts.map(|p| p.rem_euclid(1 << 33)), Some(*t), "stream {k} unit {n}");
assert_eq!(&file.read_unit(&ts, k, n).unwrap(), bytes, "stream {k} unit {n}");
}
}
}
/// An output that fails on its third write call.
struct Flaky {
fail_on: Option<usize>,
calls: usize,
data: Vec<u8>,
}
impl std::io::Write for Flaky {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
self.calls += 1;
if Some(self.calls) == self.fail_on {
return Err(std::io::Error::other("upload failed"));
}
self.data.extend_from_slice(b);
Ok(b.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn the_output_after_an_io_error_reads_on_its_own() {
let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)];
let mut m = Muxer::new(Flaky { fail_on: Some(3), calls: 0, data: Vec::new() }, Config::default(), &streams).unwrap();
let mut after = [0usize; 2];
let mut failed = false;
for k in 0..60i64 {
let t = 90_000 + k * 3000;
let data = h264(k % 30 == 0, false, 2000, k as u8);
for (s, frame) in
[(0, Frame { data: &data, pts: t, dts: None, key: k % 30 == 0 }), (1, Frame { data: &ac3(k as u8), pts: t, dts: None, key: true })]
{
match m.write_frame(s, &frame) {
Ok(()) if failed => after[s] += 1,
Ok(()) => {}
Err(Error::Io(_)) if !failed => {
failed = true;
m.replace_writer(Flaky { fail_on: None, calls: 0, data: Vec::new() });
}
Err(e) => panic!("{e}"),
}
}
}
assert!(failed);
let ts = m.finish().unwrap().data;
let file = mpegts::open(&ts).unwrap();
assert!(file.warnings.is_empty(), "{:?}", file.warnings);
// every frame written after the error reads back
assert_eq!(file.streams[1].units.len(), after[1]);
assert_eq!(file.streams[0].units.len(), after[0]);
}
#[test]
fn a_single_frame_and_a_huge_one() {
let streams = [Stream::new(0x100, Codec::H264)];
// 1000 bytes: the demuxer needs five packets in a row to recognize the file
let one = h264(true, false, 1000, 1);
let mut items = vec![Item { stream: 0, expect: with_aud(Codec::H264, &one), data: one, pts: 90_000, dts: 90_000, key: true }];
round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264]);
// past PES_packet_length's 65 535 bytes: an unbounded video PES packet
let big = h264(true, false, 3_000_000, 2);
let small = h264(false, false, 100, 3);
let mut items = vec![
Item { stream: 0, expect: with_aud(Codec::H264, &big), data: big, pts: 90_000, dts: 90_000, key: true },
Item { stream: 0, expect: with_aud(Codec::H264, &small), data: small, pts: 93_000, dts: 93_000, key: false },
];
round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264]);
}
#[test]
#[should_panic(expected = "PCR flag in an adaptation field of 1 byte")]
fn the_packet_checker_refuses_a_pcr_flag_in_a_short_adaptation_field() {
// adaptation_field_length 1 holds only the flags byte, so the six bytes after it are payload
let mut p = vec![0x7E; 188];
p[..6].copy_from_slice(&[0x47, 0x01, 0x00, 0x30, 0x01, 0x10]);
check_packets(&p, 0x100, 3600 * 300);
}
+9
View File
@@ -7,6 +7,11 @@ message or a digital ID file is made of.
keeps its exact encoding, so a signed structure is verified over the bytes that were signed.
Reading is strict DER; `parse_ber` also takes indefinite lengths and segmented strings, which
PKCS #12 files from Windows use. Nesting is bounded.
- **`inspection`**: borrowed definite-length cursors without child-list allocations and borrowed X.509 wire fields.
Each sibling list is bounded to 4,096 elements and child cursors to depth 32; callers must
separately bound whole-document traversal. Redundant lengths are flagged. Optional and
trailing fields remain explicitly uninspected until their cursors are consumed. This is
evidence extraction, not a complete certificate validator or a signature/trust verdict.
- **`x509`**: certificates (RFC 5280): names, validity, key, the extensions that matter for
signing (basic constraints, key usage, extended key usage, key identifiers, OCSP and CRL
locations), `build_chain` / `build_chain_noted` (issuers that may issue, path length, validity,
@@ -42,3 +47,7 @@ Weak algorithms are read, not refused, because old signed documents use them:
`DigestAlg::weakness` and `PublicKey::weakness` say when one is weak, and the caller decides.
Moved from PdfCraft's `pdfcraft-sign`.
The inspection profile follows Craft Anything’s bounded reader and Afloat’s raw-certificate
and non-minimal-length contributions (craft-anything #1131, #1514, #1646). Existing verification
and trust APIs are unchanged; high-level CMS/metadata adapters remain separate work.
+186
View File
@@ -0,0 +1,186 @@
//! Bounded, borrowed inspection of definite-length ASN.1 and X.509 wire fields.
//!
//! These views are evidence, not validated certificates or signature/trust verdicts. They do
//! not replace [`crate::x509::Certificate`]. Unknown algorithms and original encodings are kept.
//! The profile follows Craft Anything's inspection reader (including Afloat's raw-field and
//! non-minimal-length work); callers retain their existing semantic and verification checks.
use crate::der::{Tlv, tag};
pub mod cms;
/// Maximum siblings read by one cursor, matching the inspection consumer's bound.
pub const MAX_CHILDREN: usize = 4096;
/// Maximum nesting accepted when obtaining child cursors. Root elements have depth zero.
pub const MAX_DEPTH: usize = 32;
/// An inspection stopped without establishing that the remaining bytes are complete.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum InspectionError {
#[error("malformed or unsupported definite-length element")]
Malformed,
#[error("inspection child limit reached")]
ChildLimit,
#[error("inspection depth limit reached")]
DepthLimit,
#[error("missing or unexpected certificate field")]
Field,
}
/// One borrowed wire element. Redundant definite lengths are readable but explicitly noted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Element<'a> {
tlv: Tlv<'a>,
depth: usize,
non_minimal_length: bool,
}
impl<'a> Element<'a> {
pub fn tag(&self) -> u8 {
self.tlv.tag
}
pub fn raw(&self) -> &'a [u8] {
self.tlv.raw
}
pub fn value(&self) -> &'a [u8] {
self.tlv.value
}
pub fn non_minimal_length(&self) -> bool {
self.non_minimal_length
}
/// Inspect children without allocating a child list. Primitive values are not interpreted as children.
pub fn children(&self) -> Result<Cursor<'a>, InspectionError> {
if self.tlv.tag & 0x20 == 0 {
return Err(InspectionError::Field);
}
// Prevent callers following nested wire fields from silently exceeding the profile.
if self.depth >= MAX_DEPTH {
return Err(InspectionError::DepthLimit);
}
Ok(Cursor::at_depth(self.tlv.value, self.depth + 1))
}
}
/// A non-recursive sibling cursor with a hard per-list work bound and no child-list allocation.
///
/// Successful reads allocate no memory; the underlying parser may allocate an error message.
/// `Ok(None)` means complete input, never a malformed/limited prefix. Errors are sticky and
/// leave the offending remainder available. Separate cursors have separate sibling budgets;
/// this does not impose a global budget on an application's traversal of many lists.
#[derive(Clone, Debug)]
pub struct Cursor<'a> {
remaining: &'a [u8],
count: usize,
depth: usize,
stopped: Option<InspectionError>,
}
impl<'a> Cursor<'a> {
pub fn new(input: &'a [u8]) -> Self {
Self::at_depth(input, 0)
}
fn at_depth(input: &'a [u8], depth: usize) -> Self {
Self { remaining: input, count: 0, depth, stopped: None }
}
/// Bytes not yet inspected. An empty remainder alone is not a recursive DER validation.
pub fn remaining(&self) -> &'a [u8] {
self.remaining
}
pub fn next_element(&mut self) -> Result<Option<Element<'a>>, InspectionError> {
if let Some(error) = self.stopped {
return Err(error);
}
if self.remaining.is_empty() {
return Ok(None);
}
if self.count == MAX_CHILDREN {
self.stopped = Some(InspectionError::ChildLimit);
return Err(InspectionError::ChildLimit);
}
let input = self.remaining;
let (tlv, rest) = match Tlv::parse(input) {
Ok(value) => value,
Err(_) => {
self.stopped = Some(InspectionError::Malformed);
return Err(InspectionError::Malformed);
}
};
let non_minimal_length = input.get(1).is_some_and(|b| b & 0x80 != 0) && (input.get(2) == Some(&0) || tlv.value.len() < 128);
self.remaining = rest;
self.count += 1;
Ok(Some(Element { tlv, depth: self.depth, non_minimal_length }))
}
fn required(&mut self, expected: u8) -> Result<Element<'a>, InspectionError> {
self.next_element()?.filter(|e| e.tag() == expected).ok_or(InspectionError::Field)
}
}
/// Borrowed required X.509 wire fields, without algorithm, signature, key or trust validation.
///
/// The BIT STRING is retained whole, including its unused-bit count. Both AlgorithmIdentifier
/// encodings are retained independently: their equality and parameter policy are the verifier's
/// responsibility. Optional/trailing fields remain in bounded cursors rather than being silently
/// reported as complete. Parsing this view does not walk nested names, keys or extensions.
#[derive(Clone, Debug)]
pub struct CertificateView<'a> {
pub certificate: Element<'a>,
pub tbs: Element<'a>,
pub version: Option<Element<'a>>,
pub serial: Element<'a>,
pub signed_algorithm: Element<'a>,
pub issuer: Element<'a>,
pub validity: Element<'a>,
pub subject: Element<'a>,
pub spki: Element<'a>,
pub signature_algorithm: Element<'a>,
pub signature_bits: Element<'a>,
pub remaining_certificate_fields: Cursor<'a>,
pub remaining_tbs_fields: Cursor<'a>,
}
impl<'a> CertificateView<'a> {
/// Inspect required fields of the first certificate; return bytes following its outer TLV.
/// Readable prefixes do not imply complete optional fields. Inspect the returned cursors to
/// distinguish complete, malformed, and limited tails. Existing strict verification stays separate.
pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> {
let mut roots = Cursor::new(input);
let certificate = roots.required(tag::SEQUENCE)?;
let mut outer = certificate.children()?;
let tbs = outer.required(tag::SEQUENCE)?;
let signature_algorithm = outer.required(tag::SEQUENCE)?;
let signature_bits = outer.required(tag::BIT_STRING)?;
let mut fields = tbs.children()?;
let first = fields.next_element()?.ok_or(InspectionError::Field)?;
let (version, serial) = if first.tag() == tag::ctx(0) {
(Some(first), fields.required(tag::INTEGER)?)
} else if first.tag() == tag::INTEGER {
(None, first)
} else {
return Err(InspectionError::Field);
};
let signed_algorithm = fields.required(tag::SEQUENCE)?;
let issuer = fields.required(tag::SEQUENCE)?;
let validity = fields.required(tag::SEQUENCE)?;
let subject = fields.required(tag::SEQUENCE)?;
let spki = fields.required(tag::SEQUENCE)?;
Ok((
Self {
certificate,
tbs,
version,
serial,
signed_algorithm,
issuer,
validity,
subject,
spki,
signature_algorithm,
signature_bits,
remaining_certificate_fields: outer,
remaining_tbs_fields: fields,
},
roots.remaining(),
))
}
}
+103
View File
@@ -0,0 +1,103 @@
//! Borrowed CMS wire prefixes. These do not validate signed attributes or authenticate signers.
//! Optional/remaining fields are explicit cursors, governed by the parent inspection bounds.
//!
//! Each `parse` starts a new depth root. Callers traversing nested structures must retain their
//! whole-document work/depth policy; reparsing a slice does not carry a previous cursor's budget.
//! The required wire tags and exact SignedData OID are this view's structural profile, not a
//! replacement for a consumer's acceptance or diagnostic policy. Existing parsers remain unchanged.
use super::{Cursor, Element, InspectionError};
use crate::der::tag;
/// Required SignedData fields inside ContentInfo, without copying certificates or content.
/// All optional certificate/CRL/signer sets remain in `remaining_fields` for bounded inspection.
#[derive(Clone, Debug)]
pub struct SignedDataView<'a> {
pub content_info: Element<'a>,
pub signed_data: Element<'a>,
pub version: Element<'a>,
pub digest_algorithms: Element<'a>,
pub encapsulated_content: Element<'a>,
pub remaining_fields: Cursor<'a>,
pub remaining_explicit_fields: Cursor<'a>,
pub remaining_content_info_fields: Cursor<'a>,
}
impl<'a> SignedDataView<'a> {
/// Read the required prefix and retain every tail. Matching the ContentInfo OID is not a
/// signature check. Encapsulated content, certificates, attributes and identities are unvalidated.
pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> {
let mut roots = Cursor::new(input);
let content_info = roots.required(tag::SEQUENCE)?;
let mut fields = content_info.children()?;
let kind = fields.required(tag::OID)?;
if kind.value() != [0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 1, 7, 2] {
return Err(InspectionError::Field);
}
let explicit = fields.required(tag::ctx(0))?;
let mut wrapped = explicit.children()?;
let signed_data = wrapped.required(tag::SEQUENCE)?;
let mut inner = signed_data.children()?;
let version = inner.required(tag::INTEGER)?;
let digest_algorithms = inner.required(tag::SET)?;
let encapsulated_content = inner.required(tag::SEQUENCE)?;
Ok((
Self {
content_info,
signed_data,
version,
digest_algorithms,
encapsulated_content,
remaining_fields: inner,
remaining_explicit_fields: wrapped,
remaining_content_info_fields: fields,
},
roots.remaining(),
))
}
}
/// One SignerInfo's raw required fields, not an authentication or identity-match result.
/// The identity remains its original issuer/serial SEQUENCE or context-specific key identifier.
/// Version consistency, algorithm policy, signed-attribute validation and re-encoding remain the
/// caller's responsibility; this view never substitutes an encapsulated content type or digest.
#[derive(Clone, Debug)]
pub struct SignerInfoView<'a> {
pub signer_info: Element<'a>,
pub version: Element<'a>,
pub identifier: Element<'a>,
pub digest_algorithm: Element<'a>,
pub signed_attributes: Option<Element<'a>>,
pub signature_algorithm: Element<'a>,
pub signature: Element<'a>,
pub remaining_fields: Cursor<'a>,
}
impl<'a> SignerInfoView<'a> {
/// Read one signer's required wire fields, retaining any optional tail and subsequent signers.
/// An absent signature field is an error, not an implicitly empty authenticated signature.
pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> {
let mut roots = Cursor::new(input);
let signer_info = roots.required(tag::SEQUENCE)?;
let mut fields = signer_info.children()?;
let version = fields.required(tag::INTEGER)?;
let identifier = fields.next_element()?.ok_or(InspectionError::Field)?;
if identifier.tag() != tag::SEQUENCE && identifier.tag() != tag::ctx_prim(0) {
return Err(InspectionError::Field);
}
let digest_algorithm = fields.required(tag::SEQUENCE)?;
let next = fields.next_element()?.ok_or(InspectionError::Field)?;
let (signed_attributes, signature_algorithm) = if next.tag() == tag::ctx(0) {
(Some(next), fields.required(tag::SEQUENCE)?)
} else if next.tag() == tag::SEQUENCE {
(None, next)
} else {
return Err(InspectionError::Field);
};
let signature = fields.required(tag::OCTET_STRING)?;
Ok((
Self { signer_info, version, identifier, digest_algorithm, signed_attributes, signature_algorithm, signature, remaining_fields: fields },
roots.remaining(),
))
}
}
+1
View File
@@ -29,6 +29,7 @@
pub mod cms;
pub mod der;
mod ec512;
pub mod inspection;
pub mod keys;
pub mod pkcs12;
pub mod revocation;
+119
View File
@@ -0,0 +1,119 @@
//! Benign wire parity and boundary tests; no signature/trust decisions are made by these views.
use craft_pkcs7::der::{self, tag};
use craft_pkcs7::inspection::{CertificateView, Cursor, InspectionError, MAX_CHILDREN, MAX_DEPTH};
#[test]
fn cursor_keeps_exact_bytes_and_length_notes() {
for (encoded, note) in [(vec![4, 3, 1, 2, 3], false), (vec![4, 0x81, 3, 1, 2, 3], true), (vec![4, 0x82, 0, 3, 1, 2, 3], true)] {
let mut cursor = Cursor::new(&encoded);
let element = cursor.next_element().unwrap().unwrap();
assert_eq!(element.raw(), encoded);
assert_eq!(element.raw().as_ptr(), encoded.as_ptr());
assert_eq!(element.value(), &[1, 2, 3]);
assert_eq!(element.non_minimal_length(), note);
assert_eq!(cursor.next_element(), Ok(None));
}
let canonical = der::octets(&[7; 128]);
assert!(!Cursor::new(&canonical).next_element().unwrap().unwrap().non_minimal_length());
}
#[test]
fn cursor_distinguishes_completion_and_sticky_partial_results() {
let bytes = [5, 0, 4]; // One complete NULL followed by an incomplete header.
let mut cursor = Cursor::new(&bytes);
assert_eq!(cursor.next_element().unwrap().unwrap().tag(), tag::NULL);
assert_eq!(cursor.next_element(), Err(InspectionError::Malformed));
assert_eq!(cursor.next_element(), Err(InspectionError::Malformed));
assert_eq!(cursor.remaining(), &[4]);
assert_eq!(Cursor::new(&[0x30, 0x80, 0, 0]).next_element(), Err(InspectionError::Malformed));
assert_eq!(Cursor::new(&[0x30, 0]).next_element().unwrap().unwrap().raw(), &[0x30, 0]);
}
#[test]
fn sibling_limit_allows_exact_completion_without_allocating_a_child_list() {
let mut bytes = [5, 0].repeat(MAX_CHILDREN);
let mut cursor = Cursor::new(&bytes);
for _ in 0..MAX_CHILDREN {
assert!(cursor.next_element().unwrap().is_some());
}
assert_eq!(cursor.next_element(), Ok(None));
bytes.extend_from_slice(&[5, 0]);
let mut cursor = Cursor::new(&bytes);
for _ in 0..MAX_CHILDREN {
cursor.next_element().unwrap();
}
assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit));
assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit));
assert_eq!(cursor.remaining(), &[5, 0]);
}
#[test]
fn nested_cursor_depth_is_explicitly_bounded() {
let mut bytes = der::seq(&[]);
for _ in 0..MAX_DEPTH {
bytes = der::seq(&[&bytes]);
}
let mut element = Cursor::new(&bytes).next_element().unwrap().unwrap();
for _ in 0..MAX_DEPTH {
element = element.children().unwrap().next_element().unwrap().unwrap();
}
assert!(matches!(element.children(), Err(InspectionError::DepthLimit)));
}
fn certificate(version: bool, tail: &[u8]) -> (Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>) {
// Unknown algorithms are still inspectable. These are wire fixtures, not signed certificates.
let algorithm = der::seq(&[&der::oid("1.2.3.4"), &der::tlv(tag::NULL, &[])]);
let name = der::seq(&[]);
let spki = der::seq(&[&algorithm, &der::bit_string(&[1, 2, 3])]);
let version_field = if version { der::explicit(0, &der::int(2)) } else { vec![] };
let tbs = der::seq(&[&version_field, &der::int(7), &algorithm, &name, &der::seq(&[]), &name, &spki, tail]);
let cert = der::seq(&[&tbs, &algorithm, &der::bit_string(&[9, 8, 7])]);
(cert, tbs, algorithm, spki)
}
#[test]
fn certificate_fields_are_borrowed_exact_and_do_not_consume_trailing_input() {
for version in [false, true] {
let (mut bytes, tbs, algorithm, spki) = certificate(version, &[]);
let len = bytes.len();
bytes.extend_from_slice(&[5, 0]);
let (mut view, rest) = CertificateView::parse(&bytes).unwrap();
assert_eq!(view.certificate.raw(), &bytes[..len]);
assert_eq!(view.certificate.raw().as_ptr(), bytes.as_ptr());
assert_eq!(view.tbs.raw(), tbs);
assert_eq!(view.signed_algorithm.raw(), algorithm);
assert_eq!(view.signature_algorithm.raw(), algorithm);
assert_eq!(view.spki.raw(), spki);
assert_eq!(view.serial.value(), &[7]);
assert_eq!(view.signature_bits.value(), &[0, 9, 8, 7]);
assert_eq!(view.version.is_some(), version);
assert_eq!(rest, &[5, 0]);
assert_eq!(view.remaining_tbs_fields.next_element(), Ok(None));
assert_eq!(view.remaining_certificate_fields.next_element(), Ok(None));
}
}
#[test]
fn required_fields_do_not_hide_optional_tail_diagnostics() {
let (bytes, _, _, _) = certificate(false, &[0xa3]);
let (mut view, _) = CertificateView::parse(&bytes).unwrap();
assert_eq!(view.remaining_tbs_fields.remaining(), &[0xa3]);
assert_eq!(view.remaining_tbs_fields.next_element(), Err(InspectionError::Malformed));
// This partial wire view is deliberately not accepted as a validated certificate.
assert!(craft_pkcs7::Certificate::parse(&bytes).is_err());
}
#[test]
fn existing_certificate_fixture_retains_signed_components() {
let cert = craft_pkcs7::x509::load_certificates(include_bytes!("../data/ca.crt.pem")).unwrap().remove(0);
let (view, rest) = CertificateView::parse(&cert.raw).unwrap();
assert!(rest.is_empty());
let parts = cert.clone().into_parts();
assert_eq!(view.tbs.raw(), parts.tbs);
assert_eq!(view.signature_algorithm.raw(), parts.sig_alg);
assert_eq!(view.signature_bits.value().first(), Some(&0));
assert_eq!(&view.signature_bits.value()[1..], parts.signature);
assert_eq!(view.issuer.raw(), parts.issuer.raw);
assert_eq!(view.subject.raw(), parts.subject.raw);
assert_eq!(view.spki.raw(), parts.public_key.spki());
}
+111
View File
@@ -0,0 +1,111 @@
use craft_pkcs7::der::{self, tag};
use craft_pkcs7::inspection::InspectionError;
use craft_pkcs7::inspection::cms::{SignedDataView, SignerInfoView};
fn fixture(key_id: bool, attrs: bool) -> (Vec<u8>, Vec<u8>) {
let digest = der::seq(&[&der::oid("2.16.840.1.101.3.4.2.1")]);
let sig_alg = der::seq(&[&der::oid("1.2.840.113549.1.1.1"), &der::tlv(tag::NULL, &[])]);
let identifier = if key_id { der::tlv(tag::ctx_prim(0), &[7, 8]) } else { der::seq(&[&der::seq(&[]), &der::int(7)]) };
let attributes = if attrs {
let content = der::seq(&[&der::oid("1.2.840.113549.1.9.3"), &der::set_of(&[&der::oid("1.2.840.113549.1.7.1")])]);
let digest_attr = der::seq(&[&der::oid("1.2.840.113549.1.9.4"), &der::set_of(&[&der::octets(&[6; 32])])]);
der::tlv(tag::ctx(0), &[content, digest_attr].concat())
} else {
vec![]
};
let signer = der::seq(&[&der::int(if key_id { 3 } else { 1 }), &identifier, &digest, &attributes, &sig_alg, &der::octets(&[1, 2, 3])]);
let content = der::seq(&[&der::oid("1.2.840.113549.1.7.1"), &der::explicit(0, &der::octets(b"hello"))]);
let signed_data = der::seq(&[&der::int(1), &der::set_of(&[&digest]), &content, &der::set_of(&[&signer])]);
(der::seq(&[&der::oid("1.2.840.113549.1.7.2"), &der::explicit(0, &signed_data)]), signer)
}
#[test]
fn cms_fields_retain_encodings_and_both_identifier_forms() {
for key_id in [false, true] {
for attrs in [false, true] {
let (cms, signer) = fixture(key_id, attrs);
let (mut view, rest) = SignedDataView::parse(&cms).unwrap();
assert!(rest.is_empty());
assert_eq!(view.content_info.raw().as_ptr(), cms.as_ptr());
assert_eq!(view.version.value(), &[1]);
let signer_set = view.remaining_fields.next_element().unwrap().unwrap();
let (mut si, rest) = SignerInfoView::parse(signer_set.value()).unwrap();
assert_eq!(si.signer_info.raw(), signer);
assert!(rest.is_empty());
assert_eq!(si.identifier.tag(), if key_id { 0x80 } else { 0x30 });
assert_eq!(si.signed_attributes.is_some(), attrs);
assert_eq!(si.signature.value(), &[1, 2, 3]);
assert_eq!(si.remaining_fields.next_element(), Ok(None));
assert_eq!(view.remaining_fields.next_element(), Ok(None));
assert_eq!(view.remaining_explicit_fields.next_element(), Ok(None));
assert_eq!(view.remaining_content_info_fields.next_element(), Ok(None));
}
}
}
#[test]
fn signer_prefix_does_not_hide_optional_tail_or_consume_next_signer() {
let (_, signer) = fixture(false, true);
let parsed = der::Tlv::parse_all(&signer).unwrap();
let with_tail = der::seq(&[parsed.value, &[0xa1]]);
let joined = [with_tail, signer.clone()].concat();
let (mut view, rest) = SignerInfoView::parse(&joined).unwrap();
assert_eq!(rest, signer);
assert_eq!(view.remaining_fields.next_element(), Err(InspectionError::Malformed));
assert_eq!(view.remaining_fields.remaining(), &[0xa1]);
}
// Ordinary optional sets and complete trailing TLVs, never interpreted as trust evidence here.
fn optional_fixture(certificate_count: usize, with_crl: bool, tails: bool) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
let certificate = craft_pkcs7::x509::load_certificates(include_bytes!("../data/ca.crt.pem")).unwrap().remove(0).raw;
let (base, signer) = fixture(false, true);
let (view, _) = SignedDataView::parse(&base).unwrap();
let certificates = der::tlv(tag::ctx(0), &certificate.repeat(certificate_count));
let crl = if with_crl { der::tlv(tag::ctx(1), &der::seq(&[])) } else { vec![] };
let tail = if tails { der::tlv(tag::NULL, &[]) } else { vec![] };
let signed_data = der::seq(&[
view.version.raw(),
view.digest_algorithms.raw(),
view.encapsulated_content.raw(),
&certificates,
&crl,
&der::set_of(&[&signer]),
&tail,
]);
let wrapped = der::tlv(tag::ctx(0), &[signed_data, tail.clone()].concat());
let content = der::seq(&[&der::oid("1.2.840.113549.1.7.2"), &wrapped, &tail]);
([content, tail].concat(), certificate, crl)
}
#[test]
fn optional_certificate_crl_sets_and_all_tails_remain_visible() {
for with_crl in [false, true] {
let (bytes, cert, crl) = optional_fixture(2, with_crl, true);
let (mut view, rest) = SignedDataView::parse(&bytes).unwrap();
assert_eq!(rest, &[5, 0]);
let certs = view.remaining_fields.next_element().unwrap().unwrap();
assert_eq!(certs.tag(), tag::ctx(0));
assert_eq!(certs.value(), cert.repeat(2));
if with_crl {
assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().raw(), crl);
}
assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().tag(), tag::SET);
for cursor in [&mut view.remaining_fields, &mut view.remaining_explicit_fields, &mut view.remaining_content_info_fields] {
assert_eq!(cursor.next_element().unwrap().unwrap().raw(), &[5, 0]);
assert_eq!(cursor.next_element(), Ok(None));
}
}
}
#[test]
fn signer_unsigned_attributes_remain_raw_and_separate_from_signed_attributes() {
let (_, signer) = fixture(true, true);
let fields = der::Tlv::parse_all(&signer).unwrap();
let unsigned = der::tlv(tag::ctx(1), &der::seq(&[]));
let bytes = der::seq(&[fields.value, &unsigned]);
let (mut view, rest) = SignerInfoView::parse(&bytes).unwrap();
assert!(rest.is_empty());
assert_eq!(view.signed_attributes.unwrap().tag(), tag::ctx(0));
assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().raw(), unsigned);
assert_eq!(view.remaining_fields.next_element(), Ok(None));
}
+3
View File
@@ -5,4 +5,7 @@ mod ber;
mod chain;
mod cms;
mod crypto;
mod inspection;
mod store_keys;
mod inspection_cms;
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "craft-ppt-binary"
description = "Reader for the PowerPoint 97-2003 binary file format (.ppt, .pot, .pps; [MS-PPT], [MS-ODRAW]) into the craft-pptx presentation model, on craft-cfb."
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
craft-cfb = { workspace = true }
craft-drawingml = { workspace = true }
craft-pptx = { workspace = true }
log = { workspace = true }
miniz_oxide = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
# Pictures in the tests: a PNG to embed, and the BMP a DIB blip becomes.
image = { version = "0.25", default-features = false, features = ["png", "bmp"] }
+40
View File
@@ -0,0 +1,40 @@
# craft-ppt-binary
Reader for the PowerPoint 97-2003 binary file format (`.ppt`, `.pot` and `.pps`) into the
`craft-pptx` presentation model. It is DeckCraft's reader, on `craft-cfb` for the compound file.
Import only: there is no `.ppt` writer.
| Document | Used for |
|---|---|
| [MS-PPT] PowerPoint (.ppt) Binary File Format (Microsoft Open Specifications) | the Current User stream, the edit chain and persist directories, documents, masters, slides, notes, text and its styles, headers and footers |
| [MS-ODRAW] Office Drawing Binary File Formats | shapes, their property tables and geometry, the BLIP store and its pictures |
| [MS-CFB] Compound File Binary File Format | through `craft-cfb` |
```rust
// Not a compound file: an error, never a panic.
assert!(!craft_ppt_binary::sniff(b"not a .ppt"));
assert!(craft_ppt_binary::import(b"not a .ppt", &craft_pptx::Plain).is_err());
```
- `sniff(bytes)`, `import(bytes, &defaults)` and `import_checked(bytes, &defaults)`, which also
names the slides the file lists but whose objects are gone.
- Main masters become masters, with their colour scheme, fonts, text styles, background and
decorative shapes. Title masters become layouts of their main master.
- Slides keep their shapes (preset and freeform geometry, groups, rotation and flips), fills,
lines, shadows, pictures (PNG, JPEG, DIB, TIFF, EMF and WMF), tables (as groups of shapes, the
way the file stores them), and text with the master's styles resolved into it, along with
fields, numbering, headers and footers, notes, and hidden slides.
- Damaged files read as far as they can: a broken edit chain falls back to a scan of the edits,
and unknown or damaged records are skipped. Sizes, counts, nesting and picture decoding are
bounded.
- Password-protected files are refused (`PptError::Encrypted`), as are PowerPoint 95 and earlier
files (`PptError::TooOld`).
The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from:
its layouts and placeholders. The file's masters then place and style the placeholders that
master has. With `craft_pptx::Plain` (one blank layout, no placeholders), the slides still read
with their own boxes.
The reader was written for DeckCraft (storytold/deckcraft#1137); the history of
`crates/ppt-binary` names its authors. Its tests build `.ppt` files from records; no file made
by PowerPoint is used.
+404
View File
@@ -0,0 +1,404 @@
//! Pictures ([MS-ODRAW] §2.2.32–2.2.45): the drawing group's blip store lists every picture
//! (`FBSE`), either holding its blip or pointing into the `Pictures` stream. Shapes name a picture
//! by its 1-based index in the store.
use crate::doc::rt;
use crate::record::Rec;
/// Largest picture inflated from a compressed metafile.
const MAX_INFLATED: usize = 64 << 20;
/// Most bytes all of a file's pictures may decode to together: 2 GiB, the total a `.pptx` package
/// may inflate to (`craft_pptx::MAX_TOTAL`). Pictures are the only part of a `.ppt`
/// that inflates, so a small hostile file can't make the import hold more than a `.pptx` could.
/// It also fits a 32-bit `usize` (wasm32), where a 4 GiB constant wraps to 0.
const MAX_TOTAL: usize = 2 << 30;
// A zero or tiny budget would drop every picture without a word, and the shift above can wrap on
// a 32-bit target (wasm32) without any error, so the build checks it on every target.
const _: () = assert!(MAX_TOTAL >= MAX_INFLATED);
/// A decoded picture: file extension, content type and bytes as a file of that type.
#[derive(Clone, Debug, PartialEq)]
pub struct Picture {
pub ext: &'static str,
pub content_type: &'static str,
pub data: Vec<u8>,
}
/// The blip store: each entry's blip record, decoded only when a shape first asks for it, every
/// entry at most once, and all of them together within [`MAX_TOTAL`] bytes.
pub struct Store<'a> {
entries: Vec<Option<Rec<'a>>>,
budget: usize,
}
impl<'a> Store<'a> {
pub fn new(dgg: Option<Rec<'a>>, pictures_stream: &'a [u8]) -> Self {
let entries = match dgg.and_then(|d| d.child(rt::BSTORE)) {
Some(bstore) => bstore.children().map(|r| if r.kind == rt::FBSE { fbse(&r, pictures_stream) } else { None }).collect(),
None => vec![],
};
Store { entries, budget: MAX_TOTAL }
}
/// The picture at `index` (0-based; shapes use 1-based ids), taken out of the store. `None`
/// for an entry that is empty, can't be read, was taken already, or would pass the budget.
pub fn take(&mut self, index: usize) -> Option<Picture> {
let blip = self.entries.get_mut(index)?.take()?;
self.decode_charged(&blip)
}
/// A blip held in a shape's own property ([MS-ODRAW] §2.2.37: a complex `fillBlip` or `pib`
/// whose extra bytes are the blip record itself), decoded within the same budget.
pub fn decode_inline(&mut self, bytes: &[u8]) -> Option<Picture> {
let blip = Rec::at(bytes, 0).filter(|r| (0xF018..=0xF117).contains(&r.kind))?;
self.decode_charged(&blip)
}
/// Decode `blip` and take its size from the budget. A compressed metafile is also charged
/// its compressed bytes, which inflating reads whatever it produces, and one that fails to
/// inflate is charged what the inflate may have produced before failing: many entries pointing
/// at one damaged stream (or one that inflates to nothing) would otherwise each inflate it again
/// for free.
fn decode_charged(&mut self, blip: &Rec) -> Option<Picture> {
let bounds = inflate_bounds(blip, self.budget);
let pic = decode(blip, self.budget);
let cost = match (&pic, bounds) {
(Some(p), Some((input, _))) => input.saturating_add(p.data.len()),
(Some(p), None) => p.data.len(),
(None, Some((input, output))) => input.saturating_add(output),
(None, None) => 0,
};
self.budget = self.budget.saturating_sub(cost);
pic
}
}
/// For a compressed metafile (EMF or WMF, with one UID or, for instances 0x3D5 and 0x217, two):
/// the compressed bytes inflating it reads, and the most bytes it may produce so that both
/// together stay within `limit`. `None` for any other blip, or when the compressed bytes alone
/// pass `limit`.
fn inflate_bounds(b: &Rec, limit: usize) -> Option<(usize, usize)> {
if !matches!(b.kind, 0xF01A | 0xF01B) {
return None;
}
let uids = if matches!(b.instance, 0x3D5 | 0x217) { 32 } else { 16 };
let h = b.data.get(uids..uids + 34)?;
let size = crate::record::u32_at(h, 0)? as usize;
if *h.get(32)? != 0 {
return None;
}
let input = b.data.get(uids + 34..)?.len();
let output = limit.checked_sub(input)?;
Some((input, size.min(MAX_INFLATED).min(output)))
}
fn fbse<'a>(r: &Rec<'a>, pictures: &'a [u8]) -> Option<Rec<'a>> {
// btWin32, btMacOS, rgbUid[16], tag, size, cRef, foDelay, unused, cbName, unused, unused.
let size = r.u32(20)? as usize;
let offset = r.u32(28)? as usize;
let name_len = usize::from(r.u8(33)?);
if size == 0 {
return None;
}
let embedded_at = 36usize.checked_add(name_len)?;
if r.data.len() > embedded_at { Rec::at(r.data, embedded_at) } else { Rec::at(pictures, offset) }
}
/// Decode one blip record into at most `limit` bytes.
pub fn decode(b: &Rec, limit: usize) -> Option<Picture> {
// The instance says whether a second UID follows the first.
let (kind, two_uids): (u16, bool) = match b.instance {
0x3D4 | 0x216 | 0x542 | 0x46A | 0x6E2 | 0x6E0 | 0x7A8 | 0x6E4 => (b.kind, false),
0x3D5 | 0x217 | 0x543 | 0x46B | 0x6E3 | 0x6E1 | 0x7A9 | 0x6E5 => (b.kind, true),
_ => (b.kind, false),
};
let uids = if two_uids { 32 } else { 16 };
// The bytes a picture is copied from, refused before copying when they (plus `extra` bytes of
// header to add) would pass the budget.
let within = |bytes: &'_ [u8], extra: usize| bytes.len().checked_add(extra).is_some_and(|n| n <= limit);
let bitmap = || b.data.get(uids + 1..).filter(|d| within(d, 0)).map(<[u8]>::to_vec);
match kind {
// EMF, WMF: a metafile header then (usually deflated) data.
0xF01A | 0xF01B => {
let h = b.data.get(uids..uids + 34)?;
let size = crate::record::u32_at(h, 0)? as usize;
let compressed = *h.get(32)? == 0;
let body = b.data.get(uids + 34..)?;
let data = if compressed {
miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(body, inflate_bounds(b, limit)?.1).ok()?
} else {
body.get(..size.min(body.len())).filter(|d| within(d, 0))?.to_vec()
};
let (ext, content_type) = if kind == 0xF01A { ("emf", "image/x-emf") } else { ("wmf", "image/x-wmf") };
Some(Picture { ext, content_type, data })
}
// Bitmaps: a one-byte tag then the file.
0xF01D | 0xF02A => Some(Picture { ext: "jpg", content_type: "image/jpeg", data: bitmap()? }),
0xF01E => Some(Picture { ext: "png", content_type: "image/png", data: bitmap()? }),
0xF029 => Some(Picture { ext: "tif", content_type: "image/tiff", data: bitmap()? }),
0xF01F => Some(Picture { ext: "bmp", content_type: "image/bmp", data: dib_to_bmp(b.data.get(uids + 1..).filter(|d| within(d, 14))?)? }),
// PICT (Macintosh) has no decoder here.
_ => None,
}
.filter(|p| p.data.len() <= limit)
}
/// A device-independent bitmap with the 14-byte file header a `.bmp` needs in front.
fn dib_to_bmp(dib: &[u8]) -> Option<Vec<u8>> {
let header = crate::record::u32_at(dib, 0)? as usize;
let (bits, compression, used) = if header == 12 {
(usize::from(crate::record::u16_at(dib, 10)?), 0, 0)
} else {
(usize::from(crate::record::u16_at(dib, 14)?), crate::record::u32_at(dib, 16)?, crate::record::u32_at(dib, 32)? as usize)
};
let entry = if header == 12 { 3 } else { 4 };
// The colour table: up to 2^bits entries (all of them when biClrUsed is 0) for 8 bits or
// fewer; biClrUsed entries, an optional table, for more.
let colors = match bits {
0..=8 if used > 0 => used.min(1 << bits),
0..=8 => 1 << bits,
_ => used,
};
// BI_BITFIELDS with the 40-byte header: three masks follow it.
let masks = if compression == 3 && header == 40 { 12 } else { 0 };
let offset = 14usize.checked_add(header)?.checked_add(colors.checked_mul(entry)?)?.checked_add(masks)?;
let file_len = 14usize.checked_add(dib.len())?;
// Pixels starting past the end are no bitmap.
if offset > file_len {
return None;
}
let total = u32::try_from(file_len).ok()?;
let mut out = Vec::with_capacity(dib.len() + 14);
out.extend_from_slice(b"BM");
out.extend_from_slice(&total.to_le_bytes());
out.extend_from_slice(&[0; 4]);
out.extend_from_slice(&u32::try_from(offset).ok()?.to_le_bytes());
out.extend_from_slice(dib);
Some(out)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::record::build::*;
fn decode_all(b: &Rec) -> Option<Picture> {
decode(b, usize::MAX)
}
/// Many entries pointing at one deflated metafile decode within the shared budget, each
/// at most once.
#[test]
fn the_store_decodes_lazily_within_a_budget() {
let wmf = vec![7u8; 1000];
let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6);
let mut header = vec![0u8; 34];
header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes());
let pictures = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat());
let mut fbse = vec![0u8; 36];
fbse[20..24].copy_from_slice(&(pictures.len() as u32).to_le_bytes());
let entries: Vec<Vec<u8>> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect();
let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]);
let mut store = Store::new(Rec::at(&dgg, 0), &pictures);
store.budget = 2500;
assert_eq!(store.take(0).map(|p| p.data.len()), Some(1000));
assert!(store.take(0).is_none(), "taken already");
assert!(store.take(1).is_some());
assert!(store.take(2).is_none(), "past the budget");
assert!(store.take(99).is_none());
}
/// A compressed metafile that fails to inflate still costs the budget what it may have
/// inflated, so entries pointing at one damaged stream can't each inflate it again for free.
#[test]
fn a_failed_inflate_is_charged_to_the_budget() {
let mut header = vec![0u8; 34];
header[..4].copy_from_slice(&1000u32.to_le_bytes());
let damaged = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &[0x78, 0x9C, 0xFF, 0xFF]].concat());
let mut fbse = vec![0u8; 36];
fbse[20..24].copy_from_slice(&(damaged.len() as u32).to_le_bytes());
let entries: Vec<Vec<u8>> = (0..3).map(|_| atom(rt::FBSE, 3, &fbse)).collect();
let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 3, &entries)]);
let mut store = Store::new(Rec::at(&dgg, 0), &damaged);
store.budget = 2500;
assert!(store.take(0).is_none());
assert_eq!(store.budget, 1496, "1000 bytes it may have inflated and the 4 it read");
assert!(store.take(1).is_none());
assert!(store.take(2).is_none());
assert_eq!(store.budget, 0, "the last attempt is charged what was left");
// A picture that isn't a compressed metafile costs nothing when it can't be read.
let mut store = Store::new(None, &[]);
store.budget = 10;
assert!(store.decode_inline(&atom(0xF01E, 0x6E0, &[0; 4])).is_none());
assert_eq!(store.budget, 10);
}
/// A compressed metafile that inflates to nothing (a declared size of 0 and a run of empty
/// stored blocks, here with a bad checksum) still costs the bytes it makes the inflate read, so
/// many entries pointing at it run out of budget instead of each reading it again for free.
#[test]
fn inflating_is_charged_the_compressed_bytes() {
let mut z = vec![0x78, 0x01];
for _ in 0..200 {
z.extend_from_slice(&[0x00, 0x00, 0x00, 0xFF, 0xFF]);
}
z.extend_from_slice(&[0x01, 0x00, 0x00, 0xFF, 0xFF, 1, 2, 3, 4]);
let empty = atom(0xF01B, 0x216, &[&[0u8; 16][..], &[0u8; 34], &z].concat());
let mut fbse = vec![0u8; 36];
fbse[20..24].copy_from_slice(&(empty.len() as u32).to_le_bytes());
let entries: Vec<Vec<u8>> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect();
let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]);
let mut store = Store::new(Rec::at(&dgg, 0), &empty);
store.budget = 2 * z.len() + 10;
assert!(store.take(0).is_none());
assert_eq!(store.budget, z.len() + 10);
assert!(store.take(1).is_none());
assert_eq!(store.budget, 10);
// Too little left for its compressed bytes: not inflated, and nothing charged.
assert!(store.take(2).is_none());
assert_eq!(store.budget, 10);
// One that inflates is charged its compressed bytes as well as what they inflate to.
let wmf = vec![7u8; 100];
let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6);
let mut header = vec![0u8; 34];
header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes());
let blip = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat());
let mut store = Store::new(None, &[]);
store.budget = 1000;
assert_eq!(store.decode_inline(&blip).map(|p| p.data.len()), Some(100));
assert_eq!(store.budget, 1000 - 100 - z.len());
}
#[test]
fn decodes_png_and_deflated_metafiles() {
let png = [&[0u8; 17][..], b"\x89PNG..."].concat();
let p = decode_all(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap()).unwrap();
assert_eq!((p.ext, &p.data[..4]), ("png", &b"\x89PNG"[..]));
// Over the remaining budget: refused before it is copied.
assert!(decode(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap(), 6).is_none());
let wmf = b"\x01\x00\x09\x00\x00\x03 a tiny metafile".to_vec();
let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6);
let mut header = vec![0u8; 34];
header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes());
header[28..32].copy_from_slice(&(z.len() as u32).to_le_bytes());
let body = [&[0u8; 16][..], &header, &z].concat();
let p = decode_all(&Rec::at(&atom(0xF01B, 0x216, &body), 0).unwrap()).unwrap();
assert_eq!((p.ext, p.data), ("wmf", wmf));
// Damaged deflate data is no picture rather than a panic.
let bad = [&[0u8; 16][..], &header, &[1, 2, 3]].concat();
assert!(decode_all(&Rec::at(&atom(0xF01A, 0x3D4, &bad), 0).unwrap()).is_none());
}
#[test]
fn a_dib_becomes_a_bmp_the_image_crate_reads() {
// 1×1, 24-bit.
let mut dib = vec![0u8; 40];
dib[0] = 40;
dib[4] = 1;
dib[8] = 1;
dib[12] = 1;
dib[14] = 24;
dib.extend_from_slice(&[0, 0, 255, 0]);
let body = [&[0u8; 17][..], &dib].concat();
let p = decode_all(&Rec::at(&atom(0xF01F, 0x7A8, &body), 0).unwrap()).unwrap();
assert_eq!(&p.data[..2], b"BM");
assert_eq!(u32::from_le_bytes(p.data[10..14].try_into().unwrap()), 54);
let img = image::load_from_memory_with_format(&p.data, image::ImageFormat::Bmp).unwrap().to_rgba8();
assert_eq!(img.dimensions(), (1, 1));
assert_eq!(img.get_pixel(0, 0).0, [255, 0, 0, 255]);
}
/// The pixels start after the colour table: biClrUsed entries for more than 8 bits (none when
/// it is 0), at most 2^bits for fewer, and a table running past the DIB is no picture.
#[test]
fn a_dib_colour_table_is_sized_by_its_bit_depth() {
let dib = |bits: u16, used: u32, extra: usize| {
let mut d = vec![0u8; 40];
d[0] = 40;
d[14..16].copy_from_slice(&bits.to_le_bytes());
d[32..36].copy_from_slice(&used.to_le_bytes());
d.resize(40 + extra, 0);
d
};
let offset = |b: &[u8]| dib_to_bmp(b).map(|bmp| u32::from_le_bytes(bmp[10..14].try_into().unwrap()));
assert_eq!(offset(&dib(24, 0, 4)), Some(54));
assert_eq!(offset(&dib(24, 300, 1204)), Some(54 + 1200), "more than 256 entries for 24 bits");
assert_eq!(offset(&dib(8, 300, 1028)), Some(54 + 1024), "8 bits: at most 256");
assert_eq!(offset(&dib(4, 0, 68)), Some(54 + 64));
assert_eq!(offset(&dib(24, 300, 100)), None, "the table runs past the DIB");
assert_eq!(offset(&dib(32, u32::MAX, 0)), None);
}
/// JPEG (RGB and CMYK), TIFF and a PNG with a second UID: the instance says how many UIDs come
/// before the tag byte, and the bytes after it are the file.
#[test]
fn decodes_each_bitmap_kind() {
let file = b"the picture file";
for (kind, instance, uids, ext) in [
(0xF01D, 0x46A, 16, "jpg"),
(0xF01D, 0x46B, 32, "jpg"),
(0xF02A, 0x6E2, 16, "jpg"),
(0xF029, 0x6E4, 16, "tif"),
(0xF029, 0x6E5, 32, "tif"),
(0xF01E, 0x6E1, 32, "png"),
] {
let body = [&vec![0xAAu8; uids][..], &[0xFF], file].concat();
let p = decode_all(&Rec::at(&atom(kind, instance, &body), 0).unwrap()).unwrap();
assert_eq!((p.ext, p.data.as_slice()), (ext, &file[..]), "{kind:#x}/{instance:#x}");
}
}
/// A metafile stored without compression (compression byte 0xFE) is copied as it is, up to its
/// stated size; with two UIDs the header starts 32 bytes in.
#[test]
fn decodes_an_uncompressed_metafile() {
let emf = b"\x01\x00\x00\x00 an enhanced metafile".to_vec();
let mut header = vec![0u8; 34];
header[..4].copy_from_slice(&(emf.len() as u32).to_le_bytes());
header[28..32].copy_from_slice(&(emf.len() as u32).to_le_bytes());
header[32] = 0xFE;
for (instance, uids) in [(0x3D4, 16), (0x3D5, 32)] {
let body = [&vec![0u8; uids][..], &header, &emf, b"trailing"].concat();
let p = decode_all(&Rec::at(&atom(0xF01A, instance, &body), 0).unwrap()).unwrap();
assert_eq!((p.ext, &p.data), ("emf", &emf));
}
}
/// A metafile whose inflated size (with its compressed bytes) would pass the remaining budget is refused, compressed or not.
#[test]
fn a_metafile_over_the_budget_is_refused() {
let wmf = vec![9u8; 4000];
let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6);
let mut header = vec![0u8; 34];
header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes());
let deflated = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat());
// The budget covers the compressed bytes read as well as the bytes they inflate to.
assert!(decode(&Rec::at(&deflated, 0).unwrap(), 3999 + z.len()).is_none());
assert_eq!(decode(&Rec::at(&deflated, 0).unwrap(), 4000 + z.len()).map(|p| p.data.len()), Some(4000));
header[32] = 0xFE;
let raw = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &wmf].concat());
assert!(decode(&Rec::at(&raw, 0).unwrap(), 3999).is_none());
assert!(decode(&Rec::at(&raw, 0).unwrap(), 4000).is_some());
}
/// An FBSE may hold its blip itself, after its name, instead of pointing into the Pictures
/// stream.
#[test]
fn a_blip_inside_its_fbse_is_read() {
let png = [&[0u8; 17][..], b"\x89PNG inside"].concat();
let blip = atom(0xF01E, 0x6E0, &png);
let name = "p".encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<u8>>();
let mut fbse = [0u8; 36];
fbse[20..24].copy_from_slice(&(blip.len() as u32).to_le_bytes());
fbse[33] = name.len() as u8;
let entry = atom(rt::FBSE, 6, &[&fbse[..], &name, &blip].concat());
let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 1, &[entry])]);
// The Pictures stream is empty: the blip can only come from the FBSE.
let mut store = Store::new(Rec::at(&dgg, 0), &[]);
let p = store.take(0).unwrap();
assert_eq!((p.ext, &p.data[..]), ("png", &b"\x89PNG inside"[..]));
}
}
File diff suppressed because it is too large Load Diff
+390
View File
@@ -0,0 +1,390 @@
//! The document structure of the `PowerPoint Document` stream ([MS-PPT] §2.1–2.4): the current
//! user's pointer to the last edit, the chain of edits with their persist directories (which map
//! object ids to stream offsets, newer edits winning), the document container and the lists of
//! masters, slides and notes.
use std::collections::{HashMap, HashSet, VecDeque};
use crate::PptError;
use crate::record::{Rec, Records};
pub mod rt {
//! Record types used here ([MS-PPT] §2.13.24, [MS-ODRAW] §2.1.4).
pub const DOCUMENT: u16 = 0x03E8;
pub const DOCUMENT_ATOM: u16 = 0x03E9;
pub const SLIDE: u16 = 0x03EE;
pub const SLIDE_ATOM: u16 = 0x03EF;
pub const NOTES: u16 = 0x03F0;
pub const NOTES_ATOM: u16 = 0x03F1;
pub const ENVIRONMENT: u16 = 0x03F2;
pub const SLIDE_PERSIST_ATOM: u16 = 0x03F3;
pub const MAIN_MASTER: u16 = 0x03F8;
pub const SLIDE_SHOW_SLIDE_INFO: u16 = 0x03F9;
pub const DRAWING_GROUP: u16 = 0x040B;
pub const DRAWING: u16 = 0x040C;
pub const COLOR_SCHEME: u16 = 0x07F0;
pub const LIST: u16 = 0x07D0;
pub const PROG_TAGS: u16 = 0x1388;
pub const PROG_BINARY_TAG: u16 = 0x138A;
pub const BINARY_TAG_DATA: u16 = 0x138B;
pub const STYLE_TEXT_PROP9: u16 = 0x0FAC;
pub const OUTLINE_TEXT_PROPS9: u16 = 0x0FAE;
pub const OUTLINE_TEXT_PROPS_HEADER: u16 = 0x0FAF;
pub const FONT_COLLECTION: u16 = 0x07D5;
pub const OUTLINE_TEXT_REF: u16 = 0x0F9E;
pub const TEXT_HEADER: u16 = 0x0F9F;
pub const TEXT_CHARS: u16 = 0x0FA0;
pub const STYLE_TEXT_PROP: u16 = 0x0FA1;
pub const TEXT_MASTER_STYLE: u16 = 0x0FA3;
pub const TEXT_CF_EXCEPTION: u16 = 0x0FA4;
pub const TEXT_PF_EXCEPTION: u16 = 0x0FA5;
pub const TEXT_RULER: u16 = 0x0FA6;
pub const TEXT_BYTES: u16 = 0x0FA8;
pub const FONT_ENTITY: u16 = 0x0FB7;
pub const CSTRING: u16 = 0x0FBA;
pub const SLIDE_NUMBER_MC: u16 = 0x0FD8;
pub const HEADERS_FOOTERS: u16 = 0x0FD9;
pub const HEADERS_FOOTERS_ATOM: u16 = 0x0FDA;
pub const SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0;
pub const USER_EDIT: u16 = 0x0FF5;
pub const CURRENT_USER: u16 = 0x0FF6;
pub const DATETIME_MC: u16 = 0x0FF7;
pub const GENERIC_DATE_MC: u16 = 0x0FF8;
pub const PLACEHOLDER_ATOM: u16 = 0x0BC3;
pub const PERSIST_DIRECTORY: u16 = 0x1772;
pub const CRYPT_SESSION: u16 = 0x2F14;
pub const DGG_CONTAINER: u16 = 0xF000;
pub const BSTORE: u16 = 0xF001;
pub const DG_CONTAINER: u16 = 0xF002;
pub const SPGR_CONTAINER: u16 = 0xF003;
pub const SP_CONTAINER: u16 = 0xF004;
pub const FBSE: u16 = 0xF007;
pub const FSPGR: u16 = 0xF009;
pub const FSP: u16 = 0xF00A;
pub const FOPT: u16 = 0xF00B;
pub const CLIENT_TEXTBOX: u16 = 0xF00D;
pub const CHILD_ANCHOR: u16 = 0xF00F;
pub const CLIENT_ANCHOR: u16 = 0xF010;
pub const CLIENT_DATA: u16 = 0xF011;
pub const SECONDARY_FOPT: u16 = 0xF121;
pub const TERTIARY_FOPT: u16 = 0xF122;
}
/// `headerToken` of a `CurrentUserAtom` for an encrypted document.
const ENCRYPTED_TOKEN: u32 = 0xF3D1_C4DF;
/// `headerToken` of an unencrypted PowerPoint 97+ document.
const PLAIN_TOKEN: u32 = 0xE391_C05F;
/// Edits followed at most along the `offsetLastEdit` chain.
const MAX_EDITS: usize = 4096;
/// A master, slide or notes page as listed in a `SlideListWithTextContainer`.
#[derive(Clone, Debug)]
pub struct Listed<'a> {
/// The container (`SlideContainer`, `MainMasterContainer`, `NotesContainer`).
pub rec: Rec<'a>,
/// The id other records use for it (`SlideAtom.masterIdRef`, `NotesAtom.slideIdRef`).
pub slide_id: u32,
/// The outline text stored in the list after its `SlidePersistAtom` (placeholders point at it
/// with an `OutlineTextRefAtom`).
pub outline: Vec<Records<'a>>,
}
/// The parsed structure of a `.ppt`.
pub struct Doc<'a> {
pub document: Rec<'a>,
pub masters: Vec<Listed<'a>>,
pub slides: Vec<Listed<'a>>,
pub notes: Vec<Listed<'a>>,
/// Slides the slide list names but whose objects couldn't be found: what a damaged file lost.
pub lost: Vec<String>,
}
/// Read the structure from the `Current User` and `PowerPoint Document` streams.
pub fn read<'a>(current_user: &[u8], stream: &'a [u8]) -> Result<Doc<'a>, PptError> {
let damaged = |s: &str| PptError::Damaged(s.to_string());
// The current user names the newest edit; without it (some writers omit the stream), scan
// for the last UserEditAtom in the stream.
let mut edit_at = None;
// [MS-PPT] allows only the two tokens. Any other value (or none, in a truncated record) is a
// damaged PowerPoint 97 file or an older format; only the scan below can tell which.
let mut unknown_token = false;
if let Some(cu) = Rec::at(current_user, 0).filter(|r| r.kind == rt::CURRENT_USER) {
match cu.u32(4) {
Some(ENCRYPTED_TOKEN) => return Err(PptError::Encrypted),
Some(PLAIN_TOKEN) => edit_at = cu.u32(8).map(|v| v as usize),
_ => unknown_token = true,
}
}
let edit_at = match edit_at.filter(|&at| Rec::at(stream, at).is_some_and(|r| r.kind == rt::USER_EDIT)) {
Some(at) => at,
None => match Records::new(stream).filter(|r| r.kind == rt::USER_EDIT).last() {
Some(r) => r.offset,
None if unknown_token => return Err(PptError::TooOld),
None => return Err(damaged("no edit record")),
},
};
// Walk the edits newest first; the first entry seen for a persist id wins.
let mut persist: HashMap<u32, usize> = HashMap::new();
let mut doc_ref = None;
let mut seen = HashSet::new();
// Many edits may name one persist directory; it is read once (its first reading wins anyway).
let mut dirs_seen = HashSet::new();
// All directories together are read within one stream's worth of words. Real directories
// don't overlap, so they fit. Hostile ones nested inside each other would otherwise each be
// read to the end of the stream, once per edit (MAX_EDITS × the stream).
let mut words = stream.len() / 4;
let mut at = edit_at;
// The chain ends at an edit whose previous offset is 0. Ending anywhere else (a loop, an
// offset that isn't an edit, too many edits) means older edits were cut off.
let mut broken = true;
for _ in 0..MAX_EDITS {
if !seen.insert(at) {
break;
}
let Some(edit) = Rec::at(stream, at).filter(|r| r.kind == rt::USER_EDIT) else { break };
if doc_ref.is_none() {
doc_ref = edit.u32(16);
// An encryptSessionPersistIdRef follows only in encrypted documents.
if edit.data.len() >= 32 {
return Err(PptError::Encrypted);
}
}
if let Some(dir) =
edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY)
{
read_persist_directory(dir.data, &mut persist, &mut words);
}
match edit.u32(8) {
Some(0) => {
broken = false;
break;
}
None => break,
Some(prev) => at = prev as usize,
}
}
if broken {
// Recover what the cut-off edits held: every edit in the stream, newest (last written)
// first, fills only the persist ids the chain left unset. Past MAX_EDITS, the newest are
// kept: they are the ones that win.
log::warn!("ppt: the edit history is broken; reading every edit in the stream");
let mut edits: VecDeque<Rec> = VecDeque::with_capacity(MAX_EDITS.min(64));
for edit in Records::new(stream).filter(|r| r.kind == rt::USER_EDIT) {
if edits.len() == MAX_EDITS {
edits.pop_front();
}
edits.push_back(edit);
}
for edit in edits.into_iter().rev() {
if let Some(dir) =
edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY)
{
read_persist_directory(dir.data, &mut persist, &mut words);
}
}
}
let lookup = |id: u32| persist.get(&id).and_then(|&o| Rec::at(stream, o));
let document = doc_ref.and_then(lookup).filter(|r| r.kind == rt::DOCUMENT).ok_or_else(|| damaged("no document container"))?;
if lookup_kind(&persist, stream, rt::CRYPT_SESSION) {
return Err(PptError::Encrypted);
}
let mut doc = Doc { document, masters: vec![], slides: vec![], notes: vec![], lost: vec![] };
// Each object is listed once. PowerPoint never lists one twice, and a hostile file that lists a
// big drawing many times would otherwise have it converted again for every listing (shapes ×
// listings, from linear input).
let mut listed = HashSet::new();
for list in document.children_of(rt::SLIDE_LIST_WITH_TEXT) {
let out = match list.instance {
0 => &mut doc.slides,
1 => &mut doc.masters,
2 => &mut doc.notes,
_ => continue,
};
let mut current: Option<Listed> = None;
for r in list.children() {
if r.kind == rt::SLIDE_PERSIST_ATOM {
if let Some(l) = current.take() {
out.push(l);
}
let (Some(pid), Some(slide_id)) = (r.u32(0), r.u32(12)) else { continue };
match lookup(pid) {
// The slide list names slides; anything else there is a slide the file lost.
Some(rec) if list.instance == 0 && rec.kind != rt::SLIDE => {
log::warn!("ppt: slide persist id {pid} is not a slide");
doc.lost.push(format!("slide {slide_id}"));
}
Some(rec) if !listed.insert(rec.offset) => log::warn!("ppt: persist id {pid} is listed again; skipped"),
Some(rec) => current = Some(Listed { rec, slide_id, outline: vec![] }),
None => {
log::warn!("ppt: slide persist id {pid} has no object");
if list.instance == 0 {
doc.lost.push(format!("slide {slide_id}"));
}
}
}
} else if r.kind == rt::TEXT_HEADER
&& let Some(l) = current.as_mut()
{
// An outline text block starts at its header and runs to the next header or persist atom.
let rest = list.data.get(r.offset..).unwrap_or(&[]);
l.outline.push(Records::new(rest));
}
}
if let Some(l) = current.take() {
out.push(l);
}
}
Ok(doc)
}
/// Read one persist directory into `persist`, taking each word read from `words`.
fn read_persist_directory(b: &[u8], persist: &mut HashMap<u32, usize>, words: &mut usize) {
let mut c = crate::record::Cursor::new(b);
let mut next = |c: &mut crate::record::Cursor| {
*words = words.checked_sub(1)?;
c.u32()
};
while let Some(head) = next(&mut c) {
let first = head & 0x000F_FFFF;
let count = head >> 20;
for k in 0..count {
let Some(off) = next(&mut c) else { return };
persist.entry(first.saturating_add(k)).or_insert(off as usize);
}
}
}
fn lookup_kind(persist: &HashMap<u32, usize>, stream: &[u8], kind: u16) -> bool {
persist.values().any(|&o| Rec::at(stream, o).is_some_and(|r| r.kind == kind))
}
/// The `DocumentAtom`: slide and notes sizes in master units (576 per inch), first slide number.
pub struct DocumentAtom {
pub slide_w: i32,
pub slide_h: i32,
pub notes_w: i32,
pub notes_h: i32,
pub first_slide_number: u16,
}
impl Doc<'_> {
pub fn document_atom(&self) -> Option<DocumentAtom> {
let a = self.document.child(rt::DOCUMENT_ATOM)?;
Some(DocumentAtom {
slide_w: a.i32(0)?,
slide_h: a.i32(4)?,
notes_w: a.i32(8)?,
notes_h: a.i32(12)?,
first_slide_number: a.u16(32).unwrap_or(1),
})
}
}
/// The `SlideAtom` of a slide or master.
#[derive(Clone, Copy, Debug, Default)]
pub struct SlideAtom {
/// `SlideLayoutType`.
pub geom: u32,
pub master_id: u32,
pub follow_master_objects: bool,
pub follow_master_scheme: bool,
pub follow_master_background: bool,
}
pub fn slide_atom(container: &Rec) -> SlideAtom {
let Some(a) = container.child(rt::SLIDE_ATOM) else {
return SlideAtom { follow_master_objects: true, follow_master_scheme: true, follow_master_background: true, ..Default::default() };
};
let flags = a.u16(20).unwrap_or(0x7);
SlideAtom {
geom: a.u32(0).unwrap_or(0),
master_id: a.u32(12).unwrap_or(0),
follow_master_objects: flags & 0x1 != 0,
follow_master_scheme: flags & 0x2 != 0,
follow_master_background: flags & 0x4 != 0,
}
}
/// Font names by index (`FontCollectionContainer` in the environment).
pub fn fonts(doc: &Doc) -> Vec<String> {
let Some(coll) = doc.document.child(rt::ENVIRONMENT).and_then(|e| e.child(rt::FONT_COLLECTION)) else { return vec![] };
coll.children_of(rt::FONT_ENTITY)
.map(|f| {
let units: Vec<u16> = (0..32).filter_map(|i| f.u16(i * 2)).take_while(|&u| u != 0).collect();
String::from_utf16_lossy(&units)
})
.collect()
}
/// What a `HeadersFootersContainer` ([MS-PPT] §2.4.15.1 and §2.5.16) says the footer row
/// shows: the date (today's in a format, or fixed text), the slide number and the footer text.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct HeadersFooters {
/// `formatId`: 0–12, the date format.
pub format: u16,
pub date: bool,
/// The date is fixed text (`fHasUserDate`) rather than today's.
pub user_date: bool,
pub slide_number: bool,
pub footer: bool,
pub date_text: String,
pub footer_text: String,
}
/// The UTF-16 units of a `CString` body, up to its first NUL: the record has no terminator, but a
/// writer that adds one would otherwise put a NUL into the text, or make a tag name fail to match.
fn cstring_units(b: &[u8]) -> impl Iterator<Item = u16> + '_ {
b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|&u| u != 0)
}
/// The slides' headers and footers in `container`, from its `HeadersFootersContainer` of
/// `instance`: 3 in the document (`SlideHeadersFootersContainer`, for every slide), 0 in a slide or
/// main master (`PerSlideHeadersFootersContainer`, its own).
pub fn headers_footers(container: &Rec, instance: u16) -> Option<HeadersFooters> {
let hf = container.children().find(|r| r.kind == rt::HEADERS_FOOTERS && r.instance == instance)?;
let atom = hf.child(rt::HEADERS_FOOTERS_ATOM)?;
let flags = atom.u16(2)?;
let text = |instance: u16| {
hf.children()
.find(|r| r.kind == rt::CSTRING && r.instance == instance)
.map(|r| String::from_utf16_lossy(&cstring_units(r.data).collect::<Vec<u16>>()))
.unwrap_or_default()
};
Some(HeadersFooters {
format: atom.u16(0).unwrap_or(0),
date: flags & 0x01 != 0,
user_date: flags & 0x04 != 0,
slide_number: flags & 0x08 != 0,
footer: flags & 0x20 != 0,
date_text: text(0),
footer_text: text(2),
})
}
/// The PowerPoint 2000 paragraph formatting of the slides' outline text ([MS-PPT] §2.4.22.10,
/// the document's `___PPT9` tag): by slide id and text type, one `StyleTextProp9Atom` for each of
/// the slide's outline blocks of that type, in order.
pub fn outline_numbering(document: &Rec) -> HashMap<(u32, u32), Vec<Vec<crate::text::Pf9>>> {
let mut out: HashMap<(u32, u32), Vec<Vec<crate::text::Pf9>>> = HashMap::new();
let tags = document.child(rt::LIST).and_then(|l| l.child(rt::PROG_TAGS));
let Some(tags) = tags else { return out };
let ppt9 = tags
.children_of(rt::PROG_BINARY_TAG)
.find(|tag| tag.child(rt::CSTRING).is_some_and(|name| cstring_units(name.data).eq("___PPT9".encode_utf16())));
let Some(data) = ppt9.and_then(|t| t.child(rt::BINARY_TAG_DATA)) else { return out };
// The tag's data is an atom whose body holds records.
for props in Records::new(data.data).filter(|r| r.kind == rt::OUTLINE_TEXT_PROPS9) {
let mut header = None;
for r in props.children() {
if r.kind == rt::OUTLINE_TEXT_PROPS_HEADER {
header = r.u32(0).zip(r.u32(4));
} else if r.kind == rt::STYLE_TEXT_PROP9
&& let Some(key) = header.take()
{
out.entry(key).or_default().push(crate::text::read_style9(r.data));
}
}
}
out
}
+522
View File
@@ -0,0 +1,522 @@
//! OfficeArt drawings ([MS-ODRAW]) as `.ppt` stores them: a tree of shape group containers and
//! shape containers, each shape with its `FSP` (type, id, flags), property tables (`FOPT`),
//! anchor and client records (placeholder, text).
use std::collections::HashMap;
use crate::doc::rt;
use crate::record::{MAX_DEPTH, Rec};
/// Property ids ([MS-ODRAW] §2.3).
pub mod prop {
pub const ROTATION: u16 = 0x0004;
pub const TEXT_LEFT: u16 = 0x0081;
pub const TEXT_TOP: u16 = 0x0082;
pub const TEXT_RIGHT: u16 = 0x0083;
pub const TEXT_BOTTOM: u16 = 0x0084;
pub const WRAP_TEXT: u16 = 0x0085;
pub const ANCHOR_TEXT: u16 = 0x0087;
pub const CROP_TOP: u16 = 0x0100;
pub const CROP_BOTTOM: u16 = 0x0101;
pub const CROP_LEFT: u16 = 0x0102;
pub const CROP_RIGHT: u16 = 0x0103;
pub const PIB: u16 = 0x0104;
pub const GEO_LEFT: u16 = 0x0140;
pub const GEO_TOP: u16 = 0x0141;
pub const GEO_RIGHT: u16 = 0x0142;
pub const GEO_BOTTOM: u16 = 0x0143;
pub const SHAPE_PATH: u16 = 0x0144;
pub const VERTICES: u16 = 0x0145;
pub const SEGMENT_INFO: u16 = 0x0146;
pub const ADJUST_VALUE: u16 = 0x0147;
pub const FILL_TYPE: u16 = 0x0180;
pub const FILL_COLOR: u16 = 0x0181;
pub const FILL_OPACITY: u16 = 0x0182;
pub const FILL_BACK_COLOR: u16 = 0x0183;
pub const FILL_BACK_OPACITY: u16 = 0x0184;
pub const FILL_BLIP: u16 = 0x0186;
pub const FILL_ANGLE: u16 = 0x018B;
pub const FILL_FOCUS: u16 = 0x018C;
pub const FILL_BOOLS: u16 = 0x01BF;
pub const LINE_COLOR: u16 = 0x01C0;
pub const LINE_OPACITY: u16 = 0x01C1;
pub const LINE_WIDTH: u16 = 0x01CB;
pub const LINE_STYLE: u16 = 0x01CD;
pub const LINE_DASHING: u16 = 0x01CE;
pub const LINE_START_ARROW: u16 = 0x01D0;
pub const LINE_END_ARROW: u16 = 0x01D1;
pub const LINE_START_ARROW_WIDTH: u16 = 0x01D2;
pub const LINE_START_ARROW_LENGTH: u16 = 0x01D3;
pub const LINE_END_ARROW_WIDTH: u16 = 0x01D4;
pub const LINE_END_ARROW_LENGTH: u16 = 0x01D5;
pub const LINE_JOIN: u16 = 0x01D6;
pub const LINE_CAP: u16 = 0x01D7;
pub const LINE_BOOLS: u16 = 0x01FF;
pub const SHADOW_COLOR: u16 = 0x0201;
pub const SHADOW_OPACITY: u16 = 0x0204;
pub const SHADOW_OFFSET_X: u16 = 0x0205;
pub const SHADOW_OFFSET_Y: u16 = 0x0206;
pub const SHADOW_BOOLS: u16 = 0x023F;
pub const HSP_MASTER: u16 = 0x0301;
pub const NAME: u16 = 0x0380;
pub const DESCRIPTION: u16 = 0x0381;
pub const GROUP_BOOLS: u16 = 0x03BF;
}
/// UTF-16 units kept of a string property.
pub const MAX_STRING: usize = 4096;
/// Distinct properties one set keeps. Ids are 14 bits, so a file's tables could name about 16K of
/// them, and every shape copies the drawing defaults' and its master shape's sets into its own:
/// unbounded, that is shapes × 16K. [MS-ODRAW] defines a few hundred properties and a real shape
/// or the drawing defaults set tens of them. Entries past the limit are still read (their complex
/// data keeps its place) but not kept.
pub const MAX_PROPS: usize = 1024;
/// One property value: the 32-bit operand and, for complex properties, the extra bytes.
#[derive(Clone, Copy, Debug)]
pub struct PropVal<'a> {
pub op: u32,
pub complex: Option<&'a [u8]>,
}
/// A shape's merged property tables (primary first; secondary and tertiary fill gaps).
#[derive(Clone, Debug, Default)]
pub struct Props<'a> {
map: HashMap<u16, PropVal<'a>>,
}
impl<'a> Props<'a> {
/// Read one `FOPT` body: `count` 6-byte entries then the complex data in entry order. Entries
/// already present are kept (the caller adds the most specific table first).
pub fn add_table(&mut self, r: &Rec<'a>) {
let count = usize::from(r.instance);
let mut complex_at = count.saturating_mul(6);
for i in 0..count {
let (Some(id), Some(op)) = (r.u16(i * 6), r.u32(i * 6 + 2)) else { break };
let is_complex = id & 0x8000 != 0;
let pid = id & 0x3FFF;
let complex = if is_complex {
let len = op as usize;
let data = r.data.get(complex_at..complex_at.saturating_add(len).min(r.data.len()));
complex_at = complex_at.saturating_add(len);
data
} else {
None
};
self.fill_gap(pid, PropVal { op, complex });
}
}
/// Fill gaps from another set (a master shape's or the drawing defaults).
pub fn inherit(&mut self, other: &Props<'a>) {
for (k, v) in &other.map {
self.fill_gap(*k, *v);
}
}
/// Add `v` for `id` where this set doesn't say it already. A boolean property word ([MS-ODRAW]:
/// the last id of each 64-id group) holds sixteen flags, each with its own `fUse` bit 16
/// places up, so it is merged flag by flag: a shape that sets only `fNoFillHitTest` still
/// inherits `fFilled` from its master or the defaults.
fn fill_gap(&mut self, id: u16, v: PropVal<'a>) {
let full = self.map.len() >= MAX_PROPS;
match self.map.get_mut(&id) {
None if full => {}
None => {
self.map.insert(id, v);
}
Some(have) if id & 0x3F == 0x3F => {
let unset = !(have.op >> 16) & 0xFFFF;
let take = (v.op >> 16) & unset;
have.op |= take << 16;
have.op = (have.op & !take) | (v.op & take);
}
Some(_) => {}
}
}
/// Set a simple (non-complex) property.
pub fn set(&mut self, id: u16, op: u32) {
self.map.insert(id, PropVal { op, complex: None });
}
pub fn get(&self, id: u16) -> Option<u32> {
self.map.get(&id).map(|v| v.op)
}
pub fn complex(&self, id: u16) -> Option<&'a [u8]> {
self.map.get(&id).and_then(|v| v.complex)
}
/// A 16.16 fixed-point value.
pub fn fixed(&self, id: u16) -> Option<f64> {
self.get(id).map(|v| f64::from(v as i32) / 65536.0)
}
/// A boolean from a bool-property word: bit `bit` holds the value, bit `bit + 16` says it is set.
pub fn flag(&self, id: u16, bit: u32) -> Option<bool> {
let v = self.get(id)?;
(v & (1 << (bit + 16)) != 0).then_some(v & (1 << bit) != 0)
}
/// A UTF-16 string property (names, alt text), at most [`MAX_STRING`] units: a master shape's
/// name is copied into every shape that inherits it.
pub fn string(&self, id: u16) -> Option<String> {
let b = self.complex(id)?;
let units: Vec<u16> = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take(MAX_STRING).take_while(|&u| u != 0).collect();
Some(String::from_utf16_lossy(&units)).filter(|s| !s.is_empty())
}
/// An `IMsoArray` property: element size and the elements' bytes.
pub fn array(&self, id: u16) -> Option<(usize, &'a [u8])> {
let b = self.complex(id)?;
let n = usize::from(crate::record::u16_at(b, 0)?);
let size = crate::record::u16_at(b, 4)?;
// 0xFFF0 marks 4-byte elements stored as two 2-byte halves.
let size = if size == 0xFFF0 { 4 } else { usize::from(size) };
if size == 0 {
return None;
}
let body = b.get(6..)?;
let len = n.saturating_mul(size).min(body.len() / size * size);
Some((size, body.get(..len)?))
}
}
/// An anchor rectangle in its own coordinate units: master units for a client anchor, the parent
/// group's units for a child anchor.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Anchor {
pub left: f64,
pub top: f64,
pub right: f64,
pub bottom: f64,
}
/// The placeholder a shape stands for (`OEPlaceholderAtom`).
#[derive(Clone, Copy, Debug)]
pub struct Placeholder {
pub position: u32,
/// `PlaceholderEnum`.
pub kind: u8,
}
/// One shape of a drawing, before conversion.
#[derive(Clone, Debug)]
pub struct RawShape<'a> {
/// `MSOSPT` shape type.
pub shape_type: u16,
pub spid: u32,
pub flip_h: bool,
pub flip_v: bool,
pub patriarch: bool,
pub deleted: bool,
pub props: Props<'a>,
pub anchor: Option<Anchor>,
/// For a group: the child coordinate rectangle (`FSPGR`).
pub group_rect: Option<Anchor>,
pub children: Vec<RawShape<'a>>,
pub is_group: bool,
pub placeholder: Option<Placeholder>,
/// The records of the shape's text box (`OfficeArtClientTextbox`).
pub text: Option<Rec<'a>>,
}
/// The top-level shapes and the background shape of a `DrawingContainer`.
pub struct Drawing<'a> {
pub shapes: Vec<RawShape<'a>>,
pub background: Option<RawShape<'a>>,
}
/// Read the drawing of a slide, master or notes container.
pub fn drawing<'a>(container: &Rec<'a>) -> Drawing<'a> {
let mut out = Drawing { shapes: vec![], background: None };
let Some(dg) = container.child(rt::DRAWING).and_then(|d| d.child(rt::DG_CONTAINER)) else { return out };
// The background is the container's own shape (`OfficeArtDgContainer.shape`, [MS-ODRAW]
// 2.2.13), not one found by its fBackground flag.
if let Some(bg) = dg.child(rt::SP_CONTAINER) {
out.background = Some(shape(&bg));
}
if let Some(top) = dg.child(rt::SPGR_CONTAINER) {
// The first shape of the top group is the patriarch, standing for the drawing itself.
out.shapes = group_children(&top, 0).into_iter().filter(|s| !s.patriarch).collect();
}
out
}
fn group_children<'a>(gr: &Rec<'a>, depth: usize) -> Vec<RawShape<'a>> {
if depth > MAX_DEPTH {
return vec![];
}
let mut out = vec![];
for r in gr.children() {
match r.kind {
rt::SP_CONTAINER => out.push(shape(&r)),
rt::SPGR_CONTAINER => {
let mut kids = r.children();
// A group container's first shape describes the group itself.
let Some(head) = kids.next().filter(|h| h.kind == rt::SP_CONTAINER) else { continue };
let mut g = shape(&head);
g.is_group = true;
g.children = group_children(&r, depth + 1).into_iter().skip(1).collect();
out.push(g);
}
_ => {}
}
}
out
}
fn rect_i32(r: &Rec) -> Option<Anchor> {
Some(Anchor { left: f64::from(r.i32(0)?), top: f64::from(r.i32(4)?), right: f64::from(r.i32(8)?), bottom: f64::from(r.i32(12)?) })
}
fn shape<'a>(sp: &Rec<'a>) -> RawShape<'a> {
let mut s = RawShape {
shape_type: 0,
spid: 0,
flip_h: false,
flip_v: false,
patriarch: false,
deleted: false,
props: Props::default(),
anchor: None,
group_rect: None,
children: vec![],
is_group: false,
placeholder: None,
text: None,
};
// Tables in specificity order: primary (the last one first), then secondary and tertiary.
let mut primary: Vec<Rec> = vec![];
let mut tables: Vec<Rec> = vec![];
for r in sp.children() {
match r.kind {
rt::FSP => {
s.shape_type = r.instance;
s.spid = r.u32(0).unwrap_or(0);
let f = r.u32(4).unwrap_or(0);
s.patriarch = f & 0x4 != 0;
s.deleted = f & 0x8 != 0;
s.flip_h = f & 0x40 != 0;
s.flip_v = f & 0x80 != 0;
}
rt::FOPT => primary.push(r),
rt::SECONDARY_FOPT | rt::TERTIARY_FOPT => tables.push(r),
rt::FSPGR => s.group_rect = rect_i32(&r),
rt::CHILD_ANCHOR => s.anchor = rect_i32(&r),
rt::CLIENT_ANCHOR => {
s.anchor = if r.data.len() >= 16 {
// RectStruct: top, left, right, bottom.
(|| {
Some(Anchor {
top: f64::from(r.i32(0)?),
left: f64::from(r.i32(4)?),
right: f64::from(r.i32(8)?),
bottom: f64::from(r.i32(12)?),
})
})()
} else {
// SmallRectStruct: top, left, right, bottom.
(|| {
Some(Anchor {
top: f64::from(r.i16(0)?),
left: f64::from(r.i16(2)?),
right: f64::from(r.i16(4)?),
bottom: f64::from(r.i16(6)?),
})
})()
};
}
rt::CLIENT_DATA => {
if let Some(p) = r.child(rt::PLACEHOLDER_ATOM) {
s.placeholder = Some(Placeholder { position: p.u32(0).unwrap_or(0), kind: p.u8(4).unwrap_or(0) });
}
}
rt::CLIENT_TEXTBOX => s.text = Some(r),
_ => {}
}
}
for t in primary.iter().rev().chain(&tables) {
s.props.add_table(t);
}
s
}
/// The drawing-wide default properties (`OfficeArtDggContainer`'s `FOPT`).
pub fn default_props<'a>(dgg: Option<Rec<'a>>) -> Props<'a> {
let mut p = Props::default();
if let Some(dgg) = dgg {
for t in dgg.children().filter(|r| matches!(r.kind, rt::FOPT | rt::SECONDARY_FOPT | rt::TERTIARY_FOPT)) {
p.add_table(&t);
}
}
p
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::record::build::*;
pub fn fopt(entries: &[(u16, u32)], complex: &[u8]) -> Vec<u8> {
let mut b = vec![];
for (id, op) in entries {
b.extend_from_slice(&id.to_le_bytes());
b.extend_from_slice(&op.to_le_bytes());
}
b.extend_from_slice(complex);
atom(rt::FOPT, entries.len() as u16, &b)
}
#[test]
fn reads_properties_and_complex_strings() {
let name: Vec<u8> = "Logo\0".encode_utf16().flat_map(u16::to_le_bytes).collect();
let t = fopt(&[(prop::FILL_COLOR, 0x0011_2233), (0x8000 | prop::NAME, name.len() as u32), (prop::FILL_BOOLS, 0x0010_0000)], &name);
let mut p = Props::default();
p.add_table(&Rec::at(&t, 0).unwrap());
assert_eq!(p.get(prop::FILL_COLOR), Some(0x0011_2233));
assert_eq!(p.string(prop::NAME).as_deref(), Some("Logo"));
assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false));
assert_eq!(p.flag(prop::LINE_BOOLS, 3), None);
}
/// A boolean word inherits the flags it doesn't set (storytold/deckcraft#1137 review): a text box that sets only
/// `fNoFillHitTest` (bit 4 is `fFilled`, bit 0 `fNoFillHitTest`) still gets "not filled"
/// from below, and its own flags win over the inherited ones.
#[test]
fn boolean_properties_merge_flag_by_flag() {
let mut p = Props::default();
p.set(prop::FILL_BOOLS, 0x0001_0001); // fNoFillHitTest = true; fFilled not said
p.set(prop::LINE_BOOLS, 0x0008_0008); // fLine = true
let mut below = Props::default();
below.set(prop::FILL_BOOLS, 0x0011_0000); // fFilled = false, fNoFillHitTest = false
below.set(prop::LINE_BOOLS, 0x0008_0000); // fLine = false
p.inherit(&below);
assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false));
assert_eq!(p.flag(prop::FILL_BOOLS, 0), Some(true));
assert_eq!(p.flag(prop::LINE_BOOLS, 3), Some(true));
// The same merge applies between a shape's own tables.
let t = fopt(&[(prop::FILL_BOOLS, 0x0001_0001)], &[]);
let t2 = fopt(&[(prop::FILL_BOOLS, 0x0010_0010)], &[]);
let mut q = Props::default();
q.add_table(&Rec::at(&t, 0).unwrap());
q.add_table(&Rec::at(&t2, 0).unwrap());
assert_eq!(q.flag(prop::FILL_BOOLS, 4), Some(true));
assert_eq!(q.flag(prop::FILL_BOOLS, 0), Some(true));
// Non-boolean properties still keep the first value.
let mut r = Props::default();
r.set(prop::FILL_COLOR, 1);
let mut s = Props::default();
s.set(prop::FILL_COLOR, 2);
r.inherit(&s);
assert_eq!(r.get(prop::FILL_COLOR), Some(1));
}
/// A string property longer than [`MAX_STRING`] units is cut there.
#[test]
fn a_long_string_property_is_capped() {
let name: Vec<u8> = "x".repeat(10_000).encode_utf16().flat_map(u16::to_le_bytes).collect();
let t = fopt(&[(0x8000 | prop::NAME, name.len() as u32)], &name);
let mut p = Props::default();
p.add_table(&Rec::at(&t, 0).unwrap());
assert_eq!(p.string(prop::NAME).map(|s| s.len()), Some(MAX_STRING));
}
/// A table naming more than [`MAX_PROPS`] properties keeps that many, and still reads the
/// complex data after them and the records after it.
#[test]
fn a_property_set_keeps_at_most_max_props() {
let mut entries: Vec<(u16, u32)> = (0..MAX_PROPS as u16 + 100).map(|i| (0x1000 + i, u32::from(i))).collect();
let name: Vec<u8> = "Kept\0".encode_utf16().flat_map(u16::to_le_bytes).collect();
entries.insert(0, (0x8000 | prop::NAME, name.len() as u32));
let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat());
let anchor = atom(rt::CHILD_ANCHOR, 0, &[1i32, 2, 3, 4].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
let sp = container(rt::SP_CONTAINER, 0, &[fsp, fopt(&entries, &name), anchor]);
let s = shape(&Rec::at(&sp, 0).unwrap());
assert_eq!(s.props.map.len(), MAX_PROPS);
assert_eq!(s.props.string(prop::NAME).as_deref(), Some("Kept"));
assert_eq!(s.props.get(0x1000), Some(0));
assert_eq!(s.props.get(0x1000 + MAX_PROPS as u16), None, "past the limit");
assert_eq!(s.anchor, Some(Anchor { left: 1.0, top: 2.0, right: 3.0, bottom: 4.0 }));
// Inheriting can't pass the limit either.
let mut p = Props::default();
p.set(prop::FILL_COLOR, 1);
p.inherit(&s.props);
assert_eq!(p.map.len(), MAX_PROPS);
}
/// A shape's later primary property table wins over its earlier one, and both over its
/// secondary table.
#[test]
fn the_last_primary_table_wins() {
let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat());
let secondary = {
let mut b = vec![];
for (id, op) in [(prop::FILL_COLOR, 3u32), (prop::LINE_COLOR, 3)] {
b.extend_from_slice(&id.to_le_bytes());
b.extend_from_slice(&op.to_le_bytes());
}
atom(rt::SECONDARY_FOPT, 2, &b)
};
let sp = container(
rt::SP_CONTAINER,
0,
&[fsp, secondary, fopt(&[(prop::FILL_COLOR, 1), (prop::LINE_WIDTH, 1)], &[]), fopt(&[(prop::FILL_COLOR, 2)], &[])],
);
let s = shape(&Rec::at(&sp, 0).unwrap());
assert_eq!((s.props.get(prop::FILL_COLOR), s.props.get(prop::LINE_WIDTH), s.props.get(prop::LINE_COLOR)), (Some(2), Some(1), Some(3)));
}
#[test]
fn a_complex_length_past_the_record_is_clipped() {
let t = fopt(&[(0x8000 | prop::NAME, 0xFFFF_FFFF), (0x8000 | prop::DESCRIPTION, 10)], b"A\0");
let mut p = Props::default();
p.add_table(&Rec::at(&t, 0).unwrap());
assert_eq!(p.string(prop::NAME).as_deref(), Some("A"));
assert_eq!(p.complex(prop::DESCRIPTION), None);
}
#[test]
fn reads_groups_anchors_and_placeholders() {
let fsp = |t: u16, id: u32, flags: u32| atom(rt::FSP, t, &[id.to_le_bytes(), flags.to_le_bytes()].concat());
let small =
|t: i16, l: i16, r: i16, b: i16| atom(rt::CLIENT_ANCHOR, 0, &[t, l, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
let child =
|l: i32, t: i32, r: i32, b: i32| atom(rt::CHILD_ANCHOR, 0, &[l, t, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
let ph = container(rt::CLIENT_DATA, 0, &[atom(rt::PLACEHOLDER_ATOM, 0, &[0, 0, 0, 0, 0x0D, 0, 0, 0])]);
let patriarch = container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &[0; 16]), fsp(0, 1024, 0x5)]);
let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 1025, 0xA00), small(10, 20, 300, 80), ph]);
let group = container(
rt::SPGR_CONTAINER,
0,
&[
container(
rt::SP_CONTAINER,
0,
&[
atom(rt::FSPGR, 1, &[0i32, 0, 100, 100].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>()),
fsp(0, 1026, 0x201),
small(100, 100, 200, 200),
],
),
container(rt::SP_CONTAINER, 0, &[fsp(3, 1027, 0x40), child(0, 0, 50, 50)]),
],
);
let drawing = container(rt::DRAWING, 0, &[container(rt::DG_CONTAINER, 0, &[container(rt::SPGR_CONTAINER, 0, &[patriarch, title, group])])]);
let slide = container(rt::SLIDE, 0, &[drawing]);
let d = super::drawing(&Rec::at(&slide, 0).unwrap());
assert_eq!(d.shapes.len(), 2);
let t = &d.shapes[0];
assert_eq!(t.placeholder.unwrap().kind, 0x0D);
assert_eq!(t.anchor, Some(Anchor { left: 20.0, top: 10.0, right: 300.0, bottom: 80.0 }));
let g = &d.shapes[1];
assert!(g.is_group);
assert_eq!(g.children.len(), 1);
assert!(g.children[0].flip_h);
assert_eq!(g.group_rect.unwrap().right, 100.0);
}
}
+454
View File
@@ -0,0 +1,454 @@
//! Shape geometry: OfficeArt shape types (`MSOSPT`, [MS-ODRAW] §2.4.24) as DrawingML preset
//! names, and freeform paths from the vertices and segment properties (§2.3.6).
use craft_pptx::{CustomPath, Geom};
use crate::draw::{Props, prop};
/// The preset for a shape type, `None` for a freeform (`msosptNotPrimitive`) or a type with no
/// preset counterpart.
pub fn preset_name(shape_type: u16) -> Option<&'static str> {
Some(match shape_type {
1 | 75 | 202 | 201 => "rect",
2 => "roundRect",
3 => "ellipse",
4 => "diamond",
5 => "triangle",
6 => "rtTriangle",
7 => "parallelogram",
8 => "trapezoid",
9 => "hexagon",
10 => "octagon",
11 => "plus",
12 => "star5",
13 | 14 => "rightArrow",
15 => "homePlate",
16 => "cube",
17 => "wedgeRoundRectCallout",
18 => "star16",
19 => "arc",
20 => "line",
21 => "plaque",
22 => "can",
23 => "donut",
32 => "straightConnector1",
33 => "bentConnector2",
34 => "bentConnector3",
35 => "bentConnector4",
36 => "bentConnector5",
37 => "curvedConnector2",
38 => "curvedConnector3",
39 => "curvedConnector4",
40 => "curvedConnector5",
41 | 178 => "callout1",
42 => "callout2",
43 => "callout3",
44 | 179 => "accentCallout1",
45 => "accentCallout2",
46 => "accentCallout3",
47 | 180 => "borderCallout1",
48 => "borderCallout2",
49 => "borderCallout3",
50 | 181 => "accentBorderCallout1",
51 => "accentBorderCallout2",
52 => "accentBorderCallout3",
53 => "ribbon",
54 => "ribbon2",
55 => "chevron",
56 => "pentagon",
57 => "noSmoking",
58 => "star8",
59 => "star16",
60 => "star32",
61 => "wedgeRectCallout",
62 => "wedgeRoundRectCallout",
63 => "wedgeEllipseCallout",
64 => "wave",
65 => "foldedCorner",
66 => "leftArrow",
67 => "downArrow",
68 => "upArrow",
69 => "leftRightArrow",
70 => "upDownArrow",
71 => "irregularSeal1",
72 => "irregularSeal2",
73 => "lightningBolt",
74 => "heart",
76 => "quadArrow",
77 => "leftArrowCallout",
78 => "rightArrowCallout",
79 => "upArrowCallout",
80 => "downArrowCallout",
81 => "leftRightArrowCallout",
82 => "upDownArrowCallout",
83 => "quadArrowCallout",
84 => "bevel",
85 => "leftBracket",
86 => "rightBracket",
87 => "leftBrace",
88 => "rightBrace",
89 => "leftUpArrow",
90 => "bentUpArrow",
91 => "bentArrow",
92 => "star24",
93 => "stripedRightArrow",
94 => "notchedRightArrow",
95 => "blockArc",
96 => "smileyFace",
97 => "verticalScroll",
98 => "horizontalScroll",
99 | 100 => "circularArrow",
101 => "uturnArrow",
102 => "curvedRightArrow",
103 => "curvedLeftArrow",
104 => "curvedUpArrow",
105 => "curvedDownArrow",
106 => "cloudCallout",
107 => "ellipseRibbon",
108 => "ellipseRibbon2",
109 => "flowChartProcess",
110 => "flowChartDecision",
111 => "flowChartInputOutput",
112 => "flowChartPredefinedProcess",
113 => "flowChartInternalStorage",
114 => "flowChartDocument",
115 => "flowChartMultidocument",
116 => "flowChartTerminator",
117 => "flowChartPreparation",
118 => "flowChartManualInput",
119 => "flowChartManualOperation",
120 => "flowChartConnector",
121 => "flowChartPunchedCard",
122 => "flowChartPunchedTape",
123 => "flowChartSummingJunction",
124 => "flowChartOr",
125 => "flowChartCollate",
126 => "flowChartSort",
127 => "flowChartExtract",
128 => "flowChartMerge",
129 => "flowChartOfflineStorage",
130 => "flowChartOnlineStorage",
131 => "flowChartMagneticTape",
132 => "flowChartMagneticDisk",
133 => "flowChartMagneticDrum",
134 => "flowChartDisplay",
135 => "flowChartDelay",
176 => "flowChartAlternateProcess",
177 => "flowChartOffpageConnector",
182 => "leftRightUpArrow",
183 => "sun",
184 => "moon",
185 => "bracketPair",
186 => "bracePair",
187 => "star4",
188 => "doubleWave",
189 => "actionButtonBlank",
190 => "actionButtonHome",
191 => "actionButtonHelp",
192 => "actionButtonInformation",
193 => "actionButtonForwardNext",
194 => "actionButtonBackPrevious",
195 => "actionButtonEnd",
196 => "actionButtonBeginning",
197 => "actionButtonReturn",
198 => "actionButtonDocument",
199 => "actionButtonSound",
200 => "actionButtonMovie",
// WordArt text shapes (24–31, 136–175) draw their text as plain text in a rectangle.
24..=31 | 136..=175 => "rect",
_ => return None,
})
}
/// Whether a shape type is a connector.
pub fn is_connector(shape_type: u16) -> bool {
(32..=40).contains(&shape_type)
}
/// The geometry of a shape: its preset (checked against the presets `craft_drawingml` draws, with a
/// rounded rectangle's corner carried over), else its freeform path, else a rectangle.
pub fn geometry(shape_type: u16, props: &Props) -> Geom {
if let Some(name) = preset_name(shape_type).filter(|n| craft_drawingml::preset::build(n, 100.0, 100.0, &[]).is_some()) {
let mut adj = vec![];
// A rounded rectangle's corner: a 21600 coordinate in OfficeArt, a 100000 fraction of the
// shorter side in DrawingML.
if shape_type == 2
&& let Some(v) = props.get(prop::ADJUST_VALUE)
{
adj.push(f64::from(v as i32).clamp(0.0, 10800.0) / 21600.0 * 100_000.0);
}
return Geom::Preset { name: name.into(), adj };
}
custom_path(props).map(|paths| Geom::Custom { paths }).unwrap_or_default()
}
/// Segments followed at most in one path.
const MAX_SEGMENTS: usize = 1 << 16;
/// Vertices used at most in one path. The path text is copied into every shape that inherits the
/// vertices from a master shape, so it stays a bounded size.
const MAX_POINTS: usize = 8192;
/// A freeform's path in its geometry box.
fn custom_path(props: &Props) -> Option<Vec<CustomPath>> {
let (size, verts) = props.array(prop::VERTICES)?;
let points: Vec<(f64, f64)> = match size {
8 => verts
.as_chunks::<8>()
.0
.iter()
.take(MAX_POINTS)
.map(|c| (f64::from(i32::from_le_bytes([c[0], c[1], c[2], c[3]])), f64::from(i32::from_le_bytes([c[4], c[5], c[6], c[7]]))))
.collect(),
4 => verts
.as_chunks::<4>()
.0
.iter()
.take(MAX_POINTS)
.map(|c| (f64::from(i16::from_le_bytes([c[0], c[1]])), f64::from(i16::from_le_bytes([c[2], c[3]]))))
.collect(),
_ => return None,
};
if points.is_empty() {
return None;
}
let left = f64::from(props.get(prop::GEO_LEFT).unwrap_or(0) as i32);
let top = f64::from(props.get(prop::GEO_TOP).unwrap_or(0) as i32);
let right = f64::from(props.get(prop::GEO_RIGHT).unwrap_or(21600) as i32);
let bottom = f64::from(props.get(prop::GEO_BOTTOM).unwrap_or(21600) as i32);
let (w, h) = ((right - left).abs().max(1.0), (bottom - top).abs().max(1.0));
let mut pts = points.iter().map(|(x, y)| (x - left, y - top));
let mut d = String::new();
let mut push = |cmd: &str, ps: &[(f64, f64)]| {
d.push_str(cmd);
for (x, y) in ps {
d.push_str(&format!(" {x} {y}"));
}
d.push(' ');
};
match props.array(prop::SEGMENT_INFO) {
// An empty segment list is no segments ([MS-ODRAW] shapePath: it applies unless the list
// is "neither NULL nor empty").
Some((2, segs)) if !segs.is_empty() => {
for c in segs.as_chunks::<2>().0.iter().take(MAX_SEGMENTS) {
let v = u16::from_le_bytes(*c);
let count = usize::from(v & 0x1FFF);
match v >> 13 {
// lineTo
0 => {
for _ in 0..count.max(1) {
let Some(p) = pts.next() else { break };
push("L", &[p]);
}
}
// curveTo: three points per segment
1 => {
for _ in 0..count.max(1) {
let ps: Vec<_> = pts.by_ref().take(3).collect();
if ps.len() < 3 {
break;
}
push("C", &ps);
}
}
2 => {
let Some(p) = pts.next() else { break };
push("M", &[p]);
}
3 => push("Z", &[]),
4 => break,
// Escapes (MSOPATHESCAPEINFO: escape code in bits 8–12, point count in bits
// 0–7). They aren't drawn as curves, but they use up their points, and the
// segments after them start where they end.
5 => {
let n = usize::from(v & 0xFF);
let code = (v >> 8) & 0x1F;
let mut last = None;
for _ in 0..n {
last = pts.next().or(last);
}
match code {
// Extension: more points for the escape that follows. Fill and line
// colours: a colour pair, not a place. NoFill, NoLine and the Bézier
// editing hints: no points.
0x00 | 0x0A..=0x16 => {}
// Elliptical quadrants run from point to point and a quadratic Bézier
// ends on its last point: a line there keeps the path's place.
0x07..=0x09 => {
if let Some(p) = last {
push("L", &[p]);
}
}
// Angle ellipses and arcs end at a point computed from their angles or
// radial vectors, not at one of their vertices: the path stops rather
// than go on from the wrong place. So does any other escape.
_ => break,
}
}
// Client escapes mean what the writing application says: the path stops
// unless one has no points.
6 if v & 0xFF != 0 => break,
_ => {}
}
}
}
// No segments: shapePath says how the vertices join (MSOSHAPEPATH), by default
// msoshapeLinesClosed.
_ => {
let shape_path = props.get(prop::SHAPE_PATH).unwrap_or(1);
if let Some(p) = pts.next() {
push("M", &[p]);
}
if matches!(shape_path, 2 | 3) {
loop {
let ps: Vec<_> = pts.by_ref().take(3).collect();
if ps.len() < 3 {
break;
}
push("C", &ps);
}
} else {
for p in pts {
push("L", &[p]);
}
}
if matches!(shape_path, 1 | 3) {
push("Z", &[]);
}
}
}
let d = d.trim_end().to_string();
if !d.starts_with('M') {
return None;
}
Some(vec![CustomPath { w, h, d, ..Default::default() }])
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::record::Rec;
use crate::record::build::atom;
fn props(entries: &[(u16, u32)], complex: &[u8]) -> Vec<u8> {
let mut b = vec![];
for (id, op) in entries {
b.extend_from_slice(&id.to_le_bytes());
b.extend_from_slice(&op.to_le_bytes());
}
b.extend_from_slice(complex);
atom(crate::doc::rt::FOPT, entries.len() as u16, &b)
}
fn array(size: u16, elems: &[u8]) -> Vec<u8> {
let n = (elems.len() / usize::from(size)) as u16;
[&n.to_le_bytes()[..], &n.to_le_bytes(), &size.to_le_bytes(), elems].concat()
}
#[test]
fn every_mapped_preset_is_one_craft_drawingml_draws() {
for t in 0..=255u16 {
if let Some(name) = preset_name(t) {
assert!(craft_drawingml::preset::build(name, 100.0, 100.0, &[]).is_some(), "type {t}: {name}");
}
}
}
#[test]
fn reads_a_freeform_triangle() {
let verts: Vec<u8> = [(0i16, 100i16), (50, 0), (100, 100)].iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect();
// moveTo, lineTo ×2, close, end
let segs: Vec<u8> = [0x4000u16, 0x0002, 0x6001, 0x8000].iter().flat_map(|v| v.to_le_bytes()).collect();
let v = array(4, &verts);
let s = array(2, &segs);
let t = props(
&[
(prop::GEO_RIGHT, 100),
(prop::GEO_BOTTOM, 100),
(0x8000 | prop::VERTICES, v.len() as u32),
(0x8000 | prop::SEGMENT_INFO, s.len() as u32),
],
&[v, s].concat(),
);
let mut p = Props::default();
p.add_table(&Rec::at(&t, 0).unwrap());
let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") };
assert_eq!(paths[0].d, "M 0 100 L 50 0 L 100 100 Z");
assert_eq!((paths[0].w, paths[0].h), (100.0, 100.0));
}
/// A freeform with more vertices than [`MAX_POINTS`] draws through the first of them only.
#[test]
fn a_path_uses_at_most_max_points() {
let verts: Vec<u8> = (0..20_000u32).flat_map(|i| [(i as i16 % 100).to_le_bytes(), 0i16.to_le_bytes()].concat()).collect();
let v = array(4, &verts);
let t = props(&[(0x8000 | prop::VERTICES, v.len() as u32)], &v);
let mut p = Props::default();
p.add_table(&Rec::at(&t, 0).unwrap());
let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") };
let d = &paths[0].d;
assert_eq!(d.matches('M').count() + d.matches('L').count(), MAX_POINTS);
}
fn freeform(verts: &[(i16, i16)], segs: Option<&[u16]>, extra: &[(u16, u32)]) -> Geom {
let verts: Vec<u8> = verts.iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect();
let v = array(4, &verts);
let mut entries = vec![(prop::GEO_RIGHT, 100), (prop::GEO_BOTTOM, 100), (0x8000 | prop::VERTICES, v.len() as u32)];
entries.extend_from_slice(extra);
let mut complex = v;
if let Some(segs) = segs {
let s = array(2, &segs.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
entries.push((0x8000 | prop::SEGMENT_INFO, s.len() as u32));
complex.extend_from_slice(&s);
}
let t = props(&entries, &complex);
let mut p = Props::default();
p.add_table(&Rec::at(&t, 0).unwrap());
geometry(0, &p)
}
fn path_of(g: Geom) -> String {
let Geom::Custom { paths } = g else { panic!("not custom: {g:?}") };
paths[0].d.clone()
}
/// An escape segment uses up its points and the path goes on from where it ends: after
/// elliptical quadrants or a quadratic Bézier, from their last point; an arc ends at a point
/// worked out from its radial vectors, so the path stops there rather than draw the next line
/// from the point before the arc.
#[test]
fn path_escapes_end_where_they_end() {
let verts = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (50, 60)];
let escape = |code: u16, n: u16| (5u16 << 13) | (code << 8) | n;
// moveTo, escape ArcTo (3) over 4 points, lineTo, end.
assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(3, 4), 0x0001, 0x8000]), &[])), "M 0 0");
// moveTo, two elliptical quadrants (7), lineTo, end.
let verts = [(0, 0), (10, 10), (20, 0), (50, 60)];
assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(7, 2), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0 L 50 60");
// A colour escape uses its point but doesn't move the path.
assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(0x15, 1), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0");
}
/// Without segments, shapePath says how the vertices join: closed lines by default, open
/// lines, or Bézier curves three points at a time. An empty segment list is no segments.
#[test]
fn shape_path_joins_vertices_without_segments() {
let tri = [(0, 100), (50, 0), (100, 100)];
assert_eq!(path_of(freeform(&tri, None, &[])), "M 0 100 L 50 0 L 100 100 Z");
assert_eq!(path_of(freeform(&tri, Some(&[]), &[])), "M 0 100 L 50 0 L 100 100 Z");
assert_eq!(path_of(freeform(&tri, None, &[(prop::SHAPE_PATH, 0)])), "M 0 100 L 50 0 L 100 100");
let curve = [(0, 0), (10, 0), (20, 10), (20, 20)];
assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 2)])), "M 0 0 C 10 0 20 10 20 20");
assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 3)])), "M 0 0 C 10 0 20 10 20 20 Z");
}
#[test]
fn a_rounded_rectangle_keeps_its_corner() {
let t = props(&[(prop::ADJUST_VALUE, 5400)], &[]);
let mut p = Props::default();
p.add_table(&Rec::at(&t, 0).unwrap());
assert_eq!(geometry(2, &p), Geom::Preset { name: "roundRect".into(), adj: vec![25000.0] });
assert_eq!(geometry(9999, &Props::default()), Geom::default());
}
}
+76
View File
@@ -0,0 +1,76 @@
//! Legacy PowerPoint 97–2003 import (`.ppt`, `.pot`, `.pps`), written from Microsoft's public
//! Open Specifications: [MS-PPT] (the presentation records) and [MS-ODRAW] (the shapes and
//! pictures), on `craft-cfb` for the compound file ([MS-CFB]).
//!
//! [`import`] reads a presentation leniently into a [`craft_pptx::Presentation`]: unknown records
//! are skipped, damaged ones are left out, and every size, count and depth is bounded. The caller's
//! [`Defaults`] supply each master's layouts and placeholders, which the file's masters then
//! place and style. There is no `.ppt` writer.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeExamples;
mod blip;
mod convert;
mod doc;
mod draw;
mod geom;
mod record;
mod text;
use craft_cfb::{CompoundFile, Error as CfbError};
use craft_pptx::{Defaults, Presentation};
/// Name of the stream holding the presentation.
const DOCUMENT_STREAM: &str = "PowerPoint Document";
#[derive(Debug, thiserror::Error)]
pub enum PptError {
#[error("not a PowerPoint 97-2003 presentation")]
NotPpt,
#[error("the presentation is password-protected")]
Encrypted,
#[error("the presentation was made by PowerPoint 95 or earlier")]
TooOld,
#[error("the presentation is damaged: {0}")]
Damaged(String),
}
/// Does this look like a PowerPoint 97–2003 file (a compound file with a `PowerPoint Document`
/// stream)?
pub fn sniff(bytes: &[u8]) -> bool {
craft_cfb::sniff(bytes) && CompoundFile::open(bytes).is_ok_and(|f| f.has_stream(DOCUMENT_STREAM))
}
/// Read a `.ppt` / `.pot` / `.pps` file. `defaults` gives the master each of the file's masters
/// starts from, and the one used when the file has none it can read.
pub fn import(bytes: &[u8], defaults: &dyn Defaults) -> Result<Presentation, PptError> {
import_checked(bytes, defaults).map(|(p, _)| p)
}
/// [`import`], plus the slides the file lists but whose objects couldn't be found, so they are not
/// in the presentation.
pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec<String>), PptError> {
let file = CompoundFile::open(bytes).map_err(|e| match e {
CfbError::NotCfb => PptError::NotPpt,
other => PptError::Damaged(other.to_string()),
})?;
// No stream is longer than the file holding it: a larger stated size is damage, refused
// before anything is allocated for it.
let cap = bytes.len() as u64;
let stream = file.read_path_capped(DOCUMENT_STREAM, cap).map_err(|e| match e {
CfbError::NotFound(_) => PptError::NotPpt,
other => PptError::Damaged(other.to_string()),
})?;
let current_user = file.read_path_capped("Current User", cap).unwrap_or_default();
// A damaged or missing picture stream costs the pictures, not the presentation.
let pictures = file.read_path_capped("Pictures", cap).unwrap_or_default();
let d = doc::read(&current_user, &stream)?;
Ok((convert::convert(&d, &pictures, defaults), d.lost.clone()))
}
#[cfg(test)]
mod tests;
+186
View File
@@ -0,0 +1,186 @@
//! The record framing shared by [MS-PPT] and [MS-ODRAW]: an 8-byte header (version, instance,
//! type, length) followed by `len` bytes, which for a container (version `0xF`) are more records.
/// The little-endian `u16` at `at`, if `b` holds it.
pub(crate) fn u16_at(b: &[u8], at: usize) -> Option<u16> {
let s = b.get(at..at.checked_add(2)?)?;
Some(u16::from_le_bytes([*s.first()?, *s.get(1)?]))
}
/// The little-endian `u32` at `at`, if `b` holds it.
pub(crate) fn u32_at(b: &[u8], at: usize) -> Option<u32> {
let s = b.get(at..at.checked_add(4)?)?;
Some(u32::from_le_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?]))
}
/// Containers nest at most this deep; deeper input is treated as damaged and skipped.
pub const MAX_DEPTH: usize = 32;
/// One record over borrowed bytes.
#[derive(Clone, Copy, Debug)]
pub struct Rec<'a> {
pub ver: u8,
pub instance: u16,
pub kind: u16,
/// The record's body (after the header), clipped to the input.
pub data: &'a [u8],
/// Offset of the header in the slice it was read from.
pub offset: usize,
}
impl<'a> Rec<'a> {
/// The record whose header starts at `at`, its body clipped to `bytes` (a truncated last record
/// keeps what is there).
pub fn at(bytes: &'a [u8], at: usize) -> Option<Rec<'a>> {
let vi = u16_at(bytes, at)?;
let kind = u16_at(bytes, at.checked_add(2)?)?;
let len = u32_at(bytes, at.checked_add(4)?)? as usize;
let start = at.checked_add(8)?;
let end = start.saturating_add(len).min(bytes.len());
Some(Rec { ver: (vi & 0xF) as u8, instance: vi >> 4, kind, data: bytes.get(start..end)?, offset: at })
}
pub fn is_container(&self) -> bool {
self.ver == 0xF
}
/// The records inside this one; none for an atom.
pub fn children(&self) -> Records<'a> {
Records::new(if self.is_container() { self.data } else { &[] })
}
/// The first child of type `kind`.
pub fn child(&self, kind: u16) -> Option<Rec<'a>> {
self.children().find(|r| r.kind == kind)
}
/// Every child of type `kind`.
pub fn children_of(&self, kind: u16) -> impl Iterator<Item = Rec<'a>> {
self.children().filter(move |r| r.kind == kind)
}
pub fn u8(&self, at: usize) -> Option<u8> {
self.data.get(at).copied()
}
pub fn u16(&self, at: usize) -> Option<u16> {
u16_at(self.data, at)
}
pub fn i16(&self, at: usize) -> Option<i16> {
self.u16(at).map(|v| v as i16)
}
pub fn u32(&self, at: usize) -> Option<u32> {
u32_at(self.data, at)
}
pub fn i32(&self, at: usize) -> Option<i32> {
self.u32(at).map(|v| v as i32)
}
}
/// Iterates the records laid end to end in a byte slice.
#[derive(Clone, Debug)]
pub struct Records<'a> {
bytes: &'a [u8],
at: usize,
}
impl<'a> Records<'a> {
pub fn new(bytes: &'a [u8]) -> Self {
Records { bytes, at: 0 }
}
}
impl<'a> Iterator for Records<'a> {
type Item = Rec<'a>;
fn next(&mut self) -> Option<Rec<'a>> {
let r = Rec::at(self.bytes, self.at)?;
// Always advance by at least the header, so a zero-length record can't stall the walk.
self.at = self.at.checked_add(8)?.checked_add(r.data.len())?;
Some(r)
}
}
/// A little-endian reader over a record body for the variable-length structures (text
/// exceptions, style runs): every read is checked and a short body ends the walk.
pub struct Cursor<'a> {
pub b: &'a [u8],
pub at: usize,
}
impl<'a> Cursor<'a> {
pub fn new(b: &'a [u8]) -> Self {
Cursor { b, at: 0 }
}
/// Bytes left to read.
pub fn remaining(&self) -> usize {
self.b.len().saturating_sub(self.at)
}
pub fn u8(&mut self) -> Option<u8> {
let v = *self.b.get(self.at)?;
self.at += 1;
Some(v)
}
pub fn u16(&mut self) -> Option<u16> {
let v = u16_at(self.b, self.at)?;
self.at += 2;
Some(v)
}
pub fn i16(&mut self) -> Option<i16> {
self.u16().map(|v| v as i16)
}
pub fn u32(&mut self) -> Option<u32> {
let v = u32_at(self.b, self.at)?;
self.at += 4;
Some(v)
}
}
#[cfg(test)]
pub(crate) mod build {
//! Writing records, for tests that build `.ppt` files.
pub fn atom(kind: u16, instance: u16, body: &[u8]) -> Vec<u8> {
head(0, kind, instance, body)
}
pub fn container(kind: u16, instance: u16, children: &[Vec<u8>]) -> Vec<u8> {
head(0xF, kind, instance, &children.concat())
}
fn head(ver: u16, kind: u16, instance: u16, body: &[u8]) -> Vec<u8> {
let mut v = Vec::with_capacity(body.len() + 8);
v.extend_from_slice(&(ver | (instance << 4)).to_le_bytes());
v.extend_from_slice(&kind.to_le_bytes());
v.extend_from_slice(&(body.len() as u32).to_le_bytes());
v.extend_from_slice(body);
v
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::build::*;
use super::*;
#[test]
fn walks_nested_records() {
let c = container(0x03E8, 0, &[atom(0x03E9, 0, &[1, 2, 3, 4]), atom(0x0FA0, 2, &[9; 6])]);
let r = Rec::at(&c, 0).unwrap();
assert!(r.is_container());
let kids: Vec<_> = r.children().collect();
assert_eq!(kids.len(), 2);
assert_eq!(kids[1].instance, 2);
assert_eq!(r.child(0x03E9).unwrap().u32(0), Some(0x0403_0201));
}
#[test]
fn truncated_and_zero_length_records_end_the_walk() {
let mut c = atom(0x1, 0, &[]).repeat(3);
c.extend_from_slice(&[0xF, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0x7F, 1, 2]);
let all: Vec<_> = Records::new(&c).collect();
assert_eq!(all.len(), 4);
assert_eq!(all[3].data, &[1, 2]);
assert!(Records::new(&[1, 2, 3]).next().is_none());
}
}
File diff suppressed because it is too large Load Diff
+755
View File
@@ -0,0 +1,755 @@
//! Text in `.ppt` ([MS-PPT] §2.9): characters in a `TextCharsAtom` (UTF-16) or `TextBytesAtom`
//! (Latin-1), formatting as runs of paragraph exceptions (`TextPFException`) and character
//! exceptions (`TextCFException`) over the master's per-level text styles.
use crate::doc::rt;
use crate::record::{Cursor, Rec};
/// A colour as text formatting stores it: an RGB value or an index into the colour scheme.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextColor {
Rgb(u8, u8, u8),
Scheme(u8),
}
fn color_index(c: &mut Cursor) -> Option<Option<TextColor>> {
let (r, g, b, i) = (c.u8()?, c.u8()?, c.u8()?, c.u8()?);
Some(match i {
0xFE => Some(TextColor::Rgb(r, g, b)),
0..=7 => Some(TextColor::Scheme(i)),
_ => None,
})
}
/// Paragraph formatting; `None` fields are not set at this level.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Pf {
pub has_bullet: Option<bool>,
pub bullet_has_font: Option<bool>,
pub bullet_has_color: Option<bool>,
pub bullet_has_size: Option<bool>,
pub bullet_char: Option<u16>,
pub bullet_font: Option<u16>,
/// Positive: percent of the text size; negative: absolute size in points.
pub bullet_size: Option<i16>,
pub bullet_color: Option<TextColor>,
/// 0 left, 1 centre, 2 right, 3 justify, 4 distributed, 5 Thai distributed, 6 justify low.
pub align: Option<u16>,
/// Positive: percent of a line; negative: master units (−8 per point).
pub line_spacing: Option<i16>,
pub space_before: Option<i16>,
pub space_after: Option<i16>,
/// Master units from the text box's left edge.
pub left_margin: Option<u16>,
pub indent: Option<u16>,
pub default_tab: Option<u16>,
pub tabs: Option<Vec<(i16, u16)>>,
}
impl Pf {
/// Overlay `o`'s set fields on this one.
pub fn apply(&mut self, o: &Pf) {
macro_rules! over {
($($f:ident),*) => { $( if o.$f.is_some() { self.$f.clone_from(&o.$f); } )* };
}
over!(
has_bullet,
bullet_has_font,
bullet_has_color,
bullet_has_size,
bullet_char,
bullet_font,
bullet_size,
bullet_color,
align,
line_spacing,
space_before,
space_after,
left_margin,
indent,
default_tab,
tabs
);
}
}
/// Character formatting; `None` fields are not set at this level.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Cf {
pub bold: Option<bool>,
pub italic: Option<bool>,
pub underline: Option<bool>,
pub shadow: Option<bool>,
pub font: Option<u16>,
pub ea_font: Option<u16>,
pub symbol_font: Option<u16>,
/// Points.
pub size: Option<u16>,
pub color: Option<TextColor>,
/// Superscript (positive) or subscript (negative) offset, percent of the size.
pub position: Option<i16>,
/// `pp9rt`: the index of the paragraph's PowerPoint 2000 formatting (numbering) in the text's
/// `StyleTextProp9Atom`.
pub pp9rt: Option<u8>,
}
impl Cf {
pub fn apply(&mut self, o: &Cf) {
macro_rules! over {
($($f:ident),*) => { $( if o.$f.is_some() { self.$f = o.$f; } )* };
}
over!(bold, italic, underline, shadow, font, ea_font, symbol_font, size, color, position, pp9rt);
}
}
fn bit(m: u32, b: u32) -> bool {
m & (1 << b) != 0
}
/// A `TextPFException`.
pub fn read_pf(c: &mut Cursor) -> Option<Pf> {
let m = c.u32()?;
let mut pf = Pf::default();
if m & 0xF != 0 {
let flags = c.u16()?;
for (b, slot) in [(0, &mut pf.has_bullet), (1, &mut pf.bullet_has_font), (2, &mut pf.bullet_has_color), (3, &mut pf.bullet_has_size)] {
if bit(m, b) {
*slot = Some(flags & (1 << b) != 0);
}
}
}
if bit(m, 7) {
pf.bullet_char = Some(c.u16()?);
}
if bit(m, 4) {
pf.bullet_font = Some(c.u16()?);
}
if bit(m, 6) {
pf.bullet_size = Some(c.i16()?);
}
if bit(m, 5) {
pf.bullet_color = color_index(c)?;
}
if bit(m, 11) {
pf.align = Some(c.u16()?);
}
if bit(m, 12) {
pf.line_spacing = Some(c.i16()?);
}
if bit(m, 13) {
pf.space_before = Some(c.i16()?);
}
if bit(m, 14) {
pf.space_after = Some(c.i16()?);
}
if bit(m, 8) {
pf.left_margin = Some(c.u16()?);
}
if bit(m, 10) {
pf.indent = Some(c.u16()?);
}
if bit(m, 15) {
pf.default_tab = Some(c.u16()?);
}
if bit(m, 20) {
pf.tabs = Some(read_tabs(c)?);
}
if bit(m, 16) {
c.u16()?; // fontAlign
}
if m & (0x7 << 17) != 0 {
c.u16()?; // wrapFlags
}
if bit(m, 21) {
c.u16()?; // textDirection
}
Some(pf)
}
/// Tab stops kept per paragraph exception or ruler. Every entry is still read past, so the fields
/// after the list stay aligned; the rest are dropped, since each paragraph copies the list.
const MAX_TABS: usize = 64;
fn read_tabs(c: &mut Cursor) -> Option<Vec<(i16, u16)>> {
let n = c.u16()?;
let mut v = Vec::with_capacity(usize::from(n).min(MAX_TABS));
for _ in 0..n {
let tab = (c.i16()?, c.u16()?);
if v.len() < MAX_TABS {
v.push(tab);
}
}
Some(v)
}
/// A `TextCFException`.
pub fn read_cf(c: &mut Cursor) -> Option<Cf> {
let m = c.u32()?;
let mut cf = Cf::default();
// fontStyle is present when any of bold, italic, underline, shadow, fehint, kumi, emboss or
// fHasStyle is in the mask.
if m & 0x3EB7 != 0 {
let s = c.u16()?;
// Emboss (bit 9) has no counterpart in the model; docs/gaps.md lists it.
for (b, slot) in [(0, &mut cf.bold), (1, &mut cf.italic), (2, &mut cf.underline), (4, &mut cf.shadow)] {
if bit(m, b) {
*slot = Some(s & (1 << b) != 0);
}
}
// fHasStyle (bits 10–13) says pp9rt, the same four bits of fontStyle, is given.
if m & 0x3C00 != 0 {
cf.pp9rt = Some(((s >> 10) & 0xF) as u8);
}
}
if bit(m, 16) {
cf.font = Some(c.u16()?);
}
if bit(m, 21) {
cf.ea_font = Some(c.u16()?);
}
if bit(m, 22) {
c.u16()?; // ansiFontRef
}
if bit(m, 23) {
cf.symbol_font = Some(c.u16()?);
}
if bit(m, 17) {
cf.size = Some(c.u16()?);
}
if bit(m, 18) {
cf.color = color_index(c)?;
}
if bit(m, 19) {
cf.position = Some(c.i16()?);
}
// The fields PowerPoint 2002 and later add are not used, but they must be read past: the next
// run's count and mask follow them, so stopping short garbles every later run's formatting.
if bit(m, 20) {
c.u32()?; // pp10runid (4 bits) and unused (28 bits)
}
if bit(m, 24) {
c.u16()?; // newEAFontRef
}
if bit(m, 25) {
c.u16()?; // csFontRef
}
if bit(m, 26) {
c.u32()?; // pp11ext
}
Some(cf)
}
/// A paragraph's PowerPoint 2000 formatting (`TextPFException9`): its automatic numbering.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Pf9 {
/// `fBulletHasAutoNumber` with `bulletAutoNumberScheme`: the scheme and the first number.
pub auto_number: Option<(u16, i16)>,
}
/// The entries of a `StyleTextProp9Atom` ([MS-PPT] §2.9.33): each a `TextPFException9`, a
/// `TextCFException9` and a `TextSIException`, indexed by the runs' `pp9rt`. Reading stops at an
/// entry with a field this reader can't size, keeping the entries before it.
pub fn read_style9(b: &[u8]) -> Vec<Pf9> {
let mut c = Cursor::new(b);
let mut out = vec![];
// pp9rt has four bits, so sixteen entries are all a run can name.
while out.len() < 16 && c.remaining() > 0 {
let Some(pf9) = read_pf9(&mut c) else { break };
out.push(pf9);
// TextCFException9: the extension fields of a character mask.
let Some(m) = c.u32() else { break };
if m & !((1 << 20) | (1 << 24) | (1 << 25) | (1 << 26)) != 0 {
break;
}
let ok = (!bit(m, 20) || c.u32().is_some())
&& (!bit(m, 24) || c.u16().is_some())
&& (!bit(m, 25) || c.u16().is_some())
&& (!bit(m, 26) || c.u32().is_some());
// TextSIException: spelling, language, alternate language, bidi, pp10 extension, smart tags.
if !ok || read_si(&mut c).is_none() {
break;
}
}
out
}
fn read_pf9(c: &mut Cursor) -> Option<Pf9> {
let m = c.u32()?;
if bit(m, 23) {
c.i16()?; // bulletBlipRef
}
let has_auto = if bit(m, 25) { Some(c.u16()? != 0) } else { None };
let scheme = if bit(m, 24) { Some((c.u16()?, c.i16()?)) } else { None };
if bit(m, 26) {
c.u32()?; // pp10 extension
}
Some(Pf9 { auto_number: if has_auto == Some(true) { Some(scheme.unwrap_or((3, 1))) } else { None } })
}
fn read_si(c: &mut Cursor) -> Option<()> {
let m = c.u32()?;
if m & !0x027F != 0 {
return None;
}
for b in [0, 1, 2, 6] {
if bit(m, b) {
c.u16()?;
}
}
if bit(m, 5) {
c.u32()?; // pp10runid and reserved
}
if bit(m, 9) {
let n = c.u32()?;
for _ in 0..n {
c.u32()?;
}
}
Some(())
}
/// The DrawingML numbering scheme of a `TextAutoNumberSchemeEnum` value.
pub fn auto_number_scheme(v: u16) -> &'static str {
match v {
0 => "alphaLcPeriod",
1 => "alphaUcPeriod",
2 => "arabicParenR",
4 => "romanLcParenBoth",
5 => "romanLcParenR",
6 => "romanLcPeriod",
7 => "romanUcPeriod",
8 => "alphaLcParenBoth",
9 => "alphaLcParenR",
10 => "alphaUcParenBoth",
11 => "alphaUcParenR",
12 => "arabicParenBoth",
13 => "arabicPlain",
14 => "romanUcParenBoth",
15 => "romanUcParenR",
0x10 => "ea1ChsPlain",
0x11 => "ea1ChsPeriod",
0x12 => "circleNumDbPlain",
0x13 => "circleNumWdWhitePlain",
0x14 => "circleNumWdBlackPlain",
0x15 => "ea1ChtPlain",
0x16 => "ea1ChtPeriod",
0x17 => "arabic1Minus",
0x18 => "arabic2Minus",
0x19 => "hebrew2Minus",
0x1A => "ea1JpnKorPlain",
0x1B => "ea1JpnKorPeriod",
0x1C => "arabicDbPlain",
0x1D => "arabicDbPeriod",
0x1E => "thaiAlphaPeriod",
0x1F => "thaiAlphaParenR",
0x20 => "thaiAlphaParenBoth",
0x21 => "thaiNumPeriod",
0x22 => "thaiNumParenR",
0x23 => "thaiNumParenBoth",
0x24 => "hindiAlphaPeriod",
0x25 => "hindiNumPeriod",
0x26 => "ea1JpnChsDbPeriod",
0x27 => "hindiNumParenR",
0x28 => "hindiAlpha1Period",
_ => "arabicPeriod",
}
}
/// Text types (`TextHeaderAtom.textType`).
pub mod ty {
pub const TITLE: u32 = 0;
pub const BODY: u32 = 1;
pub const NOTES: u32 = 2;
pub const OTHER: u32 = 4;
pub const CENTER_BODY: u32 = 5;
pub const CENTER_TITLE: u32 = 6;
pub const HALF_BODY: u32 = 7;
pub const QUARTER_BODY: u32 = 8;
}
/// One master text style: up to five levels of paragraph and character formatting.
#[derive(Clone, Debug, Default)]
pub struct LevelStyles {
pub levels: Vec<(Pf, Cf)>,
}
/// A `TextMasterStyleAtom` body.
pub fn read_master_style(r: &Rec) -> LevelStyles {
let mut c = Cursor::new(r.data);
let mut out = LevelStyles::default();
let Some(n) = c.u16() else { return out };
for i in 0..usize::from(n.min(5)) {
// From the centre-body type on, each level names itself (TextMasterStyleLevel.level).
let level = if u32::from(r.instance) >= ty::CENTER_BODY {
let Some(l) = c.u16() else { break };
usize::from(l)
} else {
i
};
let Some(pf) = read_pf(&mut c) else { break };
let Some(cf) = read_cf(&mut c) else { break };
// Only five levels exist; one naming another is read past.
if level >= 5 {
continue;
}
if out.levels.len() <= level {
out.levels.resize(level + 1, Default::default());
}
if let Some(slot) = out.levels.get_mut(level) {
*slot = (pf, cf);
}
}
out
}
/// The text styles in effect for a master: the document defaults plus the master's styles by text
/// type.
#[derive(Clone, Debug, Default)]
pub struct StyleSheet {
pub default_pf: Pf,
pub default_cf: Cf,
/// Indexed by text type (0–8).
pub types: Vec<Option<LevelStyles>>,
}
impl StyleSheet {
/// Read the defaults of the document environment and, over them, a master's styles.
pub fn new(environment: Option<Rec>, master: Option<&Rec>) -> Self {
let mut s = StyleSheet { types: vec![None; 9], ..Default::default() };
if let Some(env) = environment {
if let Some(pf) = env.child(rt::TEXT_PF_EXCEPTION).and_then(|r| read_pf(&mut Cursor { b: r.data, at: 2 })) {
s.default_pf = pf;
}
if let Some(cf) = env.child(rt::TEXT_CF_EXCEPTION).and_then(|r| read_cf(&mut Cursor::new(r.data))) {
s.default_cf = cf;
}
for r in env.children_of(rt::TEXT_MASTER_STYLE) {
if let Some(slot) = s.types.get_mut(usize::from(r.instance)) {
*slot = Some(read_master_style(&r));
}
}
}
if let Some(m) = master {
for r in m.children_of(rt::TEXT_MASTER_STYLE) {
if let Some(slot) = s.types.get_mut(usize::from(r.instance)) {
*slot = Some(read_master_style(&r));
}
}
}
s
}
/// The formatting of text type `ty` at outline level `level`: defaults, then the base type's
/// level 1 and level, then this type's.
pub fn resolve(&self, ty: u32, level: u8) -> (Pf, Cf) {
let (mut pf, mut cf) = (self.default_pf.clone(), self.default_cf.clone());
let base = match ty {
ty::CENTER_TITLE => Some(ty::TITLE),
ty::CENTER_BODY | ty::HALF_BODY | ty::QUARTER_BODY => Some(ty::BODY),
_ => None,
};
for t in base.into_iter().chain(std::iter::once(ty)) {
let Some(Some(st)) = self.types.get(t as usize) else { continue };
for l in [0usize, usize::from(level)] {
if let Some((p, c)) = st.levels.get(l) {
pf.apply(p);
cf.apply(c);
}
if level == 0 {
break;
}
}
}
(pf, cf)
}
}
/// A field inside text: its character position and kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FieldKind {
SlideNumber,
DateTime,
}
/// A block of text with its formatting runs.
#[derive(Clone, Debug, Default)]
pub struct TextBlock {
pub text_type: u32,
pub chars: Vec<u16>,
/// (character count, indent level, paragraph exception).
pub para_runs: Vec<(u32, u8, Pf)>,
/// (character count, character exception).
pub char_runs: Vec<(u32, Cf)>,
/// Ruler overrides per level: (left margin, indent) in master units.
pub ruler: [(Option<u16>, Option<u16>); 5],
pub fields: Vec<(u32, FieldKind)>,
/// An `OutlineTextRefAtom`: the text is the n-th outline block of the slide list entry.
pub outline_ref: Option<u32>,
/// The slide list's outline block this text was read from.
pub outline_index: Option<usize>,
}
/// Read a text block from a run of records starting at its `TextHeaderAtom` (inside a client text
/// box, or in the slide list). Stops at the next header or slide persist atom. A client text box
/// may hold only an `OutlineTextRefAtom` ([MS-PPT] OfficeArtClientTextbox), with no header: that
/// is still a block, so the caller can follow the reference.
pub fn read_block<'a>(records: impl Iterator<Item = Rec<'a>>) -> Option<TextBlock> {
let mut b = TextBlock::default();
let mut started = false;
let mut style: Option<Rec> = None;
for r in records {
match r.kind {
rt::TEXT_HEADER if started => break,
rt::SLIDE_PERSIST_ATOM => break,
rt::TEXT_HEADER => {
started = true;
b.text_type = r.u32(0).unwrap_or(ty::OTHER);
}
rt::TEXT_CHARS => b.chars = r.data.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(),
rt::TEXT_BYTES => b.chars = r.data.iter().map(|&c| u16::from(c)).collect(),
rt::STYLE_TEXT_PROP => style = Some(r),
rt::TEXT_RULER => b.ruler = read_ruler(&r),
rt::OUTLINE_TEXT_REF => b.outline_ref = r.u32(0),
rt::SLIDE_NUMBER_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::SlideNumber))),
rt::DATETIME_MC | rt::GENERIC_DATE_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::DateTime))),
_ => {}
}
}
if !started && b.outline_ref.is_none() {
return None;
}
if let Some(st) = style {
// Text past u32::MAX characters can't be addressed by the runs; saturate rather than wrap.
read_style_runs(&st, u32::try_from(b.chars.len()).unwrap_or(u32::MAX).saturating_add(1), &mut b);
}
Some(b)
}
/// The paragraph runs then the character runs of a `StyleTextPropAtom`; each set covers the text
/// plus one (the final paragraph mark).
fn read_style_runs(r: &Rec, total: u32, b: &mut TextBlock) {
let mut c = Cursor::new(r.data);
let mut covered = 0u32;
while covered < total {
let Some(n) = c.u32() else { return };
let Some(level) = c.u16() else { return };
let Some(pf) = read_pf(&mut c) else { return };
b.para_runs.push((n, level.min(8) as u8, pf));
covered = covered.saturating_add(n.max(1));
}
covered = 0;
while covered < total {
let Some(n) = c.u32() else { return };
let Some(cf) = read_cf(&mut c) else { return };
b.char_runs.push((n, cf));
covered = covered.saturating_add(n.max(1));
}
}
fn read_ruler(r: &Rec) -> [(Option<u16>, Option<u16>); 5] {
let mut out = [(None, None); 5];
let mut c = Cursor::new(r.data);
let Some(m) = c.u32() else { return out };
if bit(m, 1) && c.u16().is_none() {
return out;
}
if bit(m, 0) && c.u16().is_none() {
return out;
}
if bit(m, 2) && read_tabs(&mut c).is_none() {
return out;
}
for (l, slot) in out.iter_mut().enumerate() {
let l = l as u32;
if bit(m, 3 + l) {
slot.0 = c.u16();
}
if bit(m, 8 + l) {
slot.1 = c.u16();
}
}
out
}
#[cfg(test)]
pub(crate) mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::record::build::*;
/// A PF exception with alignment and bullets on or off.
pub fn pf_bytes(align: u16, bullet: bool) -> Vec<u8> {
let mut v = (0x0000_0801u32).to_le_bytes().to_vec(); // hasBullet + align
v.extend_from_slice(&u16::from(bullet).to_le_bytes());
v.extend_from_slice(&align.to_le_bytes());
v
}
/// A CF exception with bold, a font, a size and an RGB colour.
pub fn cf_bytes(bold: bool, font: u16, size: u16, rgb: [u8; 3]) -> Vec<u8> {
let mut v = (0x0007_0001u32).to_le_bytes().to_vec(); // bold + typeface + size + color
v.extend_from_slice(&u16::from(bold).to_le_bytes());
v.extend_from_slice(&font.to_le_bytes());
v.extend_from_slice(&size.to_le_bytes());
v.extend_from_slice(&[rgb[0], rgb[1], rgb[2], 0xFE]);
v
}
/// The `StyleTextProp9Atom` entries as PowerPoint writes them: three, the second numbered "1."
/// from 1. Short or unknown data keeps the entries read before it.
#[test]
fn reads_numbering_entries() {
let mut b = vec![0u8; 12];
b.extend_from_slice(&[0, 0, 0, 3, 1, 0, 3, 0, 1, 0]);
b.extend_from_slice(&[0; 8]);
b.extend_from_slice(&[0; 12]);
let e = read_style9(&b);
assert_eq!(e.iter().map(|p| p.auto_number).collect::<Vec<_>>(), [None, Some((3, 1)), None]);
assert_eq!(read_style9(b.get(..20).unwrap()).len(), 1);
assert_eq!(read_style9(b.get(..22).unwrap()).len(), 2);
assert_eq!(read_style9(&[0xFF; 64]).len(), 1);
assert!(read_style9(&[]).is_empty());
assert_eq!(auto_number_scheme(3), "arabicPeriod");
assert_eq!(auto_number_scheme(0), "alphaLcPeriod");
}
/// The East Asian, bidi, Thai and Hindi schemes (0x10–0x28) have DrawingML names of their
/// own; only an unknown value falls back to "1.".
#[test]
fn every_numbering_scheme_has_its_drawingml_name() {
assert_eq!(auto_number_scheme(0x10), "ea1ChsPlain");
assert_eq!(auto_number_scheme(0x13), "circleNumWdWhitePlain");
assert_eq!(auto_number_scheme(0x19), "hebrew2Minus");
assert_eq!(auto_number_scheme(0x26), "ea1JpnChsDbPeriod");
assert_eq!(auto_number_scheme(0x28), "hindiAlpha1Period");
let names: std::collections::HashSet<_> = (0..=0x28).map(auto_number_scheme).collect();
assert_eq!(names.len(), 0x29, "each value its own scheme");
assert_eq!(auto_number_scheme(0x29), "arabicPeriod");
}
/// From the centre-body type on, a master style level names its level: it is stored there,
/// and a level past the fifth is read past.
#[test]
fn master_style_levels_go_where_they_say() {
let level = |l: u16, size: u16| [&l.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, size, [0, 0, 0])].concat();
let body = [&3u16.to_le_bytes()[..], &level(2, 20), &level(7, 30), &level(0, 40)].concat();
let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::CENTER_BODY as u16, &body);
let st = read_master_style(&Rec::at(&rec, 0).unwrap());
let sizes: Vec<_> = st.levels.iter().map(|(_, cf)| cf.size).collect();
assert_eq!(sizes, [Some(40), None, Some(20)]);
// Before it, levels are in order.
let body = [&1u16.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, 12, [0, 0, 0])].concat();
let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::BODY as u16, &body);
assert_eq!(read_master_style(&Rec::at(&rec, 0).unwrap()).levels[0].1.size, Some(12));
}
/// A paragraph exception with many tab stops keeps the first [`MAX_TABS`] and reads the
/// fields after the list where they are.
#[test]
fn tab_stops_are_capped_and_read_past() {
let mut b = ((1u32 << 20) | (1 << 21)).to_le_bytes().to_vec(); // tabStops + textDirection
b.extend_from_slice(&1000u16.to_le_bytes());
for i in 0..1000u16 {
b.extend_from_slice(&(i as i16).to_le_bytes());
b.extend_from_slice(&1u16.to_le_bytes());
}
b.extend_from_slice(&0x1234u16.to_le_bytes()); // textDirection
b.push(0xAB);
let mut c = Cursor::new(&b);
let pf = read_pf(&mut c).unwrap();
let tabs = pf.tabs.unwrap();
assert_eq!(tabs.len(), MAX_TABS);
assert_eq!(tabs[MAX_TABS - 1], (MAX_TABS as i16 - 1, 1));
assert_eq!(c.u8(), Some(0xAB), "the cursor stopped past textDirection");
}
#[test]
fn reads_exceptions_in_mask_order() {
let pf = read_pf(&mut Cursor::new(&pf_bytes(1, true))).unwrap();
assert_eq!(pf.has_bullet, Some(true));
assert_eq!(pf.align, Some(1));
assert_eq!(pf.bullet_has_font, None);
let cf = read_cf(&mut Cursor::new(&cf_bytes(true, 3, 28, [1, 2, 3]))).unwrap();
assert_eq!((cf.bold, cf.italic, cf.font, cf.size, cf.color), (Some(true), None, Some(3), Some(28), Some(TextColor::Rgb(1, 2, 3))));
// A mask promising more than the bytes hold reads nothing.
assert!(read_cf(&mut Cursor::new(&0x0007_0000u32.to_le_bytes())).is_none());
}
#[test]
fn reads_a_text_block_with_runs() {
let chars: Vec<u8> = "Hi\rthere".encode_utf16().flat_map(u16::to_le_bytes).collect();
let mut style = vec![];
for (n, lvl) in [(3u32, 0u16), (6, 1)] {
style.extend_from_slice(&n.to_le_bytes());
style.extend_from_slice(&lvl.to_le_bytes());
style.extend_from_slice(&pf_bytes(0, lvl == 1));
}
for n in [2u32, 7] {
style.extend_from_slice(&n.to_le_bytes());
style.extend_from_slice(&cf_bytes(n == 2, 0, 20, [0, 0, 0]));
}
let recs = [
atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()),
atom(rt::TEXT_CHARS, 0, &chars),
atom(rt::STYLE_TEXT_PROP, 0, &style),
atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()),
]
.concat();
let b = read_block(crate::record::Records::new(&recs)).unwrap();
assert_eq!(b.text_type, ty::BODY);
assert_eq!(String::from_utf16_lossy(&b.chars), "Hi\rthere");
assert_eq!(b.para_runs.len(), 2);
assert_eq!(b.para_runs[1].1, 1);
assert_eq!(b.char_runs.len(), 2);
assert_eq!(b.char_runs[0].1.bold, Some(true));
}
/// A CF exception with only the fields PowerPoint 2002 and later add after `position`:
/// pp10runid (bit 20), newEAFontRef (bit 24), csFontRef (bit 25) and pp11ext (bit 26).
fn cf_later_fields() -> Vec<u8> {
let mut v = (1u32 << 20 | 1 << 24 | 1 << 25 | 1 << 26).to_le_bytes().to_vec();
v.extend_from_slice(&0x0000_0003u32.to_le_bytes()); // pp10runid + unused
v.extend_from_slice(&7u16.to_le_bytes()); // newEAFontRef
v.extend_from_slice(&8u16.to_le_bytes()); // csFontRef
v.extend_from_slice(&0u32.to_le_bytes()); // pp11ext
v
}
#[test]
fn later_character_fields_are_read_past() {
let bytes = cf_later_fields();
let mut c = Cursor::new(&bytes);
assert!(read_cf(&mut c).is_some());
assert!(c.u8().is_none(), "the cursor stopped inside the exception");
// A run carrying those fields, then a bold 18 pt run: the second must read as written.
let chars: Vec<u8> = "abcd".encode_utf16().flat_map(u16::to_le_bytes).collect();
let mut style = vec![];
style.extend_from_slice(&5u32.to_le_bytes());
style.extend_from_slice(&0u16.to_le_bytes());
style.extend_from_slice(&pf_bytes(0, false));
style.extend_from_slice(&2u32.to_le_bytes());
style.extend_from_slice(&cf_later_fields());
style.extend_from_slice(&3u32.to_le_bytes());
style.extend_from_slice(&cf_bytes(true, 1, 18, [0, 0, 0]));
let recs = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &chars), atom(rt::STYLE_TEXT_PROP, 0, &style)].concat();
let b = read_block(crate::record::Records::new(&recs)).unwrap();
assert_eq!(b.char_runs.len(), 2, "{:?}", b.char_runs);
let (n, cf) = &b.char_runs[1];
assert_eq!((*n, cf.bold, cf.font, cf.size), (3, Some(true), Some(1), Some(18)));
}
#[test]
fn styles_inherit_from_level_one_and_the_base_type() {
let mut s = StyleSheet { types: vec![None; 9], ..Default::default() };
let lvl = |size: u16, align: u16| (Pf { align: Some(align), ..Default::default() }, Cf { size: Some(size), ..Default::default() });
s.types[ty::BODY as usize] = Some(LevelStyles { levels: vec![lvl(32, 0), (Pf::default(), Cf { size: Some(28), ..Default::default() })] });
s.types[ty::CENTER_BODY as usize] = Some(LevelStyles { levels: vec![(Pf { align: Some(1), ..Default::default() }, Cf::default())] });
let (pf, cf) = s.resolve(ty::CENTER_BODY, 1);
assert_eq!(cf.size, Some(28));
assert_eq!(pf.align, Some(1));
let (pf, cf) = s.resolve(ty::BODY, 0);
assert_eq!((pf.align, cf.size), (Some(0), Some(32)));
}
}
Binary file not shown.
+19 -4
View File
@@ -26,10 +26,14 @@ const BUILTIN_FORMATS: [(u32, &str); 36] = [
(20, "h:mm"),
(21, "h:mm:ss"),
(22, "m/d/yyyy h:mm"),
(37, "#,##0 ;(#,##0)"),
(38, "#,##0 ;[Red](#,##0)"),
(39, "#,##0.00;(#,##0.00)"),
(40, "#,##0.00;[Red](#,##0.00)"),
// 37 to 40 are the codes Excel reports for these ids, not the ECMA-376 Part 1 18.8.30 text
// (`#,##0 ;(#,##0)`, `#,##0.00;(#,##0.00)` and their [Red] forms). Excel pads a positive number
// by the width of a closing parenthesis (`_)`). It writes neither a numFmt nor a FORMAT record
// for them, so these codes are what a file Excel saved means.
(37, "#,##0_);(#,##0)"),
(38, "#,##0_);[Red](#,##0)"),
(39, "#,##0.00_);(#,##0.00)"),
(40, "#,##0.00_);[Red](#,##0.00)"),
(41, "_(* #,##0_);_(* \\(#,##0\\);_(* \"-\"_);_(@_)"),
(42, "_(\"$\"* #,##0_);_(\"$\"* \\(#,##0\\);_(\"$\"* \"-\"_);_(@_)"),
(43, "_(* #,##0.00_);_(* \\(#,##0.00\\);_(* \"-\"??_);_(@_)"),
@@ -86,6 +90,17 @@ mod tests {
assert_eq!(builtin_format_id("yyyy"), None);
}
#[test]
fn formats_37_to_40_are_the_codes_excel_reports() {
let codes = ["#,##0_);(#,##0)", "#,##0_);[Red](#,##0)", "#,##0.00_);(#,##0.00)", "#,##0.00_);[Red](#,##0.00)"];
for (id, code) in (37..=40).zip(codes) {
assert_eq!(builtin_format(id), Some(code), "{id}");
assert_eq!(builtin_format_id(code), Some(id), "{id}");
}
// The 18.8.30 text is not a built-in, so it is written as a custom format.
assert_eq!(builtin_format_id("#,##0.00;(#,##0.00)"), None);
}
#[test]
fn the_palette_repeats_its_eight_fixed_colours() {
assert_eq!(DEFAULT_PALETTE.get(..8), DEFAULT_PALETTE.get(8..16));
+7 -2
View File
@@ -80,8 +80,13 @@ rav1e = { version = "0.8", default-features = false, optional = true }
[dev-dependencies]
craft-media-testkit = { workspace = true }
# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test, and the VMD demuxer for the VMD decoder's.
craft-media = { workspace = true, features = ["avi", "vmd"] }
# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test; the MP4, MPEG-TS and AVI
# demuxers, for the track decoder's tests; the VMD demuxer, for the VMD decoder's.
craft-media = { workspace = true, features = ["avi", "isobmff", "mpegts", "vmd"] }
# Built with any decoder feature; each codec's tests need its own.
[[test]]
name = "track"
[[test]]
name = "vmd"
+28
View File
@@ -55,3 +55,31 @@ comes with its codec's feature):
The constructors check that every plane's buffer, stride and size fit the frame, so a picture
with inconsistent fields is an error, not an out-of-bounds read.
## Decoding a track
`TrackDecoder` is the counterpart of `craft_audio::TrackDecoder` for an app with its own demuxer.
It picks the decoder from a track's `CodecParams`, takes packets in decode order with their
timestamps, and returns `VideoFrame`s in display order. `flush` returns the frames still held at
the end of the stream, and `reset` prepares for decoding from another key frame after a seek. It
is built with any of the decoder features below and decodes the codecs whose feature is on.
| Codec | Feature | `extradata` |
|---|---|---|
| H.264 | `h264-decode` | an `avcC` record (length-prefixed packets), Annex B parameter sets, or empty (Annex B packets) |
| HEVC | `hevc-decode` | an `hvcC` record (length-prefixed packets), Annex B parameter sets, or empty (Annex B packets) |
| VP9 | `vp9-decode` | ignored |
| AV1 | `av1-decode` | an `av1C` record, or empty |
| MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty |
Configuration that holds picture data (a slice, a frame OBU, an MPEG-2 picture) is refused.
Errors are `VideoError`: `Unsupported`, `Malformed`, or a picture that did not convert.
When a picture does not convert, the frames finished with it are kept and the next call returns
them first. When the codec itself fails, the pictures it had finished are up to the codec:
- H.264 keeps them for later calls, also when the error comes at `flush`.
- HEVC does too, but only its newest 32 while calls keep failing, which bounds its memory.
- VP9 keeps those of earlier packets.
- MPEG-2 returns them with the call, unless the packet made too many pictures.
- AV1 drops those the failing `decode` or `flush` had finished.
+1 -1
View File
@@ -5,7 +5,7 @@
#![allow(clippy::needless_range_loop, clippy::type_complexity)]
mod bits;
pub(crate) mod bits;
mod cdef;
mod cdf;
mod decoder;
+73
View File
@@ -0,0 +1,73 @@
//! [`VideoError`], the error of the codec-agnostic layer ([`crate::TrackDecoder`]).
use crate::frame::FrameError;
/// Errors from the codec-agnostic layer.
///
/// Codec errors convert into it, so code mixing [`crate::TrackDecoder`] with the codec modules can
/// use `?` throughout: a codec's "unsupported" stays [`VideoError::Unsupported`], anything else in
/// the input is [`VideoError::Malformed`]. The message starts with the codec's name.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum VideoError {
/// The codec, or a feature of the stream, is valid but not supported (or its decoder is not
/// in this build).
#[error("unsupported video: {0}")]
Unsupported(String),
/// The input is corrupt or not what it claims to be.
#[error("malformed video: {0}")]
Malformed(String),
/// A decoded picture did not convert into a [`crate::frame::VideoFrame`].
#[error(transparent)]
Frame(#[from] FrameError),
}
#[cfg(feature = "h264-decode")]
impl From<crate::h264::decode::Error> for VideoError {
fn from(e: crate::h264::decode::Error) -> Self {
match e {
crate::h264::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("H.264: {e}")),
_ => VideoError::Malformed(format!("H.264: {e}")),
}
}
}
#[cfg(feature = "hevc-decode")]
impl From<crate::hevc::decode::Error> for VideoError {
fn from(e: crate::hevc::decode::Error) -> Self {
match e {
crate::hevc::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("HEVC: {e}")),
_ => VideoError::Malformed(format!("HEVC: {e}")),
}
}
}
#[cfg(feature = "vp9-decode")]
impl From<crate::vp9::decode::Error> for VideoError {
fn from(e: crate::vp9::decode::Error) -> Self {
match e {
crate::vp9::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("VP9: {e}")),
_ => VideoError::Malformed(format!("VP9: {e}")),
}
}
}
#[cfg(feature = "av1-decode")]
impl From<crate::av1::decode::Error> for VideoError {
fn from(e: crate::av1::decode::Error) -> Self {
match e {
crate::av1::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("AV1: {e}")),
_ => VideoError::Malformed(format!("AV1: {e}")),
}
}
}
#[cfg(feature = "mpeg2-decode")]
impl From<crate::mpeg2::Error> for VideoError {
fn from(e: crate::mpeg2::Error) -> Self {
match e {
crate::mpeg2::Error::Unsupported(_) => VideoError::Unsupported(format!("MPEG-2: {e}")),
crate::mpeg2::Error::Invalid(_) => VideoError::Malformed(format!("MPEG-2: {e}")),
}
}
}
+11
View File
@@ -28,12 +28,23 @@
//! Each decoder returns its own picture type. [`frame::VideoFrame`] is the codec-agnostic form
//! they all convert into (`VideoFrame::try_from`).
//!
//! `TrackDecoder` picks the decoder for a track from its `craft_media::CodecParams` and returns
//! `VideoFrame`s, for H.264, HEVC, VP9, AV1 and MPEG-2 (built with any of their decoder features).
//!
//! Containers and bit-level I/O are in `craft-media`; the codecs here share its `bitstream`
//! module and describe their streams with `craft_media::CodecParams`.
pub mod budget;
mod error;
pub mod frame;
pub use error::VideoError;
#[cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))]
mod track;
#[cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))]
pub use track::TrackDecoder;
#[cfg(any(feature = "apv-decode", feature = "apv-encode"))]
pub mod apv;
+413
View File
@@ -0,0 +1,413 @@
//! [`TrackDecoder`]: one video track's packets in, [`VideoFrame`]s out, whatever the codec. The
//! counterpart of `craft_audio::TrackDecoder`, for an app with its own demuxer.
#[cfg(feature = "av1-decode")]
use crate::av1;
use crate::error::VideoError;
use crate::frame::{FrameError, VideoFrame};
#[cfg(feature = "h264-decode")]
use crate::h264;
#[cfg(feature = "hevc-decode")]
use crate::hevc;
#[cfg(feature = "mpeg2-decode")]
use crate::mpeg2;
#[cfg(feature = "vp9-decode")]
use crate::vp9;
use craft_media::{CodecId, CodecParams};
/// The codec-specific decoder behind a [`TrackDecoder`].
enum Inner {
/// The decoder, and the `avcC` record or Annex B parameter sets that [`TrackDecoder::reset`]
/// applies again (the decoder's own reset forgets them).
#[cfg(feature = "h264-decode")]
H264 { dec: Box<h264::decode::Decoder>, config: Vec<u8> },
/// The decoder, and the `hvcC` record or Annex B parameter sets a reset rebuilds it from.
#[cfg(feature = "hevc-decode")]
Hevc { dec: Box<hevc::decode::Decoder>, config: Vec<u8> },
#[cfg(feature = "vp9-decode")]
Vp9(Box<vp9::decode::Decoder>),
/// The decoder, and the `av1C` config OBUs a reset rebuilds it from.
#[cfg(feature = "av1-decode")]
Av1 { dec: Box<av1::decode::Decoder>, config_obus: Vec<u8> },
#[cfg(feature = "mpeg2-decode")]
Mpeg2(Box<mpeg2::Decoder>),
}
/// A decoder for one video track, whatever its codec: built from the track's [`CodecParams`],
/// it takes the track's packets in decode order and returns [`VideoFrame`]s in display order.
///
/// | Codec | Feature | `extradata` |
/// |---|---|---|
/// | H.264 | `h264-decode` | an `avcC` record, Annex B parameter sets, or empty |
/// | HEVC | `hevc-decode` | an `hvcC` record, Annex B parameter sets, or empty |
/// | VP9 | `vp9-decode` | ignored (the frame headers repeat the `vpcC` values) |
/// | AV1 | `av1-decode` | an `av1C` record, or empty |
/// | MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty |
///
/// With an `avcC` or `hvcC` record, packets are length-prefixed NAL units, as MP4 and Matroska
/// store them. Otherwise they are Annex B, as MPEG-TS and AVI store them, and the parameter sets
/// may come in the packets themselves. The configuration must not hold picture data: an `avcC`
/// or `hvcC` record holds parameter sets (and SEI for `hvcC`), Annex B `extradata` holds
/// parameter sets, SEI and access unit delimiters, `av1C` config OBUs are sequence headers and
/// metadata, and MPEG-2 `extradata` holds sequence headers, their extensions, user data and GOP
/// headers.
///
/// Other codecs are [`VideoError::Unsupported`], as is a codec whose decoder feature is off.
///
/// A packet carries its presentation timestamp, in any unit; each frame returns with the timestamp
/// of the packet that coded it, through reordering ([`VideoFrame::pts`]).
///
/// ```no_run
/// # fn run(params: &craft_media::CodecParams, packets: &[(Vec<u8>, i64)]) -> Result<(), craft_video::VideoError> {
/// use craft_video::TrackDecoder;
///
/// let mut dec = TrackDecoder::new(params)?;
/// for (packet, pts) in packets {
/// for frame in dec.decode(packet, *pts)? {
/// println!("{}x{} at {:?}", frame.width(), frame.height(), frame.pts);
/// }
/// }
/// for frame in dec.flush()? {
/// let _ = frame;
/// }
/// # Ok(()) }
/// ```
pub struct TrackDecoder {
inner: Inner,
codec: CodecId,
/// Frames finished by a call that then failed, which the next call returns first.
held: Vec<VideoFrame>,
}
impl std::fmt::Debug for TrackDecoder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TrackDecoder").field("codec", &self.codec).field("held", &self.held.len()).finish_non_exhaustive()
}
}
impl TrackDecoder {
/// A decoder for the track `params` describes. Only `codec` and `extradata` are read; the
/// picture size and format come from the stream.
///
/// Configuration that the codec refuses, or that holds picture data, is
/// [`VideoError::Malformed`].
pub fn new(params: &CodecParams) -> Result<TrackDecoder, VideoError> {
Ok(TrackDecoder { inner: Inner::new(params.codec, &params.extradata)?, codec: params.codec, held: Vec::new() })
}
/// The track's codec, as `params` gave it.
pub fn codec(&self) -> CodecId {
self.codec
}
/// Decode one packet (an access unit, a VP9 frame or superframe, an AV1 temporal unit) with
/// its presentation timestamp. Returns the frames that became ready for display, in display
/// order; a decoder that reorders or decodes on worker threads returns a packet's frame from a
/// later call or from [`TrackDecoder::flush`].
///
/// When a call fails because a picture does not convert, the frames finished with it are
/// kept: the next call returns them first. When the codec itself fails, the pictures it had
/// finished are up to the codec. H.264 keeps them for later calls. HEVC does too, but only
/// its newest 32 while calls keep failing, which bounds its memory. VP9 keeps those of earlier
/// packets. MPEG-2 returns them with the call, unless the packet made too many pictures. AV1
/// drops those the failing call had finished.
///
/// Decoding can go on with the next packet; a decoder that lost its references waits for the
/// next random access point or conceals, as the codec does.
pub fn decode(&mut self, packet: &[u8], pts: i64) -> Result<Vec<VideoFrame>, VideoError> {
match &mut self.inner {
#[cfg(feature = "h264-decode")]
Inner::H264 { dec, .. } => {
let pics = dec.decode(packet, pts)?;
self.output(pics, None)
}
#[cfg(feature = "hevc-decode")]
Inner::Hevc { dec, .. } => {
let pics = dec.decode(packet, pts)?;
self.output(pics, None)
}
#[cfg(feature = "vp9-decode")]
Inner::Vp9(dec) => {
let pics = dec.decode(packet, pts)?;
self.output(pics, None)
}
#[cfg(feature = "av1-decode")]
Inner::Av1 { dec, .. } => {
let pics = dec.decode_pts(packet, pts)?;
self.output(pics, None)
}
#[cfg(feature = "mpeg2-decode")]
Inner::Mpeg2(dec) => {
let pics = dec.decode(packet, pts)?;
self.output(pics, None)
}
}
}
/// End of stream: every frame the decoder still holds, in display order.
///
/// A decoding error found while finishing them is returned instead; the H.264 and HEVC frames
/// are then kept for the next call, while the AV1 decoder drops its own.
pub fn flush(&mut self) -> Result<Vec<VideoFrame>, VideoError> {
match &mut self.inner {
#[cfg(feature = "h264-decode")]
Inner::H264 { dec, .. } => {
let pics = dec.flush();
let err = dec.take_error().map(VideoError::from);
self.output(pics, err)
}
#[cfg(feature = "hevc-decode")]
Inner::Hevc { dec, .. } => {
let pics = dec.flush();
let err = dec.take_error().map(VideoError::from);
self.output(pics, err)
}
#[cfg(feature = "vp9-decode")]
Inner::Vp9(dec) => {
let pics = dec.flush();
self.output(pics, None)
}
#[cfg(feature = "av1-decode")]
Inner::Av1 { dec, .. } => {
let pics = dec.flush_result()?;
self.output(pics, None)
}
#[cfg(feature = "mpeg2-decode")]
Inner::Mpeg2(dec) => {
let pics = dec.flush();
self.output(pics, None)
}
}
}
/// Forget the pictures and references, and the frames kept from a failed call, before decoding
/// from another random access point (after a seek). The track's configuration is kept: H.264
/// and HEVC parameter sets from `extradata`, the AV1 sequence header from `av1C`, and the
/// MPEG-2 sequence; parameter sets that came in packets are forgotten (MPEG-2 keeps its
/// latest sequence header).
///
/// An error is the configuration failing to apply again, which it did not when the decoder was
/// built.
pub fn reset(&mut self) -> Result<(), VideoError> {
self.held.clear();
match &mut self.inner {
#[cfg(feature = "h264-decode")]
Inner::H264 { dec, config } => {
dec.reset();
configure_h264(dec, config)
}
#[cfg(feature = "hevc-decode")]
Inner::Hevc { dec, config } => {
// The HEVC decoder has no reset of its own: a new one starts from nothing.
let mut fresh = Box::new(hevc::decode::Decoder::new());
configure_hevc(&mut fresh, config)?;
*dec = fresh;
Ok(())
}
#[cfg(feature = "vp9-decode")]
Inner::Vp9(dec) => {
dec.reset();
Ok(())
}
#[cfg(feature = "av1-decode")]
Inner::Av1 { dec, config_obus } => {
// The AV1 decoder has no reset of its own: a new one starts from nothing.
let mut fresh = Box::new(av1::decode::Decoder::new());
configure_av1(&mut fresh, config_obus)?;
*dec = fresh;
Ok(())
}
#[cfg(feature = "mpeg2-decode")]
Inner::Mpeg2(dec) => {
dec.reset();
Ok(())
}
}
}
/// The frames kept from a failed call, then `pics` converted. On `err`, or on a picture that
/// does not convert, the frames are kept for the next call and the (first) error returned.
fn output<P>(&mut self, pics: Vec<P>, err: Option<VideoError>) -> Result<Vec<VideoFrame>, VideoError>
where
VideoFrame: TryFrom<P, Error = FrameError>,
{
let mut frames = std::mem::take(&mut self.held);
frames.reserve(pics.len());
let mut err = err;
for pic in pics {
match VideoFrame::try_from(pic) {
Ok(frame) => frames.push(frame),
Err(e) => {
err.get_or_insert(e.into());
}
}
}
match err {
None => Ok(frames),
Some(e) => {
self.held = frames;
Err(e)
}
}
}
}
impl Inner {
fn new(codec: CodecId, extradata: &[u8]) -> Result<Inner, VideoError> {
#[cfg(not(any(feature = "h264-decode", feature = "hevc-decode", feature = "av1-decode", feature = "mpeg2-decode")))]
let _ = extradata;
match codec {
#[cfg(feature = "h264-decode")]
CodecId::H264 => {
let mut dec = Box::new(h264::decode::Decoder::new());
configure_h264(&mut dec, extradata)?;
Ok(Inner::H264 { dec, config: extradata.to_vec() })
}
#[cfg(feature = "hevc-decode")]
CodecId::Hevc => {
let mut dec = Box::new(hevc::decode::Decoder::new());
configure_hevc(&mut dec, extradata)?;
Ok(Inner::Hevc { dec, config: extradata.to_vec() })
}
#[cfg(feature = "vp9-decode")]
CodecId::Vp9 => Ok(Inner::Vp9(Box::default())),
#[cfg(feature = "av1-decode")]
CodecId::Av1 => {
let config_obus = av1c_config_obus(extradata)?.to_vec();
let mut dec = Box::new(av1::decode::Decoder::new());
configure_av1(&mut dec, &config_obus)?;
Ok(Inner::Av1 { dec, config_obus })
}
#[cfg(feature = "mpeg2-decode")]
CodecId::Mpeg2Video => {
let mut dec = Box::new(mpeg2::Decoder::new());
if !extradata.is_empty() {
check_mpeg2_config(extradata)?;
dec.decode(extradata, 0)?;
}
Ok(Inner::Mpeg2(dec))
}
other => Err(VideoError::Unsupported(format!("no {} decoder in this build", other.name()))),
}
}
}
/// Whether `extradata` is Annex B (starts with a start code) rather than an `avcC` / `hvcC` record.
#[cfg(any(feature = "h264-decode", feature = "hevc-decode"))]
fn is_annex_b(extradata: &[u8]) -> bool {
extradata.starts_with(&[0, 0, 1]) || extradata.starts_with(&[0, 0, 0, 1])
}
/// Annex B `extradata` holds only NAL units whose type `allowed` accepts (`codec` names it in the
/// error).
#[cfg(any(feature = "h264-decode", feature = "hevc-decode"))]
fn check_annex_b(codec: &str, extradata: &[u8], nal_type: fn(u8) -> u8, allowed: &[u8]) -> Result<(), VideoError> {
for nal in craft_media::bitstream::annexb_nals(extradata) {
let t = nal.first().map_or(u8::MAX, |&b| nal_type(b));
if !allowed.contains(&t) {
return Err(VideoError::Malformed(format!("{codec}: configuration holds NAL unit type {t}, not a parameter set")));
}
}
Ok(())
}
/// H.264 NAL unit types Annex B `extradata` may hold: SEI, SPS, PPS, access unit delimiter, SPS
/// extension and subset SPS.
#[cfg(feature = "h264-decode")]
const H264_CONFIG_NALS: [u8; 6] = [6, 7, 8, 9, 13, 15];
/// HEVC NAL unit types Annex B `extradata` may hold: VPS, SPS, PPS, access unit delimiter, prefix
/// and suffix SEI.
#[cfg(feature = "hevc-decode")]
const HEVC_CONFIG_NALS: [u8; 6] = [32, 33, 34, 35, 39, 40];
/// Apply H.264 `extradata`: an `avcC` record, Annex B parameter sets, or nothing.
#[cfg(feature = "h264-decode")]
fn configure_h264(dec: &mut h264::decode::Decoder, extradata: &[u8]) -> Result<(), VideoError> {
if extradata.is_empty() {
Ok(())
} else if is_annex_b(extradata) {
check_annex_b("H.264", extradata, |b| b & 0x1f, &H264_CONFIG_NALS)?;
dec.decode(extradata, 0)?;
Ok(())
} else {
Ok(dec.configure_avcc(extradata)?)
}
}
/// Apply HEVC `extradata`: an `hvcC` record, Annex B parameter sets, or nothing.
#[cfg(feature = "hevc-decode")]
fn configure_hevc(dec: &mut hevc::decode::Decoder, extradata: &[u8]) -> Result<(), VideoError> {
if extradata.is_empty() {
Ok(())
} else if is_annex_b(extradata) {
check_annex_b("HEVC", extradata, |b| (b >> 1) & 0x3f, &HEVC_CONFIG_NALS)?;
dec.decode(extradata, 0)?;
Ok(())
} else {
Ok(dec.configure_hvcc(extradata)?)
}
}
/// MPEG-2 start codes `extradata` may hold: user data, sequence header, extension and GOP header.
#[cfg(feature = "mpeg2-decode")]
const MPEG2_CONFIG_CODES: [u8; 4] = [0xb2, 0xb3, 0xb5, 0xb8];
/// MPEG-2 `extradata` holds no picture: every start code in it is one of [`MPEG2_CONFIG_CODES`].
#[cfg(feature = "mpeg2-decode")]
fn check_mpeg2_config(extradata: &[u8]) -> Result<(), VideoError> {
for w in extradata.windows(4) {
if let [0, 0, 1, code] = *w
&& !MPEG2_CONFIG_CODES.contains(&code)
{
return Err(VideoError::Malformed(format!("MPEG-2: configuration holds start code {code:#04x}, not a sequence header")));
}
}
Ok(())
}
/// The config OBUs of an `av1C` record (empty for empty `extradata`), once they are checked to
/// hold only sequence headers and metadata.
#[cfg(feature = "av1-decode")]
fn av1c_config_obus(extradata: &[u8]) -> Result<&[u8], VideoError> {
const SEQUENCE_HEADER: u8 = 1;
const METADATA: u8 = 5;
if extradata.is_empty() {
return Ok(&[]);
}
// marker (1) and version (1), then three bytes of profile, level and chroma fields
let obus = match extradata {
[0x81, _, _, _, obus @ ..] => obus,
_ => return Err(VideoError::Malformed("AV1: configuration is not an av1C record (version 1)".into())),
};
let mut rest = obus;
while let Some(&header) = rest.first() {
let obu_type = (header >> 3) & 0xf;
if obu_type != SEQUENCE_HEADER && obu_type != METADATA {
return Err(VideoError::Malformed(format!("AV1: av1C holds OBU type {obu_type}, not a sequence header or metadata")));
}
// obu_extension_flag adds a byte; without obu_has_size_field the OBU runs to the end
let start = 1 + usize::from(header & 4 != 0);
let body = rest.get(start..).ok_or_else(|| VideoError::Malformed("AV1: av1C OBU header truncated".into()))?;
rest = if header & 2 != 0 {
let (size, n) = av1::decode::bits::leb128(body)?;
let end = usize::try_from(size).ok().and_then(|s| s.checked_add(n));
end.and_then(|end| body.get(end..)).ok_or_else(|| VideoError::Malformed("AV1: av1C OBU truncated".into()))?
} else {
&[]
};
}
Ok(obus)
}
/// Apply `av1C` config OBUs (sequence headers and metadata, checked by [`av1c_config_obus`]).
#[cfg(feature = "av1-decode")]
fn configure_av1(dec: &mut av1::decode::Decoder, config_obus: &[u8]) -> Result<(), VideoError> {
if !config_obus.is_empty() {
dec.decode_pts(config_obus, 0)?;
}
Ok(())
}
#[cfg(test)]
mod tests;
+266
View File
@@ -0,0 +1,266 @@
//! Unit tests of the track decoder: codec selection, configuration checks and the frames kept
//! from a failed call. Decoding real streams is in `tests/track`.
use super::*;
fn params(codec: CodecId, extradata: &[u8]) -> CodecParams {
CodecParams::new(codec).with_extradata(extradata.to_vec())
}
fn new_err(codec: CodecId, extradata: &[u8]) -> VideoError {
match TrackDecoder::new(&params(codec, extradata)) {
Ok(_) => panic!("{codec:?} with extradata {extradata:02x?} was accepted"),
Err(e) => e,
}
}
#[test]
fn a_codec_without_a_decoder_is_unsupported() {
let off = [
CodecId::Theora,
CodecId::Aac,
CodecId::Unknown,
#[cfg(not(feature = "h264-decode"))]
CodecId::H264,
#[cfg(not(feature = "hevc-decode"))]
CodecId::Hevc,
#[cfg(not(feature = "vp9-decode"))]
CodecId::Vp9,
#[cfg(not(feature = "av1-decode"))]
CodecId::Av1,
#[cfg(not(feature = "mpeg2-decode"))]
CodecId::Mpeg2Video,
];
for codec in off {
let err = new_err(codec, &[]);
assert!(matches!(err, VideoError::Unsupported(_)), "{codec:?}: {err}");
assert!(err.to_string().contains(codec.name()), "{err}");
}
}
#[test]
fn every_built_decoder_starts_without_configuration() {
let on = [
#[cfg(feature = "h264-decode")]
CodecId::H264,
#[cfg(feature = "hevc-decode")]
CodecId::Hevc,
#[cfg(feature = "vp9-decode")]
CodecId::Vp9,
#[cfg(feature = "av1-decode")]
CodecId::Av1,
#[cfg(feature = "mpeg2-decode")]
CodecId::Mpeg2Video,
];
for codec in on {
let mut dec = TrackDecoder::new(&params(codec, &[])).unwrap();
assert_eq!(dec.codec(), codec);
assert!(dec.flush().unwrap().is_empty(), "{codec:?}");
dec.reset().unwrap();
assert!(dec.decode(&[], 0).unwrap_or_default().is_empty(), "{codec:?}");
}
}
#[test]
fn track_decoder_is_send() {
fn send<T: Send>() {}
send::<TrackDecoder>();
}
/// An Annex B configuration that holds a slice would start a picture: it is refused before any
/// NAL unit reaches the decoder (which would report the slice's missing parameter set instead).
#[cfg(feature = "h264-decode")]
#[test]
fn h264_annex_b_configuration_with_a_slice_is_refused() {
let err = new_err(CodecId::H264, &[0, 0, 0, 1, 0x65, 0x88, 0x84, 0x00]);
assert!(matches!(err, VideoError::Malformed(_)), "{err}");
assert!(err.to_string().contains("NAL unit type 5"), "{err}");
}
#[cfg(feature = "hevc-decode")]
#[test]
fn hevc_annex_b_configuration_with_a_slice_is_refused() {
// IDR_W_RADL (19): (19 << 1) = 0x26
let err = new_err(CodecId::Hevc, &[0, 0, 1, 0x26, 0x01, 0xaf, 0x00]);
assert!(matches!(err, VideoError::Malformed(_)), "{err}");
assert!(err.to_string().contains("NAL unit type 19"), "{err}");
}
/// A picture after a valid sequence header is refused, not decoded and then dropped.
#[cfg(feature = "mpeg2-decode")]
#[test]
fn mpeg2_configuration_with_a_picture_is_refused() {
// 32x32, 4:3, 25 fps
let header = [0, 0, 1, 0xb3, 0x02, 0x00, 0x20, 0x23, 0xff, 0xff, 0xe0, 0x18];
assert!(TrackDecoder::new(&params(CodecId::Mpeg2Video, &header)).is_ok());
// a picture header (I picture) and the start of its first slice
let picture = [0, 0, 1, 0x00, 0x00, 0x0f, 0xff, 0xf8, 0, 0, 1, 0x01, 0x12, 0x34];
let err = new_err(CodecId::Mpeg2Video, &[&header[..], &picture].concat());
assert!(matches!(err, VideoError::Malformed(_)), "{err}");
assert!(err.to_string().contains("start code 0x00"), "{err}");
}
/// A record that is neither Annex B nor version 1 is the codec's own error.
#[cfg(feature = "h264-decode")]
#[test]
fn h264_configuration_that_is_not_avcc_is_refused() {
let err = new_err(CodecId::H264, &[2, 0x42, 0, 0x1e, 0xff, 0xe0, 0]);
assert!(matches!(err, VideoError::Malformed(_)), "{err}");
assert!(err.to_string().contains("avcC"), "{err}");
}
#[cfg(feature = "av1-decode")]
mod av1c {
use super::*;
const HEADER: [u8; 4] = [0x81, 0x00, 0x0c, 0x00];
fn with_obus(obus: &[u8]) -> Vec<u8> {
[&HEADER[..], obus].concat()
}
#[test]
fn empty_and_header_only_records_hold_no_obus() {
assert_eq!(av1c_config_obus(&[]).unwrap(), &[] as &[u8]);
assert_eq!(av1c_config_obus(&HEADER).unwrap(), &[] as &[u8]);
}
#[test]
fn sequence_headers_and_metadata_pass() {
// a sequence header (size 2), one with an extension byte (size 0), metadata (size 1), and
// a sequence header without a size field that runs to the end
let obus = [0x0a, 2, 0xaa, 0xbb, 0x0e, 0x00, 0, 0x2a, 1, 0xcc, 0x08, 0xdd, 0xee];
assert_eq!(av1c_config_obus(&with_obus(&obus)).unwrap(), &obus);
}
#[test]
fn a_record_that_is_not_av1c_version_1_is_refused() {
for bad in [&[0x81, 0, 0][..], &[0x80, 0, 0, 0], &[0x82, 0, 0, 0], &[0x0a, 0, 0, 0, 0]] {
let err = av1c_config_obus(bad).unwrap_err();
assert!(err.to_string().contains("not an av1C record"), "{bad:02x?}: {err}");
}
}
#[test]
fn a_frame_or_temporal_delimiter_is_refused() {
// temporal delimiter (2), frame header (3), tile group (4), frame (6), after a valid OBU
for t in [2u8, 3, 4, 6] {
let obus = [0x0a, 0, (t << 3) | 2, 0];
let err = av1c_config_obus(&with_obus(&obus)).unwrap_err();
assert!(err.to_string().contains(&format!("OBU type {t}")), "{t}: {err}");
}
assert!(matches!(new_err(CodecId::Av1, &with_obus(&[0x32, 0])), VideoError::Malformed(_)));
}
#[test]
fn truncated_obus_are_refused() {
for obus in [&[0x0a, 5, 1, 2][..], &[0x0a, 0x80], &[0x0a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], &[0x0e]] {
let err = av1c_config_obus(&with_obus(obus)).unwrap_err();
assert!(matches!(err, VideoError::Malformed(_)), "{obus:02x?}: {err}");
}
}
#[test]
fn hostile_records_do_not_panic() {
let seed = with_obus(&[0x0a, 2, 0xaa, 0xbb, 0x2a, 1, 0xcc]);
craft_media_testkit::hostile::hammer("av1C config OBUs", &seed, 2000, |data| {
let _ = av1c_config_obus(data);
});
}
}
/// Configuration bytes of every codec, damaged, never panic the decoder that applies them.
#[test]
fn hostile_configuration_does_not_panic() {
let seeds: &[(CodecId, &[u8])] = &[
#[cfg(feature = "h264-decode")]
(CodecId::H264, &[1, 0x42, 0xc0, 0x1e, 0xff, 0xe1, 0x00, 0x04, 0x67, 0x42, 0xc0, 0x1e, 0x01, 0x00, 0x02, 0x68, 0xce]),
#[cfg(feature = "h264-decode")]
(CodecId::H264, &[0, 0, 0, 1, 0x67, 0x42, 0xc0, 0x1e, 0, 0, 1, 0x68, 0xce]),
#[cfg(feature = "hevc-decode")]
(CodecId::Hevc, &[0, 0, 0, 1, 0x40, 0x01, 0x0c, 0, 0, 1, 0x42, 0x01, 0x01, 0, 0, 1, 0x44, 0x01, 0xc1]),
#[cfg(feature = "av1-decode")]
(CodecId::Av1, &[0x81, 0x00, 0x0c, 0x00, 0x0a, 0x0b, 0x00, 0x00, 0x00, 0x24, 0xc4, 0xff, 0xdf, 0x00, 0x68, 0x02, 0x10]),
#[cfg(feature = "mpeg2-decode")]
(CodecId::Mpeg2Video, &[0, 0, 1, 0xb3, 0x02, 0x00, 0x20, 0x13, 0xff, 0xff, 0xe0, 0x18, 0, 0, 1, 0xb5, 0x14, 0x8a, 0x00, 0x01, 0x00, 0x00]),
];
for &(codec, seed) in seeds {
craft_media_testkit::hostile::hammer(codec.name(), seed, 300, move |data| {
if let Ok(mut dec) = TrackDecoder::new(&params(codec, data)) {
let _ = dec.reset();
}
});
}
}
#[cfg(feature = "h264-decode")]
mod held {
use super::*;
/// A 4x2 picture with timestamp `pts`; `y_len` other than 8 makes it fail to convert.
fn picture(y_len: usize, pts: i64) -> h264::decode::Picture {
h264::decode::Picture {
width: 4,
height: 2,
chroma_width: 2,
chroma_height: 1,
y: vec![16; y_len],
u: vec![128; 2],
v: vec![128; 2],
y_stride: 4,
uv_stride: 2,
pts,
poc: 0,
key: true,
color: h264::decode::ColorInfo { full_range: false, primaries: 1, transfer: 1, matrix: 1 },
sar: (0, 0),
draft: false,
}
}
fn decoder() -> TrackDecoder {
TrackDecoder::new(&params(CodecId::H264, &[])).unwrap()
}
fn pts(frames: &[VideoFrame]) -> Vec<Option<i64>> {
frames.iter().map(|f| f.pts).collect()
}
/// A picture that does not convert fails the call; the others come with the next call, ahead
/// of its own frames and in order.
#[test]
fn frames_around_a_picture_that_does_not_convert_come_next() {
let mut dec = decoder();
let err = dec.output(vec![picture(8, 1), picture(3, 2), picture(8, 3)], None).unwrap_err();
assert!(matches!(err, VideoError::Frame(FrameError::Plane(_))), "{err}");
assert_eq!(pts(&dec.output(vec![picture(8, 4)], None).unwrap()), [Some(1), Some(3), Some(4)]);
assert!(dec.output(Vec::<h264::decode::Picture>::new(), None).unwrap().is_empty());
}
/// An error reported with the pictures (a flush whose decoding job failed) keeps them too.
#[test]
fn frames_finished_with_an_error_come_next() {
let mut dec = decoder();
let err = dec.output(vec![picture(8, 1)], Some(VideoError::Malformed("job".into()))).unwrap_err();
assert!(matches!(err, VideoError::Malformed(_)));
assert_eq!(pts(&dec.flush().unwrap()), [Some(1)]);
}
/// An error from the codec itself leaves the kept frames for the call after it.
#[test]
fn a_failed_packet_does_not_drop_kept_frames() {
let mut dec = decoder();
assert!(dec.output(vec![picture(8, 1), picture(0, 2)], None).is_err());
// an IDR slice without parameter sets
assert!(dec.decode(&[0, 0, 1, 0x65, 0x88, 0x84], 5).is_err());
assert_eq!(pts(&dec.decode(&[], 6).unwrap()), [Some(1)]);
}
#[test]
fn reset_drops_kept_frames() {
let mut dec = decoder();
assert!(dec.output(vec![picture(8, 1), picture(0, 2)], None).is_err());
dec.reset().unwrap();
assert!(dec.flush().unwrap().is_empty());
}
}
+72
View File
@@ -0,0 +1,72 @@
//! AV1 in MP4 (an `av1C` record whose config OBUs hold the sequence header).
use crate::common;
use craft_media::CodecId;
/// libaom when ffmpeg has it, else SVT-AV1: a fixture name and the encoder arguments.
fn encoder() -> Option<(&'static str, &'static [&'static str])> {
if common::has_encoder("libaom-av1") {
Some(("av1_aom", &["-c:v", "libaom-av1", "-cpu-used", "8", "-b:v", "300k", "-g", "12", "-pix_fmt", "yuv420p"]))
} else if common::has_encoder("libsvtav1") {
Some(("av1_svt", &["-c:v", "libsvtav1", "-preset", "12", "-g", "12", "-pix_fmt", "yuv420p"]))
} else {
craft_media_testkit::skip("ffmpeg has neither libaom-av1 nor libsvtav1")
}
}
fn fixture() -> Option<(common::Track, common::Fixture)> {
let (name, args) = encoder()?;
let f = common::fixture(name, "mp4", args, "yuv420p")?;
let track = common::mp4(&f.file);
assert_eq!(track.params.codec, CodecId::Av1);
Some((track, f))
}
/// The OBUs of a packet as (type, bytes); every OBU has a size field, as MP4 stores them.
fn obus(data: &[u8]) -> Vec<(u8, &[u8])> {
let mut out = Vec::new();
let mut pos = 0;
while pos < data.len() {
let header = data[pos];
assert!(header & 2 != 0, "an OBU without a size field");
let mut p = pos + 1 + usize::from(header & 4 != 0);
let mut size = 0usize;
for i in 0.. {
let b = data[p];
p += 1;
size |= usize::from(b & 0x7f) << (7 * i);
if b & 0x80 == 0 {
break;
}
}
out.push(((header >> 3) & 0xf, &data[pos..p + size]));
pos = p + size;
}
out
}
#[test]
fn mp4_av1c() {
let Some((track, f)) = fixture() else { return };
common::check_track(&track, &f);
}
/// With every sequence header taken out of the packets, the one in `av1C` is what decodes them.
///
/// The record's config OBUs are the stream's own sequence header: SVT-AV1 writes `av1C` before it
/// encodes, with a sequence header that differs from the one it then puts in the stream.
#[test]
fn sequence_header_from_av1c() {
let Some((mut track, f)) = fixture() else { return };
let header = obus(&track.packets[0].data).into_iter().find(|o| o.0 == 1).unwrap().1.to_vec();
track.params.extradata = [&track.params.extradata[..4], &header].concat();
for p in &mut track.packets {
p.data = obus(&p.data).into_iter().filter(|o| o.0 != 1).flat_map(|o| o.1.to_vec()).collect();
}
let mut bare = track.clone();
bare.params.extradata.clear();
let mut dec = craft_video::TrackDecoder::new(&bare.params).unwrap();
let decoded = bare.packets.iter().filter_map(|p| dec.decode(&p.data, p.pts).ok()).flatten().count();
assert_eq!(decoded, 0, "the packets decode without a sequence header");
common::check_track(&track, &f);
}
+201
View File
@@ -0,0 +1,201 @@
//! Fixtures (ffmpeg encodes a short clip into a container), demuxing with craft-media, ffmpeg's
//! own decode of each fixture as the reference, and the checks every codec runs.
#![allow(dead_code)]
use craft_media::CodecParams;
use craft_video::TrackDecoder;
use craft_video::frame::{Samples, VideoFrame};
use std::path::{Path, PathBuf};
use std::process::Command;
/// Frames in every fixture.
pub const FRAMES: usize = 24;
/// One packet of a demuxed track, in decode order.
#[derive(Clone)]
pub struct Packet {
pub data: Vec<u8>,
pub pts: i64,
/// The container marks it as a random access point.
pub key: bool,
}
/// A demuxed video track.
#[derive(Clone)]
pub struct Track {
pub params: CodecParams,
pub packets: Vec<Packet>,
}
/// A fixture and ffmpeg's decode of it.
pub struct Fixture {
pub file: PathBuf,
/// Raw frames in display order, planes one after another, 16-bit samples little-endian.
pub reference: Vec<u8>,
/// How far a sample may be from the reference: 0 (bit-exact) unless a test sets it.
pub max_diff: u8,
}
/// Lowest PSNR of a frame decoded within a tolerance, as the MPEG-2 oracle tests require.
const MIN_PSNR: f64 = 58.0;
/// `name.ext` made by ffmpeg from 24 frames of a noisy test pattern at 176x144, with `args`
/// choosing the encoder, and its decode as `pix_fmt` raw video. `None` (a skip) without ffmpeg or
/// the encoder; a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`.
pub fn fixture(name: &str, ext: &str, args: &[&str], pix_fmt: &str) -> Option<Fixture> {
let ff = craft_media_testkit::ffmpeg()?;
let dir = craft_media_testkit::fixture_subdir("video-track");
let required = craft_media_testkit::oracles_required();
let file = dir.join(format!("{name}.{ext}"));
let raw = dir.join(format!("{name}.{ext}.{pix_fmt}.raw"));
craft_media_testkit::generate_and_report(name, &[file.clone(), raw.clone()], || {
if !file.exists() {
let tmp = craft_media_testkit::temp_path(&file);
let mut cmd = Command::new(&ff);
cmd.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i"])
.arg("testsrc2=size=176x144:rate=25,noise=alls=12:allf=t+u")
.args(["-frames:v", &FRAMES.to_string(), "-an"])
.args(args)
.arg(&tmp);
craft_media_testkit::run_generator(&mut cmd, &tmp, &file, required)?;
}
if !raw.exists() {
let tmp = craft_media_testkit::temp_path(&raw);
let mut cmd = Command::new(&ff);
cmd.args(["-hide_banner", "-loglevel", "error", "-y", "-i"])
.arg(&file)
.args(["-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt])
.arg(&tmp);
craft_media_testkit::run_generator(&mut cmd, &tmp, &raw, required)?;
}
Some(Fixture { reference: std::fs::read(&raw).unwrap(), file: file.clone(), max_diff: 0 })
})
}
/// Whether ffmpeg has `encoder`, without skipping.
pub fn has_encoder(encoder: &str) -> bool {
craft_media_testkit::tool("ffmpeg").is_some_and(|ff| craft_media_testkit::ffmpeg_has_encoder(&ff, encoder))
}
/// The video track of an MP4 file.
pub fn mp4(path: &Path) -> Track {
use craft_media::isobmff::{TrackKind, open};
let bytes = std::fs::read(path).unwrap();
let file = open(bytes.as_slice()).unwrap();
let t = file.track_of_kind(TrackKind::Video).unwrap();
let track = &file.tracks[t];
let packets = (track.samples.iter().enumerate())
.map(|(i, s)| Packet { data: file.read_sample(bytes.as_slice(), t, i).unwrap(), pts: s.pts, key: s.is_sync })
.collect();
Track { params: track.codec_params(), packets }
}
/// The video stream of an MPEG transport stream.
pub fn ts(path: &Path) -> Track {
use craft_media::mpegts::{Kind, open};
let bytes = std::fs::read(path).unwrap();
let file = open(bytes.as_slice()).unwrap();
let s = file.find(Kind::Video, |_| true).unwrap();
let stream = &file.streams[s];
let packets = (stream.units.iter().enumerate())
.map(|(i, u)| Packet { data: file.read_unit(bytes.as_slice(), s, i).unwrap(), pts: u.pts.unwrap(), key: u.key })
.collect();
Track { params: stream.codec_params(), packets }
}
/// The video stream of an AVI file. AVI has no timestamps: a chunk's index stands in.
pub fn avi(path: &Path) -> Track {
use craft_media::avi::{StreamKind, open};
let bytes = std::fs::read(path).unwrap();
let file = open(bytes.as_slice()).unwrap();
let s = file.streams.iter().position(|s| s.kind == StreamKind::Video).unwrap();
let stream = &file.streams[s];
let packets = (stream.chunks.iter().enumerate())
.map(|(i, c)| Packet { data: file.read_chunk(bytes.as_slice(), s, i).unwrap(), pts: i as i64, key: c.key })
.collect();
Track { params: stream.codec_params(), packets }
}
/// Decode `packets` with `dec` and flush it.
pub fn run(dec: &mut TrackDecoder, packets: &[Packet]) -> Vec<VideoFrame> {
let mut frames = Vec::new();
for (i, p) in packets.iter().enumerate() {
frames.extend(dec.decode(&p.data, p.pts).unwrap_or_else(|e| panic!("packet {i}: {e}")));
}
frames.extend(dec.flush().unwrap());
frames
}
/// Every frame of `track`, from a new decoder.
pub fn decode(track: &Track) -> Vec<VideoFrame> {
run(&mut TrackDecoder::new(&track.params).unwrap(), &track.packets)
}
/// The samples of `frame`, planes one after another, as ffmpeg's raw video has them: a byte per
/// sample up to 8 bits (whatever the storage; AV1 stores 8-bit samples in `u16`), else two bytes
/// little-endian.
pub fn frame_bytes(frame: &VideoFrame) -> Vec<u8> {
let mut out = Vec::new();
for p in frame.planes() {
for y in 0..p.height() {
match p.samples() {
Samples::U8(_) => out.extend_from_slice(p.row_u8(y).unwrap()),
Samples::U16(_) if p.bit_depth() <= 8 => out.extend(p.row_u16(y).unwrap().iter().map(|&s| u8::try_from(s).unwrap())),
Samples::U16(_) => out.extend(p.row_u16(y).unwrap().iter().flat_map(|s| s.to_le_bytes())),
}
}
}
out
}
/// `frames` are every frame of `track` in display order, each with the timestamp of the packet
/// that coded it, and their samples are ffmpeg's (within `fixture.max_diff`).
pub fn check_frames(track: &Track, frames: &[VideoFrame], fixture: &Fixture) {
let reference = &fixture.reference;
assert_eq!(frames.len(), FRAMES, "frame count");
let got: Vec<i64> = frames.iter().map(|f| f.pts.unwrap()).collect();
let mut want: Vec<i64> = track.packets.iter().map(|p| p.pts).collect();
want.sort_unstable();
assert_eq!(got, want, "timestamps in display order");
let size = reference.len() / FRAMES;
assert_eq!(size * FRAMES, reference.len(), "reference size");
for (i, (frame, want)) in frames.iter().zip(reference.chunks(size)).enumerate() {
assert_eq!((frame.width(), frame.height()), (176, 144), "frame {i} size");
let got = frame_bytes(frame);
assert_eq!(got.len(), want.len(), "frame {i} bytes");
let diff: Vec<usize> = (0..got.len()).filter(|&k| got[k] != want[k]).collect();
let max = diff.iter().map(|&k| got[k].abs_diff(want[k])).max().unwrap_or(0);
let what = format!("frame {i} (pts {:?}): {} of {} bytes differ from ffmpeg's decode, by up to {max}", frame.pts, diff.len(), got.len());
if fixture.max_diff == 0 {
assert!(diff.is_empty(), "{what}");
} else {
let sse: f64 = diff.iter().map(|&k| f64::from(got[k].abs_diff(want[k])).powi(2)).sum();
let psnr = if sse == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64.powi(2) * got.len() as f64 / sse).log10() };
assert!(max <= fixture.max_diff && psnr >= MIN_PSNR, "{what}, PSNR {psnr:.1} dB");
}
}
}
/// Decode `track`, check it against `fixture`'s reference, then reset the decoder twice: once
/// halfway through, decoding the whole track again, and once to decode from its last key packet
/// (a seek), which gives the frames of the packets from there on.
pub fn check_track(track: &Track, fixture: &Fixture) {
let frames = decode(track);
check_frames(track, &frames, fixture);
let mut dec = TrackDecoder::new(&track.params).unwrap();
let half = track.packets.len() / 2;
for p in &track.packets[..half] {
dec.decode(&p.data, p.pts).unwrap();
}
dec.reset().unwrap();
assert!(run(&mut dec, &track.packets) == frames, "decoding again after a reset");
let key = track.packets.iter().rposition(|p| p.key).unwrap();
assert!(key > 0, "the track has a second key packet");
dec.reset().unwrap();
let seek = run(&mut dec, &track.packets[key..]);
let pts: Vec<i64> = track.packets[key..].iter().map(|p| p.pts).collect();
let want: Vec<&VideoFrame> = frames.iter().filter(|f| pts.contains(&f.pts.unwrap())).collect();
assert!(seek.iter().eq(want.iter().copied()), "decoding from key packet {key} after a reset");
}
+63
View File
@@ -0,0 +1,63 @@
//! H.264 in MP4 (an `avcC` record, length-prefixed packets), MPEG-TS (Annex B, no configuration)
//! and AVI with the parameter sets in the stream header only (an Annex B configuration).
use crate::common;
use craft_media::CodecId;
use craft_video::{TrackDecoder, VideoError};
const X264: &[&str] = &["-c:v", "libx264", "-preset", "fast", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p"];
/// The NAL unit types of an Annex B packet.
fn nal_types(data: &[u8]) -> Vec<u8> {
craft_media::bitstream::annexb_nals(data).iter().filter_map(|n| n.first()).map(|b| b & 0x1f).collect()
}
/// The parameter sets are in the `avcC` record only, so decoding again after a reset needs them
/// applied again.
#[test]
fn mp4_avcc() {
let Some(f) = common::fixture("h264_avcc", "mp4", X264, "yuv420p") else { return };
let track = common::mp4(&f.file);
assert_eq!((track.params.codec, track.params.extradata.first()), (CodecId::H264, Some(&1)), "an avcC record");
common::check_track(&track, &f);
}
#[test]
fn ts_annex_b() {
let Some(f) = common::fixture("h264", "ts", X264, "yuv420p") else { return };
let track = common::ts(&f.file);
assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::H264, 0));
common::check_track(&track, &f);
}
fn global_header_avi() -> Option<(common::Track, common::Fixture)> {
let args = ["-c:v", "libx264", "-preset", "fast", "-bf", "0", "-g", "12", "-pix_fmt", "yuv420p", "-flags", "+global_header"];
let f = common::fixture("h264_global_header", "avi", &args, "yuv420p")?;
let track = common::avi(&f.file);
assert_eq!(track.params.codec, CodecId::H264);
assert_eq!(nal_types(&track.params.extradata).iter().filter(|&&t| t == 7 || t == 8).count(), 2, "an SPS and a PPS in the stream header");
for (i, p) in track.packets.iter().enumerate() {
assert!(!nal_types(&p.data).contains(&7), "chunk {i} repeats the SPS");
}
Some((track, f))
}
/// AVI written with global headers: the chunks need the parameter sets from the stream header.
#[test]
fn avi_annex_b_configuration() {
let Some((track, f)) = global_header_avi() else { return };
common::check_track(&track, &f);
}
/// Annex B configuration with the first picture's slice after the parameter sets is refused,
/// rather than decoding that picture into the reference store.
#[test]
fn annex_b_configuration_with_a_slice_is_refused() {
let Some((mut track, _)) = global_header_avi() else { return };
track.params.extradata.extend_from_slice(&track.packets[0].data);
assert!(nal_types(&track.params.extradata).contains(&5), "an IDR slice");
match TrackDecoder::new(&track.params) {
Err(VideoError::Malformed(m)) => assert!(m.contains("NAL unit type 5"), "{m}"),
other => panic!("{other:?}"),
}
}
+68
View File
@@ -0,0 +1,68 @@
//! HEVC in MP4 (an `hvcC` record, length-prefixed packets) and MPEG-TS (Annex B, no
//! configuration), 8-bit and 10-bit.
use crate::common;
use craft_media::CodecId;
/// Closed GOPs every 12 frames with B-frames, so decoding from a key packet gives every frame
/// from there on.
const X265: &[&str] = &["-c:v", "libx265", "-preset", "fast", "-x265-params", "log-level=error:keyint=12:min-keyint=12:open-gop=0:bframes=2"];
fn args(pix_fmt: &str, mp4: bool) -> Vec<&str> {
let mut a = X265.to_vec();
a.extend(["-pix_fmt", pix_fmt]);
if mp4 {
a.extend(["-tag:v", "hvc1"]);
}
a
}
/// The parameter sets are in the `hvcC` record only, so decoding again after a reset needs them
/// applied again.
#[test]
fn mp4_hvcc() {
let Some(f) = common::fixture("hevc_hvcc", "mp4", &args("yuv420p", true), "yuv420p") else { return };
let track = common::mp4(&f.file);
assert_eq!((track.params.codec, track.params.extradata.first()), (CodecId::Hevc, Some(&1)), "an hvcC record");
common::check_track(&track, &f);
}
#[test]
fn mp4_hvcc_10bit() {
let Some(f) = common::fixture("hevc_hvcc_10bit", "mp4", &args("yuv420p10le", true), "yuv420p10le") else { return };
let track = common::mp4(&f.file);
let frames = common::decode(&track);
assert!(frames.iter().all(|f| f.bit_depth() == 10));
common::check_track(&track, &f);
}
#[test]
fn ts_annex_b() {
let Some(f) = common::fixture("hevc", "ts", &args("yuv420p", false), "yuv420p") else { return };
let track = common::ts(&f.file);
assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::Hevc, 0));
common::check_track(&track, &f);
}
/// The NAL unit types of an Annex B packet.
fn nal_types(data: &[u8]) -> Vec<u8> {
craft_media::bitstream::annexb_nals(data).iter().filter_map(|n| n.first()).map(|b| (b >> 1) & 0x3f).collect()
}
/// AVI written with global headers: the chunks need the VPS, SPS and PPS from the stream header.
/// (ffmpeg writes an empty FourCC for HEVC in AVI unless it is given one.)
#[test]
fn avi_annex_b_configuration() {
// AVI has no timestamps (a chunk's index stands in), so no B-frames.
let params = "log-level=error:keyint=12:min-keyint=12:open-gop=0:bframes=0";
let a = ["-c:v", "libx265", "-preset", "fast", "-x265-params", params, "-pix_fmt", "yuv420p", "-flags", "+global_header", "-tag:v", "HEVC"];
let Some(f) = common::fixture("hevc_global_header", "avi", &a, "yuv420p") else { return };
let track = common::avi(&f.file);
assert_eq!(track.params.codec, CodecId::Hevc);
let sets = nal_types(&track.params.extradata);
assert!([32, 33, 34].iter().all(|t| sets.contains(t)), "a VPS, an SPS and a PPS in the stream header: {sets:?}");
for (i, p) in track.packets.iter().enumerate() {
assert!(!nal_types(&p.data).contains(&33), "chunk {i} repeats the SPS");
}
common::check_track(&track, &f);
}
+18
View File
@@ -0,0 +1,18 @@
//! `TrackDecoder` on real streams: ffmpeg encodes a short clip into MP4, MPEG-TS or AVI,
//! craft-media demuxes it, and the decoder's frames must be ffmpeg's decode of the file, in display
//! order, with the timestamps of the packets that coded them. Each codec also checks that a reset
//! decodes the track again and decodes from a later key packet.
#![cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))]
mod common;
#[cfg(feature = "av1-decode")]
mod av1;
#[cfg(feature = "h264-decode")]
mod h264;
#[cfg(feature = "hevc-decode")]
mod hevc;
#[cfg(feature = "mpeg2-decode")]
mod mpeg2;
#[cfg(feature = "vp9-decode")]
mod vp9;
+55
View File
@@ -0,0 +1,55 @@
//! MPEG-2 video in MPEG-TS (no configuration), and with its sequence header moved from the
//! packets into `extradata`.
use crate::common;
use craft_media::CodecId;
/// Closed GOPs every 12 frames with B-frames (ffmpeg's encoder needs scene change detection off
/// for closed GOPs).
const MPEG2: &[&str] =
&["-c:v", "mpeg2video", "-bf", "2", "-g", "12", "-flags", "+cgop", "-sc_threshold", "1000000000", "-q:v", "4", "-pix_fmt", "yuv420p"];
/// MPEG-2's IDCT is not bit-exact by definition (any IEEE 1180-accurate IDCT conforms), so the
/// frames are compared with ffmpeg's within the MPEG-2 oracle tests' tolerance.
fn fixture() -> Option<(common::Track, common::Fixture)> {
let mut f = common::fixture("mpeg2", "ts", MPEG2, "yuv420p")?;
f.max_diff = 4;
let track = common::ts(&f.file);
assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::Mpeg2Video, 0));
Some((track, f))
}
/// The byte range of the sequence header and its extensions in `data`: from the sequence header
/// start code to the next start code that is not an extension.
fn sequence_header(data: &[u8]) -> Option<std::ops::Range<usize>> {
let codes: Vec<(usize, u8)> = (0..data.len().saturating_sub(3)).filter(|&i| data[i..i + 3] == [0, 0, 1]).map(|i| (i, data[i + 3])).collect();
let k = codes.iter().position(|c| c.1 == 0xb3)?;
let end = codes[k + 1..].iter().find(|c| c.1 != 0xb5).map_or(data.len(), |c| c.0);
Some(codes[k].0..end)
}
#[test]
fn ts() {
let Some((track, f)) = fixture() else { return };
common::check_track(&track, &f);
}
/// With every sequence header taken out of the packets, the one in `extradata` is what decodes
/// them, before and after a reset.
#[test]
fn sequence_header_from_extradata() {
let Some((mut track, f)) = fixture() else { return };
let first = sequence_header(&track.packets[0].data).unwrap();
track.params.extradata = track.packets[0].data[first].to_vec();
for p in &mut track.packets {
while let Some(r) = sequence_header(&p.data) {
p.data.drain(r);
}
}
let mut bare = track.clone();
bare.params.extradata.clear();
let mut dec = craft_video::TrackDecoder::new(&bare.params).unwrap();
let decoded = bare.packets.iter().filter_map(|p| dec.decode(&p.data, p.pts).ok()).flatten().count();
assert_eq!(decoded, 0, "the packets decode without a sequence header");
common::check_track(&track, &f);
}
+14
View File
@@ -0,0 +1,14 @@
//! VP9 in MP4 (a `vpcC` record, which the decoder does not need).
use crate::common;
use craft_media::CodecId;
#[test]
fn mp4() {
let args = ["-c:v", "libvpx-vp9", "-deadline", "good", "-cpu-used", "5", "-b:v", "400k", "-g", "12", "-pix_fmt", "yuv420p"];
let Some(f) = common::fixture("vp9", "mp4", &args, "yuv420p") else { return };
let track = common::mp4(&f.file);
assert_eq!(track.params.codec, CodecId::Vp9);
assert!(!track.params.extradata.is_empty(), "a vpcC record");
common::check_track(&track, &f);
}
+6 -4
View File
@@ -32,9 +32,10 @@ cargo clippy --workspace --all-targets --locked -- -D warnings
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
"""
TEST_SOURCE = """
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_SETUP = """powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'"""
EXPECTED_SOURCE = {
@@ -90,9 +91,10 @@ COMMON = [
"clippy --workspace --all-targets --all-features --locked -- -D warnings",
]
TESTS = [
"nextest run --workspace --all-features --locked --profile ci",
"nextest run --workspace --all-features --locked --profile ci --lib --bins --tests",
"nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench",
"test --workspace --doc --all-features --locked",
"nextest run -p craft-image-codecs -p craft-text --locked --profile ci",
"nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests",
]
+7 -2
View File
@@ -42,12 +42,17 @@ Consuming workspaces need a `hayro-cmap` patch entry beside the other Hayro entr
`hayro-postscript` 0.1.0 is the crates.io package (upstream revision
a2354aebaf86f5ab13e5fd6b6b0521306488bf9d), the PostScript token scanner `hayro-cmap` uses
to parse the CMap streams PDFs embed. One local patch: the scanner, which does not parse
to parse the CMap streams PDFs embed. Two local patches. The scanner, which does not parse
dictionaries yet, skips runs of `<<` and `>>` in a loop and returns the next object, instead
of recursing once per delimiter, so a long run of `<` or `>` bytes no longer overflows the
stack. Tests: `object::tests::long_open_dict_run_does_not_overflow`,
`object::tests::long_close_dict_run_does_not_overflow`, `object::tests::dict_delimiters_are_skipped`
and `object::tests::nested_dict_delimiters_are_skipped`. Its `SOURCE.json` records the
and `object::tests::nested_dict_delimiters_are_skipped`. A literal string's `\ddd` escape keeps
the low eight bits of its value, as ISO 32000-2 §7.3.4.2 asks ("high-order overflow shall be
ignored"), so `\737` decodes to `0xDF` instead of being dropped; code comments label it
`Craft patch (octal overflow, craft-libs #2321)`. Tests:
`string::tests::literal_octal_overflow_keeps_the_low_eight_bits` and
`string::tests::literal_octal_short_escape_stops_at_a_non_octal_byte`. Its `SOURCE.json` records the
registry hashes. Consuming workspaces need a `hayro-postscript` patch entry beside the other
Hayro entries.
+4 -3
View File
@@ -8,7 +8,8 @@
"upstream_revision": "a2354aebaf86f5ab13e5fd6b6b0521306488bf9d",
"upstream_directory": "hayro-postscript",
"local_patches": [
"Skip runs of `<<` and `>>` in a loop in `object::read` instead of recursing once per delimiter, so a long run cannot overflow the stack."
"Skip runs of `<<` and `>>` in a loop in `object::read` instead of recursing once per delimiter, so a long run cannot overflow the stack.",
"Keep the low eight bits of a literal string's `\\ddd` escape in `string::literal::decode_into` (ISO 32000-2 §7.3.4.2), instead of dropping an escape above `\\377`."
],
"files": [
{
@@ -99,7 +100,7 @@
"path": "src/string.rs",
"source_sha256": "1c47947beb5ce7c56036d5b115a47e703a5a276cb9f3faf5e9b2a4304e4a518f",
"source_git_blob": null,
"sha256": "1c47947beb5ce7c56036d5b115a47e703a5a276cb9f3faf5e9b2a4304e4a518f"
"sha256": "42bb4c6a7291165f3841333032f582c74145109443f9161065afc6881d2e9f2b"
},
{
"path": "src/string/ascii_85.rs",
@@ -117,7 +118,7 @@
"path": "src/string/literal.rs",
"source_sha256": "8633efbb282227512ef506d020ea69d4ef47c549ae9248e7b0d4fcefd2aaf933",
"source_git_blob": null,
"sha256": "8633efbb282227512ef506d020ea69d4ef47c549ae9248e7b0d4fcefd2aaf933"
"sha256": "0feae923df7807fe671bc3d320bdcf5e1a65cb7b652aa9245b0b918376c1daf9"
}
]
}
+15
View File
@@ -187,6 +187,21 @@ mod tests {
assert_eq!(decode_literal(b"(\\3)").unwrap(), b"\x03");
}
#[test]
fn literal_octal_overflow_keeps_the_low_eight_bits() {
assert_eq!(decode_literal(b"(\\737)").unwrap(), b"\xDF");
assert_eq!(decode_literal(b"(\\400\\777)").unwrap(), b"\x00\xFF");
assert_eq!(decode_literal(b"(\\1234)").unwrap(), b"S4");
}
#[test]
fn literal_octal_short_escape_stops_at_a_non_octal_byte() {
assert_eq!(
decode_literal(b"(\\36a\\3z\\0089)").unwrap(),
b"\x1ea\x03z\x0089"
);
}
#[test]
fn literal_line_continuation_lf() {
assert_eq!(decode_literal(b"(Hi \\\nthere)").unwrap(), b"Hi there");
+24 -33
View File
@@ -12,38 +12,26 @@ pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
b'\\' => {
let next = r.read_byte()?;
if is_octal_digit(next) {
let second = r.read_byte();
let third = r.read_byte();
let bytes = match (second, third) {
(Some(n1), Some(n2)) => match (is_octal_digit(n1), is_octal_digit(n2)) {
(true, true) => [next, n1, n2],
(true, _) => {
r.jump(r.offset() - 1);
[b'0', next, n1]
}
_ => {
r.jump(r.offset() - 2);
[b'0', b'0', next]
}
},
(Some(n1), None) => {
if is_octal_digit(n1) {
[b'0', next, n1]
} else {
r.jump(r.offset() - 1);
[b'0', b'0', next]
}
}
_ => [b'0', b'0', next],
};
let str = core::str::from_utf8(&bytes).unwrap();
if let Ok(num) = u8::from_str_radix(str, 8) {
out.push(num);
if let Some(first) = octal_digit(next) {
// Craft patch (octal overflow, craft-libs #2321): read one
// to three octal digits and keep the low eight bits of
// the value. "The number ddd may consist of one, two, or
// three octal digits; high-order overflow shall be
// ignored" (ISO 32000-2 §7.3.4.2; PostScript Language
// Reference, third edition, §3.2.2), so `\737` is 0xDF.
// Previously an escape above `\377` was dropped.
let mut value = first;
for _ in 0..2 {
let Some(digit) = r.peek_byte().and_then(octal_digit) else {
break;
};
r.forward();
// At most 0o777 after three digits, so no overflow.
value = value * 8 + digit;
}
// Truncation to the low byte is the overflow rule above.
out.push((value & 0xFF) as u8);
} else {
match next {
b'n' => out.push(0xA),
@@ -80,6 +68,9 @@ pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
Some(())
}
fn is_octal_digit(byte: u8) -> bool {
matches!(byte, b'0'..=b'7')
fn octal_digit(byte: u8) -> Option<u16> {
match byte {
b'0'..=b'7' => Some(u16::from(byte - b'0')),
_ => None,
}
}