diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml new file mode 100644 index 000000000..e19902e8c --- /dev/null +++ b/.github/workflows/formats.yml @@ -0,0 +1,111 @@ +name: Shared format crates + +on: + push: + branches: [main] + paths: + - "crates/xml/**" + - "crates/mime/**" + - "crates/cfb/**" + - "crates/mesh/**" + - "crates/metafile/**" + - "crates/dxf/**" + - "crates/gcode/**" + - "crates/svg-paths/**" + - "crates/silhouette-studio/**" + - "crates/tiff/**" + - "crates/heif/**" + - "crates/cms/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/formats.yml" + pull_request: + paths: + - "crates/xml/**" + - "crates/mime/**" + - "crates/cfb/**" + - "crates/mesh/**" + - "crates/metafile/**" + - "crates/dxf/**" + - "crates/gcode/**" + - "crates/svg-paths/**" + - "crates/silhouette-studio/**" + - "crates/tiff/**" + - "crates/heif/**" + - "crates/cms/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/formats.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # Pull requests share one group per branch, so a newer push cancels the older run. Every other + # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it + # always gets to save the cache. + group: shared-formats-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + check: + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + # `features`: each is linted alone, so code that needs another feature fails here. + - { crate: craft-xml, features: "" } + - { crate: craft-mime, features: "" } + - { crate: craft-cfb, features: "" } + - { crate: craft-mesh, features: "stl obj ply gltf" } + - { crate: craft-metafile, features: "write" } + - { crate: craft-dxf, features: "" } + - { crate: craft-gcode, features: "" } + - { crate: craft-svg-paths, features: "" } + - { crate: craft-silhouette-studio, features: "" } + - { crate: craft-tiff, features: "" } + - { crate: craft-heif, features: "testdata" } + - { crate: craft-cms, features: "" } + name: ${{ matrix.crate }} lint, tests, WASM + runs-on: ubuntu-latest + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + with: + components: rustfmt, clippy + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: ${{ matrix.crate }} + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo fmt -p "$CRATE" --check + env: + CRATE: ${{ matrix.crate }} + - name: Clippy, default features and each feature alone + env: + CRATE: ${{ matrix.crate }} + FEATURES: ${{ matrix.features }} + run: | + cargo clippy -p "$CRATE" --all-targets --locked -- -D warnings + for f in $FEATURES; do + echo "::group::feature: $f" + cargo clippy -p "$CRATE" --all-targets --locked --no-default-features --features "$f" -- -D warnings + echo "::endgroup::" + done + - run: cargo clippy -p "$CRATE" --all-targets --locked --all-features -- -D warnings + env: + CRATE: ${{ matrix.crate }} + - run: cargo test -p "$CRATE" --all-features --locked + env: + CRATE: ${{ matrix.crate }} + - run: cargo check -p "$CRATE" --all-features --locked --target wasm32-unknown-unknown + env: + CRATE: ${{ matrix.crate }} diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 1f88bd5d1..654fe4c02 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -20,4 +20,8 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main with: pdf-test-fonts: true + # The codec and format code behind features that are off by default. Without these the + # coverage build never compiles it, and new code there reads as untested. + cargo-features: >- + craft-video/dnx,craft-video/vp8,craft-video/prores,craft-video/h264,craft-video/hevc,craft-video/vp9,craft-video/av1,craft-video/threads,craft-audio/decode,craft-audio/encode,craft-audio/peaks,craft-audio/rayon,craft-audio/serde,craft-media/matroska,craft-media/ogg,craft-media/bitstream,craft-media/serde,craft-mesh/stl,craft-mesh/obj,craft-mesh/ply,craft-mesh/gltf,craft-metafile/write secrets: inherit diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index 1c4e063d1..ec1c16eda 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -40,7 +40,7 @@ jobs: # Each feature on its own, so code that needs another feature fails here. - name: Clippy, each feature alone run: | - for f in "" dnx vp8 prores h264 hevc vp9 av1 threads; do + for f in "" dnx vp8 prores h264 hevc vp9 vp9-decode vp9-encode av1 threads; do echo "::group::features: ${f:-none}" cargo clippy -p craft-video --all-targets --locked --no-default-features ${f:+--features "$f"} -- -D warnings echo "::endgroup::" diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index bfe2b07c7..e9120eb91 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -28,6 +28,9 @@ author, source and license. Library code and original assets are under the repos | `crates/crw/tests/samples.json` (manifest only; the 11 raw files are not bundled, `scripts/fetch-crw-samples.py` downloads them outside the checkout) | The photographers who contributed each file to raw.pixls.us (Canon EOS D30, D60, 10D ×3, 300D ×2, Digital Rebel, PowerShot G1, G5, G6) | [raw.pixls.us](https://raw.pixls.us/), each file's `getfile.php` URL and SHA-256 in the manifest | CC0-1.0 (as published by raw.pixls.us for each file) | | `crates/crw/src/tables.rs`, `crates/crw/clean-room/logs/table_sel*.json` | craft-crw contributors (derived in LightCraft, 2026-10, by known-plaintext alignment of the sample files' entropy streams; `crates/crw/clean-room/02-crw-format.md`) | this repository | MIT OR Apache-2.0 | | `crates/crw/clean-room/logs/private-corpus.tsv` (file names, sizes and SHA-256 of the maintainer's own EOS D60 files; no image content) | craft-crw contributors (LightCraft derivation record) | this repository | MIT OR Apache-2.0 | +| `crates/prc/src/acof/table.rs` (the rows of the PRC `Double` prefix-code table, reformatted as Rust tuples) | Kristof Ralovich (prc-rs); the table is defined by ISO 14739-1 | [ralovich/prc-rs@287b671](https://github.com/ralovich/prc-rs/blob/287b671bb5b31b05efb5ec1b98f7c359b9e4dd7d/src/double.rs), through [PdfCraft `crates/prc`](https://github.com/storytold/pdfcraft/tree/80e26e674d1aa33078e83c8139875047f3289eb6/crates/prc) | MIT (`licenses/prc-rs/LICENSE.txt`; the notice is also in the file header) | +| `crates/math/tests/corpus/equations.tsv`, `crates/math/tests/corpus/latex.tsv` (unmodified) | shuff57 (equaSHion) | [storytold/craft-libs#29](https://github.com/storytold/craft-libs/pull/29) at `7a6ef6b9`, `corpus/` | MIT OR Apache-2.0 | +| `crates/math/tests/corpus/omml/*.xml` (unmodified) | WordCraft and DeckCraft contributors, collected by shuff57 (equaSHion) | [storytold/craft-libs#29](https://github.com/storytold/craft-libs/pull/29) at `7a6ef6b9`, `corpus/omml/` | MIT OR Apache-2.0 | Original assets are covered by the repository licence. @@ -79,6 +82,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso | `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged | | `crates/audio/src/ac3/golden_frames.bin` | FilmCraft contributors (original work: 12 AC-3 and E-AC-3 syncframes that ffmpeg's `ac3` and `eac3` encoders made from tones and seeded noise synthesised by ffmpeg's lavfi generators; no third-party or recorded audio) | [FilmCraft `crates/ac3`](https://github.com/storytold/filmcraft/tree/1c9c2e82/crates/ac3/src) | MIT OR Apache-2.0 | | `crates/audio/tests/fixtures/` | SoundCraft and craft-libs contributors (original work: 0.1 s test tones from ffmpeg's `sine` generator and hand-built silent MPEG frames; no third-party or recorded audio; commands in `crates/audio/tests/fixtures/README.md`) | [SoundCraft `crates/audio-io/tests/fixtures`](https://github.com/storytold/soundcraft/tree/e86d09a/crates/audio-io/tests/fixtures); `tone.mov`, `tone.mka`, `tone.opus`, `tone.ac3` and `tone.eac3` made in this repository | MIT OR Apache-2.0 | +| `crates/raster-codecs/src/xpm/x11_colors.rs` | X.Org Foundation and X11 contributors (X11 `rgb.txt` colour names and values, normalised into a lookup table) | , via [PhotoCraft `crates/codecs`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/codecs/src/codecs/xpm) | MIT (X.Org app/rgb) | | `crates/psd/tests/fixtures/atn/*.atn` (seven synthetic action sets, encoded field by field; `crates/psd/tests/fixtures/atn/README.md`) | PhotoCraft contributors | [PhotoCraft `crates/psd/tests/fixtures/atn`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/psd/tests/fixtures/atn) | MIT OR Apache-2.0 | | `crates/lottie/tests/fixtures/` | EffectCraft contributors (original work: four hand-written Lottie JSON documents, written from the public Lottie format description; not exported from any Adobe product or third-party file) | [EffectCraft `crates/lottie/tests/fixtures`](https://github.com/storytold/effectcraft/tree/e18f48fb/crates/lottie/tests/fixtures) | MIT OR Apache-2.0 | | `crates/affinity/tests/support/corpus.tsv`, `crates/affinity/tests/support/affinity3-signatures.txt` (manifest and measured signatures only; the 51 documents are not bundled, `scripts/fetch-affinity-corpus.sh` downloads them outside the checkout) | The authors of each document: samuel-etver (vector-art), Seth A. Robinson (Patchy fixtures), Nick Beeuwsaert (AFDesignLoad), Jeremy Cantu (Branding), eviltwo (AssetStoreTemplate), Square (leakcanary) | each file's pinned upstream URL and SHA-256 in the manifest; list carried over from [VectorCraft `xtask/src/affinity_corpus.rs`](https://github.com/storytold/vectorcraft/blob/6e873b806c9d5b3f2b55f651df57bd97933b579a/xtask/src/affinity_corpus.rs) | CC0-1.0, MIT or Apache-2.0 (per file, in the manifest) | diff --git a/Cargo.lock b/Cargo.lock index 313c939c5..45ae4e5b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -29,6 +29,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "ahash" version = "0.8.12" @@ -48,13 +59,28 @@ version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + [[package]] name = "alloc-stdlib" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" dependencies = [ - "alloc-no-stdlib", + "alloc-no-stdlib 2.0.4", +] + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib 3.0.0", ] [[package]] @@ -358,6 +384,12 @@ dependencies = [ "serde", ] +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + [[package]] name = "bitflags" version = "1.3.2" @@ -392,6 +424,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -453,9 +494,20 @@ version = "8.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", + "brotli-decompressor 5.0.3", +] + +[[package]] +name = "brotli" +version = "9.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.3.1", ] [[package]] @@ -464,8 +516,18 @@ version = "5.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", +] + +[[package]] +name = "brotli-decompressor" +version = "6.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", ] [[package]] @@ -588,6 +650,17 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "chardetng" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13de944a44b5064ee5d3a5ceccc49a41bfec50f2580e66f82e87703acdb88b53" +dependencies = [ + "cfg-if", + "encoding_rs", + "memchr", +] + [[package]] name = "chrono" version = "0.4.45" @@ -602,6 +675,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + [[package]] name = "cmake" version = "0.1.58" @@ -611,6 +694,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cmpv2" version = "0.2.0" @@ -629,7 +718,7 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "spki", "x509-cert", @@ -705,6 +794,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "constant_time_eq" version = "0.4.2" @@ -776,6 +871,12 @@ dependencies = [ "libm", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -794,6 +895,16 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-aaf" +version = "0.1.0" +dependencies = [ + "craft-audio", + "craft-cfb", + "craft-timeline", + "thiserror 2.0.21", +] + [[package]] name = "craft-aep" version = "0.1.0" @@ -807,7 +918,7 @@ dependencies = [ "image", "proptest", "ruzstd", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -853,8 +964,10 @@ dependencies = [ name = "craft-captions" version = "0.1.0" dependencies = [ + "craft-timeline", "craft-xml", "proptest", + "roxmltree 0.21.2", "thiserror 2.0.21", ] @@ -866,11 +979,27 @@ version = "0.1.0" name = "craft-cms" version = "0.1.0" dependencies = [ - "md-5", + "md-5 0.10.6", "moxcms", "rayon", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +dependencies = [ + "encoding_rs", +] + +[[package]] +name = "craft-crs" +version = "0.1.0" +dependencies = [ + "craft-metadata", + "craft-xml", + "thiserror 2.0.21", +] + [[package]] name = "craft-crw" version = "0.1.0" @@ -878,7 +1007,7 @@ dependencies = [ "proptest", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", ] @@ -889,6 +1018,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-dav" +version = "0.1.0" +dependencies = [ + "craft-xml", + "proptest", +] + [[package]] name = "craft-dialogs" version = "0.1.0" @@ -921,19 +1058,51 @@ dependencies = [ name = "craft-docpath" version = "0.1.0" +[[package]] +name = "craft-docx" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "chrono", + "craft-cfb", + "craft-offcrypto", + "craft-opc", + "craft-wordmodel", + "craft-xml", + "image", + "log", + "proptest", + "quick-xml 0.41.0", + "serde_json", + "thiserror 2.0.21", + "unicode-bidi", + "zeroize", + "zip", +] + +[[package]] +name = "craft-dpx" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-drawingml" version = "0.1.0" dependencies = [ "craft-xml", "kurbo 0.13.1", + "log", "serde", + "serde_json", ] [[package]] name = "craft-dxf" version = "0.1.0" dependencies = [ + "craft-codepage", "encoding_rs", "log", "thiserror 2.0.21", @@ -948,28 +1117,72 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-eps" +version = "0.1.0" + [[package]] name = "craft-epub" version = "0.1.0" dependencies = [ "craft-xml", - "flate2", + "craft-zip", "thiserror 2.0.21", "zip", ] +[[package]] +name = "craft-ews" +version = "0.1.0" +dependencies = [ + "craft-xml", + "proptest", +] + +[[package]] +name = "craft-exr" +version = "0.1.0" +dependencies = [ + "exr", + "flate2", + "half", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-fig" version = "0.1.0" dependencies = [ + "craft-figma-rest", "craft-kiwi", + "craft-zip", "flate2", + "kurbo 0.13.1", "ruzstd", "serde_json", "thiserror 2.0.21", "zip", ] +[[package]] +name = "craft-figma-rest" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-flow" +version = "0.1.0" +dependencies = [ + "craft-wordmodel", + "image", + "log", +] + [[package]] name = "craft-font-catalog" version = "0.1.0" @@ -1010,7 +1223,7 @@ dependencies = [ "ruzstd", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "skrifa 0.47.0", "tar", "thiserror 2.0.21", @@ -1049,6 +1262,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-gif" +version = "0.1.0" +dependencies = [ + "image", +] + +[[package]] +name = "craft-hdr" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-heif" version = "0.1.0" @@ -1057,6 +1284,13 @@ dependencies = [ "rayon", ] +[[package]] +name = "craft-html" +version = "0.1.0" +dependencies = [ + "proptest", +] + [[package]] name = "craft-i18n" version = "0.1.0" @@ -1080,16 +1314,32 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-ical" +version = "0.1.0" +dependencies = [ + "chrono", + "proptest", +] + [[package]] name = "craft-idml" version = "0.1.0" dependencies = [ "craft-xml", - "flate2", + "craft-zip", "thiserror 2.0.21", "zip", ] +[[package]] +name = "craft-jmap" +version = "0.1.0" +dependencies = [ + "proptest", + "serde_json", +] + [[package]] name = "craft-jpeg" version = "0.1.0" @@ -1111,7 +1361,7 @@ dependencies = [ "image", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tempfile", ] @@ -1119,6 +1369,16 @@ dependencies = [ name = "craft-kiwi" version = "0.1.0" +[[package]] +name = "craft-kra" +version = "0.1.0" +dependencies = [ + "craft-xml", + "craft-zip", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-lottie" version = "0.1.0" @@ -1127,6 +1387,25 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-markdown" +version = "0.1.0" +dependencies = [ + "craft-flow", + "craft-html", + "craft-wordmodel", +] + +[[package]] +name = "craft-math" +version = "0.1.0" +dependencies = [ + "craft-xml", + "proptest", + "serde", + "serde_json", +] + [[package]] name = "craft-media" version = "0.1.0" @@ -1159,10 +1438,26 @@ dependencies = [ name = "craft-mesh" version = "0.1.0" dependencies = [ + "craft-opc", + "craft-xml", "miniz_oxide 0.9.1", "serde_json", ] +[[package]] +name = "craft-metadata" +version = "0.1.0" +dependencies = [ + "brotli 9.1.1", + "brotli-decompressor 6.3.1", + "chrono", + "craft-tiff", + "proptest", + "quick-xml 0.41.0", + "serde", + "serde_json", +] + [[package]] name = "craft-metafile" version = "0.1.0" @@ -1187,22 +1482,78 @@ dependencies = [ name = "craft-mime" version = "0.1.0" dependencies = [ + "chardetng", "chrono", + "craft-codepage", "encoding_rs", "proptest", ] +[[package]] +name = "craft-odf" +version = "0.1.0" +dependencies = [ + "aes", + "base64 0.23.1", + "craft-xml", + "craft-zip", + "flate2", + "getrandom 0.3.4", + "hmac", + "sha1 0.11.0", + "sha2 0.11.1", + "thiserror 2.0.21", + "zeroize", + "zip", +] + +[[package]] +name = "craft-ods" +version = "0.1.0" +dependencies = [ + "craft-odf", + "craft-sheet", + "craft-xml", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-offcrypto" +version = "0.1.0" +dependencies = [ + "aes", + "base64 0.23.1", + "craft-cfb", + "craft-xml", + "getrandom 0.3.4", + "hmac", + "sha1 0.11.0", + "sha2 0.11.1", + "thiserror 2.0.21", + "zeroize", +] + [[package]] name = "craft-opc" version = "0.1.0" dependencies = [ "craft-xml", - "flate2", + "craft-zip", "log", "thiserror 2.0.21", "zip", ] +[[package]] +name = "craft-ora" +version = "0.1.0" +dependencies = [ + "craft-xml", + "craft-zip", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-pcraft-format" version = "0.1.0" @@ -1216,23 +1567,40 @@ dependencies = [ name = "craft-pdf" version = "0.1.0" dependencies = [ + "aes", "bytemuck", + "craft-stream-codecs", + "flate2", "hayro", "hayro-cmap", "hayro-interpret", "hayro-syntax", "krilla", "kurbo 0.13.1", + "md-5 0.11.0", + "proptest", + "sha2 0.11.1", + "stringprep", "thiserror 2.0.21", "ttf-parser", "wasm-bindgen-test", + "zeroize", +] + +[[package]] +name = "craft-pdn" +version = "0.1.0" +dependencies = [ + "flate2", + "proptest", + "thiserror 2.0.21", ] [[package]] name = "craft-penpot" version = "0.1.0" dependencies = [ - "flate2", + "craft-zip", "serde_json", "thiserror 2.0.21", "zip", @@ -1276,6 +1644,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-prc" +version = "0.1.0" +dependencies = [ + "flate2", + "proptest", + "thiserror 2.0.21", +] + [[package]] name = "craft-prepress" version = "0.1.0" @@ -1325,6 +1702,13 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pst" +version = "0.1.0" +dependencies = [ + "proptest", +] + [[package]] name = "craft-quit" version = "0.1.0" @@ -1336,6 +1720,14 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-raster-codecs" +version = "0.1.0" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-raw" version = "0.1.0" @@ -1359,6 +1751,7 @@ dependencies = [ name = "craft-rtf" version = "0.1.0" dependencies = [ + "craft-codepage", "encoding_rs", ] @@ -1373,6 +1766,10 @@ dependencies = [ "toml_edit", ] +[[package]] +name = "craft-sheet" +version = "0.1.0" + [[package]] name = "craft-silhouette-studio" version = "0.1.0" @@ -1385,12 +1782,26 @@ dependencies = [ name = "craft-sketch" version = "0.1.0" dependencies = [ - "flate2", + "craft-figma-rest", + "craft-zip", + "kurbo 0.13.1", "serde_json", "thiserror 2.0.21", "zip", ] +[[package]] +name = "craft-stream-codecs" +version = "0.1.0" +dependencies = [ + "fax", + "hayro-ccitt", + "hayro-jbig2", + "proptest", + "thiserror 2.0.21", + "weezl 0.2.1", +] + [[package]] name = "craft-svg" version = "0.1.0" @@ -1400,6 +1811,7 @@ dependencies = [ "kurbo 0.13.1", "roxmltree 0.21.2", "thiserror 2.0.21", + "usvg 0.48.1", ] [[package]] @@ -1424,6 +1836,13 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "craft-tga" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1488,7 +1907,7 @@ dependencies = [ "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tar", "tempfile", "ureq", @@ -1498,6 +1917,15 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-vcard" +version = "0.1.0" +dependencies = [ + "chrono", + "craft-mime", + "proptest", +] + [[package]] name = "craft-vectorcraft-format" version = "0.1.0" @@ -1546,6 +1974,14 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-webp" +version = "0.1.0" +dependencies = [ + "image", + "thiserror 2.0.21", +] + [[package]] name = "craft-window" version = "0.1.0" @@ -1564,11 +2000,43 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "craft-wordmodel" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "log", + "proptest", + "serde", + "serde_json", + "thiserror 2.0.21", + "unicode-segmentation", +] + +[[package]] +name = "craft-xcf" +version = "0.1.0" +dependencies = [ + "flate2", + "thiserror 2.0.21", +] + [[package]] name = "craft-xls" version = "0.1.0" dependencies = [ "craft-cfb", + "craft-sheet", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xlsx" +version = "0.1.0" +dependencies = [ + "craft-opc", + "craft-sheet", + "craft-xml", "thiserror 2.0.21", ] @@ -1580,6 +2048,23 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-y4m" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +dependencies = [ + "craft-zip", + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1651,6 +2136,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1669,7 +2172,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der_derive", "flagset", "pem-rfc7468", @@ -1712,8 +2215,20 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -2143,6 +2658,21 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "smallvec", + "zune-inflate", +] + [[package]] name = "extended" version = "0.1.0" @@ -2282,6 +2812,27 @@ dependencies = [ "serde", ] +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree 0.20.0", +] + +[[package]] +name = "fontdb" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" +dependencies = [ + "fontconfig-parser", + "log", + "slotmap", + "tinyvec", +] + [[package]] name = "fontique" version = "0.11.1" @@ -2468,9 +3019,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] @@ -2494,7 +3047,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" dependencies = [ "color_quant", - "weezl", + "weezl 0.1.12", ] [[package]] @@ -2728,7 +3281,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" name = "hayro-cmap" version = "0.1.0" dependencies = [ - "brotli", + "brotli 8.0.4", "hayro-postscript", ] @@ -2823,6 +3376,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.5.0" @@ -2862,6 +3424,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -3237,6 +3808,12 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c" +[[package]] +name = "imagesize" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" + [[package]] name = "indexmap" version = "2.14.2" @@ -3247,6 +3824,15 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "hybrid-array", +] + [[package]] name = "io-extras" version = "0.19.0" @@ -3478,7 +4064,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46" dependencies = [ - "brotli-decompressor", + "brotli-decompressor 5.0.3", "jxl-bitstream", "jxl-frame", "jxl-grid", @@ -3510,7 +4096,7 @@ version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3" dependencies = [ - "brotli-decompressor", + "brotli-decompressor 5.0.3", "jxl-bitstream", "jxl-color", "jxl-frame", @@ -3670,6 +4256,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.190" @@ -3782,7 +4374,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", ] [[package]] @@ -3884,6 +4486,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -5159,9 +5783,9 @@ dependencies = [ "log", "pico-args", "rgb", - "svgtypes", + "svgtypes 0.15.3", "tiny-skia", - "usvg", + "usvg 0.45.1", ] [[package]] @@ -5577,7 +6201,18 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -5588,7 +6223,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -5642,12 +6288,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" dependencies = [ "aws-lc-rs", "base64 0.22.1", - "const-oid", + "const-oid 0.9.6", "der", - "digest", + "digest 0.10.7", "pem", "rand_core 0.10.1", - "sha2", + "sha2 0.10.9", "signature", "sigstore-types", "spki", @@ -5716,7 +6362,7 @@ dependencies = [ "chrono", "cmpv2", "cms", - "const-oid", + "const-oid 0.9.6", "der", "hex", "rand", @@ -5755,7 +6401,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cms", - "const-oid", + "const-oid 0.9.6", "hex", "pem", "rustls-pki-types", @@ -6008,6 +6654,16 @@ dependencies = [ "siphasher", ] +[[package]] +name = "svgtypes" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" +dependencies = [ + "kurbo 0.13.1", + "siphasher", +] + [[package]] name = "symphonia" version = "0.6.1" @@ -6301,6 +6957,12 @@ dependencies = [ "xattr", ] +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "tempfile" version = "3.27.0" @@ -6373,7 +7035,7 @@ dependencies = [ "flate2", "half", "quick-error 2.0.1", - "weezl", + "weezl 0.1.12", "zune-jpeg", ] @@ -6766,6 +7428,12 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + [[package]] name = "unicode-width" version = "0.2.2" @@ -6843,11 +7511,38 @@ dependencies = [ "simplecss", "siphasher", "strict-num", - "svgtypes", + "svgtypes 0.15.3", "tiny-skia-path 0.11.4", "xmlwriter", ] +[[package]] +name = "usvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" +dependencies = [ + "base64 0.23.1", + "data-url", + "fontdb", + "harfrust", + "imagesize 0.15.0", + "kurbo 0.13.1", + "log", + "pico-args", + "roxmltree 0.21.2", + "simplecss", + "siphasher", + "skrifa 0.44.0", + "strict-num", + "svgtypes 0.16.2", + "tiny-skia-path 0.12.0", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + [[package]] name = "utf16_iter" version = "1.0.5" @@ -7199,6 +7894,12 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + [[package]] name = "wgpu" version = "30.0.1" @@ -7788,9 +8489,9 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", - "sha1", + "sha1 0.10.7", "signature", "spki", "tls_codec", @@ -8096,6 +8797,15 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + [[package]] name = "zune-jpeg" version = "0.5.15" diff --git a/Cargo.toml b/Cargo.toml index 485004f47..ab3d87968 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } craft-ai-core = { path = "crates/ai-core" } craft-pdf = { path = "crates/pdf", version = "=0.1.0" } +craft-pdn = { path = "crates/pdn" } craft-plate-test = { path = "crates/plate-test" } krilla = { version = "=0.8.2", default-features = false, features = ["raster-images"] } hayro = { version = "=0.7.1", default-features = false } @@ -25,72 +26,109 @@ hayro-syntax = { version = "=0.7.2", default-features = false, features = ["std" bytemuck = "1" kurbo = "0.13" thiserror = "2" +craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } +craft-codepage = { path = "crates/codepage" } craft-cms = { path = "crates/cms" } +craft-crs = { path = "crates/crs" } craft-crw = { path = "crates/crw" } craft-csv = { path = "crates/csv" } +craft-dav = { path = "crates/dav" } craft-dialogs = { path = "crates/dialogs" } +craft-docx = { path = "crates/docx" } craft-dxf = { path = "crates/dxf" } craft-drawingml = { path = "crates/drawingml" } +craft-eps = { path = "crates/eps" } craft-doc = { path = "crates/doc" } craft-docpath = { path = "crates/docpath" } +craft-dpx = { path = "crates/dpx" } craft-ecproj-format = { path = "crates/ecproj-format" } +craft-figma-rest = { path = "crates/figma-rest" } +craft-exr = { path = "crates/exr" } craft-font-catalog = { path = "crates/font-catalog" } craft-font-manager = { path = "crates/font-manager" } craft-font-store = { path = "crates/font-store" } craft-gainmap = { path = "crates/gainmap" } +craft-flow = { path = "crates/flow" } craft-gcode = { path = "crates/gcode" } +craft-gif = { path = "crates/gif" } +craft-hdr = { path = "crates/hdr" } craft-mesh = { path = "crates/mesh" } +craft-html = { path = "crates/html" } craft-heif = { path = "crates/heif" } craft-fig = { path = "crates/fig" } craft-fonts-build = { path = "crates/fonts-build" } craft-i18n = { path = "crates/i18n" } craft-idml = { path = "crates/idml" } +craft-jmap = { path = "crates/jmap" } +craft-ical = { path = "crates/ical" } craft-jpeg = { path = "crates/jpeg" } craft-kiwi = { path = "crates/kiwi" } craft-keymap = { path = "crates/keymap" } craft-assuan = { path = "crates/assuan" } +craft-kra = { path = "crates/kra" } craft-audio = { path = "crates/audio" } # No default features, so craft-audio's `encode` builds craft-media without `isobmff`. +craft-markdown = { path = "crates/markdown" } +craft-math = { path = "crates/math" } craft-media = { path = "crates/media", default-features = false } craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } craft-mime = { path = "crates/mime" } +craft-odf = { path = "crates/odf" } +craft-ods = { path = "crates/ods" } +craft-prc = { path = "crates/prc" } craft-lottie = { path = "crates/lottie" } craft-menu = { path = "crates/menu" } craft-metafile = { path = "crates/metafile" } +craft-offcrypto = { path = "crates/offcrypto" } craft-opc = { path = "crates/opc" } +craft-ora = { path = "crates/ora" } craft-penpot = { path = "crates/penpot" } craft-pcraft-format = { path = "crates/pcraft-format" } craft-plotter = { path = "crates/plotter" } craft-prepress = { path = "crates/prepress" } craft-print = { path = "crates/print" } craft-proof = { path = "crates/proof" } +craft-raster-codecs = { path = "crates/raster-codecs" } craft-psd = { path = "crates/psd" } +craft-pst = { path = "crates/pst" } craft-quit = { path = "crates/quit" } craft-rtf = { path = "crates/rtf" } craft-raw = { path = "crates/raw" } +craft-sheet = { path = "crates/sheet" } craft-sketch = { path = "crates/sketch" } craft-settings = { path = "crates/settings" } craft-silhouette-studio = { path = "crates/silhouette-studio" } craft-svg = { path = "crates/svg" } craft-svg-paths = { path = "crates/svg-paths" } +craft-stream-codecs = { path = "crates/stream-codecs" } craft-text = { path = "crates/text" } +craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } craft-tiff = { path = "crates/tiff" } +craft-metadata = { path = "crates/metadata" } craft-ui = { path = "crates/ui" } craft-update = { path = "crates/update" } +craft-vcard = { path = "crates/vcard" } craft-vectorcraft-format = { path = "crates/vectorcraft-format" } craft-vectordrawable = { path = "crates/vectordrawable" } craft-xls = { path = "crates/xls" } +craft-wordmodel = { path = "crates/wordmodel" } +craft-xlsx = { path = "crates/xlsx" } +craft-xcf = { path = "crates/xcf" } craft-xml = { path = "crates/xml" } +craft-zip = { path = "crates/zip" } +craft-y4m = { path = "crates/y4m" } craft-epub = { path = "crates/epub" } +craft-ews = { path = "crates/ews" } craft-video = { path = "crates/video" } craft-web-api = { path = "crates/web-api" } craft-window = { path = "crates/window" } craft-web-host = { path = "crates/web-host" } +craft-webp = { path = "crates/webp" } egui = { version = "0.37", default-features = false } md5 = { package = "md-5", version = "0.10", default-features = false } rayon = "1" diff --git a/NOTICE b/NOTICE index 6729833e3..91123023b 100644 --- a/NOTICE +++ b/NOTICE @@ -93,7 +93,7 @@ crates/raw (craft-raw) is moved from LightCraft, with behaviour ported from two - 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, vendor.rs (shared level helpers), vendor/mrw.rs, vendor/erf.rs, vendor/mef.rs, vendor/kodak.rs, vendor/pef.rs, - vendor/srw.rs, tests/it/vendor_robust.rs and their tests) and crates/meta/src/mrw.rs (the MRW block container), + vendor/srw.rs, vendor/cr2.rs, vendor/cr2/sraw.rs, vendor/nef.rs, vendor/nefc.rs, vendor/nef_lens.rs, docs/nikon-lens-corrections.md, vendor/rw2.rs, vendor/raf.rs, vendor/rafc.rs, vendor/raf_lens.rs, docs/raf-compression.md, docs/raf-corpus.sha256, vendor/orf.rs, docs/orf-compression.md, kelvin_presets.rs (the preset ordering), tests/it/vendor_robust.rs and their tests) and crates/meta/src/mrw.rs (the MRW block container), revision 5ff567a4a2e067bef1b6bce152c11e7f727ccbaf. https://github.com/storytold/lightcraft Copyright (c) 2026 ArtCraft Team and the LightCraft contributors. diff --git a/README.md b/README.md index 024d28593..d638b5ff6 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = "` form on craft-xml elements, value codecs and the package writer; and InDesign Tagged Text, read and written. +- [`craft-ical`](crates/ical/README.md): iCalendar (RFC 5545) building blocks, from MailCraft: content + lines, DATE/DATE-TIME values, durations, TEXT escaping, the common subset of recurrence rules, + and `VTIMEZONE` definitions read and written. No time-zone database; what events and to-dos + mean stays in each app. Bounded and panic-free on hostile input. +- [`craft-stream-codecs`](crates/stream-codecs/README.md): byte-stream and bi-level image codecs that + PDF, PostScript and TIFF share: LZW, ASCII85, ASCIIHex, RunLength, TIFF and PNG predictors, + CCITT Group 3 and 4 decoding and Group 4 encoding, JBIG2 decoding and lossless encoding. Every + decoder is bounded and returns its partial output on damage. From PdfCraft; a PDF filter chain + is built on it in `craft-pdf`. - [`craft-timeline`](crates/timeline/README.md): editorial timeline interchange: exact media time and SMPTE timecode, import/export reports, media path and `file://` URL handling, Avid Log Exchange (ALE) and CMX 3600 EDL documents, format detection. From FilmCraft. +- [`craft-metadata`](crates/metadata/README.md): photo metadata, from LightCraft: EXIF (read and write, + maker-note lens and focus point, every tag by name), IPTC-IIM, XMP packets (read, write, and a merge + that keeps what another program wrote), GPX track logs, and the blocks that carry them in JPEG, PNG, + WebP, TIFF-based, RAF and CR3 files. One `Metadata` model for all of them. Built on `craft-tiff`. - [`craft-tiff`](crates/tiff/README.md): TIFF and BigTIFF IFD reader and writer, from LightCraft: every field type, the IFD chain, SubIFDs and Exif/GPS/Interop pointer IFDs, maker-note IFDs (Canon, Nikon, Sony, Fujifilm, Olympus, Panasonic, Pentax), strip and tile layout. Bounded and @@ -133,9 +193,17 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = "`/`` instances and the CSS cascade as Bézier paths in millimetres, each tagged by the caller); `color` parses CSS colours; `write` writes documents - (elements with escaping, path data, numbers). + (elements with escaping, path data, numbers). Feature `tree`: the full parser, usvg at the one + version every Craft app uses, re-exported behind an entry point that runs those checks first + (plus nesting with references followed, attribute counts, bounded embedded SVGs), and a budget + check for drawing a tree with resvg. Apps take usvg from here, not as their own dependency. - [`craft-svg-paths`](crates/svg-paths/src/lib.rs): the former name of `craft-svg`'s `paths`, `color` and `write`; re-exports them for existing users. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds @@ -212,6 +301,11 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = "` shape (`request`, `execute`, `commands`, `docInspect`, `uiInspect`, `screenshot`) over the app's JSON control channel. - [`craft-web-host`](crates/web-host/README.md): the host messages between a Craft app's web build and the page that hosts it (`?host=parent` or `data-host="page"`): one contract and one bridge for every app. +- [`craft-webp`](crates/webp/src/lib.rs): the WebP container, from EffectCraft (reader) and + PhotoCraft (writer): canvas size, alpha and every animation frame's timing from the chunk + headers without decoding, and the RIFF container around an encoded VP8 frame with alpha, ICC, + EXIF and XMP chunks. The VP8 and VP8L codecs are not part of it. - [`craft-xls`](crates/xls/README.md): clean-room Excel 97-2003 workbook (`.xls`, BIFF8) reader: worksheets, cell values, formulas as A1 text (shared and array formulas included), cell formats with resolved palette colours, merged cells, column and row records, defined names, print areas and calculation settings, with limits on records, cells and text. +- [`craft-wordmodel`](crates/wordmodel/README.md): a word-processing document model (stories, paragraphs, + runs, tables, sections, styles, numbering, fields, notes, comments, revisions, drawings, math): what the + text-format crates read into and write from. WordCraft's model without its editing code. +- [`craft-xlsx`](crates/xlsx/README.md): Excel workbooks (`.xlsx`, `.xlsm`, SpreadsheetML, transitional and strict) and binary workbooks (`.xlsb`) on `craft-opc`: the workbook part, shared strings, the styles tables and worksheet rows streamed one at a time, with limits on the package, the XML and the binary records. +- [`craft-ora`](crates/ora/README.md): OpenRaster documents (`.ora`): the ZIP archive and the `stack.xml` layer tree as written, read with bounded sizes and written. From PhotoCraft. +- [`craft-y4m`](crates/y4m/src/lib.rs): YUV4MPEG2 (`.y4m`) reader, from FilmCraft: the stream + header, colour space layouts at 8 to 16 bits, a frame index built from the `FRAME` lines without + loading the file, and plane access. Bounded on hostile input. +- [`craft-kra`](crates/kra/README.md): Krita documents (`.kra`, `.krz`), read: the ZIP archive, the `maindoc.xml` node tree as written, and the tiled pixel files with their LZF compression, a tile at a time. From PhotoCraft. +- [`craft-xcf`](crates/xcf/README.md): GIMP XCF images (`.xcf`, `.xcf.gz`), read: header, properties, parasites, layers with their item paths, channels, and tiled pixels (uncompressed, RLE, zlib) at every precision, under a caller's byte budget. From PhotoCraft. - [`craft-xml`](crates/xml/README.md): bounded XML for hostile input: an owned element tree with limits on size, depth, nodes and attributes, streaming of repeated elements, namespace handling (as written, by local name, or canonical prefixes by URI), escaping and a writer. No DTDs and no entity expansion. +- [`craft-zip`](crates/zip/README.md): ZIP archives from untrusted files: an entry-count check before the archive is indexed (ZIP64 included), entry reads within per-entry and total budgets that count real bytes, duplicate-name detection, a strict structure preflight, and a deterministic stored/deflate writer. The shared ZIP layer for the package formats. - [Shared UI component audit](docs/ui-components-audit.md): source inventory, extraction priorities and compatibility boundaries across the Craft suite. - [Theme infrastructure](docs/theme-infrastructure.md): eight-app comparison and the small shared diff --git a/crates/aaf/Cargo.toml b/crates/aaf/Cargo.toml new file mode 100644 index 000000000..397032961 --- /dev/null +++ b/crates/aaf/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "craft-aaf" +description = "Clean-room AAF (Edit Protocol, structured storage) and OMF Interchange 2.0 (Bento) readers and writers over one mob-style composition model, with embedded PCM essence." +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-timeline = { workspace = true } +# WAV and AIFF around embedded PCM essence: the one WAV/AIFF implementation, not a second one here. +craft-audio = { workspace = true, features = ["decode-native", "pcm-encode"] } +thiserror = { workspace = true } diff --git a/crates/aaf/README.md b/crates/aaf/README.md new file mode 100644 index 000000000..7d3d44767 --- /dev/null +++ b/crates/aaf/README.md @@ -0,0 +1,67 @@ +# craft-aaf + +AAF and OMF, the two mob-based editorial interchange formats, read and written through one +composition model. + +| Module | What | +|---|---| +| `model` | `Document`: compositions (tracks of fillers, source clips and overlapping transitions; clip gain, constant or keyframed; markers; start timecode), nested compositions, and the media `Source`s they reference (file path or embedded PCM, picture size and rate, sound channels / rate / bits, start timecode, markers). Times are exact `craft_timeline::time::Tick`s. | +| `aaf` | `read`, `write`, `sniff`: AAF Edit Protocol in structured storage (`craft-cfb`). | +| `omf` | `read`, `write`, `sniff`: OMF Interchange 2.0 in a Bento container. Sound only. | + +No file I/O: documents are bytes and media references are strings. An application maps its own +timeline onto `model` once and gets both formats. Embedded audio is PCM in the model; the WAVE and +AIFF wrappers the formats use come from `craft-audio`. + +## Specifications + +Clean-room: written from public specifications only. The AAF SDK, pyaaf2, the OMF Toolkit and +other implementations were not consulted. Where a specification leaves a layout open (how a +nested sequence is written, how several video tracks share a slot), what Premiere Pro does was +read off files it exports. + +| Format | Document | Edition | Used for | +|---|---|---|---| +| AAF | AMWA *AAF Object Specification* | v1.1 (2005) | classes, properties, mob / slot / segment model, sequences and transitions, operation groups, parameters, definitions, descriptors, locators, essence data | +| AAF | AMWA *AAF Low-Level Container Specification* | v1.0.1 | objects as structured storages, `properties` streams, stored forms, strong / weak reference collections and their index streams, `referenced properties` | +| AAF | AMWA *AAF Edit Protocol* | v1.0 (AMWA AS-01) | top-level composition, mob chains (composition → master → file → physical source), operation definitions, usage codes | +| AAF | SMPTE RP 224 / RP 210 registers | — | data definition, class and type labels | +| AAF | Microsoft [MS-CFB] | rev. 10.0 | the container, see `craft-cfb` | +| OMF | Avid *OMF Interchange Specification* | Version 2.0 (1997) | classes (`HEAD`, `CMOB`, `MMOB`, `SMOB`, `MSLT`, `TRKD`, `SEQU`, `SCLP`, `FILL`, `TRAN`, `EFFE`, `ESLT`, `CVAL`, `VVAL`, `TCCP`, `WAVD`, `AIFD`, `WAVE`, `AIFC`, locators), property and type names | +| OMF | Apple *Bento Specification* | revision 1.0d5 | container label, TOC encoding, objects / properties / types, references | + +## What is read and written + +AAF: a top-level composition mob with a timecode slot, a timeline slot per track (sequences of +fillers, source clips and transitions; `VideoDissolve`, `VideoFadeToBlack`, `SMPTEVideoWipe`, +`MonoAudioDissolve`), clip gain as a `MonoAudioGain` operation group with a constant or varying +amplitude, markers as comment markers in an event slot, a composition mob for every nested +composition, and per media item a master mob, file source mobs (CDCI or PCM descriptor with a +network locator, or `EssenceData` with embedded PCM) and a tape source mob with the start +timecode. The reader also takes sequences inside sequences, selectors, essence groups, legacy data +definitions, and Premiere Pro's layout (all video tracks as layers of one slot, nested compositions +tagged top-level). 512-byte or 4096-byte sectors. + +OMF: a composition mob with a timecode slot and a sound slot per track, in samples; transitions as +`SimpleMonoAudioDissolve`; gain as `MonoAudioGain`; master, file (`WAVD` / `AIFD`, embedded `WAVE` +data or a locator) and tape mobs. + +Not represented: speed changes, video effects other than transitions, OMF picture and markers. + +Private tags, first written by FilmCraft and kept so existing files read back: AAF tagged values +`FilmCraft Effect`, `FilmCraft Frame Size`, `FilmCraft Audio Sample Rate`; OMF properties +`FilmCraft:SCLP:ClipName`, `FilmCraft:EFFE:EffectID`. + +## Hostile input + +A damaged or crafted file gives an error or a report entry, never a panic, a hang or an allocation +sized by a count in the file: weak-collection counts are checked against the index stream, zero-size +keys are refused, a storage owned twice is an error, nesting of segments and of compositions is +bounded, times are clamped to about three days. `src/aaf/hostile_tests.rs` and +`src/roundtrip_tests.rs` (truncation at every 97th byte, 400 random 8-byte corruptions per format) +cover them. + +## Origin + +Moved from FilmCraft's `filmcraft-interchange` (`aaf`, `omf`, the model types of `comp`). The +mapping between the model and an application's project stays in the application. diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs new file mode 100644 index 000000000..05894f94e --- /dev/null +++ b/crates/aaf/src/aaf.rs @@ -0,0 +1,84 @@ +//! AAF (Advanced Authoring Format) import and export, following the AAF Edit Protocol. +//! +//! Written from the public AMWA specifications: *AAF Object Specification v1.1*, *AAF Low-Level +//! Container Specification v1.0.1* (structured storage mapping, see [`store`]) and *AAF Edit +//! Protocol v1.0*; the container is Microsoft's Compound File Binary format ([`craft_cfb`]). +//! +//! A written file holds one top-level **CompositionMob** (Edit Protocol usage code +//! "top level") with +//! +//! - a timecode slot (sequence start timecode, rounded rate, drop frame), +//! - one timeline slot per video track (picture) and per audio track (sound; one per channel when +//! broken out to mono), each a **Sequence** of **Filler**s, **SourceClip**s and **Transition**s +//! (Cross Dissolve → `VideoDissolve_2`, Dip to Black → `VideoFadeToBlack`, audio crossfades → +//! `MonoAudioDissolve`; the model's transition name is kept in a tagged value), +//! - clip volume as a `MonoAudioGain` **OperationGroup** around the source clip with an +//! `Amplitude` **ConstantValue** or **VaryingValue** (keyframes as control points), +//! - sequence markers as **CommentMarker**s in an event slot; +//! +//! a **CompositionMob** without a usage code for every nested sequence, built the same way (a +//! clip of the nested sequence is a **SourceClip** that points at that mob, at its first slot of +//! the clip's kind, with its start in that slot's edit units; Premiere Pro writes nested sequences +//! this way); +//! +//! and for every media item a **MasterMob**, a file **SourceMob** per essence (a CDCI or PCM +//! descriptor with a network locator to the file, or `EssenceData` holding embedded PCM) and a +//! tape **SourceMob** carrying the media's start timecode. Clip and media markers become comment +//! markers on the master mob. +//! +//! Import reads the same structures (and the common variations: sequences inside sequences, +//! selectors, operation groups around clips, legacy data definitions, essence groups, and Premiere +//! Pro's one video slot holding a nested scope with a segment per video track) into the model: +//! compositions (one that others use is a nested composition), sources (with their path, or their +//! embedded audio as PCM) and markers. +//! +//! Private tags. Three tagged values are not in any register; they were first written by FilmCraft +//! and keep their names so that existing files read back: `FilmCraft Effect` (a transition's +//! name), `FilmCraft Frame Size` and `FilmCraft Audio Sample Rate` (on the composition). + +mod ids; +mod read; +pub(crate) mod store; +mod write; + +use crate::model::Document; +use crate::{Identity, Report, Result}; + +/// How to write an AAF file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct WriteOptions<'a> { + pub identity: Identity<'a>, + /// Write 512-byte sectors (compound file version 3) instead of 4096-byte sectors. + pub small_sectors: bool, +} + +/// Write `doc` as an AAF file: its first composition is the top-level one, with every nested +/// composition and every source it uses. Times that are not on whole edit units are rounded and +/// reported. +pub fn write(doc: &Document, opts: &WriteOptions<'_>, report: &mut Report) -> Result> { + let version = if opts.small_sectors { craft_cfb::Version::V3 } else { craft_cfb::Version::V4 }; + write::write(doc, version, &opts.identity, report) +} + +/// Read an AAF file: its top-level compositions, the compositions nested in them and their +/// sources. What cannot be represented is skipped and named in `report`. +pub fn read(bytes: &[u8], report: &mut Report) -> Result { + read::read(bytes, report) +} + +/// Whether `bytes` look like an AAF file (a compound file whose root has the AAF root class or a +/// `Header-2` storage). +pub fn sniff(bytes: &[u8]) -> bool { + if !craft_cfb::sniff(bytes) { + return false; + } + match craft_cfb::CompoundFile::open(bytes) { + Ok(cf) => cf.root().clsid == ids::ROOT || cf.find("Header-2").is_ok(), + Err(_) => false, + } +} + +#[cfg(test)] +mod hostile_tests; +#[cfg(test)] +mod tests; diff --git a/crates/aaf/src/aaf/hostile_tests.rs b/crates/aaf/src/aaf/hostile_tests.rs new file mode 100644 index 000000000..853b0000c --- /dev/null +++ b/crates/aaf/src/aaf/hostile_tests.rs @@ -0,0 +1,110 @@ +//! Hostile object trees: a crafted file must give an error, never a crash, a hang or an +//! allocation sized by a count in the file (AGENTS.md §0). + +use craft_cfb::{Version, Writer}; + +use super::store::{self, SF_STRONG_VECTOR, SF_WEAK_SET, SF_WEAK_VECTOR, Value, utf16z}; + +const PID: u16 = 0x0007; + +/// A root object whose one property `PID` is a weak reference vector or set (stored form `sf`) +/// named `Keys`, with `index` as its `Keys index` stream. +fn weak_collection_file(sf: u16, index: Vec) -> Vec { + let name = utf16z("Keys"); + // byte order 'L', format version, 1 entry { pid, stored form, value length }, the value + let mut props = vec![0x4C, 0x20]; + for x in [1, PID, sf, name.len() as u16] { + props.extend_from_slice(&x.to_le_bytes()); + } + props.extend_from_slice(&name); + let mut w = Writer::new(Version::V3); + w.stream(Writer::ROOT, "properties", props).unwrap(); + w.stream(Writer::ROOT, "Keys index", index).unwrap(); + w.finish() +} + +/// A weak collection index: u32 count, u16 tag, u16 key pid, u8 key size, then the keys. +fn index(count: u32, size: u8, keys: &[u8]) -> Vec { + let mut v = count.to_le_bytes().to_vec(); + v.extend_from_slice(&0u16.to_le_bytes()); + v.extend_from_slice(&0x1B01u16.to_le_bytes()); + v.push(size); + v.extend_from_slice(keys); + v +} + +fn read_keys(sf: u16, index: Vec) -> Result>, String> { + match store::read(&weak_collection_file(sf, index))?.get(PID) { + Some(Value::WeakVec(_, _, keys)) => Ok(keys.clone()), + other => panic!("not a weak collection: {other:?}"), + } +} + +/// With a key size of 0 every key fits, so the count alone drove the loop: up to 4.29 billion +/// empty keys (about 100 GB) from a 9-byte index. A million is enough to show it, cheaply. +#[test] +fn zero_size_weak_collection_keys_are_an_error() { + for sf in [SF_WEAK_VECTOR, SF_WEAK_SET] { + match read_keys(sf, index(1_000_000, 0, &[])) { + Err(e) => assert!(e.contains("zero-size"), "{e}"), + Ok(keys) => panic!("read {} empty keys instead of an error", keys.len()), + } + } +} + +#[test] +fn weak_collection_count_beyond_the_index_is_an_error() { + for sf in [SF_WEAK_VECTOR, SF_WEAK_SET] { + let e = read_keys(sf, index(u32::MAX, 4, &[1, 2, 3, 4, 5, 6, 7, 8])).unwrap_err(); + assert!(e.contains("short weak collection index"), "{e}"); + } +} + +#[test] +fn weak_collections_within_the_index_are_read() { + for sf in [SF_WEAK_VECTOR, SF_WEAK_SET] { + assert_eq!(read_keys(sf, index(0, 0, &[])).unwrap(), Vec::>::new()); + assert_eq!(read_keys(sf, index(2, 4, &[1, 2, 3, 4, 5, 6, 7, 8])).unwrap(), [vec![1, 2, 3, 4], vec![5, 6, 7, 8]]); + } +} + +/// A strong vector whose entries all name the same child storage would rebuild that subtree once +/// per entry; a storage has one owner, so the repeat is an error. +#[test] +fn a_storage_owned_twice_is_an_error() { + let name = utf16z("Items"); + let mut props = vec![0x4C, 0x20]; + for x in [1, PID, SF_STRONG_VECTOR, name.len() as u16] { + props.extend_from_slice(&x.to_le_bytes()); + } + props.extend_from_slice(&name); + // count, next free key, last key, then the entry keys + let mut idx = 3u32.to_le_bytes().to_vec(); + idx.extend_from_slice(&[0; 8]); + for _ in 0..3 { + idx.extend_from_slice(&1u32.to_le_bytes()); + } + let mut w = Writer::new(Version::V3); + w.stream(Writer::ROOT, "properties", props).unwrap(); + w.stream(Writer::ROOT, "Items index", idx).unwrap(); + let child = w.storage(Writer::ROOT, "Items{1}", [0; 16]).unwrap(); + w.stream(child, "properties", vec![0x4C, 0x20, 0, 0]).unwrap(); + let e = store::read(&w.finish()).unwrap_err(); + assert!(e.contains("more than one reference"), "{e}"); +} + +/// Objects nest through strong references; a chain deeper than the reader follows is an error, +/// and one within it reads. +#[test] +fn objects_nested_too_deeply_are_an_error() { + let chain = |depth: usize| { + let mut o = store::Obj::new([1; 16]); + for _ in 0..depth { + o = store::Obj::new([1; 16]).with(PID, Value::Strong(Box::new(o))); + } + store::write(&o, Version::V4).unwrap() + }; + assert!(store::read(&chain(150)).is_ok()); + let e = store::read(&chain(250)).unwrap_err(); + assert!(e.contains("nested too deeply"), "{e}"); +} diff --git a/crates/aaf/src/aaf/ids.rs b/crates/aaf/src/aaf/ids.rs new file mode 100644 index 000000000..70a184060 --- /dev/null +++ b/crates/aaf/src/aaf/ids.rs @@ -0,0 +1,262 @@ +//! Class ids, property ids and definition ids of the AAF object model subset read and +//! writes (AAF Object Specification v1.1, AAF Edit Protocol). Class and data definition AUIDs are +//! SMPTE labels (RP 224 / RP 210 registers) in AUID byte order; property ids are the AAF / ST 377-1 +//! local tags. + +use super::store::Auid; + +/// AUID of a SMPTE universal label: the label's last 8 bytes become Data1–Data3 (stored +/// little-endian), its first 8 bytes Data4. +pub(crate) const fn ul(b: [u8; 16]) -> Auid { + [b[11], b[10], b[9], b[8], b[13], b[12], b[15], b[14], b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]] +} + +/// A GUID `{d1-d2-d3-d4}` in AUID byte order. +pub(crate) const fn guid(d1: u32, d2: u16, d3: u16, d4: [u8; 8]) -> Auid { + let a = d1.to_le_bytes(); + let b = d2.to_le_bytes(); + let c = d3.to_le_bytes(); + [a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d4[0], d4[1], d4[2], d4[3], d4[4], d4[5], d4[6], d4[7]] +} + +/// Class AUID: SMPTE label 06.0E.2B.34.02.06.01.01.0D.01.01.01.01.01.xx.00. +pub(crate) const fn class(xx: u8) -> Auid { + ul([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x06, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x01, 0x01, 0x01, xx, 0x00]) +} + +/// The root object's class (the storage class of the file's root). +pub(crate) const ROOT: Auid = guid(0xB3B398A5, 0x1C90, 0x11D4, [0x80, 0x53, 0x08, 0x00, 0x36, 0x21, 0x08, 0x04]); +/// The meta-dictionary (class 0x25 of the meta-model, 06.0E.2B.34.02.06.01.01.0D.01.01.01.02.25.00.00). +pub(crate) const META_DICTIONARY: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x06, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x01, 0x02, 0x25, 0x00, 0x00]); + +#[allow(dead_code)] +pub(crate) mod cls { + use super::class; + use crate::aaf::store::Auid; + pub const COMMENT_MARKER: Auid = class(0x08); + pub const FILLER: Auid = class(0x09); + pub const OPERATION_GROUP: Auid = class(0x0A); + pub const NESTED_SCOPE: Auid = class(0x0B); + pub const SCOPE_REFERENCE: Auid = class(0x0D); + pub const SELECTOR: Auid = class(0x0E); + pub const SEQUENCE: Auid = class(0x0F); + pub const SOURCE_CLIP: Auid = class(0x11); + pub const TIMECODE: Auid = class(0x14); + pub const TRANSITION: Auid = class(0x17); + pub const CONTENT_STORAGE: Auid = class(0x18); + pub const CONTROL_POINT: Auid = class(0x19); + pub const DATA_DEFINITION: Auid = class(0x1B); + pub const OPERATION_DEFINITION: Auid = class(0x1C); + pub const PARAMETER_DEFINITION: Auid = class(0x1D); + pub const CONTAINER_DEFINITION: Auid = class(0x20); + pub const INTERPOLATION_DEFINITION: Auid = class(0x21); + pub const DICTIONARY: Auid = class(0x22); + pub const ESSENCE_DATA: Auid = class(0x23); + pub const CDCI_DESCRIPTOR: Auid = class(0x28); + pub const TAPE_DESCRIPTOR: Auid = class(0x2E); + pub const HEADER: Auid = class(0x2F); + pub const IDENTIFICATION: Auid = class(0x30); + pub const NETWORK_LOCATOR: Auid = class(0x32); + pub const COMPOSITION_MOB: Auid = class(0x35); + pub const MASTER_MOB: Auid = class(0x36); + pub const SOURCE_MOB: Auid = class(0x37); + pub const EVENT_MOB_SLOT: Auid = class(0x39); + pub const TIMELINE_MOB_SLOT: Auid = class(0x3B); + pub const CONSTANT_VALUE: Auid = class(0x3D); + pub const VARYING_VALUE: Auid = class(0x3E); + pub const TAGGED_VALUE: Auid = class(0x3F); + pub const DESCRIPTIVE_MARKER: Auid = class(0x41); + pub const PCM_DESCRIPTOR: Auid = class(0x48); + pub const IMPORT_DESCRIPTOR: Auid = class(0x4A); + /// Classes with a `Locator` and media properties read as file descriptors. + pub const WAVE_DESCRIPTOR: Auid = class(0x2C); + pub const AIFC_DESCRIPTOR: Auid = class(0x26); + pub const SOUND_DESCRIPTOR: Auid = class(0x42); + pub const RGBA_DESCRIPTOR: Auid = class(0x29); + pub const MULTIPLE_DESCRIPTOR: Auid = class(0x44); +} + +/// Property ids. +#[allow(dead_code)] +pub(crate) mod pid { + // Root + pub const ROOT_META_DICTIONARY: u16 = 0x0001; + pub const ROOT_HEADER: u16 = 0x0002; + // MetaDictionary and MetaDefinition + pub const META_CLASS_DEFINITIONS: u16 = 0x0003; + pub const META_TYPE_DEFINITIONS: u16 = 0x0004; + pub const META_IDENTIFICATION: u16 = 0x0005; + // Header + pub const BYTE_ORDER: u16 = 0x3B01; + pub const LAST_MODIFIED: u16 = 0x3B02; + pub const CONTENT: u16 = 0x3B03; + pub const DICTIONARY: u16 = 0x3B04; + pub const VERSION: u16 = 0x3B05; + pub const IDENTIFICATION_LIST: u16 = 0x3B06; + pub const OBJECT_MODEL_VERSION: u16 = 0x3B07; + pub const OPERATIONAL_PATTERN: u16 = 0x3B09; + // Identification + pub const COMPANY_NAME: u16 = 0x3C01; + pub const PRODUCT_NAME: u16 = 0x3C02; + pub const PRODUCT_VERSION_STRING: u16 = 0x3C04; + pub const PRODUCT_ID: u16 = 0x3C05; + pub const DATE: u16 = 0x3C06; + pub const PLATFORM: u16 = 0x3C08; + pub const GENERATION_AUID: u16 = 0x3C09; + // ContentStorage + pub const MOBS: u16 = 0x1901; + pub const ESSENCE_DATA: u16 = 0x1902; + // Dictionary + pub const OPERATION_DEFINITIONS: u16 = 0x2603; + pub const PARAMETER_DEFINITIONS: u16 = 0x2604; + pub const DATA_DEFINITIONS: u16 = 0x2605; + pub const CONTAINER_DEFINITIONS: u16 = 0x2608; + pub const INTERPOLATION_DEFINITIONS: u16 = 0x2609; + // DefinitionObject + pub const IDENTIFICATION: u16 = 0x1B01; + pub const NAME: u16 = 0x1B02; + pub const DESCRIPTION: u16 = 0x1B03; + // OperationDefinition + pub const OPDEF_DATA_DEFINITION: u16 = 0x1E01; + pub const OPDEF_IS_TIME_WARP: u16 = 0x1E02; + pub const OPDEF_NUMBER_INPUTS: u16 = 0x1E07; + pub const OPDEF_PARAMETERS_DEFINED: u16 = 0x1E09; + // ParameterDefinition + pub const PARAMDEF_DISPLAY_UNITS: u16 = 0x1F03; + // Mob + pub const MOB_ID: u16 = 0x4401; + pub const MOB_NAME: u16 = 0x4402; + pub const SLOTS: u16 = 0x4403; + pub const MOB_LAST_MODIFIED: u16 = 0x4404; + pub const MOB_CREATION_TIME: u16 = 0x4405; + pub const MOB_USER_COMMENTS: u16 = 0x4406; + pub const USAGE_CODE: u16 = 0x4408; + // SourceMob + pub const ESSENCE_DESCRIPTION: u16 = 0x4701; + // MobSlot + pub const SLOT_ID: u16 = 0x4801; + pub const SLOT_NAME: u16 = 0x4802; + pub const SEGMENT: u16 = 0x4803; + pub const PHYSICAL_TRACK_NUMBER: u16 = 0x4804; + // TimelineMobSlot / EventMobSlot + pub const EDIT_RATE: u16 = 0x4B01; + pub const ORIGIN: u16 = 0x4B02; + pub const EVENT_EDIT_RATE: u16 = 0x4901; + // Component + pub const DATA_DEFINITION: u16 = 0x0201; + pub const LENGTH: u16 = 0x0202; + pub const COMPONENT_USER_COMMENTS: u16 = 0x0204; + // Sequence + pub const COMPONENTS: u16 = 0x1001; + // SourceReference / SourceClip + pub const SOURCE_ID: u16 = 0x1101; + pub const SOURCE_MOB_SLOT_ID: u16 = 0x1102; + pub const START_TIME: u16 = 0x1201; + // Event + pub const POSITION: u16 = 0x0601; + pub const COMMENT: u16 = 0x0602; + // Timecode + pub const TC_START: u16 = 0x1501; + pub const TC_FPS: u16 = 0x1502; + pub const TC_DROP: u16 = 0x1503; + // Transition + pub const OPERATION_GROUP: u16 = 0x1801; + pub const CUT_POINT: u16 = 0x1802; + // OperationGroup + pub const OPERATION: u16 = 0x0B01; + pub const INPUT_SEGMENTS: u16 = 0x0B02; + pub const PARAMETERS: u16 = 0x0B03; + // Selector / NestedScope + pub const SELECTED: u16 = 0x0F01; + pub const NESTED_SLOTS: u16 = 0x0C01; + // Parameter / ConstantValue / VaryingValue / ControlPoint + pub const PARAMETER_DEFINITION: u16 = 0x4C01; + pub const CONSTANT_VALUE: u16 = 0x4D01; + pub const INTERPOLATION: u16 = 0x4E01; + pub const POINT_LIST: u16 = 0x4E02; + pub const CP_VALUE: u16 = 0x1A02; + pub const CP_TIME: u16 = 0x1A03; + pub const CP_EDIT_HINT: u16 = 0x1A04; + // TaggedValue + pub const TAG_NAME: u16 = 0x5001; + pub const TAG_VALUE: u16 = 0x5003; + // EssenceDescriptor / FileDescriptor + pub const LOCATOR: u16 = 0x2F01; + pub const SAMPLE_RATE: u16 = 0x3001; + pub const FILE_LENGTH: u16 = 0x3002; + pub const CONTAINER_FORMAT: u16 = 0x3004; + pub const STORED_HEIGHT: u16 = 0x3202; + pub const STORED_WIDTH: u16 = 0x3203; + pub const FRAME_LAYOUT: u16 = 0x320C; + pub const VIDEO_LINE_MAP: u16 = 0x320D; + pub const IMAGE_ASPECT_RATIO: u16 = 0x320E; + pub const COMPONENT_WIDTH: u16 = 0x3301; + pub const HORIZONTAL_SUBSAMPLING: u16 = 0x3302; + pub const QUANTIZATION_BITS: u16 = 0x3D01; + pub const LOCKED: u16 = 0x3D02; + pub const AUDIO_SAMPLING_RATE: u16 = 0x3D03; + pub const CHANNELS: u16 = 0x3D07; + pub const AVERAGE_BPS: u16 = 0x3D09; + pub const BLOCK_ALIGN: u16 = 0x3D0A; + // NetworkLocator + pub const URL_STRING: u16 = 0x4001; + // EssenceData + pub const ESSENCE_MOB_ID: u16 = 0x2701; + pub const ESSENCE_STREAM: u16 = 0x2702; +} + +/// Data definitions (SMPTE RP 224 labels 06.0E.2B.34.04.01.01.01.01.03.02.xx.yy). +pub(crate) mod ddef { + use super::{guid, ul}; + use crate::aaf::store::Auid; + pub const PICTURE: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x01, 0x00, 0x00, 0x00]); + pub const SOUND: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00]); + pub const TIMECODE: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00]); + pub const DESCRIPTIVE_METADATA: Auid = ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x01, 0x10, 0x00, 0x00, 0x00]); + /// Pre-SMPTE ("legacy") data definitions written by older applications. + pub const LEGACY_PICTURE: Auid = guid(0x6F3C8CE1, 0x6CEF, 0x11D2, [0x80, 0x7D, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]); + pub const LEGACY_SOUND: Auid = guid(0x78E1EBE1, 0x6CEF, 0x11D2, [0x80, 0x7D, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]); + pub const LEGACY_TIMECODE: Auid = guid(0x7F275E81, 0x77E5, 0x11D2, [0x80, 0x7F, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]); +} + +/// Operation, parameter, interpolation and container definitions. +pub(crate) mod def { + use super::guid; + use crate::aaf::store::Auid; + const AV: [u8; 8] = [0x8A, 0x09, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]; + pub const VIDEO_DISSOLVE: Auid = guid(0x0C3BEA41, 0xFC05, 0x11D2, AV); + pub const VIDEO_FADE_TO_BLACK: Auid = guid(0x0C3BEA40, 0xFC05, 0x11D2, AV); + pub const SMPTE_VIDEO_WIPE: Auid = guid(0x0C3BEA43, 0xFC05, 0x11D2, AV); + pub const MONO_AUDIO_DISSOLVE: Auid = guid(0x0C3BEA44, 0xFC05, 0x11D2, AV); + const AG: [u8; 8] = [0x8A, 0x38, 0x00, 0x50, 0x04, 0x0E, 0xF7, 0xD2]; + pub const MONO_AUDIO_GAIN: Auid = guid(0x9D2EA893, 0x0968, 0x11D3, AG); + const PD: [u8; 8] = [0x8A, 0x4C, 0x00, 0x50, 0x04, 0x0E, 0xF7, 0xD2]; + pub const PARAM_LEVEL: Auid = guid(0xE4962320, 0x2267, 0x11D3, PD); + pub const PARAM_AMPLITUDE: Auid = guid(0xE4962321, 0x2267, 0x11D3, PD); + const IP: [u8; 8] = [0x80, 0xA9, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]; + pub const INTERP_LINEAR: Auid = guid(0x5B6C85A4, 0x0EDE, 0x11D3, IP); + pub const INTERP_CONSTANT: Auid = guid(0x5B6C85A5, 0x0EDE, 0x11D3, IP); + const CD: [u8; 8] = [0x80, 0x9B, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F]; + pub const CONTAINER_AAF: Auid = guid(0x4313B571, 0xD8BA, 0x11D2, CD); + pub const CONTAINER_EXTERNAL: Auid = guid(0x4313B572, 0xD8BA, 0x11D2, CD); + /// Type ids of indirect values (SMPTE RP 210 type labels). + pub const TYPE_RATIONAL: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x01, 0x04, 0x01, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]); + pub const TYPE_STRING: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x01, 0x04, 0x01, 0x01, 0x01, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00]); + /// Edit Protocol operational pattern (`AAFEditProtocol`) and mob usage codes (`Usage_TopLevel`), + /// as in the SMPTE Labels register. + pub const OP_EDIT_PROTOCOL: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x05, 0x0D, 0x01, 0x12, 0x01, 0x01, 0x00, 0x00, 0x00]); + pub const USAGE_TOP_LEVEL: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x02, 0x01, 0x01, 0x07, 0x00]); + /// The label FilmCraft 0.16 and earlier wrote as the top-level usage code (in no register). + /// Import reads it as top-level too. + pub const USAGE_TOP_LEVEL_OLD: Auid = super::ul([0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x05, 0x0D, 0x01, 0x12, 0x01, 0x02, 0x03, 0x00, 0x00]); +} + +/// Weak reference target paths (pids from the root object). +pub(crate) mod path { + use super::pid; + pub const DATA_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::DATA_DEFINITIONS]; + pub const OPERATION_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::OPERATION_DEFINITIONS]; + pub const PARAMETER_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::PARAMETER_DEFINITIONS]; + pub const INTERPOLATION_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::INTERPOLATION_DEFINITIONS]; + pub const CONTAINER_DEFS: [u16; 3] = [pid::ROOT_HEADER, pid::DICTIONARY, pid::CONTAINER_DEFINITIONS]; +} diff --git a/crates/aaf/src/aaf/read.rs b/crates/aaf/src/aaf/read.rs new file mode 100644 index 000000000..206c2ead3 --- /dev/null +++ b/crates/aaf/src/aaf/read.rs @@ -0,0 +1,722 @@ +//! AAF objects → composition model. + +use std::collections::{HashMap, HashSet}; + +use craft_timeline::time::{FrameRate, Tick}; + +use super::ids::{cls, ddef, def, pid}; +use super::store::{self, Auid, Obj, Value, rational_of, utf16_of}; +use crate::model::{CClip, CItem, CKind, CMarker, CTrack, CTransition, Composition, Document, Gain, Source, units_to_ticks}; +use crate::{Error, Report, Result}; + +type MobId = [u8; 32]; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum DataKind { + Picture, + Sound, + Timecode, + Other, +} + +fn data_kind(o: &Obj) -> DataKind { + match o.weak_key(pid::DATA_DEFINITION).and_then(|k| ::try_from(k).ok()) { + Some(k) if k == ddef::PICTURE || k == ddef::LEGACY_PICTURE => DataKind::Picture, + Some(k) if k == ddef::SOUND || k == ddef::LEGACY_SOUND => DataKind::Sound, + Some(k) if k == ddef::TIMECODE || k == ddef::LEGACY_TIMECODE => DataKind::Timecode, + Some(_) => DataKind::Other, + None => DataKind::Other, + } +} + +fn len_of(o: &Obj) -> i64 { + o.i64(pid::LENGTH).unwrap_or(0).max(0) +} + +/// The value of an indirect property: (type id, bytes). +fn indirect(d: &[u8]) -> Option<(Auid, &[u8])> { + if d.len() >= 17 && (d[0] == 0x4C || d[0] == 0x42) { + return Some((d[1..17].try_into().ok()?, &d[17..])); + } + if d.len() >= 16 { + return Some((d[..16].try_into().ok()?, &d[16..])); + } + None +} + +fn tagged_values(o: &Obj, p: u16) -> Vec<(String, String)> { + o.objs(p) + .iter() + .filter_map(|t| { + let name = t.string(pid::TAG_NAME)?; + let (ty, v) = indirect(t.data(pid::TAG_VALUE)?)?; + let value = if ty == def::TYPE_STRING || v.len() % 2 == 0 { utf16_of(v) } else { String::new() }; + Some((name, value)) + }) + .collect() +} + +fn indirect_f64(d: &[u8]) -> Option { + let (_, v) = indirect(d)?; + match v.len() { + 8 => rational_of(v).filter(|r| r.1 != 0).map(|(n, d)| n as f64 / d as f64), + 4 => Some(i32::from_le_bytes(v.try_into().ok()?) as f64), + _ => None, + } +} + +struct R<'a> { + report: &'a mut Report, + mobs: HashMap, + essence: HashMap, + doc: Document, + /// (file mob id, slot id, master key) → source index + sources: HashMap<(MobId, u32, String), usize>, + /// Composition mobs read as nested compositions: their index in `doc.nested`. + nests: HashMap, + /// The compositions being read, outermost first. + open: Vec, +} + +struct NestClip<'a> { + mob_id: MobId, + slot_id: u32, + rate: (i64, i64), + kind: CKind, + name: String, + mob: &'a Obj, +} + +/// Compositions nested deeper than this are read as gaps. +const MAX_NESTING: usize = 16; + +pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { + let root = store::read(bytes).map_err(|e| Error::Parse { format: "AAF", message: e })?; + let header = root.strong(pid::ROOT_HEADER).ok_or_else(|| Error::Parse { format: "AAF", message: "no header object".into() })?; + let content = header.strong(pid::CONTENT).ok_or_else(|| Error::Parse { format: "AAF", message: "no content storage".into() })?; + let mut mobs = HashMap::new(); + for m in content.objs(pid::MOBS) { + if let Some(id) = m.mob_id(pid::MOB_ID) { + mobs.insert(id, m); + } + } + let mut essence = HashMap::new(); + for e in content.objs(pid::ESSENCE_DATA) { + if let (Some(id), Some(d)) = (e.mob_id(pid::ESSENCE_MOB_ID), e.stream(pid::ESSENCE_STREAM)) { + essence.insert(id, d); + } + } + let mut r = R { report, mobs, essence, doc: Document::default(), sources: HashMap::new(), nests: HashMap::new(), open: Vec::new() }; + // Top-level compositions: those no other composition uses, among the ones tagged top-level + // when any are. (Premiere Pro tags a nested sequence's composition top-level too; it is still + // only a nested sequence.) Compositions that only use each other in a circle all count. The + // label older FilmCraft versions wrote for top-level counts as top-level too. + let comps: Vec<&Obj> = content.objs(pid::MOBS).iter().filter(|m| m.class == cls::COMPOSITION_MOB).collect(); + let mut referenced = HashSet::new(); + for c in &comps { + collect_refs(c, &mut referenced); + } + let is_top = |c: &&Obj| c.auid(pid::USAGE_CODE).is_some_and(|u| u == def::USAGE_TOP_LEVEL || u == def::USAGE_TOP_LEVEL_OLD); + let tagged_top: Vec<&Obj> = comps.iter().copied().filter(is_top).collect(); + let pool = if tagged_top.is_empty() { comps } else { tagged_top }; + let unused: Vec<&Obj> = pool.iter().copied().filter(|c| c.mob_id(pid::MOB_ID).is_none_or(|id| !referenced.contains(&id))).collect(); + let top = if unused.is_empty() { pool } else { unused }; + for c in top { + r.open.extend(c.mob_id(pid::MOB_ID)); + let comp = r.composition(c); + r.open.clear(); + r.doc.compositions.push(comp); + } + if r.doc.compositions.is_empty() { + return Err(Error::Empty); + } + Ok(r.doc) +} + +fn collect_refs(o: &Obj, out: &mut HashSet) { + if o.class == cls::SOURCE_CLIP + && let Some(id) = o.mob_id(pid::SOURCE_ID) + { + out.insert(id); + } + for (_, v) in &o.props { + match v { + Value::Strong(c) => collect_refs(c, out), + Value::StrongVec(v) | Value::StrongSet(v, _) => v.iter().for_each(|c| collect_refs(c, out)), + _ => {} + } + } +} + +fn rate_of(o: &Obj, p: u16) -> Option<(i64, i64)> { + o.rational(p).filter(|r| r.0 > 0 && r.1 > 0) +} + +impl R<'_> { + fn composition(&mut self, c: &Obj) -> Composition { + let name = c.string(pid::MOB_NAME).unwrap_or_else(|| "Sequence".into()); + let slots = c.objs(pid::SLOTS); + let pic_rate = slots + .iter() + .filter(|s| s.class == cls::TIMELINE_MOB_SLOT) + .find(|s| s.strong(pid::SEGMENT).is_some_and(|g| matches!(data_kind(g), DataKind::Picture | DataKind::Timecode))) + .and_then(|s| rate_of(s, pid::EDIT_RATE)) + .or_else(|| slots.iter().find_map(|s| rate_of(s, pid::EDIT_RATE))) + .unwrap_or((25, 1)); + let rate = FrameRate::new(pic_rate.0, pic_rate.1); + let tags = tagged_values(c, pid::MOB_USER_COMMENTS); + let tag = |n: &str| tags.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone()); + let (mut width, mut height) = tag("FilmCraft Frame Size") + .and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.trim().parse().ok()?, b.trim().parse().ok()?)))) + .unwrap_or((0, 0)); + let mut sample_rate = tag("FilmCraft Audio Sample Rate").and_then(|s| s.parse().ok()).unwrap_or(0u32); + let mut comp = Composition { + name, + rate, + sample_rate: 48_000, + width: 1920, + height: 1080, + start_tc: 0, + drop: false, + tracks: Vec::new(), + markers: Vec::new(), + }; + let (mut nv, mut na) = (0, 0); + for s in slots { + let Some(seg) = s.strong(pid::SEGMENT) else { continue }; + if s.class == cls::EVENT_MOB_SLOT { + let er = rate_of(s, pid::EVENT_EDIT_RATE).unwrap_or(pic_rate); + comp.markers.extend(markers_of(seg, er)); + continue; + } + let er = rate_of(s, pid::EDIT_RATE).unwrap_or(pic_rate); + let origin = s.i64(pid::ORIGIN).unwrap_or(0); + match data_kind(seg) { + DataKind::Timecode => { + if let Some(tc) = find_class(seg, cls::TIMECODE) { + comp.start_tc = tc.i64(pid::TC_START).unwrap_or(0); + comp.drop = tc.u8(pid::TC_DROP).unwrap_or(0) != 0; + } + } + kind @ (DataKind::Picture | DataKind::Sound) => { + let ckind = if kind == DataKind::Picture { CKind::Picture } else { CKind::Sound }; + if ckind == CKind::Sound && sample_rate == 0 && er.1 == 1 && er.0 >= 8000 { + sample_rate = er.0 as u32; + } + // Premiere Pro writes every video track into one slot: a nested scope with a + // segment per track, the lowest track first. (A scope whose last segment + // refers to the others is an effect over layers: one track, as before.) + let layers: Vec<&Obj> = if ckind == CKind::Picture && seg.class == cls::NESTED_SCOPE && !refers_to_scope(seg, 0) { + seg.objs(pid::NESTED_SLOTS).iter().collect() + } else { + Vec::new() + }; + let layered = !layers.is_empty(); + let whole = units_to_ticks(len_of(seg), er.0, er.1); + for layer in if layered { layers } else { vec![seg] } { + let mut items = self.segment(layer, er, ckind, 0); + if layered { + fit(&mut items, whole); + } + if origin > 0 { + // material before the origin is not shown + trim_front(&mut items, units_to_ticks(origin, er.0, er.1)); + } + let number = s.u32(pid::PHYSICAL_TRACK_NUMBER).unwrap_or(0); + let name = s.string(pid::SLOT_NAME).unwrap_or_default(); + let channels = if ckind == CKind::Sound { + items + .iter() + .filter_map(|i| match i { + CItem::Clip(c) => self.doc.sources.get(c.source).map(|s| s.channels), + _ => None, + }) + .max() + .unwrap_or(1) + .min(6) + } else { + 0 + }; + let n = if ckind == CKind::Picture { + nv += 1; + nv + } else { + na += 1; + na + }; + comp.tracks.push(CTrack { kind: ckind, name, number: if number > 0 && !layered { number } else { n }, channels, items }); + } + } + DataKind::Other => self.report.info("a slot of an unsupported data kind was skipped"), + } + } + if width == 0 { + // no size in the file: that of the first picture this composition shows, else of any + let own = comp.tracks.iter().filter(|t| t.kind == CKind::Picture).flat_map(|t| &t.items).find_map(|i| match i { + CItem::Clip(c) => self.doc.sources.get(c.source).filter(|s| s.kind == CKind::Picture && s.width > 0 && s.nested.is_none()), + _ => None, + }); + let pic = own.or_else(|| self.doc.sources.iter().find(|s| s.kind == CKind::Picture && s.width > 0)); + (width, height) = pic.map_or((1920, 1080), |p| (p.width, p.height)); + } + comp.width = width; + comp.height = height; + if sample_rate > 0 { + comp.sample_rate = sample_rate; + } + comp + } + + /// Items of a segment (a sequence or a single component). + fn segment(&mut self, seg: &Obj, rate: (i64, i64), kind: CKind, depth: usize) -> Vec { + if depth > 32 { + self.report.warn("segments nested too deeply were skipped"); + return vec![CItem::Filler(units_to_ticks(len_of(seg), rate.0, rate.1))]; + } + if seg.class == cls::SEQUENCE { + let mut out = Vec::new(); + for c in seg.objs(pid::COMPONENTS) { + out.extend(self.component(c, rate, kind, depth + 1)); + } + return out; + } + self.component(seg, rate, kind, depth + 1) + } + + fn component(&mut self, c: &Obj, rate: (i64, i64), kind: CKind, depth: usize) -> Vec { + let len = units_to_ticks(len_of(c), rate.0, rate.1); + match c.class { + x if x == cls::FILLER => vec![CItem::Filler(len)], + x if x == cls::SOURCE_CLIP => vec![self.clip(c, rate, kind, None)], + x if x == cls::SEQUENCE => self.segment(c, rate, kind, depth), + x if x == cls::TRANSITION => { + let cut = units_to_ticks(c.i64(pid::CUT_POINT).unwrap_or(0), rate.0, rate.1); + let og = c.strong(pid::OPERATION_GROUP); + let effect = og + .and_then(|o| tagged_values(o, pid::COMPONENT_USER_COMMENTS).into_iter().find(|(k, _)| k == "FilmCraft Effect").map(|(_, v)| v)) + .unwrap_or_else(|| { + let op = og.and_then(|o| o.weak_key(pid::OPERATION)).and_then(|k| ::try_from(k).ok()); + match (kind, op) { + (CKind::Sound, _) => "constant_power".into(), + (_, Some(o)) if o == def::VIDEO_FADE_TO_BLACK => "dip_to_black".into(), + (_, Some(o)) if o == def::SMPTE_VIDEO_WIPE => "wipe".into(), + _ => "cross_dissolve".into(), + } + }); + vec![CItem::Transition(CTransition { len, cut: cut.clamp(Tick::ZERO, len), effect })] + } + x if x == cls::OPERATION_GROUP => { + let op = c.weak_key(pid::OPERATION).and_then(|k| ::try_from(k).ok()); + let inputs = c.objs(pid::INPUT_SEGMENTS); + let Some(input) = inputs.first() else { + self.report.info("an effect without input was imported as a gap"); + return vec![CItem::Filler(len)]; + }; + let gain = if op == Some(def::MONO_AUDIO_GAIN) { + self.gain(c, len, rate) + } else { + self.report.warn("effects other than audio gain are not imported (their first input is used)"); + None + }; + let mut items = self.segment(input, rate, kind, depth); + // the operation's length rules + fit(&mut items, len); + if let Some(g) = gain { + match items.as_mut_slice() { + [CItem::Clip(cl)] => cl.gain = Some(g), + _ => self.report.warn("audio gain around several clips was not imported"), + } + } + items + } + x if x == cls::SELECTOR => match c.strong(pid::SELECTED) { + Some(s) => { + let mut items = self.segment(s, rate, kind, depth); + fit(&mut items, len); + items + } + None => vec![CItem::Filler(len)], + }, + x if x == cls::NESTED_SCOPE => match c.objs(pid::NESTED_SLOTS).last() { + Some(s) => { + let mut items = self.segment(s, rate, kind, depth); + fit(&mut items, len); + items + } + None => vec![CItem::Filler(len)], + }, + _ => { + self.report.info("an unsupported component was imported as a gap"); + vec![CItem::Filler(len)] + } + } + } + + fn gain(&mut self, og: &Obj, len: Tick, _rate: (i64, i64)) -> Option { + let p = og + .objs(pid::PARAMETERS) + .iter() + .find(|p| p.auid(pid::PARAMETER_DEFINITION) == Some(def::PARAM_AMPLITUDE)) + .or_else(|| og.objs(pid::PARAMETERS).first())?; + if p.class == cls::CONSTANT_VALUE { + return p.data(pid::CONSTANT_VALUE).and_then(indirect_f64).map(Gain::Constant); + } + if p.class == cls::VARYING_VALUE { + let linear = p.weak_key(pid::INTERPOLATION).and_then(|k| ::try_from(k).ok()) != Some(def::INTERP_CONSTANT); + let points: Vec<(Tick, f64)> = p + .objs(pid::POINT_LIST) + .iter() + .filter_map(|cp| { + let (n, d) = cp.rational(pid::CP_TIME).filter(|r| r.1 != 0)?; + let v = cp.data(pid::CP_VALUE).and_then(indirect_f64)?; + Some((Tick((len.0 as i128 * n as i128 / d as i128).clamp(-(1i128 << 56), 1i128 << 56) as i64), v)) + }) + .collect(); + return (!points.is_empty()).then_some(Gain::Varying { linear, points }); + } + None + } + + fn clip(&mut self, c: &Obj, rate: (i64, i64), kind: CKind, master_key: Option) -> CItem { + let len = units_to_ticks(len_of(c), rate.0, rate.1); + let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), rate.0, rate.1); + let name = tagged_values(c, pid::COMPONENT_USER_COMMENTS).into_iter().find(|(k, _)| k == "Clip Name").map(|(_, v)| v).unwrap_or_default(); + let (Some(id), Some(slot)) = (c.mob_id(pid::SOURCE_ID), c.u32(pid::SOURCE_MOB_SLOT_ID)) else { return CItem::Filler(len) }; + if id == [0; 32] { + return CItem::Filler(len); + } + if let Some(mob) = self.mobs.get(&id).copied().filter(|m| m.class == cls::COMPOSITION_MOB) { + return self.nest_clip(c, NestClip { mob, mob_id: id, slot_id: slot, rate, kind, name }); + } + match self.resolve(id, slot, start, kind, master_key, 0) { + Some((source, t)) => CItem::Clip(CClip { len, source, start: t, gain: None, name }), + None => CItem::Filler(len), + } + } + + /// A source clip that points at a composition: a nested sequence (Premiere Pro writes its + /// nested sequences this way). The composition is read once, however many clips use it. + fn nest_clip(&mut self, c: &Obj, clip: NestClip<'_>) -> CItem { + let NestClip { mob, mob_id: id, slot_id, rate, kind, name } = clip; + let len = units_to_ticks(len_of(c), rate.0, rate.1); + let index = match self.nests.get(&id) { + Some(&i) => i, + None => { + if self.open.contains(&id) || self.open.len() >= MAX_NESTING { + self.report.warn("a composition nested in itself or nested too deeply was imported as a gap"); + return CItem::Filler(len); + } + self.open.push(id); + let comp = self.composition(mob); + self.open.pop(); + let i = self.doc.nested.len(); + self.doc.nested.push(comp); + self.nests.insert(id, i); + i + } + }; + // the start counts edit units of the slot the clip points at + let slot_rate = + mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot_id)).and_then(|s| rate_of(s, pid::EDIT_RATE)).unwrap_or(rate); + let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), slot_rate.0, slot_rate.1); + let skey = (id, if kind == CKind::Picture { 0 } else { 1 }, "composition".to_string()); + let source = match self.sources.get(&skey) { + Some(&i) => i, + None => { + let Some(comp) = self.doc.nested.get(index) else { return CItem::Filler(len) }; + let length = comp + .tracks + .iter() + .map(|t| { + Tick(t.items.iter().fold(0i64, |a, i| { + if matches!(i, CItem::Transition(_)) { a.saturating_sub(i.len().0) } else { a.saturating_add(i.len().0) } + })) + }) + .max() + .unwrap_or(Tick::ZERO); + let channels = if kind == CKind::Sound { 2 } else { 0 }; + let s = Source { + key: format!("composition:{}", hex(&id)), + name: comp.name.clone(), + kind, + path: None, + channel: None, + channels, + file_channels: channels, + width: comp.width, + height: comp.height, + frame_rate: comp.rate, + sample_rate: comp.sample_rate, + bits: 16, + length, + offset: Tick::ZERO, + start_tc: None, + tc_rate: comp.rate, + embedded: None, + markers: Vec::new(), + nested: Some(index), + }; + let i = self.doc.sources.len(); + self.doc.sources.push(s); + self.sources.insert(skey, i); + i + } + }; + CItem::Clip(CClip { len, source, start, gain: None, name }) + } + + /// Follow a source reference to a file source mob: (source index, file time). + fn resolve(&mut self, id: MobId, slot_id: u32, start: Tick, kind: CKind, master_key: Option, depth: usize) -> Option<(usize, Tick)> { + if depth > 16 { + return None; + } + let Some(mob) = self.mobs.get(&id).copied() else { + self.report.warn("a clip references a mob that is not in the file (imported as a gap)"); + return None; + }; + let slot = mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot_id))?; + let rate = rate_of(slot, pid::EDIT_RATE).unwrap_or((25, 1)); + let seg = slot.strong(pid::SEGMENT)?; + if mob.class == cls::COMPOSITION_MOB { + self.report.warn("nested compositions are not supported (imported as gaps)"); + return None; + } + if mob.class == cls::MASTER_MOB { + let key = master_key.unwrap_or_else(|| hex(&id)); + let clip = first_clip(seg)?; + let inner = units_to_ticks(clip.i64(pid::START_TIME).unwrap_or(0), rate.0, rate.1); + let next = clip.mob_id(pid::SOURCE_ID)?; + let next_slot = clip.u32(pid::SOURCE_MOB_SLOT_ID)?; + if next == [0; 32] { + return None; + } + let markers = mob + .objs(pid::SLOTS) + .iter() + .filter(|s| s.class == cls::EVENT_MOB_SLOT) + .flat_map(|s| s.strong(pid::SEGMENT).map(|g| markers_of(g, rate_of(s, pid::EVENT_EDIT_RATE).unwrap_or(rate))).unwrap_or_default()) + .collect::>(); + let r = self.resolve(next, next_slot, start + inner, kind, Some(key), depth + 1)?; + let src = &mut self.doc.sources[r.0]; + if src.markers.is_empty() { + src.markers = markers; + } + if src.name.is_empty() + && let Some(n) = mob.string(pid::MOB_NAME) + { + src.name = n; + } + return Some(r); + } + // a source mob: file (has a file descriptor) or physical (tape / import) + let desc = mob.strong(pid::ESSENCE_DESCRIPTION); + let is_file = desc.is_some_and(|d| d.get(pid::SAMPLE_RATE).is_some() || d.get(pid::LOCATOR).is_some() || self.essence.contains_key(&id)); + if !is_file { + return None; + } + let key = master_key.unwrap_or_else(|| hex(&id)); + let skey = (id, slot_id, key.clone()); + if let Some(&i) = self.sources.get(&skey) { + return Some((i, start)); + } + let d = desc?; + let seg_kind = match data_kind(seg) { + DataKind::Picture => CKind::Picture, + DataKind::Sound => CKind::Sound, + _ => kind, + }; + let path = d.objs(pid::LOCATOR).iter().find_map(|l| l.string(pid::URL_STRING)).map(|u| craft_timeline::path::file_url_to_path(&u)); + let file_rate = rate_of(d, pid::SAMPLE_RATE).unwrap_or(rate); + let length = d + .i64(pid::FILE_LENGTH) + .map(|l| units_to_ticks(l, file_rate.0, file_rate.1)) + .unwrap_or_else(|| units_to_ticks(len_of(seg), rate.0, rate.1)); + let sound_slots = mob.objs(pid::SLOTS).iter().filter(|s| s.strong(pid::SEGMENT).is_some_and(|g| data_kind(g) == DataKind::Sound)).count(); + let file_channels = d.u32(pid::CHANNELS).unwrap_or(1).max(1); + let channel = (seg_kind == CKind::Sound && file_channels > 1 && sound_slots > 1) + .then(|| slot.u32(pid::PHYSICAL_TRACK_NUMBER).unwrap_or(slot_id).saturating_sub(1).min(file_channels - 1)); + let mut layout = d.u8(pid::FRAME_LAYOUT).unwrap_or(0); + if layout > 4 { + layout = 0; + } + let stored_h = d.u32(pid::STORED_HEIGHT).unwrap_or(0); + let fr = FrameRate::new(file_rate.0, file_rate.1); + // timecode from the physical source mob + let tc = first_clip(seg).and_then(|clip| { + let tid = clip.mob_id(pid::SOURCE_ID)?; + let tape = self.mobs.get(&tid)?; + let tslot = tape.objs(pid::SLOTS).iter().find_map(|s| { + let g = s.strong(pid::SEGMENT)?; + let t = find_class(g, cls::TIMECODE)?; + Some((t.i64(pid::TC_START).unwrap_or(0), t.u16(pid::TC_FPS).unwrap_or(25).max(1) as i64, rate_of(s, pid::EDIT_RATE))) + })?; + let off = units_to_ticks(clip.i64(pid::START_TIME).unwrap_or(0), rate.0, rate.1); + let tcr = tslot.2.map(|r| FrameRate::new(r.0, r.1)).unwrap_or_else(|| FrameRate::new(tslot.1, 1)); + Some((tslot.0 + tcr.frame_at(off), tcr)) + }); + let mut s = Source { + key, + name: mob.string(pid::MOB_NAME).unwrap_or_default(), + kind: seg_kind, + path, + channel, + channels: if channel.is_some() { 1 } else { file_channels }, + file_channels, + width: d.u32(pid::STORED_WIDTH).unwrap_or(0), + height: if matches!(layout, 1 | 3) { stored_h.saturating_mul(2) } else { stored_h }, + frame_rate: if seg_kind == CKind::Picture { fr } else { FrameRate::FPS_25 }, + sample_rate: d + .rational(pid::AUDIO_SAMPLING_RATE) + .filter(|r| r.1 > 0 && r.0 > 0) + .map(|r| (r.0 / r.1) as u32) + .unwrap_or(file_rate.0 as u32), + bits: d.u32(pid::QUANTIZATION_BITS).unwrap_or(16).clamp(8, 32) as u16, + length, + offset: Tick::ZERO, + start_tc: tc.map(|t| t.0), + tc_rate: tc.map(|t| t.1).unwrap_or(fr), + embedded: None, + markers: Vec::new(), + nested: None, + }; + if s.kind == CKind::Sound { + s.frame_rate = FrameRate::FPS_25; + if let Some(data) = self.essence.get(&id) { + s.embedded = Some(data.to_vec()); + // embedded essence may be a whole WAVE / AIFF file + if let Some((pcm, ch, sr, bits)) = crate::pcm::parse_wav(data) { + s.embedded = Some(pcm); + s.file_channels = ch as u32; + s.channels = if s.channel.is_some() { 1 } else { ch as u32 }; + s.sample_rate = sr; + s.bits = bits; + } + } + } + if s.kind == CKind::Picture && s.width == 0 { + s.width = 1920; + s.height = 1080; + } + let i = self.doc.sources.len(); + self.doc.sources.push(s); + self.sources.insert(skey, i); + Some((i, start)) + } +} + +/// Drop `t` from the front of a track's items (slot origin). +fn trim_front(items: &mut Vec, mut t: Tick) { + while t > Tick::ZERO && !items.is_empty() { + let l = items[0].len(); + if matches!(items[0], CItem::Transition(_)) { + items.remove(0); + continue; + } + if l <= t { + items.remove(0); + t -= l; + } else { + match &mut items[0] { + CItem::Filler(x) => *x -= t, + CItem::Clip(c) => { + c.len -= t; + c.start += t; + } + CItem::Transition(_) => {} + } + t = Tick::ZERO; + } + } +} + +/// Make the items exactly `len` long (an operation group / selector is as long as itself). +fn fit(items: &mut Vec, len: Tick) { + let total = Tick( + items.iter().fold(0i64, |a, i| if matches!(i, CItem::Transition(_)) { a.saturating_sub(i.len().0) } else { a.saturating_add(i.len().0) }), + ); + if total == len || items.is_empty() { + if items.is_empty() { + items.push(CItem::Filler(len)); + } + return; + } + if total < len { + items.push(CItem::Filler(len - total)); + return; + } + let mut excess = total - len; + while excess > Tick::ZERO { + match items.last_mut() { + Some(CItem::Filler(x)) | Some(CItem::Clip(CClip { len: x, .. })) if *x > excess => { + *x -= excess; + excess = Tick::ZERO; + } + Some(CItem::Transition(_)) => { + items.pop(); + } + Some(other) => { + excess -= other.len(); + items.pop(); + } + None => break, + } + } +} + +/// Whether anything inside `o` is a scope reference (a nested scope used as an effect's layers). +fn refers_to_scope(o: &Obj, depth: usize) -> bool { + if o.class == cls::SCOPE_REFERENCE { + return true; + } + if depth > 32 { + return false; + } + o.props.iter().any(|(_, v)| match v { + Value::Strong(c) => refers_to_scope(c, depth + 1), + Value::StrongVec(v) | Value::StrongSet(v, _) => v.iter().any(|c| refers_to_scope(c, depth + 1)), + _ => false, + }) +} + +fn first_clip(seg: &Obj) -> Option<&Obj> { + if seg.class == cls::SOURCE_CLIP { + return Some(seg); + } + if seg.class == cls::SEQUENCE { + return seg.objs(pid::COMPONENTS).iter().find_map(first_clip); + } + // essence group (choices 0x0501) / operation group inputs + seg.objs(0x0501).iter().find_map(first_clip).or_else(|| seg.objs(pid::INPUT_SEGMENTS).iter().find_map(first_clip)) +} + +fn find_class(seg: &Obj, class: Auid) -> Option<&Obj> { + if seg.class == class { + return Some(seg); + } + seg.objs(pid::COMPONENTS).iter().find_map(|c| find_class(c, class)) +} + +fn markers_of(seg: &Obj, rate: (i64, i64)) -> Vec { + let events: Vec<&Obj> = if seg.class == cls::SEQUENCE { seg.objs(pid::COMPONENTS).iter().collect() } else { vec![seg] }; + events + .into_iter() + .filter(|e| e.class == cls::COMMENT_MARKER || e.class == cls::DESCRIPTIVE_MARKER || e.get(pid::POSITION).is_some()) + .map(|e| { + let tags = tagged_values(e, pid::COMPONENT_USER_COMMENTS); + let tag = |n: &str| tags.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone()); + let comment = e.string(pid::COMMENT).unwrap_or_default(); + let start = units_to_ticks(e.i64(pid::POSITION).unwrap_or(0), rate.0, rate.1); + CMarker { + start, + duration: units_to_ticks(e.i64(pid::LENGTH).unwrap_or(0).max(0), rate.0, rate.1), + name: tag("Name").unwrap_or_else(|| comment.clone()), + comment: tag("Comment").unwrap_or_else(|| if tags.is_empty() { String::new() } else { comment.clone() }), + color: tag("Color"), + } + }) + .collect() +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} diff --git a/crates/aaf/src/aaf/store.rs b/crates/aaf/src/aaf/store.rs new file mode 100644 index 000000000..46ab95dae --- /dev/null +++ b/crates/aaf/src/aaf/store.rs @@ -0,0 +1,538 @@ +//! AAF objects in structured storage (the AAF Low-Level Container Specification): every object +//! is a storage whose class id is the object's class AUID, holding a `properties` stream; strong +//! references are child storages, collections have an index stream, weak references name a key +//! in a target collection through the root's `referenced properties` table. +//! +//! `properties` stream (little-endian): +//! +//! ```text +//! u8 byte order (0x4C 'L') u8 format version (0x20) u16 entry count +//! entry count × { u16 pid, u16 stored form, u16 value length } the values, in entry order +//! ``` +//! +//! | stored form | value | +//! |---|---| +//! | 0x82 data | the property's bytes | +//! | 0x22 strong reference | UTF-16 name of the child storage | +//! | 0x32 strong reference vector | UTF-16 collection name; storages `name{key}`, stream `name index`: u32 count, u32 first free key, u32 last free key, count × u32 local key | +//! | 0x3A strong reference set | as a vector; the index adds u16 key pid, u8 key size, and each entry is u32 local key, u32 reference count, key bytes | +//! | 0x02 weak reference | u16 referenced-property tag, u16 key pid, u8 key size, key bytes | +//! | 0x12 / 0x1A weak reference vector / set | UTF-16 collection name; stream `name index`: u32 count, u16 tag, u16 key pid, u8 key size, count × key | +//! | 0x42 data stream | u8 byte order, UTF-16 name of the stream | +//! +//! `referenced properties` (root stream): u8 byte order, u16 path count, u32 pid count, then the +//! pids of each path (from the root object) terminated by a 0 pid. + +use craft_cfb::{CompoundFile, EntryKind, NodeId, Version, Writer}; + +pub(crate) type Auid = [u8; 16]; + +pub(crate) const SF_DATA: u16 = 0x82; +pub(crate) const SF_DATA_STREAM: u16 = 0x42; +pub(crate) const SF_STRONG: u16 = 0x22; +pub(crate) const SF_STRONG_VECTOR: u16 = 0x32; +pub(crate) const SF_STRONG_SET: u16 = 0x3A; +pub(crate) const SF_WEAK: u16 = 0x02; +pub(crate) const SF_WEAK_VECTOR: u16 = 0x12; +pub(crate) const SF_WEAK_SET: u16 = 0x1A; + +const BYTE_ORDER_LE: u8 = 0x4C; +const FORMAT_VERSION: u8 = 0x20; + +/// A property value. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Value { + Data(Vec), + Strong(Box), + StrongVec(Vec), + /// Objects keyed by the data property `key_pid` of each. + StrongSet(Vec, u16), + /// (path of pids from the root to the target collection, key pid, key) + Weak(Vec, u16, Vec), + WeakVec(Vec, u16, Vec>), + Stream(Vec), +} + +/// An AAF object: its class and properties. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Obj { + pub class: Auid, + pub props: Vec<(u16, Value)>, +} + +impl Obj { + pub fn new(class: Auid) -> Obj { + Obj { class, props: Vec::new() } + } + pub fn set(&mut self, pid: u16, v: Value) -> &mut Obj { + match self.props.iter_mut().find(|(p, _)| *p == pid) { + Some(slot) => slot.1 = v, + None => self.props.push((pid, v)), + } + self + } + pub fn with(mut self, pid: u16, v: Value) -> Obj { + self.set(pid, v); + self + } + pub fn data_prop(mut self, pid: u16, d: Vec) -> Obj { + self.set(pid, Value::Data(d)); + self + } + pub fn get(&self, pid: u16) -> Option<&Value> { + self.props.iter().find(|(p, _)| *p == pid).map(|(_, v)| v) + } + pub fn data(&self, pid: u16) -> Option<&[u8]> { + match self.get(pid)? { + Value::Data(d) => Some(d), + _ => None, + } + } + pub fn strong(&self, pid: u16) -> Option<&Obj> { + match self.get(pid)? { + Value::Strong(o) => Some(o), + _ => None, + } + } + /// Elements of a strong vector or set (empty when absent). + pub fn objs(&self, pid: u16) -> &[Obj] { + match self.get(pid) { + Some(Value::StrongVec(v)) | Some(Value::StrongSet(v, _)) => v, + _ => &[], + } + } + pub fn weak_key(&self, pid: u16) -> Option<&[u8]> { + match self.get(pid)? { + Value::Weak(_, _, k) => Some(k), + _ => None, + } + } + pub fn stream(&self, pid: u16) -> Option<&[u8]> { + match self.get(pid)? { + Value::Stream(d) => Some(d), + _ => None, + } + } + pub fn u8(&self, pid: u16) -> Option { + self.data(pid).and_then(|d| d.first().copied()) + } + pub fn u16(&self, pid: u16) -> Option { + self.data(pid).filter(|d| d.len() >= 2).map(|d| u16::from_le_bytes([d[0], d[1]])) + } + pub fn u32(&self, pid: u16) -> Option { + self.data(pid).filter(|d| d.len() >= 4).map(|d| u32::from_le_bytes([d[0], d[1], d[2], d[3]])) + } + pub fn i64(&self, pid: u16) -> Option { + let d = self.data(pid)?; + match d.len() { + 8.. => Some(i64::from_le_bytes(d[..8].try_into().ok()?)), + 4..=7 => Some(i32::from_le_bytes(d[..4].try_into().ok()?) as i64), + _ => None, + } + } + pub fn rational(&self, pid: u16) -> Option<(i64, i64)> { + self.data(pid).and_then(rational_of) + } + pub fn string(&self, pid: u16) -> Option { + self.data(pid).map(utf16_of) + } + pub fn auid(&self, pid: u16) -> Option { + self.data(pid).and_then(|d| d.get(..16)).and_then(|d| d.try_into().ok()) + } + pub fn mob_id(&self, pid: u16) -> Option<[u8; 32]> { + self.data(pid).and_then(|d| d.get(..32)).and_then(|d| d.try_into().ok()) + } +} + +pub(crate) fn rational_of(d: &[u8]) -> Option<(i64, i64)> { + (d.len() >= 8).then(|| (i32::from_le_bytes([d[0], d[1], d[2], d[3]]) as i64, i32::from_le_bytes([d[4], d[5], d[6], d[7]]) as i64)) +} + +pub(crate) fn rational(num: i64, den: i64) -> Vec { + let mut v = (num.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_le_bytes().to_vec(); + v.extend_from_slice(&(den.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_le_bytes()); + v +} + +/// UTF-16LE with a terminating NUL. +pub(crate) fn utf16z(s: &str) -> Vec { + let mut v: Vec = s.encode_utf16().flat_map(u16::to_le_bytes).collect(); + v.extend_from_slice(&[0, 0]); + v +} + +pub(crate) fn utf16_of(d: &[u8]) -> String { + let u: Vec = d.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&c| c != 0).collect(); + String::from_utf16_lossy(&u) +} + +/// Short property names used to name storages and streams (any name is valid: readers follow +/// the names stored in the property values). +fn prop_name(pid: u16) -> &'static str { + match pid { + 0x0001 => "MetaDictionary", + 0x0002 => "Header", + 0x0003 => "ClassDefinitions", + 0x0004 => "TypeDefinitions", + 0x3B03 => "Content", + 0x3B04 => "Dictionary", + 0x3B06 => "IdentificationList", + 0x1901 => "Mobs", + 0x1902 => "EssenceData", + 0x2603 => "OperationDefinitions", + 0x2604 => "ParameterDefinitions", + 0x2605 => "DataDefinitions", + 0x2607 => "CodecDefinitions", + 0x2608 => "ContainerDefinitions", + 0x2609 => "InterpolationDefs", + 0x4403 => "Slots", + 0x4406 => "UserComments", + 0x4803 => "Segment", + 0x1001 => "Components", + 0x1801 => "OperationGroup", + 0x0B02 => "InputSegments", + 0x0B03 => "Parameters", + 0x4E02 => "PointList", + 0x4701 => "EssenceDescription", + 0x2F01 => "Locator", + 0x2702 => "Data", + 0x0204 => "ComponentComments", + 0x1E09 => "ParametersDefined", + _ => "Property", + } +} + +/// The key size of a strong reference set keyed by `key_pid`, for a set with no entry to take it +/// from: AUIDs (definitions) are 16 bytes, MobIDs 32. +fn set_key_size(key_pid: u16) -> usize { + match key_pid { + 0x0005 | 0x1B01 => 16, + 0x4401 | 0x2701 => 32, + _ => 0, + } +} + +fn storage_name(pid: u16) -> String { + let suffix = format!("-{pid:x}"); + let name: String = prop_name(pid).chars().take(22 - suffix.len()).collect(); + format!("{name}{suffix}") +} + +/// Errors while reading the object tree. +fn bad(s: impl Into) -> String { + s.into() +} + +// --------------------------------------------------------------------------------------------- +// Writing +// --------------------------------------------------------------------------------------------- + +struct W { + cfb: Writer, + paths: Vec>, +} + +/// Serialise `root` (the Root object: MetaDictionary 0x0001, Header 0x0002) into a compound file. +pub(crate) fn write(root: &Obj, version: Version) -> Result, String> { + let mut w = W { cfb: Writer::new(version), paths: Vec::new() }; + w.obj(Writer::ROOT, root)?; + let mut rp = vec![BYTE_ORDER_LE]; + rp.extend_from_slice(&(w.paths.len() as u16).to_le_bytes()); + let n: usize = w.paths.iter().map(|p| p.len() + 1).sum(); + rp.extend_from_slice(&(n as u32).to_le_bytes()); + for p in &w.paths { + for pid in p { + rp.extend_from_slice(&pid.to_le_bytes()); + } + rp.extend_from_slice(&0u16.to_le_bytes()); + } + w.cfb.stream(Writer::ROOT, "referenced properties", rp).map_err(|e| e.to_string())?; + Ok(w.cfb.finish()) +} + +impl W { + fn tag(&mut self, path: &[u16]) -> u16 { + match self.paths.iter().position(|p| p == path) { + Some(i) => i as u16, + None => { + self.paths.push(path.to_vec()); + (self.paths.len() - 1) as u16 + } + } + } + + fn obj(&mut self, node: NodeId, o: &Obj) -> Result<(), String> { + self.cfb.set_clsid(node, o.class); + let mut entries: Vec<(u16, u16, Vec)> = Vec::new(); + for (pid, v) in &o.props { + let pid = *pid; + let (sf, value) = match v { + Value::Data(d) => (SF_DATA, d.clone()), + Value::Strong(child) => { + let name = storage_name(pid); + let s = self.cfb.storage(node, &name, child.class).map_err(|e| e.to_string())?; + self.obj(s, child)?; + (SF_STRONG, utf16z(&name)) + } + Value::StrongVec(items) | Value::StrongSet(items, _) => { + let name = storage_name(pid); + let mut index = Vec::new(); + index.extend_from_slice(&(items.len() as u32).to_le_bytes()); + index.extend_from_slice(&(items.len() as u32).to_le_bytes()); // first free key + index.extend_from_slice(&u32::MAX.to_le_bytes()); // last free key + let set_key = if let Value::StrongSet(_, k) = v { Some(*k) } else { None }; + let key_size = set_key.map(|k| items.first().and_then(|i| i.data(k)).map_or_else(|| set_key_size(k), <[u8]>::len)).unwrap_or(0); + if let Some(k) = set_key { + index.extend_from_slice(&k.to_le_bytes()); + index.push(key_size as u8); + } + for (i, item) in items.iter().enumerate() { + let s = self.cfb.storage(node, &format!("{name}{{{i:x}}}"), item.class).map_err(|e| e.to_string())?; + self.obj(s, item)?; + index.extend_from_slice(&(i as u32).to_le_bytes()); + if let Some(k) = set_key { + index.extend_from_slice(&1u32.to_le_bytes()); + let mut key = item.data(k).unwrap_or(&[]).to_vec(); + key.resize(key_size, 0); + index.extend_from_slice(&key); + } + } + self.cfb.stream(node, &format!("{name} index"), index).map_err(|e| e.to_string())?; + (if set_key.is_some() { SF_STRONG_SET } else { SF_STRONG_VECTOR }, utf16z(&name)) + } + Value::Weak(path, key_pid, key) => { + let mut d = self.tag(path).to_le_bytes().to_vec(); + d.extend_from_slice(&key_pid.to_le_bytes()); + d.push(key.len() as u8); + d.extend_from_slice(key); + (SF_WEAK, d) + } + Value::WeakVec(path, key_pid, keys) => { + let name = storage_name(pid); + let tag = self.tag(path); + let size = keys.first().map_or(0, Vec::len); + let mut index = (keys.len() as u32).to_le_bytes().to_vec(); + index.extend_from_slice(&tag.to_le_bytes()); + index.extend_from_slice(&key_pid.to_le_bytes()); + index.push(size as u8); + for k in keys { + let mut k = k.clone(); + k.resize(size, 0); + index.extend_from_slice(&k); + } + self.cfb.stream(node, &format!("{name} index"), index).map_err(|e| e.to_string())?; + (SF_WEAK_VECTOR, utf16z(&name)) + } + Value::Stream(data) => { + let name = storage_name(pid); + self.cfb.stream(node, &name, data.clone()).map_err(|e| e.to_string())?; + let mut d = vec![BYTE_ORDER_LE]; + d.extend_from_slice(&utf16z(&name)); + (SF_DATA_STREAM, d) + } + }; + if value.len() > u16::MAX as usize { + return Err(format!("property {pid:#06x} is {} bytes (the limit is 65535)", value.len())); + } + entries.push((pid, sf, value)); + } + let mut props = vec![BYTE_ORDER_LE, FORMAT_VERSION]; + props.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + for (pid, sf, v) in &entries { + props.extend_from_slice(&pid.to_le_bytes()); + props.extend_from_slice(&sf.to_le_bytes()); + props.extend_from_slice(&(v.len() as u16).to_le_bytes()); + } + for (_, _, v) in &entries { + props.extend_from_slice(v); + } + self.cfb.stream(node, "properties", props).map_err(|e| e.to_string())?; + Ok(()) + } +} + +// --------------------------------------------------------------------------------------------- +// Reading +// --------------------------------------------------------------------------------------------- + +struct R<'a> { + cf: CompoundFile<'a>, + paths: Vec>, + objects: usize, + materialized_stream_bytes: usize, + /// Storages already read: a storage is owned by one parent, so a second strong reference to it + /// (which would rebuild its whole subtree again) is refused. + owned: std::collections::HashSet, + /// Bytes of weak-reference target paths copied into the tree so far. + path_bytes: usize, +} + +const MAX_DEPTH: usize = 200; +const MAX_OBJECTS: usize = 2_000_000; +const MAX_MATERIALIZED_STREAM_BYTES: usize = 256 << 20; +/// Each weak reference carries its own copy of its target path (real paths are a handful of +/// property ids); the copies together may not exceed this. +const MAX_PATH_BYTES: usize = 64 << 20; + +/// Parse the object tree of an AAF compound file (the root object). +pub(crate) fn read(bytes: &[u8]) -> Result { + let cf = CompoundFile::open(bytes).map_err(|e| e.to_string())?; + let mut paths = Vec::new(); + if let Ok(rp) = cf.read_path("referenced properties") + && rp.len() >= 7 + { + let count = u16::from_le_bytes([rp[1], rp[2]]) as usize; + let mut cur = Vec::new(); + for c in rp[7..].as_chunks::<2>().0 { + let pid = u16::from_le_bytes([c[0], c[1]]); + if pid == 0 { + paths.push(std::mem::take(&mut cur)); + if paths.len() == count { + break; + } + } else { + cur.push(pid); + } + } + } + let mut r = R { cf, paths, objects: 0, materialized_stream_bytes: 0, owned: Default::default(), path_bytes: 0 }; + r.obj(0, 0) +} + +fn rd_u16(b: &[u8], at: usize) -> Option { + b.get(at..at + 2).map(|s| u16::from_le_bytes([s[0], s[1]])) +} +fn rd_u32(b: &[u8], at: usize) -> Option { + b.get(at..at + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) +} + +impl R<'_> { + fn child(&self, parent: usize, name: &str) -> Result { + self.cf.child(parent, name).ok_or_else(|| bad(format!("missing storage or stream \"{name}\""))) + } + + fn stream(&mut self, parent: usize, name: &str) -> Result, String> { + let id = self.child(parent, name)?; + let data = self.cf.read(id).map_err(|e| e.to_string())?; + self.materialized_stream_bytes = self + .materialized_stream_bytes + .checked_add(data.len()) + .filter(|&n| n <= MAX_MATERIALIZED_STREAM_BYTES) + .ok_or_else(|| bad("AAF materialized stream data exceeds the memory limit"))?; + Ok(data) + } + + /// A copy of weak-reference path `tag`, counted against [`MAX_PATH_BYTES`]. + fn path(&mut self, tag: u16) -> Result, String> { + let path = self.paths.get(tag as usize).cloned().unwrap_or_default(); + self.path_bytes = self.path_bytes.saturating_add(path.len() * 2); + if self.path_bytes > MAX_PATH_BYTES { + return Err(bad("weak reference paths exceed the memory limit")); + } + Ok(path) + } + + fn obj(&mut self, entry: usize, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err(bad("objects nested too deeply")); + } + if !self.owned.insert(entry) { + return Err(bad("a storage is owned by more than one reference")); + } + self.objects += 1; + if self.objects > MAX_OBJECTS { + return Err(bad("too many objects")); + } + let e = self.cf.entry(entry).ok_or_else(|| bad("bad directory entry"))?; + if !matches!(e.kind, EntryKind::Root | EntryKind::Storage) { + return Err(bad(format!("\"{}\" is not a storage", e.name))); + } + let mut o = Obj::new(e.clsid); + let props = self.stream(entry, "properties")?; + if props.len() < 4 { + return Err(bad("short properties stream")); + } + if props[0] != BYTE_ORDER_LE { + return Err(bad("big-endian AAF files are not supported")); + } + let n = rd_u16(&props, 2).unwrap_or(0) as usize; + let mut at = 4 + n * 6; + if at > props.len() { + return Err(bad("truncated property index")); + } + for i in 0..n { + let (Some(pid), Some(sf), Some(len)) = (rd_u16(&props, 4 + i * 6), rd_u16(&props, 6 + i * 6), rd_u16(&props, 8 + i * 6)) else { + return Err(bad("truncated property index")); + }; + if o.props.iter().any(|(previous, _)| *previous == pid) { + return Err(bad("duplicate property id")); + } + let v = props.get(at..at + len as usize).ok_or_else(|| bad("truncated property value"))?; + at += len as usize; + let value = match sf { + SF_STRONG => { + let c = self.child(entry, &utf16_of(v))?; + Value::Strong(Box::new(self.obj(c, depth + 1)?)) + } + SF_STRONG_VECTOR | SF_STRONG_SET => { + let name = utf16_of(v); + let idx = self.stream(entry, &format!("{name} index"))?; + let count = rd_u32(&idx, 0).ok_or_else(|| bad("short collection index"))? as usize; + let mut items = Vec::new(); + if sf == SF_STRONG_VECTOR { + for k in 0..count { + let key = rd_u32(&idx, 12 + k * 4).ok_or_else(|| bad("short vector index"))?; + let c = self.child(entry, &format!("{name}{{{key:x}}}"))?; + items.push(self.obj(c, depth + 1)?); + } + Value::StrongVec(items) + } else { + let key_pid = rd_u16(&idx, 12).ok_or_else(|| bad("short set index"))?; + let key_size = *idx.get(14).ok_or_else(|| bad("short set index"))? as usize; + let stride = 8 + key_size; + for k in 0..count { + let key = rd_u32(&idx, 15 + k * stride).ok_or_else(|| bad("short set index"))?; + let c = self.child(entry, &format!("{name}{{{key:x}}}"))?; + items.push(self.obj(c, depth + 1)?); + } + Value::StrongSet(items, key_pid) + } + } + SF_WEAK => { + let (Some(tag), Some(key_pid), Some(&size)) = (rd_u16(v, 0), rd_u16(v, 2), v.get(4)) else { + return Err(bad("short weak reference")); + }; + let key = v.get(5..5 + size as usize).ok_or_else(|| bad("short weak reference"))?.to_vec(); + Value::Weak(self.path(tag)?, key_pid, key) + } + SF_WEAK_VECTOR | SF_WEAK_SET => { + let name = utf16_of(v); + let idx = self.stream(entry, &format!("{name} index"))?; + let (Some(count), Some(tag), Some(key_pid), Some(&size)) = (rd_u32(&idx, 0), rd_u16(&idx, 4), rd_u16(&idx, 6), idx.get(8)) else { + return Err(bad("short weak collection index")); + }; + let size = size as usize; + if count > 0 && size == 0 { + return Err(bad("zero-size weak collection key")); + } + // every key must lie in the index, so its length (not the count) bounds the loop + if (count as usize).checked_mul(size).and_then(|n| n.checked_add(9)).is_none_or(|end| end > idx.len()) { + return Err(bad("short weak collection index")); + } + let mut keys = Vec::new(); + for k in 0..count as usize { + keys.push(idx.get(9 + k * size..9 + (k + 1) * size).ok_or_else(|| bad("short weak collection index"))?.to_vec()); + } + Value::WeakVec(self.path(tag)?, key_pid, keys) + } + SF_DATA_STREAM => { + let name = utf16_of(v.get(1..).unwrap_or(&[])); + Value::Stream(self.stream(entry, &name)?) + } + _ => Value::Data(v.to_vec()), + }; + o.props.push((pid, value)); + } + Ok(o) + } +} diff --git a/crates/aaf/src/aaf/tests.rs b/crates/aaf/src/aaf/tests.rs new file mode 100644 index 000000000..2773fda6d --- /dev/null +++ b/crates/aaf/src/aaf/tests.rs @@ -0,0 +1,467 @@ +//! Structural checks of written AAF files against the required properties and rules of the AAF +//! Object Specification v1.1 and the Edit Protocol, read back through the compound file reader. + +use std::collections::HashSet; + +use craft_timeline::time::FrameRate; + +use super::ids::{self, cls, ddef, def, path, pid}; +use super::store::{self, Obj, Value}; +use super::*; +use crate::model::{CItem, CKind}; +use crate::testdoc::{IDENTITY, clip, composition, picture_and_sound_cut, source, track}; + +fn document() -> Document { + // two 48-frame clips from source frames 10 and 200, a 12-frame transition + picture_and_sound_cut(FrameRate::FPS_24, 48, 12, (10, 200)) +} + +fn written(doc: &Document, small_sectors: bool) -> Vec { + let mut report = Report::default(); + let bytes = write(doc, &WriteOptions { identity: IDENTITY, small_sectors }, &mut report).unwrap(); + assert!(!report.has_warnings(), "{report}"); + bytes +} + +fn read_clean(bytes: &[u8]) -> Document { + let mut report = Report::default(); + let doc = read(bytes, &mut report).unwrap(); + assert!(!report.has_warnings(), "{report}"); + doc +} + +fn walk<'a>(o: &'a Obj, out: &mut Vec<&'a Obj>) { + out.push(o); + for (_, v) in &o.props { + match v { + Value::Strong(c) => walk(c, out), + Value::StrongVec(v) | Value::StrongSet(v, _) => v.iter().for_each(|c| walk(c, out)), + _ => {} + } + } +} + +fn keys(dict: &Obj, p: u16) -> HashSet> { + dict.objs(p).iter().filter_map(|d| d.data(pid::IDENTIFICATION).map(<[u8]>::to_vec)).collect() +} + +/// filmcraft#323: readers that load the meta-dictionary (pyaaf2) need its ClassDefinitions and +/// TypeDefinitions sets. They are empty: everything written uses the baseline classes and types +/// those readers already know. +#[test] +fn the_meta_dictionary_has_its_class_and_type_definition_sets() { + for small in [false, true] { + let bytes = written(&document(), small); + let cf = craft_cfb::CompoundFile::open(&bytes).unwrap(); + assert_eq!(cf.entries[cf.find("MetaDictionary-1").unwrap()].clsid, ids::META_DICTIONARY); + for name in ["ClassDefinitions-3", "TypeDefinitions-4"] { + // u32 count, u32 first free key, u32 last free key, u16 key pid, u8 key size + let index = cf.read_path(&format!("MetaDictionary-1/{name} index")).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(index.len(), 15, "{name}: an empty set"); + assert_eq!(index[0..4], 0u32.to_le_bytes(), "{name}: no entries"); + assert_eq!(u16::from_le_bytes([index[12], index[13]]), pid::META_IDENTIFICATION, "{name}: keyed by the definition's AUID"); + assert_eq!(index[14], 16, "{name}: 16-byte keys"); + } + let root = store::read(&bytes).unwrap(); + let meta = root.strong(pid::ROOT_META_DICTIONARY).unwrap(); + for set in [pid::META_CLASS_DEFINITIONS, pid::META_TYPE_DEFINITIONS] { + assert!(matches!(meta.get(set), Some(Value::StrongSet(items, k)) if items.is_empty() && *k == pid::META_IDENTIFICATION), "{set:#06x}"); + } + } +} + +#[test] +fn written_files_have_the_required_structure() { + for small in [false, true] { + let bytes = written(&document(), small); + assert_written_file(&bytes, small); + } +} + +/// The top-level composition is tagged `Usage_TopLevel`, which the SMPTE Labels register gives as +/// urn:smpte:ul:060e2b34.04010101.0d010102.01010700, stored as the AUID +/// {0d010102-0101-0700-060e-2b3404010101}. Readers that look for it (LibAAF) find no sequence +/// without it. +#[test] +fn the_top_level_composition_has_the_registered_usage_code() { + let bytes = written(&document(), false); + let root = store::read(&bytes).unwrap(); + let content = root.strong(pid::ROOT_HEADER).unwrap().strong(pid::CONTENT).unwrap(); + let comp = content.objs(pid::MOBS).iter().find(|m| m.class == cls::COMPOSITION_MOB).unwrap(); + let usage = [0x02, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x00, 0x07, 0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x01]; + assert_eq!(comp.data(pid::USAGE_CODE), Some(&usage[..])); +} + +/// Files from FilmCraft 0.16 and earlier tag the top-level composition with the unregistered label +/// 060e2b34.04010105.0d011201.02030000. They still import: the composition no other one uses is +/// the edit. +#[test] +fn files_with_the_old_usage_code_still_import() { + let bytes = written(&document(), false); + let mut root = store::read(&bytes).unwrap(); + let content = strong_mut(strong_mut(&mut root, pid::ROOT_HEADER), pid::CONTENT); + for mob in objs_mut(content, pid::MOBS).iter_mut().filter(|m| m.class == cls::COMPOSITION_MOB) { + mob.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL_OLD.to_vec())); + } + let old_file = store::write(&root, craft_cfb::Version::V4).unwrap(); + let got = read_clean(&old_file); + assert_eq!(got.compositions.len(), 1); + assert_eq!(got, read_clean(&bytes)); +} + +/// A file that holds one edit tagged with each label (a tool merged a composition from an older +/// file into a newer one) imports both edits. +#[test] +fn edits_tagged_with_either_usage_code_both_import() { + let bytes = written(&document(), false); + let mut root = store::read(&bytes).unwrap(); + let content = strong_mut(strong_mut(&mut root, pid::ROOT_HEADER), pid::CONTENT); + let mobs = objs_mut(content, pid::MOBS); + let mut old = mobs.iter().find(|m| m.class == cls::COMPOSITION_MOB).unwrap().clone(); + let mut id = old.mob_id(pid::MOB_ID).unwrap(); + id[31] ^= 0xFF; + old.set(pid::MOB_ID, Value::Data(id.to_vec())); + old.set(pid::MOB_NAME, Value::Data(store::utf16z("Old"))); + old.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL_OLD.to_vec())); + mobs.push(old); + let mixed = store::write(&root, craft_cfb::Version::V4).unwrap(); + let mut names: Vec = read_clean(&mixed).compositions.into_iter().map(|c| c.name).collect(); + names.sort(); + assert_eq!(names, ["Old", "S"]); +} + +fn assert_written_file(bytes: &[u8], small: bool) { + assert_compound_file(bytes, small); + let root = store::read(bytes).unwrap(); + assert!(root.strong(pid::ROOT_META_DICTIONARY).is_some()); + let header = root.strong(pid::ROOT_HEADER).unwrap(); + let content = assert_header(header); + let dict = header.strong(pid::DICTIONARY).unwrap(); + let definitions = Definitions { + data: keys(dict, pid::DATA_DEFINITIONS), + operations: keys(dict, pid::OPERATION_DEFINITIONS), + interpolation: keys(dict, pid::INTERPOLATION_DEFINITIONS), + containers: keys(dict, pid::CONTAINER_DEFINITIONS), + parameters: keys(dict, pid::PARAMETER_DEFINITIONS), + }; + let mobs = content.objs(pid::MOBS); + let comp = assert_mob_set(content, mobs); + for mob in mobs { + assert_mob(mob, mobs, &definitions); + } + assert_composition(comp); +} + +fn assert_compound_file(bytes: &[u8], small: bool) { + let cf = craft_cfb::CompoundFile::open(bytes).unwrap(); + assert_eq!(cf.version, if small { 3 } else { 4 }); + assert_eq!(cf.root().clsid, ids::ROOT); + let references = cf.read_path("referenced properties").unwrap(); + let pids: Vec = references[7..].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + assert!(pids.windows(3).any(|w| w == path::DATA_DEFS)); + let header = cf.find("Header-2").unwrap(); + assert_eq!(cf.entries[header].clsid, cls::HEADER); + assert!(cf.read_path("Header-2/properties").unwrap().starts_with(&[0x4C, 0x20])); +} + +fn assert_header(header: &Obj) -> &Obj { + for req in [pid::BYTE_ORDER, pid::LAST_MODIFIED, pid::CONTENT, pid::DICTIONARY, pid::VERSION, pid::IDENTIFICATION_LIST, pid::OBJECT_MODEL_VERSION] + { + assert!(header.get(req).is_some(), "Header property {req:#06x}"); + } + assert_eq!(header.auid(pid::OPERATIONAL_PATTERN), Some(def::OP_EDIT_PROTOCOL)); + let ident = &header.objs(pid::IDENTIFICATION_LIST)[0]; + for req in [pid::COMPANY_NAME, pid::PRODUCT_NAME, pid::PRODUCT_VERSION_STRING, pid::PRODUCT_ID, pid::DATE, pid::GENERATION_AUID] { + assert!(ident.get(req).is_some(), "Identification property {req:#06x}"); + } + header.strong(pid::CONTENT).unwrap() +} + +struct Definitions { + data: HashSet>, + operations: HashSet>, + interpolation: HashSet>, + containers: HashSet>, + parameters: HashSet>, +} + +fn assert_mob_set<'a>(content: &Obj, mobs: &'a [Obj]) -> &'a Obj { + let mob_ids: Vec<[u8; 32]> = mobs.iter().map(|m| m.mob_id(pid::MOB_ID).unwrap()).collect(); + assert_eq!(mob_ids.iter().collect::>().len(), mob_ids.len(), "unique mob ids"); + assert!(matches!(content.get(pid::MOBS), Some(Value::StrongSet(_, k)) if *k == pid::MOB_ID)); + let compositions: Vec<&Obj> = mobs.iter().filter(|m| m.class == cls::COMPOSITION_MOB).collect(); + assert_eq!(compositions.len(), 1); + assert_eq!(compositions[0].auid(pid::USAGE_CODE), Some(def::USAGE_TOP_LEVEL)); + assert_eq!(mobs.iter().filter(|m| m.class == cls::MASTER_MOB).count(), 1); + assert_eq!(mobs.iter().filter(|m| m.class == cls::SOURCE_MOB).count(), 3, "picture file, sound file, tape"); + compositions[0] +} + +fn assert_mob(mob: &Obj, mobs: &[Obj], definitions: &Definitions) { + for req in [pid::MOB_ID, pid::MOB_NAME, pid::SLOTS, pid::MOB_LAST_MODIFIED, pid::MOB_CREATION_TIME] { + assert!(mob.get(req).is_some(), "Mob property {req:#06x}"); + } + assert_source_descriptor(mob, &definitions.containers); + for slot in mob.objs(pid::SLOTS) { + assert!(slot.get(pid::SLOT_ID).is_some() && slot.get(pid::SEGMENT).is_some()); + if slot.class == cls::TIMELINE_MOB_SLOT { + assert!(slot.rational(pid::EDIT_RATE).is_some_and(|r| r.0 > 0 && r.1 > 0)); + assert!(slot.get(pid::ORIGIN).is_some()); + } + } + let mut all = Vec::new(); + walk(mob, &mut all); + for component in all { + assert_component(component, mobs, definitions); + } +} + +fn assert_source_descriptor(mob: &Obj, containers: &HashSet>) { + if mob.class != cls::SOURCE_MOB { + return; + } + let descriptor = mob.strong(pid::ESSENCE_DESCRIPTION).expect("SourceMob::EssenceDescription"); + if descriptor.class != cls::TAPE_DESCRIPTOR { + for req in [pid::SAMPLE_RATE, pid::FILE_LENGTH, pid::CONTAINER_FORMAT] { + assert!(descriptor.get(req).is_some(), "FileDescriptor property {req:#06x}"); + } + assert!(containers.contains(descriptor.weak_key(pid::CONTAINER_FORMAT).unwrap())); + let url = descriptor.objs(pid::LOCATOR)[0].string(pid::URL_STRING).unwrap(); + assert_eq!(url, "file:///m/a.mov"); + } + if descriptor.class == cls::PCM_DESCRIPTOR { + assert_eq!(descriptor.u32(pid::CHANNELS), Some(2)); + assert_eq!(descriptor.u32(pid::QUANTIZATION_BITS), Some(24)); + assert_eq!(descriptor.u16(pid::BLOCK_ALIGN), Some(6)); + } +} + +fn assert_component(o: &Obj, mobs: &[Obj], definitions: &Definitions) { + if is_component(o) { + let dd = o.weak_key(pid::DATA_DEFINITION).expect("Component::DataDefinition"); + assert!(definitions.data.contains(dd), "data definition in the dictionary"); + let event_seq = o.class == cls::SEQUENCE && dd == ddef::DESCRIPTIVE_METADATA; + assert!(event_seq || o.get(pid::LENGTH).is_some(), "Component::Length"); + } + if o.class == cls::SOURCE_CLIP { + assert_source_clip(o, mobs); + } else if o.class == cls::OPERATION_GROUP { + assert_operation_group(o, definitions); + } else if o.class == cls::SEQUENCE && o.get(pid::LENGTH).is_some() { + assert_sequence_length(o); + } +} + +fn is_component(o: &Obj) -> bool { + [cls::FILLER, cls::SOURCE_CLIP, cls::SEQUENCE, cls::TRANSITION, cls::OPERATION_GROUP, cls::TIMECODE, cls::COMMENT_MARKER].contains(&o.class) +} + +fn assert_source_clip(clip: &Obj, mobs: &[Obj]) { + let id = clip.mob_id(pid::SOURCE_ID).unwrap(); + let slot = clip.u32(pid::SOURCE_MOB_SLOT_ID).unwrap(); + assert!(clip.get(pid::START_TIME).is_some()); + if id != [0; 32] { + let target = mobs.iter().find(|m| m.mob_id(pid::MOB_ID) == Some(id)).expect("source clip target in the file"); + assert!(target.objs(pid::SLOTS).iter().any(|s| s.u32(pid::SLOT_ID) == Some(slot)), "target slot exists"); + } +} + +fn assert_operation_group(group: &Obj, definitions: &Definitions) { + assert!(definitions.operations.contains(group.weak_key(pid::OPERATION).unwrap())); + for parameter in group.objs(pid::PARAMETERS) { + assert!(definitions.parameters.contains(parameter.auid(pid::PARAMETER_DEFINITION).unwrap().as_slice())); + if parameter.class == cls::VARYING_VALUE { + assert!(definitions.interpolation.contains(parameter.weak_key(pid::INTERPOLATION).unwrap())); + assert!(!parameter.objs(pid::POINT_LIST).is_empty()); + } + } +} + +fn assert_sequence_length(sequence: &Obj) { + let components = sequence.objs(pid::COMPONENTS); + let sum = components + .iter() + .enumerate() + .map(|(i, component)| { + let len = component.i64(pid::LENGTH).unwrap(); + if component.class == cls::TRANSITION { + assert!(i > 0 && i + 1 < components.len(), "transition at a sequence end"); + assert!(components[i - 1].class != cls::TRANSITION && components[i + 1].class != cls::TRANSITION); + assert!(components[i - 1].i64(pid::LENGTH).unwrap() >= len && components[i + 1].i64(pid::LENGTH).unwrap() >= len); + let cut = component.i64(pid::CUT_POINT).unwrap(); + assert!((0..=len).contains(&cut)); + assert!(component.strong(pid::OPERATION_GROUP).is_some()); + -len + } else { + len + } + }) + .sum::(); + assert_eq!(sum, sequence.i64(pid::LENGTH).unwrap(), "sequence length = segments − transitions"); +} + +fn assert_composition(comp: &Obj) { + let slots = comp.objs(pid::SLOTS); + let tc = slots[0].strong(pid::SEGMENT).unwrap(); + assert_eq!(tc.class, cls::TIMECODE); + assert_eq!(tc.u16(pid::TC_FPS), Some(24)); + let video = slots[1].strong(pid::SEGMENT).unwrap().objs(pid::COMPONENTS); + assert_eq!(video.iter().map(|c| c.class).collect::>(), vec![cls::SOURCE_CLIP, cls::TRANSITION, cls::SOURCE_CLIP]); + assert_eq!(video[0].i64(pid::LENGTH), Some(54), "outgoing clip extends to the transition end"); + assert_eq!(video[2].i64(pid::LENGTH), Some(54), "incoming clip starts at the transition start"); + assert_eq!(video[2].i64(pid::START_TIME), Some(194)); + assert_eq!(video[1].i64(pid::CUT_POINT), Some(6)); + assert_eq!(video[1].strong(pid::OPERATION_GROUP).unwrap().weak_key(pid::OPERATION), Some(&def::VIDEO_DISSOLVE[..])); + assert_audio_composition_slot(&slots[2]); +} + +fn assert_audio_composition_slot(slot: &Obj) { + let audio = slot.strong(pid::SEGMENT).unwrap().objs(pid::COMPONENTS); + assert_eq!(slot.rational(pid::EDIT_RATE), Some((48_000, 1))); + assert_eq!(audio[2].class, cls::OPERATION_GROUP); + assert_eq!(audio[2].weak_key(pid::OPERATION), Some(&def::MONO_AUDIO_GAIN[..])); + let amplitude = audio[2].objs(pid::PARAMETERS)[0].data(pid::CONSTANT_VALUE).unwrap(); + let (numerator, denominator) = store::rational_of(&litude[17..]).unwrap(); + assert!((numerator as f64 / denominator as f64 - 10f64.powf(-3.0 / 20.0)).abs() < 1e-4); + assert_eq!(audio[1].strong(pid::OPERATION_GROUP).unwrap().weak_key(pid::OPERATION), Some(&def::MONO_AUDIO_DISSOLVE[..])); +} + +#[test] +fn store_round_trips_every_stored_form() { + let leaf = |n: u8| Obj::new([n; 16]).data_prop(0x1B01, vec![n; 16]); + let root = Obj::new(ids::ROOT) + .data_prop(0x0003, vec![1, 2, 3]) + .with(0x0004, Value::Strong(Box::new(leaf(1).with(0x0005, Value::StrongVec(vec![leaf(2), leaf(3)]))))) + .with( + 0x0002, + Value::Strong(Box::new( + Obj::new([9; 16]) + .with(0x3B04, Value::Strong(Box::new(Obj::new([8; 16]).with(0x2605, Value::StrongSet(vec![leaf(4), leaf(5)], 0x1B01))))), + )), + ) + .with(0x0006, Value::Weak(path::DATA_DEFS.to_vec(), 0x1B01, vec![5; 16])) + .with(0x0007, Value::WeakVec(path::DATA_DEFS.to_vec(), 0x1B01, vec![vec![4; 16], vec![5; 16]])) + .with(0x0008, Value::Stream((0..10_000u32).map(|i| i as u8).collect())); + for v in [craft_cfb::Version::V3, craft_cfb::Version::V4] { + let bytes = store::write(&root, v).unwrap(); + assert_eq!(store::read(&bytes).unwrap(), root); + } + // a data value longer than a property can hold is an error, not a panic + assert!(store::write(&Obj::new(ids::ROOT).data_prop(1, vec![0; 70_000]), craft_cfb::Version::V4).is_err()); +} + +/// The property `p` of `o` as a list of objects, to change. +fn objs_mut(o: &mut Obj, p: u16) -> &mut Vec { + match o.props.iter_mut().find(|(k, _)| *k == p).map(|(_, v)| v) { + Some(Value::StrongVec(v)) | Some(Value::StrongSet(v, _)) => v, + _ => panic!("no object list {p:#06x}"), + } +} + +fn strong_mut(o: &mut Obj, p: u16) -> &mut Obj { + match o.props.iter_mut().find(|(k, _)| *k == p).map(|(_, v)| v) { + Some(Value::Strong(v)) => v, + _ => panic!("no object {p:#06x}"), + } +} + +fn is_picture(o: &Obj) -> bool { + o.weak_key(pid::DATA_DEFINITION) == Some(&ddef::PICTURE[..]) +} + +/// How Premiere Pro 26.5.2 lays a sequence with a nested sequence out in AAF (seen in a file it +/// exported): every composition is tagged top-level, the nested one too; all video tracks of a +/// composition are in ONE slot, a nested scope with a segment per track, lowest first; a clip of +/// the nested sequence is a source clip that points at its composition. Our own file is rewritten +/// into that layout and must read back as the same edit. +#[test] +fn premiere_style_layers_and_nested_compositions_are_read() { + let r = FrameRate::FPS_24; + // "Outer": media on V1 and V3, the sequence "S" nested on V2 with its sound on A1 + let inner = document(); + let mut sources = inner.sources.clone(); + for kind in [CKind::Picture, CKind::Sound] { + let mut nest = source("seq:2", "S", kind, r, 16, None); + (nest.path, nest.nested, nest.length, nest.width, nest.height) = (None, Some(0), r.tick_of(96), 1920, 1080); + sources.push(nest); + } + let gap = |frames: i64| CItem::Filler(r.tick_of(frames)); + let outer = composition( + "Outer", + r, + vec![ + track(CKind::Picture, "V1", 1, vec![clip(r, 0, 5, 30, "a")]), + track(CKind::Picture, "V2", 2, vec![gap(10), clip(r, 2, 12, 40, "S")]), + track(CKind::Picture, "V3", 3, vec![gap(60), clip(r, 0, 100, 20, "a")]), + track(CKind::Sound, "A1", 1, vec![gap(10), clip(r, 3, 12, 40, "S")]), + ], + ); + let ours = written(&Document { compositions: vec![outer], sources, nested: inner.compositions }, false); + + let mut root = store::read(&ours).unwrap(); + let content = strong_mut(strong_mut(&mut root, pid::ROOT_HEADER), pid::CONTENT); + let mut compositions = 0; + for mob in objs_mut(content, pid::MOBS).iter_mut().filter(|m| m.class == cls::COMPOSITION_MOB) { + compositions += 1; + mob.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL.to_vec())); + let slots = objs_mut(mob, pid::SLOTS); + let picture: Vec = slots.iter().enumerate().filter(|(_, s)| s.strong(pid::SEGMENT).is_some_and(is_picture)).map(|(i, _)| i).collect(); + let layers: Vec = picture.iter().map(|&i| slots[i].strong(pid::SEGMENT).unwrap().clone()).collect(); + let length = layers.iter().filter_map(|l| l.i64(pid::LENGTH)).max().unwrap_or(0); + let scope = Obj::new(cls::NESTED_SCOPE) + .with(pid::DATA_DEFINITION, Value::Weak(path::DATA_DEFS.to_vec(), pid::IDENTIFICATION, ddef::PICTURE.to_vec())) + .data_prop(pid::LENGTH, length.to_le_bytes().to_vec()) + .with(pid::NESTED_SLOTS, Value::StrongVec(layers)); + // the first video slot keeps its id (clips of the nested sequence point at it) and holds + // every layer; the other video slots go + slots[picture[0]].set(pid::SEGMENT, Value::Strong(Box::new(scope))); + for &i in picture[1..].iter().rev() { + slots.remove(i); + } + } + assert_eq!(compositions, 2); + let theirs = store::write(&root, craft_cfb::Version::V4).unwrap(); + assert_ne!(theirs, ours); + + let want = read_clean(&ours); + let got = read_clean(&theirs); + // one edit; the nested composition is one it uses, not a second edit + assert_eq!(got.compositions.len(), 1); + assert_eq!(got.nested.len(), 1); + // layers of one slot share its name and are all as long as the scope: the same edit apart + // from picture track names and gaps after the last clip + let edit = |mut doc: Document| { + for t in doc.compositions.iter_mut().chain(&mut doc.nested).flat_map(|c| &mut c.tracks).filter(|t| t.kind == CKind::Picture) { + t.name.clear(); + while matches!(t.items.last(), Some(CItem::Filler(_))) { + t.items.pop(); + } + } + doc + }; + assert_eq!(edit(got.clone()), edit(want)); + // and that edit is the one that was written: three video tracks, the nest on the second + let q = &got.compositions[0]; + let picture: Vec<_> = q.tracks.iter().filter(|t| t.kind == CKind::Picture).collect(); + assert_eq!(picture.iter().map(|t| t.items.iter().filter(|i| matches!(i, CItem::Clip(_))).count()).collect::>(), [1, 1, 1]); + let nest_of = |kind: CKind| { + let t = q.tracks.iter().filter(|t| t.kind == kind).nth(if kind == CKind::Picture { 1 } else { 0 }).unwrap(); + let [CItem::Filler(gap), CItem::Clip(c), ..] = &t.items[..] else { panic!("{:?}", t.items) }; + (*gap, c.len, c.start, got.sources[c.source].nested, got.sources[c.source].name.clone()) + }; + assert_eq!(nest_of(CKind::Picture), (r.tick_of(10), r.tick_of(40), r.tick_of(12), Some(0), "S".to_string())); + assert_eq!(nest_of(CKind::Sound), nest_of(CKind::Picture)); + assert_eq!(got.nested[0].name, "S"); +} + +/// A slot's name is the track's name, whatever it starts with; a track without one reads back +/// without one. +#[test] +fn audio_tracks_keep_their_names() { + for name in ["Dialogue.Dialogue-1", "Dialogue.Dialogue-1 L", "", "é", "音声", "🎤 Dialogue", "Ä1"] { + let mut doc = document(); + doc.compositions[0].tracks[1].name = name.into(); + let back = read_clean(&written(&doc, false)); + assert_eq!(back.compositions[0].tracks[1].name, name); + } +} diff --git a/crates/aaf/src/aaf/write.rs b/crates/aaf/src/aaf/write.rs new file mode 100644 index 000000000..7ab51cea9 --- /dev/null +++ b/crates/aaf/src/aaf/write.rs @@ -0,0 +1,800 @@ +//! Composition model → AAF objects. + +use std::collections::HashMap; + +use craft_timeline::time::{FrameRate, Tick}; + +use super::ids::{META_DICTIONARY, ROOT, cls, ddef, def, path, pid}; +use super::store::{self, Auid, Obj, Value, rational, utf16z}; +use crate::model::{CItem, CKind, CMarker, Composition, Document, Gain, Source, ticks_to_units}; +use crate::{Error, Identity, Report, Result}; + +/// UMID-style mob id (SMPTE 330 basic UMID): label, length 0x13, instance 0, material number. +pub(crate) fn mob_id(seed: u64, n: u64) -> [u8; 32] { + let mut id = [0u8; 32]; + id[..12].copy_from_slice(&[0x06, 0x0A, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x05, 0x01, 0x01, 0x0F, 0x20]); + id[12] = 0x13; + let a = mix(seed ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15)); + let b = mix(a ^ 0xD6E8_FEB8_6659_FD93); + id[16..24].copy_from_slice(&a.to_le_bytes()); + id[24..32].copy_from_slice(&b.to_le_bytes()); + // a "random" material number per RFC 4122 v4 layout keeps it a valid UUID + id[22] = (id[22] & 0x0F) | 0x40; + id[24] = (id[24] & 0x3F) | 0x80; + id +} + +fn mix(mut z: u64) -> u64 { + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +pub(crate) fn fnv(s: &[u8], h: u64) -> u64 { + s.iter().fold(h, |h, &b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01B3)) +} + +fn timestamp() -> Vec { + // 1970-01-01 00:00:00.00: written files are reproducible + let mut v = 1970i16.to_le_bytes().to_vec(); + v.extend_from_slice(&[1, 1, 0, 0, 0, 0]); + v +} + +fn weak(path: [u16; 3], key: Auid) -> Value { + Value::Weak(path.to_vec(), pid::IDENTIFICATION, key.to_vec()) +} + +fn data_def(kind: CKind) -> Auid { + match kind { + CKind::Picture => ddef::PICTURE, + CKind::Sound => ddef::SOUND, + } +} + +/// An indirect value: byte order, type id, value. +pub(crate) fn indirect(ty: Auid, v: &[u8]) -> Vec { + let mut d = vec![0x4C]; + d.extend_from_slice(&ty); + d.extend_from_slice(v); + d +} + +fn tagged(name: &str, value: &str) -> Obj { + Obj::new(cls::TAGGED_VALUE).data_prop(pid::TAG_NAME, utf16z(name)).data_prop(pid::TAG_VALUE, indirect(def::TYPE_STRING, &utf16z(value))) +} + +fn gain_rational(g: f64) -> Vec { + rational((g.max(0.0) * 65536.0).round().min(i32::MAX as f64) as i64, 65536) +} + +fn definition(class: Auid, id: Auid, name: &str) -> Obj { + Obj::new(class).data_prop(pid::IDENTIFICATION, id.to_vec()).data_prop(pid::NAME, utf16z(name)).data_prop(pid::DESCRIPTION, utf16z("")) +} + +struct W<'a> { + report: &'a mut Report, + inexact: bool, +} + +struct IdGen { + seed: u64, + next: u64, +} + +impl IdGen { + fn for_document(doc: &Document, comp: &Composition) -> Self { + let mut seed = fnv(comp.name.as_bytes(), 0xCBF2_9CE4_8422_2325); + for source in &doc.sources { + seed = fnv(source.path.as_deref().unwrap_or("").as_bytes(), fnv(source.key.as_bytes(), seed)); + } + seed = fnv(&(comp.tracks.len() as u64).to_le_bytes(), seed); + Self { seed, next: 0 } + } + + fn next(&mut self) -> [u8; 32] { + self.next += 1; + mob_id(self.seed, self.next) + } +} + +struct MediaOutput { + mobs: Vec, + essence: Vec, + master_ref: HashMap, +} + +type FileMob = ((Option, usize, CKind), [u8; 32], Vec, usize); + +struct GroupSlots { + master_id: [u8; 32], + tape_id: [u8; 32], + timecode: Option<(i64, FrameRate)>, + master_slots: Vec, + tape_slots: Vec, + files: Vec, + master_ref: HashMap, +} + +struct GroupSlotBuilder<'a, 'b> { + doc: &'a Document, + master_id: [u8; 32], + tape_id: [u8; 32], + ids: &'b mut IdGen, + files: &'b mut Vec, + master_slots: &'b mut Vec, + tape_slots: &'b mut Vec, + master_ref: &'b mut HashMap, +} + +struct FileSlotInput<'a> { + source: &'a Source, + file_slot: u32, + length: i64, + has_timecode: bool, + tape_id: [u8; 32], + member_index: usize, + slots: &'a mut Vec, + rate: (i64, i64), +} + +impl W<'_> { + /// Edit units at `rate` of tick `t`. + fn u(&mut self, t: Tick, rate: (i64, i64)) -> i64 { + let (n, exact) = ticks_to_units(t, rate.0, rate.1); + if !exact { + self.inexact = true; + } + n + } +} + +fn source_rate(s: &Source) -> (i64, i64) { + match s.kind { + CKind::Picture => (s.frame_rate.num, s.frame_rate.den), + CKind::Sound => (s.sample_rate.max(1) as i64, 1), + } +} + +fn write_media(doc: &Document, w: &mut W<'_>, ids: &mut IdGen) -> MediaOutput { + let mut groups: Vec<(String, Vec)> = Vec::new(); + for (index, source) in doc.sources.iter().enumerate() { + if source.nested.is_some() { + continue; + } + match groups.iter_mut().find(|(key, _)| *key == source.key) { + Some((_, members)) => members.push(index), + None => groups.push((source.key.clone(), vec![index])), + } + } + + let mut output = MediaOutput { mobs: Vec::new(), essence: Vec::new(), master_ref: HashMap::new() }; + for (_, members) in groups { + write_source_group(doc, &members, w, ids, &mut output); + } + output +} + +fn write_source_group(doc: &Document, members: &[usize], w: &mut W<'_>, ids: &mut IdGen, output: &mut MediaOutput) { + let first = &doc.sources[members[0]]; + let slots = build_group_slots(doc, members, w, ids); + output.master_ref.extend(slots.master_ref); + let mut master_slots = slots.master_slots; + add_master_markers(doc, members, w, &mut master_slots); + output.mobs.push( + Obj::new(cls::MASTER_MOB) + .data_prop(pid::MOB_ID, slots.master_id.to_vec()) + .data_prop(pid::MOB_NAME, utf16z(&first.name)) + .data_prop(pid::MOB_LAST_MODIFIED, timestamp()) + .data_prop(pid::MOB_CREATION_TIME, timestamp()) + .with(pid::SLOTS, Value::StrongVec(master_slots)), + ); + let tape_id = slots.tape_id; + let timecode = slots.timecode; + let tape_slots = slots.tape_slots; + add_file_mobs(doc, slots.files, w, output); + add_tape_mob(first, tape_id, timecode, tape_slots, output); +} + +fn build_group_slots(doc: &Document, members: &[usize], w: &mut W<'_>, ids: &mut IdGen) -> GroupSlots { + let master_id = ids.next(); + let tape_id = ids.next(); + let timecode = members.iter().find_map(|&i| doc.sources[i].start_tc.map(|t| (t, doc.sources[i].tc_rate))); + let mut tape_slots = Vec::new(); + if let Some((start, rate)) = timecode { + tape_slots.push(timecode_slot(members, doc, w, start, rate)); + } + let mut files: Vec = Vec::new(); + let mut master_slots = Vec::new(); + let mut master_ref = HashMap::new(); + let mut builder = GroupSlotBuilder { + doc, + master_id, + tape_id, + ids, + files: &mut files, + master_slots: &mut master_slots, + tape_slots: &mut tape_slots, + master_ref: &mut master_ref, + }; + for (member_index, &source_index) in members.iter().enumerate() { + builder.add_source(source_index, member_index, timecode.is_some(), w); + } + GroupSlots { master_id, tape_id, timecode, master_slots, tape_slots, files, master_ref } +} + +fn timecode_slot(members: &[usize], doc: &Document, w: &mut W<'_>, start: i64, rate: FrameRate) -> Obj { + let edit_rate = (rate.num, rate.den); + let len = members.iter().map(|&i| doc.sources[i].length).max().unwrap_or(Tick::ZERO); + let units = w.u(len, edit_rate); + timeline_slot( + 1, + "TC1", + 0, + edit_rate, + Obj::new(cls::TIMECODE) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::TIMECODE)) + .data_prop(pid::LENGTH, units.to_le_bytes().to_vec()) + .data_prop(pid::TC_START, start.to_le_bytes().to_vec()) + .data_prop(pid::TC_FPS, (rate.timecode_base().clamp(1, u16::MAX as i64) as u16).to_le_bytes().to_vec()) + .data_prop(pid::TC_DROP, vec![0]), + ) +} + +impl GroupSlotBuilder<'_, '_> { + fn add_source(&mut self, source_index: usize, member_index: usize, has_timecode: bool, w: &mut W<'_>) { + let source = &self.doc.sources[source_index]; + let rate = source_rate(source); + let embedded_key = if source.embedded.is_some() { source_index } else { usize::MAX }; + let file_key = (source.path.clone(), embedded_key, source.kind); + let file_slot = source.channel.map_or(1, |channel| channel + 1); + let len_units = w.u(source.length, rate); + let file_index = match self.files.iter().position(|file| file.0 == file_key) { + Some(index) => index, + None => { + self.files.push((file_key, self.ids.next(), Vec::new(), source_index)); + self.files.len() - 1 + } + }; + let file_id = self.files[file_index].1; + add_file_slot(FileSlotInput { + source, + file_slot, + length: len_units, + has_timecode, + tape_id: self.tape_id, + member_index, + slots: &mut self.files[file_index].2, + rate, + }); + if has_timecode { + let tape_slot_id = 2 + member_index as u32; + self.tape_slots.push(timeline_slot( + tape_slot_id, + &slot_name(source.kind, member_index as u32 + 1), + member_index as u32 + 1, + rate, + source_clip(source.kind, len_units, [0; 32], 0, 0), + )); + } + let master_slot = member_index as u32 + 1; + self.master_slots.push(timeline_slot( + master_slot, + &slot_name(source.kind, master_slot), + master_slot, + rate, + source_clip(source.kind, len_units, file_id, file_slot, 0), + )); + self.master_ref.insert(source_index, (self.master_id, master_slot)); + } +} + +fn add_file_slot(input: FileSlotInput<'_>) { + let FileSlotInput { source, file_slot, length, has_timecode, tape_id, member_index, slots, rate } = input; + if slots.iter().any(|slot| slot.u32(pid::SLOT_ID) == Some(file_slot)) { + return; + } + let tape_slot_id = if has_timecode { 2 + member_index as u32 } else { 0 }; + let mob_id = if has_timecode { tape_id } else { [0; 32] }; + let clip = source_clip(source.kind, length, mob_id, tape_slot_id, 0); + slots.push(timeline_slot(file_slot, &slot_name(source.kind, file_slot), file_slot, rate, clip)); +} + +fn add_master_markers(doc: &Document, members: &[usize], w: &mut W<'_>, master_slots: &mut Vec) { + let first = &doc.sources[members[0]]; + let marker_rate = + members.iter().map(|&i| &doc.sources[i]).find(|source| source.kind == CKind::Picture).map(source_rate).unwrap_or_else(|| source_rate(first)); + let markers: Vec<&CMarker> = members.iter().flat_map(|&i| doc.sources[i].markers.iter()).collect(); + if markers.is_empty() { + return; + } + let mut unique: Vec = markers.into_iter().cloned().collect(); + unique.sort_by(|a, b| (a.start, &a.name).cmp(&(b.start, &b.name))); + unique.dedup(); + master_slots.push(event_slot(w, members.len() as u32 + 1, marker_rate, &unique)); +} + +fn add_file_mobs(doc: &Document, files: Vec, w: &mut W<'_>, output: &mut MediaOutput) { + for (_, file_id, slots, source_index) in files { + let source = &doc.sources[source_index]; + let desc = descriptor(w, source); + output.mobs.push( + Obj::new(cls::SOURCE_MOB) + .data_prop(pid::MOB_ID, file_id.to_vec()) + .data_prop(pid::MOB_NAME, utf16z(&source.name)) + .data_prop(pid::MOB_LAST_MODIFIED, timestamp()) + .data_prop(pid::MOB_CREATION_TIME, timestamp()) + .with(pid::SLOTS, Value::StrongVec(slots)) + .with(pid::ESSENCE_DESCRIPTION, Value::Strong(Box::new(desc))), + ); + if let Some(data) = &source.embedded { + output.essence.push( + Obj::new(cls::ESSENCE_DATA).data_prop(pid::ESSENCE_MOB_ID, file_id.to_vec()).with(pid::ESSENCE_STREAM, Value::Stream(data.clone())), + ); + } + } +} + +fn add_tape_mob(first: &Source, tape_id: [u8; 32], timecode: Option<(i64, FrameRate)>, tape_slots: Vec, output: &mut MediaOutput) { + let Some(_) = timecode else { return }; + let reel = first.path.as_deref().map(craft_timeline::path::file_stem).unwrap_or(&first.name).to_string(); + output.mobs.push( + Obj::new(cls::SOURCE_MOB) + .data_prop(pid::MOB_ID, tape_id.to_vec()) + .data_prop(pid::MOB_NAME, utf16z(&reel)) + .data_prop(pid::MOB_LAST_MODIFIED, timestamp()) + .data_prop(pid::MOB_CREATION_TIME, timestamp()) + .with(pid::SLOTS, Value::StrongVec(tape_slots)) + .with(pid::ESSENCE_DESCRIPTION, Value::Strong(Box::new(Obj::new(cls::TAPE_DESCRIPTOR)))), + ); +} + +/// Serialise a composition document. +pub(crate) fn write(doc: &Document, version: craft_cfb::Version, identity: &Identity<'_>, report: &mut Report) -> Result> { + let comp = doc.compositions.first().ok_or(Error::Empty)?; + let mut w = W { report, inexact: false }; + let mut ids = IdGen::for_document(doc, comp); + let MediaOutput { mut mobs, essence, master_ref } = write_media(doc, &mut w, &mut ids); + let mut used_ops: Vec = Vec::new(); + let mut uses_varying = false; + + // ---- nested compositions: a clip refers to one as it does to a master mob, through the + // composition's first track of the clip's kind (a broken-out channel: that channel's track) + let mut refs = Refs { mobs: master_ref, rates: HashMap::new() }; + let nested_ids: Vec<[u8; 32]> = doc.nested.iter().map(|_| ids.next()).collect(); + for (si, s) in doc.sources.iter().enumerate() { + let Some((comp, id)) = s.nested.and_then(|n| Some((doc.nested.get(n)?, nested_ids.get(n)?))) else { continue }; + let of_kind: Vec = comp.tracks.iter().enumerate().filter(|(_, t)| t.kind == s.kind).map(|(i, _)| i).collect(); + let Some(&track) = s.channel.and_then(|c| of_kind.get(c as usize)).or(of_kind.first()) else { continue }; + let rate = match s.kind { + CKind::Picture => (comp.rate.num, comp.rate.den), + CKind::Sound => (comp.sample_rate.max(1) as i64, 1), + }; + refs.mobs.insert(si, (*id, track as u32 + 2)); + refs.rates.insert(si, rate); + } + + // ---- the compositions: the exported sequence first + let comp_id = ids.next(); + let composition_mobs = { + let mut composition_writer = CompositionWriter { w: &mut w, doc, refs: &refs, used_ops: &mut used_ops, uses_varying: &mut uses_varying }; + let mut output = vec![composition_writer.write(comp, comp_id, true)]; + output.extend(doc.nested.iter().zip(&nested_ids).map(|(nested, id)| composition_writer.write(nested, *id, false))); + output + }; + mobs.splice(0..0, composition_mobs); + if w.inexact { + w.report.info("some times are not on whole edit units and were rounded"); + } + + // ---- dictionary + let mut ddefs = Vec::new(); + for (id, name) in + [(ddef::PICTURE, "Picture"), (ddef::SOUND, "Sound"), (ddef::TIMECODE, "Timecode"), (ddef::DESCRIPTIVE_METADATA, "DescriptiveMetadata")] + { + ddefs.push(definition(cls::DATA_DEFINITION, id, name)); + } + let mut opdefs = Vec::new(); + for op in &used_ops { + let (name, dd, inputs) = match *op { + x if x == def::VIDEO_DISSOLVE => ("Video Dissolve", ddef::PICTURE, 2), + x if x == def::VIDEO_FADE_TO_BLACK => ("Video Fade To Black", ddef::PICTURE, 1), + x if x == def::SMPTE_VIDEO_WIPE => ("SMPTE Video Wipe", ddef::PICTURE, 2), + x if x == def::MONO_AUDIO_DISSOLVE => ("Mono Audio Dissolve", ddef::SOUND, 2), + _ => ("Mono Audio Gain", ddef::SOUND, 1i32), + }; + let params: Vec> = if *op == def::MONO_AUDIO_GAIN { + vec![def::PARAM_AMPLITUDE.to_vec()] + } else if *op == def::VIDEO_DISSOLVE { + vec![def::PARAM_LEVEL.to_vec()] + } else { + Vec::new() + }; + let mut o = definition(cls::OPERATION_DEFINITION, *op, name) + .with(pid::OPDEF_DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::OPDEF_IS_TIME_WARP, vec![0]) + .data_prop(pid::OPDEF_NUMBER_INPUTS, inputs.to_le_bytes().to_vec()); + if !params.is_empty() { + o.set(pid::OPDEF_PARAMETERS_DEFINED, Value::WeakVec(path::PARAMETER_DEFS.to_vec(), pid::IDENTIFICATION, params)); + } + opdefs.push(o); + } + let pdefs = vec![ + definition(cls::PARAMETER_DEFINITION, def::PARAM_LEVEL, "Level").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")), + definition(cls::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE, "Amplitude").data_prop(pid::PARAMDEF_DISPLAY_UNITS, utf16z("")), + ]; + let idefs = if uses_varying || !used_ops.is_empty() { + vec![ + definition(cls::INTERPOLATION_DEFINITION, def::INTERP_LINEAR, "Linear"), + definition(cls::INTERPOLATION_DEFINITION, def::INTERP_CONSTANT, "Constant"), + ] + } else { + Vec::new() + }; + let cdefs = vec![ + definition(cls::CONTAINER_DEFINITION, def::CONTAINER_EXTERNAL, "External Container"), + definition(cls::CONTAINER_DEFINITION, def::CONTAINER_AAF, "AAF Container"), + ]; + let mut dict = Obj::new(cls::DICTIONARY) + .with(pid::DATA_DEFINITIONS, Value::StrongSet(ddefs, pid::IDENTIFICATION)) + .with(pid::PARAMETER_DEFINITIONS, Value::StrongSet(pdefs, pid::IDENTIFICATION)) + .with(pid::CONTAINER_DEFINITIONS, Value::StrongSet(cdefs, pid::IDENTIFICATION)); + if !opdefs.is_empty() { + dict.set(pid::OPERATION_DEFINITIONS, Value::StrongSet(opdefs, pid::IDENTIFICATION)); + } + if !idefs.is_empty() { + dict.set(pid::INTERPOLATION_DEFINITIONS, Value::StrongSet(idefs, pid::IDENTIFICATION)); + } + + let mut content = Obj::new(cls::CONTENT_STORAGE).with(pid::MOBS, Value::StrongSet(mobs, pid::MOB_ID)); + if !essence.is_empty() { + content.set(pid::ESSENCE_DATA, Value::StrongSet(essence, pid::ESSENCE_MOB_ID)); + } + let ident = Obj::new(cls::IDENTIFICATION) + .data_prop(pid::COMPANY_NAME, utf16z(identity.company)) + .data_prop(pid::PRODUCT_NAME, utf16z(identity.product)) + .data_prop(pid::PRODUCT_VERSION_STRING, utf16z(identity.version)) + .data_prop(pid::PRODUCT_ID, identity.product_id.to_vec()) + .data_prop(pid::DATE, timestamp()) + .data_prop(pid::PLATFORM, utf16z(identity.platform)) + .data_prop(pid::GENERATION_AUID, mob_id(ids.seed, 0)[16..].to_vec()); + let header = Obj::new(cls::HEADER) + .data_prop(pid::BYTE_ORDER, 0x4949i16.to_le_bytes().to_vec()) + .data_prop(pid::LAST_MODIFIED, timestamp()) + .data_prop(pid::VERSION, vec![1, 1]) + .data_prop(pid::OBJECT_MODEL_VERSION, 1u32.to_le_bytes().to_vec()) + .data_prop(pid::OPERATIONAL_PATTERN, def::OP_EDIT_PROTOCOL.to_vec()) + .with(pid::CONTENT, Value::Strong(Box::new(content))) + .with(pid::DICTIONARY, Value::Strong(Box::new(dict))) + .with(pid::IDENTIFICATION_LIST, Value::StrongVec(vec![ident])); + // The meta-dictionary holds only extensions to the baseline object model, and everything written + // here is baseline, so its class and type definition sets are empty; readers that load them + // (pyaaf2) still need the sets to be there (filmcraft#323). + let meta = Obj::new(META_DICTIONARY) + .with(pid::META_CLASS_DEFINITIONS, Value::StrongSet(Vec::new(), pid::META_IDENTIFICATION)) + .with(pid::META_TYPE_DEFINITIONS, Value::StrongSet(Vec::new(), pid::META_IDENTIFICATION)); + let root = Obj::new(ROOT).with(pid::ROOT_META_DICTIONARY, Value::Strong(Box::new(meta))).with(pid::ROOT_HEADER, Value::Strong(Box::new(header))); + store::write(&root, version).map_err(Error::Other) +} + +/// Where clips find their sources: source index → (mob id, slot id), and for nested compositions +/// the edit rate of that slot. +#[derive(Default)] +struct Refs { + mobs: HashMap, + rates: HashMap, +} + +/// The composition mob of `comp`. Slot 1 is its timecode; its tracks follow from slot 2 in order. +struct CompositionWriter<'a, 'b, 'c> { + w: &'a mut W<'c>, + doc: &'b Document, + refs: &'b Refs, + used_ops: &'a mut Vec, + uses_varying: &'a mut bool, +} + +impl CompositionWriter<'_, '_, '_> { + fn write(&mut self, comp: &Composition, id: [u8; 32], top: bool) -> Obj { + let w = &mut *self.w; + let doc = self.doc; + let refs = self.refs; + let used_ops = &mut *self.used_ops; + let uses_varying = &mut *self.uses_varying; + let crate_rate = (comp.rate.num, comp.rate.den); + let mut slots = Vec::new(); + let total = comp + .tracks + .iter() + .map(|t| { + let mut c = Tick::ZERO; + for i in &t.items { + match i { + CItem::Transition(x) => c -= x.len, + other => c += other.len(), + } + } + c + }) + .max() + .unwrap_or(Tick::ZERO); + let total_units = w.u(total, crate_rate); + slots.push(timeline_slot( + 1, + "TC1", + 0, + crate_rate, + Obj::new(cls::TIMECODE) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::TIMECODE)) + .data_prop(pid::LENGTH, total_units.to_le_bytes().to_vec()) + .data_prop(pid::TC_START, comp.start_tc.to_le_bytes().to_vec()) + .data_prop(pid::TC_FPS, (comp.rate.timecode_base().clamp(1, u16::MAX as i64) as u16).to_le_bytes().to_vec()) + .data_prop(pid::TC_DROP, vec![comp.drop as u8]), + )); + let mut slot_id = 2u32; + for t in &comp.tracks { + let rate = match t.kind { + CKind::Picture => crate_rate, + CKind::Sound => (comp.sample_rate.max(1) as i64, 1), + }; + let dd = data_def(t.kind); + let mut comps = Vec::new(); + let mut cursor = Tick::ZERO; + for it in &t.items { + match it { + CItem::Filler(l) => { + let n = w.u(cursor + *l, rate) - w.u(cursor, rate); + cursor += *l; + comps.push( + Obj::new(cls::FILLER) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, n.to_le_bytes().to_vec()), + ); + } + CItem::Clip(c) => { + let n = w.u(cursor + c.len, rate) - w.u(cursor, rate); + let s = &doc.sources[c.source]; + let (mid, mslot) = refs.mobs.get(&c.source).copied().unwrap_or(([0; 32], 0)); + // (a nested composition counts the start in its own slot's edit units) + let start = w.u(c.start, refs.rates.get(&c.source).copied().unwrap_or(rate)); + let mut sc = source_clip(t.kind, n, mid, mslot, start); + if !c.name.is_empty() && c.name != s.name { + sc.set(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(vec![tagged("Clip Name", &c.name)])); + } + let seg = match (&c.gain, t.kind) { + (Some(g), CKind::Sound) => { + if !used_ops.contains(&def::MONO_AUDIO_GAIN) { + used_ops.push(def::MONO_AUDIO_GAIN); + } + let param = match g { + Gain::Constant(a) => Obj::new(cls::CONSTANT_VALUE) + .data_prop(pid::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE.to_vec()) + .data_prop(pid::CONSTANT_VALUE, indirect(def::TYPE_RATIONAL, &gain_rational(*a))), + Gain::Varying { linear, points } => { + *uses_varying = true; + let pts = points + .iter() + .map(|(off, a)| { + let o = w.u(cursor + *off, rate) - w.u(cursor, rate); + Obj::new(cls::CONTROL_POINT) + .data_prop(pid::CP_TIME, rational(o, n.max(1))) + .data_prop(pid::CP_VALUE, indirect(def::TYPE_RATIONAL, &gain_rational(*a))) + .data_prop(pid::CP_EDIT_HINT, vec![0]) + }) + .collect(); + Obj::new(cls::VARYING_VALUE) + .data_prop(pid::PARAMETER_DEFINITION, def::PARAM_AMPLITUDE.to_vec()) + .with( + pid::INTERPOLATION, + weak(path::INTERPOLATION_DEFS, if *linear { def::INTERP_LINEAR } else { def::INTERP_CONSTANT }), + ) + .with(pid::POINT_LIST, Value::StrongVec(pts)) + } + }; + Obj::new(cls::OPERATION_GROUP) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, n.to_le_bytes().to_vec()) + .with(pid::OPERATION, weak(path::OPERATION_DEFS, def::MONO_AUDIO_GAIN)) + .with(pid::INPUT_SEGMENTS, Value::StrongVec(vec![sc])) + .with(pid::PARAMETERS, Value::StrongVec(vec![param])) + } + _ => sc, + }; + comps.push(seg); + cursor += c.len; + } + CItem::Transition(x) => { + let ts = cursor - x.len; + let n = w.u(cursor, rate) - w.u(ts, rate); + let cut = w.u(ts + x.cut, rate) - w.u(ts, rate); + cursor = ts; + let op = transition_op(t.kind, &x.effect); + if !used_ops.contains(&op) { + used_ops.push(op); + } + let mut og = Obj::new(cls::OPERATION_GROUP) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, n.to_le_bytes().to_vec()) + .with(pid::OPERATION, weak(path::OPERATION_DEFS, op)) + .with(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(vec![tagged("FilmCraft Effect", &x.effect)])); + if op == def::VIDEO_DISSOLVE { + *uses_varying = true; + let pts = [(0, 0), (1, 1)] + .iter() + .map(|&(t, v)| { + Obj::new(cls::CONTROL_POINT) + .data_prop(pid::CP_TIME, rational(t, 1)) + .data_prop(pid::CP_VALUE, indirect(def::TYPE_RATIONAL, &rational(v, 1))) + .data_prop(pid::CP_EDIT_HINT, vec![0]) + }) + .collect(); + og.set( + pid::PARAMETERS, + Value::StrongVec(vec![ + Obj::new(cls::VARYING_VALUE) + .data_prop(pid::PARAMETER_DEFINITION, def::PARAM_LEVEL.to_vec()) + .with(pid::INTERPOLATION, weak(path::INTERPOLATION_DEFS, def::INTERP_LINEAR)) + .with(pid::POINT_LIST, Value::StrongVec(pts)), + ]), + ); + } + comps.push( + Obj::new(cls::TRANSITION) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, n.to_le_bytes().to_vec()) + .data_prop(pid::CUT_POINT, cut.to_le_bytes().to_vec()) + .with(pid::OPERATION_GROUP, Value::Strong(Box::new(og))), + ); + } + } + } + let len: i64 = comps + .iter() + .map(|c| { + let l = c.i64(pid::LENGTH).unwrap_or(0); + if c.class == cls::TRANSITION { -l } else { l } + }) + .sum(); + let seq = Obj::new(cls::SEQUENCE) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, dd)) + .data_prop(pid::LENGTH, len.to_le_bytes().to_vec()) + .with(pid::COMPONENTS, Value::StrongVec(comps)); + slots.push(timeline_slot(slot_id, &t.name, t.number, rate, seq)); + slot_id += 1; + } + if !comp.markers.is_empty() { + slots.push(event_slot(w, slot_id, crate_rate, &comp.markers)); + } + let mut mob = Obj::new(cls::COMPOSITION_MOB) + .data_prop(pid::MOB_ID, id.to_vec()) + .data_prop(pid::MOB_NAME, utf16z(&comp.name)) + .data_prop(pid::MOB_LAST_MODIFIED, timestamp()) + .data_prop(pid::MOB_CREATION_TIME, timestamp()); + // only the exported sequence is a top-level composition; a nested sequence is found through + // the clips that use it + if top { + mob.set(pid::USAGE_CODE, Value::Data(def::USAGE_TOP_LEVEL.to_vec())); + } + mob.with(pid::SLOTS, Value::StrongVec(slots)).with( + pid::MOB_USER_COMMENTS, + Value::StrongVec(vec![ + tagged("FilmCraft Frame Size", &format!("{}x{}", comp.width, comp.height)), + tagged("FilmCraft Audio Sample Rate", &comp.sample_rate.to_string()), + ]), + ) + } +} + +fn slot_name(kind: CKind, n: u32) -> String { + match kind { + CKind::Picture => format!("V{n}"), + CKind::Sound => format!("A{n}"), + } +} + +fn timeline_slot(id: u32, name: &str, number: u32, rate: (i64, i64), segment: Obj) -> Obj { + let mut o = Obj::new(cls::TIMELINE_MOB_SLOT) + .data_prop(pid::SLOT_ID, id.to_le_bytes().to_vec()) + .data_prop(pid::SLOT_NAME, utf16z(name)) + .data_prop(pid::EDIT_RATE, rational(rate.0, rate.1)) + .data_prop(pid::ORIGIN, 0i64.to_le_bytes().to_vec()) + .with(pid::SEGMENT, Value::Strong(Box::new(segment))); + if number > 0 { + o.set(pid::PHYSICAL_TRACK_NUMBER, Value::Data(number.to_le_bytes().to_vec())); + } + o +} + +fn source_clip(kind: CKind, len: i64, source: [u8; 32], slot: u32, start: i64) -> Obj { + Obj::new(cls::SOURCE_CLIP) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, data_def(kind))) + .data_prop(pid::LENGTH, len.to_le_bytes().to_vec()) + .data_prop(pid::SOURCE_ID, source.to_vec()) + .data_prop(pid::SOURCE_MOB_SLOT_ID, slot.to_le_bytes().to_vec()) + .data_prop(pid::START_TIME, start.to_le_bytes().to_vec()) +} + +fn event_slot(w: &mut W, id: u32, rate: (i64, i64), markers: &[CMarker]) -> Obj { + let comps = markers + .iter() + .map(|m| { + let pos = w.u(m.start, rate); + let len = w.u(m.start + m.duration, rate) - pos; + let mut tags = vec![tagged("Name", &m.name), tagged("Comment", &m.comment)]; + if let Some(c) = &m.color { + tags.push(tagged("Color", c)); + } + Obj::new(cls::COMMENT_MARKER) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::DESCRIPTIVE_METADATA)) + .data_prop(pid::LENGTH, len.to_le_bytes().to_vec()) + .data_prop(pid::POSITION, pos.to_le_bytes().to_vec()) + .data_prop(pid::COMMENT, utf16z(if m.comment.is_empty() { &m.name } else { &m.comment })) + .with(pid::COMPONENT_USER_COMMENTS, Value::StrongVec(tags)) + }) + .collect(); + Obj::new(cls::EVENT_MOB_SLOT) + .data_prop(pid::SLOT_ID, id.to_le_bytes().to_vec()) + .data_prop(pid::SLOT_NAME, utf16z("Markers")) + .data_prop(pid::EVENT_EDIT_RATE, rational(rate.0, rate.1)) + .with( + pid::SEGMENT, + Value::Strong(Box::new( + Obj::new(cls::SEQUENCE) + .with(pid::DATA_DEFINITION, weak(path::DATA_DEFS, ddef::DESCRIPTIVE_METADATA)) + .with(pid::COMPONENTS, Value::StrongVec(comps)), + )), + ) +} + +fn transition_op(kind: CKind, effect: &str) -> Auid { + match kind { + CKind::Sound => def::MONO_AUDIO_DISSOLVE, + CKind::Picture => match effect { + "dip_to_black" => def::VIDEO_FADE_TO_BLACK, + e if e.contains("wipe") => def::SMPTE_VIDEO_WIPE, + _ => def::VIDEO_DISSOLVE, + }, + } +} + +fn descriptor(w: &mut W, s: &Source) -> Obj { + let rate = source_rate(s); + let len = w.u(s.length, rate); + let container = if s.embedded.is_some() { def::CONTAINER_AAF } else { def::CONTAINER_EXTERNAL }; + let mut d = match s.kind { + CKind::Picture => Obj::new(cls::CDCI_DESCRIPTOR) + .data_prop(pid::STORED_WIDTH, s.width.to_le_bytes().to_vec()) + .data_prop(pid::STORED_HEIGHT, s.height.to_le_bytes().to_vec()) + .data_prop(pid::FRAME_LAYOUT, vec![0]) + .data_prop(pid::IMAGE_ASPECT_RATIO, rational(s.width.max(1) as i64, s.height.max(1) as i64)) + .data_prop(pid::VIDEO_LINE_MAP, { + let mut v = 2u32.to_le_bytes().to_vec(); + v.extend_from_slice(&4u32.to_le_bytes()); + v.extend_from_slice(&0i32.to_le_bytes()); + v.extend_from_slice(&0i32.to_le_bytes()); + v + }) + .data_prop(pid::COMPONENT_WIDTH, 8u32.to_le_bytes().to_vec()) + .data_prop(pid::HORIZONTAL_SUBSAMPLING, 2u32.to_le_bytes().to_vec()), + CKind::Sound => { + // Channel counts and rates come from the project: saturate, as these fields can't + // hold more anyway. + let block = s.file_channels.max(1).saturating_mul((s.bits as u32).div_ceil(8)); + Obj::new(cls::PCM_DESCRIPTOR) + .data_prop(pid::AUDIO_SAMPLING_RATE, rational(s.sample_rate as i64, 1)) + .data_prop(pid::LOCKED, vec![1]) + .data_prop(pid::CHANNELS, s.file_channels.max(1).to_le_bytes().to_vec()) + .data_prop(pid::QUANTIZATION_BITS, (s.bits as u32).to_le_bytes().to_vec()) + .data_prop(pid::BLOCK_ALIGN, u16::try_from(block).unwrap_or(u16::MAX).to_le_bytes().to_vec()) + .data_prop(pid::AVERAGE_BPS, block.saturating_mul(s.sample_rate).to_le_bytes().to_vec()) + } + }; + d.set(pid::SAMPLE_RATE, Value::Data(rational(rate.0, rate.1))); + d.set(pid::FILE_LENGTH, Value::Data(len.to_le_bytes().to_vec())); + d.set(pid::CONTAINER_FORMAT, weak(path::CONTAINER_DEFS, container)); + if let Some(p) = &s.path { + let url = if craft_timeline::path::is_absolute(p) { craft_timeline::path::path_to_file_url(p, false) } else { p.clone() }; + d.set(pid::LOCATOR, Value::StrongVec(vec![Obj::new(cls::NETWORK_LOCATOR).data_prop(pid::URL_STRING, utf16z(&url))])); + } + d +} diff --git a/crates/aaf/src/lib.rs b/crates/aaf/src/lib.rs new file mode 100644 index 000000000..ee7448bc0 --- /dev/null +++ b/crates/aaf/src/lib.rs @@ -0,0 +1,60 @@ +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] +//! AAF and OMF: the two mob-based editorial interchange formats, read and written through one +//! composition model. +//! +//! - [`model`]: a [`model::Document`] of compositions (tracks of fillers, source clips and +//! overlapping transitions, with clip gain and markers) and the media sources they reference, +//! with exact times ([`craft_timeline::time::Tick`]). +//! - [`aaf`]: Advanced Authoring Format, Edit Protocol, in structured storage (`craft-cfb`). +//! - [`omf`]: OMF Interchange 2.0 in a Bento container; sound only. +//! +//! Both read into and write from the same model, so an application maps its timeline onto the +//! model once. Audio essence can be embedded: the model carries it as PCM, and the WAVE / AIFF +//! wrappers the formats use are craft-audio's. +//! +//! Clean-room: written from the public specifications only (AMWA *AAF Object Specification* v1.1, +//! *AAF Low-Level Container Specification* v1.0.1, *AAF Edit Protocol* v1.0, SMPTE RP 224 / RP 210 +//! labels; Avid *OMF Interchange Specification* 2.0, Apple *Bento Specification* 1.0d5). No file +//! I/O: documents are bytes and media references are strings. +//! +//! Input is untrusted: a damaged or crafted file gives an [`Error`] or a [`Report`] entry, never +//! a panic, a hang or an allocation sized by a count in the file. + +pub mod aaf; +pub mod model; +pub mod omf; +mod pcm; +#[cfg(test)] +mod roundtrip_tests; +#[cfg(test)] +mod testdoc; + +pub use craft_timeline::report::Report; + +/// Error from a reader or writer. Unsupported *features* never error; they go in the [`Report`]. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The bytes are not a readable document of the format. + #[error("{format} parse error: {message}")] + Parse { format: &'static str, message: String }, + /// The document has no composition. + #[error("the document contains no timeline")] + Empty, + /// The document could not be written. + #[error("{0}")] + Other(String), +} + +pub type Result = std::result::Result; + +/// Who a written file says made it (the AAF `Identification` object, the OMF `IDNT` object). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Identity<'a> { + pub company: &'a str, + pub product: &'a str, + /// The product's version, as text. + pub version: &'a str, + pub platform: &'a str, + /// AAF `ProductID`: an AUID naming the product. + pub product_id: [u8; 16], +} diff --git a/crates/aaf/src/model.rs b/crates/aaf/src/model.rs new file mode 100644 index 000000000..3dff507be --- /dev/null +++ b/crates/aaf/src/model.rs @@ -0,0 +1,185 @@ +//! A format-neutral mob-style composition model shared by AAF and OMF. +//! +//! Both formats describe a timeline as a composition of slots (tracks) whose segments are +//! sequences of fillers, source clips and transitions, where a transition *overlaps* the end of +//! the segment before it and the start of the segment after it (the sequence's length is the sum of +//! its segment lengths minus its transition lengths). Source clips reference media through master +//! mobs and file source mobs: here, a [`Source`] per essence, grouped into one media item by its +//! key. All times are ticks; the format serialisers convert to and from edit units. + +use craft_timeline::time::{FrameRate, TICKS_PER_SECOND, Tick}; + +/// Picture or sound. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CKind { + Picture, + Sound, +} + +/// A whole document: compositions and the media they reference. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Document { + /// The top-level compositions. + pub compositions: Vec, + pub sources: Vec, + /// Compositions that are only used inside others (nested sequences); a [`Source`] refers to + /// one by its index here. They may nest further. + pub nested: Vec, +} + +/// How a nested sequence is written. Premiere Pro writes one as a composition of its own in AAF +/// (clips refer to it the way they refer to media) and renders its sound in OMF, which has no +#[derive(Clone, Debug, PartialEq)] +pub struct Composition { + pub name: String, + pub rate: FrameRate, + pub sample_rate: u32, + pub width: u32, + pub height: u32, + pub start_tc: i64, + pub drop: bool, + pub tracks: Vec, + pub markers: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CTrack { + pub kind: CKind, + pub name: String, + /// Physical track number (1-based, per kind). + pub number: u32, + /// Sound: channels of the track (1 mono, 2 stereo, 6 5.1). + pub channels: u32, + pub items: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum CItem { + Filler(Tick), + Clip(CClip), + Transition(CTransition), +} + +impl CItem { + /// The item's length on the track. + pub fn len(&self) -> Tick { + match self { + CItem::Filler(l) => *l, + CItem::Clip(c) => c.len, + CItem::Transition(t) => t.len, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CClip { + pub len: Tick, + /// Index into [`Document::sources`]. + pub source: usize, + /// Source (file) time of the segment's first frame. + pub start: Tick, + pub gain: Option, + pub name: String, +} + +/// Clip gain (linear amplitude). +#[derive(Clone, Debug, PartialEq)] +pub enum Gain { + Constant(f64), + /// Points at offsets from the segment start; `linear` false = hold (step) interpolation. + Varying { + linear: bool, + points: Vec<(Tick, f64)>, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CTransition { + pub len: Tick, + /// Where the cut lies, from the transition start. + pub cut: Tick, + /// The transition, by a name of the writing application's choosing; it is kept in a private tag + /// and comes back unchanged. Names the formats themselves can say: `cross_dissolve` and + /// `dip_to_black` (picture), any name containing `wipe` (a SMPTE wipe), `constant_power` (sound). + /// A file without the tag reads as one of these. + pub effect: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CMarker { + pub start: Tick, + pub duration: Tick, + pub name: String, + pub comment: String, + pub color: Option, +} + +/// One essence: a file (or embedded data) carrying the picture, or some channels of sound, of a +/// media item. +#[derive(Clone, Debug, PartialEq)] +pub struct Source { + /// Groups the sources of one media item (one master mob). + pub key: String, + pub name: String, + pub kind: CKind, + pub path: Option, + /// Sound: the (0-based) channel of the file this source exposes (broken out to mono), or + /// `None` for all of them. + pub channel: Option, + /// Sound: channels this source exposes (1 when `channel` is set, else `file_channels`). + pub channels: u32, + /// Sound: channels of the file / embedded data. + pub file_channels: u32, + pub width: u32, + pub height: u32, + /// Picture: the frame rate of the media. + pub frame_rate: FrameRate, + pub sample_rate: u32, + pub bits: u16, + pub length: Tick, + /// Media time of the essence's time 0 (trimmed / consolidated essence). + pub offset: Tick, + /// Start timecode in frames at `tc_rate`. + pub start_tc: Option, + pub tc_rate: FrameRate, + pub embedded: Option>, + pub markers: Vec, + /// Not media but a nested composition: its index in [`Document::nested`]. `start` of a clip + /// that uses it is a time in that composition. + pub nested: Option, +} + +impl Source { + /// A picture source with no length: a still image. + pub fn is_still(&self) -> bool { + self.kind == CKind::Picture && self.length == Tick::ZERO + } +} + +/// The largest time read from a document (about 3.3 days). +pub const MAX_TIME: Tick = Tick(1 << 56); + +/// Ticks of `n` edit units at rate `num/den` (rounded to the nearest tick). +pub fn units_to_ticks(n: i64, num: i64, den: i64) -> Tick { + if num <= 0 || den <= 0 { + return Tick::ZERO; + } + let t = n as i128 * den as i128 * TICKS_PER_SECOND as i128; + let q = t.div_euclid(num as i128); + let r = t.rem_euclid(num as i128); + // documents are untrusted: keep every time far from overflow (±3 days) + Tick((q + if r * 2 >= num as i128 { 1 } else { 0 }).clamp(-MAX_TIME.0 as i128, MAX_TIME.0 as i128) as i64) +} + +/// Edit units at rate `num/den` nearest to `t`; the flag is false when `t` is not on a unit. +pub fn ticks_to_units(t: Tick, num: i64, den: i64) -> (i64, bool) { + if num <= 0 || den <= 0 { + return (0, false); + } + let x = t.0 as i128 * num as i128; + let d = den as i128 * TICKS_PER_SECOND as i128; + let q = x.div_euclid(d); + let r = x.rem_euclid(d); + let n = q + if r * 2 >= d { 1 } else { 0 }; + (n.clamp(i64::MIN as i128, i64::MAX as i128) as i64, r == 0) +} diff --git a/crates/aaf/src/omf.rs b/crates/aaf/src/omf.rs new file mode 100644 index 000000000..57e0f756c --- /dev/null +++ b/crates/aaf/src/omf.rs @@ -0,0 +1,47 @@ +//! OMF Interchange 2.0 for audio post: written, and the same structures read. +//! +//! Written from the public *OMF Interchange Specification Version 2.0* (Avid Technology, 1995/97) +//! and Apple's *Bento Specification* revision 1.0d5 for the container ([`bento`]). +//! +//! The file holds a composition mob (`CMOB`) with a timecode slot and one sound slot per audio +//! track (one per channel when broken out to mono): sequences (`SEQU`) of fillers (`FILL`), source +//! clips (`SCLP`) and transitions (`TRAN` with a `SimpleMonoAudioDissolve` effect); clip volume is a +//! `MonoAudioGain` effect (`EFFE`) whose slot −1 is the clip and slot 1 the amplitude +//! (`CVAL` constant or `VVAL` keyframes). Every media item has a master mob (`MMOB`), a file source +//! mob (`SMOB` with a `WAVD` / `AIFD` descriptor: embedded essence in a `WAVE` media data object, +//! or a locator to a separate file) and a tape source mob carrying its timecode. Times are in +//! samples (sound slots use the sample rate as edit rate) so edits are sample-exact. +//! +//! Only sound is written: picture tracks and markers of the model are left out, and a nested +//! composition is not written as one (readers of OMF do not follow compositions). A caller with +//! nested sequences mixes their sound and passes it as media like any other; Premiere Pro's OMF +//! export does the same. +//! +//! Private properties. `FilmCraft:SCLP:ClipName` (a clip's name) and `FilmCraft:EFFE:EffectID` (a +//! transition's name) are not in the specification; they were first written by FilmCraft and keep +//! their names so that existing files read back. + +pub(crate) mod bento; +mod read; +mod write; + +use crate::model::Document; +use crate::{Identity, Report, Result}; + +/// Write the sound of `doc`'s first composition as an OMF 2.0 file. +pub fn write(doc: &Document, identity: &Identity<'_>, report: &mut Report) -> Result> { + write::write(doc, identity, report) +} + +/// Read an OMF 2.0 file (as written by [`write`] and by applications using the same structures). +pub fn read(bytes: &[u8], report: &mut Report) -> Result { + read::read(bytes, report) +} + +/// Whether `bytes` end with a Bento container label (OMF files do). +pub fn sniff(bytes: &[u8]) -> bool { + bento::sniff(bytes) +} + +#[cfg(test)] +mod tests; diff --git a/crates/aaf/src/omf/bento.rs b/crates/aaf/src/omf/bento.rs new file mode 100644 index 000000000..00a7e2a26 --- /dev/null +++ b/crates/aaf/src/omf/bento.rs @@ -0,0 +1,407 @@ +//! The Bento container (Apple, *Bento Specification* revision 1.0d5), the storage layer of OMF +//! Interchange 2.0 files. +//! +//! A Bento container is a heap of value bytes, a table of contents (TOC) describing every value of +//! every object, and a fixed-size label at the very end of the file that locates the TOC: +//! +//! ```text +//! label (24 bytes, big-endian): magic A4 'C' 'M' A5 'H' 'd' 'r' D7, u16 flags, u16 buffer size +//! (KiB), u16 major version (1), u16 minor version (0), +//! u32 TOC offset, u32 TOC size +//! ``` +//! +//! Every value belongs to an (object id, property id, type id) triple. Properties and types are +//! themselves objects carrying a global name (`"OMFI:CPNT:Length"`, `"omfi:Length32"`). The TOC +//! is a stream of one-byte operations, each followed by its operands (big-endian): +//! +//! | op | operands | meaning | +//! |---|---|---| +//! | 1 NewObject | u32 id | following entries belong to this object | +//! | 2 NewProperty | u32 id | … to this property | +//! | 3 NewType | u32 id | starts a new value of this type | +//! | 4 ExplicitGen | u32 | generation of the value | +//! | 5 Offset4Len4 | u32 offset, u32 length | a value segment in the file | +//! | 6 ContdOffset4Len4 | u32 offset, u32 length | a continuation segment | +//! | 7 Offset8Len4 / 8 Contd… | u64 offset, u32 length | segments beyond 4 GiB | +//! | 9–13 Immediate0–4 | 4 bytes | a value of 0–4 bytes stored in the TOC | +//! | 14 ContdImmediate4 | 4 bytes | continuation | +//! | 15 ReferenceListID | u32 id | the object holding this value's reference list | +//! | 24 EndOfBufr | — | skip to the end of the current TOC buffer | +//! | 0xFF Padding | — | ignored | +//! +//! Object references (OMF's `omfi:ObjRef`) are 4-byte keys resolved through the referencing +//! object's reference list (standard property 22: pairs of u32 key, u32 object id). FilmCraft +//! uses the referenced object's id as the key. + +use std::collections::{BTreeMap, HashMap}; + +pub(crate) const MAGIC: [u8; 8] = [0xA4, b'C', b'M', 0xA5, b'H', b'd', b'r', 0xD7]; +pub(crate) const LABEL_SIZE: usize = 24; + +// standard object ids +const TOC_OBJECT: u32 = 1; +const TOC_SEED: u32 = 2; +const TOC_MIN_SEED: u32 = 3; +const TOC_TYPE: u32 = 19; +const TYPE_7BIT_ASCII: u32 = 21; +pub(crate) const OBJ_REFERENCES: u32 = 22; +const GLOBAL_TYPE_NAME: u32 = 23; +const GLOBAL_PROP_NAME: u32 = 24; +const MIN_USER_ID: u32 = 100; + +const OP_NEW_OBJECT: u8 = 1; +const OP_NEW_PROPERTY: u8 = 2; +const OP_NEW_TYPE: u8 = 3; +const OP_EXPLICIT_GEN: u8 = 4; +const OP_OFFSET4_LEN4: u8 = 5; +const OP_CONTD_OFFSET4_LEN4: u8 = 6; +const OP_OFFSET8_LEN4: u8 = 7; +const OP_CONTD_OFFSET8_LEN4: u8 = 8; +const OP_IMMEDIATE0: u8 = 9; +const OP_IMMEDIATE4: u8 = 13; +const OP_CONTD_IMMEDIATE4: u8 = 14; +const OP_REFERENCE_LIST_ID: u8 = 15; +const OP_END_OF_BUFFER: u8 = 24; +const OP_PADDING: u8 = 0xFF; + +const TOC_BUFFER_KIB: u16 = 8; + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Seg { + Imm(Vec), + At(u64, u32), +} + +/// Bento values are metadata, not essence payloads. Limit reassembled segments so repeated +/// references cannot amplify a small OMF into an enormous allocation. +const MAX_VALUE_BYTES: usize = 16 << 20; + +/// Most bytes of global names (property and type names) kept for one container. Real files name a +/// few hundred short strings; without a cap, many objects naming one large shared range would each +/// retain their own copy. +const MAX_NAME_BYTES: usize = 4 << 20; + +/// Builds a Bento container. +pub(crate) struct Writer { + data: Vec, + names: HashMap<(u32, String), u32>, + next: u32, + /// (object, property, type, segments) + entries: Vec<(u32, u32, u32, Vec)>, +} + +impl Writer { + pub fn new() -> Writer { + Writer { data: Vec::new(), names: HashMap::new(), next: MIN_USER_ID, entries: Vec::new() } + } + + fn named(&mut self, kind: u32, name: &str) -> u32 { + if let Some(&id) = self.names.get(&(kind, name.to_string())) { + return id; + } + let id = self.new_object(); + let mut v = name.as_bytes().to_vec(); + v.push(0); + let seg = self.store(&v); + self.entries.push((id, kind, TYPE_7BIT_ASCII, vec![seg])); + self.names.insert((kind, name.to_string()), id); + id + } + + pub fn property(&mut self, name: &str) -> u32 { + self.named(GLOBAL_PROP_NAME, name) + } + + pub fn type_id(&mut self, name: &str) -> u32 { + self.named(GLOBAL_TYPE_NAME, name) + } + + pub fn new_object(&mut self) -> u32 { + let id = self.next; + self.next += 1; + id + } + + fn store(&mut self, v: &[u8]) -> Seg { + if v.len() <= 4 { + return Seg::Imm(v.to_vec()); + } + let at = self.data.len() as u64; + self.data.extend_from_slice(v); + Seg::At(at, v.len() as u32) + } + + /// Set a value of `obj` (values of more than 4 GiB are not supported by OMF). + pub fn set(&mut self, obj: u32, property: &str, ty: &str, value: &[u8]) { + let p = self.property(property); + let t = self.type_id(ty); + let seg = self.store(value); + self.entries.push((obj, p, t, vec![seg])); + } + + /// The reference list of `obj` (keys are object ids). + pub fn set_references(&mut self, obj: u32, targets: &[u32]) { + let mut v = Vec::with_capacity(targets.len() * 8); + for t in targets { + v.extend_from_slice(&t.to_be_bytes()); + v.extend_from_slice(&t.to_be_bytes()); + } + let seg = self.store(&v); + self.entries.push((obj, OBJ_REFERENCES, TYPE_7BIT_ASCII, vec![seg])); + } + + pub fn finish(mut self) -> Vec { + let seed = self.next; + self.entries.push((TOC_OBJECT, TOC_SEED, TOC_TYPE, vec![Seg::Imm(seed.to_be_bytes().to_vec())])); + self.entries.push((TOC_OBJECT, TOC_MIN_SEED, TOC_TYPE, vec![Seg::Imm(MIN_USER_ID.to_be_bytes().to_vec())])); + self.entries.sort_by_key(|e| (e.0, e.1, e.2)); + let mut toc = Vec::new(); + let (mut cur_obj, mut cur_prop) = (u32::MAX, u32::MAX); + for (obj, prop, ty, segs) in &self.entries { + if *obj != cur_obj { + toc.push(OP_NEW_OBJECT); + toc.extend_from_slice(&obj.to_be_bytes()); + cur_obj = *obj; + cur_prop = u32::MAX; + } + if *prop != cur_prop { + toc.push(OP_NEW_PROPERTY); + toc.extend_from_slice(&prop.to_be_bytes()); + cur_prop = *prop; + } + toc.push(OP_NEW_TYPE); + toc.extend_from_slice(&ty.to_be_bytes()); + for (i, s) in segs.iter().enumerate() { + match s { + Seg::Imm(b) => { + toc.push(if i > 0 { OP_CONTD_IMMEDIATE4 } else { OP_IMMEDIATE0 + b.len() as u8 }); + let mut w = [0u8; 4]; + w[..b.len()].copy_from_slice(b); + toc.extend_from_slice(&w); + } + Seg::At(off, len) if *off <= u32::MAX as u64 => { + toc.push(if i > 0 { OP_CONTD_OFFSET4_LEN4 } else { OP_OFFSET4_LEN4 }); + toc.extend_from_slice(&(*off as u32).to_be_bytes()); + toc.extend_from_slice(&len.to_be_bytes()); + } + Seg::At(off, len) => { + toc.push(if i > 0 { OP_CONTD_OFFSET8_LEN4 } else { OP_OFFSET8_LEN4 }); + toc.extend_from_slice(&off.to_be_bytes()); + toc.extend_from_slice(&len.to_be_bytes()); + } + } + } + } + let mut out = self.data; + let toc_at = out.len() as u64; + out.extend_from_slice(&toc); + let mut label = MAGIC.to_vec(); + label.extend_from_slice(&0u16.to_be_bytes()); // flags + label.extend_from_slice(&TOC_BUFFER_KIB.to_be_bytes()); + label.extend_from_slice(&1u16.to_be_bytes()); + label.extend_from_slice(&0u16.to_be_bytes()); + label.extend_from_slice(&(toc_at.min(u32::MAX as u64) as u32).to_be_bytes()); + label.extend_from_slice(&(toc.len() as u32).to_be_bytes()); + out.extend_from_slice(&label); + out + } +} + +/// One value of a parsed object. +#[derive(Clone, Debug)] +pub(crate) struct Prop { + pub prop: u32, + #[allow(dead_code)] + pub ty: u32, + segs: Vec, +} + +/// A parsed Bento container. +pub(crate) struct Container<'a> { + data: &'a [u8], + pub objects: BTreeMap>, + names: HashMap, + by_name: HashMap, +} + +fn be32(b: &[u8], at: usize) -> Option { + b.get(at..at + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])) +} + +/// Whether `b` ends with a Bento label. +pub(crate) fn sniff(b: &[u8]) -> bool { + b.len() >= LABEL_SIZE && b[b.len() - LABEL_SIZE..b.len() - LABEL_SIZE + 8] == MAGIC +} + +impl<'a> Container<'a> { + pub fn open(data: &'a [u8]) -> Result, String> { + if !sniff(data) { + return Err("no Bento label at the end of the file".into()); + } + let l = &data[data.len() - LABEL_SIZE..]; + let buf = (u16::from_be_bytes([l[10], l[11]]) as usize).max(1) * 1024; + let toc_at = be32(l, 16).unwrap_or(0) as usize; + let toc_len = be32(l, 20).unwrap_or(0) as usize; + let toc = data.get(toc_at..toc_at.checked_add(toc_len).ok_or("bad TOC size")?).ok_or("the TOC lies outside the file")?; + let mut c = Container { data, objects: BTreeMap::new(), names: HashMap::new(), by_name: HashMap::new() }; + let (mut obj, mut prop) = (0u32, 0u32); + let mut i = 0; + while i < toc.len() { + let op = toc[i]; + i += 1; + let need = |n: usize| -> Result<&[u8], String> { toc.get(i..i + n).ok_or_else(|| "truncated TOC".to_string()) }; + match op { + OP_NEW_OBJECT => { + obj = be32(need(4)?, 0).unwrap_or(0); + i += 4; + } + OP_NEW_PROPERTY => { + prop = be32(need(4)?, 0).unwrap_or(0); + i += 4; + } + OP_NEW_TYPE => { + let ty = be32(need(4)?, 0).unwrap_or(0); + i += 4; + c.objects.entry(obj).or_default().push(Prop { prop, ty, segs: Vec::new() }); + } + OP_EXPLICIT_GEN | OP_REFERENCE_LIST_ID => { + need(4)?; + i += 4; + } + OP_OFFSET4_LEN4 | OP_CONTD_OFFSET4_LEN4 => { + let b = need(8)?; + let seg = Seg::At(be32(b, 0).unwrap_or(0) as u64, be32(b, 4).unwrap_or(0)); + i += 8; + c.push_seg(obj, seg)?; + } + OP_OFFSET8_LEN4 | OP_CONTD_OFFSET8_LEN4 => { + let b = need(12)?; + let off = u64::from_be_bytes(b[..8].try_into().map_err(|_| "truncated TOC")?); + let seg = Seg::At(off, be32(b, 8).unwrap_or(0)); + i += 12; + c.push_seg(obj, seg)?; + } + x @ (OP_IMMEDIATE0..=OP_IMMEDIATE4 | OP_CONTD_IMMEDIATE4) => { + let b = need(4)?; + let n = if x == OP_CONTD_IMMEDIATE4 { 4 } else { (x - OP_IMMEDIATE0) as usize }; + let seg = Seg::Imm(b[..n].to_vec()); + i += 4; + c.push_seg(obj, seg)?; + } + OP_END_OF_BUFFER => { + // the rest of this TOC buffer is unused + i = (i - 1) / buf * buf + buf; + } + OP_PADDING | 0 => {} + other => return Err(format!("unknown TOC operation {other}")), + } + } + // global names + let ids: Vec = c.objects.keys().copied().collect(); + let mut name_bytes = 0usize; + for id in ids { + let name = c.objects[&id].iter().find(|p| p.prop == GLOBAL_PROP_NAME || p.prop == GLOBAL_TYPE_NAME).and_then(|p| c.value(p).ok()); + if let Some(n) = name { + name_bytes = name_bytes.saturating_add(n.len()); + if name_bytes > MAX_NAME_BYTES { + return Err("Bento global names exceed the name budget".into()); + } + let s = String::from_utf8_lossy(&n).trim_end_matches('\0').to_string(); + c.by_name.insert(s.clone(), id); + c.names.insert(id, s); + } + } + Ok(c) + } + + fn push_seg(&mut self, obj: u32, seg: Seg) -> Result<(), String> { + let p = self.objects.get_mut(&obj).and_then(|v| v.last_mut()).ok_or("a value without a type in the TOC")?; + if p.segs.len() > 1 << 20 { + return Err("too many value segments".into()); + } + p.segs.push(seg); + Ok(()) + } + + /// The bytes of a value. + pub fn value(&self, p: &Prop) -> Result, String> { + let total = p.segs.iter().try_fold(0usize, |total, s| { + let len = match s { + Seg::Imm(b) => b.len(), + Seg::At(_, len) => *len as usize, + }; + total.checked_add(len).ok_or_else(|| "Bento value length overflows".to_string()) + })?; + if total > MAX_VALUE_BYTES { + return Err("Bento value exceeds the decoded-value budget".into()); + } + let mut out = Vec::new(); + out.try_reserve_exact(total).map_err(|_| "cannot allocate Bento value")?; + for s in &p.segs { + match s { + Seg::Imm(b) => out.extend_from_slice(b), + Seg::At(off, len) => { + let start = usize::try_from(*off).map_err(|_| "value offset too large")?; + let b = + self.data.get(start..start.checked_add(*len as usize).ok_or("bad value length")?).ok_or("a value lies outside the file")?; + out.extend_from_slice(b); + } + } + } + Ok(out) + } + + pub fn id_of(&self, name: &str) -> Option { + self.by_name.get(name).copied() + } + + #[allow(dead_code)] + pub fn name_of(&self, id: u32) -> Option<&str> { + self.names.get(&id).map(String::as_str) + } + + /// The first value of property `name` of `obj`. + pub fn get(&self, obj: u32, name: &str) -> Option> { + let pid = self.id_of(name)?; + let p = self.objects.get(&obj)?.iter().find(|p| p.prop == pid)?; + self.value(p).ok() + } + + /// Resolve an object reference key of `obj` through its reference list. + pub fn resolve(&self, obj: u32, key: u32) -> u32 { + if let Some(p) = self.objects.get(&obj).and_then(|v| v.iter().find(|p| p.prop == OBJ_REFERENCES)) + && let Ok(v) = self.value(p) + { + for pair in v.as_chunks::<8>().0 { + if be32(pair, 0) == Some(key) { + return be32(pair, 4).unwrap_or(key); + } + } + } + key + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn many_objects_cannot_name_themselves_with_one_shared_range() { + let mut w = Writer::new(); + w.data = vec![b'a'; 1 << 20]; + let ids: Vec = (0..8).map(|_| w.new_object()).collect(); + for id in ids { + w.entries.push((id, GLOBAL_PROP_NAME, TYPE_7BIT_ASCII, vec![Seg::At(0, 1 << 20)])); + } + let file = w.finish(); + assert!(Container::open(&file).err().is_some_and(|e| e.contains("name budget"))); + } + + #[test] + fn repeated_segments_cannot_expand_a_value_past_its_budget() { + let p = Prop { prop: 1, ty: 1, segs: vec![Seg::At(0, MAX_VALUE_BYTES as u32), Seg::Imm(vec![0])] }; + let c = Container { data: &[], objects: BTreeMap::new(), names: HashMap::new(), by_name: HashMap::new() }; + assert!(c.value(&p).unwrap_err().contains("budget")); + } +} diff --git a/crates/aaf/src/omf/read.rs b/crates/aaf/src/omf/read.rs new file mode 100644 index 000000000..50e4b270c --- /dev/null +++ b/crates/aaf/src/omf/read.rs @@ -0,0 +1,438 @@ +//! OMF 2.0 objects (Bento) → composition model. + +use std::collections::{HashMap, HashSet}; + +use craft_timeline::time::{FrameRate, Tick}; + +use super::bento::Container; +use crate::model::{CClip, CItem, CKind, CTrack, CTransition, Composition, Document, Gain, Source, units_to_ticks}; +use crate::{Error, Report, Result}; + +type Uid = [u8; 12]; + +const MAX_REFERENCE_VISITS: usize = 65_536; + +struct R<'a, 'b> { + c: &'b Container<'a>, + report: &'b mut Report, + /// big-endian values ("MM"); "II" files are little-endian + be: bool, + mobs: HashMap, + media: HashMap>, + doc: Document, + sources: HashMap<(Uid, u32, String), usize>, +} + +pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result { + let perr = |m: String| Error::Parse { format: "OMF", message: m }; + let c = Container::open(bytes).map_err(perr)?; + let class_of = |o: u32| c.get(o, "OMFI:OOBJ:ObjClass").and_then(|v| v.get(..4).map(|b| [b[0], b[1], b[2], b[3]])); + let head = c.objects.keys().copied().find(|&o| class_of(o) == Some(*b"HEAD")).ok_or_else(|| perr("no OMF header object".into()))?; + let be = c.get(head, "OMFI:HEAD:ByteOrder").is_none_or(|v| v.first() != Some(&0x49)); + let mut r = R { c: &c, report, be, mobs: HashMap::new(), media: HashMap::new(), doc: Document::default(), sources: HashMap::new() }; + let mob_list = r.refs(head, "OMFI:HEAD:Mobs"); + let mob_list = if mob_list.is_empty() { + c.objects.keys().copied().filter(|&o| matches!(class_of(o).as_ref(), Some(b"CMOB" | b"MMOB" | b"SMOB"))).collect() + } else { + mob_list + }; + for &m in &mob_list { + if let Some(id) = r.uid(m, "OMFI:MOBJ:MobID") { + r.mobs.insert(id, m); + } + } + let md = r.refs(head, "OMFI:HEAD:MediaData"); + let md = + if md.is_empty() { c.objects.keys().copied().filter(|&o| matches!(class_of(o).as_ref(), Some(b"WAVE" | b"AIFC"))).collect() } else { md }; + for m in md { + let Some(id) = r.uid(m, "OMFI:MDAT:MobID") else { continue }; + if let Some(d) = c.get(m, "OMFI:WAVE:Data") { + r.media.insert(id, d); + } else if let Some(d) = c.get(m, "OMFI:AIFC:Data") { + r.media.insert(id, d); + } + } + let cmobs: Vec = mob_list.iter().copied().filter(|&m| class_of(m) == Some(*b"CMOB")).collect(); + let mut referenced = HashSet::new(); + let mut visited = HashSet::new(); + let mut visits = 0; + for &m in &cmobs { + r.collect_refs(m, &mut referenced, &mut visited, &mut visits, 0); + } + let primary: Vec = r.refs(head, "OMFI:HEAD:PrimaryMobs").into_iter().filter(|m| cmobs.contains(m)).collect(); + let top: Vec = if !primary.is_empty() { + primary + } else { + cmobs.iter().copied().filter(|m| r.uid(*m, "OMFI:MOBJ:MobID").is_none_or(|id| !referenced.contains(&id))).collect() + }; + for m in top { + let comp = r.composition(m); + r.doc.compositions.push(comp); + } + if r.doc.compositions.is_empty() { + return Err(Error::Empty); + } + Ok(r.doc) +} + +impl R<'_, '_> { + fn class(&self, o: u32) -> [u8; 4] { + self.c.get(o, "OMFI:OOBJ:ObjClass").and_then(|v| v.get(..4).map(|b| [b[0], b[1], b[2], b[3]])).unwrap_or(*b"????") + } + fn u32_of(&self, b: &[u8]) -> Option { + let a: [u8; 4] = b.get(..4)?.try_into().ok()?; + Some(if self.be { u32::from_be_bytes(a) } else { u32::from_le_bytes(a) }) + } + fn i32(&self, o: u32, p: &str) -> Option { + self.c.get(o, p).and_then(|v| self.u32_of(&v)).map(|x| x as i32 as i64) + } + fn u32(&self, o: u32, p: &str) -> Option { + self.c.get(o, p).and_then(|v| self.u32_of(&v)) + } + fn u16(&self, o: u32, p: &str) -> Option { + let v = self.c.get(o, p)?; + let a: [u8; 2] = v.get(..2)?.try_into().ok()?; + Some(if self.be { u16::from_be_bytes(a) } else { u16::from_le_bytes(a) }) + } + fn rational(&self, o: u32, p: &str) -> Option<(i64, i64)> { + let v = self.c.get(o, p)?; + self.rational_of(&v) + } + fn rational_of(&self, v: &[u8]) -> Option<(i64, i64)> { + Some((self.u32_of(v)? as i32 as i64, self.u32_of(v.get(4..)?)? as i32 as i64)) + } + fn string(&self, o: u32, p: &str) -> Option { + self.c.get(o, p).map(|v| String::from_utf8_lossy(&v).trim_end_matches('\0').to_string()) + } + fn uid(&self, o: u32, p: &str) -> Option { + self.c.get(o, p).and_then(|v| v.get(..12).and_then(|b| b.try_into().ok())) + } + fn r#ref(&self, o: u32, p: &str) -> Option { + let v = self.c.get(o, p)?; + let key = u32::from_be_bytes(v.get(..4)?.try_into().ok()?); + Some(self.c.resolve(o, key)) + } + fn refs(&self, o: u32, p: &str) -> Vec { + let Some(v) = self.c.get(o, p) else { return Vec::new() }; + if v.len() < 2 { + return Vec::new(); + } + let n = u16::from_be_bytes([v[0], v[1]]) as usize; + v[2..].as_chunks::<4>().0.iter().take(n).map(|k| self.c.resolve(o, u32::from_be_bytes([k[0], k[1], k[2], k[3]]))).collect() + } + fn data_kind(&self, o: u32) -> String { + self.r#ref(o, "OMFI:CPNT:DataKind").and_then(|d| self.string(d, "OMFI:DDEF:DataKindID")).unwrap_or_default() + } + fn len(&self, o: u32) -> i64 { + self.i32(o, "OMFI:CPNT:Length").unwrap_or(0).max(0) + } + + fn collect_refs(&self, o: u32, out: &mut HashSet, visited: &mut HashSet, visits: &mut usize, depth: usize) { + if depth > 64 || !visited.insert(o) || *visits >= MAX_REFERENCE_VISITS { + return; + } + *visits += 1; + if self.class(o) == *b"SCLP" + && let Some(id) = self.uid(o, "OMFI:SCLP:SourceID") + { + out.insert(id); + } + for p in ["OMFI:MOBJ:Slots", "OMFI:SEQU:Components", "OMFI:EFFE:EffectSlots"] { + for c in self.refs(o, p) { + self.collect_refs(c, out, visited, visits, depth + 1); + } + } + for p in ["OMFI:MSLT:Segment", "OMFI:ESLT:ArgValue"] { + if let Some(c) = self.r#ref(o, p) { + self.collect_refs(c, out, visited, visits, depth + 1); + } + } + } + + fn composition(&mut self, m: u32) -> Composition { + let name = self.string(m, "OMFI:MOBJ:Name").unwrap_or_else(|| "Sequence".into()); + let mut comp = Composition { + name, + rate: FrameRate::FPS_25, + sample_rate: 48_000, + width: 1920, + height: 1080, + start_tc: 0, + drop: false, + tracks: Vec::new(), + markers: Vec::new(), + }; + let slots = self.refs(m, "OMFI:MOBJ:Slots"); + let mut na = 0; + for s in slots { + let Some(seg) = self.r#ref(s, "OMFI:MSLT:Segment") else { continue }; + let rate = self.rational(s, "OMFI:MSLT:EditRate").filter(|r| r.0 > 0 && r.1 > 0).unwrap_or((25, 1)); + let kind = self.data_kind(seg); + if self.class(seg) == *b"TCCP" || kind == "omfi:data:Timecode" { + comp.rate = FrameRate::new(rate.0, rate.1); + if self.class(seg) == *b"TCCP" { + comp.start_tc = self.i32(seg, "OMFI:TCCP:Start").unwrap_or(0); + comp.drop = self.c.get(seg, "OMFI:TCCP:Drop").and_then(|v| v.first().copied()).unwrap_or(0) != 0; + } + continue; + } + let ckind = match kind.as_str() { + "omfi:data:Sound" => CKind::Sound, + "omfi:data:Picture" | "omfi:data:PictureWithMatte" => CKind::Picture, + _ => { + self.report.info("an OMF slot of an unsupported data kind was skipped"); + continue; + } + }; + if ckind == CKind::Picture { + self.report.info("OMF picture slots are not imported (audio only)"); + continue; + } + if rate.1 == 1 && rate.0 >= 8000 { + comp.sample_rate = rate.0 as u32; + } + let items = self.segment(seg, rate, 0); + na += 1; + let td = self.r#ref(s, "OMFI:MSLT:TrackDesc"); + let tname = td.and_then(|t| self.string(t, "OMFI:TRKD:TrackName")).unwrap_or_else(|| format!("A{na}")); + let number = td.and_then(|t| self.u32(t, "OMFI:TRKD:PhysicalTrack")).unwrap_or(na); + let channels = items + .iter() + .filter_map(|i| match i { + CItem::Clip(c) => Some(self.doc.sources[c.source].channels), + _ => None, + }) + .max() + .unwrap_or(1) + .min(6); + comp.tracks.push(CTrack { kind: CKind::Sound, name: tname, number, channels, items }); + } + comp + } + + fn segment(&mut self, seg: u32, rate: (i64, i64), depth: usize) -> Vec { + let len = units_to_ticks(self.len(seg), rate.0, rate.1); + if depth > 32 { + return vec![CItem::Filler(len)]; + } + match &self.class(seg) { + b"SEQU" => { + let mut out = Vec::new(); + for c in self.refs(seg, "OMFI:SEQU:Components") { + out.extend(self.segment(c, rate, depth + 1)); + } + out + } + b"FILL" => vec![CItem::Filler(len)], + b"SCLP" => vec![self.clip(seg, rate)], + b"TRAN" => { + let cut = units_to_ticks(self.i32(seg, "OMFI:TRAN:CutPoint").unwrap_or(0), rate.0, rate.1); + let effect = self + .r#ref(seg, "OMFI:TRAN:Effect") + .and_then(|e| self.string(e, "FilmCraft:EFFE:EffectID")) + .unwrap_or_else(|| "constant_power".into()); + vec![CItem::Transition(CTransition { len, cut: cut.clamp(Tick::ZERO, len), effect })] + } + b"EFFE" => { + let kind = self.r#ref(seg, "OMFI:EFFE:EffectKind").and_then(|k| self.string(k, "OMFI:EDEF:EffectID")).unwrap_or_default(); + let slots = self.refs(seg, "OMFI:EFFE:EffectSlots"); + let arg = |r: &Self, id: i64| { + slots.iter().copied().find(|&s| r.i32(s, "OMFI:ESLT:ArgID") == Some(id)).and_then(|s| r.r#ref(s, "OMFI:ESLT:ArgValue")) + }; + let Some(input) = arg(self, -1).or_else(|| arg(self, 1).filter(|_| kind != "omfi:effect:MonoAudioGain")) else { + return vec![CItem::Filler(len)]; + }; + let gain = if kind == "omfi:effect:MonoAudioGain" { + arg(self, 1).and_then(|v| self.gain(v, len)) + } else { + self.report.warn("OMF effects other than audio gain are not imported (their input is used)"); + None + }; + let mut items = self.segment(input, rate, depth + 1); + if let (Some(g), [CItem::Clip(c)]) = (gain, items.as_mut_slice()) { + c.gain = Some(g); + } + items + } + _ => { + self.report.info("an unsupported OMF component was imported as a gap"); + vec![CItem::Filler(len)] + } + } + } + + fn amp(&self, v: &[u8]) -> Option { + self.rational_of(v).filter(|r| r.1 != 0).map(|(n, d)| n as f64 / d as f64) + } + + fn gain(&mut self, v: u32, len: Tick) -> Option { + match &self.class(v) { + b"CVAL" => self.c.get(v, "OMFI:CVAL:Value").and_then(|d| self.amp(&d)).map(Gain::Constant), + b"VVAL" => { + let linear = self.u16(v, "OMFI:VVAL:Interpolation") != Some(1); + let points: Vec<(Tick, f64)> = self + .refs(v, "OMFI:VVAL:PointList") + .into_iter() + .filter_map(|p| { + let (n, d) = self.rational(p, "OMFI:CTLP:Time").filter(|r| r.1 != 0)?; + let a = self.c.get(p, "OMFI:CTLP:Value").and_then(|d| self.amp(&d))?; + Some((Tick((len.0 as i128 * n as i128 / d as i128).clamp(-(1i128 << 56), 1i128 << 56) as i64), a)) + }) + .collect(); + (!points.is_empty()).then_some(Gain::Varying { linear, points }) + } + _ => None, + } + } + + fn clip(&mut self, c: u32, rate: (i64, i64)) -> CItem { + let len = units_to_ticks(self.len(c), rate.0, rate.1); + let start = units_to_ticks(self.i32(c, "OMFI:SCLP:StartTime").unwrap_or(0), rate.0, rate.1); + let name = self.string(c, "FilmCraft:SCLP:ClipName").unwrap_or_default(); + let (Some(id), Some(track)) = (self.uid(c, "OMFI:SCLP:SourceID"), self.u32(c, "OMFI:SCLP:SourceTrackID")) else { return CItem::Filler(len) }; + if id == [0; 12] { + return CItem::Filler(len); + } + match self.resolve(id, track, start, None, 0) { + Some((source, t)) => CItem::Clip(CClip { len, source, start: t, gain: None, name }), + None => CItem::Filler(len), + } + } + + fn slot_of(&self, mob: u32, track: u32) -> Option { + self.refs(mob, "OMFI:MOBJ:Slots") + .into_iter() + .find(|&s| self.r#ref(s, "OMFI:MSLT:TrackDesc").and_then(|t| self.u32(t, "OMFI:TRKD:TrackID")) == Some(track)) + } + + fn first_clip(&self, seg: u32) -> Option { + match &self.class(seg) { + b"SCLP" => Some(seg), + b"SEQU" => self.refs(seg, "OMFI:SEQU:Components").into_iter().find_map(|c| self.first_clip(c)), + _ => None, + } + } + + fn resolve(&mut self, id: Uid, track: u32, start: Tick, master: Option, depth: usize) -> Option<(usize, Tick)> { + if depth > 16 { + return None; + } + let Some(&mob) = self.mobs.get(&id) else { + self.report.warn("a clip references a mob that is not in the file (imported as a gap)"); + return None; + }; + let slot = self.slot_of(mob, track)?; + let rate = self.rational(slot, "OMFI:MSLT:EditRate").filter(|r| r.0 > 0 && r.1 > 0).unwrap_or((48_000, 1)); + let seg = self.r#ref(slot, "OMFI:MSLT:Segment")?; + match &self.class(mob) { + b"MMOB" => { + let key = master.unwrap_or_else(|| id.iter().map(|b| format!("{b:02x}")).collect()); + let clip = self.first_clip(seg)?; + let inner = units_to_ticks(self.i32(clip, "OMFI:SCLP:StartTime").unwrap_or(0), rate.0, rate.1); + let next = self.uid(clip, "OMFI:SCLP:SourceID")?; + let next_track = self.u32(clip, "OMFI:SCLP:SourceTrackID")?; + let name = self.string(mob, "OMFI:MOBJ:Name"); + let r = self.resolve(next, next_track, start + inner, Some(key), depth + 1)?; + if let Some(n) = name { + self.doc.sources[r.0].name = n; + } + Some(r) + } + b"SMOB" => { + let desc = self.r#ref(mob, "OMFI:SMOB:MediaDescription")?; + let sr = self.rational(desc, "OMFI:MDFL:SampleRate"); + if sr.is_none() && !self.media.contains_key(&id) { + return None; // a tape / physical source + } + let key = master.unwrap_or_else(|| id.iter().map(|b| format!("{b:02x}")).collect()); + let skey = (id, track, key.clone()); + if let Some(&i) = self.sources.get(&skey) { + return Some((i, start)); + } + let file_rate = sr.filter(|r| r.0 > 0 && r.1 > 0).unwrap_or(rate); + let length = units_to_ticks(self.i32(desc, "OMFI:MDFL:Length").unwrap_or(0), file_rate.0, file_rate.1); + let summary = self.c.get(desc, "OMFI:WAVD:Summary").or_else(|| self.c.get(desc, "OMFI:AIFD:Summary")).unwrap_or_default(); + let fmt = crate::pcm::parse_wav(&summary).or_else(|| crate::pcm::parse_aiff(&summary)).map(|(_, ch, sr, bits)| (ch as u32, sr, bits)); + let mut path = None; + for l in self.refs(desc, "OMFI:MDES:Locator") { + let p = match &self.class(l) { + b"UNXL" => self.string(l, "OMFI:UNXL:PathName"), + b"DOSL" => self.string(l, "OMFI:DOSL:PathName"), + b"MACL" => self.string(l, "OMFI:MACL:PathName"), + b"TXTL" => self.string(l, "OMFI:TXTL:Name"), + b"NETL" => self.string(l, "OMFI:NETL:URLString").map(|u| craft_timeline::path::file_url_to_path(&u)), + _ => None, + }; + if p.is_some() { + path = p; + break; + } + } + let sound_slots = self.refs(mob, "OMFI:MOBJ:Slots").len(); + let (file_channels, sample_rate, bits) = fmt.unwrap_or((1, file_rate.0 as u32, 16)); + let channel = (file_channels > 1 && sound_slots > 1).then(|| track.saturating_sub(1).min(file_channels - 1)); + // timecode of the physical source + let tc = self.first_clip(seg).and_then(|clip| { + let tid = self.uid(clip, "OMFI:SCLP:SourceID")?; + let tape = *self.mobs.get(&tid)?; + let (start_tc, fps, trate) = self.refs(tape, "OMFI:MOBJ:Slots").into_iter().find_map(|s| { + let g = self.r#ref(s, "OMFI:MSLT:Segment")?; + (self.class(g) == *b"TCCP").then(|| { + ( + self.i32(g, "OMFI:TCCP:Start").unwrap_or(0), + self.u16(g, "OMFI:TCCP:FPS").unwrap_or(25), + self.rational(s, "OMFI:MSLT:EditRate"), + ) + }) + })?; + let tcr = trate + .filter(|r| r.0 > 0 && r.1 > 0) + .map(|r| FrameRate::new(r.0, r.1)) + .unwrap_or_else(|| FrameRate::new(fps.max(1) as i64, 1)); + let off = units_to_ticks(self.i32(clip, "OMFI:SCLP:StartTime").unwrap_or(0), rate.0, rate.1); + Some((start_tc + tcr.frame_at(off), tcr)) + }); + let mut s = Source { + key, + name: self.string(mob, "OMFI:MOBJ:Name").unwrap_or_default(), + kind: CKind::Sound, + path, + channel, + channels: if channel.is_some() { 1 } else { file_channels }, + file_channels, + width: 0, + height: 0, + frame_rate: FrameRate::FPS_25, + sample_rate, + bits, + length, + offset: Tick::ZERO, + start_tc: tc.map(|t| t.0), + tc_rate: tc.map(|t| t.1).unwrap_or(FrameRate::FPS_25), + embedded: None, + markers: Vec::new(), + nested: None, + }; + if let Some(d) = self.media.get(&id) { + if let Some((pcm, ch, sr, b)) = crate::pcm::parse_wav(d).or_else(|| crate::pcm::parse_aiff(d)) { + s.embedded = Some(pcm); + s.file_channels = ch as u32; + s.channels = if s.channel.is_some() { 1 } else { ch as u32 }; + s.sample_rate = sr; + s.bits = b; + } else { + self.report.warn("embedded OMF audio in an unsupported format was skipped"); + } + } + let i = self.doc.sources.len(); + self.doc.sources.push(s); + self.sources.insert(skey, i); + Some((i, start)) + } + _ => { + self.report.warn("nested OMF compositions are not supported (imported as gaps)"); + None + } + } + } +} diff --git a/crates/aaf/src/omf/tests.rs b/crates/aaf/src/omf/tests.rs new file mode 100644 index 000000000..c6f4ef9f0 --- /dev/null +++ b/crates/aaf/src/omf/tests.rs @@ -0,0 +1,135 @@ +//! Structural checks of written OMF files: the Bento label and TOC, and the required properties of +//! the OMF Interchange 2.0 classes written. + +use std::collections::HashMap; + +use super::bento::{self, Container}; +use super::*; +use crate::testdoc::{IDENTITY, sound_only}; + +/// Every object of a class written has the properties the specification requires of it. +fn assert_required_properties(c: &Container<'_>, by_class: &HashMap>) { + let required: &[(&str, &[&str])] = &[ + ( + "HEAD", + &[ + "OMFI:HEAD:ByteOrder", + "OMFI:HEAD:LastModified", + "OMFI:HEAD:Version", + "OMFI:HEAD:Mobs", + "OMFI:HEAD:MediaData", + "OMFI:HEAD:DefinitionObjects", + ], + ), + ("CMOB", &["OMFI:MOBJ:MobID", "OMFI:MOBJ:Slots", "OMFI:MOBJ:LastModified", "OMFI:MOBJ:CreationTime"]), + ("MMOB", &["OMFI:MOBJ:MobID", "OMFI:MOBJ:Slots", "OMFI:MOBJ:LastModified", "OMFI:MOBJ:CreationTime"]), + ("SMOB", &["OMFI:MOBJ:MobID", "OMFI:MOBJ:Slots", "OMFI:SMOB:MediaDescription"]), + ("MSLT", &["OMFI:MSLT:Segment", "OMFI:MSLT:EditRate", "OMFI:MSLT:TrackDesc"]), + ("TRKD", &["OMFI:TRKD:Origin", "OMFI:TRKD:TrackID"]), + ("SEQU", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:SEQU:Components"]), + ("SCLP", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:SCLP:SourceID", "OMFI:SCLP:SourceTrackID", "OMFI:SCLP:StartTime"]), + ("FILL", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length"]), + ("TRAN", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:TRAN:CutPoint", "OMFI:TRAN:Effect"]), + ("EFFE", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:EFFE:EffectKind"]), + ("ESLT", &["OMFI:ESLT:ArgID", "OMFI:ESLT:ArgValue"]), + ("CVAL", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:CVAL:Value"]), + ("EDEF", &["OMFI:EDEF:EffectID"]), + ("DDEF", &["OMFI:DDEF:DataKindID"]), + ("TCCP", &["OMFI:CPNT:DataKind", "OMFI:CPNT:Length", "OMFI:TCCP:Start", "OMFI:TCCP:FPS", "OMFI:TCCP:Drop"]), + ("WAVD", &["OMFI:MDFL:IsOMFI", "OMFI:MDFL:SampleRate", "OMFI:MDFL:Length", "OMFI:WAVD:Summary"]), + ("WAVE", &["OMFI:MDAT:MobID", "OMFI:WAVE:Data"]), + ("IDNT", &["OMFI:IDNT:CompanyName", "OMFI:IDNT:ProductName"]), + ]; + for (k, props) in required { + let Some(objs) = by_class.get(*k) else { + assert_eq!(*k, "FILL", "no {k} object"); + continue; + }; + for &o in objs { + for prop in *props { + assert!(c.get(o, prop).is_some(), "{k} {o} lacks {prop}"); + } + } + } +} + +#[test] +fn written_files_have_the_required_structure() { + let mut report = Report::default(); + let bytes = write(&sound_only(Some(vec![7; 480 * 4])), &IDENTITY, &mut report).unwrap(); + assert!(!report.has_warnings(), "{report}"); + // label + let l = &bytes[bytes.len() - bento::LABEL_SIZE..]; + assert_eq!(&l[..8], &bento::MAGIC); + assert_eq!(u16::from_be_bytes([l[12], l[13]]), 1, "Bento major version"); + let c = Container::open(&bytes).unwrap(); + let class = |o: u32| c.get(o, "OMFI:OOBJ:ObjClass").map(|v| String::from_utf8_lossy(&v).to_string()); + let mut by_class: HashMap> = HashMap::new(); + for &o in c.objects.keys() { + if let Some(k) = class(o) { + by_class.entry(k).or_default().push(o); + } + } + assert_required_properties(&c, &by_class); + assert_eq!(by_class["HEAD"].len(), 1); + assert_eq!(by_class["CMOB"].len(), 1); + let head = by_class["HEAD"][0]; + assert_eq!(c.get(head, "OMFI:HEAD:Version"), Some(vec![2, 0])); + assert_eq!(c.get(head, "OMFI:HEAD:ByteOrder"), Some(b"MM".to_vec())); + // object references resolve to objects of the right class + let refs = |o: u32, p: &str| -> Vec { + let v = c.get(o, p).unwrap(); + let n = u16::from_be_bytes([v[0], v[1]]) as usize; + v[2..].as_chunks::<4>().0.iter().take(n).map(|k| c.resolve(o, u32::from_be_bytes([k[0], k[1], k[2], k[3]]))).collect() + }; + let one = |o: u32, p: &str| -> u32 { c.resolve(o, u32::from_be_bytes(c.get(o, p).unwrap()[..4].try_into().unwrap())) }; + for m in refs(head, "OMFI:HEAD:Mobs") { + assert!(matches!(class(m).as_deref(), Some("CMOB" | "MMOB" | "SMOB"))); + for s in refs(m, "OMFI:MOBJ:Slots") { + assert_eq!(class(s).as_deref(), Some("MSLT")); + assert_eq!(class(one(s, "OMFI:MSLT:TrackDesc")).as_deref(), Some("TRKD")); + } + } + // embedded media: WAVE data is a WAVE file of the file mob it names + for w in &by_class["WAVE"] { + let data = c.get(*w, "OMFI:WAVE:Data").unwrap(); + let (pcm, ch, sr, bits) = crate::pcm::parse_wav(&data).unwrap(); + assert_eq!((pcm.len(), ch, sr, bits), (480 * 4, 2, 48_000, 16)); + let id = c.get(*w, "OMFI:MDAT:MobID").unwrap(); + assert!(by_class["SMOB"].iter().any(|s| c.get(*s, "OMFI:MOBJ:MobID") == Some(id.clone()))); + } + // the composition's sound sequence: clip, transition, gain effect around a clip + let cm = by_class["CMOB"][0]; + let slots = refs(cm, "OMFI:MOBJ:Slots"); + assert_eq!(class(one(slots[0], "OMFI:MSLT:Segment")).as_deref(), Some("TCCP")); + let seq = one(slots[1], "OMFI:MSLT:Segment"); + let comps = refs(seq, "OMFI:SEQU:Components"); + let classes: Vec = comps.iter().map(|&o| class(o).unwrap()).collect(); + assert_eq!(classes, vec!["EFFE", "TRAN", "SCLP"]); + let len = |o: u32| i32::from_be_bytes(c.get(o, "OMFI:CPNT:Length").unwrap()[..4].try_into().unwrap()) as i64; + let samples = |f: i64| f * 48_000 / 25; + assert_eq!(len(comps[0]), samples(55)); + assert_eq!(len(comps[1]), samples(10)); + assert_eq!(len(comps[2]), samples(55)); + assert_eq!(len(seq), samples(100)); + assert_eq!(c.get(one(comps[0], "OMFI:EFFE:EffectKind"), "OMFI:EDEF:EffectID"), Some(b"omfi:effect:MonoAudioGain\0".to_vec())); +} + +#[test] +fn bento_values_round_trip() { + let mut w = bento::Writer::new(); + let a = w.new_object(); + let b = w.new_object(); + w.set(a, "Test:Small", "test:Bytes", &[1, 2]); + w.set(a, "Test:Empty", "test:Bytes", &[]); + w.set(b, "Test:Big", "test:Bytes", &vec![9; 100_000]); + w.set_references(a, &[b]); + let bytes = w.finish(); + let c = Container::open(&bytes).unwrap(); + assert_eq!(c.get(a, "Test:Small"), Some(vec![1, 2])); + assert_eq!(c.get(a, "Test:Empty"), Some(vec![])); + assert_eq!(c.get(b, "Test:Big").map(|v| v.len()), Some(100_000)); + assert_eq!(c.resolve(a, b), b); + assert_eq!(c.name_of(c.id_of("Test:Big").unwrap()), Some("Test:Big")); + assert!(Container::open(&bytes[..bytes.len() - 1]).is_err()); +} diff --git a/crates/aaf/src/omf/write.rs b/crates/aaf/src/omf/write.rs new file mode 100644 index 000000000..755994804 --- /dev/null +++ b/crates/aaf/src/omf/write.rs @@ -0,0 +1,419 @@ +//! Composition model → OMF 2.0 objects in a Bento container. + +use std::collections::HashMap; + +use craft_timeline::time::Tick; + +use super::bento; +use crate::model::{CItem, CKind, Document, Gain, Source, ticks_to_units}; +use crate::{Error, Identity, Report, Result}; + +/// An OMF mob id (`omfi:UID`): prefix, major, minor. +pub(crate) type Uid = [u8; 12]; + +pub(crate) fn uid(prefix: u32, major: u32, minor: u32) -> Uid { + let mut u = [0u8; 12]; + u[..4].copy_from_slice(&prefix.to_be_bytes()); + u[4..8].copy_from_slice(&major.to_be_bytes()); + u[8..].copy_from_slice(&minor.to_be_bytes()); + u +} + +struct W<'a> { + b: bento::Writer, + refs: HashMap>, + ddefs: HashMap<&'static str, u32>, + edefs: HashMap<&'static str, u32>, + defs: Vec, + report: &'a mut Report, + inexact: bool, +} + +fn rational(n: i64, d: i64) -> Vec { + let mut v = (n.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_be_bytes().to_vec(); + v.extend_from_slice(&(d.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_be_bytes()); + v +} + +fn cstr(s: &str) -> Vec { + let mut v = s.as_bytes().to_vec(); + v.push(0); + v +} + +impl W<'_> { + fn obj(&mut self, class: &[u8; 4]) -> u32 { + let id = self.b.new_object(); + self.b.set(id, "OMFI:OOBJ:ObjClass", "omfi:ClassID", class); + id + } + fn str(&mut self, o: u32, p: &str, v: &str) { + self.b.set(o, p, "omfi:String", &cstr(v)); + } + fn i32(&mut self, o: u32, p: &str, ty: &str, v: i64) { + if v > i32::MAX as i64 || v < i32::MIN as i64 { + self.report.warn("a time does not fit OMF's 32-bit positions and was clamped"); + } + self.b.set(o, p, ty, &(v.clamp(i32::MIN as i64, i32::MAX as i64) as i32).to_be_bytes()); + } + fn r#ref(&mut self, o: u32, p: &str, target: u32) { + self.b.set(o, p, "omfi:ObjRef", &target.to_be_bytes()); + self.refs.entry(o).or_default().push(target); + } + fn refs(&mut self, o: u32, p: &str, targets: &[u32]) { + let mut v = (targets.len() as u16).to_be_bytes().to_vec(); + for t in targets { + v.extend_from_slice(&t.to_be_bytes()); + } + self.b.set(o, p, "omfi:ObjRefArray", &v); + self.refs.entry(o).or_default().extend_from_slice(targets); + } + fn u(&mut self, t: Tick, rate: (i64, i64)) -> i64 { + let (n, exact) = ticks_to_units(t, rate.0, rate.1); + if !exact { + self.inexact = true; + } + n + } + fn ddef(&mut self, kind: &'static str) -> u32 { + if let Some(&d) = self.ddefs.get(kind) { + return d; + } + let d = self.obj(b"DDEF"); + self.b.set(d, "OMFI:DDEF:DataKindID", "omfi:UniqueName", &cstr(kind)); + self.ddefs.insert(kind, d); + self.defs.push(d); + d + } + fn edef(&mut self, id: &'static str, name: &str) -> u32 { + if let Some(&d) = self.edefs.get(id) { + return d; + } + let d = self.obj(b"EDEF"); + self.b.set(d, "OMFI:EDEF:EffectID", "omfi:UniqueName", &cstr(id)); + self.str(d, "OMFI:EDEF:EffectName", name); + self.b.set(d, "OMFI:EDEF:Bypass", "omfi:ArgIDType", &(-1i32).to_be_bytes()); + self.edefs.insert(id, d); + self.defs.push(d); + d + } + fn cpnt(&mut self, o: u32, kind: &'static str, len: i64) { + let d = self.ddef(kind); + self.r#ref(o, "OMFI:CPNT:DataKind", d); + self.i32(o, "OMFI:CPNT:Length", "omfi:Length32", len); + } + fn mob(&mut self, class: &[u8; 4], id: Uid, name: &str, slots: &[u32]) -> u32 { + let m = self.obj(class); + self.b.set(m, "OMFI:MOBJ:MobID", "omfi:UID", &id); + self.str(m, "OMFI:MOBJ:Name", name); + self.refs(m, "OMFI:MOBJ:Slots", slots); + self.b.set(m, "OMFI:MOBJ:LastModified", "omfi:TimeStamp", &[0, 0, 0, 0, 1]); + self.b.set(m, "OMFI:MOBJ:CreationTime", "omfi:TimeStamp", &[0, 0, 0, 0, 1]); + m + } + fn slot(&mut self, rate: (i64, i64), segment: u32, track_id: u32, name: &str, physical: u32) -> u32 { + let t = self.obj(b"TRKD"); + self.i32(t, "OMFI:TRKD:Origin", "omfi:Position32", 0); + self.b.set(t, "OMFI:TRKD:TrackID", "omfi:UInt32", &track_id.to_be_bytes()); + self.str(t, "OMFI:TRKD:TrackName", name); + if physical > 0 { + self.b.set(t, "OMFI:TRKD:PhysicalTrack", "omfi:UInt32", &physical.to_be_bytes()); + } + let s = self.obj(b"MSLT"); + self.b.set(s, "OMFI:MSLT:EditRate", "omfi:Rational", &rational(rate.0, rate.1)); + self.r#ref(s, "OMFI:MSLT:Segment", segment); + self.r#ref(s, "OMFI:MSLT:TrackDesc", t); + s + } + fn sclp(&mut self, kind: &'static str, len: i64, source: Uid, track: u32, start: i64) -> u32 { + let c = self.obj(b"SCLP"); + self.cpnt(c, kind, len); + self.b.set(c, "OMFI:SCLP:SourceID", "omfi:UID", &source); + self.b.set(c, "OMFI:SCLP:SourceTrackID", "omfi:UInt32", &track.to_be_bytes()); + self.i32(c, "OMFI:SCLP:StartTime", "omfi:Position32", start); + c + } + fn tccp(&mut self, len: i64, start: i64, fps: i64, drop: bool) -> u32 { + let t = self.obj(b"TCCP"); + self.cpnt(t, "omfi:data:Timecode", len); + self.i32(t, "OMFI:TCCP:Start", "omfi:Position32", start); + self.b.set(t, "OMFI:TCCP:FPS", "omfi:UInt16", &(fps.clamp(1, u16::MAX as i64) as u16).to_be_bytes()); + self.b.set(t, "OMFI:TCCP:Drop", "omfi:Boolean", &[drop as u8]); + t + } + fn value(&mut self, len: i64, g: &Gain, seg_len: i64, rate: (i64, i64), base: Tick) -> u32 { + match g { + Gain::Constant(a) => { + let v = self.obj(b"CVAL"); + self.cpnt(v, "omfi:data:Rational", len); + self.b.set(v, "OMFI:CVAL:Value", "omfi:DataValue", &(*a)); + v + } + Gain::Varying { linear, points } => { + let mut pts = Vec::new(); + for (off, a) in points { + let o = self.u(base + *off, rate) - self.u(base, rate); + let p = self.obj(b"CTLP"); + self.b.set(p, "OMFI:CTLP:Time", "omfi:Rational", &rational(o, seg_len.max(1))); + self.b.set(p, "OMFI:CTLP:Value", "omfi:DataValue", &(*a)); + self.b.set(p, "OMFI:CTLP:EditHint", "omfi:EditHintType", &[0]); + pts.push(p); + } + let v = self.obj(b"VVAL"); + self.cpnt(v, "omfi:data:Rational", len); + self.b.set(v, "OMFI:VVAL:Interpolation", "omfi:InterpKind", &(if *linear { 2u16 } else { 1u16 }).to_be_bytes()); + self.refs(v, "OMFI:VVAL:PointList", &pts); + v + } + } + } +} + +fn fnv(s: &[u8], h: u64) -> u64 { + s.iter().fold(h, |h, &b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01B3)) +} + +fn amp(a: f64) -> Vec { + rational((a.max(0.0) * 65536.0).round().min(i32::MAX as f64) as i64, 65536) +} + +fn rate_of(s: &Source) -> (i64, i64) { + match s.kind { + CKind::Picture => (s.frame_rate.num, s.frame_rate.den), + CKind::Sound => (s.sample_rate.max(1) as i64, 1), + } +} + +pub(crate) fn write(doc: &Document, identity: &Identity<'_>, report: &mut Report) -> Result> { + let comp = doc.compositions.first().ok_or(Error::Empty)?; + let mut w = + W { b: bento::Writer::new(), refs: HashMap::new(), ddefs: HashMap::new(), edefs: HashMap::new(), defs: Vec::new(), report, inexact: false }; + let mut seed = fnv(comp.name.as_bytes(), 0xCBF2_9CE4_8422_2325); + for s in &doc.sources { + seed = fnv(s.path.as_deref().unwrap_or("").as_bytes(), fnv(s.key.as_bytes(), seed)); + } + let major = (seed >> 32) as u32 ^ seed as u32; + let mut minor = 0u32; + let mut new_uid = || { + minor += 1; + uid(0x464C_4D43, major, minor) + }; + let mut mobs = Vec::new(); + let mut media_data = Vec::new(); + let mut master_ref: HashMap = HashMap::new(); + // media + let mut groups: Vec<(String, Vec)> = Vec::new(); + for (i, s) in doc.sources.iter().enumerate() { + if s.kind != CKind::Sound { + continue; + } + match groups.iter_mut().find(|(k, _)| *k == s.key) { + Some((_, v)) => v.push(i), + None => groups.push((s.key.clone(), vec![i])), + } + } + for (_, members) in &groups { + let first = &doc.sources[members[0]]; + let master = new_uid(); + let tc = members.iter().find_map(|&i| doc.sources[i].start_tc.map(|t| (t, doc.sources[i].tc_rate))); + let tape = new_uid(); + let mut tape_slots = Vec::new(); + if let Some((start, r)) = tc { + let len = members.iter().map(|&i| doc.sources[i].length).max().unwrap_or(Tick::ZERO); + let l = w.u(len, (r.num, r.den)); + let t = w.tccp(l, start, r.timecode_base(), false); + tape_slots.push(w.slot((r.num, r.den), t, 1, "TC1", 0)); + } + let mut master_slots = Vec::new(); + for (k, &si) in members.iter().enumerate() { + let s = &doc.sources[si]; + let rate = rate_of(s); + let len = w.u(s.length, rate); + // file mob + let file = new_uid(); + let file_track = s.channel.map_or(1, |c| c + 1); + let tape_track = 2 + k as u32; + let to_tape = + if tc.is_some() { w.sclp("omfi:data:Sound", len, tape, tape_track, 0) } else { w.sclp("omfi:data:Sound", len, uid(0, 0, 0), 0, 0) }; + let fslot = w.slot(rate, to_tape, file_track, &format!("A{file_track}"), file_track); + let desc = descriptor(&mut w, s, len); + let fm = w.mob(b"SMOB", file, &s.name, &[fslot]); + w.r#ref(fm, "OMFI:SMOB:MediaDescription", desc); + mobs.push(fm); + if let Some(pcm) = &s.embedded { + let md = w.obj(b"WAVE"); + w.b.set(md, "OMFI:MDAT:MobID", "omfi:UID", &file); + w.b.set( + md, + "OMFI:WAVE:Data", + "omfi:DataValue", + &craft_audio::pcm_wav_file(pcm, u16::try_from(s.file_channels.max(1)).unwrap_or(u16::MAX), s.sample_rate, s.bits), + ); + media_data.push(md); + } + if tc.is_some() { + let c = w.sclp("omfi:data:Sound", len, uid(0, 0, 0), 0, 0); + tape_slots.push(w.slot(rate, c, tape_track, &format!("A{}", k + 1), k as u32 + 1)); + } + let mclip = w.sclp("omfi:data:Sound", len, file, file_track, 0); + master_slots.push(w.slot(rate, mclip, k as u32 + 1, &format!("A{}", k + 1), k as u32 + 1)); + master_ref.insert(si, (master, k as u32 + 1)); + } + mobs.push(w.mob(b"MMOB", master, &first.name, &master_slots)); + if tc.is_some() { + let d = w.obj(b"MDTP"); + let reel = first.path.as_deref().map(craft_timeline::path::file_stem).unwrap_or(&first.name).to_string(); + let tm = w.mob(b"SMOB", tape, &reel, &tape_slots); + w.r#ref(tm, "OMFI:SMOB:MediaDescription", d); + mobs.push(tm); + } + } + // composition + let crate_rate = (comp.rate.num, comp.rate.den); + let mut slots = Vec::new(); + let total = comp + .tracks + .iter() + .map(|t| t.items.iter().fold(Tick::ZERO, |a, i| if matches!(i, CItem::Transition(_)) { a - i.len() } else { a + i.len() })) + .max() + .unwrap_or(Tick::ZERO); + let tl = w.u(total, crate_rate); + let tcc = w.tccp(tl, comp.start_tc, comp.rate.timecode_base(), comp.drop); + slots.push(w.slot(crate_rate, tcc, 1, "TC1", 0)); + for (track_id, t) in (2..).zip(comp.tracks.iter().filter(|t| t.kind == CKind::Sound)) { + let rate = (comp.sample_rate.max(1) as i64, 1); + let mut comps = Vec::new(); + let mut cursor = Tick::ZERO; + for it in &t.items { + match it { + CItem::Filler(l) => { + let n = w.u(cursor + *l, rate) - w.u(cursor, rate); + cursor += *l; + let f = w.obj(b"FILL"); + w.cpnt(f, "omfi:data:Sound", n); + comps.push(f); + } + CItem::Clip(c) => { + let n = w.u(cursor + c.len, rate) - w.u(cursor, rate); + let (mid, mtrack) = master_ref.get(&c.source).copied().unwrap_or((uid(0, 0, 0), 0)); + let start = w.u(c.start, rate); + let sc = w.sclp("omfi:data:Sound", n, mid, mtrack, start); + if !c.name.is_empty() { + w.str(sc, "FilmCraft:SCLP:ClipName", &c.name); + } + let seg = match &c.gain { + Some(g) => { + let v = w.value(n, g, n, rate, cursor); + let input = w.obj(b"ESLT"); + w.b.set(input, "OMFI:ESLT:ArgID", "omfi:ArgIDType", &(-1i32).to_be_bytes()); + w.r#ref(input, "OMFI:ESLT:ArgValue", sc); + let level = w.obj(b"ESLT"); + w.b.set(level, "OMFI:ESLT:ArgID", "omfi:ArgIDType", &1i32.to_be_bytes()); + w.r#ref(level, "OMFI:ESLT:ArgValue", v); + let kind = w.edef("omfi:effect:MonoAudioGain", "Mono Audio Gain"); + let e = w.obj(b"EFFE"); + w.cpnt(e, "omfi:data:Sound", n); + w.r#ref(e, "OMFI:EFFE:EffectKind", kind); + w.refs(e, "OMFI:EFFE:EffectSlots", &[input, level]); + e + } + None => sc, + }; + comps.push(seg); + cursor += c.len; + } + CItem::Transition(x) => { + let ts = cursor - x.len; + let n = w.u(cursor, rate) - w.u(ts, rate); + let cut = w.u(ts + x.cut, rate) - w.u(ts, rate); + cursor = ts; + let kind = w.edef("omfi:effect:SimpleMonoAudioDissolve", "Simple Mono Audio Dissolve"); + let e = w.obj(b"EFFE"); + w.cpnt(e, "omfi:data:Sound", n); + w.r#ref(e, "OMFI:EFFE:EffectKind", kind); + w.refs(e, "OMFI:EFFE:EffectSlots", &[]); + w.str(e, "FilmCraft:EFFE:EffectID", &x.effect); + let tr = w.obj(b"TRAN"); + w.cpnt(tr, "omfi:data:Sound", n); + w.i32(tr, "OMFI:TRAN:CutPoint", "omfi:Position32", cut); + w.r#ref(tr, "OMFI:TRAN:Effect", e); + comps.push(tr); + } + } + } + let len = w.u(cursor.max(Tick::ZERO), rate); + let seq = w.obj(b"SEQU"); + w.cpnt(seq, "omfi:data:Sound", len); + w.refs(seq, "OMFI:SEQU:Components", &comps); + slots.push(w.slot(rate, seq, track_id, &t.name, t.number)); + } + let cmob = w.mob(b"CMOB", new_uid(), &comp.name, &slots); + mobs.insert(0, cmob); + if w.inexact { + w.report.info("some times are not on whole samples / frames and were rounded"); + } + let ident = w.obj(b"IDNT"); + w.str(ident, "OMFI:IDNT:CompanyName", identity.company); + w.str(ident, "OMFI:IDNT:ProductName", identity.product); + w.str(ident, "OMFI:IDNT:ProductVersionString", identity.version); + w.str(ident, "OMFI:IDNT:Platform", identity.platform); + w.b.set(ident, "OMFI:IDNT:Date", "omfi:TimeStamp", &[0, 0, 0, 0, 1]); + let head = w.obj(b"HEAD"); + w.b.set(head, "OMFI:HEAD:ByteOrder", "omfi:Int16", &0x4D4Di16.to_be_bytes()); + w.b.set(head, "OMFI:HEAD:LastModified", "omfi:TimeStamp", &[0, 0, 0, 0, 1]); + w.b.set(head, "OMFI:HEAD:Version", "omfi:VersionType", &[2, 0]); + w.refs(head, "OMFI:HEAD:Mobs", &mobs); + w.refs(head, "OMFI:HEAD:MediaData", &media_data); + w.refs(head, "OMFI:HEAD:PrimaryMobs", &[cmob]); + let defs = w.defs.clone(); + w.refs(head, "OMFI:HEAD:DefinitionObjects", &defs); + w.refs(head, "OMFI:HEAD:IdentificationList", &[ident]); + let refs = std::mem::take(&mut w.refs); + let mut keys: Vec<_> = refs.keys().copied().collect(); + keys.sort_unstable(); + for k in keys { + let mut t = refs[&k].clone(); + t.sort_unstable(); + t.dedup(); + w.b.set_references(k, &t); + } + Ok(w.b.finish()) +} + +fn descriptor(w: &mut W, s: &Source, len: i64) -> u32 { + let aiff = + s.embedded.is_none() && s.path.as_deref().is_some_and(|p| matches!(craft_timeline::path::extension(p).as_str(), "aif" | "aiff" | "aifc")); + let d = w.obj(if aiff { b"AIFD" } else { b"WAVD" }); + w.b.set(d, "OMFI:MDFL:IsOMFI", "omfi:Boolean", &[s.embedded.is_some() as u8]); + let r = rate_of(s); + w.b.set(d, "OMFI:MDFL:SampleRate", "omfi:Rational", &rational(r.0, r.1)); + w.i32(d, "OMFI:MDFL:Length", "omfi:Length32", len); + let frames = u32::try_from(len.max(0)).unwrap_or(u32::MAX); + // Channel counts come from the project: saturate, as the headers can't hold more anyway. + let bytes_per_frame = s.file_channels.max(1).saturating_mul((s.bits as u32).div_ceil(8)); + let channels = u16::try_from(s.file_channels.max(1)).unwrap_or(u16::MAX); + if aiff { + w.b.set(d, "OMFI:AIFD:Summary", "omfi:DataValue", &craft_audio::pcm_aiff_header(frames, channels, s.sample_rate, s.bits)); + } else { + w.b.set( + d, + "OMFI:WAVD:Summary", + "omfi:DataValue", + &craft_audio::pcm_wav_header(frames.saturating_mul(bytes_per_frame), channels, s.sample_rate, s.bits), + ); + } + if let Some(p) = &s.path { + let mut locs = Vec::new(); + let dos = p.len() > 2 && p.as_bytes()[1] == b':'; + let l = w.obj(if dos { b"DOSL" } else { b"UNXL" }); + w.str(l, if dos { "OMFI:DOSL:PathName" } else { "OMFI:UNXL:PathName" }, p); + locs.push(l); + if craft_timeline::path::is_absolute(p) { + let n = w.obj(b"NETL"); + w.str(n, "OMFI:NETL:URLString", &craft_timeline::path::path_to_file_url(p, false)); + locs.push(n); + } + w.refs(d, "OMFI:MDES:Locator", &locs); + } + d +} diff --git a/crates/aaf/src/pcm.rs b/crates/aaf/src/pcm.rs new file mode 100644 index 000000000..789c976a8 --- /dev/null +++ b/crates/aaf/src/pcm.rs @@ -0,0 +1,11 @@ +//! Embedded PCM essence in and out of WAVE and AIFF wrappers (craft-audio does the containers). + +/// PCM (little-endian, 8-bit unsigned), channels, sample rate and bits of a WAVE file. +pub(crate) fn parse_wav(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { + craft_audio::wav_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits)) +} + +/// The same for an AIFF / AIFF-C (`NONE`, `twos`, `sowt`) file. +pub(crate) fn parse_aiff(b: &[u8]) -> Option<(Vec, u16, u32, u16)> { + craft_audio::aiff_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits)) +} diff --git a/crates/aaf/src/roundtrip_tests.rs b/crates/aaf/src/roundtrip_tests.rs new file mode 100644 index 000000000..5ae2a6d8f --- /dev/null +++ b/crates/aaf/src/roundtrip_tests.rs @@ -0,0 +1,217 @@ +//! Documents written and read back, in both formats; damaged files. + +use craft_timeline::time::{FrameRate, Tick}; + +use crate::model::{CItem, CKind, CMarker, Document, Gain}; +use crate::testdoc::{IDENTITY, pcm_ramp, picture_and_sound, sound_only}; +use crate::{Error, Report, aaf, omf}; + +fn aaf_bytes(doc: &Document, small_sectors: bool) -> Vec { + let mut report = Report::default(); + let bytes = aaf::write(doc, &aaf::WriteOptions { identity: IDENTITY, small_sectors }, &mut report).unwrap(); + assert!(report.is_empty(), "{report}"); + bytes +} + +fn omf_bytes(doc: &Document) -> Vec { + let mut report = Report::default(); + let bytes = omf::write(doc, &IDENTITY, &mut report).unwrap(); + assert!(!report.has_warnings(), "{report}"); + bytes +} + +fn read_clean(bytes: &[u8], is_aaf: bool) -> Document { + let mut report = Report::default(); + let doc = if is_aaf { aaf::read(bytes, &mut report) } else { omf::read(bytes, &mut report) }.unwrap(); + assert!(!report.has_warnings(), "{report}"); + doc +} + +/// What a track holds, with each clip's source by what it is rather than by index. Gain is stored +/// as a rational: four decimals survive. +fn shape(doc: &Document) -> Vec<(CKind, String, u32, Vec)> { + let comp = &doc.compositions[0]; + comp.tracks + .iter() + .map(|t| { + let items = t + .items + .iter() + .map(|i| match i { + CItem::Filler(l) => format!("gap {}", l.0), + CItem::Transition(x) => format!("{} {} cut {}", x.effect, x.len.0, x.cut.0), + CItem::Clip(c) => { + let s = &doc.sources[c.source]; + let gain = match &c.gain { + None => "unity".to_string(), + Some(Gain::Constant(g)) => format!("{g:.4}"), + Some(Gain::Varying { linear, points }) => { + format!("{linear} {:?}", points.iter().map(|(t, g)| (t.0, format!("{g:.4}"))).collect::>()) + } + }; + format!("clip {} from {} of {:?} {:?} gain {gain}", c.len.0, c.start.0, s.path, s.kind) + } + }) + .collect(); + (t.kind, t.name.clone(), t.number, items) + }) + .collect() +} + +#[test] +fn aaf_round_trips_the_edit_at_every_rate() { + for (rate, drop) in [(FrameRate::FPS_25, false), (FrameRate::FPS_29_97, true), (FrameRate::FPS_23_976, false), (FrameRate::FPS_59_94, true)] { + let mut doc = picture_and_sound(rate); + let comp = &mut doc.compositions[0]; + (comp.start_tc, comp.drop) = (rate.timecode_base() * 3600, drop); + comp.markers = vec![ + CMarker { start: rate.tick_of(10), duration: Tick::ZERO, name: "Slate".into(), comment: "take 2".into(), color: Some("Green".into()) }, + CMarker { start: rate.tick_of(40), duration: rate.tick_of(5), name: "Range".into(), comment: String::new(), color: None }, + ]; + // keyframed gain on the first sound clip, held gain steps on nothing else + if let Some(CItem::Clip(c)) = comp.tracks[1].items.first_mut() { + c.gain = Some(Gain::Varying { linear: true, points: vec![(Tick::ZERO, 1.0), (rate.tick_of(25), 0.5)] }); + } + doc.sources[0].markers = + vec![CMarker { start: rate.tick_of(30), duration: Tick::ZERO, name: "In media".into(), comment: String::new(), color: None }]; + for small in [false, true] { + let back = read_clean(&aaf_bytes(&doc, small), true); + let (want, got) = (&doc.compositions[0], &back.compositions[0]); + assert_eq!(shape(&back), shape(&doc), "{rate} small {small}"); + assert_eq!((&got.name, got.rate, got.start_tc, got.drop), (&want.name, want.rate, want.start_tc, want.drop), "{rate}"); + assert_eq!((got.width, got.height, got.sample_rate), (1920, 1080, 48_000), "{rate}"); + let markers = |m: &[CMarker]| m.iter().map(|m| (m.start, m.duration, m.name.clone(), m.comment.clone())).collect::>(); + assert_eq!(markers(&got.markers), markers(&want.markers), "{rate}"); + assert_eq!(back.nested, []); + let picture = back.sources.iter().find(|s| s.kind == CKind::Picture).unwrap(); + assert_eq!((picture.width, picture.height, picture.frame_rate, picture.length), (1280, 720, rate, doc.sources[0].length), "{rate}"); + assert_eq!((picture.start_tc, picture.tc_rate), (Some(86_400), rate), "{rate}"); + assert_eq!(markers(&picture.markers), markers(&doc.sources[0].markers), "{rate}"); + let sound = back.sources.iter().find(|s| s.kind == CKind::Sound).unwrap(); + assert_eq!((sound.channels, sound.file_channels, sound.sample_rate, sound.bits), (2, 2, 48_000, 24), "{rate}"); + assert_eq!(sound.key, picture.key, "one media item"); + // what was read, written again, reads as the same edit (mob ids, and so source keys, are new) + let again = read_clean(&aaf_bytes(&back, small), true); + assert_eq!((shape(&again), &again.compositions), (shape(&back), &back.compositions), "{rate}"); + } + } +} + +#[test] +fn embedded_audio_comes_back_bit_for_bit() { + let pcm = pcm_ramp(480, 2, 3); + let mut doc = sound_only(Some(pcm.clone())); + // trimmed essence: its first sample is media time 0.2 s + doc.sources[0].offset = Tick::from_units(9_600, 48_000); + for is_aaf in [true, false] { + let bytes = if is_aaf { aaf_bytes(&doc, false) } else { omf_bytes(&doc) }; + assert_eq!((aaf::sniff(&bytes), omf::sniff(&bytes)), (is_aaf, !is_aaf)); + let back = read_clean(&bytes, is_aaf); + let s = &back.sources[0]; + assert_eq!(s.embedded.as_deref(), Some(&pcm[..]), "aaf {is_aaf}"); + assert_eq!((s.path.as_deref(), s.file_channels, s.sample_rate, s.bits), (None, 2, 48_000, 16), "aaf {is_aaf}"); + assert_eq!(s.length, Tick::from_units(480, 48_000), "aaf {is_aaf}"); + assert_eq!(shape(&back), shape(&doc), "aaf {is_aaf}"); + } +} + +#[test] +fn omf_round_trips_sound_linked_to_wave_and_aiff_files() { + for path in ["/m/a.wav", "/m/a.aif"] { + let mut doc = sound_only(None); + doc.sources[0].path = Some(path.into()); + let back = read_clean(&omf_bytes(&doc), false); + assert_eq!(shape(&back), shape(&doc), "{path}"); + let s = &back.sources[0]; + assert_eq!((s.file_channels, s.sample_rate, s.bits, s.embedded.as_ref()), (2, 48_000, 16, None), "{path}"); + assert_eq!(back.compositions[0].rate, FrameRate::FPS_25); + } +} + +#[test] +fn omf_leaves_picture_out() { + let doc = picture_and_sound(FrameRate::FPS_25); + let back = read_clean(&omf_bytes(&doc), false); + assert!(back.compositions[0].tracks.iter().all(|t| t.kind == CKind::Sound)); + assert_eq!(shape(&back).len(), 1); +} + +#[test] +fn empty_and_foreign_documents() { + let none = Document::default(); + assert_eq!(aaf::write(&none, &aaf::WriteOptions { identity: IDENTITY, small_sectors: false }, &mut Report::default()), Err(Error::Empty)); + assert_eq!(omf::write(&none, &IDENTITY, &mut Report::default()), Err(Error::Empty)); + let mut empty = sound_only(None); + empty.compositions[0].tracks.clear(); + empty.sources.clear(); + for small in [false, true] { + assert_eq!(read_clean(&aaf_bytes(&empty, small), true).compositions.len(), 1); + } + assert_eq!(read_clean(&omf_bytes(&empty), false).compositions.len(), 1); + assert!(matches!(aaf::read(b"not an aaf", &mut Report::default()), Err(Error::Parse { format: "AAF", .. }))); + assert!(matches!(omf::read(b"not an omf", &mut Report::default()), Err(Error::Parse { format: "OMF", .. }))); + assert!(!aaf::sniff(b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1 but short")); + assert!(!omf::sniff(b"")); +} + +/// Truncation and random corruption: an error or a document, never a panic. +#[test] +fn damaged_documents_never_panic() { + let aaf_file = aaf_bytes(&picture_and_sound(FrameRate::FPS_25), true); + let omf_file = omf_bytes(&sound_only(Some(pcm_ramp(100, 2, 1)))); + for (bytes, is_aaf) in [(&aaf_file, true), (&omf_file, false)] { + let read = |b: &[u8]| { + let mut report = Report::default(); + let _ = if is_aaf { aaf::read(b, &mut report) } else { omf::read(b, &mut report) }; + }; + for cut in (0..bytes.len()).step_by(97) { + read(&bytes[..cut]); + } + let mut seed = 0xA5A5_1234_5678_9ABCu64; + for _ in 0..400 { + let mut g = bytes.clone(); + for _ in 0..8 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let at = (seed as usize) % g.len(); + g[at] = (seed >> 40) as u8; + } + read(&g); + } + } +} + +/// A time that is not on a whole edit unit is rounded, and the report says so. +#[test] +fn off_grid_times_are_rounded_and_reported() { + let mut doc = picture_and_sound(FrameRate::FPS_25); + if let Some(CItem::Clip(c)) = doc.compositions[0].tracks[0].items.first_mut() { + c.start += Tick(7); + } + let mut report = Report::default(); + aaf::write(&doc, &aaf::WriteOptions { identity: IDENTITY, small_sectors: false }, &mut report).unwrap(); + assert!(report.mentions("rounded"), "{report}"); +} + +/// A composition that uses itself (a damaged file) is a gap with a warning, not a recursion. +#[test] +fn a_composition_nested_in_itself_is_a_gap() { + let rate = FrameRate::FPS_25; + let mut doc = picture_and_sound(rate); + let mut inner = doc.compositions[0].clone(); + inner.name = "Inner".into(); + let mut nest = doc.sources[0].clone(); + (nest.key, nest.path, nest.nested, nest.start_tc) = ("seq:9".into(), None, Some(0), None); + doc.sources.push(nest); + let uses_inner = CItem::Clip(crate::model::CClip { len: rate.tick_of(20), source: 2, start: Tick::ZERO, gain: None, name: "Inner".into() }); + inner.tracks[0].items = vec![uses_inner.clone()]; + doc.nested.push(inner); + doc.compositions[0].tracks[0].items = vec![uses_inner]; + let bytes = aaf::write(&doc, &aaf::WriteOptions { identity: IDENTITY, small_sectors: false }, &mut Report::default()).unwrap(); + let mut report = Report::default(); + let back = aaf::read(&bytes, &mut report).unwrap(); + assert!(report.mentions("nested in itself"), "{report}"); + assert_eq!(back.nested.len(), 1); + assert!(matches!(back.nested[0].tracks[0].items[..], [CItem::Filler(_)]), "{:?}", back.nested[0].tracks[0].items); +} diff --git a/crates/aaf/src/testdoc.rs b/crates/aaf/src/testdoc.rs new file mode 100644 index 000000000..81db0a158 --- /dev/null +++ b/crates/aaf/src/testdoc.rs @@ -0,0 +1,106 @@ +//! Documents the tests write: what an editor's two-clip sequence with a dissolve looks like in +//! the model. + +use craft_timeline::time::{FrameRate, Tick}; + +use crate::Identity; +use crate::model::{CClip, CItem, CKind, CTrack, CTransition, Composition, Document, Gain, Source}; + +pub(crate) const IDENTITY: Identity<'static> = + Identity { company: "Craft", product: "craft-aaf tests", version: "1.2.3", platform: "test", product_id: *b"craft-aaf-tests." }; + +/// A source of `kind` for the media item `key` at `path`: 1280×720 picture at `rate`, or stereo +/// 48 kHz sound of `bits` bits; 100 seconds long. +pub(crate) fn source(key: &str, path: &str, kind: CKind, rate: FrameRate, bits: u16, start_tc: Option) -> Source { + let sound = kind == CKind::Sound; + Source { + key: key.into(), + name: path.rsplit('/').next().unwrap_or(path).into(), + kind, + path: Some(path.into()), + channel: None, + channels: if sound { 2 } else { 0 }, + file_channels: if sound { 2 } else { 0 }, + width: if sound { 0 } else { 1280 }, + height: if sound { 0 } else { 720 }, + frame_rate: rate, + sample_rate: 48_000, + bits, + length: rate.tick_of(100 * rate.timecode_base()), + offset: Tick::ZERO, + start_tc, + tc_rate: rate, + embedded: None, + markers: Vec::new(), + nested: None, + } +} + +pub(crate) fn clip(rate: FrameRate, source: usize, start: i64, len: i64, name: &str) -> CItem { + CItem::Clip(CClip { len: rate.tick_of(len), source, start: rate.tick_of(start), gain: None, name: name.into() }) +} + +/// Two clips of `source` cut at frame `cut`, each `cut` frames long on the timeline, joined by a +/// transition of `dur` frames centred on the cut: each clip runs half the transition past the cut. +pub(crate) fn two_clips(rate: FrameRate, source: usize, cut: i64, dur: i64, (in_a, in_b): (i64, i64), effect: &str) -> Vec { + let half = dur / 2; + vec![ + clip(rate, source, in_a, cut + half, "a"), + CItem::Transition(CTransition { len: rate.tick_of(dur), cut: rate.tick_of(half), effect: effect.into() }), + clip(rate, source, in_b - half, cut + half, "a"), + ] +} + +pub(crate) fn composition(name: &str, rate: FrameRate, tracks: Vec) -> Composition { + Composition { name: name.into(), rate, sample_rate: 48_000, width: 1920, height: 1080, start_tc: 0, drop: false, tracks, markers: Vec::new() } +} + +pub(crate) fn track(kind: CKind, name: &str, number: u32, items: Vec) -> CTrack { + CTrack { kind, name: name.into(), number, channels: if kind == CKind::Sound { 2 } else { 0 }, items } +} + +/// "S" at `rate`: V1 and A1 each hold two clips of `a.mov`, `cut` frames each on the timeline (from +/// source frames `ins`), with a transition of `dur` frames centred on the cut; the second sound +/// clip is 3 dB down. +pub(crate) fn picture_and_sound_cut(rate: FrameRate, cut: i64, dur: i64, ins: (i64, i64)) -> Document { + let sources = vec![ + source("item:1", "/m/a.mov", CKind::Picture, rate, 24, Some(86_400)), + source("item:1", "/m/a.mov", CKind::Sound, rate, 24, Some(86_400)), + ]; + let mut sound = two_clips(rate, 1, cut, dur, ins, "constant_power"); + if let Some(CItem::Clip(c)) = sound.last_mut() { + c.gain = Some(Gain::Constant(10f64.powf(-3.0 / 20.0))); + } + let tracks = vec![track(CKind::Picture, "V1", 1, two_clips(rate, 0, cut, dur, ins, "cross_dissolve")), track(CKind::Sound, "A1", 1, sound)]; + Document { compositions: vec![composition("S", rate, tracks)], sources, nested: Vec::new() } +} + +/// [`picture_and_sound_cut`] with 50-frame clips from source frames 10 and 205 and a 10-frame +/// transition: every time is a multiple of five frames, which is a whole number of 48 kHz samples +/// at the NTSC rates too. +pub(crate) fn picture_and_sound(rate: FrameRate) -> Document { + picture_and_sound_cut(rate, 50, 10, (10, 205)) +} + +/// 16-bit PCM: `frames` frames of `channels` channels, every sample different from its neighbours. +pub(crate) fn pcm_ramp(frames: usize, channels: usize, seed: i32) -> Vec { + (0..frames * channels).flat_map(|i| ((i as i32 * 37 + seed * 1000) as i16).to_le_bytes()).collect() +} + +/// "S" at 25 fps, sound only: A1 holds two 50-frame clips of `a.wav` (from source frames 10 and +/// 300) with a 10-frame crossfade centred on the cut; the first clip is 6 dB up. The sound is +/// embedded when `embedded` is given (480 frames of 16-bit stereo). +pub(crate) fn sound_only(embedded: Option>) -> Document { + let rate = FrameRate::FPS_25; + let mut s = source("item:1", "/m/a.wav", CKind::Sound, rate, 16, None); + if let Some(pcm) = embedded { + s.path = None; + s.length = Tick::from_units((pcm.len() / 4) as i64, 48_000); + s.embedded = Some(pcm); + } + let mut items = two_clips(rate, 0, 50, 10, (10, 300), "constant_power"); + if let Some(CItem::Clip(c)) = items.first_mut() { + c.gain = Some(Gain::Constant(10f64.powf(6.0 / 20.0))); + } + Document { compositions: vec![composition("S", rate, vec![track(CKind::Sound, "A1", 1, items)])], sources: vec![s], nested: Vec::new() } +} diff --git a/crates/aep/README.md b/crates/aep/README.md index 12ce8f9d6..95fcdd1a6 100644 --- a/crates/aep/README.md +++ b/crates/aep/README.md @@ -24,6 +24,13 @@ The XML form of a project (`.aepx`) is read into the same tree by `read_aepx` (a XML tokenizer of its own); `parse_any` picks the reader by content, so the typed view takes either form. The mapping is in [`docs/aep-format.md`](docs/aep-format.md), section 1. +A reader that only looks does not need the owned tree. `TreeIndex` is the same tree as one flat, +read-only array in depth-first order, borrowed from the input: `TreeIndex::parse` for an `.aep`, +`index_aepx` and `TreeIndex::from_drafts` for an `.aepx` (decoded into one buffer first). It +counts the same chunks against the same `Limits` and returns the same errors as `parse`, and the +typed view reads through either (`Project::new` for the owned tree, `Project::from_index` for the +index). An importer should use the index; it is about twice as fast and allocates far less. + Bodies that look like lists but are not chunk sequences (for example `LIST btdk`, raw text) stay opaque rather than failing the parse. Input is untrusted: sizes are checked against the remaining input, nesting and chunk count are bounded (`Limits`), nothing is allocated from a declared size, diff --git a/crates/aep/docs/aep-format.md b/crates/aep/docs/aep-format.md index a9269bc10..3582276d7 100644 --- a/crates/aep/docs/aep-format.md +++ b/crates/aep/docs/aep-format.md @@ -121,6 +121,11 @@ counterpart (a name that is not 1 to 4 characters) are skipped with their conten with the byte offset. It runs without recursion; the nesting depth (`Limits::max_depth`) and the element count (`Limits::max_chunks`) are bounded, and everything it allocates is bounded by the size of the input. +- There are two readers. `read_aepx` builds the owned tree element by element. The importer, which + only reads, uses a second reader that decodes every body (hex, text, the alias JSON, the + numbers) into one buffer and records the chunks as a flat depth-first list whose bodies are + ranges of that buffer; it indexes that buffer (`TreeIndex`) as it indexes an `.aep`. The tests + hold both readers to the same tree and the same errors. - Tests: `tests/aepx.rs` compares the five fixture pairs chunk by chunk and byte by byte, compares the typed view of both forms, and runs truncated, bit-flipped, deeply nested and oversized inputs; `crates/aep/tests/it/import/aepx.rs` imports both forms of each pair and expects the same @@ -139,8 +144,8 @@ write on their own. |---|---| | `svap` (4 bytes, the first top-level chunk) is the version of the After Effects that **wrote** the file: `0f 11 0e 02` in all 36 (a down-saved copy keeps the 2026 word) and in all 1 192 other `.aep` files of the local corpus folders. After Effects opens a file without `svap` (`t-nosvap`). | All 36; corpus scan. | | `head` bytes 4 to 7 are the version the file is **written for**: `0f 11 0e 02` (= `svap`) in the 2026 saves, `0f 0b 06 61` in the 25.x copies, `0f 03 06 41` in the 24.x copies, the same word in every family. After Effects refuses a file whose word is zero ("created with an older version [0.0x0]", `u-zhead`). | All 36; `u-zhead`. | -| The word is packed (bit 31 first): bits 25-24 and 21-19 the major, 18-15 the minor, 14-11 the bug-fix, 10-8 a stage (6 in all), 7-0 the build; bits 31-26 (`000011`) and 23-22 (`00`) are the same in all samples and not decoded. `0f110e02` = **26.2.1x2**, which is what the saving After Effects reports for itself (`app.version` recorded by the corpus scripts) - this one sample fixes minor, bug-fix and build. The copies read as **25.6.0x97** and **24.6.0x65** (major **V** from three consecutive majors; minor, bug-fix and build of the copies **E**: one other word decides their positions). `effectcraft_aep::AeVersion`, `AepFile::file_version`, `AepFile::saved_by_version`. | Tests `decodes_the_sampled_words`, `the_container_of_a_copy_states_its_version_in_head_and_the_writer_in_svap`. | -| `head` bytes 0 to 1 (a `u16`) step with the major: 97 (`0x61`) in the 2026 saves, 96 in 25.x, 95 in 24.x; bytes 2 to 3 are 5, 9 and 6 (**?**). Bytes 8 to 15 differ between families, not between versions; bytes 16 to 19 are the save counter (one higher in each copy). Nothing is derived from bytes 0 to 3 (`AepFile::head_revision` exposes the `u16`). | All 36. | +| The word is packed (bit 31 first): bits 25-24 and 21-19 the major, 18-15 the minor, 14-11 the bug-fix, 10-8 a stage (6 in all), 7-0 the build; bits 31-26 (`000011`) and 23-22 (`00`) are the same in all samples and not decoded. `0f110e02` = **26.2.1x2**, which is what the saving After Effects reports for itself (`app.version` recorded by the corpus scripts) - this one sample fixes minor, bug-fix and build. The copies read as **25.6.0x97** and **24.6.0x65** (major **V** from three consecutive majors; minor, bug-fix and build of the copies **E**: one other word decides their positions). `craft_aep::AeVersion`, `AepFile::file_version`, `AepFile::saved_by_version`. | Tests `decodes_the_sampled_words`, `the_container_of_a_copy_states_its_version_in_head_and_the_writer_in_svap`. | +| `head` bytes 0 to 1 (a `u16`) step with the major: 97 (`0x61`) in the 2026 saves, 96 in 25.x, 95 in 24.x; bytes 2 to 3 are 5, 9 and 6 (**?**). Bytes 8 to 15 differ between families, not between versions; bytes 16 to 19 are the save counter (one higher in each copy). Nothing is derived from bytes 0 to 3, and the reader does not expose them. | All 36. | | The XMP packet after the container is no guide: its `CreatorTool` is "Adobe After Effects 2026" in the copies too. | All 36. | | **26 against 25.x** (per family, chunk tree aligned by item and layer id): besides `head`, `nhed` / `nnhd` differ in 6 bytes (`nhed` 20-23 and 26-27: `827fa930` / `0015` in the 2026 save, `00000000` / `011b` in both copies; session state, see section 4). Every **solid's** `Pin /CLRS` changes: the 2026 save has `dcui` (1 byte, 1), `apid` all `0xff` and an empty `Utf8`; the copies drop `dcui`, set `apid` to a GUID (`601e9973...`, the same in all) and embed a 935-byte JSON with an ICC profile (`baseColorProfile/colorProfileData`). A **footage** item that the 2026 save stores with an assigned profile (`mcsp` = 1 and a profile JSON) loses `mcsp` and that JSON in the copies, and its `epid` becomes all `0xff`. The rest is save noise: the footage alias `ascendcount_base` (the copies were saved in another folder), `sspc` byte 112 of a footage item (a modification time), the `oEXR` `opti` of an EXR item (the copies hold the display device name `\.\DISPLAY1` as UTF-16 at byte 126 and, in the 24.x copy, a few non-zero bytes from byte 2 102 that look like uninitialised memory; the 2026 save has zeros), the plug-ins' sequence data `sdat` of Lumetri Color (16 instances and the project's `EfdG`), the mask counter `mkif` byte 8. No chunk is added or reordered, and no `pard`, `cdat`, `ldta`, `cdta`, `tdb4`, keyframe, text or shape chunk differs. | All 12 families. | | **25.x against 24.x**: only `head` (bytes 1, 3, 5 and 7), and the session noise in `opti` and `sdat` above. | All 12 families. | @@ -218,12 +223,12 @@ the value from the corpus manifest (test file in parentheses at the end of each API: `LayerHeader` (`is_video_enabled`/`is_enabled`, `is_audio_enabled`, `is_effects_enabled`, `is_auto_oriented`, `light_type`, `blend_mode`, `stretch` / `stretch_den`, `stretch_ratio`, -`stretch_percent`, `in_point`, `out_point`); the same switches on `Layer`; `Layer::track_matte` +`in_point`, `out_point`); the same switches on `Layer`; `Layer::track_matte` (`TrackMatte`, `MatteMode`; test `tests/matte.rs`). `stretch` is now the numerator of the ratio (it was the whole multiplier before 50 % and 150 % were sampled). Tests: `tests/header.rs`, `tests/layer_switches.rs`. The layer name itself is the `Utf8` child of the `Layr` (empty while the name is the source's); the layer then shows the name of its source item -(`Project::layer_display_name`). +(`Project::layer_source(...)` then `Item::display_name`, the rule the importer uses). ### 3.2 Composition header (`Item/cdta`, 204 bytes; the decoder needs the first 176) and renderer @@ -248,9 +253,9 @@ numerator of the ratio (it was the whole multiplier before 50 % and 150 % were s The inert `ADBE Time Remapping` record of every AV layer has `tduM` = the source's duration in seconds: 5 for 5 s compositions (124, 257, 258), 3 and 2 for a 3 s and a 2 s composition (600, 601), 1 for the 1 s WAV (351), 0.1 for the three-frame sequence (353), 0 on solids and stills (000, 126). Every property's keyframe time scale (`tdb4` bytes 12 to 15) follows the composition (23 976 in every property of `L` after 229 and 230). The corpus manifest calls the classic renderer -`ADBE Advanced 3d`; the file stores `ADBE Escher` / `Classic 3D`. API: `CompHeader::frame_rate_exact` -(exact fraction), `duration_frames`, `shutter_phase`, `display_start`, `display_start_seconds`, -`display_start_frame`. Tests: `tests/header.rs`, `tests/layer_switches.rs`. +`ADBE Advanced 3d`; the file stores `ADBE Escher` / `Classic 3D`. API: `CompHeader::{time_base, +frame_rate_fixed, duration_units, shutter_phase, display_start}` (`display_start` is the exact +fraction). Tests: `tests/header.rs`, `tests/layer_switches.rs`. ### 3.3 Items, footage and precomps @@ -295,7 +300,8 @@ name. A footage layer shows the item's name while it has no name of its own (351 Test: `tests/header.rs` (precomp), `tests/text_markers_footage.rs` and `tests/batch3_objects.rs` (footage), `tests/layer_switches.rs` (solid colour). API: `Footage::{duration, native_frame_rate, -bits_per_pixel, file_size, audio_sample_rate, is_sequence, sequence_frame_count}`. +bits_per_pixel, file_size, audio_sample_rate, is_sequence}`; `Item::sequence_info` (with +`SequenceInfo::frame_count`). ### 3.4 Properties: sparse storage, static values and units @@ -404,8 +410,8 @@ out speed, at 40 out influence**). Scale key 1 of 305 (`n = 3`, in 0 / 33 %, out 15 / 66) is `0,0, .33,.33, 15,15, .66,.66`. Component `i` uses slot `i` of each block (**V** for the block layout and the units, Scale speed in fractions per second and Mask Feather speed in pixels per second; **E** that different values per dimension sit in the slot of their dimension, because -the tool that made the corpus applies one ease to all dimensions; **V** since the exporter wrote three different eases for the three Scale dimensions and After Effects read the same three back, aep-export.md R13). `Keyframe::plain_ease_slots` -returns the doubles as stored, `Keyframe::ease_component(i)` one component's `KeyEase`. Layout of +the tool that made the corpus applies one ease to all dimensions; **V** since the exporter wrote three different eases for the three Scale dimensions and After Effects read the same three back, aep-export.md R13). `Keyframe::ease_component(i)` +returns one component's `KeyEase`, `Keyframe::ease_components` all of them. Layout of the spatial template: `u32` at 8 (1 normally, 0 after the spatial auto-bezier and continuous switches were turned off together, 054), `f64` arc length of the segment to the next key at 16 (100 in 204 key 1, 0 on the last key and right after creation; safe to ignore), **ease at 24 in @@ -430,7 +436,7 @@ in tangent (`n` x `f64`, relative offset from the value) at `56 + 8 n`, out tang | **ease, colour switched to bezier** | spatial n=4 @24..55 | keyframe.set_interpolation bezier on two colour keys stores speed 0 and influence 0 on both sides, and After Effects interpolates them linearly (598 Start Color red to blue: 0.75 / 0.5 / 0.25 red at 0.5 / 1 / 1.5 s); a custom colour ease cannot be set by script | 598 | V | | **ease, mask path** | 64-byte record @24..55 | in speed, in influence, out speed, out influence as in the spatial template: 599 out / in influence 0.75, 700 0.2 / 0.5, speeds 0 (the path at 0.5 s is 5.42 % / 28.0 % of the way). The `f64` at 16 is 1 (093) or 2 (599, 700) on the first key and 0 on the last (not decoded) | 093, 599, 700 | V (influence), ? (speed unit) | -API: `Keyframe::{interpolation_in, interpolation_out, kind, value, ease, ease_component, ease_components, plain_ease_slots, color_distance, spatial}`; +API: `Keyframe::{interpolation_in, interpolation_out, kind, value, ease, ease_component, ease_components, spatial}` (the `f64` at byte 16 of a colour key is `SpatialKey::segment_length`); `Property::keys()` hands the property's template to its records. Marker record (16 bytes): time, `03 03` hold bytes, 8 stale bytes. Mask path record (64 bytes): the common fields and the ease at byte 24 (599, 700). Test: `tests/values.rs`, `tests/keyframes.rs`. @@ -767,7 +773,7 @@ pins are placed by hand or by a preset. 328), so mode and inverted are reported per mask. `mkif` byte 8 is the running mask id counter of the **layer** in the session (1, 2 for the two masks of 328; 329 then gets 3; undo does not reset it; a new layer starts at 1 again): exposed as `Mask::counter`, a session counter and not a stable id. API: -`Mask::{mode, inverted, counter}`, `Project::mask_vertices_px` (vertices in layer pixels), `Layer::mask_atoms` (`MaskAtom`: the mask with its atom group, its path property and its shapes by position, for the keys and expressions of the mask properties). Tests: +`Mask::{mode, inverted, counter}`, `ShapePath::vertices(size)` (vertices in layer pixels: `size` is the size of the layer's source, `Project::layer_source_size`; a text or shape layer has no source size and its mask boxes are already pixels, so the importer passes 1 x 1), `Layer::mask_atoms` (`MaskAtom`: the mask with its atom group, its path property and its shapes by position, for the keys and expressions of the mask properties). Tests: `tests/masks.rs` (with a synthetic check of the handle order), `tests/batch3_objects.rs`. ### 3.9 Shape layers (`tdgp[ADBE Root Vectors Group]`) @@ -895,7 +901,7 @@ groups as on other layers, with these conventions: | What | Path | Stored | Evidence | Conf. | |---|---|---|---|---| -| camera Position, default (auto state) | `ADBE Transform Group/ADBE Position`, `tdb4` 76 and 77 = 1 although no expression exists | `[0, 0, -2666.67]` (x and y are 0 whatever the composition size; z = -zoom). A **one-node** camera reports `[0, 0, -2666.67]` (251). **Correction (S16): a reopened two-node camera reports `[0, 0, -2666.67]` too (256 read back), and After Effects renders it there**: the default two-node camera of 537 above the 3D solid of 486 renders from `[0, 0, -2666.67]` towards the point of interest, not like the composition's default view (537 differs from 486 in 24 % of the grid points, and EffectCraft's import with the stored position matches 537 but for 4 edge points). The `[960, 540, ...]` of the batch-3 notes was not reproduced (535 and 537, created by script, read back the stored value too); `CameraPosition::reported` keeps the old rule and is marked as contradicted | 256, 251, 537 | V | +| camera Position, default (auto state) | `ADBE Transform Group/ADBE Position`, `tdb4` 76 and 77 = 1 although no expression exists | `[0, 0, -2666.67]` (x and y are 0 whatever the composition size; z = -zoom). A **one-node** camera reports `[0, 0, -2666.67]` (251). **Correction (S16): a reopened two-node camera reports `[0, 0, -2666.67]` too (256 read back), and After Effects renders it there**: the default two-node camera of 537 above the 3D solid of 486 renders from `[0, 0, -2666.67]` towards the point of interest, not like the composition's default view (537 differs from 486 in 24 % of the grid points, and EffectCraft's import with the stored position matches 537 but for 4 edge points). The `[960, 540, ...]` of the batch-3 notes was not reproduced (535 and 537, created by script, read back the stored value too); the reader keeps only the stored value (`CameraPosition::stored`) | 256, 251, 537 | V | | camera Position, set by the user | same, `tdb4` 76 and 77 = 0 | the absolute value `[100, 200, -1000]` | 253 | V | | camera point of interest | `ADBE Anchor Point` | `[960, 540, 0]` in **pixels** (not a fraction); the record's `tdsb` is 1 on a two-node and 3 on the one-node camera (not asserted) | 251, 253, 256 | V (value), E (`tdsb`) | | light Position, default | same as the camera | `[0, 0, -1333.33]`, as After Effects reports it (255 read back); the point of interest `[960, 540, 0]` | 254, 255 | V | @@ -911,10 +917,8 @@ groups as on other layers, with these conventions: A point light made by converting a spot light has a different property set (`Orientation`, `Rotate X/Y/Z`, `Cone Angle`, `Cone Feather 2` in the default state) that a spot light lacks (252); whether that -is an artefact of the conversion is untested. API: `Layer::camera_position`, -`CameraPosition::reported`, `Layer::camera_point_of_interest`, `Layer::light_intensity`, -`Layer::{camera_zoom, camera_depth_of_field, camera_focus_distance, camera_aperture, light_color, -light_cone_angle, light_cone_feather}`, `DEFAULT_CAMERA_ZOOM` (2 666.67 is verified for the 1920 px +is an artefact of the conversion is untested. API: `Layer::camera_position`; the camera and light +options are read by the importer's table (`import/camera.rs`); `DEFAULT_CAMERA_ZOOM` (2 666.67 is verified for the 1920 px composition only), `Layer::orientation` (`Orientation`; test `orientation_is_otst_otda` in `tests/batch5.rs`). Render checks against After Effects (20 px grid, 5 184 points): 486 1 point off, 535 2, 536 0, 537 4 (anti-aliased edges); **488 (Orientation `[10, 20, 30]`): 272 points diff --git a/crates/aep/src/aepx.rs b/crates/aep/src/aepx.rs index 9fad696ce..5267080fb 100644 --- a/crates/aep/src/aepx.rs +++ b/crates/aep/src/aepx.rs @@ -12,13 +12,23 @@ //! instructions. A document type declaration is refused (no entity expansion). It runs without //! recursion; the nesting depth and the element count are bounded by [`Limits`], and everything //! it allocates is bounded by the size of the input. +//! +//! There are two readers. [`read_aepx`] builds the owned tree element by element +//! (`aepx/tree.rs`). The importer, which only reads, uses `index_aepx`: it decodes every body +//! (hex, text, the alias JSON, the numbers) into one buffer and records the chunks as entries of +//! the flat index ([`Draft`]s, in depth-first order, bodies as ranges of the buffer), which +//! [`crate::TreeIndex::from_drafts`] turns into an index that borrows the buffer. +//! The tests hold both to the same tree and the same errors. use std::borrow::Cow; -use crate::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; +use crate::chunk::{AepFile, LIST, NESTED_IDS}; use crate::error::AepError; +use crate::index::{Draft, Kind as EntryKind}; use crate::read::{Limits, parse}; +mod tree; + /// The root element of an `.aepx`. const ROOT: &[u8] = b"AfterEffectsProject"; /// The element that holds the XMP packet (the trailer of an `.aep`). @@ -68,17 +78,71 @@ pub fn read_aepx(data: &[u8]) -> Result, AepError> { /// # Errors /// See [`read_aepx`]. pub fn read_aepx_with_limits(data: &[u8], limits: Limits) -> Result, AepError> { + tree::read(data, limits) +} + +/// An `.aepx` read for the flat index: every body decoded into one buffer, and the chunks as +/// [`Draft`]s in depth-first order with their bodies as ranges of that buffer. +/// [`crate::TreeIndex::from_drafts`] makes the index, which borrows the buffer. +pub struct AepxDrafts { + /// The decoded bodies (hex, text, alias JSON, numbers) and the XMP packet. + pub buffer: Vec, + pub nodes: Vec, + /// The XMP packet: a range of `buffer` (empty without one). + pub trailer: (usize, usize), +} + +/// Reads an `.aepx` into [`AepxDrafts`]: the tree [`read_aepx_with_limits`] gives, with the same +/// errors, without one allocation per chunk. +/// +/// # Errors +/// See [`read_aepx_with_limits`]. When memory runs out, two errors come up in more cases than +/// there: [`AepError::TooLarge`] when the chunk list cannot grow (the owned-tree reader would +/// abort), and [`AepError::Xml`] "bdata is too large to hold in memory" also when the shared body +/// buffer cannot grow (the owned-tree reader reserves each value on its own). +pub fn index_aepx(data: &[u8], limits: Limits) -> Result { let text = match std::str::from_utf8(data) { Ok(t) => t.as_bytes(), Err(e) => return Err(xml(e.valid_up_to(), "the file is not valid UTF-8")), }; - Reader { data: text, pos: 0, limits, count: 0, stack: Vec::new(), top: None, trailer: None }.run() + // Every counted element takes at least 3 bytes (`` in a document cut short), so there are + // never more chunks than this. + let bound = (text.len() / 3).min(limits.max_chunks); + let mut nodes = Vec::new(); + let _ = nodes.try_reserve_exact(bound.min(INITIAL_SLOTS)); + // Hex is most of an `.aepx` and decodes to half its length: one buffer of that size usually + // holds everything. A failed reservation is not an error here; the buffer grows as it goes. + let mut buffer = Vec::new(); + let _ = buffer.try_reserve_exact(text.len() / 2); + let reader = Reader { + data: text, + pos: 0, + limits, + count: 0, + stack: Vec::new(), + root_closed: false, + trailer: None, + buffer, + nodes, + bound, + attrs: Vec::new(), + }; + reader.run() } +/// The slots the chunk list starts with; it doubles from there (as the array of +/// [`crate::TreeIndex`] does). +const INITIAL_SLOTS: usize = 1024; + fn xml(offset: usize, what: &'static str) -> AepError { AepError::Xml { offset, what } } +/// The pad byte of a body of `len` bytes, as [`crate::Chunk::data`] sets it. +fn pad_of(len: usize) -> Option { + if len % 2 == 1 { Some(0) } else { None } +} + /// What an open element becomes when it closes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Kind { @@ -102,13 +166,14 @@ struct Frame { at: usize, /// The name as written, to match the end tag. name: (usize, usize), - /// The decoded `bdata` attribute. - bdata: Option>, + /// The chunk's entry in the list (for `Chunk`, `Utf8` and `Alias`). + entry: Option, + /// The buffer length when the element opened: its body starts here. + mark: usize, + /// The end of the decoded `bdata` attribute in the buffer. + bdata_end: Option, /// The attributes of a `fileReference`, in document order. attrs: Vec<(String, String)>, - /// Collected text (only for `string` and the XMP packet). - text: Vec, - children: Vec>, } struct Reader<'d> { @@ -117,13 +182,19 @@ struct Reader<'d> { limits: Limits, count: usize, stack: Vec, - /// The top-level chunks once the root element has closed. - top: Option>>, - trailer: Option>, + /// True once the root element has closed. + root_closed: bool, + trailer: Option<(usize, usize)>, + buffer: Vec, + nodes: Vec, + /// The most chunks the input can hold under the limits: `nodes` never reserves past it. + bound: usize, + /// The attributes of the current start tag; kept to reuse its allocation. + attrs: Vec<((usize, usize), Cow<'d, [u8]>)>, } -impl Reader<'_> { - fn run(mut self) -> Result, AepError> { +impl<'d> Reader<'d> { + fn run(mut self) -> Result { if self.data.starts_with(&[0xef, 0xbb, 0xbf]) { self.pos = 3; } @@ -137,11 +208,13 @@ impl Reader<'_> { if let Some(open) = self.stack.last() { return Err(xml(open.at, "an element is not closed before the end of the file")); } - let chunks = self.top.ok_or_else(|| xml(self.data.len(), "no AfterEffectsProject root element"))?; - Ok(AepFile { chunks, trailer: Cow::Owned(self.trailer.unwrap_or_default()) }) + if !self.root_closed { + return Err(xml(self.data.len(), "no AfterEffectsProject root element")); + } + Ok(AepxDrafts { buffer: self.buffer, nodes: self.nodes, trailer: self.trailer.unwrap_or((0, 0)) }) } - fn rest(&self) -> &[u8] { + fn rest(&self) -> &'d [u8] { self.data.get(self.pos..).unwrap_or(&[]) } @@ -181,14 +254,13 @@ impl Reader<'_> { self.pos = start; let end = self.skip_past(b"]]>", "a CDATA section is not closed")?; let content = self.data.get(start..end).unwrap_or(&[]); - let at = start; - match self.stack.last_mut() { + match self.stack.last() { Some(frame) => { if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) { - frame.text.extend_from_slice(content); + self.buffer.extend_from_slice(content); } } - None => return Err(xml(at, "CDATA outside the root element")), + None => return Err(xml(start, "CDATA outside the root element")), } } else if rest.starts_with(b" { self.pos = self.pos.saturating_add(n); } - fn slice(&self, (a, b): (usize, usize)) -> &[u8] { + fn slice(&self, (a, b): (usize, usize)) -> &'d [u8] { self.data.get(a..b).unwrap_or(&[]) } - fn start_tag(&mut self) -> Result<(), AepError> { - let at = self.pos; - self.pos = self.pos.saturating_add(1); - let name = self.name()?; - let mut attrs: Vec<((usize, usize), Vec)> = Vec::new(); - let self_closing = loop { + /// Reads the attributes of a start tag into `attrs`; true when the tag closes itself. + fn attributes(&mut self, at: usize, attrs: &mut Vec<((usize, usize), Cow<'d, [u8]>)>) -> Result { + loop { self.skip_ws(); let rest = self.rest(); if rest.starts_with(b"/>") { self.pos = self.pos.saturating_add(2); - break true; + return Ok(true); } if rest.starts_with(b">") { self.pos = self.pos.saturating_add(1); - break false; + return Ok(false); } if rest.is_empty() { return Err(xml(at, "a start tag is not closed")); @@ -259,11 +328,27 @@ impl Reader<'_> { if raw.contains(&b'<') { return Err(xml(vstart, "`<` inside an attribute value")); } - let mut value = Vec::new(); - decode_entities(raw, vstart, &mut value)?; + // A value without `&` is its own decoding (most of them, every `bdata` After Effects + // writes): borrow it instead of copying it. + let value = if raw.contains(&b'&') { + let mut value = Vec::new(); + decode_entities(raw, vstart, &mut value)?; + Cow::Owned(value) + } else { + Cow::Borrowed(raw) + }; self.pos = vend.saturating_add(1); attrs.push((key, value)); - }; + } + } + + fn start_tag(&mut self) -> Result<(), AepError> { + let at = self.pos; + self.pos = self.pos.saturating_add(1); + let name = self.name()?; + let mut attrs = std::mem::take(&mut self.attrs); + attrs.clear(); + let self_closing = self.attributes(at, &mut attrs)?; let kind = self.kind_of(name, at)?; if kind != Kind::Root { self.count = self.count.saturating_add(1); @@ -275,15 +360,27 @@ impl Reader<'_> { return Err(AepError::TooDeep); } } - let mut frame = Frame { kind, at, name, bdata: None, attrs: Vec::new(), text: Vec::new(), children: Vec::new() }; - if matches!(kind, Kind::Chunk(_)) { - if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { - frame.bdata = Some(decode_hex(value, key.1)?); + let mark = self.buffer.len(); + let mut frame = Frame { kind, at, name, entry: None, mark, bdata_end: None, attrs: Vec::new() }; + match kind { + Kind::Chunk(id) => { + if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { + decode_hex_into(value, key.1, MAX_BDATA, &mut self.buffer)?; + frame.bdata_end = Some(self.buffer.len()); + } + frame.entry = Some(self.open_entry(id)?); } - } else if kind == Kind::Alias { - frame.attrs = - attrs.iter().map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())).collect(); + Kind::Utf8 => frame.entry = Some(self.open_entry(*b"Utf8")?), + Kind::Alias => { + frame.attrs = attrs + .iter() + .map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())) + .collect(); + frame.entry = Some(self.open_entry(*b"alas")?); + } + Kind::Root | Kind::Xmp | Kind::Skip => {} } + self.attrs = attrs; self.stack.push(frame); if self_closing { self.close()?; @@ -291,12 +388,38 @@ impl Reader<'_> { Ok(()) } + /// Appends the entry of a chunk whose element just opened; its body is filled in when it + /// closes. The list grows by its length (at least 16) but never past [`Self::bound`]; an + /// allocation the target cannot make is an error, not an abort. + fn open_entry(&mut self, id: [u8; 4]) -> Result { + let at = self.nodes.len(); + // This entry and the one after it must have `u32` indices. + u32::try_from(at.checked_add(1).ok_or(AepError::TooManyChunks)?).map_err(|_| AepError::TooManyChunks)?; + if at == self.nodes.capacity() { + // Past the bound (which only a wrong guess could reach) it keeps doubling. + let room = self.bound.saturating_sub(at); + let more = if room == 0 { at.max(16) } else { at.max(16).min(room) }; + self.nodes.try_reserve_exact(more).map_err(|_| AepError::TooLarge)?; + } + self.nodes.push(Draft::placeholder(id)); + Ok(at) + } + + /// Fills in the entry at `at` once its element has closed; its subtree is what follows it. + fn finish(&mut self, at: usize, id: [u8; 4], kind: EntryKind, list_type: [u8; 4], body: (usize, usize), pad: Option) -> Result<(), AepError> { + let end = u32::try_from(self.nodes.len()).map_err(|_| AepError::TooManyChunks)?; + if let Some(d) = self.nodes.get_mut(at) { + *d = Draft { start: body.0, len: body.1.saturating_sub(body.0), id, list_type, end, kind, pad }; + } + Ok(()) + } + /// Classifies an element by its name and where it is. fn kind_of(&self, name: (usize, usize), at: usize) -> Result { let n = self.slice(name); let parent = match self.stack.last() { None => { - if self.top.is_some() { + if self.root_closed { return Err(xml(at, "a second root element")); } if n != ROOT { @@ -340,39 +463,104 @@ impl Reader<'_> { self.close() } - /// Closes the innermost element and hands its chunk to the parent. + /// Closes the innermost element and fills in its chunk's entry. fn close(&mut self) -> Result<(), AepError> { let frame = self.stack.pop().ok_or(xml(self.pos, "an end tag without a start tag"))?; - let chunk = match frame.kind { - Kind::Root => { - self.top = Some(frame.children); - return Ok(()); - } - Kind::Skip => return Ok(()), + match frame.kind { + Kind::Root => self.root_closed = true, + Kind::Skip => {} Kind::Xmp => { + // Only the first packet is kept; a later one is dropped from the buffer (its + // children are skipped, so nothing else was written after it opened). if self.trailer.is_none() { - self.trailer = Some(frame.text); + self.trailer = Some((frame.mark, self.buffer.len())); + } else { + self.buffer.truncate(frame.mark); } - return Ok(()); } - Kind::Utf8 => Chunk::data(*b"Utf8", frame.text), - Kind::Alias => Chunk::data(*b"alas", alias_json(&frame.attrs).into_bytes()), - Kind::Chunk(id) => chunk_of(id, frame)?, - }; - if let Some(parent) = self.stack.last_mut() { - parent.children.push(chunk); + Kind::Utf8 => { + let at = frame.entry.ok_or(xml(frame.at, "an element lost its chunk"))?; + let end = self.buffer.len(); + self.finish(at, *b"Utf8", EntryKind::Data, [0; 4], (frame.mark, end), pad_of(end.saturating_sub(frame.mark)))?; + } + Kind::Alias => { + let at = frame.entry.ok_or(xml(frame.at, "an element lost its chunk"))?; + self.buffer.extend_from_slice(alias_json(&frame.attrs).as_bytes()); + let end = self.buffer.len(); + self.finish(at, *b"alas", EntryKind::Data, [0; 4], (frame.mark, end), pad_of(end.saturating_sub(frame.mark)))?; + } + Kind::Chunk(id) => self.close_chunk(id, &frame)?, } Ok(()) } + /// The chunk of a closed element named by a chunk id (what the owned reader's `chunk_of` + /// built): `bdata` wins over children, `numS` / `ppSn` hold their number, a nested id holds its + /// children (or nothing), any other name is a `LIST` of that type. + fn close_chunk(&mut self, id: [u8; 4], frame: &Frame) -> Result<(), AepError> { + let at = frame.entry.ok_or(xml(frame.at, "an element lost its chunk"))?; + let after = at.checked_add(1).ok_or(AepError::TooManyChunks)?; + if let Some(bdata_end) = frame.bdata_end { + // The children were read (and counted, and checked) but are not part of the chunk. + self.nodes.truncate(after); + self.buffer.truncate(bdata_end); + let body = (frame.mark, bdata_end); + let pad = pad_of(bdata_end.saturating_sub(frame.mark)); + if OPAQUE_LIST_TYPES.contains(&id) { + return self.finish(at, LIST, EntryKind::OpaqueList, id, body, pad); + } + return self.finish(at, id, EntryKind::Data, [0; 4], body, pad); + } + // Numbers written as text: `0` and `150.000000000`. + if &id == b"numS" || &id == b"ppSn" { + let missing = || xml(frame.at, "a numS or ppSn element without its number"); + // Exactly one child chunk, a `Utf8`: the entry after this one, whose subtree runs to the end. + let only = self.nodes.get(after).copied().filter(|c| usize::try_from(c.end).ok() == Some(self.nodes.len())).ok_or_else(missing)?; + if only.id != *b"Utf8" { + return Err(missing()); + } + let text = match only.kind { + EntryKind::Data | EntryKind::OpaqueList => { + only.start.checked_add(only.len).and_then(|end| self.buffer.get(only.start..end)).unwrap_or(&[]) + } + EntryKind::List | EntryKind::Nested => &[], + }; + let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); + let body: [u8; 8]; + let bytes: &[u8] = if &id == b"numS" { + // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. + let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); + let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; + body = u64::from(n as u32).to_be_bytes(); + body.get(4..).unwrap_or(&[]) + } else { + body = text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes(); + &body + }; + self.nodes.truncate(after); + self.buffer.truncate(frame.mark); + self.buffer.extend_from_slice(bytes); + let end = self.buffer.len(); + return self.finish(at, id, EntryKind::Data, [0; 4], (frame.mark, end), pad_of(bytes.len())); + } + let empty = (frame.mark, frame.mark); + if NESTED_IDS.contains(&id) { + if self.nodes.len() == after { + return self.finish(at, id, EntryKind::Data, [0; 4], empty, None); + } + return self.finish(at, id, EntryKind::Nested, [0; 4], empty, None); + } + self.finish(at, LIST, EntryKind::List, id, empty, None) + } + fn text(&mut self) -> Result<(), AepError> { let start = self.pos; let len = self.rest().iter().position(|b| *b == b'<').unwrap_or(self.rest().len()); let end = start.saturating_add(len); self.pos = end; let raw = self.data.get(start..end).unwrap_or(&[]); - match self.stack.last_mut() { - Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut frame.text), + match self.stack.last() { + Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut self.buffer), Some(_) => Ok(()), None if raw.iter().all(u8::is_ascii_whitespace) => Ok(()), None => Err(xml(start, "text outside the root element")), @@ -393,41 +581,6 @@ fn chunk_id(name: &[u8]) -> Option<[u8; 4]> { Some(id) } -/// The chunk of a closed element named by a chunk id. -fn chunk_of(id: [u8; 4], frame: Frame) -> Result, AepError> { - if let Some(bytes) = frame.bdata { - if OPAQUE_LIST_TYPES.contains(&id) { - let pad = if bytes.len() % 2 == 1 { Some(0) } else { None }; - return Ok(Chunk { id: LIST, body: Body::OpaqueList { list_type: id, data: Cow::Owned(bytes) }, pad }); - } - return Ok(Chunk::data(id, bytes)); - } - // Numbers written as text: `0` and `150.000000000`. - if &id == b"numS" || &id == b"ppSn" { - let text = match frame.children.as_slice() { - [only] if only.is(b"Utf8") => only.bytes().unwrap_or(&[]), - _ => return Err(xml(frame.at, "a numS or ppSn element without its number")), - }; - let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); - let body = if &id == b"numS" { - // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. - let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); - let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; - (n as u32).to_be_bytes().to_vec() - } else { - text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes().to_vec() - }; - return Ok(Chunk::data(id, body)); - } - if NESTED_IDS.contains(&id) { - if frame.children.is_empty() { - return Ok(Chunk::data(id, Vec::new())); - } - return Ok(Chunk { id, body: Body::Chunks(frame.children), pad: None }); - } - Ok(Chunk::list(id, frame.children)) -} - /// Appends `raw` with the predefined entities and character references decoded. fn decode_entities(raw: &[u8], offset: usize, out: &mut Vec) -> Result<(), AepError> { let mut i = 0; @@ -465,23 +618,74 @@ fn decode_entities(raw: &[u8], offset: usize, out: &mut Vec) -> Result<(), A Ok(()) } -/// Decodes a `bdata` value (hex digits, two per byte). +/// Decodes a `bdata` value (hex digits, two per byte) into a new `Vec` of exactly its size. fn decode_hex(text: &[u8], offset: usize) -> Result, AepError> { - if text.len() % 2 == 1 { - return Err(xml(offset, "bdata has an odd number of hex digits")); - } + decode_hex_at_most(text, offset, MAX_BDATA) +} + +/// The most bytes one `bdata` may decode to: what the 32-bit size field of a chunk can hold (a +/// larger body could not be written back as an `.aep` either). +const MAX_BDATA: usize = u32::MAX as usize; + +/// [`decode_hex`] with the decoded-size limit as a parameter (so tests can reach it). +fn decode_hex_at_most(text: &[u8], offset: usize, max: usize) -> Result, AepError> { + // Checked before anything is reserved, then sized once (collecting into `Option` has no + // size hint and regrows step by step), and without aborting when the memory is not there. + let pairs = check_hex(text, offset, max)?; + let mut out = Vec::new(); + out.try_reserve_exact(pairs).map_err(|_| xml(offset, "bdata is too large to hold in memory"))?; + decode_checked(text, offset, &mut out)?; + Ok(out) +} + +/// Appends the bytes of a `bdata` value (hex digits, two per byte, at most `max` bytes) to `out`. +/// On an error `out` is unchanged. +fn decode_hex_into(text: &[u8], offset: usize, max: usize, out: &mut Vec) -> Result<(), AepError> { + let pairs = check_hex(text, offset, max)?; + // Grown at most once per value (amortised over a shared buffer), and without aborting when the + // memory is not there. + out.try_reserve(pairs).map_err(|_| xml(offset, "bdata is too large to hold in memory"))?; + decode_checked(text, offset, out) +} + +/// Appends the bytes of a `bdata` value that [`check_hex`] accepted. On an error (a digit the +/// check let through, which it does not) `out` is unchanged. +fn decode_checked(text: &[u8], offset: usize, out: &mut Vec) -> Result<(), AepError> { let digit = |b: u8| match b { b'0'..=b'9' => Some(b - b'0'), b'a'..=b'f' => Some(b - b'a' + 10), b'A'..=b'F' => Some(b - b'A' + 10), _ => None, }; - let (pairs, _) = text.as_chunks::<2>(); - pairs - .iter() - .map(|[hi, lo]| digit(*hi).zip(digit(*lo)).map(|(h, l)| (h << 4) | l)) - .collect::>>() - .ok_or(xml(offset, "bdata holds a character that is not a hex digit")) + let mark = out.len(); + for [hi, lo] in text.as_chunks::<2>().0 { + match (digit(*hi), digit(*lo)) { + (Some(h), Some(l)) => out.push((h << 4) | l), + _ => { + out.truncate(mark); + return Err(xml(offset, "bdata holds a character that is not a hex digit")); + } + } + } + Ok(()) +} + +/// Checks a `bdata` value before anything is reserved for it: an even number of hex digits, at +/// most `max` bytes. Returns the number of bytes it decodes to. +fn check_hex(text: &[u8], offset: usize, max: usize) -> Result { + if text.len() % 2 == 1 { + return Err(xml(offset, "bdata has an odd number of hex digits")); + } + let pairs = text.len() / 2; + if pairs > max { + return Err(AepError::TooLarge); + } + // One cheap pass checks every digit first. Blocks without an early exit inside, so the check + // vectorises; it stops at the first bad block. + if !text.chunks(4096).all(|block| block.iter().fold(true, |ok, b| ok & b.is_ascii_hexdigit())) { + return Err(xml(offset, "bdata holds a character that is not a hex digit")); + } + Ok(pairs) } /// The JSON body of an `alas` chunk from the attributes of a `fileReference`, keys in document @@ -529,6 +733,7 @@ fn json_str(out: &mut String, s: &str) { #[cfg(test)] mod tests { use super::*; + use crate::index::TreeIndex; fn doc(body: &str) -> String { format!("\n{body}\n") @@ -629,6 +834,92 @@ mod tests { assert!(matches!(read_aepx(b"\xff"), Err(AepError::Xml { .. }))); } + /// Attribute values decode entities only where they have them. + #[test] + fn attribute_values_decode_entities_only_where_they_have_them() { + // An entity inside `bdata` still decodes before the hex does. + let f = read_aepx(doc("").as_bytes()).unwrap(); + assert_eq!(f.chunks[0].bytes(), Some(&[0x01, 0xab][..])); + // A bad entity in any attribute, even of an element that is skipped, is still an error. + for bad in ["", "", ""] { + assert!(matches!(read_aepx(doc(bad).as_bytes()), Err(AepError::Xml { .. })), "{bad}"); + } + // Without `&` the value is taken as written. + let f = read_aepx(doc("").as_bytes()).unwrap(); + assert_eq!(f.chunks[0].bytes(), Some(&[0x0a, 0xff][..])); + } + + /// A large bdata with a bad digit is refused before it is sized. + #[test] + fn a_large_bdata_with_a_bad_digit_is_refused_before_it_is_sized() { + // 10 MB of hex that is bad from the first pair (and once more at the very end). + let mut text = b"zz".to_vec(); + text.extend(std::iter::repeat_n(*b"00", 5_000_000).flatten()); + assert_eq!(decode_hex(&text, 3), Err(xml(3, "bdata holds a character that is not a hex digit"))); + let mut late = vec![b'0'; 10_000_000]; + late.extend_from_slice(b"0g"); + assert_eq!(decode_hex(&late, 3), Err(xml(3, "bdata holds a character that is not a hex digit"))); + let x = doc(&format!("", std::str::from_utf8(&text).unwrap())); + assert!(matches!(read_aepx(x.as_bytes()), Err(AepError::Xml { .. }))); + } + + /// Bdata decodes up to the size limit and not past it. + #[test] + fn bdata_decodes_up_to_the_size_limit_and_not_past_it() { + assert_eq!(decode_hex_at_most(b"00ff10", 0, 3), Ok(vec![0x00, 0xff, 0x10])); + assert_eq!(decode_hex_at_most(b"00ff10", 0, 2), Err(AepError::TooLarge)); + assert_eq!(decode_hex_at_most(b"", 0, 0), Ok(Vec::new())); + assert_eq!(decode_hex_at_most(b"00", 0, 0), Err(AepError::TooLarge)); + // The odd-length error still comes first. + assert_eq!(decode_hex_at_most(b"001", 0, 0), Err(xml(0, "bdata has an odd number of hex digits"))); + // The real limit is what a chunk's 32-bit size field holds. + assert_eq!(MAX_BDATA as u64, u64::from(u32::MAX)); + } + + /// Decode hex matches the collecting version. + #[test] + fn decode_hex_matches_the_collecting_version() { + /// The collecting decoder this one replaced, as the reference. + fn old(text: &[u8], offset: usize) -> Result, AepError> { + if text.len() % 2 == 1 { + return Err(xml(offset, "bdata has an odd number of hex digits")); + } + let digit = |b: u8| match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + b'A'..=b'F' => Some(b - b'A' + 10), + _ => None, + }; + let (pairs, _) = text.as_chunks::<2>(); + pairs + .iter() + .map(|[hi, lo]| digit(*hi).zip(digit(*lo)).map(|(h, l)| (h << 4) | l)) + .collect::>>() + .ok_or(xml(offset, "bdata holds a character that is not a hex digit")) + } + let alphabet = b"0123456789abcdefABCDEFgG \0"; + let mut seed = 0x2545_f491_4f6c_dd1du64; + for len in 0..200usize { + for _ in 0..20 { + let text: Vec = (0..len) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + // Mostly hex digits, now and then a byte that is not one. + let i = (seed % 1000) as usize; + alphabet[if i < 990 { i % 22 } else { 22 + i % 4 }] + }) + .collect(); + let new = decode_hex(&text, 7); + assert_eq!(new, old(&text, 7)); + if let Ok(v) = new { + assert_eq!(v.capacity(), v.len()); + } + } + } + } + #[test] fn limits_hold() { let deep = format!("{}{}", "".repeat(100_000), "".repeat(100_000)); @@ -638,4 +929,293 @@ mod tests { let many = format!("{}", "".repeat(10)); assert_eq!(read_aepx_with_limits(many.as_bytes(), Limits { max_depth: 64, max_chunks: 9 }), Err(AepError::TooManyChunks)); } + + /// A tiny deterministic generator (xorshift64*), so the tests need no extra crate. + struct Rng(u64); + + impl Rng { + /// The next pseudo-random number. + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + + /// A number below `n` (0 for `n == 0`). + fn below(&mut self, n: usize) -> usize { + if n == 0 { 0 } else { usize::try_from(self.next() % n as u64).unwrap() } + } + + /// One of `items`. + fn pick<'s>(&mut self, items: &[&'s str]) -> &'s str { + items[self.below(items.len())] + } + } + + /// `n` random bytes as hex, upper or lower case. + fn hex(rng: &mut Rng, n: usize) -> String { + let upper = rng.below(4) == 0; + (0..n).map(|_| if upper { format!("{:02X}", rng.below(256)) } else { format!("{:02x}", rng.below(256)) }).collect() + } + + /// Random `.aepx` content: every element form the reader knows (data, lists, nested ids, + /// strings, numbers, `btdk`, file references, skipped elements, XMP packets), `bdata` next to + /// children, bodies that read as chunk sequences, entities, CDATA, comments and stray text. + fn content(rng: &mut Rng, depth: usize, budget: &mut usize, out: &mut String) { + for _ in 0..rng.below(6) { + if *budget == 0 { + return; + } + *budget -= 1; + match rng.below(20) { + 0..=3 => { + let id = rng.pick(&["cdat", "tdmn", "head", "Utf8", "idta", "LIST", "a"]); + let n = rng.below(9); + out.push_str(&format!("<{id} bdata=\"{}\"/>", hex(rng, n))); + } + 4..=6 if depth < 10 => { + let id = rng.pick(&["Fold", "tdgp", "Layr", "Pin", "LIST", "btdk", "sspc"]); + let attr = if rng.below(5) == 0 { format!(" bdata=\"{}\"", hex(rng, 3)) } else { String::new() }; + out.push_str(&format!("<{id}{attr}>")); + content(rng, depth + 1, budget, out); + out.push_str(&format!("")); + } + 7 => { + let id = rng.pick(&["tdsn", "pdnm", "fnam"]); + match rng.below(4) { + 0 => out.push_str(&format!("<{id}/>")), + 1 => out.push_str(&format!("<{id}>name & A")), + // A body that is itself a chunk sequence (`Utf8`, 1 byte, pad): still data. + 2 => out.push_str(&format!("<{id} bdata=\"557466380000000161{}\"/>", if rng.below(2) == 0 { "00" } else { "" })), + _ => out.push_str(&format!("<{id}>ab")), + } + } + 8 => { + let text = + rng.pick(&["plain", "A < B", "", "ab", "", "été", "xgoney", "\r\n"]); + out.push_str(&format!("{text}")); + } + 9 => { + let id = rng.pick(&["numS", "ppSn"]); + let inner = rng.pick(&[ + "0", + " 7 ", + "-2147483648", + "150.000000000", + "x", + "", + "12", + "", + "", + "34", + ]); + let attr = if rng.below(6) == 0 { " bdata=\"00000002\"" } else { "" }; + out.push_str(&format!("<{id}{attr}>{inner}")); + } + 10 => { + let n = rng.pick(&["", "41", "414243", "4c495354000000000000"]); + out.push_str(&format!("")); + } + 11 => { + let platform = rng.pick(&["Win", "1", "Mac"]); + out.push_str(&format!( + "", + rng.below(3) + )); + } + 12 if depth < 10 => { + out.push_str("text"); + content(rng, depth + 1, budget, out); + out.push_str(""); + } + 13 => { + let packet = rng.pick(&["x]]>", "plain & text", ""]); + out.push_str(&format!("{packet}")); + } + 14 => out.push_str(rng.pick(&["", "", "\n ", "stray"])), + _ => { + let n = rng.below(5); + out.push_str(&format!("", hex(rng, n))); + } + } + } + } + + /// The default limits and six tight ones (depth 0, 1 and 3; 0, 7 and 40 chunks). + fn limit_sets() -> [Limits; 7] { + [ + Limits { max_depth: 0, max_chunks: 10_000_000 }, + Limits { max_depth: 64, max_chunks: 0 }, + Limits::default(), + Limits { max_depth: 1, max_chunks: 10_000_000 }, + Limits { max_depth: 3, max_chunks: 10_000_000 }, + Limits { max_depth: 64, max_chunks: 7 }, + Limits { max_depth: 64, max_chunks: 40 }, + ] + } + + /// The index reader and the owned-tree reader give the same `Result` (the tree, or the error), + /// and the index walks like the index of the owned tree. + fn same(bytes: &[u8], limits: Limits) { + let old = read_aepx_with_limits(bytes, limits); + let new = index_aepx(bytes, limits).map(|d| TreeIndex::from_drafts(&d.buffer, d.nodes, d.trailer).to_file().into_owned()); + assert_eq!(new, old, "{}", String::from_utf8_lossy(bytes)); + if let Ok(file) = &old { + let AepxDrafts { buffer, nodes, trailer } = index_aepx(bytes, limits).unwrap(); + let index = TreeIndex::from_drafts(&buffer, nodes, trailer); + let expected = TreeIndex::from_file(file).unwrap(); + assert_eq!(index.len(), expected.len()); + assert_eq!(index.trailer(), expected.trailer()); + let a: Vec = index.walk().map(|(d, n)| format!("{d} {n:?}")).collect(); + let b: Vec = expected.walk().map(|(d, n)| format!("{d} {n:?}")).collect(); + assert_eq!(a, b); + } + } + + /// The two readers give the same tree and errors on generated and damaged documents. + #[test] + fn the_two_readers_agree_on_generated_and_damaged_documents() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let noise = b"<>/=\"'&;#x0aZ \n![]-?"; + for _ in 0..600 { + let mut budget = 80; + let mut body = String::new(); + content(&mut rng, 0, &mut budget, &mut body); + let x = doc(&body); + for l in limit_sets() { + same(x.as_bytes(), l); + } + for _ in 0..4 { + let mut bad = x.clone().into_bytes(); + for _ in 0..1 + rng.below(3) { + let at = rng.below(bad.len()); + bad[at] = noise[rng.below(noise.len())]; + } + for l in limit_sets() { + same(&bad, l); + } + } + let cut = rng.below(x.len()); + same(&x.as_bytes()[..cut], Limits::default()); + // Bytes that are not UTF-8, and a multi-byte character cut in half. + let mut bad = x.clone().into_bytes(); + let at = rng.below(bad.len()); + bad.insert(at, 0xff); + same(&bad, Limits::default()); + let open = format!("{}é", x.trim_end().trim_end_matches("")).into_bytes(); + same(&open[..open.len() - 1], Limits::default()); + } + } + + /// The flat chunk list never reserves more slots than the input or the chunk limit allows. + #[test] + fn the_chunk_list_is_bounded_by_the_input_and_the_limit() { + let many = format!("{}", "".repeat(10_000)); + let d = index_aepx(many.as_bytes(), Limits::default()).unwrap(); + assert_eq!(d.nodes.len(), 10_000); + assert!(d.nodes.capacity() <= 2 * 10_000, "{} slots for 10 000 chunks", d.nodes.capacity()); + // The buffer is reserved once, at half the input, and holds nothing here. + assert!(d.buffer.is_empty() && d.buffer.capacity() <= many.len() / 2); + // At the limit the list never holds more slots than the limit. + let d = index_aepx(many.as_bytes(), Limits { max_depth: 64, max_chunks: 10_000 }).unwrap(); + assert!(d.nodes.capacity() <= 10_000); + let few = format!("{}", "".repeat(100)); + let d = index_aepx(few.as_bytes(), Limits { max_depth: 64, max_chunks: 100 }).unwrap(); + assert!(d.nodes.capacity() <= 100, "{} slots for at most 100 chunks", d.nodes.capacity()); + assert_eq!(index_aepx(few.as_bytes(), Limits { max_depth: 64, max_chunks: 99 }).err(), Some(AepError::TooManyChunks)); + // A tiny input cannot hold more than a third of its bytes in elements. + let tiny = doc(""); + assert!(index_aepx(tiny.as_bytes(), Limits::default()).unwrap().nodes.capacity() <= tiny.len() / 3); + } + + /// What a closed element drops is gone from the buffer and the chunk list, but was counted. + #[test] + fn dropped_content_leaves_nothing_behind_but_still_counts() { + // `bdata` wins over the children: they are read, counted and dropped. + let x = doc("xyzq"); + let d = index_aepx(x.as_bytes(), Limits::default()).unwrap(); + assert_eq!((d.buffer.as_slice(), d.nodes.len()), (&[1u8][..], 1)); + assert_eq!(index_aepx(x.as_bytes(), Limits { max_depth: 64, max_chunks: 4 }).err(), Some(AepError::TooManyChunks)); + assert!(index_aepx(x.as_bytes(), Limits { max_depth: 64, max_chunks: 5 }).is_ok()); + // A child's error is raised although the child would be dropped. + assert!(matches!(index_aepx(doc("").as_bytes(), Limits::default()), Err(AepError::Xml { .. }))); + // Only the first XMP packet stays in the buffer. + let packets = doc(&"packet".repeat(1000)); + let d = index_aepx(packets.as_bytes(), Limits::default()).unwrap(); + assert_eq!((d.buffer.as_slice(), d.trailer), (&b"packet"[..], (0, 6))); + // A number keeps its 4 or 8 bytes, not its text. + let d = index_aepx(doc(" 7 1.5").as_bytes(), Limits::default()).unwrap(); + assert_eq!(d.buffer, [&[0, 0, 0, 7][..], &1.5f64.to_be_bytes()[..]].concat()); + assert_eq!(d.nodes.len(), 2); + } + + /// Bodies keep what the element says they are, even where reading the same bytes as an `.aep` + /// would decide otherwise: a nested id whose `bdata` is a chunk sequence stays data, an empty + /// `btdk` stays an opaque list, an empty list at the deepest level stays a list. + #[test] + fn bodies_keep_the_kind_the_element_gives_them() { + let x = doc(""); + let AepxDrafts { buffer, nodes, trailer } = index_aepx(x.as_bytes(), Limits::default()).unwrap(); + let index = TreeIndex::from_drafts(&buffer, nodes, trailer); + let top: Vec<_> = index.chunks().collect(); + assert_eq!(top.len(), 3); + assert_eq!(top[0].bytes().map(<[u8]>::len), Some(11)); + assert!(top[0].children().next().is_none()); + assert!(top[1].is_opaque_list() && top[1].bytes() == Some(&[][..])); + assert!(top[2].is_opaque_list() && top[2].bytes().map(<[u8]>::len) == Some(12)); + // 64 levels: the innermost (empty) list is a list, not opaque. + let deep = format!("{}{}", "".repeat(64), "".repeat(64)); + let AepxDrafts { buffer, nodes, trailer } = index_aepx(deep.as_bytes(), Limits::default()).unwrap(); + let index = TreeIndex::from_drafts(&buffer, nodes, trailer); + assert_eq!(index.walk().map(|(d, _)| d).max(), Some(64)); + assert!(index.walk().all(|(_, n)| n.is_list(b"Fold") && !n.is_opaque_list())); + same(x.as_bytes(), Limits::default()); + same(deep.as_bytes(), Limits::default()); + } + + /// Hostile input is refused by both readers with the same errors. + #[test] + fn hostile_input_is_refused_alike_by_both_readers() { + let hostile = [ + format!("{}{}", "".repeat(100_000), "".repeat(100_000)), + format!("{}", "".repeat(1000)), + doc(&format!("", "00".repeat(100_000))), + doc(&format!("", "00".repeat(100_000))), + doc("4294967296"), + doc("1e400x"), + doc("�"), + doc("�"), + doc(&format!("{}", "".repeat(1000))), + format!("{}", "".repeat(10)), + " = + entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "aepx")).collect(); + paths.sort(); + for path in paths { + let bytes = std::fs::read(&path).unwrap(); + for l in limit_sets() { + let index = index_aepx(&bytes, l).map(|d| TreeIndex::from_drafts(&d.buffer, d.nodes, d.trailer).to_file().into_owned()); + assert_eq!(index, read_aepx_with_limits(&bytes, l), "{}", path.display()); + } + } + } } diff --git a/crates/aep/src/aepx/tree.rs b/crates/aep/src/aepx/tree.rs new file mode 100644 index 000000000..6c0bc8435 --- /dev/null +++ b/crates/aep/src/aepx/tree.rs @@ -0,0 +1,362 @@ +//! The `.aepx` reader of the owned chunk tree ([`super::read_aepx`]): it builds the tree element by +//! element. The importer uses the index reader in `aepx.rs` instead; the tests compare the two on +//! generated, damaged and corpus input (the same tree and the same errors). + +use std::borrow::Cow; + +use super::{FILE_REFERENCE, OPAQUE_LIST_TYPES, ROOT, STRING, XMP, alias_json, chunk_id, decode_entities, decode_hex, xml}; +use crate::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; +use crate::error::AepError; +use crate::read::Limits; + +/// [`super::read_aepx_with_limits`]. +pub(super) fn read(data: &[u8], limits: Limits) -> Result, AepError> { + let text = match std::str::from_utf8(data) { + Ok(t) => t.as_bytes(), + Err(e) => return Err(xml(e.valid_up_to(), "the file is not valid UTF-8")), + }; + Reader { data: text, pos: 0, limits, count: 0, stack: Vec::new(), top: None, trailer: None }.run() +} + +/// What an open element becomes when it closes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + /// The root element: its children are the top-level chunks. + Root, + /// A chunk with this id (or a `LIST` with this list type). + Chunk([u8; 4]), + /// A `Utf8` chunk. + Utf8, + /// An `alas` chunk built from the attributes. + Alias, + /// The XMP packet (only directly below the root). + Xmp, + /// An element without a chunk counterpart (a name that is no chunk id); skipped with its content. + Skip, +} + +struct Frame { + kind: Kind, + /// Offset of the start tag (for errors). + at: usize, + /// The name as written, to match the end tag. + name: (usize, usize), + /// The decoded `bdata` attribute. + bdata: Option>, + /// The attributes of a `fileReference`, in document order. + attrs: Vec<(String, String)>, + /// Collected text (only for `string` and the XMP packet). + text: Vec, + children: Vec>, +} + +struct Reader<'d> { + data: &'d [u8], + pos: usize, + limits: Limits, + count: usize, + stack: Vec, + /// The top-level chunks once the root element has closed. + top: Option>>, + trailer: Option>, +} + +impl Reader<'_> { + fn run(mut self) -> Result, AepError> { + if self.data.starts_with(&[0xef, 0xbb, 0xbf]) { + self.pos = 3; + } + while self.pos < self.data.len() { + if self.rest().starts_with(b"<") { + self.markup()?; + } else { + self.text()?; + } + } + if let Some(open) = self.stack.last() { + return Err(xml(open.at, "an element is not closed before the end of the file")); + } + let chunks = self.top.ok_or_else(|| xml(self.data.len(), "no AfterEffectsProject root element"))?; + Ok(AepFile { chunks, trailer: Cow::Owned(self.trailer.unwrap_or_default()) }) + } + + fn rest(&self) -> &[u8] { + self.data.get(self.pos..).unwrap_or(&[]) + } + + /// The offset of `needle` at or after `from`. + fn find(&self, from: usize, needle: &[u8]) -> Option { + let hay = self.data.get(from..)?; + if needle.is_empty() || hay.len() < needle.len() { + return None; + } + let first = *needle.first()?; + let mut i = 0; + while let Some(p) = hay.get(i..)?.iter().position(|b| *b == first) { + let at = i.checked_add(p)?; + if hay.get(at..)?.starts_with(needle) { + return from.checked_add(at); + } + i = at.checked_add(1)?; + } + None + } + + /// Skips to just after `close`, which must follow. + fn skip_past(&mut self, close: &[u8], what: &'static str) -> Result { + let at = self.find(self.pos, close).ok_or(xml(self.pos, what))?; + self.pos = at.saturating_add(close.len()); + Ok(at) + } + + fn markup(&mut self) -> Result<(), AepError> { + let rest = self.rest(); + if rest.starts_with(b"", "a processing instruction is not closed")?; + } else if rest.starts_with(b"", "a comment is not closed")?; + } else if rest.starts_with(b"", "a CDATA section is not closed")?; + let content = self.data.get(start..end).unwrap_or(&[]); + let at = start; + match self.stack.last_mut() { + Some(frame) => { + if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) { + frame.text.extend_from_slice(content); + } + } + None => return Err(xml(at, "CDATA outside the root element")), + } + } else if rest.starts_with(b" bool { + !(b.is_ascii_whitespace() || matches!(b, b'<' | b'>' | b'/' | b'=' | b'"' | b'\'' | b'&')) + } + + fn name(&mut self) -> Result<(usize, usize), AepError> { + let start = self.pos; + let len = self.rest().iter().position(|b| !Self::is_name_byte(*b)).unwrap_or(self.rest().len()); + if len == 0 { + return Err(xml(start, "a tag or attribute has no name")); + } + self.pos = start.saturating_add(len); + Ok((start, self.pos)) + } + + fn skip_ws(&mut self) { + let n = self.rest().iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(self.rest().len()); + self.pos = self.pos.saturating_add(n); + } + + fn slice(&self, (a, b): (usize, usize)) -> &[u8] { + self.data.get(a..b).unwrap_or(&[]) + } + + fn start_tag(&mut self) -> Result<(), AepError> { + let at = self.pos; + self.pos = self.pos.saturating_add(1); + let name = self.name()?; + let mut attrs = Vec::new(); + let self_closing = loop { + self.skip_ws(); + let rest = self.rest(); + if rest.starts_with(b"/>") { + self.pos = self.pos.saturating_add(2); + break true; + } + if rest.starts_with(b">") { + self.pos = self.pos.saturating_add(1); + break false; + } + if rest.is_empty() { + return Err(xml(at, "a start tag is not closed")); + } + let key = self.name()?; + self.skip_ws(); + if !self.rest().starts_with(b"=") { + return Err(xml(self.pos, "an attribute has no value")); + } + self.pos = self.pos.saturating_add(1); + self.skip_ws(); + let quote = *self.rest().first().ok_or(xml(self.pos, "a start tag is not closed"))?; + if quote != b'"' && quote != b'\'' { + return Err(xml(self.pos, "an attribute value is not quoted")); + } + let vstart = self.pos.saturating_add(1); + let vend = self.find(vstart, &[quote]).ok_or(xml(vstart, "an attribute value is not closed"))?; + let raw = self.data.get(vstart..vend).unwrap_or(&[]); + if raw.contains(&b'<') { + return Err(xml(vstart, "`<` inside an attribute value")); + } + // A value without `&` is its own decoding (most of them, every `bdata` After Effects + // writes): borrow it instead of copying it. + let value = if raw.contains(&b'&') { + let mut value = Vec::new(); + decode_entities(raw, vstart, &mut value)?; + Cow::Owned(value) + } else { + Cow::Borrowed(raw) + }; + self.pos = vend.saturating_add(1); + attrs.push((key, value)); + }; + let kind = self.kind_of(name, at)?; + if kind != Kind::Root { + self.count = self.count.saturating_add(1); + if self.count > self.limits.max_chunks { + return Err(AepError::TooManyChunks); + } + // The root's children are depth 1, like the top-level chunks of an `.aep`. + if self.stack.len() > self.limits.max_depth { + return Err(AepError::TooDeep); + } + } + let mut frame = Frame { kind, at, name, bdata: None, attrs: Vec::new(), text: Vec::new(), children: Vec::new() }; + if matches!(kind, Kind::Chunk(_)) { + if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { + frame.bdata = Some(decode_hex(value, key.1)?); + } + } else if kind == Kind::Alias { + frame.attrs = + attrs.iter().map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())).collect(); + } + self.stack.push(frame); + if self_closing { + self.close()?; + } + Ok(()) + } + + /// Classifies an element by its name and where it is. + fn kind_of(&self, name: (usize, usize), at: usize) -> Result { + let n = self.slice(name); + let parent = match self.stack.last() { + None => { + if self.top.is_some() { + return Err(xml(at, "a second root element")); + } + if n != ROOT { + return Err(xml(at, "the root element is not AfterEffectsProject")); + } + return Ok(Kind::Root); + } + Some(p) => p.kind, + }; + Ok(match parent { + Kind::Skip | Kind::Utf8 | Kind::Xmp | Kind::Alias => Kind::Skip, + Kind::Root | Kind::Chunk(_) => { + if n == STRING { + Kind::Utf8 + } else if n == FILE_REFERENCE { + Kind::Alias + } else if n == XMP && parent == Kind::Root { + Kind::Xmp + } else if let Some(id) = chunk_id(n) { + Kind::Chunk(id) + } else { + Kind::Skip + } + } + }) + } + + fn end_tag(&mut self) -> Result<(), AepError> { + let at = self.pos; + self.pos = self.pos.saturating_add(2); + let name = self.name()?; + self.skip_ws(); + if !self.rest().starts_with(b">") { + return Err(xml(at, "an end tag is not closed")); + } + self.pos = self.pos.saturating_add(1); + let open = self.stack.last().ok_or(xml(at, "an end tag without a start tag"))?; + if self.slice(open.name) != self.slice(name) { + return Err(xml(at, "an end tag does not match its start tag")); + } + self.close() + } + + /// Closes the innermost element and hands its chunk to the parent. + fn close(&mut self) -> Result<(), AepError> { + let frame = self.stack.pop().ok_or(xml(self.pos, "an end tag without a start tag"))?; + let chunk = match frame.kind { + Kind::Root => { + self.top = Some(frame.children); + return Ok(()); + } + Kind::Skip => return Ok(()), + Kind::Xmp => { + if self.trailer.is_none() { + self.trailer = Some(frame.text); + } + return Ok(()); + } + Kind::Utf8 => Chunk::data(*b"Utf8", frame.text), + Kind::Alias => Chunk::data(*b"alas", alias_json(&frame.attrs).into_bytes()), + Kind::Chunk(id) => chunk_of(id, frame)?, + }; + if let Some(parent) = self.stack.last_mut() { + parent.children.push(chunk); + } + Ok(()) + } + + fn text(&mut self) -> Result<(), AepError> { + let start = self.pos; + let len = self.rest().iter().position(|b| *b == b'<').unwrap_or(self.rest().len()); + let end = start.saturating_add(len); + self.pos = end; + let raw = self.data.get(start..end).unwrap_or(&[]); + match self.stack.last_mut() { + Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut frame.text), + Some(_) => Ok(()), + None if raw.iter().all(u8::is_ascii_whitespace) => Ok(()), + None => Err(xml(start, "text outside the root element")), + } + } +} + +/// The chunk of a closed element named by a chunk id. +fn chunk_of(id: [u8; 4], frame: Frame) -> Result, AepError> { + if let Some(bytes) = frame.bdata { + if OPAQUE_LIST_TYPES.contains(&id) { + let pad = if bytes.len() % 2 == 1 { Some(0) } else { None }; + return Ok(Chunk { id: LIST, body: Body::OpaqueList { list_type: id, data: Cow::Owned(bytes) }, pad }); + } + return Ok(Chunk::data(id, bytes)); + } + // Numbers written as text: `0` and `150.000000000`. + if &id == b"numS" || &id == b"ppSn" { + let text = match frame.children.as_slice() { + [only] if only.is(b"Utf8") => only.bytes().unwrap_or(&[]), + _ => return Err(xml(frame.at, "a numS or ppSn element without its number")), + }; + let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); + let body = if &id == b"numS" { + // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. + let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); + let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; + (n as u32).to_be_bytes().to_vec() + } else { + text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes().to_vec() + }; + return Ok(Chunk::data(id, body)); + } + if NESTED_IDS.contains(&id) { + if frame.children.is_empty() { + return Ok(Chunk::data(id, Vec::new())); + } + return Ok(Chunk { id, body: Body::Chunks(frame.children), pad: None }); + } + Ok(Chunk::list(id, frame.children)) +} diff --git a/crates/aep/src/arbitrary.rs b/crates/aep/src/arbitrary.rs index 45768ae44..70627139b 100644 --- a/crates/aep/src/arbitrary.rs +++ b/crates/aep/src/arbitrary.rs @@ -7,9 +7,9 @@ //! Hue/Saturation (444-446) or a Levels value (512-516) changes only bytes of this `aRbp` (and stale //! UI bytes of `pard`); the visible parameters of the same names keep no record. -use crate::Chunk; use crate::bytes::{be_f32, be_i32, be_u16, be_u32}; use crate::effects::Effect; +use crate::index::Node; impl<'f, 'a> Effect<'f, 'a> { /// The arbitrary data stored for the parameter with this match name (`-NNNN`): the @@ -17,13 +17,13 @@ impl<'f, 'a> Effect<'f, 'a> { /// none. pub fn arbitrary_data(&self, match_name: &str) -> Option<&'f [u8]> { let values = self.chunk().child_list(b"tdgp")?; - let kids = values.children(); - let at = kids.iter().position(|c| c.is(b"tdmn") && c.bytes().is_some_and(|b| name_is(b, match_name)))?; - // The value record, then the data list (no match name of its own). - let rest = kids.get(at.checked_add(1)?..)?; - let mut it = rest.iter().take(3); + let mut kids = values.children(); + // Up to the parameter's match name, then the value record, then the data list (no match + // name of its own). + kids.find(|c| c.is(b"tdmn") && c.bytes().is_some_and(|b| name_is(b, match_name)))?; + let mut it = kids.take(3); let _record = it.next().filter(|c| c.is_list(b"tdbs"))?; - it.find(|c| c.is_list(b"aRbs")).and_then(|l| l.child(b"aRbp")).and_then(Chunk::bytes) + it.find(|c| c.is_list(b"aRbs")).and_then(|l| l.child(b"aRbp")).and_then(Node::bytes) } } diff --git a/crates/aep/src/camera.rs b/crates/aep/src/camera.rs index 69cd8c2c8..934f36bd6 100644 --- a/crates/aep/src/camera.rs +++ b/crates/aep/src/camera.rs @@ -16,7 +16,6 @@ //! only when it is not the default 100. use crate::typed::{Layer, PropNode}; -use crate::values::{Tracked, ValueSource, read, read_opt}; /// The Position of a camera or light layer as stored. #[derive(Debug, Clone, Copy, PartialEq)] @@ -28,16 +27,6 @@ pub struct CameraPosition { pub auto_state: bool, } -impl CameraPosition { - /// The position as the batch-3 notes had After Effects report it: in the auto state of a - /// two-node camera (`two_node`) x and y are the composition centre; otherwise the stored - /// value. **Contradicted by 256 and 537 (session S16): After Effects reports and renders the - /// stored value**; use `stored` for what After Effects shows. - pub fn reported(&self, comp_width: u32, comp_height: u32, two_node: bool) -> [f64; 3] { - if self.auto_state && two_node { [f64::from(comp_width) / 2.0, f64::from(comp_height) / 2.0, self.stored[2]] } else { self.stored } - } -} - impl<'f, 'a> Layer<'f, 'a> { /// The Position record of a camera or light layer. pub fn camera_position(&self) -> Option { @@ -49,87 +38,9 @@ impl<'f, 'a> Layer<'f, 'a> { let derived = h.get(76) == Some(&1) && h.get(77) == Some(&1) && position.expression().is_none(); Some(CameraPosition { stored, auto_state: derived }) } - - /// The point of interest of a camera in pixels (its Anchor Point record); `None` when absent. - pub fn camera_point_of_interest(&self) -> Option<[f64; 3]> { - let Some(PropNode::Group(transform)) = self.properties()?.get("ADBE Transform Group") else { return None }; - let tracked = read(&transform, "ADBE Anchor Point", [0.0; 3], 1.0); - matches!(tracked.source, ValueSource::Stored | ValueSource::Keyframed).then_some(tracked.value) - } - - /// A light's intensity in percent; the default 100 when the property is absent. - pub fn light_intensity(&self) -> Option> { - let root = self.properties()?; - let Some(PropNode::Group(options)) = root.get("ADBE Light Options Group") else { return None }; - let t = read(&options, "ADBE Light Intensity", [100.0], 1.0); - Some(Tracked { value: t.value[0], source: t.source }) - } } /// The camera zoom After Effects uses when `ADBE Camera Zoom` is absent: 2666.67 px for the 50 mm /// default camera in the 1920 px wide corpus composition. Whether it follows other composition /// widths was not sampled. pub const DEFAULT_CAMERA_ZOOM: f64 = 2_666.666_666_666_666_5; - -impl<'f, 'a> Layer<'f, 'a> { - fn camera_options(&self) -> Option> { - match self.properties()?.get("ADBE Camera Options Group") { - Some(PropNode::Group(g)) => Some(g), - _ => None, - } - } - - fn light_options(&self) -> Option> { - match self.properties()?.get("ADBE Light Options Group") { - Some(PropNode::Group(g)) => Some(g), - _ => None, - } - } - - /// A camera's zoom in pixels (`ADBE Camera Options Group/ADBE Camera Zoom`); absent = the - /// default, [`DEFAULT_CAMERA_ZOOM`] (341: 2000 is stored). The auto Position keeps `-2666.67` and - /// is not recomputed from the zoom. - pub fn camera_zoom(&self) -> Option> { - let t = read(&self.camera_options()?, "ADBE Camera Zoom", [DEFAULT_CAMERA_ZOOM], 1.0); - Some(Tracked { value: t.value[0], source: t.source }) - } - - /// The depth of field switch (`ADBE Camera Depth of Field`, a checkbox; off by default, 342). - pub fn camera_depth_of_field(&self) -> Option> { - let t = read(&self.camera_options()?, "ADBE Camera Depth of Field", [0.0], 1.0); - Some(Tracked { value: t.value[0] != 0.0, source: t.source }) - } - - /// A camera's focus distance in pixels (`ADBE Camera Focus Distance`); `None` while absent (its - /// default is not known). - pub fn camera_focus_distance(&self) -> Option> { - let t = read_opt::<1>(&self.camera_options()?, "ADBE Camera Focus Distance", 1.0)?; - Some(Tracked { value: t.value[0], source: t.source }) - } - - /// A camera's aperture (`ADBE Camera Aperture`); `None` while absent (its default is not known). - pub fn camera_aperture(&self) -> Option> { - let t = read_opt::<1>(&self.camera_options()?, "ADBE Camera Aperture", 1.0)?; - Some(Tracked { value: t.value[0], source: t.source }) - } - - /// A light's colour as `[A, R, G, B]` fractions (`ADBE Light Options Group/ADBE Light Color`, - /// stored as doubles 0..255); white when absent (343 stores red). - pub fn light_color(&self) -> Option> { - Some(read(&self.light_options()?, "ADBE Light Color", [1.0; 4], 1.0 / 255.0)) - } - - /// A spot light's cone angle in degrees (`ADBE Light Cone Angle`); 90 when absent (344 stores 60). - /// A point light stores 90 with `tdsb` 3. - pub fn light_cone_angle(&self) -> Option> { - let t = read(&self.light_options()?, "ADBE Light Cone Angle", [90.0], 1.0); - Some(Tracked { value: t.value[0], source: t.source }) - } - - /// A spot light's cone feather in percent (`ADBE Light Cone Feather 2`); 50 when absent (345 - /// stores 30). - pub fn light_cone_feather(&self) -> Option> { - let t = read(&self.light_options()?, "ADBE Light Cone Feather 2", [50.0], 1.0); - Some(Tracked { value: t.value[0], source: t.source }) - } -} diff --git a/crates/aep/src/effects.rs b/crates/aep/src/effects.rs index 25b7051ab..65f3c6125 100644 --- a/crates/aep/src/effects.rs +++ b/crates/aep/src/effects.rs @@ -20,8 +20,8 @@ use std::collections::{HashMap, HashSet}; -use crate::Chunk; use crate::bytes::{array, be_f32, be_f64, be_i32, be_u16, be_u32, cstr, text, until_nul}; +use crate::index::Node; use crate::typed::{KeyList, Layer, Project, PropGroup, PropNode, Property}; /// The parameter type, the `u32` at byte 12 of `pard`. The numbering matches the plug-in @@ -132,7 +132,7 @@ pub enum LayerRef { #[derive(Debug, Clone)] pub struct Effect<'f, 'a> { match_name: String, - chunk: &'f Chunk<'a>, + chunk: Node<'f, 'a>, } /// Where the parameter definitions of an effect instance come from. @@ -178,13 +178,13 @@ impl<'f, 'a> Effect<'f, 'a> { } /// The underlying `LIST sspc` chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } /// The instance name shown in the effect controls (`fnam`). pub fn name(&self) -> Option { - self.chunk.child(b"fnam")?.children().iter().find(|c| c.is(b"Utf8"))?.bytes().map(text) + self.chunk.child(b"fnam")?.child(b"Utf8")?.bytes().map(text) } /// The name the user gave the instance: the `tdsn` of the instance's value group when it is @@ -192,7 +192,7 @@ impl<'f, 'a> Effect<'f, 'a> { /// `None` while the instance shows the effect's name. pub fn user_name(&self) -> Option { let values = self.chunk.child_list(b"tdgp")?; - let name = values.child(b"tdsn")?.children().iter().find(|c| c.is(b"Utf8"))?.bytes().map(text)?; + let name = values.child(b"tdsn")?.child(b"Utf8")?.bytes().map(text)?; (name != "-_0_/-" && !name.is_empty()).then_some(name) } @@ -250,7 +250,7 @@ impl<'f, 'a> Effect<'f, 'a> { } /// The parameters described by `part` (a `LIST parT`) with the values of this instance. - fn params_from(&self, part: &'f Chunk<'a>, borrowed: bool) -> Vec> { + fn params_from(&self, part: Node<'f, 'a>, borrowed: bool) -> Vec> { let mut out: Vec> = Vec::new(); // The stored values by match name: the first entry of a name, as `PropGroup::get` finds it // (a group of that name means no stored value). Indexed once: a lookup per parameter @@ -271,8 +271,8 @@ impl<'f, 'a> Effect<'f, 'a> { out.push(EffectParam { index: out.len(), match_name, - kind: ParamKind::from_u32(be_u32(pard, 12).unwrap_or(u32::MAX)), - name: cstr(pard, 16, 32).unwrap_or_default(), + kind: Pard(pard).kind(), + name: Pard(pard).name().unwrap_or_default(), items: None, borrowed_definition: borrowed, pard, @@ -280,7 +280,7 @@ impl<'f, 'a> Effect<'f, 'a> { }); } else if c.is(b"pdnm") && let Some(last) = out.last_mut() - && let Some(u) = c.children().iter().find(|u| u.is(b"Utf8")) + && let Some(u) = c.child(b"Utf8") && let Some(b) = u.bytes() // An empty `pdnm` names nothing (some writers store one: the effect // supplies its items). @@ -293,8 +293,9 @@ impl<'f, 'a> Effect<'f, 'a> { } } -fn has_pard(part: &Chunk<'_>) -> bool { - part.children().iter().any(|c| c.is(b"pard")) +/// True when a `LIST parT` holds parameter definitions (a `pard`). +fn has_pard(part: Node<'_, '_>) -> bool { + part.children().any(|c| c.is(b"pard")) } impl<'f, 'a> Project<'f, 'a> { @@ -302,18 +303,18 @@ impl<'f, 'a> Project<'f, 'a> { /// name and the `LIST parT` of the copied instance, in file order (the stack order of the /// types, 365/366). The `EfDC` count before them is little-endian and is not needed to read /// them. A type whose copy has no definitions is left out. - pub fn effect_definitions(&self) -> Vec<(String, &'f Chunk<'a>)> { - let mut out: Vec<(String, &'f Chunk<'a>)> = Vec::new(); + pub fn effect_definitions(&self) -> Vec<(String, Node<'f, 'a>)> { + let mut out: Vec<(String, Node<'f, 'a>)> = Vec::new(); let Some(defs) = self.effect_defs else { return out }; let mut seen: HashSet = HashSet::new(); - for df in defs.children().iter().filter(|c| c.is_list(b"EfDf")) { + for df in defs.children().filter(|c| c.is_list(b"EfDf")) { let mut name: Option = None; for c in df.children() { if c.is(b"tdmn") { name = c.bytes().map(|b| text(until_nul(b))); } else if c.is_list(b"sspc") && let Some(n) = name.take() - && let Some(part) = c.child_list(b"parT").filter(|p| has_pard(p)) + && let Some(part) = c.child_list(b"parT").filter(|p| has_pard(*p)) && seen.insert(n.clone()) { out.push((n, part)); @@ -328,8 +329,8 @@ impl<'f, 'a> Project<'f, 'a> { /// For a type without a project-level copy it also keeps the own `parT` of the first instance /// in the file (items, layers and effects in file order) that has one. pub fn effect_definition_index(&self) -> EffectDefinitions<'f, 'a> { - let by_name: HashMap> = self.effect_definitions().into_iter().collect(); - let mut instances: HashMap> = HashMap::new(); + let by_name: HashMap> = self.effect_definitions().into_iter().collect(); + let mut instances: HashMap> = HashMap::new(); for item in self.all_items() { let Some(comp) = item.comp() else { continue }; for layer in comp.layers() { @@ -337,7 +338,7 @@ impl<'f, 'a> Project<'f, 'a> { if by_name.contains_key(&fx.match_name) || instances.contains_key(&fx.match_name) { continue; } - if let Some(part) = fx.chunk.child_list(b"parT").filter(|p| has_pard(p)) { + if let Some(part) = fx.chunk.child_list(b"parT").filter(|p| has_pard(*p)) { instances.insert(fx.match_name, part); } } @@ -363,9 +364,9 @@ impl<'f, 'a> Project<'f, 'a> { #[derive(Debug, Clone, Default)] pub struct EffectDefinitions<'f, 'a> { /// The project-level copies (`EfdG`). - by_name: HashMap>, + by_name: HashMap>, /// For a type without a project-level copy: the own `parT` of the first instance that has one. - instances: HashMap>, + instances: HashMap>, } impl<'f, 'a> EffectDefinitions<'f, 'a> { @@ -392,7 +393,7 @@ impl<'f, 'a> EffectDefinitions<'f, 'a> { return effect.params(); } match self.by_name.get(effect.match_name()).or_else(|| self.instances.get(effect.match_name())) { - Some(part) => effect.params_from(part, true), + Some(part) => effect.params_from(*part, true), None => Vec::new(), } } @@ -484,26 +485,7 @@ impl<'f, 'a> EffectParam<'f, 'a> { pub fn pard_default(&self) -> Option { match self.kind { ParamKind::Popup if self.borrowed_definition => None, - ParamKind::FloatSlider => be_f64(self.pard, 56).map(ParamValue::Number), - ParamKind::FixedSlider | ParamKind::Angle => be_i32(self.pard, 56).map(|v| ParamValue::Number(f64::from(v) / 65536.0)), - ParamKind::IntSlider => be_i32(self.pard, 56).map(|v| ParamValue::Number(f64::from(v))), - ParamKind::Checkbox => be_u32(self.pard, 56).map(|v| ParamValue::Bool(v != 0)), - ParamKind::Popup => be_u32(self.pard, 56).map(ParamValue::Index), - ParamKind::Point => { - let p = [f64::from(be_i32(self.pard, 56)?) / 65536.0, f64::from(be_i32(self.pard, 60)?) / 65536.0]; - // A fresh instance stores fractions of the layer (0.5, 0.5); After Effects' save of - // a project it opened stores percent (50, 50: the re-saves of read-back tests e1 and - // e2, where Gradient Ramp's Start and End and every other point default came back - // as 50 / 0 and 50 / 100). Point - // defaults lie inside the layer, so a component beyond 1 tells percent. - let percent = p.iter().any(|c| c.abs() > 1.0 + 1e-9); - Some(ParamValue::Point(if percent { p.map(|c| c / 100.0) } else { p })) - } - ParamKind::Color => { - let [a, r, g, b] = array::<4>(self.pard, 56)?.map(|c| f64::from(c) / 255.0); - Some(ParamValue::Argb([a, r, g, b])) - } - _ => None, + kind => Pard(self.pard).default(kind), } } @@ -557,22 +539,14 @@ impl<'f, 'a> EffectParam<'f, 'a> { /// slider differs per parameter (Amount 37.5 % is stored 37.5, Blend 25 % is stored 0.25), so /// this is what tells a reader the scale. `None` for other types. pub fn valid_max(&self) -> Option { - match self.kind { - ParamKind::FixedSlider => be_i32(self.pard, 128).map(|v| f64::from(v) / 65536.0), - ParamKind::FloatSlider => be_f32(self.pard, 108).map(f64::from), - ParamKind::IntSlider => be_i32(self.pard, 128).map(f64::from), - _ => None, - } + Pard(self.pard).valid_max(self.kind) } /// The smallest valid value of a float slider, the `f32` at byte 104 of `pard` (Exposure /// -100, Offset -2, Gamma Correction 0.1: 389). `None` for other types (a fixed slider's /// minimum is not decoded). pub fn valid_min(&self) -> Option { - match self.kind { - ParamKind::FloatSlider => be_f32(self.pard, 104).map(f64::from), - _ => None, - } + Pard(self.pard).valid_min(self.kind) } /// The range of a float slider's slider (what the control's drag covers, inside the valid @@ -581,7 +555,7 @@ impl<'f, 'a> EffectParam<'f, 'a> { /// for other types. pub fn slider_range(&self) -> Option<(f64, f64)> { match self.kind { - ParamKind::FloatSlider => Some((f64::from(be_f32(self.pard, 112)?), f64::from(be_f32(self.pard, 116)?))), + ParamKind::FloatSlider => Pard(self.pard).slider_range(self.kind), _ => None, } } @@ -591,7 +565,7 @@ impl<'f, 'a> EffectParam<'f, 'a> { if self.kind != ParamKind::Popup { return None; } - be_u16(self.pard, 60) + Pard(self.pard).popup_item_count() } /// For a popup: the selected item index (1-based): the stored selection, else the default. @@ -619,6 +593,93 @@ impl<'f, 'a> EffectParam<'f, 'a> { } } +/// A parameter definition (`pard`, 148 bytes; aep-format.md 3.7): the one decoder of its fields. +/// The import reads them through [`EffectParam`]; the export writes them from its effect table and +/// its tests read them back through this. +#[derive(Clone, Copy, Debug)] +pub struct Pard<'f>(pub &'f [u8]); + +impl Pard<'_> { + /// The type code, the `u32` at byte 12. + pub fn code(self) -> Option { + be_u32(self.0, 12) + } + + /// The parameter type (an unreadable code is [`ParamKind::Other`]). + pub fn kind(self) -> ParamKind { + ParamKind::from_u32(self.code().unwrap_or(u32::MAX)) + } + + /// The parameter name at byte 16 (32 bytes). + pub fn name(self) -> Option { + cstr(self.0, 16, 32) + } + + /// The default at byte 56 as a parameter of type `kind` reads it (see + /// [`EffectParam::pard_default`]). + pub fn default(self, kind: ParamKind) -> Option { + let p = self.0; + match kind { + ParamKind::FloatSlider => be_f64(p, 56).map(ParamValue::Number), + ParamKind::FixedSlider | ParamKind::Angle => be_i32(p, 56).map(|v| ParamValue::Number(f64::from(v) / 65536.0)), + ParamKind::IntSlider => be_i32(p, 56).map(|v| ParamValue::Number(f64::from(v))), + ParamKind::Checkbox => be_u32(p, 56).map(|v| ParamValue::Bool(v != 0)), + ParamKind::Popup => be_u32(p, 56).map(ParamValue::Index), + ParamKind::Point => { + let pt = [f64::from(be_i32(p, 56)?) / 65536.0, f64::from(be_i32(p, 60)?) / 65536.0]; + // A fresh instance stores fractions of the layer (0.5, 0.5); After Effects' save of + // a project it opened stores percent (50, 50: the re-saves of read-back tests e1 and + // e2, where Gradient Ramp's Start and End and every other point default came back + // as 50 / 0 and 50 / 100). Point + // defaults lie inside the layer, so a component beyond 1 tells percent. + let percent = pt.iter().any(|c| c.abs() > 1.0 + 1e-9); + Some(ParamValue::Point(if percent { pt.map(|c| c / 100.0) } else { pt })) + } + ParamKind::Color => { + let [a, r, g, b] = array::<4>(p, 56)?.map(|c| f64::from(c) / 255.0); + Some(ParamValue::Argb([a, r, g, b])) + } + _ => None, + } + } + + /// The valid maximum of a slider (see [`EffectParam::valid_max`]). + pub fn valid_max(self, kind: ParamKind) -> Option { + match kind { + ParamKind::FixedSlider => be_i32(self.0, 128).map(|v| f64::from(v) / 65536.0), + ParamKind::FloatSlider => be_f32(self.0, 108).map(f64::from), + ParamKind::IntSlider => be_i32(self.0, 128).map(f64::from), + _ => None, + } + } + + /// The valid minimum of a float slider (see [`EffectParam::valid_min`]). + pub fn valid_min(self, kind: ParamKind) -> Option { + match kind { + ParamKind::FloatSlider => be_f32(self.0, 104).map(f64::from), + _ => None, + } + } + + /// A slider's range, the one its value records repeat as `tdum` / `tduM`: a float slider's + /// `f32` pair at 112 / 116, a fixed slider's 16.16 pair and an integer slider's `i32` pair at + /// 132 / 136. + pub fn slider_range(self, kind: ParamKind) -> Option<(f64, f64)> { + let p = self.0; + match kind { + ParamKind::FloatSlider => Some((f64::from(be_f32(p, 112)?), f64::from(be_f32(p, 116)?))), + ParamKind::FixedSlider => Some((f64::from(be_i32(p, 132)?) / 65536.0, f64::from(be_i32(p, 136)?) / 65536.0)), + ParamKind::IntSlider => Some((f64::from(be_i32(p, 132)?), f64::from(be_i32(p, 136)?))), + _ => None, + } + } + + /// A popup's item count, the `u16` at byte 60. + pub fn popup_item_count(self) -> Option { + be_u16(self.0, 60) + } +} + impl<'f, 'a> Layer<'f, 'a> { /// The effects on the layer, in stack order (`ADBE Effect Parade`). pub fn effects(&self) -> Vec> { @@ -638,6 +699,30 @@ impl<'f, 'a> Layer<'f, 'a> { #[cfg(test)] mod tests { use super::*; + use crate::Chunk; + + #[test] + fn a_parameter_definition_reads_its_fields_and_nothing_from_a_cut_record() { + let mut b = vec![0u8; 148]; + b[12..16].copy_from_slice(&7u32.to_be_bytes()); + b[16..22].copy_from_slice(b"Amount"); + b[56..64].copy_from_slice(&2.5f64.to_be_bytes()); + let p = Pard(&b); + assert_eq!((p.code(), p.name().as_deref()), (Some(7), Some("Amount"))); + assert_eq!(p.default(ParamKind::FloatSlider), Some(ParamValue::Number(2.5))); + // The same bytes as a checkbox and as a popup: the `u32` at 56, and the `u16` at 60. + b[56..60].copy_from_slice(&1u32.to_be_bytes()); + b[60..62].copy_from_slice(&3u16.to_be_bytes()); + let p = Pard(&b); + assert_eq!(p.default(ParamKind::Checkbox), Some(ParamValue::Bool(true))); + assert_eq!((p.default(ParamKind::Popup), p.popup_item_count()), (Some(ParamValue::Index(1)), Some(3))); + assert_eq!(p.default(ParamKind::IntSlider), Some(ParamValue::Number(1.0))); + // A record cut before a field has no value for it, and an unreadable code is `Other`. + let cut = Pard(&b[..12]); + assert_eq!((cut.code(), cut.kind(), cut.name(), cut.popup_item_count()), (None, ParamKind::Other(u32::MAX), None, None)); + assert_eq!(cut.default(ParamKind::FloatSlider), None); + assert_eq!(Pard(&b[..58]).default(ParamKind::Checkbox), None); + } fn tdmn(name: &str) -> Chunk<'static> { let mut b = name.as_bytes().to_vec(); @@ -670,11 +755,11 @@ mod tests { ("A".to_string(), Chunk::list(*b"tdbs", vec![Chunk::data(*b"cdat", vec![0u8; 8])])), ]; let chunk = instance(&names, &stored); - let fx = Effect { match_name: "X".into(), chunk: &chunk }; + let fx = Effect { match_name: "X".into(), chunk: Node::from(&chunk) }; let params = fx.params(); assert_eq!(params.iter().map(|p| p.match_name.as_str()).collect::>(), ["A", "B", "C"]); let first = params.first().and_then(|p| p.stored).expect("A stored"); - assert!(first.chunk.children().is_empty(), "the first A (the second has a cdat)"); + assert!(first.chunk.children().next().is_none(), "the first A (the second has a cdat)"); assert!(params.get(1).is_some_and(|p| p.stored.is_none()), "a group of that name is no stored value"); assert!(params.get(2).is_some_and(|p| p.stored.is_none())); } @@ -687,7 +772,7 @@ mod tests { let names: Vec = (0..n).map(|i| format!("P{i}")).collect(); let stored: Vec<(String, Chunk<'static>)> = names.iter().map(|m| (m.clone(), tdbs())).collect(); let chunk = instance(&names, &stored); - let fx = Effect { match_name: "X".into(), chunk: &chunk }; + let fx = Effect { match_name: "X".into(), chunk: Node::from(&chunk) }; let params = fx.params(); assert_eq!(params.len(), n); assert!(params.iter().all(|p| p.stored.is_some())); @@ -707,19 +792,19 @@ mod tests { } let efdg = Chunk::list(*b"EfdG", defs); let fold = Chunk::list(*b"Fold", Vec::new()); - let project = Project { fold: &fold, effect_defs: Some(&efdg) }; + let project = Project { fold: Node::from(&fold), effect_defs: Some(Node::from(&efdg)) }; let all = project.effect_definitions(); assert_eq!(all.len(), n); let index = project.effect_definition_index(); let bare = Chunk::list(*b"sspc", vec![Chunk::list(*b"parT", Vec::new())]); for i in (0..n).step_by(50) { - let fx = Effect { match_name: format!("FX{i}"), chunk: &bare }; + let fx = Effect { match_name: format!("FX{i}"), chunk: Node::from(&bare) }; assert_eq!(index.source(&fx), DefinitionSource::Project); let params = index.params(&fx); assert_eq!(params.iter().map(|p| p.match_name.as_str()).collect::>(), ["R0"], "the first copy's definitions"); assert!(params.iter().all(|p| p.borrowed_definition)); } - let unknown = Effect { match_name: "nope".into(), chunk: &bare }; + let unknown = Effect { match_name: "nope".into(), chunk: Node::from(&bare) }; assert_eq!(index.source(&unknown), DefinitionSource::Missing); assert!(index.params(&unknown).is_empty()); assert_eq!(project.definition_source(&unknown), DefinitionSource::Missing); diff --git a/crates/aep/src/footage.rs b/crates/aep/src/footage.rs index 58a653a4a..e8c89b924 100644 --- a/crates/aep/src/footage.rs +++ b/crates/aep/src/footage.rs @@ -2,8 +2,8 @@ //! of a layer's source. use crate::bytes::{be_f32, be_f64, be_i32, be_u32, cstr, le_u32, text, until_nul}; -use crate::chunk::Chunk; use crate::header::Rational; +use crate::index::Node; use crate::typed::{Item, ItemKind, Layer, Project}; /// The footage data of an item (`LIST Pin ` with `sspc`, `opti` and, for files, `Als2/alas`). @@ -101,21 +101,6 @@ impl PsdLayer { } impl Footage { - /// The number of frames of an image sequence (`duration * native_frame_rate`: 3/30 s at 30 fps is - /// 3); `None` for anything else. - pub fn sequence_frame_count(&self) -> Option { - if !self.is_sequence { - return None; - } - let d = self.duration?; - let frames = i128::from(d.num).checked_mul(i128::from(self.native_frame_rate))?; - let den = i128::from(d.den); - if den <= 0 || frames % den != 0 { - return None; - } - u32::try_from(frames / den).ok() - } - /// The solid's colour as fractions R, G, B. pub fn solid_rgb(&self) -> Option<[f32; 3]> { let [_, r, g, b] = self.solid_argb?; @@ -269,14 +254,14 @@ impl SequenceInfo { /// is unreadable (empty). A name that is not a plain file name (holding `/`, `\`, `:` or a control /// character such as NUL, or being `.` or `..`) makes the whole list unreadable (empty): the names /// are joined to the folder. -fn sequence_file_list(list: &Chunk<'_>) -> Vec { +fn sequence_file_list(list: Node<'_, '_>) -> Vec { // After Effects writes the count first (the one sample); a list without a readable count is // not read rather than guessed. let Some(count) = list.child(b"StVS").and_then(|c| c.bytes()).and_then(|b| le_u32(b, 0)).and_then(|n| usize::try_from(n).ok()) else { return Vec::new(); }; let names: Vec = - list.children().iter().filter(|c| c.is(b"Utf8")).filter_map(|c| c.bytes()).take(count).map(text).filter(|n| !n.is_empty()).collect(); + list.children().filter(|c| c.is(b"Utf8")).filter_map(Node::bytes).take(count).map(text).filter(|n| !n.is_empty()).collect(); if names.iter().any(|n| n.contains(|c: char| matches!(c, '/' | '\\' | ':') || c.is_control()) || n == "." || n == "..") { return Vec::new(); } @@ -308,9 +293,8 @@ impl<'f, 'a> Item<'f, 'a> { } let pin = self.chunk.child_list(b"Pin ")?; let sspc = pin.child(b"sspc")?.bytes()?; - let kids = pin.children(); - let after = kids.iter().position(|c| c.is_list(b"Als2"))?; - let naming = || kids.iter().skip(after.saturating_add(1)).take_while(|c| !c.is(b"opti")); + let after = pin.children().position(|c| c.is_list(b"Als2"))?; + let naming = || pin.children().skip(after.saturating_add(1)).take_while(|c| !c.is(b"opti")); let (start, end, digits) = (be_u32(sspc, 172)?, be_u32(sspc, 176)?, be_u32(sspc, 180)?); // Force alphabetical order: the file list replaces the numbering. if let Some(list) = naming().find(|c| c.is_list(b"StVc")) { @@ -320,7 +304,7 @@ impl<'f, 'a> Item<'f, 'a> { } return Some(SequenceInfo { prefix: String::new(), suffix: String::new(), start, end, digits, files }); } - let names: Vec = naming().filter(|c| c.is(b"Utf8")).filter_map(|c| c.bytes()).map(text).take(2).collect(); + let names: Vec = naming().filter(|c| c.is(b"Utf8")).filter_map(Node::bytes).map(text).take(2).collect(); let (prefix, suffix) = match names.as_slice() { [prefix, suffix] => (prefix.clone(), suffix.clone()), // An empty prefix is not stored (`0001.png` has only `.png`). @@ -350,12 +334,6 @@ impl<'f, 'a> Item<'f, 'a> { self.chunk.child(b"idta")?.bytes()?.get(58).copied() } - /// The ids of the compositions this item uses as precomp layers: the little-endian `u32` of - /// each `idpi` chunk. - pub fn used_item_ids(&self) -> Vec { - self.chunk.children().iter().filter(|c| c.is(b"idpi")).filter_map(|c| le_u32(c.bytes()?, 0)).collect() - } - /// The footage data of a footage item. pub fn footage(&self) -> Option { if self.kind()? != ItemKind::Footage { @@ -405,11 +383,6 @@ impl<'f, 'a> Project<'f, 'a> { self.item_by_id(layer.header()?.source_id?) } - /// The name a layer shows: its own name, or its source's name when it has none. - pub fn layer_display_name(&self, layer: &Layer<'f, 'a>) -> Option { - layer.name().or_else(|| self.layer_source(layer)?.display_name()) - } - /// The pixel size of a layer's source: a footage item's width and height, or a precomp's /// composition size. pub fn layer_source_size(&self, layer: &Layer<'f, 'a>) -> Option<(u32, u32)> { diff --git a/crates/aep/src/header.rs b/crates/aep/src/header.rs index 8593a5633..ac869095f 100644 --- a/crates/aep/src/header.rs +++ b/crates/aep/src/header.rs @@ -237,12 +237,6 @@ impl LayerHeader { self.flag_bytes.get(byte).is_some_and(|b| b & mask != 0) } - /// Byte 37 bit `0x01`: the layer has a name set by the user (clear on a default-named camera or - /// light and on a precomp layer, whose name is the source's). - pub fn name_is_user_set(&self) -> bool { - self.flag(0, 0x01) - } - /// Byte 37 bit `0x02`: guide layer. pub fn is_guide(&self) -> bool { self.flag(0, 0x02) @@ -333,17 +327,6 @@ impl LayerHeader { Rational::new(i64::from(self.stretch), i64::from(self.stretch_den)) } - /// The time stretch in percent (`stretch / stretch_den * 100`); a zero denominator reads as 1. - pub fn stretch_percent(&self) -> f64 { - let den = if self.stretch_den == 0 { 1.0 } else { f64::from(self.stretch_den) }; - f64::from(self.stretch) / den * 100.0 - } - - /// The start time in seconds, `None` for a zero denominator. - pub fn start_seconds(&self) -> Option { - self.start.to_f64() - } - /// The absolute in point, `start + in * stretch`, exact and reduced. pub fn in_point(&self) -> Option { self.start.plus_scaled(&self.in_relative, &self.stretch_ratio()?) @@ -355,16 +338,6 @@ impl LayerHeader { pub fn out_point(&self) -> Option { self.start.plus_scaled(&self.out_relative, &self.stretch_ratio()?) } - - /// The absolute in point in seconds. - pub fn in_point_seconds(&self) -> Option { - self.in_point()?.to_f64() - } - - /// The absolute out point in seconds. - pub fn out_point_seconds(&self) -> Option { - self.out_point()?.to_f64() - } } impl<'f, 'a> Layer<'f, 'a> { @@ -464,64 +437,10 @@ impl CompHeader { self.time_base.frame_rate() } - /// The frame rate from the 16.16 fixed-point field (25 is `0x0019_0000`). - pub fn frame_rate_from_fixed(&self) -> f64 { - f64::from(self.frame_rate_fixed) / 65536.0 - } - /// The duration in seconds. pub fn duration_seconds(&self) -> Option { self.time_base.seconds(i32::try_from(self.duration_units).ok()?) } - - /// The work area start in seconds. - pub fn work_area_start_seconds(&self) -> Option { - self.time_base.seconds(i32::try_from(self.work_area_start_units).ok()?) - } - - /// The work area end in seconds; the composition duration when the work area is the whole - /// composition. - pub fn work_area_end_seconds(&self) -> Option { - match self.work_area_end_units { - Some(end) => self.time_base.seconds(i32::try_from(end).ok()?), - None => self.duration_seconds(), - } - } - - /// The background colour as fractions 0..1 (`byte / 255`). - pub fn background_rgb(&self) -> [f64; 3] { - self.background.map(|c| f64::from(c) / 255.0) - } - - /// The pixel aspect ratio as a number. - pub fn pixel_aspect_ratio(&self) -> Option { - self.pixel_aspect.to_f64() - } - - /// The display start time in seconds (the start timecode), `None` when absent or the - /// denominator is zero. - pub fn display_start_seconds(&self) -> Option { - self.display_start?.to_f64() - } - - /// The display start as a frame number (`display start * frame rate`, rounded); 100 at 25 fps - /// for a display start of 4 s. - pub fn display_start_frame(&self) -> Option { - let rate = self.frame_rate()?; - Some((self.display_start_seconds()? * rate).round() as i64) - } - - /// The frame rate as an exact fraction `timescale / frame_duration`, as typed: 29.97 fps is - /// `23976 / 800` (not `30000 / 1001`), 23.976 fps is `23976 / 1000`. - pub fn frame_rate_exact(&self) -> Option { - Rational::new(i64::from(self.time_base.timescale), i64::from(self.time_base.frame_duration)) - } - - /// The duration in whole frames (`duration / frame_duration`). After Effects snaps a duration - /// to a whole number of frames: 5 s at 29.97 fps becomes 150 frames (5.005 s). - pub fn duration_frames(&self) -> Option { - self.duration_units.checked_div(self.time_base.frame_duration) - } } impl<'f, 'a> Comp<'f, 'a> { diff --git a/crates/aep/src/index.rs b/crates/aep/src/index.rs new file mode 100644 index 000000000..76d5430da --- /dev/null +++ b/crates/aep/src/index.rs @@ -0,0 +1,1026 @@ +//! A read-only, flat index of the chunk tree for readers that only look (the importer). +//! +//! [`TreeIndex`] holds every chunk of a file in one `Vec` in depth-first order (a chunk, then its +//! whole subtree, then its next sibling). Each entry keeps its id, list type, pad byte, the bytes of +//! its body (borrowed from the input) and the index one past its subtree, so: +//! - a chunk's subtree is the index range `at + 1 .. end`, +//! - its direct children are found by stepping from `at + 1` to each child's `end`, +//! - the whole tree is one array, grown a few times while it is built and freed at once; it never +//! holds more slots than the input has room for chunk headers or the chunk limit allows. +//! +//! [`crate::parse`] builds the owned [`Chunk`] tree instead (one `Vec` per list), which +//! the exporter and editors need. [`TreeIndex::to_file`] and [`Node::to_chunk`] convert the index +//! into that tree where an owned one is needed. +//! +//! [`TreeIndex::parse_with_limits`] walks the input exactly as the [`Chunk`] parser does: the same +//! chunks are counted against [`Limits::max_chunks`] in the same order, the same lists are kept +//! opaque at [`Limits::max_depth`] or when damaged, and the same errors come back. A test compares +//! the two on the corpus and on generated and damaged trees. Two errors are its own, and both are +//! stricter than the [`Chunk`] parser (which would abort or could not address the tree): +//! [`AepError::TooLarge`] when the array cannot grow (a failed `try_reserve`), and +//! [`AepError::TooManyChunks`] for a tree of more than `u32::MAX` chunks. +//! +//! An `.aepx` is indexed by its own reader (`container/aepx.rs`), which decodes every body into +//! one buffer and fills the entries as it reads; the index then borrows that buffer +//! (`TreeIndex::from_drafts`). It gives the tree [`crate::read_aepx`] gives. +//! +//! [`Node`] is the handle the typed view ([`crate::Project`] and the types below it) +//! reads through: a chunk of either tree. The view works the same on both. + +use std::borrow::Cow; +use std::fmt; + +use crate::bytes::be_u32; +use crate::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk}; +use crate::error::AepError; +use crate::read::{Limits, container_end, id4}; + +/// What an entry's body is (the [`Body`] variants). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Kind { + Data, + /// [`Body::Chunks`]. + Nested, + List, + OpaqueList, +} + +/// One chunk of a [`TreeIndex`]. +#[derive(Debug, Clone, Copy)] +struct Entry<'a> { + /// The body bytes of a data chunk, or the bytes after the list type of an opaque list; empty + /// for a list or nested chunk (their content is their children). + data: &'a [u8], + id: [u8; 4], + /// The list type of a `LIST` (parsed or opaque); zero otherwise. + list_type: [u8; 4], + /// One past the last entry of this chunk's subtree. + end: u32, + kind: Kind, + pad: Option, +} + +impl<'a> Entry<'a> { + /// An entry for a chunk whose body is not read yet. + fn placeholder(id: [u8; 4]) -> Self { + Self { data: &[], id, list_type: [0; 4], end: 0, kind: Kind::Data, pad: None } + } +} + +/// An entry of an index whose bytes are still being written (the `.aepx` reader decodes into a +/// buffer that grows, so it keeps positions, not slices): the body is `start..start + len` of +/// that buffer. The fields are those of [`Entry`]; [`TreeIndex::from_drafts`] turns the list +/// into an index once the buffer is final. +#[derive(Debug, Clone, Copy)] +pub struct Draft { + pub(crate) start: usize, + pub(crate) len: usize, + pub(crate) id: [u8; 4], + pub(crate) list_type: [u8; 4], + pub(crate) end: u32, + pub(crate) kind: Kind, + pub(crate) pad: Option, +} + +impl Draft { + /// A data chunk with no body yet. + pub(crate) fn placeholder(id: [u8; 4]) -> Self { + Self { start: 0, len: 0, id, list_type: [0; 4], end: 0, kind: Kind::Data, pad: None } + } +} + +/// The chunk tree of a file as one flat, read-only array (see the module documentation). +#[derive(Clone)] +pub struct TreeIndex<'a> { + nodes: Vec>, + trailer: &'a [u8], +} + +impl fmt::Debug for TreeIndex<'_> { + /// The sizes only: the chunk count and the trailer length. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TreeIndex").field("chunks", &self.nodes.len()).field("trailer", &self.trailer.len()).finish() + } +} + +/// An index that does not fit a `u32` (more than 4 billion chunks) is refused as too many chunks. +fn index_u32(at: usize) -> Result { + u32::try_from(at).map_err(|_| AepError::TooManyChunks) +} + +impl<'a> TreeIndex<'a> { + /// Indexes an `.aep` with the default [`Limits`]. + /// + /// # Errors + /// The errors of [`crate::parse`], for the same inputs. + pub fn parse(data: &'a [u8]) -> Result { + Self::parse_with_limits(data, Limits::default()) + } + + /// Indexes an `.aep` with explicit [`Limits`]. + /// + /// # Errors + /// The errors of [`crate::parse_with_limits`], for the same inputs and limits; also + /// [`AepError::TooManyChunks`] for a tree of more than `u32::MAX` chunks and + /// [`AepError::TooLarge`] when the array cannot be allocated. + pub fn parse_with_limits(data: &'a [u8], limits: Limits) -> Result { + let end = container_end(data)?; + // Every chunk header takes 8 bytes of its own and is counted once, so the tree never has + // more chunks than this. + let bound = (end.saturating_sub(12) / 8).min(limits.max_chunks); + let mut builder = Builder { data, limits, count: 0, nodes: Vec::new(), bound }; + // A small start; [`Builder::push`] doubles it as chunks arrive, never past the bound, so + // the array stays proportional to the chunk count (a file of a few large chunks gets a few + // slots, not one per 32 bytes). `try_reserve_exact` so it fails nothing here. + let _ = builder.nodes.try_reserve_exact(bound.min(INITIAL_SLOTS)); + builder.sequence(12, end, 1)?; + let trailer = data.get(end..).unwrap_or(&[]); + Ok(Self { nodes: builder.nodes, trailer }) + } + + /// The index of the entries `drafts` (in depth-first order, see [`Draft`]) whose bodies and + /// trailer are ranges of `buffer`. A range outside `buffer` reads as empty. The list is turned + /// into entries; a [`Draft`] and an [`Entry`] have the same size and alignment, so the standard + /// library reuses the list's allocation for them. + pub fn from_drafts(buffer: &'a [u8], drafts: Vec, trailer: (usize, usize)) -> Self { + let slice = |start: usize, len: usize| start.checked_add(len).and_then(|end| buffer.get(start..end)).unwrap_or(&[]); + let nodes = drafts + .into_iter() + .map(|d| Entry { data: slice(d.start, d.len), id: d.id, list_type: d.list_type, end: d.end, kind: d.kind, pad: d.pad }) + .collect(); + let trailer = buffer.get(trailer.0..trailer.1).unwrap_or(&[]); + Self { nodes, trailer } + } + + /// Indexes an already parsed (or built) chunk tree. The index borrows the file's bytes. + /// + /// # Errors + /// [`AepError::TooManyChunks`] for a tree of more than `u32::MAX` chunks. + pub fn from_file(file: &'a AepFile<'_>) -> Result { + // Sized once, to the chunks the tree holds. + let mut nodes: Vec> = Vec::new(); + nodes.try_reserve_exact(file.walk().count()).map_err(|_| AepError::TooLarge)?; + // Each frame: the siblings still to visit and the entry whose subtree they fill. + let mut stack: Vec<(std::slice::Iter<'a, Chunk<'_>>, Option)> = vec![(file.chunks.iter(), None)]; + while let Some((iter, parent)) = stack.last_mut() { + let parent = *parent; + match iter.next() { + Some(chunk) => { + let at = nodes.len(); + // The entry after this one must still have a `u32` index. + let next = index_u32(at.checked_add(1).ok_or(AepError::TooManyChunks)?)?; + let (kind, data, list_type) = match &chunk.body { + Body::Data(d) => (Kind::Data, &d[..], [0; 4]), + Body::Chunks(_) => (Kind::Nested, &[][..], [0; 4]), + Body::List { list_type, .. } => (Kind::List, &[][..], *list_type), + Body::OpaqueList { list_type, data } => (Kind::OpaqueList, &data[..], *list_type), + }; + nodes.push(Entry { data, id: chunk.id, list_type, end: next, kind, pad: chunk.pad }); + let kids = chunk.children(); + if !kids.is_empty() { + stack.push((kids.iter(), Some(at))); + } + } + None => { + stack.pop(); + if let Some(p) = parent { + let end = index_u32(nodes.len())?; + if let Some(e) = nodes.get_mut(p) { + e.end = end; + } + } + } + } + } + Ok(Self { nodes, trailer: &file.trailer[..] }) + } + + /// The number of chunks in the tree (at every depth). + pub fn len(&self) -> usize { + self.nodes.len() + } + + /// True when the container holds no chunks. + pub fn is_empty(&self) -> bool { + self.nodes.is_empty() + } + + /// The bytes after the container's declared end (see [`AepFile::trailer`]). + pub fn trailer(&self) -> &'a [u8] { + self.trailer + } + + /// The top-level chunks. + pub fn chunks(&self) -> Nodes<'_, 'a> { + Nodes(NodesRepr::Index { tree: self, next: 0, end: u32::try_from(self.nodes.len()).unwrap_or(u32::MAX) }) + } + + /// The first top-level chunk with this id. + pub fn chunk(&self, id: &[u8; 4]) -> Option> { + self.chunks().find(|c| c.is(id)) + } + + /// The first top-level `LIST` of this type. + pub fn list(&self, list_type: &[u8; 4]) -> Option> { + self.chunks().find(|c| c.is_list(list_type)) + } + + /// Visits every chunk depth-first with its nesting depth (the top level is 1), as + /// [`AepFile::walk`] does. + pub fn walk(&self) -> NodeWalk<'_, 'a> { + NodeWalk(WalkRepr::Index { tree: self, next: 0, end: u32::try_from(self.nodes.len()).unwrap_or(u32::MAX), open: Vec::new() }) + } + + /// The owned chunk tree (the bodies stay borrowed from the input): what + /// [`crate::parse`] gives for the same file. + pub fn to_file(&self) -> AepFile<'a> { + AepFile { chunks: self.build(0, u32::try_from(self.nodes.len()).unwrap_or(u32::MAX)), trailer: Cow::Borrowed(self.trailer) } + } + + /// The entry at `at`, `None` past the end. + fn entry(&self, at: u32) -> Option<&Entry<'a>> { + self.nodes.get(usize::try_from(at).ok()?) + } + + /// The end of the subtree at `at`; never before `at + 1`, so walks always move on. + fn end_of(&self, at: u32) -> u32 { + self.entry(at).map_or(u32::MAX, |e| e.end).max(at.saturating_add(1)) + } + + /// The owned chunks for the siblings that start at `next` and fill `next..end`, without + /// recursion. + fn build(&self, next: u32, end: u32) -> Vec> { + struct Frame<'a> { + /// The list or nested chunk being filled; `None` for the outermost range. + at: Option, + kids: Vec>, + next: u32, + end: u32, + } + let mut stack = vec![Frame { at: None, kids: Vec::new(), next, end }]; + loop { + let Some(top) = stack.last_mut() else { return Vec::new() }; + if top.next < top.end { + let at = top.next; + top.next = self.end_of(at); + let Some(e) = self.entry(at).copied() else { + top.next = top.end; + continue; + }; + match e.kind { + Kind::List | Kind::Nested => { + let sub_end = self.end_of(at); + stack.push(Frame { at: Some(at), kids: Vec::new(), next: at.saturating_add(1), end: sub_end }); + } + Kind::Data => top.kids.push(Chunk { id: e.id, body: Body::Data(Cow::Borrowed(e.data)), pad: e.pad }), + Kind::OpaqueList => { + top.kids.push(Chunk { id: e.id, body: Body::OpaqueList { list_type: e.list_type, data: Cow::Borrowed(e.data) }, pad: e.pad }); + } + } + } else { + let Some(frame) = stack.pop() else { return Vec::new() }; + let Some(at) = frame.at else { return frame.kids }; + let Some(e) = self.entry(at).copied() else { continue }; + let body = match e.kind { + Kind::Nested => Body::Chunks(frame.kids), + Kind::List | Kind::Data | Kind::OpaqueList => Body::List { list_type: e.list_type, children: frame.kids }, + }; + let chunk = Chunk { id: e.id, body, pad: e.pad }; + match stack.last_mut() { + Some(parent) => parent.kids.push(chunk), + None => return vec![chunk], + } + } + } + } +} + +/// The slots a [`TreeIndex`] starts with (32 KiB); it doubles from there. +const INITIAL_SLOTS: usize = 1024; + +/// Builds a [`TreeIndex`]; mirrors `read::Parser` step for step (see the module documentation). +struct Builder<'a> { + data: &'a [u8], + limits: Limits, + count: usize, + nodes: Vec>, + /// The most chunks the input can hold under the limits: `nodes` never reserves past it. + bound: usize, +} + +impl<'a> Builder<'a> { + /// Appends an entry. A full array grows by its length (at least 16), but never past + /// [`Self::bound`]; an allocation the target cannot make is an error, not an abort. + fn push(&mut self, entry: Entry<'a>) -> Result<(), AepError> { + let len = self.nodes.len(); + if len == self.nodes.capacity() { + let more = len.max(16).min(self.bound.saturating_sub(len)).max(1); + self.nodes.try_reserve_exact(more).map_err(|_| AepError::TooLarge)?; + } + self.nodes.push(entry); + Ok(()) + } + + /// Appends the sibling chunks that exactly fill `start..end`, each followed by its subtree. + fn sequence(&mut self, start: usize, end: usize, depth: usize) -> Result<(), AepError> { + let mut pos = start; + while pos < end { + let short = AepError::Malformed { offset: pos, what: "bytes left over that are too short for a chunk header" }; + let body_start = pos.checked_add(8).filter(|b| *b <= end).ok_or(short)?; + let id = id4(self.data, pos).ok_or(AepError::Malformed { offset: pos, what: "short read" })?; + let size = be_u32(self.data, pos + 4).ok_or(AepError::Malformed { offset: pos, what: "short read" })? as usize; + let avail = end - body_start; + if size > avail { + return Err(AepError::ChunkTooLarge { offset: pos, size: size as u64, available: avail as u64 }); + } + self.count = self.count.saturating_add(1); + if self.count > self.limits.max_chunks { + return Err(AepError::TooManyChunks); + } + let at = self.nodes.len(); + // This entry and the one after it must have `u32` indices. + index_u32(at.checked_add(1).ok_or(AepError::TooManyChunks)?)?; + self.push(Entry::placeholder(id))?; + let body_end = body_start + size; + self.body(at, id, body_start, body_end, depth)?; + let mut next = body_end; + let mut pad = None; + if size % 2 == 1 && next < end { + pad = Some(self.data.get(next).copied().ok_or(AepError::Malformed { offset: next, what: "missing pad byte" })?); + next += 1; + } + let subtree_end = index_u32(self.nodes.len())?; + if let Some(e) = self.nodes.get_mut(at) { + e.pad = pad; + e.end = subtree_end; + } + pos = next; + } + Ok(()) + } + + /// Like [`Self::sequence`] but a structural problem yields `false` and removes what the + /// attempt appended (the caller keeps bytes). The chunk count keeps the attempt's chunks, as + /// the [`Chunk`] parser's does. + fn tentative(&mut self, start: usize, end: usize, depth: usize) -> Result { + let mark = self.nodes.len(); + match self.sequence(start, end, depth) { + Ok(()) => Ok(true), + Err(e) if e.is_structural() => { + self.nodes.truncate(mark); + Ok(false) + } + Err(e) => Err(e), + } + } + + /// The input bytes `start..end` (empty when out of range). + fn slice(&self, start: usize, end: usize) -> &'a [u8] { + self.data.get(start..end).unwrap_or(&[]) + } + + /// Fills in the body of the entry at `at` once the parser knows what it is. + fn set(&mut self, at: usize, kind: Kind, data: &'a [u8], list_type: [u8; 4]) { + if let Some(e) = self.nodes.get_mut(at) { + e.kind = kind; + e.data = data; + e.list_type = list_type; + } + } + + /// Fills in the entry at `at` for the body `start..end` and appends its subtree. + fn body(&mut self, at: usize, id: [u8; 4], start: usize, end: usize, depth: usize) -> Result<(), AepError> { + let len = end - start; + if id == LIST && len >= 4 { + let list_type = id4(self.data, start).ok_or(AepError::Malformed { offset: start, what: "short read" })?; + if depth < self.limits.max_depth && self.tentative(start + 4, end, depth + 1)? { + self.set(at, Kind::List, &[], list_type); + } else { + let data = self.slice(start + 4, end); + self.set(at, Kind::OpaqueList, data, list_type); + } + return Ok(()); + } + if NESTED_IDS.contains(&id) && len >= 8 && depth < self.limits.max_depth { + let mark = self.nodes.len(); + if self.tentative(start, end, depth + 1)? && self.nodes.len() > mark { + self.set(at, Kind::Nested, &[], [0; 4]); + return Ok(()); + } + } + let data = self.slice(start, end); + self.set(at, Kind::Data, data, [0; 4]); + Ok(()) + } +} + +/// A chunk of either tree: an owned [`Chunk`] or an entry of a [`TreeIndex`]. The typed view +/// reads through it, so it works the same on both. Cheap to copy. +#[derive(Clone, Copy)] +pub struct Node<'f, 'a>(NodeRepr<'f, 'a>); + +#[derive(Clone, Copy)] +enum NodeRepr<'f, 'a> { + Chunk(&'f Chunk<'a>), + Index(&'f TreeIndex<'a>, u32), +} + +impl<'f, 'a> From<&'f Chunk<'a>> for Node<'f, 'a> { + /// The handle for this value. + fn from(chunk: &'f Chunk<'a>) -> Self { + Node(NodeRepr::Chunk(chunk)) + } +} + +/// Prints the chunk as [`Chunk`]'s `Debug` does, whichever tree it is in, without copying the +/// subtree. +impl fmt::Debug for Node<'_, '_> { + /// The chunk as `Chunk`'s `Debug` prints it. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + NodeRepr::Chunk(c) => fmt::Debug::fmt(c, f), + NodeRepr::Index(..) => { + f.debug_struct("Chunk").field("id", &self.id()).field("body", &BodyDebug(*self)).field("pad", &self.pad()).finish() + } + } + } +} + +/// The body of an index [`Node`], printed as [`Body`]'s `Debug` prints it. +struct BodyDebug<'f, 'a>(Node<'f, 'a>); + +/// The children of a [`Node`], printed as a list. +struct ChildrenDebug<'f, 'a>(Node<'f, 'a>); + +impl fmt::Debug for BodyDebug<'_, '_> { + /// The body as `Body`'s `Debug` prints it. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Some(e) = self.0.entry() else { return f.write_str("?") }; + match e.kind { + Kind::Data => f.debug_tuple("Data").field(&e.data).finish(), + Kind::Nested => f.debug_tuple("Chunks").field(&ChildrenDebug(self.0)).finish(), + Kind::List => f.debug_struct("List").field("list_type", &e.list_type).field("children", &ChildrenDebug(self.0)).finish(), + Kind::OpaqueList => f.debug_struct("OpaqueList").field("list_type", &e.list_type).field("data", &e.data).finish(), + } + } +} + +impl fmt::Debug for ChildrenDebug<'_, '_> { + /// The children as a list. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.0.children()).finish() + } +} + +impl<'f, 'a> Node<'f, 'a> { + /// The entry at `at`, `None` past the end. + fn entry(self) -> Option<&'f Entry<'a>> { + match self.0 { + NodeRepr::Index(tree, at) => tree.entry(at), + NodeRepr::Chunk(_) => None, + } + } + + /// The [`Chunk`] when this node is one of an owned tree; `None` for an index entry (see + /// [`Self::to_chunk`]). + pub fn as_chunk(self) -> Option<&'f Chunk<'a>> { + match self.0 { + NodeRepr::Chunk(c) => Some(c), + NodeRepr::Index(..) => None, + } + } + + /// The chunk and its subtree as an owned [`Chunk`] (bodies stay borrowed). + pub fn to_chunk(self) -> Chunk<'a> { + match self.0 { + NodeRepr::Chunk(c) => c.clone(), + NodeRepr::Index(tree, at) => tree.build(at, tree.end_of(at)).into_iter().next().unwrap_or_else(|| Chunk::data(self.id(), &[][..])), + } + } + + /// The 4-byte id (see [`Chunk::id`]). + pub fn id(self) -> [u8; 4] { + match self.0 { + NodeRepr::Chunk(c) => c.id, + NodeRepr::Index(..) => self.entry().map_or([0; 4], |e| e.id), + } + } + + /// The pad byte (see [`Chunk::pad`]). + pub fn pad(self) -> Option { + match self.0 { + NodeRepr::Chunk(c) => c.pad, + NodeRepr::Index(..) => self.entry().and_then(|e| e.pad), + } + } + + /// The raw bytes of a data chunk, or the bytes after the list type of an opaque list (see + /// [`Chunk::bytes`]). + pub fn bytes(self) -> Option<&'f [u8]> { + match self.0 { + NodeRepr::Chunk(c) => c.bytes(), + NodeRepr::Index(..) => self.entry().filter(|e| matches!(e.kind, Kind::Data | Kind::OpaqueList)).map(|e| e.data), + } + } + + /// The child chunks of a list or nested chunk; none for data. + pub fn children(self) -> Nodes<'f, 'a> { + match self.0 { + NodeRepr::Chunk(c) => Nodes(NodesRepr::Slice(c.children().iter())), + NodeRepr::Index(tree, at) => { + let end = match tree.entry(at) { + Some(e) if matches!(e.kind, Kind::List | Kind::Nested) => tree.end_of(at), + _ => at.saturating_add(1), + }; + Nodes(NodesRepr::Index { tree, next: at.saturating_add(1), end }) + } + } + } + + /// The list type when this is a `LIST` (parsed or opaque). + pub fn list_type(self) -> Option<[u8; 4]> { + match self.0 { + NodeRepr::Chunk(c) => c.list_type(), + NodeRepr::Index(..) => self.entry().filter(|e| matches!(e.kind, Kind::List | Kind::OpaqueList)).map(|e| e.list_type), + } + } + + /// True when this is a `LIST` of the given type. + pub fn is_list(self, list_type: &[u8; 4]) -> bool { + match self.0 { + NodeRepr::Chunk(c) => c.is_list(list_type), + NodeRepr::Index(..) => { + self.entry().is_some_and(|e| e.id == LIST && matches!(e.kind, Kind::List | Kind::OpaqueList) && &e.list_type == list_type) + } + } + } + + /// True when this is a `LIST` whose content could not be read as chunks. + pub fn is_opaque_list(self) -> bool { + match self.0 { + NodeRepr::Chunk(c) => c.is_opaque_list(), + NodeRepr::Index(..) => self.entry().is_some_and(|e| e.kind == Kind::OpaqueList), + } + } + + /// True when this chunk has the given id. + pub fn is(self, id: &[u8; 4]) -> bool { + self.id() == *id + } + + /// The first child chunk with this id. + pub fn child(self, id: &[u8; 4]) -> Option { + self.children().find(|c| c.is(id)) + } + + /// The first child `LIST` of this type. + pub fn child_list(self, list_type: &[u8; 4]) -> Option { + self.children().find(|c| c.is_list(list_type)) + } + + /// Every chunk below this one depth-first (children before later siblings), with the depth + /// counted from 1 for the children of this chunk. + pub fn descendants(self) -> NodeWalk<'f, 'a> { + match self.0 { + NodeRepr::Chunk(c) => NodeWalk(WalkRepr::Chunk(c.descendants())), + NodeRepr::Index(tree, at) => { + let end = match tree.entry(at) { + Some(e) if matches!(e.kind, Kind::List | Kind::Nested) => tree.end_of(at), + _ => at.saturating_add(1), + }; + NodeWalk(WalkRepr::Index { tree, next: at.saturating_add(1), end, open: Vec::new() }) + } + } + } + + /// The first descendant `LIST` of this type, searching depth-first. + pub fn find_list(self, list_type: &[u8; 4]) -> Option { + match self.0 { + NodeRepr::Chunk(c) => c.find_list(list_type).map(Node::from), + // The subtree is a contiguous range in depth-first order: a plain scan. + NodeRepr::Index(tree, at) => { + let first = usize::try_from(at).ok()?.checked_add(1)?; + let end = usize::try_from(tree.end_of(at)).ok()?.min(tree.nodes.len()); + let range = tree.nodes.get(first..end)?; + let i = range.iter().position(|e| e.id == LIST && matches!(e.kind, Kind::List | Kind::OpaqueList) && &e.list_type == list_type)?; + let found = u32::try_from(first.checked_add(i)?).ok()?; + Some(Node(NodeRepr::Index(tree, found))) + } + } + } +} + +/// The children of a [`Node`] (or the top-level chunks of a [`TreeIndex`]), in file order. +#[derive(Clone)] +pub struct Nodes<'f, 'a>(NodesRepr<'f, 'a>); + +#[derive(Clone)] +enum NodesRepr<'f, 'a> { + Slice(std::slice::Iter<'f, Chunk<'a>>), + Index { tree: &'f TreeIndex<'a>, next: u32, end: u32 }, +} + +impl<'f, 'a> Iterator for Nodes<'f, 'a> { + type Item = Node<'f, 'a>; + + /// The next item, `None` at the end of the range. + fn next(&mut self) -> Option { + match &mut self.0 { + NodesRepr::Slice(it) => it.next().map(Node::from), + NodesRepr::Index { tree, next, end } => { + if *next >= *end { + return None; + } + let (tree, at) = (*tree, *next); + tree.entry(at)?; + *next = tree.end_of(at); + Some(Node(NodeRepr::Index(tree, at))) + } + } + } +} + +/// A depth-first walk over [`Node`]s with their depth; see [`Node::descendants`] and +/// [`TreeIndex::walk`]. +pub struct NodeWalk<'f, 'a>(WalkRepr<'f, 'a>); + +enum WalkRepr<'f, 'a> { + Chunk(Walk<'f, 'a>), + /// `open` holds the subtree ends of the entries above the next one (its ancestors inside the + /// walked range); their count is the next entry's depth minus one. + Index { + tree: &'f TreeIndex<'a>, + next: u32, + end: u32, + open: Vec, + }, +} + +impl<'f, 'a> Iterator for NodeWalk<'f, 'a> { + type Item = (usize, Node<'f, 'a>); + + /// The next item, `None` at the end of the range. + fn next(&mut self) -> Option { + match &mut self.0 { + WalkRepr::Chunk(w) => w.next().map(|(d, c)| (d, Node::from(c))), + WalkRepr::Index { tree, next, end, open } => { + if *next >= *end { + return None; + } + let (tree, at) = (*tree, *next); + tree.entry(at)?; + while open.last().is_some_and(|e| *e <= at) { + open.pop(); + } + let depth = open.len().saturating_add(1); + let sub_end = tree.end_of(at); + if sub_end > at.saturating_add(1) { + open.push(sub_end); + } + *next = at.saturating_add(1); + Some((depth, Node(NodeRepr::Index(tree, at)))) + } + } + } +} + +/// The top level of either tree: what the project settings and the version are read from. +#[derive(Clone, Copy)] +pub enum Root<'f, 'a> { + File(&'f AepFile<'a>), + Index(&'f TreeIndex<'a>), +} + +impl<'f, 'a> From<&'f AepFile<'a>> for Root<'f, 'a> { + /// The handle for this value. + fn from(file: &'f AepFile<'a>) -> Self { + Root::File(file) + } +} + +impl<'f, 'a> From<&'f TreeIndex<'a>> for Root<'f, 'a> { + /// The handle for this value. + fn from(index: &'f TreeIndex<'a>) -> Self { + Root::Index(index) + } +} + +impl<'f, 'a> Root<'f, 'a> { + /// The top-level chunks. + pub fn chunks(self) -> Nodes<'f, 'a> { + match self { + Root::File(f) => Nodes(NodesRepr::Slice(f.chunks.iter())), + Root::Index(t) => t.chunks(), + } + } + + /// The first top-level chunk with this id. + pub fn chunk(self, id: &[u8; 4]) -> Option> { + self.chunks().find(|c| c.is(id)) + } + + /// The first top-level `LIST` of this type. + pub fn list(self, list_type: &[u8; 4]) -> Option> { + self.chunks().find(|c| c.is_list(list_type)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{parse_with_limits, write}; + + /// A tiny deterministic generator (xorshift64*), so the tests need no extra crate. + struct Rng(u64); + + impl Rng { + /// The next pseudo-random number (xorshift64*). + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + + /// A number below `n` (0 for `n == 0`). + fn below(&mut self, n: u64) -> u64 { + if n == 0 { 0 } else { self.next() % n } + } + } + + /// A random tree: lists, nested-id chunks holding a `Utf8`, data of odd and even sizes, opaque + /// lists, empty lists, deep chains. + fn tree(rng: &mut Rng, depth: usize, budget: &mut usize) -> Vec> { + let n = rng.below(6); + let mut out = Vec::new(); + for _ in 0..n { + if *budget == 0 { + break; + } + *budget -= 1; + let pick = rng.below(10); + let chunk = if depth < 12 && pick < 4 { + let types: [&[u8; 4]; 4] = [b"Fold", b"tdgp", b"tdbs", b"Layr"]; + let t = *types[usize::try_from(rng.below(4)).expect("small")]; + Chunk::list(t, tree(rng, depth + 1, budget)) + } else if pick == 4 { + let ids: [&[u8; 4]; 3] = [b"tdsn", b"pdnm", b"fnam"]; + let id = *ids[usize::try_from(rng.below(3)).expect("small")]; + let text = vec![b'a'; usize::try_from(rng.below(5)).expect("small")]; + Chunk { id, body: Body::Chunks(vec![Chunk::data(*b"Utf8", text)]), pad: None } + } else if pick == 5 { + let raw = vec![0x5a; usize::try_from(rng.below(9)).expect("small")]; + Chunk { id: LIST, body: Body::OpaqueList { list_type: *b"btdk", data: raw.into() }, pad: None } + } else { + let ids: [&[u8; 4]; 4] = [b"cdat", b"tdmn", b"Utf8", b"idta"]; + let id = *ids[usize::try_from(rng.below(4)).expect("small")]; + Chunk::data(id, vec![u8::try_from(rng.below(256)).expect("byte"); usize::try_from(rng.below(13)).expect("small")]) + }; + out.push(chunk); + } + out + } + + /// Both readers on the same bytes and limits: the same result, errors included; and the + /// index's walk visits the same chunks at the same depths as the tree's. + fn same(bytes: &[u8], limits: Limits) { + let old = parse_with_limits(bytes, limits); + let new = TreeIndex::parse_with_limits(bytes, limits); + match (&old, &new) { + (Ok(file), Ok(index)) => { + assert_eq!(&index.to_file(), file, "the index converts to the parsed tree"); + let a: Vec<(usize, Chunk<'_>)> = file.walk().map(|(d, c)| (d, c.clone())).collect(); + let b: Vec<(usize, Chunk<'_>)> = index.walk().map(|(d, n)| (d, n.to_chunk())).collect(); + assert_eq!(a, b, "the walks agree"); + assert_eq!(index.len(), a.len()); + // Indexing the parsed tree gives the same index. + let again = TreeIndex::from_file(file).expect("index"); + assert_eq!(again.to_file(), *file); + } + (Err(a), Err(b)) => assert_eq!(a, b, "the same error"), + _ => panic!("one reader failed: {:?} vs {:?}", old.as_ref().err(), new.as_ref().err()), + } + } + + /// The default limits and four tight ones (depth 1 and 3, 7 and 40 chunks). + fn limits() -> [Limits; 5] { + [ + Limits::default(), + Limits { max_depth: 1, max_chunks: 10_000_000 }, + Limits { max_depth: 3, max_chunks: 10_000_000 }, + Limits { max_depth: 64, max_chunks: 7 }, + Limits { max_depth: 64, max_chunks: 40 }, + ] + } + + /// The index matches the chunk parser on generated and damaged trees. + #[test] + fn the_index_matches_the_chunk_parser_on_generated_and_damaged_trees() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for _ in 0..400 { + let mut budget = 120; + let chunks = tree(&mut rng, 0, &mut budget); + let file = AepFile { chunks, trailer: Cow::Borrowed(b"x") }; + let bytes = write(&file).expect("write"); + for l in limits() { + same(&bytes, l); + } + // Damage: overwrite a few bytes past the container header (sizes, ids, list types). + for _ in 0..4 { + let mut bad = bytes.clone(); + for _ in 0..1 + rng.below(3) { + let at = 12 + usize::try_from(rng.below(u64::try_from(bad.len().saturating_sub(12)).expect("len"))).expect("index"); + if let Some(b) = bad.get_mut(at) { + *b = u8::try_from(rng.below(256)).expect("byte"); + } + } + for l in limits() { + same(&bad, l); + } + } + // Truncated inputs (the container size then no longer fits). + let cut = bytes.len().saturating_sub(usize::try_from(rng.below(8)).expect("small") + 1); + same(&bytes[..cut], Limits::default()); + } + } + + /// Header errors are the same. + #[test] + fn header_errors_are_the_same() { + for bytes in + [&b""[..], b"RIFX", b"RIFX\0\0\0\x04Egg", b"RIFX\0\0\0\x04Fnord", b"RIFX\0\0\0\x08Egg!", b"RIFX\0\0\0\x03Egg!", b"RIFF\0\0\0\x04Egg!"] + { + same(bytes, Limits::default()); + } + } + + /// The typed accessors give the same answers through either tree. + #[test] + fn nodes_answer_alike_on_both_trees() { + let mut rng = Rng(42); + for _ in 0..100 { + let mut budget = 200; + let file = AepFile { chunks: tree(&mut rng, 0, &mut budget), trailer: Cow::Borrowed(&[]) }; + let bytes = write(&file).expect("write"); + let parsed = crate::parse(&bytes).expect("parse"); + let index = TreeIndex::parse(&bytes).expect("index"); + let a: Vec> = parsed.walk().map(|(_, c)| Node::from(c)).collect(); + let b: Vec> = index.walk().map(|(_, n)| n).collect(); + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(&b) { + assert_eq!( + (x.id(), x.pad(), x.bytes(), x.list_type(), x.is_opaque_list()), + (y.id(), y.pad(), y.bytes(), y.list_type(), y.is_opaque_list()) + ); + assert_eq!(x.children().map(Node::to_chunk).collect::>(), y.children().map(Node::to_chunk).collect::>()); + for t in [b"Fold", b"tdgp", b"tdbs", b"Layr", b"btdk"] { + assert_eq!(x.find_list(t).map(Node::to_chunk), y.find_list(t).map(Node::to_chunk)); + assert_eq!(x.child_list(t).map(Node::to_chunk), y.child_list(t).map(Node::to_chunk)); + assert_eq!(x.is_list(t), y.is_list(t)); + } + for id in [b"cdat", b"Utf8", b"tdsn"] { + assert_eq!(x.child(id).map(Node::to_chunk), y.child(id).map(Node::to_chunk)); + } + let dx: Vec<(usize, Chunk<'_>)> = x.descendants().map(|(d, n)| (d, n.to_chunk())).collect(); + let dy: Vec<(usize, Chunk<'_>)> = y.descendants().map(|(d, n)| (d, n.to_chunk())).collect(); + assert_eq!(dx, dy); + assert_eq!(format!("{x:?}"), format!("{y:?}")); + } + } + } + + /// The index never reserves more than the input or the limit allows. + #[test] + fn the_index_never_reserves_more_than_the_input_or_the_limit_allows() { + // 1000 empty headers: the most chunks the bytes can hold. + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + let index = TreeIndex::parse(&data).expect("index"); + assert_eq!(index.len(), 1000); + // The start (1024 slots) is cut to what the input can hold. + assert!(index.nodes.capacity() <= 1000, "{} slots for at most 1000 headers", index.nodes.capacity()); + // A short tail or a header that runs past the end does not raise the bound. + let mut big = data.clone(); + big[16..20].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(TreeIndex::parse(&big).is_err() && crate::parse(&big).is_err()); + // Under a tighter limit the parse fails as the chunk parser does, and the guess never + // exceeds the limit. + let tight = Limits { max_depth: 64, max_chunks: 10 }; + assert_eq!(TreeIndex::parse_with_limits(&data, tight).err(), Some(AepError::TooManyChunks)); + let small = Limits { max_depth: 64, max_chunks: 1000 }; + let index = TreeIndex::parse_with_limits(&data, small).expect("exactly at the limit"); + assert_eq!(index.len(), 1000); + // A limit below what the input holds bounds the reservation: 100 chunks, never more slots. + let mut wide = b"RIFX\0\0\0\0Egg!".to_vec(); + wide.extend_from_slice(b"LIST"); + wide.extend_from_slice(&u32::try_from(4 + 8 * 99).expect("small").to_be_bytes()); + wide.extend_from_slice(b"Fold"); + wide.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 99).flatten()); + let declared = u32::try_from(wide.len() - 8).expect("small"); + wide[4..8].copy_from_slice(&declared.to_be_bytes()); + let index = TreeIndex::parse_with_limits(&wide, Limits { max_depth: 64, max_chunks: 100 }).expect("100 chunks"); + assert_eq!(index.len(), 100); + assert!(index.nodes.capacity() <= 100); + // `from_file` is sized exactly. + let file = crate::parse(&wide).expect("parse"); + assert_eq!(TreeIndex::from_file(&file).expect("index").nodes.capacity(), 100); + } + + /// A file of `n` data chunks of `size` bytes each. + fn flat(n: usize, size: usize) -> Vec { + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + for _ in 0..n { + data.extend_from_slice(b"cdat"); + data.extend_from_slice(&u32::try_from(size).expect("small").to_be_bytes()); + data.extend(std::iter::repeat_n(0u8, size)); + } + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + data + } + + /// The index grows with the chunk count not the byte size. + #[test] + fn the_index_grows_with_the_chunk_count_not_the_byte_size() { + // 4 MB in 4 chunks: a few slots, not one per 32 bytes (that would be 131 072 slots, 4 MB). + let big = flat(4, 1 << 20); + let index = TreeIndex::parse(&big).expect("index"); + assert_eq!(index.len(), 4); + assert!(index.nodes.capacity() <= INITIAL_SLOTS, "{} slots for 4 chunks", index.nodes.capacity()); + // Many small chunks: at most twice the count (it doubles). + let many = flat(10_000, 2); + let index = TreeIndex::parse(&many).expect("index"); + assert_eq!(index.len(), 10_000); + assert!(index.nodes.capacity() <= 2 * 10_000, "{} slots for 10 000 chunks", index.nodes.capacity()); + same(&big, Limits::default()); + same(&many, Limits::default()); + } + + /// `LIST Fold` around `inner`, followed by 6 bytes too short for a header, so the list's + /// sequence fails and the list is kept opaque. + fn broken_level(inner: &[u8]) -> Vec { + let mut body = b"Fold".to_vec(); + body.extend_from_slice(inner); + body.extend_from_slice(&[0xee; 6]); + let mut out = b"LIST".to_vec(); + out.extend_from_slice(&u32::try_from(body.len()).expect("small").to_be_bytes()); + out.extend_from_slice(&body); + out + } + + /// Failed attempts count once and leave nothing behind. + #[test] + fn failed_attempts_count_once_and_leave_nothing_behind() { + let mut wide = b"Fold".to_vec(); + wide.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); + let mut level = b"LIST".to_vec(); + level.extend_from_slice(&u32::try_from(wide.len()).expect("small").to_be_bytes()); + level.extend_from_slice(&wide); + for _ in 0..50 { + level = broken_level(&level); + } + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend_from_slice(&level); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + let headers = 1 + 50 + 1000; + let index = TreeIndex::parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers }).expect("parse"); + assert_eq!(TreeIndex::parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers - 1 }).err(), Some(AepError::TooManyChunks)); + // Only the outermost list is left, opaque: every failed attempt was rolled back. + assert_eq!(index.len(), 1); + let top = index.chunks().next().expect("one top-level chunk"); + assert!(top.is_opaque_list() && top.bytes().map(<[u8]>::len) == Some(level.len() - 12)); + assert_eq!(write(&index.to_file()).expect("write"), data); + same(&data, Limits::default()); + } + + /// Depth beyond the limit stays opaque without recursion past it. + #[test] + fn depth_beyond_the_limit_stays_opaque_without_recursion_past_it() { + // 5000 nested lists: far deeper than the limit; everything below depth 64 stays bytes. + let mut level = b"LIST\0\0\0\x04tdgp".to_vec(); + for _ in 0..5000 { + let mut out = b"LIST".to_vec(); + out.extend_from_slice(&u32::try_from(level.len() + 4).expect("small").to_be_bytes()); + out.extend_from_slice(b"tdgp"); + out.extend_from_slice(&level); + level = out; + } + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend_from_slice(&level); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + let index = TreeIndex::parse(&data).expect("parse"); + assert_eq!(index.len(), 64); + assert_eq!(index.walk().map(|(d, _)| d).max(), Some(64)); + assert!(index.walk().last().is_some_and(|(_, n)| n.is_opaque_list())); + same(&data, Limits::default()); + // Converting and indexing a deep owned tree uses no recursion either. + let file = index.to_file(); + assert_eq!(TreeIndex::from_file(&file).expect("index").len(), 64); + } +} diff --git a/crates/aep/src/keys.rs b/crates/aep/src/keys.rs index 0c0c93ee6..6e107ad00 100644 --- a/crates/aep/src/keys.rs +++ b/crates/aep/src/keys.rs @@ -193,19 +193,10 @@ impl<'f> Keyframe<'f> { } } - /// The value of a 3-component spatial keyframe (Position), x, y and z in pixels. - pub fn spatial_value(&self) -> Option<[f64; 3]> { - let v = self.value()?; - if !matches!(self.kind(), KeyframeKind::Spatial { components: 3 }) { - return None; - } - Some([*v.first()?, *v.get(1)?, *v.get(2)?]) - } - /// The ease of the key: the four slots at byte 16 of a one-component plain record or at byte 24 /// of a spatial record or a mask path record. For linear and hold keys all four are 0 (a bezier key stores what /// `setTemporalEase` was given). Plain records with several components keep four slots per - /// component, see [`Keyframe::ease_component`] and [`Keyframe::plain_ease_slots`]. + /// component, see [`Keyframe::ease_component`]. pub fn ease(&self) -> Option { match self.kind() { KeyframeKind::Plain { components: 1 } => ease_at(self.record, 16), @@ -214,16 +205,6 @@ impl<'f> Keyframe<'f> { } } - /// The `4 n` ease `f64` of a plain record as stored (from byte `8 + 8 n`). With one component - /// they are [`Keyframe::ease`]; with several they are type-major, see - /// [`Keyframe::ease_component`]. - pub fn plain_ease_slots(&self) -> Option> { - match self.kind() { - KeyframeKind::Plain { components } => doubles(self.record, components.checked_mul(8)?.checked_add(8)?, components.checked_mul(4)?), - _ => None, - } - } - /// The ease of one value component. A plain record with `n` components stores the `4 n` ease /// doubles **type-major**: `[in speed x n][in influence x n][out speed x n][out influence x n]` /// starting at byte `8 + 8 n`, and component `i` uses slot `i` of each block (verified for the @@ -260,16 +241,6 @@ impl<'f> Keyframe<'f> { (0..n).map(|i| self.ease_component(i)).collect() } - /// The Euclidean ARGB distance to the next key that After Effects writes at byte 16 of a colour - /// (4-component spatial) record whose interpolation is not linear: 255 sqrt(2) = 360.6245 for - /// red to blue; 0 on the last key and on linear keys. `None` for other records. - pub fn color_distance(&self) -> Option { - match self.kind() { - KeyframeKind::Spatial { components: 4 } => be_f64(self.record, 16), - _ => None, - } - } - /// The decoded spatial record (Position: 128 bytes, colour: 152 bytes). pub fn spatial(&self) -> Option { let KeyframeKind::Spatial { components: n } = self.kind() else { return None }; @@ -300,11 +271,6 @@ pub struct ExpressionFlags { } impl ExpressionFlags { - /// True when bytes 76, 77 and 120 are all 1. - pub fn all_set(&self) -> bool { - self.byte_76 == 1 && self.byte_77 == 1 && self.byte_120 == 1 - } - /// True when byte 119 is 1. pub fn disabled(&self) -> bool { self.byte_119 == 1 @@ -324,11 +290,6 @@ impl<'f, 'a> Property<'f, 'a> { be_u32(self.chunk.child(b"tdsb")?.bytes()?, 0) } - /// True when `tdb4` byte 5 has bit 0 set: the property is static, it has no keyframes. - pub fn is_static_flag_set(&self) -> Option { - Some(self.header()?.get(5)? & 1 != 0) - } - /// The expression source: the raw UTF-8 text of the `Utf8` child that follows the value in the /// property (no length prefix, no engine tag; the engine is project-wide). pub fn expression(&self) -> Option { diff --git a/crates/aep/src/lib.rs b/crates/aep/src/lib.rs index a47cddfce..3e5dc2ceb 100644 --- a/crates/aep/src/lib.rs +++ b/crates/aep/src/lib.rs @@ -14,6 +14,8 @@ //! list) on damaged data instead of failing. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +// Ranges and borrowed bytes are passed around as plain tuples, as in EffectCraft, which allows this lint. +#![allow(clippy::type_complexity)] mod aepx; mod arbitrary; @@ -24,6 +26,7 @@ mod effects; mod error; mod footage; mod header; +pub mod index; mod keys; mod masks; mod matte; @@ -36,16 +39,17 @@ mod values; mod version; mod write; -pub use aepx::{is_aepx, parse_any, read_aepx, read_aepx_with_limits}; +pub use aepx::{AepxDrafts, index_aepx, is_aepx, parse_any, read_aepx, read_aepx_with_limits}; pub use arbitrary::{ CURVE_IDENTITY, CryptomatteData, CurvesData, ExtractorChannels, HueSaturationData, LevelsData, MeshData, curve_lut, identifier_channel_type, }; pub use camera::{CameraPosition, DEFAULT_CAMERA_ZOOM}; pub use chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk}; -pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue}; +pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue, Pard}; pub use error::AepError; pub use footage::{Footage, PsdLayer, SequenceInfo}; pub use header::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Quality, Rational, Renderer}; +pub use index::{Draft, Node, NodeWalk, Nodes, Root, TreeIndex}; pub use keys::{ExpressionFlags, Interpolation, KeyEase, KeyframeKind, SpatialKey}; pub use masks::{Mask, MaskAtom, MaskMode, PathVertex, ShapePath}; pub use matte::{MatteMode, TrackMatte}; diff --git a/crates/aep/src/masks.rs b/crates/aep/src/masks.rs index 203ccefd5..42b52f5f4 100644 --- a/crates/aep/src/masks.rs +++ b/crates/aep/src/masks.rs @@ -6,9 +6,9 @@ //! property (`tdbs`, with a key list when animated) and `omks` with one `LIST shap` per keyframe (a //! single one when the path is static). -use crate::Chunk; use crate::bytes::{be_f32, be_u32, until_nul}; -use crate::typed::{KeyList, Layer, Project, PropGroup, PropNode, Property}; +use crate::index::Node; +use crate::typed::{KeyList, Layer, PropGroup, PropNode, Property}; use crate::values::{Tracked, read}; /// The mask mode (`mkif` `u32` at byte 4). @@ -93,8 +93,10 @@ pub struct ShapePath { } impl ShapePath { - /// Decodes a `LIST shap`; `None` when `shph` or the point list is malformed. - pub fn from_chunk(shap: &Chunk<'_>) -> Option { + /// Decodes a `LIST shap` (a [`Chunk`](crate::Chunk) or a [`Node`]); `None` when + /// `shph` or the point list is malformed. + pub fn from_chunk<'f, 'a: 'f>(shap: impl Into>) -> Option { + let shap = shap.into(); let shph = shap.child(b"shph")?.bytes()?; let bbox = [be_f32(shph, 4)?, be_f32(shph, 8)?, be_f32(shph, 12)?, be_f32(shph, 16)?]; let closed_flag = *shph.get(20)?; @@ -187,22 +189,12 @@ fn mask_from_atom(atom: &PropGroup<'_, '_>, mkif: Option<&[u8]>) -> Mask { } } if let Some(omks) = oms.child_list(b"omks") { - mask.shapes = omks.children().iter().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect(); + mask.shapes = omks.children().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect(); } } mask } -impl<'f, 'a> Project<'f, 'a> { - /// The vertices of every path shape of a mask in pixels of the layer: mask boxes are normalised - /// to the **layer** size (the size of its source), not the composition's. `None` when the layer - /// has no source with a size. - pub fn mask_vertices_px(&self, layer: &Layer<'f, 'a>, mask: &Mask) -> Option>> { - let (width, height) = self.layer_source_size(layer)?; - Some(mask.shapes.iter().map(|s| s.vertices((f64::from(width), f64::from(height)))).collect()) - } -} - /// One mask with the views of its records, for readers that need more than [`Mask`]: the /// keyframes and expressions of the mask properties (in [`MaskAtom::atom`]: `ADBE Mask Feather`, /// `ADBE Mask Opacity`, `ADBE Mask Offset`) and the path keyframes paired with their shapes. @@ -246,7 +238,7 @@ impl<'f, 'a> Layer<'f, 'a> { if let Some(PropNode::Other(oms)) = atom.get("ADBE Mask Shape") { path = oms.child_list(b"tdbs").and_then(Property::from_chunk); if let Some(omks) = oms.child_list(b"omks") { - path_shapes = omks.children().iter().filter(|c| c.is_list(b"shap")).map(ShapePath::from_chunk).collect(); + path_shapes = omks.children().filter(|c| c.is_list(b"shap")).map(ShapePath::from_chunk).collect(); } } masks.push(MaskAtom { mask, atom, path, path_shapes }); diff --git a/crates/aep/src/read.rs b/crates/aep/src/read.rs index c769029e4..a969a3997 100644 --- a/crates/aep/src/read.rs +++ b/crates/aep/src/read.rs @@ -2,6 +2,7 @@ use std::borrow::Cow; +use crate::bytes::{array, be_u32}; use crate::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; use crate::error::AepError; @@ -36,10 +37,20 @@ pub fn parse(data: &[u8]) -> Result, AepError> { /// # Errors /// See [`parse`]; also fails with [`AepError::TooManyChunks`]. pub fn parse_with_limits(data: &[u8], limits: Limits) -> Result, AepError> { + let end = container_end(data)?; + let mut parser = Parser { data, limits, count: 0 }; + let chunks = parser.sequence(12, end, 1)?; + let trailer = data.get(end..).unwrap_or(&[]); + Ok(AepFile { chunks, trailer: Cow::Borrowed(trailer) }) +} + +/// Checks the `RIFX`/`Egg!` header and returns where the container ends (its chunks fill +/// `12..end`; the trailer follows). Shared with [`crate::index::TreeIndex::parse`]. +pub(super) fn container_end(data: &[u8]) -> Result { if id4(data, 0) != Some(*b"RIFX") { return Err(AepError::NotRifx); } - let declared = u64::from(be32(data, 4).ok_or(AepError::NotRifx)?); + let declared = u64::from(be_u32(data, 4).ok_or(AepError::NotRifx)?); let form = id4(data, 8).ok_or(AepError::NotRifx)?; if &form != b"Egg!" { return Err(AepError::BadFormType(form)); @@ -49,20 +60,12 @@ pub fn parse_with_limits(data: &[u8], limits: Limits) -> Result, Aep return Err(AepError::Truncated { declared, available }); } // `declared <= available < data.len()`, so the end is inside the input. - let end = usize::try_from(declared).map_err(|_| AepError::TooLarge)?.checked_add(8).ok_or(AepError::TooLarge)?; - let mut parser = Parser { data, limits, count: 0 }; - let chunks = parser.sequence(12, end, 1)?; - let trailer = data.get(end..).unwrap_or(&[]); - Ok(AepFile { chunks, trailer: Cow::Borrowed(trailer) }) + usize::try_from(declared).map_err(|_| AepError::TooLarge)?.checked_add(8).ok_or(AepError::TooLarge) } -fn be32(data: &[u8], at: usize) -> Option { - id4(data, at).map(u32::from_be_bytes) -} - -fn id4(data: &[u8], at: usize) -> Option<[u8; 4]> { - let b = data.get(at..at.checked_add(4)?)?; - Some([*b.first()?, *b.get(1)?, *b.get(2)?, *b.get(3)?]) +/// The 4-byte id at `at`, `None` when the input is too short. +pub(super) fn id4(data: &[u8], at: usize) -> Option<[u8; 4]> { + array::<4>(data, at) } struct Parser<'a> { @@ -74,13 +77,16 @@ struct Parser<'a> { impl<'a> Parser<'a> { /// Parses the sibling chunks that exactly fill `start..end`. fn sequence(&mut self, start: usize, end: usize, depth: usize) -> Result>, AepError> { + // Sized once: a well-formed sequence fills exactly this many slots. `try_reserve` so a + // limit raised past what the target can allocate fails nothing here (the Vec then grows). let mut out = Vec::new(); + let _ = out.try_reserve_exact(self.capacity_for(start, end)); let mut pos = start; while pos < end { let short = AepError::Malformed { offset: pos, what: "bytes left over that are too short for a chunk header" }; let body_start = pos.checked_add(8).filter(|b| *b <= end).ok_or(short)?; let id = id4(self.data, pos).ok_or(AepError::Malformed { offset: pos, what: "short read" })?; - let size = be32(self.data, pos + 4).ok_or(AepError::Malformed { offset: pos, what: "short read" })? as usize; + let size = be_u32(self.data, pos + 4).ok_or(AepError::Malformed { offset: pos, what: "short read" })? as usize; let avail = end - body_start; if size > avail { return Err(AepError::ChunkTooLarge { offset: pos, size: size as u64, available: avail as u64 }); @@ -103,6 +109,26 @@ impl<'a> Parser<'a> { Ok(out) } + /// The slots to reserve for the sequence `start..end`: its header count, bounded by the input + /// (one per 8 bytes at most) and by the chunks the limit still allows. + fn capacity_for(&self, start: usize, end: usize) -> usize { + self.count_siblings(start, end).min(self.limits.max_chunks.saturating_sub(self.count)) + } + + /// The number of chunk headers that tile `start..end` the way [`Self::sequence`] walks them, + /// stopping at the first that does not fit. Never more than `(end - start) / 8`. + fn count_siblings(&self, start: usize, end: usize) -> usize { + let mut n = 0usize; + let mut pos = start; + while let Some(body_start) = pos.checked_add(8).filter(|b| *b <= end) { + let Some(size) = be_u32(self.data, pos.saturating_add(4)) else { break }; + let Some(next) = usize::try_from(size).ok().and_then(|s| body_start.checked_add(s)).filter(|e| *e <= end) else { break }; + n = n.saturating_add(1); + pos = if size % 2 == 1 && next < end { next.saturating_add(1) } else { next }; + } + n + } + /// Like [`Self::sequence`] but a structural problem yields `None` (the caller keeps bytes). fn tentative(&mut self, start: usize, end: usize, depth: usize) -> Result>>, AepError> { match self.sequence(start, end, depth) { @@ -140,3 +166,113 @@ impl<'a> Parser<'a> { Ok(Body::Data(Cow::Borrowed(self.slice(start, end)))) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Every children `Vec` in the tree, depth first. + fn child_vecs<'f, 'a>(chunks: &'f [Chunk<'a>], out: &mut Vec<&'f Vec>>) { + for c in chunks { + match &c.body { + Body::List { children, .. } | Body::Chunks(children) => { + out.push(children); + child_vecs(children, out); + } + Body::Data(_) | Body::OpaqueList { .. } => {} + } + } + } + + /// Every sibling list is allocated once at its exact length. + #[test] + fn every_sibling_list_is_allocated_once_at_its_exact_length() { + let inner: Vec> = (0..37u8).map(|i| Chunk::data(*b"cdat", vec![i; usize::from(i % 5)])).collect(); + let middle: Vec> = (0..9).map(|_| Chunk::list(*b"tdbs", inner.clone())).collect(); + let file = AepFile { chunks: vec![Chunk::data(*b"head", vec![0; 3]), Chunk::list(*b"Fold", middle)], trailer: Cow::Borrowed(&[]) }; + let bytes = crate::write(&file).expect("write"); + let parsed = parse(&bytes).expect("parse"); + assert_eq!(crate::write(&parsed).expect("rewrite"), bytes); + let mut vecs = vec![&parsed.chunks]; + child_vecs(&parsed.chunks, &mut vecs); + assert_eq!(vecs.len(), 11); + // `try_reserve_exact` gives exactly the requested capacity with std's allocator today; a + // Vec grown push by push would have rounded up to a power of two (37 -> 64, 9 -> 16). + for v in vecs { + assert_eq!(v.capacity(), v.len(), "a sibling Vec grew past its length"); + } + } + + /// The preallocation is bounded by the input and the chunk limit. + #[test] + fn the_preallocation_is_bounded_by_the_input_and_the_chunk_limit() { + // 1000 empty headers: the most chunks the bytes can hold. + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + let parser = Parser { data: &data, limits: Limits::default(), count: 0 }; + assert_eq!(parser.count_siblings(12, data.len()), 1000); + assert!(parser.count_siblings(12, data.len()) <= (data.len() - 12) / 8); + // A header whose size runs past the end stops the count; a stray tail is not counted. + assert_eq!(parser.count_siblings(12, data.len() - 3), 999); + let mut big = data.clone(); + big[16..20].copy_from_slice(&u32::MAX.to_be_bytes()); + let parser = Parser { data: &big, limits: Limits::default(), count: 0 }; + assert_eq!(parser.count_siblings(12, big.len()), 0); + let f = parse(&data).expect("parse"); + assert_eq!((f.chunks.len(), f.chunks.capacity()), (1000, 1000)); + // Under a tighter limit the parse fails as before, without sizing for more than allowed. + let tight = Limits { max_depth: 64, max_chunks: 10 }; + assert_eq!(parse_with_limits(&data, tight), Err(AepError::TooManyChunks)); + // The reservation never exceeds what the chunk limit still allows. + let mut parser = Parser { data: &data, limits: tight, count: 0 }; + assert_eq!(parser.capacity_for(12, data.len()), 10); + parser.count = 7; + assert_eq!(parser.capacity_for(12, data.len()), 3); + parser.count = 11; + assert_eq!(parser.capacity_for(12, data.len()), 0); + let parser = Parser { data: &data, limits: Limits::default(), count: 0 }; + assert_eq!(parser.capacity_for(12, data.len()), 1000); + } + + /// `LIST Fold` around `inner`, followed by 6 bytes too short for a header, so the list's + /// sequence fails and the list is kept opaque. + fn broken_level(inner: &[u8]) -> Vec { + let mut body = b"Fold".to_vec(); + body.extend_from_slice(inner); + body.extend_from_slice(&[0xee; 6]); + let mut out = b"LIST".to_vec(); + out.extend_from_slice(&u32::try_from(body.len()).expect("small").to_be_bytes()); + out.extend_from_slice(&body); + out + } + + /// Nested lists with broken tails parse each header once. + #[test] + fn nested_lists_with_broken_tails_parse_each_header_once() { + // A wide, well-formed list at the bottom, then 50 levels that each fail and fall back to + // opaque: every level re-parses its child before giving up. + let mut wide = b"Fold".to_vec(); + wide.extend(std::iter::repeat_n(*b"abcd\0\0\0\0", 1000).flatten()); + let mut level = b"LIST".to_vec(); + level.extend_from_slice(&u32::try_from(wide.len()).expect("small").to_be_bytes()); + level.extend_from_slice(&wide); + for _ in 0..50 { + level = broken_level(&level); + } + let mut data = b"RIFX\0\0\0\0Egg!".to_vec(); + data.extend_from_slice(&level); + let declared = u32::try_from(data.len() - 8).expect("small"); + data[4..8].copy_from_slice(&declared.to_be_bytes()); + // 1 + 50 + 1000 headers in the file: the parse counts each exactly once (the count spans + // every attempt), so the work stays linear in the input. + let headers = 1 + 50 + 1000; + let f = parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers }).expect("parse"); + assert_eq!(parse_with_limits(&data, Limits { max_depth: 64, max_chunks: headers - 1 }), Err(AepError::TooManyChunks)); + // The outermost list keeps its bytes, and the file writes back unchanged. + let [top] = f.chunks.as_slice() else { panic!("one top-level chunk") }; + assert!(matches!(&top.body, Body::OpaqueList { list_type, data } if list_type == b"Fold" && data.len() + 12 == level.len())); + assert_eq!(crate::write(&f).expect("write"), data); + } +} diff --git a/crates/aep/src/settings.rs b/crates/aep/src/settings.rs index 1193dbc39..440983805 100644 --- a/crates/aep/src/settings.rs +++ b/crates/aep/src/settings.rs @@ -2,8 +2,10 @@ //! linear-light switches, the time display and the frame count start. Cases 620-634: one change //! each against the base project 620; every field below is the only byte (or chunk) that changes. +use crate::bytes::be_u32; use crate::chunk::AepFile; use crate::footage::json_string; +use crate::index::{Node, Root, TreeIndex}; /// The time display style (`nhed` byte 8, feet + frames byte 11, film type byte 13). #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -54,7 +56,17 @@ pub struct ProjectSettings { impl ProjectSettings { /// Reads the settings from the top-level chunks. pub fn read(file: &AepFile<'_>) -> ProjectSettings { - let nhed = file.chunk(b"nhed").and_then(|c| c.bytes()); + Self::of(Root::from(file)) + } + + /// Reads the settings from the top-level chunks of an indexed file. + pub fn read_index(index: &TreeIndex<'_>) -> ProjectSettings { + Self::of(Root::from(index)) + } + + /// Reads the settings from the top-level chunks of either tree. + pub fn of(file: Root<'_, '_>) -> ProjectSettings { + let nhed = file.chunk(b"nhed").and_then(Node::bytes); let byte = |i: usize| nhed.and_then(|b| b.get(i).copied()); let bits_per_channel = byte(15).and_then(|v| match v { 0 => Some(8), @@ -73,9 +85,9 @@ impl ProjectSettings { 1 => Some(1), _ => None, }); - let flag = |id: &[u8; 4]| file.chunk(id).and_then(|c| c.bytes()).and_then(|b| b.first().copied()) == Some(1); - let working_gamma_24 = file.chunk(b"dwga").and_then(|c| c.bytes()).and_then(|b| b.get(..4)).map(|b| b != [0, 0, 0, 0]); - let scene_compensation = file.chunk(b"acer").and_then(|c| c.bytes()).and_then(|b| b.first().copied()).map(|v| v != 0); + let flag = |id: &[u8; 4]| file.chunk(id).and_then(Node::bytes).and_then(|b| b.first().copied()) == Some(1); + let working_gamma_24 = file.chunk(b"dwga").and_then(Node::bytes).and_then(|b| b.get(..4)).map(|b| b != [0, 0, 0, 0]); + let scene_compensation = file.chunk(b"acer").and_then(Node::bytes).and_then(|b| b.first().copied()).map(|v| v != 0); ProjectSettings { bits_per_channel, working_space: working_space(file), @@ -90,9 +102,10 @@ impl ProjectSettings { } /// The working space: the `Utf8` right after `PwCs`. -fn working_space(file: &AepFile<'_>) -> Option { - let at = file.chunks.iter().position(|c| c.is(b"PwCs"))?; - let json = file.chunks.get(at.checked_add(1)?).filter(|c| c.is(b"Utf8"))?.bytes()?; +fn working_space(file: Root<'_, '_>) -> Option { + let mut chunks = file.chunks(); + chunks.find(|c| c.is(b"PwCs"))?; + let json = chunks.next().filter(|c| c.is(b"Utf8"))?.bytes()?; let trimmed: Vec = json.iter().copied().filter(|b| !b.is_ascii_whitespace() && *b != 0).collect(); if trimmed == b"{}" { return Some(WorkingSpace::None); @@ -130,7 +143,7 @@ fn base64_decode(text: &str) -> Option> { /// The profile description (ICC.1 tag `desc`): a v2 `desc` (ASCII) or a v4 `mluc` (its first /// record, UTF-16BE). `None` when the profile or the tag is cut short. fn icc_description(icc: &[u8]) -> Option { - let be32 = |at: usize| icc.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes); + let be32 = |at: usize| be_u32(icc, at); let count = be32(128)?; let tag = (0..count.min(1024)).find_map(|i| { let at = 132usize.checked_add(usize::try_from(i).ok()?.checked_mul(12)?)?; @@ -141,13 +154,13 @@ fn icc_description(icc: &[u8]) -> Option { let body = icc.get(off..off.checked_add(len)?)?; let text = match body.get(..4)? { b"desc" => { - let n = usize::try_from(u32::from_be_bytes(body.get(8..12)?.try_into().ok()?)).ok()?; + let n = usize::try_from(be_u32(body, 8)?).ok()?; let ascii = body.get(12..12usize.checked_add(n)?)?; String::from_utf8_lossy(ascii.split(|b| *b == 0).next().unwrap_or_default()).into_owned() } b"mluc" => { - let n = usize::try_from(u32::from_be_bytes(body.get(20..24)?.try_into().ok()?)).ok()?; - let at = usize::try_from(u32::from_be_bytes(body.get(24..28)?.try_into().ok()?)).ok()?; + let n = usize::try_from(be_u32(body, 20)?).ok()?; + let at = usize::try_from(be_u32(body, 24)?).ok()?; let units: Vec = body.get(at..at.checked_add(n)?)?.as_chunks::<2>().0.iter().map(|p| u16::from_be_bytes(*p)).collect(); String::from_utf16_lossy(&units) } diff --git a/crates/aep/src/shapes.rs b/crates/aep/src/shapes.rs index 864cfa55b..28b572506 100644 --- a/crates/aep/src/shapes.rs +++ b/crates/aep/src/shapes.rs @@ -10,7 +10,7 @@ //! points are in pixels relative to the layer origin. use crate::masks::ShapePath; -use crate::typed::{Layer, PropGroup, PropNode, Property}; +use crate::typed::{Layer, PropGroup, PropNode}; use crate::values::{Tracked, read, read_opt}; /// The stroke line cap (`ADBE Vector Stroke Line Cap`, stored as a double; butt is the default and @@ -145,7 +145,7 @@ fn number(group: &PropGroup<'_, '_>, name: &str) -> Option> { fn paths_of(group: &PropGroup<'_, '_>) -> Vec { let Some(PropNode::Other(oms)) = group.get("ADBE Vector Shape") else { return Vec::new() }; let Some(omks) = oms.child_list(b"omks") else { return Vec::new() }; - omks.children().iter().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect() + omks.children().filter(|c| c.is_list(b"shap")).filter_map(ShapePath::from_chunk).collect() } fn item(match_name: String, group: &PropGroup<'_, '_>) -> ShapeItem { @@ -269,12 +269,3 @@ impl<'f, 'a> Layer<'f, 'a> { .collect() } } - -impl<'f, 'a> Property<'f, 'a> { - /// The ARGB fractions of a static colour property (4 components stored as doubles 0..255). - pub fn color_argb(&self) -> Option<[f64; 4]> { - let v = self.static_value()?; - let [a, r, g, b] = *v.as_slice().first_chunk::<4>()?; - Some([a / 255.0, r / 255.0, g / 255.0, b / 255.0]) - } -} diff --git a/crates/aep/src/textdoc.rs b/crates/aep/src/textdoc.rs index 373fd40db..1e7569b67 100644 --- a/crates/aep/src/textdoc.rs +++ b/crates/aep/src/textdoc.rs @@ -5,8 +5,11 @@ //! as `(` + BOM `fe ff` + UTF-16BE + `)` with `\` escapes. [`parse_text_dict`] reads it (depth //! limited, never panics) and [`Layer::text_document`] pulls out the verified fields. -use crate::Chunk; +use std::borrow::Cow; +use std::sync::LazyLock; + use crate::bytes::{be_u32, text}; +use crate::index::Node; use crate::typed::{Comp, Layer, Property}; /// How deep dictionaries and arrays may nest before the parser gives up. @@ -73,15 +76,99 @@ impl TextValue { _ => None, } } +} - fn key_text(&self) -> String { +/// The text of a key the way the dictionary stores it: a `/name` as written, any other value in +/// its canonical form (`06` and `+6` are `6`, `1.0` is `1`, a string its decoded text). +fn owned_key(value: &V<'_>) -> String { + match value { + V::Name(s) | V::Token(s) => text(s), + V::Str(utf16) => decode_utf16be(utf16), + V::Int(i) => i.to_string(), + V::Float(f) => f.to_string(), + V::Bool(b) => b.to_string(), + V::Bytes(b) => text(b), + V::Dict(_) | V::Array(_) => String::new(), + } +} + +/// A value of the text dictionary as [`TextDocument::parse`] reads it: it borrows names, bare +/// words and strings from the body, so a document is read without a `String` per token. A key is +/// borrowed when it is a `/name` (every key After Effects writes); its text is the same as the +/// [`TextValue`] key's. [`V::into_owned`] gives the public [`TextValue`]. +#[derive(Debug, Clone)] +enum V<'b> { + Dict(Vec<(Cow<'b, str>, V<'b>)>), + Array(Vec>), + /// A string that started with the byte order mark: the UTF-16BE bytes after it, unescaped. + Str(Cow<'b, [u8]>), + Bytes(Cow<'b, [u8]>), + Name(&'b [u8]), + Int(i64), + Float(f64), + Bool(bool), + Token(&'b [u8]), +} + +impl<'b> V<'b> { + /// The value of a dictionary key (the last one when a key repeats). + fn get(&self, key: &str) -> Option<&V<'b>> { match self { - Self::Name(s) | Self::Str(s) | Self::Token(s) => s.clone(), - Self::Int(i) => i.to_string(), - Self::Float(f) => f.to_string(), - Self::Bool(b) => b.to_string(), - Self::Bytes(b) => text(b), - Self::Dict(_) | Self::Array(_) => String::new(), + Self::Dict(pairs) => pairs.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + fn at(&self, index: usize) -> Option<&V<'b>> { + match self { + Self::Array(items) => items.get(index), + _ => None, + } + } + + /// The decoded text of a string value. + fn string(&self) -> Option { + match self { + Self::Str(utf16) => Some(decode_utf16be(utf16)), + _ => None, + } + } + + fn as_f64(&self) -> Option { + match self { + Self::Int(i) => Some(*i as f64), + Self::Float(f) => Some(*f), + _ => None, + } + } + + fn as_i64(&self) -> Option { + match self { + Self::Int(i) => Some(*i), + _ => None, + } + } + + /// The key a value makes when it is written in a key position. + fn into_key(self) -> Cow<'b, str> { + match self { + Self::Name(s) => String::from_utf8_lossy(s), + other => Cow::Owned(owned_key(&other)), + } + } + + /// The public form. Recursion is bounded: a parsed value nests at most [`MAX_DEPTH`] + 1 deep. + fn into_owned(self) -> TextValue { + match self { + Self::Dict(pairs) => TextValue::Dict(pairs.into_iter().map(|(k, v)| (k.into_owned(), v.into_owned())).collect()), + Self::Array(items) => TextValue::Array(items.into_iter().map(V::into_owned).collect()), + Self::Str(utf16) => TextValue::Str(decode_utf16be(&utf16)), + Self::Bytes(b) => TextValue::Bytes(b.into_owned()), + Self::Name(s) => TextValue::Name(text(s)), + Self::Int(i) => TextValue::Int(i), + Self::Float(f) => TextValue::Float(f), + Self::Bool(b) => TextValue::Bool(b), + Self::Token(s) => TextValue::Token(text(s)), } } } @@ -89,32 +176,44 @@ impl TextValue { struct Parser<'b> { b: &'b [u8], i: usize, + /// The pairs of the dictionaries being read, innermost last: a dictionary's pairs are moved + /// into a vector of their exact size when it closes (one allocation per dictionary instead of + /// one per doubling). + pairs: Vec<(Cow<'b, str>, V<'b>)>, + /// The same for the items of arrays. + items: Vec>, } +/// Whitespace between tokens. fn is_ws(c: u8) -> bool { matches!(c, b' ' | b'\t' | b'\r' | b'\n') } +/// A byte that ends a bare word. fn is_delimiter(c: u8) -> bool { is_ws(c) || matches!(c, b'/' | b'[' | b']' | b'<' | b'>' | b'(' | b')') } -impl Parser<'_> { +impl<'b> Parser<'b> { + /// The next byte, `None` at the end. fn peek(&self) -> Option { self.b.get(self.i).copied() } + /// Moves past whitespace. fn skip_ws(&mut self) { while self.peek().is_some_and(is_ws) { self.i = self.i.saturating_add(1); } } + /// True when the unread bytes start with `s`. fn starts_with(&self, s: &[u8]) -> bool { self.b.get(self.i..).is_some_and(|rest| rest.starts_with(s)) } - fn word(&mut self) -> &[u8] { + /// The bare word at the position (up to the next delimiter), borrowed from the body. + fn word(&mut self) -> &'b [u8] { let start = self.i; while self.peek().is_some_and(|c| !is_delimiter(c)) { self.i = self.i.saturating_add(1); @@ -122,79 +221,106 @@ impl Parser<'_> { self.b.get(start..self.i).unwrap_or(&[]) } - fn parse(&mut self, depth: usize) -> Option { + /// The body of a `( ... )` string after the `(`, with `\` escapes resolved: borrowed when it + /// has none. `None` when the string or an escape is not closed. + fn string_body(&mut self) -> Option> { + let rest = self.b.get(self.i..)?; + let stop = rest.iter().position(|c| matches!(c, b')' | b'\\'))?; + let head = rest.get(..stop)?; + self.i = self.i.saturating_add(stop); + if self.peek()? == b')' { + self.i = self.i.saturating_add(1); + return Some(Cow::Borrowed(head)); + } + let mut out = head.to_vec(); + loop { + let c = self.peek()?; + if c == b'\\' { + out.push(*self.b.get(self.i.saturating_add(1))?); + self.i = self.i.saturating_add(2); + } else if c == b')' { + self.i = self.i.saturating_add(1); + return Some(Cow::Owned(out)); + } else { + out.push(c); + self.i = self.i.saturating_add(1); + } + } + } + + /// The value at the position, `None` when it is malformed or nested deeper than the limit. + fn parse(&mut self, depth: usize) -> Option> { self.skip_ws(); if depth > MAX_DEPTH { return None; } if self.starts_with(b"<<") { self.i = self.i.saturating_add(2); - let mut pairs = Vec::new(); + // On an error the pairs read so far stay on the stack: the error ends the whole parse. + let mark = self.pairs.len(); loop { self.skip_ws(); if self.starts_with(b">>") { self.i = self.i.saturating_add(2); - return Some(TextValue::Dict(pairs)); + return Some(V::Dict(self.pairs.drain(mark..).collect())); } let key = self.parse(depth.saturating_add(1))?; let value = self.parse(depth.saturating_add(1))?; - pairs.push((key.key_text(), value)); + self.pairs.push((key.into_key(), value)); } } match self.peek()? { b'[' => { self.i = self.i.saturating_add(1); - let mut items = Vec::new(); + let mark = self.items.len(); loop { self.skip_ws(); if self.peek()? == b']' { self.i = self.i.saturating_add(1); - return Some(TextValue::Array(items)); + return Some(V::Array(self.items.drain(mark..).collect())); } - items.push(self.parse(depth.saturating_add(1))?); + let item = self.parse(depth.saturating_add(1))?; + self.items.push(item); } } b'(' => { self.i = self.i.saturating_add(1); - let mut out = Vec::new(); - loop { - let c = self.peek()?; - if c == b'\\' { - out.push(*self.b.get(self.i.saturating_add(1))?); - self.i = self.i.saturating_add(2); - } else if c == b')' { - self.i = self.i.saturating_add(1); - break; - } else { - out.push(c); - self.i = self.i.saturating_add(1); - } - } - Some(match out.strip_prefix(&[0xfe, 0xff]) { - Some(utf16) => TextValue::Str(decode_utf16be(utf16)), - None => TextValue::Bytes(out), + let body = self.string_body()?; + Some(if body.starts_with(&[0xfe, 0xff]) { + V::Str(match body { + Cow::Borrowed(b) => Cow::Borrowed(b.get(2..).unwrap_or(&[])), + Cow::Owned(mut v) => { + let n = v.len().min(2); + v.drain(..n); + Cow::Owned(v) + } + }) + } else { + V::Bytes(body) }) } b'/' => { self.i = self.i.saturating_add(1); - Some(TextValue::Name(text(self.word()))) + Some(V::Name(self.word())) } _ => { let word = self.word(); if word.is_empty() { return None; } - let w = text(word); - Some(match w.as_str() { - "true" => TextValue::Bool(true), - "false" => TextValue::Bool(false), + // A word that is not UTF-8 reads as text with replacement characters, which is + // neither a boolean nor a number: a token. + let Ok(w) = std::str::from_utf8(word) else { return Some(V::Token(word)) }; + Some(match w { + "true" => V::Bool(true), + "false" => V::Bool(false), _ => match w.parse::() { - Ok(i) => TextValue::Int(i), + Ok(i) => V::Int(i), // `parse` also takes `nan`, `inf` and overflowing exponents; those are not // numbers a text document holds, so they stay tokens and read as missing. Err(_) => match w.parse::() { - Ok(f) if f.is_finite() => TextValue::Float(f), - _ => TextValue::Token(w), + Ok(f) if f.is_finite() => V::Float(f), + _ => V::Token(word), }, }, }) @@ -203,6 +329,7 @@ impl Parser<'_> { } } +/// A big-endian UTF-16 string as text (unpaired surrogates become U+FFFD). fn decode_utf16be(bytes: &[u8]) -> String { let (pairs, rest) = bytes.as_chunks::<2>(); let units = pairs.iter().map(|p| u16::from_be_bytes(*p)); @@ -213,11 +340,9 @@ fn decode_utf16be(bytes: &[u8]) -> String { s } -/// Parses the body of a `btdk` list into its top-level `key value` pairs (as a [`TextValue::Dict`]). -/// Parsing stops silently at the first syntax error or at nesting deeper than 64 levels; what was -/// read before is returned. -pub fn parse_text_dict(body: &[u8]) -> TextValue { - let mut parser = Parser { b: body, i: 0 }; +/// The top-level `key value` pairs of a `btdk` body, borrowed (see [`parse_text_dict`]). +fn parse_dict(body: &[u8]) -> V<'_> { + let mut parser = Parser { b: body, i: 0, pairs: Vec::new(), items: Vec::new() }; let mut pairs = Vec::new(); loop { parser.skip_ws(); @@ -226,13 +351,20 @@ pub fn parse_text_dict(body: &[u8]) -> TextValue { } let Some(key) = parser.parse(0) else { break }; let Some(value) = parser.parse(0) else { break }; - pairs.push((key.key_text(), value)); + pairs.push((key.into_key(), value)); } - TextValue::Dict(pairs) + V::Dict(pairs) +} + +/// Parses the body of a `btdk` list into its top-level `key value` pairs (as a [`TextValue::Dict`]). +/// Parsing stops silently at the first syntax error or at nesting deeper than 64 levels; what was +/// read before is returned. +pub fn parse_text_dict(body: &[u8]) -> TextValue { + parse_dict(body).into_owned() } /// The run style slots (`RUN/6/0[n]/0/0/6/`) that are decoded; every other slot is compared -/// with its default (`style_defaults`) and listed in +/// with its default (`STYLE_DEFAULTS`) and listed in /// [`TextDocument::undecoded_style_fields`] when it differs. pub const DECODED_STYLE_SLOTS: &[&str] = &["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "11", "12", "13", "18", "35", "36", "52", "53", "54", "56", "57", "58", "62", "63", "70"]; @@ -241,25 +373,27 @@ pub const DECODED_STYLE_SLOTS: &[&str] = pub const DECODED_PARAGRAPH_SLOTS: &[&str] = &["0", "1", "2", "3", "4", "5", "8", "9", "21", "29", "33"]; /// A number slot. -fn val(v: f64) -> TextValue { - TextValue::Float(v) +fn val(v: f64) -> V<'static> { + V::Float(v) } -fn dict(pairs: Vec<(&str, TextValue)>) -> TextValue { - TextValue::Dict(pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) +/// A dictionary value with these keys, for the built-in defaults. +fn dict(pairs: Vec<(&'static str, V<'static>)>) -> V<'static> { + V::Dict(pairs.into_iter().map(|(k, v)| (Cow::Borrowed(k), v)).collect()) } -fn numbers(v: &[f64]) -> TextValue { - TextValue::Array(v.iter().map(|x| val(*x)).collect()) +/// An array of numbers, for the built-in defaults. +fn numbers(v: &[f64]) -> V<'static> { + V::Array(v.iter().map(|x| val(*x)).collect()) } /// The default of every run style slot that is not decoded and not neutral (zero, `false`, /// empty, `/nil`): the value an untouched point text holds in every sample (110, 243-245). A slot /// with a neutral default is left out; [`undecoded_fields`] treats a missing default as neutral. -fn style_defaults() -> TextValue { - let paint = - |a: f64| dict(vec![("99", TextValue::Name("SimplePaint".into())), ("0", dict(vec![("0", val(1.0)), ("1", numbers(&[1.0, 1.0, 1.0, a]))]))]); - let class = |name: &str| dict(vec![("99", TextValue::Name(name.into()))]); +/// Built once. +static STYLE_DEFAULTS: LazyLock> = LazyLock::new(|| { + let paint = |a: f64| dict(vec![("99", V::Name(b"SimplePaint")), ("0", dict(vec![("0", val(1.0)), ("1", numbers(&[1.0, 1.0, 1.0, a]))]))]); + let class = |name: &'static [u8]| dict(vec![("99", V::Name(name))]); dict(vec![ ("37", val(2.0)), ("41", val(2.0)), @@ -269,24 +403,24 @@ fn style_defaults() -> TextValue { ("46", val(7.0)), ("49", val(-1.0)), ("50", val(-1.0)), - ("55", class("SimpleBlender")), + ("55", class(b"SimpleBlender")), ("64", val(4.0)), ("71", val(4.0)), - ("77", TextValue::Bool(true)), - ("78", TextValue::Bool(true)), + ("77", V::Bool(true)), + ("78", V::Bool(true)), ("79", paint(0.0)), ("82", val(3.0)), ("83", val(3.0)), - ("86", class("SimpleCustomFeature")), + ("86", class(b"SimpleCustomFeature")), ("87", val(100.0)), - ("88", TextValue::Bool(true)), + ("88", V::Bool(true)), ("95", dict(vec![("0", val(0.0)), ("1", val(0.0))])), - ("96", TextValue::Bool(true)), + ("96", V::Bool(true)), ]) -} +}); -/// The same for the paragraph slots (110, 243-245). -fn paragraph_defaults() -> TextValue { +/// The same for the paragraph slots (110, 243-245). Built once. +static PARAGRAPH_DEFAULTS: LazyLock> = LazyLock::new(|| { dict(vec![ ("6", val(1.0)), ("7", val(1.2)), @@ -294,30 +428,35 @@ fn paragraph_defaults() -> TextValue { ("11", val(2.0)), ("12", val(2.0)), ("14", val(36.0)), - ("15", TextValue::Bool(true)), + ("15", V::Bool(true)), ("16", val(0.5)), ("17", numbers(&[0.8, 1.0, 1.33])), ("18", numbers(&[0.0, 0.0, 0.0])), ("19", numbers(&[1.0, 1.0, 1.0])), ("20", val(6.0)), ("22", val(1.0)), - ("23", TextValue::Bool(true)), + ("23", V::Bool(true)), ("24", val(1.0)), - ("26", TextValue::Bool(true)), + ("26", V::Bool(true)), ("31", val(36.0)), ("35", val(1.0)), ("40", val(2.0)), ]) -} +}); -/// Equal values; numbers compare by value (`0` equals `0.0`). -fn same(a: &TextValue, b: &TextValue) -> bool { +/// Equal values; numbers compare by value (`0` equals `0.0`), names and words by their text, +/// strings by their decoded text. +fn same(a: &V<'_>, b: &V<'_>) -> bool { match (a, b) { - (TextValue::Dict(x), TextValue::Dict(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.iter().any(|(k2, v2)| k == k2 && same(v, v2))), - (TextValue::Array(x), TextValue::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)), + (V::Dict(x), V::Dict(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.iter().any(|(k2, v2)| k == k2 && same(v, v2))), + (V::Array(x), V::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)), + (V::Str(x), V::Str(y)) => x == y || decode_utf16be(x) == decode_utf16be(y), + (V::Bytes(x), V::Bytes(y)) => x == y, + (V::Name(x), V::Name(y)) | (V::Token(x), V::Token(y)) => x == y || text(x) == text(y), + (V::Bool(x), V::Bool(y)) => x == y, _ => match (a.as_f64(), b.as_f64()) { (Some(p), Some(q)) => p == q, - _ => a == b, + _ => false, }, } } @@ -326,12 +465,12 @@ fn same(a: &TextValue, b: &TextValue) -> bool { /// listed when it holds something else (a neutral value carries nothing that could be lost). /// `/nil` is how an untouched document stores a slot without a value (244: paragraph `/27`, `/28`, /// `/36`). -fn is_neutral(v: &TextValue) -> bool { +fn is_neutral(v: &V<'_>) -> bool { match v { - TextValue::Name(n) => n == "nil", - TextValue::Bool(b) => !b, - TextValue::Array(a) => a.is_empty(), - TextValue::Dict(d) => d.is_empty(), + V::Name(n) => *n == b"nil", + V::Bool(b) => !b, + V::Array(a) => a.is_empty(), + V::Dict(d) => d.is_empty(), other => other.as_f64() == Some(0.0), } } @@ -356,13 +495,13 @@ pub const MAX_UNDECODED_FIELDS: usize = 64; /// Adds to `out` the slots of `actual` that are not decoded and differ from `sampled`, each once /// and at most [`MAX_UNDECODED_FIELDS`] in all. -fn undecoded_fields(actual: &TextValue, sampled: Option<&TextValue>, decoded: &[&str], neutral: &[(&str, &[i64])], out: &mut Vec) { - let TextValue::Dict(pairs) = actual else { return }; +fn undecoded_fields(actual: &V<'_>, sampled: Option<&V<'_>>, decoded: &[&str], neutral: &[(&str, &[i64])], out: &mut Vec) { + let V::Dict(pairs) = actual else { return }; for (key, value) in pairs { if out.len() >= MAX_UNDECODED_FIELDS { return; } - if decoded.contains(&key.as_str()) || out.contains(key) { + if decoded.contains(&key.as_ref()) || out.iter().any(|o| o == key) { continue; } if neutral.iter().any(|(slot, values)| slot == key && value.as_i64().is_some_and(|v| values.contains(&v))) { @@ -373,7 +512,7 @@ fn undecoded_fields(actual: &TextValue, sampled: Option<&TextValue>, decoded: &[ None => !is_neutral(value), }; if differs { - out.push(key.clone()); + out.push(key.to_string()); } } } @@ -433,13 +572,13 @@ pub struct KernRun { /// The manual kerning list of a text run dictionary (`RUN/8/0`): entries `<< /0 << /0 amount >> /1 /// length >>` (554 kerns each of `HHHH` by 50; the closing `\r` has an entry without an amount). -fn kern_runs(run: &TextValue) -> Vec { - let Some(TextValue::Array(items)) = run.get("8").and_then(|v| v.get("0")) else { return Vec::new() }; +fn kern_runs(run: &V<'_>) -> Vec { + let Some(V::Array(items)) = run.get("8").and_then(|v| v.get("0")) else { return Vec::new() }; let runs: Vec = items .iter() .filter_map(|e| { let length = e.get("1").and_then(usize_of)?; - let amount = e.get("0").and_then(|v| v.get("0")).and_then(TextValue::as_f64).filter(|v| v.is_finite()); + let amount = e.get("0").and_then(|v| v.get("0")).and_then(V::as_f64).filter(|v| v.is_finite()); Some(KernRun { length, amount }) }) .collect(); @@ -602,7 +741,7 @@ pub struct StyleRun { impl StyleRun { /// The style of the sampled untouched document (244), used for a damaged first run. - pub(crate) const SAMPLED: StyleRun = StyleRun { + pub const SAMPLED: StyleRun = StyleRun { length: 0, font_size: 100.0, fill_argb: [1.0; 4], @@ -645,24 +784,26 @@ pub struct TextBox { pub height: f64, } -fn colour_of(style: &TextValue, slot: &str) -> Option<[f64; 4]> { +/// The RGBA colour in a style slot (`slot/0/1`), `None` when it is not four numbers. +fn colour_of(style: &V<'_>, slot: &str) -> Option<[f64; 4]> { let c = style.get(slot)?.get("0")?.get("1")?; Some([c.at(0)?.as_f64()?, c.at(1)?.as_f64()?, c.at(2)?.as_f64()?, c.at(3)?.as_f64()?]) } -fn usize_of(v: &TextValue) -> Option { +/// A non-negative integer value as `usize`. +fn usize_of(v: &V<'_>) -> Option { usize::try_from(v.as_i64()?).ok() } /// A finite number slot of a style, `default` when it is missing or not a finite number. -fn num(style: &TextValue, slot: &str, default: f64) -> f64 { - style.get(slot).and_then(TextValue::as_f64).filter(|v| v.is_finite()).unwrap_or(default) +fn num(style: &V<'_>, slot: &str, default: f64) -> f64 { + style.get(slot).and_then(V::as_f64).filter(|v| v.is_finite()).unwrap_or(default) } /// A boolean slot of a style, `default` when it is missing or not a boolean. -fn flag(style: &TextValue, slot: &str, default: bool) -> bool { +fn flag(style: &V<'_>, slot: &str, default: bool) -> bool { match style.get(slot) { - Some(TextValue::Bool(b)) => *b, + Some(V::Bool(b)) => *b, _ => default, } } @@ -676,9 +817,9 @@ struct RunNotes { } /// The paragraph runs of a text run dictionary (`RUN/5/0`). -fn paragraph_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { - let Some(TextValue::Array(items)) = run.get("5").and_then(|v| v.get("0")) else { return Vec::new() }; - let sampled = Some(paragraph_defaults()); +fn paragraph_runs(run: &V<'_>, notes: &mut RunNotes) -> Vec { + let Some(V::Array(items)) = run.get("5").and_then(|v| v.get("0")) else { return Vec::new() }; + let sampled = Some(&*PARAGRAPH_DEFAULTS); let mut out: Vec = Vec::with_capacity(items.len()); for e in items { let Some(length) = e.get("1").and_then(usize_of) else { @@ -686,7 +827,7 @@ fn paragraph_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { continue; }; let para = e.get("0").and_then(|v| v.get("0")).and_then(|v| v.get("5")); - let justification = match para.and_then(|p| p.get("0")).and_then(TextValue::as_i64) { + let justification = match para.and_then(|p| p.get("0")).and_then(V::as_i64) { Some(0) => Justification::Left, Some(1) => Justification::Right, Some(2) => Justification::Center, @@ -701,12 +842,12 @@ fn paragraph_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { } }; if let Some(p) = para { - undecoded_fields(p, sampled.as_ref(), DECODED_PARAGRAPH_SLOTS, NEUTRAL_PARAGRAPH_VALUES, &mut notes.paragraph_fields); + undecoded_fields(p, sampled, DECODED_PARAGRAPH_SLOTS, NEUTRAL_PARAGRAPH_VALUES, &mut notes.paragraph_fields); } - let num = |slot: &str| para.and_then(|p| p.get(slot)).and_then(TextValue::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0); - let int = |slot: &str, default: i64| para.and_then(|p| p.get(slot)).and_then(TextValue::as_i64).unwrap_or(default); + let num = |slot: &str| para.and_then(|p| p.get(slot)).and_then(V::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0); + let int = |slot: &str, default: i64| para.and_then(|p| p.get(slot)).and_then(V::as_i64).unwrap_or(default); let flag = |slot: &str, default: bool| match para.and_then(|p| p.get(slot)) { - Some(TextValue::Bool(b)) => *b, + Some(V::Bool(b)) => *b, _ => default, }; out.push(ParagraphRun { @@ -728,9 +869,9 @@ fn paragraph_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { } /// The style runs of a text run dictionary (`RUN/6/0`). -fn style_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { - let Some(TextValue::Array(items)) = run.get("6").and_then(|v| v.get("0")) else { return Vec::new() }; - let sampled = Some(style_defaults()); +fn style_runs(run: &V<'_>, notes: &mut RunNotes) -> Vec { + let Some(V::Array(items)) = run.get("6").and_then(|v| v.get("0")) else { return Vec::new() }; + let sampled = Some(&*STYLE_DEFAULTS); let mut out: Vec = Vec::with_capacity(items.len()); for e in items { let Some(length) = e.get("1").and_then(usize_of) else { @@ -743,31 +884,31 @@ fn style_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { out.push(StyleRun { length, ..prev }); continue; }; - let font_size = style.get("1").and_then(TextValue::as_f64); + let font_size = style.get("1").and_then(V::as_f64); let fill_argb = colour_of(style, "53"); let font_index = style.get("0").and_then(usize_of); if font_size.is_none() || fill_argb.is_none() || font_index.is_none() { notes.incomplete = notes.incomplete.saturating_add(1); } - undecoded_fields(style, sampled.as_ref(), DECODED_STYLE_SLOTS, NEUTRAL_STYLE_VALUES, &mut notes.style_fields); + undecoded_fields(style, sampled, DECODED_STYLE_SLOTS, NEUTRAL_STYLE_VALUES, &mut notes.style_fields); out.push(StyleRun { length, font_size: font_size.unwrap_or(prev.font_size), fill_argb: fill_argb.unwrap_or(prev.fill_argb), stroke_argb: colour_of(style, "54"), - tracking: style.get("8").and_then(TextValue::as_f64).unwrap_or(0.0), - faux_bold: matches!(style.get("2"), Some(TextValue::Bool(true))), - faux_italic: matches!(style.get("3"), Some(TextValue::Bool(true))), - caps: match style.get("12").and_then(TextValue::as_i64) { + tracking: style.get("8").and_then(V::as_f64).unwrap_or(0.0), + faux_bold: matches!(style.get("2"), Some(V::Bool(true))), + faux_italic: matches!(style.get("3"), Some(V::Bool(true))), + caps: match style.get("12").and_then(V::as_i64) { None | Some(0) => Caps::Normal, Some(1) => Caps::Small, Some(2) => Caps::All, Some(other) => Caps::Other(other), }, - auto_leading: matches!(style.get("4"), Some(TextValue::Bool(true))), - leading: style.get("5").and_then(TextValue::as_f64), + auto_leading: matches!(style.get("4"), Some(V::Bool(true))), + leading: style.get("5").and_then(V::as_f64), font_index: font_index.unwrap_or(prev.font_index), - baseline: match style.get("13").and_then(TextValue::as_i64) { + baseline: match style.get("13").and_then(V::as_i64) { None | Some(0) => FontBaseline::Normal, Some(1) => FontBaseline::Superscript, Some(2) => FontBaseline::Subscript, @@ -776,22 +917,22 @@ fn style_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { horizontal_scale: num(style, "6", 1.0), vertical_scale: num(style, "7", 1.0), baseline_shift: num(style, "9", 0.0), - auto_kern: match style.get("11").and_then(TextValue::as_i64) { + auto_kern: match style.get("11").and_then(V::as_i64) { Some(0) => AutoKern::None, None | Some(1) => AutoKern::Metrics, Some(2) => AutoKern::Optical, Some(other) => AutoKern::Other(other), }, ligatures: flag(style, "18", false), - baseline_direction: style.get("35").and_then(TextValue::as_i64).unwrap_or(1), + baseline_direction: style.get("35").and_then(V::as_i64).unwrap_or(1), tsume: num(style, "36", 0.0), no_break: flag(style, "52", false), apply_fill: flag(style, "56", true), apply_stroke: flag(style, "57", false), stroke_over_fill: flag(style, "58", true), - line_join: style.get("62").and_then(TextValue::as_i64).unwrap_or(0), + line_join: style.get("62").and_then(V::as_i64).unwrap_or(0), stroke_width: num(style, "63", 1.0), - digit_set: style.get("70").and_then(TextValue::as_i64).unwrap_or(0), + digit_set: style.get("70").and_then(V::as_i64).unwrap_or(0), }); } out @@ -799,13 +940,13 @@ fn style_runs(run: &TextValue, notes: &mut RunNotes) -> Vec { /// The box of paragraph text from the frame dictionary `/0/8/0[0]/0`: key `/1/0` holds 16 x, y pairs /// that trace the rectangle, and `/2/0` is 1; both keys are absent for point text. -fn text_box(top: &TextValue) -> Option { +fn text_box(top: &V<'_>) -> Option { let frame = top.get("0")?.get("8")?.get("0")?.at(0)?.get("0")?; if frame.get("2")?.get("0")?.as_i64()? != 1 { return None; } - let TextValue::Array(coords) = frame.get("1")?.get("0")? else { return None }; - let numbers: Vec = coords.iter().map(TextValue::as_f64).collect::>()?; + let V::Array(coords) = frame.get("1")?.get("0")? else { return None }; + let numbers: Vec = coords.iter().map(V::as_f64).collect::>()?; let (pairs, _) = numbers.as_chunks::<2>(); if pairs.is_empty() { return None; @@ -819,18 +960,16 @@ fn text_box(top: &TextValue) -> Option { impl TextDocument { /// Decodes the body of a `btdk` list. pub fn parse(body: &[u8]) -> Option { - let top = parse_text_dict(body); + let top = parse_dict(body); let run = top.get("1")?.get("1")?.at(0)?.get("0")?; - let raw_text = run.get("0")?.as_str()?.to_string(); + let raw_text = run.get("0")?.string()?; let style = run.get("6")?.get("0")?.at(0)?.get("0")?.get("0")?.get("6")?; let fill_argb = colour_of(style, "53")?; let font_index = usize::try_from(style.get("0")?.as_i64()?).ok()?; let mut fonts = Vec::new(); - if let Some(TextValue::Array(list)) = top.get("0").and_then(|v| v.get("1")).and_then(|v| v.get("0")) { - fonts = list - .iter() - .map(|f| f.get("0").and_then(|v| v.get("0")).and_then(|v| v.get("0")).and_then(TextValue::as_str).unwrap_or_default().to_string()) - .collect(); + if let Some(V::Array(list)) = top.get("0").and_then(|v| v.get("1")).and_then(|v| v.get("0")) { + fonts = + list.iter().map(|f| f.get("0").and_then(|v| v.get("0")).and_then(|v| v.get("0")).and_then(V::string).unwrap_or_default()).collect(); } let mut notes = RunNotes::default(); let paragraphs = paragraph_runs(run, &mut notes); @@ -858,7 +997,7 @@ impl TextDocument { .and_then(|v| v.get("0")) .and_then(|v| v.get("2")) .and_then(|v| v.get("1")) - .and_then(TextValue::as_i64), + .and_then(V::as_i64), }) } @@ -882,23 +1021,32 @@ impl TextDocument { } impl<'f, 'a> Layer<'f, 'a> { - /// The text document of a text layer (`LIST btdk` below `ADBE Text Properties`). + /// The Source Text record `LIST btds` (`ADBE Text Document`). It is a direct child of the + /// `ADBE Text Properties` group, which is a direct child of the layer's root `tdgp` + /// (`Layr/tdgp/tdgp/btds` in every sample, and where the exporter writes it), so only that + /// level is searched rather than the whole layer. + fn source_text_record(&self) -> Option> { + let root = self.chunk.child_list(b"tdgp")?; + root.children().filter(|g| g.is_list(b"tdgp")).find_map(|g| g.child_list(b"btds")) + } + + /// The text document of a text layer: the first `LIST btdk` in the Source Text record `btds` + /// (the same documents [`Layer::text_document_count`] counts). pub fn text_document(&self) -> Option { - TextDocument::parse(self.chunk.find_list(b"btdk")?.bytes()?) + TextDocument::parse(self.source_text_record()?.find_list(b"btdk")?.bytes()?) } /// The Source Text property record: the `tdbs` in `btds[ADBE Text Document]` (a placeholder /// in every sample: no keys, no expression). Source Text keyframes and expressions were not /// sampled; a `list` (keys) or an expression in it marks them. pub fn source_text_property(&self) -> Option> { - let btds = self.chunk.descendants().map(|(_, c)| c).find(|c| c.is_list(b"btds"))?; - Property::from_chunk(btds.child_list(b"tdbs")?) + Property::from_chunk(self.source_text_record()?.child_list(b"tdbs")?) } - /// The number of text documents (`LIST btdk`) of the layer: 1 in every sample; more would be - /// one per Source Text keyframe (not sampled). + /// The number of text documents (`LIST btdk`) in the Source Text record: 1 in every sample; + /// more would be one per Source Text keyframe (not sampled). pub fn text_document_count(&self) -> usize { - self.chunk.descendants().filter(|(_, c)| c.is_list(b"btdk")).count() + self.source_text_record().map_or(0, |btds| btds.descendants().filter(|(_, c)| c.is_list(b"btdk")).count()) } } @@ -943,10 +1091,24 @@ pub enum CueType { Other(u32), } +impl<'f, 'a> Node<'f, 'a> { + /// The marker list `LIST mrst` of a marker holder: a layer (`LIST Layr`) or a composition's + /// `SecL` list. A layer's `mrst` is a direct child of its root `tdgp` (`ADBE Marker`, where + /// After Effects and the exporter write it), so only that place is looked at; most layers have + /// none, and searching their whole property tree for it was a large part of an import. Any + /// other holder is searched depth-first. + pub fn marker_list(self) -> Option> { + if self.is_list(b"Layr") { + return self.child_list(b"tdgp")?.child_list(b"mrst"); + } + self.find_list(b"mrst") + } +} + /// Reads the markers below `holder` (a layer or the composition's `SecL` list): the `mrst` list has a /// property whose 16-byte records give the times and one `Nmrd` list per marker with the strings. -fn markers_in(holder: &Chunk<'_>) -> Vec { - let Some(mrst) = holder.find_list(b"mrst") else { return Vec::new() }; +fn markers_in(holder: Node<'_, '_>) -> Vec { + let Some(mrst) = holder.marker_list() else { return Vec::new() }; let Some(prop) = mrst.child_list(b"tdbs").and_then(Property::from_chunk) else { return Vec::new() }; let Some(keys) = prop.keys() else { return Vec::new() }; let scale = prop.time_scale().unwrap_or(0); @@ -956,11 +1118,11 @@ fn markers_in(holder: &Chunk<'_>) -> Vec { .filter_map(|(k, nmrd)| { let time_units = k.time_units()?; // The five strings, in the order comment, chapter, URL, frame target, cue point name. - let mut strings = nmrd.children().iter().filter(|c| c.is(b"Utf8")).map(|c| c.bytes().map(text).unwrap_or_default()); + let mut strings = nmrd.children().filter(|c| c.is(b"Utf8")).map(|c| c.bytes().map(text).unwrap_or_default()); let mut next = || strings.next().unwrap_or_default(); let (comment, chapter, url, frame_target, cue_point_name) = (next(), next(), next(), next(), next()); let extras: Vec = strings.collect(); - let header = nmrd.child(b"NmHd").and_then(Chunk::bytes); + let header = nmrd.child(b"NmHd").and_then(Node::bytes); let duration_seconds = header.and_then(|h| { let (duration, per_second) = (be_u32(h, 8)?, be_u32(h, 12)?); (per_second != 0).then(|| f64::from(duration) / f64::from(per_second)) @@ -1003,9 +1165,647 @@ impl<'f, 'a> Comp<'f, 'a> { } } +/// The dictionary parser and the defaults as they were before they borrowed from the body (#3276), +/// kept as the reference the differential tests compare with. +#[cfg(test)] +mod oracle { + use super::{MAX_DEPTH, MAX_UNDECODED_FIELDS, TextValue}; + use crate::bytes::text; + + pub(super) fn same(a: &TextValue, b: &TextValue) -> bool { + match (a, b) { + (TextValue::Dict(x), TextValue::Dict(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.iter().any(|(k2, v2)| k == k2 && same(v, v2))), + (TextValue::Array(x), TextValue::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)), + _ => match (a.as_f64(), b.as_f64()) { + (Some(p), Some(q)) => p == q, + _ => a == b, + }, + } + } + + pub(super) fn is_neutral(v: &TextValue) -> bool { + match v { + TextValue::Name(n) => n == "nil", + TextValue::Bool(b) => !b, + TextValue::Array(a) => a.is_empty(), + TextValue::Dict(d) => d.is_empty(), + other => other.as_f64() == Some(0.0), + } + } + + pub(super) fn undecoded_fields( + actual: &TextValue, + sampled: Option<&TextValue>, + decoded: &[&str], + neutral: &[(&str, &[i64])], + out: &mut Vec, + ) { + let TextValue::Dict(pairs) = actual else { return }; + for (key, value) in pairs { + if out.len() >= MAX_UNDECODED_FIELDS { + return; + } + if decoded.contains(&key.as_str()) || out.contains(key) { + continue; + } + if neutral.iter().any(|(slot, values)| slot == key && value.as_i64().is_some_and(|v| values.contains(&v))) { + continue; + } + let differs = match sampled.and_then(|s| s.get(key)) { + Some(default) => !same(value, default), + None => !is_neutral(value), + }; + if differs { + out.push(key.clone()); + } + } + } + + impl TextValue { + /// The canonical text of a key, as the owning parser built it. + fn key_text(&self) -> String { + match self { + Self::Name(s) | Self::Str(s) | Self::Token(s) => s.clone(), + Self::Int(i) => i.to_string(), + Self::Float(f) => f.to_string(), + Self::Bool(b) => b.to_string(), + Self::Bytes(b) => text(b), + Self::Dict(_) | Self::Array(_) => String::new(), + } + } + } + + struct Parser<'b> { + b: &'b [u8], + i: usize, + } + + /// Whitespace between tokens. + fn is_ws(c: u8) -> bool { + matches!(c, b' ' | b'\t' | b'\r' | b'\n') + } + + /// A byte that ends a bare word. + fn is_delimiter(c: u8) -> bool { + is_ws(c) || matches!(c, b'/' | b'[' | b']' | b'<' | b'>' | b'(' | b')') + } + + impl Parser<'_> { + /// The next byte, `None` at the end. + fn peek(&self) -> Option { + self.b.get(self.i).copied() + } + + /// Moves past whitespace. + fn skip_ws(&mut self) { + while self.peek().is_some_and(is_ws) { + self.i = self.i.saturating_add(1); + } + } + + /// True when the unread bytes start with `s`. + fn starts_with(&self, s: &[u8]) -> bool { + self.b.get(self.i..).is_some_and(|rest| rest.starts_with(s)) + } + + /// The bare word at the position (up to the next delimiter), borrowed from the body. + fn word(&mut self) -> &[u8] { + let start = self.i; + while self.peek().is_some_and(|c| !is_delimiter(c)) { + self.i = self.i.saturating_add(1); + } + self.b.get(start..self.i).unwrap_or(&[]) + } + + /// The value at the position, `None` when it is malformed or nested deeper than the limit. + fn parse(&mut self, depth: usize) -> Option { + self.skip_ws(); + if depth > MAX_DEPTH { + return None; + } + if self.starts_with(b"<<") { + self.i = self.i.saturating_add(2); + let mut pairs = Vec::new(); + loop { + self.skip_ws(); + if self.starts_with(b">>") { + self.i = self.i.saturating_add(2); + return Some(TextValue::Dict(pairs)); + } + let key = self.parse(depth.saturating_add(1))?; + let value = self.parse(depth.saturating_add(1))?; + pairs.push((key.key_text(), value)); + } + } + match self.peek()? { + b'[' => { + self.i = self.i.saturating_add(1); + let mut items = Vec::new(); + loop { + self.skip_ws(); + if self.peek()? == b']' { + self.i = self.i.saturating_add(1); + return Some(TextValue::Array(items)); + } + items.push(self.parse(depth.saturating_add(1))?); + } + } + b'(' => { + self.i = self.i.saturating_add(1); + let mut out = Vec::new(); + loop { + let c = self.peek()?; + if c == b'\\' { + out.push(*self.b.get(self.i.saturating_add(1))?); + self.i = self.i.saturating_add(2); + } else if c == b')' { + self.i = self.i.saturating_add(1); + break; + } else { + out.push(c); + self.i = self.i.saturating_add(1); + } + } + Some(match out.strip_prefix(&[0xfe, 0xff]) { + Some(utf16) => TextValue::Str(decode_utf16be(utf16)), + None => TextValue::Bytes(out), + }) + } + b'/' => { + self.i = self.i.saturating_add(1); + Some(TextValue::Name(text(self.word()))) + } + _ => { + let word = self.word(); + if word.is_empty() { + return None; + } + let w = text(word); + Some(match w.as_str() { + "true" => TextValue::Bool(true), + "false" => TextValue::Bool(false), + _ => match w.parse::() { + Ok(i) => TextValue::Int(i), + // `parse` also takes `nan`, `inf` and overflowing exponents; those are not + // numbers a text document holds, so they stay tokens and read as missing. + Err(_) => match w.parse::() { + Ok(f) if f.is_finite() => TextValue::Float(f), + _ => TextValue::Token(w), + }, + }, + }) + } + } + } + } + + /// A big-endian UTF-16 string as text (unpaired surrogates become U+FFFD). + fn decode_utf16be(bytes: &[u8]) -> String { + let (pairs, rest) = bytes.as_chunks::<2>(); + let units = pairs.iter().map(|p| u16::from_be_bytes(*p)); + let mut s: String = char::decode_utf16(units).map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)).collect(); + if !rest.is_empty() { + s.push(char::REPLACEMENT_CHARACTER); + } + s + } + + /// Parses the body of a `btdk` list into its top-level `key value` pairs (as a [`TextValue::Dict`]). + /// Parsing stops silently at the first syntax error or at nesting deeper than 64 levels; what was + /// read before is returned. + pub(super) fn parse_text_dict(body: &[u8]) -> TextValue { + let mut parser = Parser { b: body, i: 0 }; + let mut pairs = Vec::new(); + loop { + parser.skip_ws(); + if parser.i >= body.len() { + break; + } + let Some(key) = parser.parse(0) else { break }; + let Some(value) = parser.parse(0) else { break }; + pairs.push((key.key_text(), value)); + } + TextValue::Dict(pairs) + } + + fn val(v: f64) -> TextValue { + TextValue::Float(v) + } + + /// A dictionary value with these keys, for the built-in defaults. + fn dict(pairs: Vec<(&str, TextValue)>) -> TextValue { + TextValue::Dict(pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) + } + + /// An array of numbers, for the built-in defaults. + fn numbers(v: &[f64]) -> TextValue { + TextValue::Array(v.iter().map(|x| val(*x)).collect()) + } + + /// The default of every run style slot that is not decoded and not neutral (zero, `false`, + /// empty, `/nil`): the value an untouched point text holds in every sample (110, 243-245). A slot + /// with a neutral default is left out; [`undecoded_fields`] treats a missing default as neutral. + pub(super) fn style_defaults() -> TextValue { + let paint = |a: f64| { + dict(vec![("99", TextValue::Name("SimplePaint".into())), ("0", dict(vec![("0", val(1.0)), ("1", numbers(&[1.0, 1.0, 1.0, a]))]))]) + }; + let class = |name: &str| dict(vec![("99", TextValue::Name(name.into()))]); + dict(vec![ + ("37", val(2.0)), + ("41", val(2.0)), + ("43", dict(vec![("0", val(0.5))])), + ("44", val(2.0)), + ("45", val(2.0)), + ("46", val(7.0)), + ("49", val(-1.0)), + ("50", val(-1.0)), + ("55", class("SimpleBlender")), + ("64", val(4.0)), + ("71", val(4.0)), + ("77", TextValue::Bool(true)), + ("78", TextValue::Bool(true)), + ("79", paint(0.0)), + ("82", val(3.0)), + ("83", val(3.0)), + ("86", class("SimpleCustomFeature")), + ("87", val(100.0)), + ("88", TextValue::Bool(true)), + ("95", dict(vec![("0", val(0.0)), ("1", val(0.0))])), + ("96", TextValue::Bool(true)), + ]) + } + + /// The same for the paragraph slots (110, 243-245). + pub(super) fn paragraph_defaults() -> TextValue { + dict(vec![ + ("6", val(1.0)), + ("7", val(1.2)), + ("10", val(6.0)), + ("11", val(2.0)), + ("12", val(2.0)), + ("14", val(36.0)), + ("15", TextValue::Bool(true)), + ("16", val(0.5)), + ("17", numbers(&[0.8, 1.0, 1.33])), + ("18", numbers(&[0.0, 0.0, 0.0])), + ("19", numbers(&[1.0, 1.0, 1.0])), + ("20", val(6.0)), + ("22", val(1.0)), + ("23", TextValue::Bool(true)), + ("24", val(1.0)), + ("26", TextValue::Bool(true)), + ("31", val(36.0)), + ("35", val(1.0)), + ("40", val(2.0)), + ]) + } +} + #[cfg(test)] mod tests { use super::*; + use crate::Chunk; + + /// A `LIST` of this type holding `kids`. + fn list(t: &[u8; 4], kids: Vec>) -> Chunk<'static> { + Chunk::list(*t, kids) + } + + /// A document with every kind of value, close to what After Effects writes: names, numbers, + /// a UTF-16 string with escapes, a plain string, nested dictionaries and arrays, an undecoded + /// style slot, a font list and a box frame. + const DOC: &[u8] = b"/0 << /1 << /0 [ << /0 << /0 << /0 (\xfe\xff\0M\0y\0r) >> /1 1 >> >> << /0 << /0 << /0 (\xfe\xff\0A\0\\)\0b) >> >> >> ] >> \ + /8 << /0 [ << /0 << /1 << /0 [ 0 0 10 0 10 5 0 5 ] >> /2 << /0 1 /1 2 >> >> >> ] >> >> \ + /1 << /1 [ << /0 << /0 (\xfe\xff\0H\0i\0\r) /5 << /0 [ << /0 << /0 << /5 << /0 2 /9 false /24 0 /34 7 /17 [ .8 1.0 1.33 ] >> >> >> /1 3 >> ] >> \ + /6 << /0 [ << /0 << /0 << /6 << /0 1 /1 36.5 /53 << /0 << /0 1 /1 [ 1 0.5 0 1 ] >> >> /79 << /99 /SimplePaint /0 << /0 1 /1 [ 1 1 1 0 ] >> >> /68 1 /90 /x /91 (plain) /92 word >> >> >> /1 3 >> ] >> \ + /8 << /0 [ << /0 << /0 50 >> /1 2 >> << /1 1 >> ] >> >> >> ] >>"; + + /// A deterministic xorshift generator: the tests need varied input, not a dependency. + struct Rng(u64); + + impl Rng { + /// The next pseudo-random number (xorshift). + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + /// A number below `n` (0 for `n == 0`). + fn below(&mut self, n: usize) -> usize { + usize::try_from(self.next() % (n as u64)).unwrap_or(0) + } + } + + /// The borrowing parser reads what the owning one read. + #[test] + fn the_borrowing_parser_reads_what_the_owning_one_read() { + // Every key form the owned keys canonicalise (`06`, `+6`, `-0`, `1.0`, `1e2`, strings, + // booleans, containers), names that are not UTF-8, escapes, unclosed strings and escapes, + // non-finite numbers, and bare words. + let parts: &[&[u8]] = &[ + b"<<", + b">>", + b"[", + b"]", + b"/0", + b"/1", + b"/nil", + b"/SimplePaint", + b"/\xff\xfe", + b"/\xc3\xa9", + b"/", + b"06", + b"+6", + b"-0", + b"1.0", + b"1.50", + b"1e2", + b"-2.5", + b".8", + b"inf", + b"nan", + b"1e999", + b"9223372036854775808", + b"true", + b"false", + b"(abc)", + b"(\xfe\xff\0A\0B)", + b"(\xfe\xff\0A\0)", + b"(a\\)b)", + b"(\\", + b"(\xfe\xff\\)\0)", + b"(\\\xfe\xff\0C)", + b"()", + b"(\xfe\xff)", + b"(unclosed", + b"word", + b"\xc3\x28", + b"\xff", + b" ", + b"\n", + b"\t\r", + b"<", + b">", + b")", + ]; + // A value: mostly well formed, with a random part in its place now and then. + /// Appends one generated value to `out`: mostly well formed, now and then a random part. + fn value(rng: &mut Rng, parts: &[&[u8]], depth: usize, out: &mut Vec) { + let pick = |rng: &mut Rng| parts.get(rng.below(parts.len())).copied().unwrap_or_default(); + match rng.below(if depth > 6 { 5 } else { 10 }) { + 0 => out.extend_from_slice(pick(rng)), + 1..=4 => out.extend_from_slice([&b"/0"[..], b"1", b"(\xfe\xff\0z)", b"0.5", b"/nil"].get(rng.below(5)).copied().unwrap_or_default()), + 5..=7 => { + out.extend_from_slice(b"<< "); + for _ in 0..rng.below(5) { + let key = if rng.below(4) == 0 { + pick(rng) + } else { + [&b"/0"[..], b"/1", b"/6", b"/53"].get(rng.below(4)).copied().unwrap_or_default() + }; + out.extend_from_slice(key); + out.push(b' '); + value(rng, parts, depth + 1, out); + out.push(b' '); + } + if rng.below(20) != 0 { + out.extend_from_slice(b">>"); + } + } + _ => { + out.extend_from_slice(b"[ "); + for _ in 0..rng.below(5) { + value(rng, parts, depth + 1, out); + out.push(b' '); + } + if rng.below(20) != 0 { + out.push(b']'); + } + } + } + } + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let (mut read, mut nested) = (0, 0); + for case in 0..40_000 { + let mut body = Vec::new(); + if case % 2 == 0 { + for _ in 0..rng.below(60) { + body.extend_from_slice(parts.get(rng.below(parts.len())).copied().unwrap_or_default()); + if rng.below(3) != 0 { + body.push(b' '); + } + } + } else { + for _ in 0..1 + rng.below(4) { + body.extend_from_slice(b"/0 "); + value(&mut rng, parts, 0, &mut body); + body.push(b'\n'); + } + } + let parsed = parse_text_dict(&body); + assert_eq!(parsed, oracle::parse_text_dict(&body), "case {case}: {}", String::from_utf8_lossy(&body)); + let _ = TextDocument::parse(&body); + if let TextValue::Dict(pairs) = &parsed { + read += usize::from(!pairs.is_empty()); + nested += usize::from(pairs.iter().any(|(_, v)| matches!(v, TextValue::Dict(d) if !d.is_empty()))); + } + } + // The input is not all rejected at the first token. + assert!(read > 25_000 && nested > 3_000, "{read} cases read something, {nested} a dictionary"); + // Every cut of a realistic document, and nesting past the limit. + for end in 0..=DOC.len() { + let body = DOC.get(..end).unwrap_or_default(); + assert_eq!(parse_text_dict(body), oracle::parse_text_dict(body), "cut at {end}"); + let _ = TextDocument::parse(body); + } + for depth in [63, 64, 65, 66, 200] { + let body = [b"/k ".to_vec(), b"<< /a ".repeat(depth), b"1".to_vec(), b" >>".repeat(depth), b" /z 2".to_vec()].concat(); + assert_eq!(parse_text_dict(&body), oracle::parse_text_dict(&body), "depth {depth}"); + let body = [b"/k ".to_vec(), b"[ ".repeat(depth), b"]".repeat(depth)].concat(); + assert_eq!(parse_text_dict(&body), oracle::parse_text_dict(&body), "array depth {depth}"); + } + // Dictionaries and arrays mixed (`<< /a [ << /a [ ...`), closed, and left open exactly + // at the limit. + for depth in 60..=68 { + let open: Vec = (0..depth).flat_map(|i| if i % 2 == 0 { &b"<< /a "[..] } else { &b"[ "[..] }).copied().collect(); + let close: Vec = (0..depth).rev().flat_map(|i| if i % 2 == 0 { &b" >>"[..] } else { &b" ]"[..] }).copied().collect(); + for body in + [[b"/k ".to_vec(), open.clone(), b"1".to_vec(), close, b" /z 2".to_vec()].concat(), [b"/k ".to_vec(), open, b"1".to_vec()].concat()] + { + assert_eq!(parse_text_dict(&body), oracle::parse_text_dict(&body), "mixed depth {depth}"); + let _ = TextDocument::parse(&body); + } + } + } + + /// A realistic document is read in full. + #[test] + fn a_realistic_document_is_read_in_full() { + let doc = TextDocument::parse(DOC).expect("a document"); + assert_eq!((doc.text.as_str(), doc.font_size, doc.fill_argb, doc.font.as_deref()), ("Hi", 36.5, [1.0, 0.5, 0.0, 1.0], Some("A)b"))); + assert_eq!(doc.fonts, ["Myr", "A)b"]); + assert_eq!(doc.paragraphs.first().map(|p| (p.length, p.justification, p.auto_hyphenate)), Some((3, Justification::Center, false))); + // `/68 1` and `/34 7` are neutral; `/90 /x`, `/91 (plain)` and `/92 word` differ from the + // (missing, neutral) default; `/79` equals its default. + assert_eq!(doc.undecoded_style_fields, ["90", "91", "92"]); + assert!(doc.undecoded_paragraph_fields.is_empty()); + assert_eq!(doc.kerning, [KernRun { length: 2, amount: Some(50.0) }, KernRun { length: 1, amount: None }]); + assert_eq!(doc.text_box, Some(TextBox { x: 0.0, y: 0.0, width: 10.0, height: 5.0 })); + assert_eq!(doc.line_orientation, Some(2)); + } + + /// The defaults are the sampled ones and built once. + #[test] + fn the_defaults_are_the_sampled_ones_and_built_once() { + assert_eq!(STYLE_DEFAULTS.clone().into_owned(), oracle::style_defaults()); + assert_eq!(PARAGRAPH_DEFAULTS.clone().into_owned(), oracle::paragraph_defaults()); + assert!(std::ptr::eq(&*STYLE_DEFAULTS, &*STYLE_DEFAULTS)); + } + + /// Names keys and strings are borrowed from the body. + #[test] + fn names_keys_and_strings_are_borrowed_from_the_body() { + let V::Dict(pairs) = parse_dict(b"/a /b /c (\xfe\xff\0x) /d (plain) /e word /f 1.5 /g (\\(esc) 07 1") else { panic!("a dict") }; + // Every `/name` key, name, string without escapes and bare word points into the body. + assert!(pairs.iter().take(6).all(|(k, _)| matches!(k, Cow::Borrowed(_)))); + assert!(matches!(pairs.first().map(|p| &p.1), Some(V::Name(b"b")))); + assert!(matches!(pairs.get(1).map(|p| &p.1), Some(V::Str(Cow::Borrowed(b"\0x"))))); + assert!(matches!(pairs.get(2).map(|p| &p.1), Some(V::Bytes(Cow::Borrowed(b"plain"))))); + assert!(matches!(pairs.get(3).map(|p| &p.1), Some(V::Token(b"word")))); + // An escaped string is copied; a number key is written in its canonical form. + assert!(matches!(pairs.get(5).map(|p| &p.1), Some(V::Bytes(Cow::Owned(b))) if b == b"(esc")); + assert_eq!(pairs.get(6).map(|p| p.0.as_ref()), Some("7")); + // Containers hold what was read. + let V::Dict(outer) = parse_dict(b"/0 << /a 1 /b 2 /c 3 /d 4 /e 5 >> /1 [ 1 2 3 4 5 6 7 8 9 ]") else { panic!("a dict") }; + assert!(matches!(outer.first().map(|p| &p.1), Some(V::Dict(d)) if d.len() == 5 && d.capacity() >= d.len())); + assert!(matches!(outer.get(1).map(|p| &p.1), Some(V::Array(a)) if a.len() == 9 && a.capacity() >= a.len())); + } + + /// Slot checks agree with the owned ones. + #[test] + fn slot_checks_agree_with_the_owned_ones() { + // Slots: defaults, decoded, neutral-listed and unknown ones. Values: each default as + // stored (also as `Int` where it is `2.0`), near misses, neutral values and every kind. + let slots = ["0", "6", "7", "17", "24", "34", "35", "37", "43", "55", "68", "77", "79", "86", "95", "96", "200", "x"]; + let values: &[&[u8]] = &[ + b"2", + b"2.0", + b"7", + b"1", + b"0", + b"-1", + b"0.5", + b"1.2", + b"36", + b"true", + b"false", + b"/nil", + b"/x", + b"/SimpleBlender", + b"[ ]", + b"<< >>", + b"[ .8 1 1.33 ]", + b"[ 0.8 1.0 ]", + b"[ 1 1 1 ]", + b"<< /0 .5 >>", + b"<< /0 0 /1 0 >>", + b"<< /1 0 /0 0 >>", + b"<< /99 /SimpleBlender >>", + b"<< /99 /SimplePaint /0 << /0 1 /1 [ 1 1 1 0 ] >> >>", + b"<< /99 /SimplePaint /0 << /0 1 /1 [ 1 1 1 1 ] >> >>", + b"(plain)", + b"(\xfe\xff\0a)", + b"word", + b"/\xff", + ]; + let mut rng = Rng(0x2545_f491_4f6c_dd1d); + let mut listed = 0; + for case in 0..20_000 { + let mut body = b"/s << ".to_vec(); + for _ in 0..rng.below(12) { + body.push(b'/'); + body.extend_from_slice(slots.get(rng.below(slots.len())).copied().unwrap_or_default().as_bytes()); + body.push(b' '); + body.extend_from_slice(values.get(rng.below(values.len())).copied().unwrap_or_default()); + body.push(b' '); + } + body.extend_from_slice(b">>"); + let (new, old) = (parse_dict(&body), oracle::parse_text_dict(&body)); + let (Some(new), Some(old)) = (new.get("s"), old.get("s")) else { panic!("case {case}: a dict") }; + for (sampled, old_sampled, decoded, neutral) in [ + (&*STYLE_DEFAULTS, oracle::style_defaults(), DECODED_STYLE_SLOTS, NEUTRAL_STYLE_VALUES), + (&*PARAGRAPH_DEFAULTS, oracle::paragraph_defaults(), DECODED_PARAGRAPH_SLOTS, NEUTRAL_PARAGRAPH_VALUES), + ] { + let (mut a, mut b) = (Vec::new(), Vec::new()); + undecoded_fields(new, Some(sampled), decoded, neutral, &mut a); + oracle::undecoded_fields(old, Some(&old_sampled), decoded, neutral, &mut b); + assert_eq!(a, b, "case {case}: {}", String::from_utf8_lossy(&body)); + listed += a.len(); + } + // Every pair of values compares and reads as neutral alike. + if let (V::Dict(x), TextValue::Dict(y)) = (new, old) { + for ((_, p), (_, q)) in x.iter().zip(y) { + assert_eq!(is_neutral(p), oracle::is_neutral(q), "case {case}"); + for ((_, r), (_, t)) in x.iter().zip(y) { + assert_eq!(same(p, r), oracle::same(q, t), "case {case}"); + } + } + } + } + assert!(listed > 10_000, "{listed} slots listed"); + } + + /// Values compare by their text. + #[test] + fn values_compare_by_their_text() { + // Two names that are not UTF-8 read as the same text with replacement characters, as the + // owned values did. + assert!(same(&V::Name(b"\xff"), &V::Name(b"\xfe"))); + assert!(!same(&V::Name(b"a"), &V::Name(b"b"))); + assert!(same(&V::Str(Cow::Borrowed(b"\xd8\x00")), &V::Str(Cow::Owned(b"\xd8\x01".to_vec())))); + assert!(same(&V::Int(0), &V::Float(0.0)) && !same(&V::Int(0), &V::Bool(false)) && !same(&V::Name(b"x"), &V::Token(b"x"))); + assert!( + is_neutral(&V::Name(b"nil")) && !is_neutral(&V::Token(b"nil")) && is_neutral(&V::Float(0.0)) && !is_neutral(&V::Str(Cow::Borrowed(b""))) + ); + } + + /// A layers marker list is the one in its root group. + #[test] + fn a_layers_marker_list_is_the_one_in_its_root_group() { + let marked = |tag: u8| list(b"mrst", vec![Chunk::data(*b"test", vec![tag])]); + // The stored place: `Layr/tdgp/mrst`. + let layer = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![]), marked(1)])]); + assert_eq!(Node::from(&layer).marker_list().and_then(|m| m.child(b"test")).and_then(Node::bytes), Some(&[1u8][..])); + // A list deeper in the layer is not the layer's marker list (the old depth-first search + // found it); a layer without a marker list in its root group has no markers. + let deep = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![marked(2)])])]); + assert!(Node::from(&deep).marker_list().is_none()); + assert!(Layer { chunk: Node::from(&deep) }.markers().is_empty()); + // Any other holder (a composition's `SecL`) is still searched depth-first. + let secl = list(b"SecL", vec![list(b"tdgp", vec![list(b"tdgp", vec![marked(3)])])]); + assert_eq!(Node::from(&secl).marker_list().and_then(|m| m.child(b"test")).and_then(Node::bytes), Some(&[3u8][..])); + } + + /// The source text record is found in the text group. + #[test] + fn the_source_text_record_is_found_in_the_text_group() { + let doc = b"/1 << /1 [ << /0 << /0 (\xfe\xff\0H\0\r) /6 << /0 [ << /0 << /0 << /6 << /0 0 /1 50 /53 << /0 << /1 [ 1 1 0 0 ] >> >> >> >> >> /1 2 >> ] >> >> >> ] >>"; + // `btdk` is an opaque list (its body is not a chunk sequence), as the reader makes it. + let btdk = || Chunk { id: *b"LIST", body: crate::Body::OpaqueList { list_type: *b"btdk", data: doc.to_vec().into() }, pad: None }; + let btds_real = |n: usize| list(b"btds", std::iter::once(list(b"tdbs", vec![])).chain((0..n).map(|_| btdk())).collect()); + let layer = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![]), list(b"tdgp", vec![btds_real(2)])])]); + let view = Layer { chunk: Node::from(&layer) }; + assert_eq!(view.text_document().map(|d| d.text), Some("H".to_string())); + assert!(view.source_text_property().is_some()); + assert_eq!(view.text_document_count(), 2); + // A record anywhere else in the layer is not its Source Text. + let elsewhere = list(b"Layr", vec![list(b"tdgp", vec![list(b"tdgp", vec![list(b"tdgp", vec![btds_real(1)])])])]); + let view = Layer { chunk: Node::from(&elsewhere) }; + assert!(view.text_document().is_none() && view.source_text_property().is_none()); + assert_eq!(view.text_document_count(), 0); + } #[test] fn non_finite_numbers_are_not_numbers() { @@ -1018,13 +1818,13 @@ mod tests { fn undecoded_fields_are_capped_and_linear() { // 300 000 distinct undecoded slots that differ from a sampled default: before, each was // checked against every slot recorded so far (4.5e10 compares) and all were listed. - let actual = TextValue::Dict((0..300_000).map(|i| (format!("{}", 9000 + i), TextValue::Int(1))).collect()); + let actual = V::Dict((0..300_000).map(|i| (Cow::Owned(format!("{}", 9000 + i)), V::Int(1))).collect()); let mut out = Vec::new(); undecoded_fields(&actual, None, &["0"], &[], &mut out); assert_eq!(out.len(), MAX_UNDECODED_FIELDS); assert_eq!(out.first().map(String::as_str), Some("9000")); // A slot listed once is not listed again. - let again = TextValue::Dict(vec![("9000".into(), TextValue::Int(1))]); + let again = V::Dict(vec![(Cow::Borrowed("9000"), V::Int(1))]); let mut short = vec!["9000".to_string()]; undecoded_fields(&again, None, &[], &[], &mut short); assert_eq!(short, ["9000"]); diff --git a/crates/aep/src/typed.rs b/crates/aep/src/typed.rs index 16fcda33c..9334b45cc 100644 --- a/crates/aep/src/typed.rs +++ b/crates/aep/src/typed.rs @@ -4,42 +4,57 @@ //! //! Only facts that were established from our own one-change-per-file corpus and are checked by //! tests against it are decoded (see `docs/aep-format.md` for the evidence). Everything else -//! stays reachable through the raw [`Chunk`] tree. Views borrow the file and never fail loudly: -//! a chunk that does not have the expected shape yields `None` or is skipped. +//! stays reachable through the raw chunk tree ([`Node`]). Views borrow the file and never fail +//! loudly: a chunk that does not have the expected shape yields `None` or is skipped. +//! +//! A view reads either tree: the owned [`Chunk`](crate::Chunk) tree +//! ([`Project::new`]) or the flat [`TreeIndex`] the importer builds ([`Project::from_index`]); +//! both give the same answers. use crate::bytes::{be_f64, be_u16, be_u32, text, until_nul}; -use crate::chunk::{AepFile, Chunk}; +use crate::chunk::AepFile; +use crate::index::{Node, Root, TreeIndex}; /// The name a user gave a property or group: the `Utf8` inside its `tdsn` chunk. `None` for the /// sentinel `-_0_/-` ("no custom name") and for empty names. -pub(crate) fn user_name(chunk: &Chunk<'_>) -> Option { - let name = chunk.child(b"tdsn")?.children().iter().find(|c| c.is(b"Utf8"))?.bytes().map(text)?; +pub(crate) fn user_name(chunk: Node<'_, '_>) -> Option { + let name = chunk.child(b"tdsn")?.child(b"Utf8")?.bytes().map(text)?; (!name.is_empty() && name != "-_0_/-").then_some(name) } /// The content of a `Utf8` child as text (not trimmed). -pub(crate) fn utf8_child(chunk: &Chunk<'_>) -> Option { - chunk.child(b"Utf8").and_then(Chunk::bytes).map(text) +pub(crate) fn utf8_child(chunk: Node<'_, '_>) -> Option { + chunk.child(b"Utf8").and_then(Node::bytes).map(text) } /// The project: the top-level `LIST Fold`, which holds the project items. #[derive(Debug, Clone, Copy)] pub struct Project<'f, 'a> { - pub(crate) fold: &'f Chunk<'a>, + pub(crate) fold: Node<'f, 'a>, /// The top-level `LIST EfdG` (project-level effect definitions), when there is one. - pub(crate) effect_defs: Option<&'f Chunk<'a>>, + pub(crate) effect_defs: Option>, } impl<'f, 'a> Project<'f, 'a> { /// The project view of a file, or `None` when it has no `LIST Fold`. pub fn new(file: &'f AepFile<'a>) -> Option { - file.list(b"Fold").map(|fold| Self { fold, effect_defs: file.list(b"EfdG") }) + Self::of(Root::from(file)) + } + + /// The project view of an indexed file ([`TreeIndex`]), or `None` when it has no `LIST Fold`. + pub fn from_index(index: &'f TreeIndex<'a>) -> Option { + Self::of(Root::from(index)) + } + + /// The project view of either tree: its `LIST Fold` and `LIST EfdG`. + pub fn of(root: Root<'f, 'a>) -> Option { + root.list(b"Fold").map(|fold| Self { fold, effect_defs: root.list(b"EfdG") }) } /// The top-level items (the project panel's root; folders hold their children, see /// [`Item::children`]). pub fn items(&self) -> impl Iterator> + 'f { - self.fold.children().iter().filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) + self.fold.children().filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) } /// True when the `LIST Fold` could not be read as chunks (damaged): its items cannot be seen. @@ -78,12 +93,12 @@ pub enum ItemKind { /// A project item (`LIST Item`). #[derive(Debug, Clone, Copy)] pub struct Item<'f, 'a> { - pub(crate) chunk: &'f Chunk<'a>, + pub(crate) chunk: Node<'f, 'a>, } impl<'f, 'a> Item<'f, 'a> { /// The underlying chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } @@ -106,7 +121,7 @@ impl<'f, 'a> Item<'f, 'a> { /// The items inside a folder (`LIST Sfdr`). pub fn children(&self) -> impl Iterator> + 'f { - self.chunk.child_list(b"Sfdr").into_iter().flat_map(|sfdr| sfdr.children().iter()).filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) + self.chunk.child_list(b"Sfdr").into_iter().flat_map(Node::children).filter(|c| c.is_list(b"Item")).map(|chunk| Item { chunk }) } /// Whether the item has the `LIST Sfdr` of a folder's contents (After Effects writes an empty @@ -117,7 +132,7 @@ impl<'f, 'a> Item<'f, 'a> { /// True when the folder's `LIST Sfdr` is there but could not be read as chunks (damaged). pub fn folder_contents_unreadable(&self) -> bool { - self.chunk.child_list(b"Sfdr").is_some_and(Chunk::is_opaque_list) + self.chunk.child_list(b"Sfdr").is_some_and(Node::is_opaque_list) } /// The composition view when this item has composition data (`cdta`). @@ -135,6 +150,10 @@ pub struct TimeBase { } impl TimeBase { + /// The NTSC rates as `(numerator, denominator)` and the value After Effects stores for each (a + /// float32 of exactly these decimals): the one table an importer and an exporter use. + pub const NTSC: [((u32, u32), f32); 4] = [((24000, 1001), 23.976), ((30000, 1001), 29.97), ((60000, 1001), 59.94), ((120000, 1001), 119.88)]; + /// Frames per second (`timescale / frame_duration`), `None` for a zero duration. pub fn frame_rate(&self) -> Option { (self.frame_duration != 0).then(|| f64::from(self.timescale) / f64::from(self.frame_duration)) @@ -149,7 +168,7 @@ impl TimeBase { /// A composition item (an [`Item`] with `cdta`). #[derive(Debug, Clone, Copy)] pub struct Comp<'f, 'a> { - pub(crate) item: &'f Chunk<'a>, + pub(crate) item: Node<'f, 'a>, } impl<'f, 'a> Comp<'f, 'a> { @@ -163,19 +182,19 @@ impl<'f, 'a> Comp<'f, 'a> { /// The layers, top layer first (`LIST Layr`; the `DLay`/`SLay`/`CLay`/`SecL` lists next to /// them are not layers). pub fn layers(&self) -> impl Iterator> + 'f { - self.item.children().iter().filter(|c| c.is_list(b"Layr")).map(|chunk| Layer { chunk }) + self.item.children().filter(|c| c.is_list(b"Layr")).map(|chunk| Layer { chunk }) } } /// A layer (`LIST Layr`). #[derive(Debug, Clone, Copy)] pub struct Layer<'f, 'a> { - pub(crate) chunk: &'f Chunk<'a>, + pub(crate) chunk: Node<'f, 'a>, } impl<'f, 'a> Layer<'f, 'a> { /// The underlying chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } @@ -205,12 +224,12 @@ pub enum PropNode<'f, 'a> { /// A property (`LIST tdbs`). Property(Property<'f, 'a>), /// Any other list that follows a match name (observed: `otst`, the effect instance `sspc`). - Other(&'f Chunk<'a>), + Other(Node<'f, 'a>), } impl<'f, 'a> PropNode<'f, 'a> { /// The node a `LIST` after a match name is. - fn of(c: &'f Chunk<'a>) -> Self { + fn of(c: Node<'f, 'a>) -> Self { if c.is_list(b"tdgp") { PropNode::Group(PropGroup { chunk: c }) } else if c.is_list(b"tdbs") { @@ -233,17 +252,18 @@ pub struct PropEntry<'f, 'a> { /// `ADBE Group End` closes the group and names nothing. #[derive(Debug, Clone, Copy)] pub struct PropGroup<'f, 'a> { - pub(crate) chunk: &'f Chunk<'a>, + pub(crate) chunk: Node<'f, 'a>, } impl<'f, 'a> PropGroup<'f, 'a> { - /// A group view of a `LIST tdgp` chunk. - pub fn from_chunk(chunk: &'f Chunk<'a>) -> Option { + /// A group view of a `LIST tdgp` chunk (a [`Chunk`](crate::Chunk) or a [`Node`]). + pub fn from_chunk(chunk: impl Into>) -> Option { + let chunk = chunk.into(); chunk.is_list(b"tdgp").then_some(Self { chunk }) } /// The underlying chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } @@ -264,7 +284,7 @@ impl<'f, 'a> PropGroup<'f, 'a> { for c in self.chunk.children() { if c.is(b"tdmn") { pending = c.bytes().map(match_name); - } else if c.id == crate::chunk::LIST + } else if c.is(&crate::chunk::LIST) && let Some(name) = pending.take() { out.push(PropEntry { match_name: name, node: PropNode::of(c) }); @@ -285,9 +305,9 @@ impl<'f, 'a> PropGroup<'f, 'a> { for c in self.chunk.children() { if c.is(b"tdmn") { pending = c.bytes(); - } else if c.id == crate::chunk::LIST + } else if c.is(&crate::chunk::LIST) && let Some(body) = pending.take() - && match_name(body) == name + && match_name_is(body, name) { return Some(PropNode::of(c)); } @@ -314,21 +334,30 @@ fn match_name(body: &[u8]) -> String { text(until_nul(body)) } +/// `match_name(body) == name` without building the `String`: equal bytes match; otherwise only +/// a body that is not valid UTF-8 can still match (through its U+FFFD replacements), and only a +/// name that holds U+FFFD. +fn match_name_is(body: &[u8], name: &str) -> bool { + let bytes = until_nul(body); + bytes == name.as_bytes() || (name.contains('\u{FFFD}') && String::from_utf8_lossy(bytes) == name) +} + /// A property (`LIST tdbs`): `tdsb`, `tdsn`, the 124-byte header `tdb4`, then either the static /// value `cdat` or a keyframe `LIST list`. #[derive(Debug, Clone, Copy)] pub struct Property<'f, 'a> { - pub(crate) chunk: &'f Chunk<'a>, + pub(crate) chunk: Node<'f, 'a>, } impl<'f, 'a> Property<'f, 'a> { - /// A property view of a `LIST tdbs` chunk. - pub fn from_chunk(chunk: &'f Chunk<'a>) -> Option { + /// A property view of a `LIST tdbs` chunk (a [`Chunk`](crate::Chunk) or a [`Node`]). + pub fn from_chunk(chunk: impl Into>) -> Option { + let chunk = chunk.into(); chunk.is_list(b"tdbs").then_some(Self { chunk }) } /// The underlying chunk. - pub fn chunk(&self) -> &'f Chunk<'a> { + pub fn chunk(&self) -> Node<'f, 'a> { self.chunk } @@ -436,12 +465,13 @@ pub struct KeyLayout { impl<'f> KeyList<'f> { /// A view of a `LIST list` chunk. `None` when `lhd3` is not 52 bytes or `ldat` is not exactly /// `count * record_size` bytes (a list without `ldat` must have no records). - pub fn from_chunk<'a>(chunk: &'f Chunk<'a>) -> Option { + pub fn from_chunk<'a: 'f>(chunk: impl Into>) -> Option { + let chunk = chunk.into(); if !chunk.is_list(b"list") { return None; } let header = ListHeader::parse(chunk.child(b"lhd3")?.bytes()?)?; - let ldat: &[u8] = chunk.child(b"ldat").and_then(Chunk::bytes).unwrap_or(&[]); + let ldat: &[u8] = chunk.child(b"ldat").and_then(Node::bytes).unwrap_or(&[]); let expected = usize::try_from(header.count).ok()?.checked_mul(usize::try_from(header.record_size).ok()?)?; (ldat.len() == expected).then_some(Self { header, ldat, layout: None }) } @@ -500,6 +530,7 @@ impl<'f> Keyframe<'f> { #[cfg(test)] mod tests { use super::*; + use crate::Chunk; fn key_list(count: u32, record_size: u32, ldat: &[u8]) -> Chunk<'static> { let mut lhd3 = vec![0u8; 52]; @@ -543,4 +574,31 @@ mod tests { assert!(g.get("C").is_none()); assert_eq!(g.names(), ["A", "B", "A"]); } + + /// Match name is agrees with comparing the decoded name. + #[test] + fn match_name_is_agrees_with_comparing_the_decoded_name() { + let bodies: [&[u8]; 9] = [ + b"ADBE Position\0\0\0", + b"ADBE Position", + b"ADBE Pos", + b"", + b"\0ADBE", + b"ADBE \xff Bad\0", + b"\xff", + b"\xef\xbf\xbd", + "Gr\u{fc}n\0".as_bytes(), + ]; + let names = ["ADBE Position", "ADBE Pos", "", "ADBE \u{FFFD} Bad", "\u{FFFD}", "Gr\u{fc}n", "ADBE Position\0", "ADBE \u{FFFD}"]; + for body in bodies { + for name in names { + assert_eq!(match_name_is(body, name), match_name(body) == name, "{body:?} vs {name:?}"); + } + } + // Names read back from a group find their entries, a damaged one included. + let group = Chunk::list(*b"tdgp", vec![Chunk::data(*b"tdmn", b"X\xffY\0".to_vec()), Chunk::list(*b"tdbs", Vec::new())]); + let g = PropGroup::from_chunk(&group).expect("group"); + let names = g.names(); + assert!(g.get(&names[0]).is_some()); + } } diff --git a/crates/aep/src/values.rs b/crates/aep/src/values.rs index 5613e07a3..b6857165a 100644 --- a/crates/aep/src/values.rs +++ b/crates/aep/src/values.rs @@ -8,6 +8,7 @@ //! 100 %. These defaults are verified for AV layers (solids); cameras and lights use other //! conventions (see the `camera` module). +use crate::bytes::be_f64; use crate::typed::{Layer, Project, PropGroup, PropNode}; /// Where a [`Tracked`] value came from. @@ -192,8 +193,7 @@ impl<'f, 'a> Layer<'f, 'a> { let otda = otst.child_list(b"otky")?.child(b"otda")?.bytes()?; let mut degrees = [0.0; 3]; for (i, slot) in degrees.iter_mut().enumerate() { - let b = otda.get(i * 8..i * 8 + 8)?; - *slot = f64::from_be_bytes(b.try_into().ok()?); + *slot = be_f64(otda, i * 8)?; } Some(Orientation { degrees, @@ -223,12 +223,10 @@ impl<'f, 'a> Layer<'f, 'a> { .child_list(b"otky") .map(|k| { k.children() - .iter() .filter(|c| c.is(b"otda")) .map(|c| { let b = c.bytes()?; - let at = |i: usize| b.get(i * 8..i * 8 + 8).and_then(|s| s.try_into().ok()).map(f64::from_be_bytes); - Some([at(0)?, at(1)?, at(2)?]) + Some([be_f64(b, 0)?, be_f64(b, 8)?, be_f64(b, 16)?]) }) .collect() }) diff --git a/crates/aep/src/version.rs b/crates/aep/src/version.rs index 53de0834a..023793037 100644 --- a/crates/aep/src/version.rs +++ b/crates/aep/src/version.rs @@ -8,8 +8,9 @@ use std::fmt; -use crate::bytes::{be_u16, be_u32}; +use crate::bytes::be_u32; use crate::chunk::AepFile; +use crate::index::{Root, TreeIndex}; /// An After Effects version as packed in `head` / `svap`: `26.2.1x2` is major 26, minor 2, bug-fix /// 1, build 2 (the form of the scripting API's `app.version`). @@ -71,21 +72,38 @@ impl AepFile<'_> { /// version there, and the older version for File ▸ Save a Copy As 25.x / 24.x. `None` when the /// chunk is missing, short or holds no version. pub fn file_version(&self) -> Option { - AeVersion::from_word(be_u32(self.chunk(b"head")?.bytes()?, 4)?) + Root::from(self).file_version() } /// The version of the After Effects that wrote the file: `svap` bytes 0 to 3 (the same word in a /// down-saved copy as in a normal save). `None` when the chunk is missing (After Effects opens such /// a file), short or holds no version. pub fn saved_by_version(&self) -> Option { - AeVersion::from_word(be_u32(self.chunk(b"svap")?.bytes()?, 0)?) + Root::from(self).saved_by_version() + } +} + +impl TreeIndex<'_> { + /// [`AepFile::file_version`] of the indexed file. + pub fn file_version(&self) -> Option { + Root::from(self).file_version() } - /// The `u16` at `head` byte 0: 97 (`0x61`) in a 2026 file, 96 in a copy saved as 25.x, 95 as - /// 24.x. It steps with the major version of [`AepFile::file_version`]; what it counts is not - /// known, so nothing is derived from it. - pub fn head_revision(&self) -> Option { - be_u16(self.chunk(b"head")?.bytes()?, 0) + /// [`AepFile::saved_by_version`] of the indexed file. + pub fn saved_by_version(&self) -> Option { + Root::from(self).saved_by_version() + } +} + +impl Root<'_, '_> { + /// The version the file is written for (`head` bytes 4 to 7). + pub fn file_version(self) -> Option { + AeVersion::from_word(be_u32(self.chunk(b"head")?.bytes()?, 4)?) + } + + /// The version of the application that wrote the file (`svap`). + pub fn saved_by_version(self) -> Option { + AeVersion::from_word(be_u32(self.chunk(b"svap")?.bytes()?, 0)?) } } diff --git a/crates/aep/src/write.rs b/crates/aep/src/write.rs index 1adf3126d..cadd84f0d 100644 --- a/crates/aep/src/write.rs +++ b/crates/aep/src/write.rs @@ -17,6 +17,18 @@ const MAX_WRITE_DEPTH: usize = 256; /// [`AepError::TooDeep`] for an absurdly deep hand-built tree. pub fn write(file: &AepFile<'_>) -> Result, AepError> { let mut out = Vec::new(); + // Sized once to the exact output. A tree past the 32-bit container size fails at once (the + // same error the write below would give after serialising it). `try_reserve` so a hand-built + // tree that repeats one large borrowed body many times cannot abort on the allocation; the + // writer then grows as it goes, as before. + if let Some(len) = sequence_len(&file.chunks, 1) { + if u32::try_from(len.saturating_add(4)).is_err() { + return Err(AepError::TooLarge); + } + if let Some(total) = len.checked_add(12).and_then(|n| n.checked_add(file.trailer.len())) { + let _ = out.try_reserve_exact(total); + } + } out.extend_from_slice(b"RIFX"); out.extend_from_slice(&[0; 4]); out.extend_from_slice(b"Egg!"); @@ -56,6 +68,28 @@ fn write_sequence(out: &mut Vec, chunks: &[Chunk<'_>], depth: usize) -> Resu Ok(()) } +/// The number of bytes [`write_sequence`] produces for `chunks`; `None` past the depth limit or +/// on overflow (both make the write fail). +fn sequence_len(chunks: &[Chunk<'_>], depth: usize) -> Option { + if depth > MAX_WRITE_DEPTH { + return None; + } + let count = chunks.len(); + let mut total = 0usize; + for (i, chunk) in chunks.iter().enumerate() { + let body = match &chunk.body { + Body::Data(d) => d.len(), + Body::Chunks(c) => sequence_len(c, depth + 1)?, + Body::List { children, .. } => sequence_len(children, depth + 1)?.checked_add(4)?, + Body::OpaqueList { data, .. } => data.len().checked_add(4)?, + }; + // The same pad rule as `write_chunk`. + let pad = usize::from(body % 2 == 1 && (chunk.pad.is_some() || i + 1 != count)); + total = total.checked_add(8)?.checked_add(body)?.checked_add(pad)?; + } + Some(total) +} + fn write_chunk(out: &mut Vec, chunk: &Chunk<'_>, is_last: bool, depth: usize) -> Result<(), AepError> { out.extend_from_slice(&chunk.id); let size_at = out.len(); @@ -84,3 +118,62 @@ fn write_chunk(out: &mut Vec, chunk: &Chunk<'_>, is_last: bool, depth: usize } Ok(()) } + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + + use super::*; + + /// The output is sized once to its exact length. + #[test] + fn the_output_is_sized_once_to_its_exact_length() { + let odd = |n: u8| Chunk::data(*b"cdat", vec![n; usize::from(n)]); + let mut padded = odd(3); + padded.pad = Some(0x7f); + let trees = [ + AepFile { chunks: Vec::new(), trailer: Cow::Borrowed(&[]) }, + AepFile { + chunks: vec![ + odd(1), + Chunk::list(*b"Fold", vec![odd(2), odd(3), Chunk::list(*b"tdgp", vec![odd(5)])]), + Chunk { id: *b"LIST", body: Body::OpaqueList { list_type: *b"btdk", data: Cow::Owned(vec![1, 2, 3]) }, pad: None }, + Chunk { id: *b"tdmn", body: Body::Chunks(vec![odd(7), padded]), pad: None }, + odd(9), + ], + trailer: Cow::Borrowed(b""), + }, + ]; + for file in &trees { + let out = write(file).expect("write"); + assert_eq!(sequence_len(&file.chunks, 1).map(|n| n + 12 + file.trailer.len()), Some(out.len())); + // Exact with std's allocator today; grown push by push it would be rounded up. + assert_eq!(out.capacity(), out.len(), "the output grew past its size"); + } + } + + /// A tree past the container size fails before serialising. + #[cfg(target_pointer_width = "64")] + #[test] + fn a_tree_past_the_container_size_fails_before_serialising() { + // 4097 chunks borrowing one 1 MiB body: over 4 GiB of output, none of it written. + let body = vec![0u8; 1 << 20]; + let chunks: Vec> = (0..4097).map(|_| Chunk::data(*b"cdat", &body[..])).collect(); + let file = AepFile { chunks, trailer: Cow::Borrowed(&[]) }; + assert_eq!(write(&file), Err(AepError::TooLarge)); + // Just under the limit still sizes, and fails nothing up front. + assert!(sequence_len(&file.chunks[..4000], 1).is_some_and(|n| u32::try_from(n + 4).is_ok())); + } + + /// A tree past the depth limit has no size. + #[test] + fn a_tree_past_the_depth_limit_has_no_size() { + let mut deep = Chunk::data(*b"cdat", vec![0]); + for _ in 0..=MAX_WRITE_DEPTH { + deep = Chunk::list(*b"tdgp", vec![deep]); + } + let file = AepFile { chunks: vec![deep], trailer: Cow::Borrowed(&[]) }; + assert_eq!(sequence_len(&file.chunks, 1), None); + assert_eq!(write(&file), Err(AepError::TooDeep)); + } +} diff --git a/crates/aep/tests/it/common/mod.rs b/crates/aep/tests/it/common/mod.rs index 791c3bbc9..b5605bb95 100644 --- a/crates/aep/tests/it/common/mod.rs +++ b/crates/aep/tests/it/common/mod.rs @@ -128,6 +128,13 @@ pub fn resolve(name: &str) -> Option { locate(name).map(|s| s.path().clone()) } +/// The ids of the compositions an item uses as precomposition layers, as the file stores them: +/// the little-endian `u32` of each `idpi` chunk (the importer does not read them; the exporter +/// writes them). +pub fn used_item_ids(item: &craft_aep::Item<'_, '_>) -> Vec { + item.chunk().children().filter(|c| c.is(b"idpi")).filter_map(|c| Some(u32::from_le_bytes(c.bytes()?.get(..4)?.try_into().ok()?))).collect() +} + /// The bytes of a case (see the module comment), or `None` when it is missing. pub fn try_fixture(name: &str) -> Option> { match locate(name)? { diff --git a/crates/aep/tests/it/container.rs b/crates/aep/tests/it/container.rs index d937d296c..514bbde1c 100644 --- a/crates/aep/tests/it/container.rs +++ b/crates/aep/tests/it/container.rs @@ -25,5 +25,6 @@ mod shapes; mod text_fields; mod text_markers_footage; mod text_style_slots; +mod tree_index; mod typed; mod values; diff --git a/crates/aep/tests/it/container/batch3_core.rs b/crates/aep/tests/it/container/batch3_core.rs index 8c2518a9f..83bd942b8 100644 --- a/crates/aep/tests/it/container/batch3_core.rs +++ b/crates/aep/tests/it/container/batch3_core.rs @@ -117,8 +117,8 @@ fn a_transform_set_to_its_default_adds_no_record() { assert_eq!(t.opacity_percent.source, ValueSource::Default); assert!(layer.properties().unwrap().find(&["ADBE Transform Group", "ADBE Position"]).is_none()); // The two cases are layers of one file: they differ in the layer id only. - let a = without_layer_id(layer.chunk()); - skip!(with_layer("299-save-noise.aep", L, |_, other| assert_eq!(a, without_layer_id(other.chunk())))); + let a = without_layer_id(&layer.chunk().to_chunk()); + skip!(with_layer("299-save-noise.aep", L, |_, other| assert_eq!(a, without_layer_id(&other.chunk().to_chunk())))); })); } @@ -140,16 +140,13 @@ fn scale_keys_keep_their_ease_type_major() { } assert_near(&keys[0].value().unwrap(), &[1.0, 1.0, 1.0], 1e-9); assert_near(&keys[1].value().unwrap(), &[2.0, 1.5, 1.0], 1e-9); - // The raw block: [in speed x3][in influence x3][out speed x3][out influence x3]. - assert_near(&keys[0].plain_ease_slots().unwrap(), &[0.0, 0.0, 0.0, 0.33, 0.33, 0.33, 0.2, 0.2, 0.2, 0.66, 0.66, 0.66], 1e-9); - assert_near(&keys[1].plain_ease_slots().unwrap(), &[0.1, 0.1, 0.1, 0.66, 0.66, 0.66, 0.0, 0.0, 0.0, 0.33, 0.33, 0.33], 1e-9); + // The raw block is [in speed x3][in influence x3][out speed x3][out influence x3]. for i in 0..3 { assert!(same_ease(&keys[0].ease_component(i).unwrap(), &ease(0.0, 0.33, 0.2, 0.66)), "key 1 component {i}"); assert!(same_ease(&keys[1].ease_component(i).unwrap(), &ease(0.1, 0.66, 0.0, 0.33)), "key 2 component {i}"); } assert!(keys[0].ease_component(3).is_none()); assert_eq!(keys[0].ease_components().unwrap().len(), 3); - assert!(keys[0].color_distance().is_none()); })); } @@ -172,7 +169,6 @@ fn mask_feather_keys_keep_their_ease_type_major() { } assert_near(&keys[0].value().unwrap(), &[0.0, 0.0], 1e-9); assert_near(&keys[1].value().unwrap(), &[50.0, 30.0], 1e-9); - assert_near(&keys[0].plain_ease_slots().unwrap(), &[0.0, 0.0, 0.33, 0.33, 15.0, 15.0, 0.66, 0.66], 1e-9); for i in 0..2 { assert!(same_ease(&keys[0].ease_component(i).unwrap(), &ease(0.0, 0.33, 15.0, 0.66)), "key 1 component {i}"); assert!(same_ease(&keys[1].ease_component(i).unwrap(), &ease(8.0, 0.66, 0.0, 0.33)), "key 2 component {i}"); @@ -213,14 +209,15 @@ fn bezier_colour_keys_carry_the_distance_to_the_next_key() { assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); assert!(same_ease(&k.ease_component(0).unwrap(), &ease(0.0, 0.0, 0.0, 0.0))); } - assert!(near(keys[0].color_distance().unwrap(), 255.0 * 2f64.sqrt(), 1e-3), "{:?}", keys[0].color_distance()); - assert!(near(keys[0].color_distance().unwrap(), 360.6245, 1e-3)); - assert_eq!(keys[1].color_distance(), Some(0.0)); + let distance = |k: &craft_aep::Keyframe<'_>| k.spatial().unwrap().segment_length; + assert!(near(distance(&keys[0]), 255.0 * 2f64.sqrt(), 1e-3), "{}", distance(&keys[0])); + assert!(near(distance(&keys[0]), 360.6245, 1e-3)); + assert_eq!(distance(&keys[1]), 0.0); })); skip!(with_layer("210-key-fill-color-2key-linear.aep", L, |_, layer| { let p = layer.effects()[0].params().into_iter().find(|p| p.name == "Color").unwrap(); let k = p.stored().unwrap().keys().unwrap().keyframes().next().unwrap(); - assert_eq!(k.color_distance(), Some(0.0)); + assert_eq!(k.spatial().unwrap().segment_length, 0.0); })); } @@ -243,21 +240,19 @@ fn time_stretch_is_an_exact_ratio() { let (h, in_p, out_p, scale) = skip!(stretch_facts("316-layer-stretch50.aep")); assert_eq!((h.stretch, h.stretch_den), (1, 2)); assert_eq!(h.stretch_ratio(), Some(rat(1, 2))); - assert_eq!(h.stretch_percent(), 50.0); assert_eq!(h.out_relative, rat(128000, 25600)); assert_eq!((in_p, out_p, scale), (Some(rat(0, 1)), Some(rat(5, 2)), 25600)); // 317: 150 %: 3/2, ends at 7.5 s, the property time scale is 25600 x 3/2. let (h, in_p, out_p, scale) = skip!(stretch_facts("317-layer-stretch150.aep")); assert_eq!((h.stretch, h.stretch_den), (3, 2)); assert_eq!(h.stretch_ratio(), Some(rat(3, 2))); - assert_eq!(h.stretch_percent(), 150.0); assert_eq!((in_p, out_p, scale), (Some(rat(0, 1)), Some(rat(15, 2)), 38400)); // 018: 200 %: 2/1, ends at 10 s, time scale 51200. The base is 1/1. let (h, _, out_p, scale) = skip!(stretch_facts("018-layer-stretch200.aep")); assert_eq!((h.stretch, h.stretch_den, h.stretch_ratio()), (2, 1, Some(rat(2, 1)))); assert_eq!((out_p, scale), (Some(rat(10, 1)), 51200)); let (h, _, out_p, scale) = skip!(stretch_facts("000-base.aep")); - assert_eq!((h.stretch, h.stretch_den, h.stretch_percent()), (1, 1, 100.0)); + assert_eq!((h.stretch, h.stretch_den, h.stretch_ratio()), (1, 1, Some(rat(1, 1)))); assert_eq!((out_p, scale), (Some(rat(5, 1)), 25600)); } @@ -269,9 +264,9 @@ fn fractional_times_are_exact_multiples_of_one_over_25600() { assert_eq!(h.in_relative, rat(8532, 25600)); assert_eq!(h.out_relative, rat(136532, 25600)); assert_eq!(h.start, rat(0, 25600)); + // 0.33328125 s and 5.33328125 s. assert_eq!(h.in_point(), Some(rat(2133, 6400))); - assert_eq!(h.in_point_seconds(), Some(0.33328125)); - assert_eq!(h.out_point_seconds(), Some(5.33328125)); + assert_eq!(h.out_point(), Some(rat(34133, 6400))); assert_eq!(h.stretch_ratio(), Some(rat(1, 1))); } @@ -364,18 +359,17 @@ fn pixel_aspect_shutter_phase_and_display_start() { // 325: pixelAspect 0.9091 reads back 0.90909090909091 = the exact ratio 10/11. let h = skip!(comp_header("325-comp-pixelaspect-0.9091.aep")); assert_eq!(h.pixel_aspect.reduced(), Some(rat(10, 11))); - assert!(near(h.pixel_aspect_ratio().unwrap(), 0.90909090909091, 1e-12)); // 326: shutterPhase -90, the shutter angle stays 180. let h = skip!(comp_header("326-comp-shutterphase-m90.aep")); assert_eq!((h.shutter_phase, h.shutter_angle), (Some(-90), 180)); // 327: displayStartFrame 100 at 25 fps = 4 s = 102400/25600; the shutter phase is back to 0. let h = skip!(comp_header("327-comp-displaystartframe-100.aep")); assert_eq!(h.display_start, Some(rat(102400, 25600))); - assert_eq!((h.display_start_seconds(), h.display_start_frame(), h.shutter_phase), (Some(4.0), Some(100), Some(0))); + assert_eq!(h.shutter_phase, Some(0)); // The base: no phase, start 0. let h = skip!(comp_header("000-base.aep")); - assert_eq!((h.shutter_phase, h.display_start_seconds(), h.display_start_frame()), (Some(0), Some(0.0), Some(0))); - assert_eq!(h.pixel_aspect_ratio(), Some(1.0)); + assert_eq!((h.shutter_phase, h.display_start.and_then(|r| r.reduced())), (Some(0), Some(rat(0, 1)))); + assert_eq!(h.pixel_aspect.reduced(), Some(rat(1, 1))); // A short chunk still decodes the old fields. let bytes = [0u8; 176]; let h = craft_aep::CompHeader::parse(&bytes).unwrap(); diff --git a/crates/aep/tests/it/container/batch3_objects.rs b/crates/aep/tests/it/container/batch3_objects.rs index bbb7040b4..c78525a00 100644 --- a/crates/aep/tests/it/container/batch3_objects.rs +++ b/crates/aep/tests/it/container/batch3_objects.rs @@ -148,19 +148,21 @@ fn a_mask_box_is_normalised_to_the_layer_size() { for (got, want) in m.shapes[0].bbox.iter().zip(want_box) { assert!(near(f64::from(*got), want, 1e-6), "{:?}", m.shapes[0].bbox); } - let shapes = project.mask_vertices_px(&layer, m).unwrap(); - assert_eq!(shapes.len(), 1); - let got: Vec<[f64; 2]> = shapes[0].iter().map(|v| v.position).collect(); + // The box scales by the size of the layer's source (the importer takes that size from the + // source item it matched, the same item `layer_source_size` reads). + let (w, h) = project.layer_source_size(&layer).unwrap(); + assert_eq!(m.shapes.len(), 1); + let got: Vec<[f64; 2]> = m.shapes[0].vertices((f64::from(w), f64::from(h))).iter().map(|v| v.position).collect(); for (g, w) in got.iter().zip([[20.0, 30.0], [80.0, 30.0], [80.0, 70.0], [20.0, 70.0]]) { assert_near(g, &w, 1e-3); } assert_eq!(got.len(), 4); - // A layer without a sized source has no pixel vertices. + // A layer without a sized source has no size to scale by. let bytes = fixture!("333-shape-group-two-rects.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); let shape = layer_named(&first_comp(&project), "Shape"); - assert!(project.mask_vertices_px(&shape, m).is_none()); + assert!(project.layer_source_size(&shape).is_none()); } #[test] @@ -178,12 +180,14 @@ fn one_mkif_per_mask_and_the_mode_none() { assert_eq!((m.mode, m.inverted, m.counter), (Some(MaskMode::Add), Some(false), Some(counter))); assert_eq!(m.shapes.len(), 1); } - let v1 = project.mask_vertices_px(&layer, &masks[0]).unwrap(); + let (w, h) = project.layer_source_size(&layer).unwrap(); + let px = |m: &craft_aep::Mask| m.shapes.iter().map(|s| s.vertices((f64::from(w), f64::from(h)))).collect::>(); + let v1 = px(&masks[0]); for (v, w) in v1[0].iter().zip(ellipse_vertices()) { assert_near(&v.position, &w, 1e-2); } // Mask 2 has its own box (500..900 x 350..650) normalised to the layer. - let v2 = project.mask_vertices_px(&layer, &masks[1]).unwrap(); + let v2 = px(&masks[1]); for (v, w) in v2[0].iter().zip([[500.0, 350.0], [900.0, 350.0], [900.0, 650.0], [500.0, 650.0]]) { assert_near(&v.position, &w, 1e-2); } @@ -384,81 +388,16 @@ fn the_last_style_run_absorbs_the_final_carriage_return() { // ------------------------------------------------------------------ camera and light (341-345) +/// Camera zoom keeps the auto position. #[test] -fn camera_zoom_and_depth_of_field() { - let camera = |name: &str| { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_of_type(&first_comp(&project), LayerType::Camera); - ( - layer.camera_zoom(), - layer.camera_depth_of_field(), - layer.camera_focus_distance(), - layer.camera_aperture(), - layer.camera_position().map(|p| (p.stored, p.auto_state)), - ) - }) - }; - // 341: Zoom 2000 is stored; the auto Position keeps [0, 0, -2666.67]. - let (zoom, dof, focus, aperture, pos) = skip!(camera("341-camera-zoom-2000.aep")); - assert_eq!(zoom.map(|z| (z.value, z.source)), Some((2000.0, ValueSource::Stored))); - assert_eq!((dof.map(|d| (d.value, d.source)), focus, aperture), (Some((false, ValueSource::Default)), None, None)); - let (stored, auto) = pos.unwrap(); - assert!(auto && near(stored[2], -2666.67, 0.01) && stored[0] == 0.0, "{stored:?}"); - // 342: DOF on, Focus Distance 800, Aperture 30; Zoom stays the default. - let (zoom, dof, focus, aperture, _) = skip!(camera("342-camera-dof-800-30.aep")); - assert_eq!(zoom.map(|z| (z.source, near(z.value, 2666.67, 0.01))), Some((ValueSource::Default, true))); - assert_eq!(dof.map(|d| (d.value, d.source)), Some((true, ValueSource::Stored))); - assert_eq!(focus.map(|f| (f.value, f.source)), Some((800.0, ValueSource::Stored))); - assert_eq!(aperture.map(|f| (f.value, f.source)), Some((30.0, ValueSource::Stored))); - // The default camera (256) has nothing but the default zoom. - let (zoom, dof, ..) = skip!(camera("256-camera-two-node-default.aep")); - assert_eq!((zoom.unwrap().source, dof.unwrap().value), (ValueSource::Default, false)); - assert_eq!(zoom.unwrap().value, craft_aep::DEFAULT_CAMERA_ZOOM); -} - -#[test] -fn light_colour_cone_angle_and_feather() { - let light = |name: &str| { - Some({ - let bytes = crate::common::try_fixture(name)?; - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let layer = layer_of_type(&first_comp(&project), LayerType::Light); - assert_eq!(layer.header().unwrap().light_type(), Some(craft_aep::LightType::Spot), "{name}"); - let t = |x: Option>| x.map(|x| (x.value, x.source)); - (layer.light_color().map(|c| (c.value, c.source)), t(layer.light_cone_angle()), t(layer.light_cone_feather())) - }) - }; - // The default spot light: white, 90, 50, all absent. - let (colour, angle, feather) = skip!(light("254-light-spot-intensity-50.aep")); - assert_eq!( - (colour, angle, feather), - (Some(([1.0; 4], ValueSource::Default)), Some((90.0, ValueSource::Default)), Some((50.0, ValueSource::Default))) - ); - // 343: colour [1,0,0,1] = ARGB doubles [255,255,0,0]. - let (colour, angle, feather) = skip!(light("343-light-spot-color-red.aep")); - assert_eq!(colour, Some(([1.0, 1.0, 0.0, 0.0], ValueSource::Stored))); - assert_eq!((angle, feather), (Some((90.0, ValueSource::Default)), Some((50.0, ValueSource::Default)))); - // 344: Cone Angle 60. 345: Cone Feather 30. - let (colour, angle, feather) = skip!(light("344-light-spot-coneangle-60.aep")); - assert_eq!((colour.unwrap().1, angle, feather), (ValueSource::Default, Some((60.0, ValueSource::Stored)), Some((50.0, ValueSource::Default)))); - let (_, angle, feather) = skip!(light("345-light-spot-conefeather-30.aep")); - assert_eq!((angle, feather), (Some((90.0, ValueSource::Default)), Some((30.0, ValueSource::Stored)))); - // A point light (252) stores Cone Angle 90 / Feather 50 in their default state. - let bytes = fixture!("252-light-point.aep"); +fn camera_zoom_keeps_the_auto_position() { + // 341: Zoom 2000 is stored (checked on import); the auto Position keeps [0, 0, -2666.67]. + let bytes = fixture!("341-camera-zoom-2000.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); - let layer = layer_of_type(&first_comp(&project), LayerType::Light); - assert_eq!(layer.light_cone_angle().map(|a| (a.value, a.source)), Some((90.0, ValueSource::Stored))); - // Layers without light options have no light accessors. - let bytes = fixture!("000-base.aep"); - let file = open(&bytes); - let project = Project::new(&file).unwrap(); - let solid = base_layer(&first_comp(&project)); - assert!(solid.light_color().is_none() && solid.camera_zoom().is_none() && solid.camera_depth_of_field().is_none()); + let layer = layer_of_type(&first_comp(&project), LayerType::Camera); + let pos = layer.camera_position().unwrap(); + assert!(pos.auto_state && near(pos.stored[2], -2666.67, 0.01) && pos.stored[0] == 0.0, "{:?}", pos.stored); } // ------------------------------------------------------------------ marker data (347-349, 249) @@ -508,7 +447,7 @@ fn audio_footage_item() { assert_eq!((f.width, f.height, f.is_solid), (0, 0, false)); assert_eq!(f.duration, Some(rat(48000, 48000))); assert_eq!((f.audio_sample_rate, f.file_size, f.bits_per_pixel, f.native_frame_rate), (Some(48000.0), 96044, 0, 0)); - assert!(!f.is_sequence && f.sequence_frame_count().is_none()); + assert!(!f.is_sequence && item.sequence_info().is_none()); // The combined file stores no display name for the item (the single-case file had // "test-tone.wav"); the path names the file. assert_eq!(item.label(), Some(7)); @@ -532,7 +471,7 @@ fn image_sequence_is_one_item() { assert_eq!(f.duration, Some(rat(3, 30)), "{name}"); assert_eq!((f.native_frame_rate, f.bits_per_pixel, f.file_size, f.audio_sample_rate), (30, 24, 504, None), "{name}"); assert!(f.is_sequence, "{name}"); - assert_eq!(f.sequence_frame_count(), Some(3), "{name}"); + assert_eq!(item.sequence_info().map(|s| s.frame_count()), Some(3), "{name}"); // The first file name sits in opti; the alias points at the sequence folder. assert_eq!(f.name.as_deref(), Some("seq_001.png"), "{name}"); assert!(f.path.as_deref().is_some_and(|p| p.ends_with("test-seq")), "{name}"); diff --git a/crates/aep/tests/it/container/cases_600.rs b/crates/aep/tests/it/container/cases_600.rs index 210fb0916..43df3052a 100644 --- a/crates/aep/tests/it/container/cases_600.rs +++ b/crates/aep/tests/it/container/cases_600.rs @@ -38,7 +38,7 @@ fn a_composition_counts_the_compositions_it_shows() { let id = |n: &str| items.iter().find(|i| i.display_name().as_deref() == Some(n)).and_then(|i| i.id()).expect(n); let c = items.iter().find(|i| i.display_name().as_deref() == Some("C")).expect("C"); // The list holds each used composition once (in no particular order). - let mut used = c.used_item_ids(); + let mut used = crate::common::used_item_ids(c); used.sort(); let mut want = vec![id("P30"), id("Q")]; want.sort(); @@ -60,8 +60,8 @@ fn an_image_sequence_knows_its_numbering() { let item = project.all_items().into_iter().find(|i| i.footage().is_some_and(|f| !f.is_solid)).expect("sequence"); let f = item.footage().expect("footage"); assert_eq!((f.file_type.as_str(), f.width, f.height, f.native_frame_rate, f.is_sequence), ("oEXR", 64, 48, 30, true)); - assert_eq!(f.sequence_frame_count(), Some(3)); let s = item.sequence_info().expect("numbering"); + assert_eq!(s.frame_count(), 3); assert_eq!((s.prefix.as_str(), s.suffix.as_str(), s.start, s.end, s.digits), ("shot_", ".exr", 101, 103, 4)); assert_eq!(s.file_name(101), "shot_0101.exr"); // A still has no numbering (000: the solid; the base has no other footage). diff --git a/crates/aep/tests/it/container/header.rs b/crates/aep/tests/it/container/header.rs index f78b0bba9..f9252f7fd 100644 --- a/crates/aep/tests/it/container/header.rs +++ b/crates/aep/tests/it/container/header.rs @@ -55,7 +55,6 @@ fn assert_plain(h: &LayerHeader) { assert_eq!(h.label, 1); // No name was set, so the copy of the name at byte 64 is empty (the layer shows its source name). assert_eq!(h.name_copy, ""); - assert!(!h.name_is_user_set()); assert!(!h.is_null_object()); assert_eq!(h.parent_id, None); assert_eq!(h.source_id, Some(0x1a)); @@ -67,16 +66,13 @@ fn base_layer_header() { assert_plain(&h); assert_eq!(h.quality, Quality::Best); assert_eq!(h.blend_mode, BlendMode::Normal); - assert_eq!(h.stretch, 1); - assert_eq!(h.stretch_percent(), 100.0); + assert_eq!((h.stretch, h.stretch_den), (1, 1)); assert_eq!(switches(&h), NONE); // start 0 s, in 0 s, out 5 s; denominator = the composition timescale. assert_eq!(h.start, Rational { num: 0, den: 25600 }); assert_eq!(h.in_relative, Rational { num: 0, den: 25600 }); assert_eq!(h.out_relative, Rational { num: 128_000, den: 25600 }); - assert_eq!(h.start_seconds(), Some(0.0)); - assert_eq!(h.in_point_seconds(), Some(0.0)); - assert_eq!(h.out_point_seconds(), Some(5.0)); + assert_eq!(h.in_point(), Rational::new(0, 1)); assert_eq!(h.out_point(), Rational::new(5, 1)); } @@ -98,7 +94,7 @@ fn one_switch_per_case() { assert_eq!(switches(&h), expected, "{name}"); assert_plain(&h); assert_eq!((h.quality, h.blend_mode, h.stretch), (Quality::Best, BlendMode::Normal, 1), "{name}"); - assert_eq!(h.out_point_seconds(), Some(5.0), "{name}"); + assert_eq!(h.out_point(), Rational::new(5, 1), "{name}"); } } @@ -106,7 +102,6 @@ fn one_switch_per_case() { fn name_blend_mode_and_quality() { let h = skip!(l_header("010-layer-name.aep")); assert_eq!(h.name_copy, "Renamed"); - assert!(h.name_is_user_set()); let bytes = fixture!("010-layer-name.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); @@ -114,7 +109,6 @@ fn name_blend_mode_and_quality() { // The layer name is the user's; the source footage keeps its own name. assert_eq!(layer.name().as_deref(), Some("Renamed")); assert_eq!(project.layer_source(&layer).and_then(|i| i.display_name()).as_deref(), Some("L")); - assert_eq!(project.layer_display_name(&layer).as_deref(), Some("Renamed")); assert_eq!(skip!(l_header("016-layer-blend-multiply.aep")).blend_mode, BlendMode::Multiply); assert_eq!(skip!(l_header("023-layer-quality-draft.aep")).quality, Quality::Draft); @@ -127,7 +121,7 @@ fn display_name_falls_back_to_the_source_name() { let project = Project::new(&file).unwrap(); let layer = base_layer(&first_comp(&project)); assert_eq!(layer.name(), None); - assert_eq!(project.layer_display_name(&layer).as_deref(), Some("L")); + assert_eq!(project.layer_source(&layer).and_then(|i| i.display_name()).as_deref(), Some("L")); assert_eq!(project.layer_source_size(&layer), Some((1920, 1080))); let source = project.layer_source(&layer).unwrap(); assert_eq!(source.id(), Some(0x1a)); @@ -139,26 +133,23 @@ fn time_stretch_and_the_in_out_start_convention() { // 018: stretch 100 -> 200: the stored out point stays 5 s, the layer ends at 10 s. let h = skip!(l_header("018-layer-stretch200.aep")); assert_eq!(h.stretch, 2); - assert_eq!(h.stretch_percent(), 200.0); + assert_eq!(h.stretch_ratio(), Rational::new(2, 1)); assert_eq!(h.out_relative, Rational { num: 128_000, den: 25600 }); - assert_eq!(h.out_point_seconds(), Some(10.0)); - assert_eq!(h.in_point_seconds(), Some(0.0)); + assert_eq!(h.out_point(), Rational::new(10, 1)); + assert_eq!(h.in_point(), Rational::new(0, 1)); // 019: inPoint 0 -> 1; AE moved the out point to 6 s and left the start at 0. let h = skip!(l_header("019-layer-inpoint1.aep")); - assert_eq!(h.start_seconds(), Some(0.0)); + assert_eq!(h.start.num, 0); assert_eq!(h.in_relative, Rational { num: 25600, den: 25600 }); assert_eq!(h.in_point(), Rational::new(1, 1)); - assert_eq!(h.out_point_seconds(), Some(6.0)); + assert_eq!(h.out_point(), Rational::new(6, 1)); // 021: startTime 0 -> 0.5: in 0.5 s and out 5.5 s although the stored in point stays 0. let h = skip!(l_header("021-layer-starttime0.5.aep")); assert_eq!(h.start, Rational { num: 12800, den: 25600 }); - assert_eq!(h.start_seconds(), Some(0.5)); assert_eq!(h.in_relative.num, 0); assert_eq!(h.in_point(), Rational::new(1, 2)); - assert_eq!(h.in_point_seconds(), Some(0.5)); - assert_eq!(h.out_point_seconds(), Some(5.5)); assert_eq!(h.out_point(), Rational::new(11, 2)); } @@ -175,7 +166,6 @@ fn parent_link_and_null_object() { let nh = null.header().unwrap(); assert_eq!(null.name().as_deref(), Some("Null")); assert!(nh.is_null_object()); - assert!(nh.name_is_user_set()); assert_eq!(nh.layer_type, LayerType::Av); assert_eq!(nh.parent_id, None); assert_eq!(project.layer_source(null).and_then(|i| i.display_name()).as_deref(), Some("Null 1")); @@ -225,17 +215,14 @@ fn base_comp_header() { assert_eq!((h.width, h.height), (1920, 1080)); assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 25600)); assert_eq!(h.frame_rate(), Some(25.0)); - assert_eq!(h.frame_rate_from_fixed(), 25.0); + assert_eq!(h.frame_rate_fixed, 25 << 16); assert_eq!(h.duration_units, 128_000); assert_eq!(h.duration_seconds(), Some(5.0)); assert_eq!(h.background, [0, 0, 0]); - assert_eq!(h.background_rgb(), [0.0, 0.0, 0.0]); assert_eq!(h.shutter_angle, 180); - assert_eq!(h.work_area_start_seconds(), Some(0.0)); + assert_eq!(h.work_area_start_units, 0); assert_eq!(h.work_area_end_units, None); - assert_eq!(h.work_area_end_seconds(), Some(5.0)); assert_eq!(h.pixel_aspect, Rational { num: 1, den: 1 }); - assert_eq!(h.pixel_aspect_ratio(), Some(1.0)); assert!(!h.motion_blur); // The manifest calls the classic renderer `ADBE Advanced 3d`; the file stores `ADBE Escher` // and the display name `Classic 3D`. @@ -255,7 +242,7 @@ fn one_comp_change_per_case() { let (h, _, _) = skip!(comp_header("031-comp-fps30.aep")); assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 30720)); assert_eq!(h.frame_rate(), Some(30.0)); - assert_eq!(h.frame_rate_from_fixed(), 30.0); + assert_eq!(h.frame_rate_fixed, 30 << 16); assert_eq!(h.duration_units, 153_600); assert_eq!(h.duration_seconds(), Some(5.0)); @@ -263,12 +250,11 @@ fn one_comp_change_per_case() { let (h, _, _) = skip!(comp_header("032-comp-duration10.aep")); assert_eq!(h.duration_units, 256_000); assert_eq!(h.duration_seconds(), Some(10.0)); - assert_eq!(h.work_area_end_seconds(), Some(10.0)); + assert_eq!(h.work_area_end_units, None); // 033: bgColor [0,0,0] -> [0,1,0]. let (h, _, _) = skip!(comp_header("033-comp-bg-green.aep")); assert_eq!(h.background, [0, 255, 0]); - assert_eq!(h.background_rgb(), [0.0, 1.0, 0.0]); // 034: shutterAngle 180 -> 90. let (h, _, _) = skip!(comp_header("034-comp-shutter90.aep")); @@ -279,8 +265,6 @@ fn one_comp_change_per_case() { let (h, _, _) = skip!(comp_header("035-comp-workarea-1-2.aep")); assert_eq!(h.work_area_start_units, 25600); assert_eq!(h.work_area_end_units, Some(76_800)); - assert_eq!(h.work_area_start_seconds(), Some(1.0)); - assert_eq!(h.work_area_end_seconds(), Some(3.0)); } #[test] @@ -290,7 +274,6 @@ fn one_comp_change_per_case_aspect_blur_renderer() { // 037: pixelAspect 1 -> 2. let (h, _, _) = skip!(comp_header("037-comp-pixelaspect2.aep")); assert_eq!(h.pixel_aspect, Rational { num: 2, den: 1 }); - assert_eq!(h.pixel_aspect_ratio(), Some(2.0)); // 038: comp motion blur on. let (h, _, _) = skip!(comp_header("038-comp-motionblur.aep")); @@ -328,17 +311,16 @@ fn precomp_item_ids_and_labels() { assert_eq!(h.source_id, pre_item.id()); assert_eq!(project.layer_source(layer).unwrap().id(), pre_item.id()); assert_eq!(h.label, 15); - assert!(!h.name_is_user_set()); assert_eq!(layer.name(), None); - assert_eq!(project.layer_display_name(layer).as_deref(), Some("Pre")); + assert_eq!(project.layer_source(layer).and_then(|i| i.display_name()).as_deref(), Some("Pre")); assert_eq!(project.layer_source_size(layer), Some((1920, 1080))); // The precomp layer's start time has the denominator 1; the Pre comp is 1920x1080, 25 fps, 5 s. assert_eq!(h.start.den, 1); let ph = pre.header().unwrap(); assert_eq!((ph.width, ph.height, ph.frame_rate(), ph.duration_seconds()), (1920, 1080, Some(25.0), Some(5.0))); // C records that it uses the comp Pre (chunk idpi, a little-endian u32). - assert_eq!(c_item.used_item_ids(), [pre_item.id().unwrap()]); - assert!(pre_item.used_item_ids().is_empty()); + assert_eq!(crate::common::used_item_ids(c_item), [pre_item.id().unwrap()]); + assert!(crate::common::used_item_ids(pre_item).is_empty()); assert_eq!(pre_item.label(), Some(15)); // The layer inside Pre is a new layer made from the solid L (moving the layers into a precomp // creates new layers). @@ -347,7 +329,7 @@ fn precomp_item_ids_and_labels() { let ih = inner[0].header().unwrap(); assert_ne!(ih.id, L); assert_eq!(ih.source_id, Some(0x1a)); - assert_eq!(project.layer_display_name(&inner[0]).as_deref(), Some("L")); + assert_eq!(project.layer_source(&inner[0]).and_then(|i| i.display_name()).as_deref(), Some("L")); } #[test] @@ -356,9 +338,8 @@ fn a_negative_stretch_is_a_reversed_layer() { // point 0 and out point 5 s relative, so the layer runs from 5 s back to 0 s; 983: -50 % = -1/2. let h = skip!(l_header("981-layer-stretch-minus100-start5.aep")); assert_eq!((h.stretch, h.stretch_den), (-1, 1)); - assert_eq!(h.stretch_percent(), -100.0); - assert_eq!((h.in_point_seconds(), h.out_point_seconds()), (Some(5.0), Some(0.0))); + assert_eq!((h.in_point(), h.out_point()), (Rational::new(5, 1), Rational::new(0, 1))); let h = skip!(l_header("983-layer-stretch-minus50-opacity-keys.aep")); assert_eq!((h.stretch, h.stretch_den), (-1, 2)); - assert_eq!((h.in_point_seconds(), h.out_point_seconds()), (Some(5.0), Some(2.5))); + assert_eq!((h.in_point(), h.out_point()), (Rational::new(5, 1), Rational::new(5, 2))); } diff --git a/crates/aep/tests/it/container/helpers.rs b/crates/aep/tests/it/container/helpers.rs index b6ab11432..af2282ab8 100644 --- a/crates/aep/tests/it/container/helpers.rs +++ b/crates/aep/tests/it/container/helpers.rs @@ -379,7 +379,8 @@ pub fn layer_named<'f, 'a>(comp: &Comp<'f, 'a>, name: &str) -> Layer<'f, 'a> { /// The layer that shows this name: its own name, or its source's while it has none. pub fn layer_shown_as<'f, 'a>(project: &Project<'f, 'a>, comp: &Comp<'f, 'a>, name: &str) -> Layer<'f, 'a> { - comp.layers().find(|l| project.layer_display_name(l).as_deref() == Some(name)).unwrap_or_else(|| panic!("no layer shown as {name}")) + let shown = |l: &Layer<'f, 'a>| l.name().or_else(|| project.layer_source(l)?.display_name()); + comp.layers().find(|l| shown(l).as_deref() == Some(name)).unwrap_or_else(|| panic!("no layer shown as {name}")) } /// The first layer of this type in a composition. diff --git a/crates/aep/tests/it/container/keyframes.rs b/crates/aep/tests/it/container/keyframes.rs index 56ec367cc..27b8073ab 100644 --- a/crates/aep/tests/it/container/keyframes.rs +++ b/crates/aep/tests/it/container/keyframes.rs @@ -19,6 +19,9 @@ fn prop_of(name: &str, path: &[&str], f: impl FnOnce(Property<'_, '_>) -> R) const POSITION: &[&str] = &["ADBE Transform Group", "ADBE Position"]; const OPACITY: &[&str] = &["ADBE Transform Group", "ADBE Opacity"]; +/// The ease of a linear key: all four slots 0. +const NO_EASE: KeyEase = KeyEase { in_speed: 0.0, in_influence: 0.0, out_speed: 0.0, out_influence: 0.0 }; + fn ease(in_speed: f64, in_influence: f64, out_speed: f64, out_influence: f64) -> KeyEase { KeyEase { in_speed, in_influence, out_speed, out_influence } } @@ -33,7 +36,7 @@ fn in_and_out_interpolation_are_separate_bytes() { assert_eq!((keys[0].interpolation_in(), keys[0].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Hold))); assert_eq!((keys[1].interpolation_in(), keys[1].interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 1.0]); - assert_eq!(keys[1].spatial_value(), Some([100.0, 0.0, 0.0])); + assert_eq!(keys[1].value(), Some(vec![100.0, 0.0, 0.0])); })); // 203: key 1 inType HOLD, outType LINEAR (bytes 03 01): byte 4 is the incoming side. skip!(prop_of("203-key-in-hold-out-linear.aep", POSITION, |p| { @@ -76,7 +79,7 @@ fn opacity_ease_speed_is_in_stored_units_per_second() { assert_near(&[e0.in_speed, e0.in_influence, e0.out_speed, e0.out_influence], &[0.05, 0.2, 0.2, 0.8], 1e-12); let e1 = keys[1].ease().unwrap(); assert_near(&[e1.in_speed, e1.in_influence, e1.out_speed, e1.out_influence], &[0.3, 0.6, 0.09, 0.4], 1e-12); - assert_eq!(keys[0].plain_ease_slots().unwrap().len(), 4); + assert_eq!(keys[0].ease_components(), Some(vec![e0])); for k in &keys { assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Bezier), Some(Interpolation::Bezier))); } @@ -94,7 +97,7 @@ fn scale_keys_use_the_plain_template_with_three_components() { // A 128-byte record is not always spatial: the header's template flag decides. assert_eq!(k.kind(), KeyframeKind::Plain { components: 3 }); assert_eq!(k.spatial(), None); - assert_eq!(k.plain_ease_slots(), Some(vec![0.0; 12])); + assert_eq!(k.ease_components(), Some(vec![NO_EASE; 3])); assert_eq!(k.ease(), None); assert_eq!((k.interpolation_in(), k.interpolation_out()), (Some(Interpolation::Linear), Some(Interpolation::Linear))); } @@ -125,7 +128,7 @@ fn two_dimensional_mask_feather_keys() { assert!(keys.iter().all(|k| k.raw().len() == 88 && k.kind() == KeyframeKind::Plain { components: 2 })); assert_eq!(keys.iter().map(|k| k.value().unwrap()).collect::>(), [vec![0.0, 0.0], vec![40.0, 20.0]]); assert_eq!(keys.iter().map(|k| k.seconds(25600).unwrap()).collect::>(), [0.0, 1.0]); - assert_eq!(keys[0].plain_ease_slots(), Some(vec![0.0; 8])); + assert_eq!(keys[0].ease_components(), Some(vec![NO_EASE; 2])); let mask = &layer.masks()[0]; assert!(mask.feather.source == ValueSource::Keyframed && mask.feather.value == [0.0, 0.0]); } diff --git a/crates/aep/tests/it/container/layer_switches.rs b/crates/aep/tests/it/container/layer_switches.rs index 5e2179d53..05e939c38 100644 --- a/crates/aep/tests/it/container/layer_switches.rs +++ b/crates/aep/tests/it/container/layer_switches.rs @@ -2,7 +2,7 @@ //! colours, checked against the values the corpus was made with (its MANIFEST, batch 2). use crate::container::helpers::{assert_near, base_layer, first_comp, layer_of_type, layer_shown_as, open}; -use craft_aep::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Project, Rational, ValueSource}; +use craft_aep::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Project}; fn l_header(name: &str) -> Option { Some({ @@ -80,22 +80,24 @@ fn ntsc_frame_rates_are_exact_fractions() { // 229: frameRate 29.97 -> read back 29.9700012207031; the duration snaps from 5 s to 150 frames (5.005005 s). let h = skip!(comp_header("229-comp-fps-29.97.aep")); assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (800, 23976)); - assert_eq!(h.frame_rate_exact(), Some(Rational { num: 2997, den: 100 })); assert!((h.frame_rate().unwrap() - 29.97).abs() < 1e-12); - assert!((h.frame_rate_from_fixed() - 29.970_001_220_703_1).abs() < 1e-7); - assert_eq!((h.duration_units, h.duration_frames()), (120_000, Some(150))); + // The 16.16 rate holds the float32 29.97 (29.9700012207031). + assert_eq!(h.frame_rate_fixed, 1_964_114); + // 150 frames of 800 units. + assert_eq!(h.duration_units, 120_000); assert!((h.duration_seconds().unwrap() - 5.005_005_005_005_01).abs() < 1e-9); // 230: frameRate 23.976 -> read back 23.9759979248047; 120 frames. let h = skip!(comp_header("230-comp-fps-23.976.aep")); assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1000, 23976)); - assert_eq!(h.frame_rate_exact(), Some(Rational { num: 2997, den: 125 })); assert!((h.frame_rate().unwrap() - 23.976).abs() < 1e-12); - assert!((h.frame_rate_from_fixed() - 23.975_997_924_804_7).abs() < 1e-7); - assert_eq!((h.duration_units, h.duration_frames()), (120_000, Some(120))); + // The 16.16 rate holds the float32 23.976 (23.9759979248047). + assert_eq!(h.frame_rate_fixed, 1_571_291); + // 120 frames of 1000 units. + assert_eq!(h.duration_units, 120_000); assert!((h.duration_seconds().unwrap() - 5.005_005_005_005_01).abs() < 1e-9); // 25 fps stays 25. let h = skip!(comp_header("000-base.aep")); - assert_eq!((h.frame_rate_exact(), h.duration_frames()), (Some(Rational { num: 25, den: 1 }), Some(125))); + assert_eq!((h.time_base.timescale, h.time_base.frame_duration, h.duration_units), (25600, 1024, 128_000)); } #[test] @@ -128,7 +130,6 @@ fn background_is_8_bits_per_channel() { // 231: bgColor [0.5, 0.5, 0.5] is stored as 128 and reads back as 128/255 = 0.50196. let h = skip!(comp_header("231-comp-bg-grey-0.5.aep")); assert_eq!(h.background, [128, 128, 128]); - assert_near(&h.background_rgb(), &[0.501_960_784_313_73; 3], 1e-12); // The frame rate stays 25 even though an earlier edit of the AE session left other numbers in the cache-like fields. assert_eq!((h.time_base.frame_duration, h.time_base.timescale), (1024, 25600)); } @@ -143,12 +144,10 @@ fn cameras_auto_orient_and_position() { let camera = layer_of_type(&comp, LayerType::Camera); let h = camera.header().unwrap(); assert_eq!((h.flag_bytes[1], h.is_auto_oriented(), h.is_three_d(), h.source_id, h.light_type()), (0x44, true, true, None, None)); - // The default Position is an "auto state" record that stores [0, 0, -2666.67]; the two-node camera reports the comp centre. + // The default Position is an "auto state" record that stores [0, 0, -2666.67]. let pos = camera.camera_position().unwrap(); assert!(pos.auto_state); assert_near(&pos.stored, &[0.0, 0.0, -2666.67], 0.01); - assert_near(&pos.reported(1920, 1080, true), &[960.0, 540.0, -2666.67], 0.01); - assert_eq!(camera.camera_point_of_interest(), Some([960.0, 540.0, 0.0])); let bytes = fixture!("251-camera-one-node.aep"); let file = open(&bytes); @@ -159,10 +158,9 @@ fn cameras_auto_orient_and_position() { // AE reports [0, 0, -2666.67] for the one-node camera: the stored value. let pos = camera.camera_position().unwrap(); assert!(pos.auto_state); - assert_near(&pos.reported(1920, 1080, h.is_auto_oriented()), &[0.0, 0.0, -2666.67], 0.01); - assert_eq!(camera.camera_point_of_interest(), Some([960.0, 540.0, 0.0])); + assert_near(&pos.stored, &[0.0, 0.0, -2666.67], 0.01); - // 253: Position set to [100, 200, -1000]: stored as given, no auto state; the point of interest stays [960, 540, 0]. + // 253: Position set to [100, 200, -1000]: stored as given, no auto state. let bytes = fixture!("253-camera-position-100-200-m1000.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); @@ -170,35 +168,28 @@ fn cameras_auto_orient_and_position() { let pos = camera.camera_position().unwrap(); assert!(!pos.auto_state); assert_eq!(pos.stored, [100.0, 200.0, -1000.0]); - assert_eq!(pos.reported(1920, 1080, true), [100.0, 200.0, -1000.0]); - assert_eq!(camera.camera_point_of_interest(), Some([960.0, 540.0, 0.0])); - // A camera has no light intensity. - assert_eq!(camera.light_intensity(), None); } +/// Lights type and position. #[test] -fn lights_type_and_intensity() { - // 254: a spot light, Intensity 100 -> 50 (stored as 50.0 percent, absent at the default 100). +fn lights_type_and_position() { + // 254: a spot light (its Intensity 50 is checked on import). let bytes = fixture!("254-light-spot-intensity-50.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); let light = layer_of_type(&first_comp(&project), LayerType::Light); let h = light.header().unwrap(); assert_eq!((h.light_type(), h.light_type_code, h.source_id, h.is_auto_oriented(), h.is_three_d()), (Some(LightType::Spot), 1, None, true, true)); - let intensity = light.light_intensity().unwrap(); - assert_eq!((intensity.value, intensity.source), (50.0, ValueSource::Stored)); assert!(light.camera_position().unwrap().auto_state); assert_near(&light.camera_position().unwrap().stored, &[0.0, 0.0, -1333.33], 0.01); - // 252: a point light (light type 2) at the default intensity, which is not stored. + // 252: a point light (light type 2). let bytes = fixture!("252-light-point.aep"); let file = open(&bytes); let project = Project::new(&file).unwrap(); let light = layer_of_type(&first_comp(&project), LayerType::Light); let h = light.header().unwrap(); assert_eq!((h.light_type(), h.light_type_code), (Some(LightType::Point), 2)); - let intensity = light.light_intensity().unwrap(); - assert_eq!((intensity.value, intensity.source), (100.0, ValueSource::Default)); // The solid under it is no light. let solid = base_layer(&first_comp(&project)).header().unwrap(); assert_eq!((solid.light_type(), solid.light_type_code), (None, 0)); @@ -220,6 +211,6 @@ fn solid_colour_is_four_float32_argb() { // L is still red. let red = project.layer_source(&base_layer(&comp)).unwrap().footage().unwrap(); assert_eq!(red.solid_rgb(), Some([1.0, 0.0, 0.0])); - // The new layer has no user-set name flag (it shows its source's name). - assert!(!blue.header().unwrap().name_is_user_set()); + // The new layer has no name of its own (it shows its source's name). + assert_eq!(blue.name(), None); } diff --git a/crates/aep/tests/it/container/matte.rs b/crates/aep/tests/it/container/matte.rs index 97c8aad74..c05045e39 100644 --- a/crates/aep/tests/it/container/matte.rs +++ b/crates/aep/tests/it/container/matte.rs @@ -13,7 +13,7 @@ fn layers(name: &str) -> Option, u32)>> { comp.layers() .map(|l| { let h = l.header().expect("header"); - (project.layer_display_name(&l).unwrap_or_default(), h.is_video_enabled(), l.track_matte(), h.id) + (l.name().or_else(|| project.layer_source(&l)?.display_name()).unwrap_or_default(), h.is_video_enabled(), l.track_matte(), h.id) }) .collect() }) diff --git a/crates/aep/tests/it/container/robustness.rs b/crates/aep/tests/it/container/robustness.rs index f27f53d25..0f26cdd4c 100644 --- a/crates/aep/tests/it/container/robustness.rs +++ b/crates/aep/tests/it/container/robustness.rs @@ -154,16 +154,15 @@ use craft_aep::{AepFile, Body, Chunk, Comp, Layer, Project, PropGroup, PropNode, /// Touches the property accessors; none may panic on a damaged property. fn exercise_property(p: &Property<'_, '_>) { - let _ = (p.header(), p.dims(), p.is_animated(), p.static_value(), p.time_scale(), p.flags(), p.is_static_flag_set()); - let _ = (p.expression(), p.expression_flags().map(|f| (f.all_set(), f.disabled())), p.expression_enabled(), p.user_name(), p.first_key_value()); - let _ = p.color_argb(); + let _ = (p.header(), p.dims(), p.is_animated(), p.static_value(), p.time_scale(), p.flags()); + let _ = (p.expression(), p.expression_flags().map(|f| f.disabled()), p.expression_enabled(), p.user_name(), p.first_key_value()); if let Some(keys) = p.keys() { let scale = p.time_scale().unwrap_or(0); for k in keys.keyframes() { - let _ = (k.time_units(), k.spatial_value(), k.raw().len(), k.kind(), k.seconds(scale), k.seconds(0)); + let _ = (k.time_units(), k.raw().len(), k.kind(), k.seconds(scale), k.seconds(0)); let _ = (k.interpolation_in(), k.interpolation_out(), k.flags(), k.label(), k.is_roving()); - let _ = (k.scalar_value(), k.ease(), k.spatial(), k.components(), k.value(), k.plain_ease_slots()); - let _ = (k.ease_components(), k.color_distance()); + let _ = (k.scalar_value(), k.ease(), k.spatial(), k.components(), k.value()); + let _ = k.ease_components(); for component in [0, 1, 2, 3, 7, 255, usize::MAX] { let _ = k.ease_component(component); } @@ -193,10 +192,9 @@ fn exercise_group(g: &PropGroup<'_, '_>, depth: usize) { fn exercise_layer(project: &Project<'_, '_>, comp_size: (u32, u32), layer: &Layer<'_, '_>) { let _ = (layer.name(), layer.is_three_d(), layer.id(), layer.track_matte()); if let Some(h) = layer.header() { - let _ = (h.in_point(), h.out_point(), h.in_point_seconds(), h.out_point_seconds(), h.start_seconds(), h.stretch_percent()); - let _ = (h.stretch_ratio(), h.stretch_den); + let _ = (h.in_point(), h.out_point(), h.stretch_ratio(), h.stretch_den); let _ = (h.is_shy(), h.is_locked(), h.is_solo(), h.is_three_d(), h.is_motion_blur(), h.is_adjustment(), h.is_guide()); - let _ = (h.is_null_object(), h.collapses_transformations(), h.name_is_user_set(), h.quality, h.blend_mode, h.layer_type); + let _ = (h.is_null_object(), h.collapses_transformations(), h.quality, h.blend_mode, h.layer_type); let _ = ( h.is_enabled(), h.is_video_enabled(), @@ -208,10 +206,8 @@ fn exercise_layer(project: &Project<'_, '_>, comp_size: (u32, u32), layer: &Laye ); } let _ = (layer.is_enabled(), layer.is_audio_enabled(), layer.is_effects_enabled()); - let _ = (layer.camera_position().map(|p| p.reported(comp_size.0, comp_size.1, true)), layer.camera_point_of_interest(), layer.light_intensity()); + let _ = layer.camera_position().map(|p| (p.stored, p.auto_state)); let _ = project.layer_anchor_px(layer); - let _ = (layer.camera_zoom(), layer.camera_depth_of_field(), layer.camera_focus_distance(), layer.camera_aperture()); - let _ = (layer.light_color(), layer.light_cone_angle(), layer.light_cone_feather()); let _ = layer .time_remap() .map(|t| (t.enabled, t.keys.iter().fold(0.0, |acc, k| acc + k.value_seconds + k.time_seconds.unwrap_or(0.0) + f64::from(k.time_units)))); @@ -238,7 +234,8 @@ fn exercise_layer(project: &Project<'_, '_>, comp_size: (u32, u32), layer: &Laye } } } - let _ = (project.layer_source(layer).map(|i| i.id()), project.layer_display_name(layer), project.layer_source_size(layer)); + let _ = + (project.layer_source(layer).map(|i| i.id()), project.layer_source(layer).and_then(|i| i.display_name()), project.layer_source_size(layer)); if let Some(t) = layer.transform(comp_size.0, comp_size.1) { let _ = (t.anchor_px(f64::from(comp_size.0), f64::from(comp_size.1)), t.position.value, t.opacity_percent.value); } @@ -271,7 +268,6 @@ fn exercise_layer(project: &Project<'_, '_>, comp_size: (u32, u32), layer: &Laye } for m in layer.masks() { let _ = (m.name.clone(), m.mode, m.inverted, m.counter, m.feather, m.opacity_percent, m.expansion, m.path_animated, m.path_key_seconds.len()); - let _ = project.mask_vertices_px(layer, &m).map(|shapes| shapes.iter().map(Vec::len).sum::()); for s in &m.shapes { let _ = (s.vertex_count(), s.vertices((1920.0, 1080.0)).len(), s.vertices((f64::NAN, f64::INFINITY)).len(), s.open); } @@ -302,10 +298,9 @@ fn exercise_comp(project: &Project<'_, '_>, comp: &Comp<'_, '_>) { let mut size = (1920, 1080); if let Some(h) = comp.header() { size = (u32::from(h.width), u32::from(h.height)); - let _ = (h.frame_rate(), h.frame_rate_from_fixed(), h.duration_seconds(), h.work_area_start_seconds(), h.work_area_end_seconds()); - let _ = (h.frame_rate_exact(), h.duration_frames()); - let _ = (h.background_rgb(), h.pixel_aspect_ratio(), h.pixel_aspect.reduced(), h.shutter_angle, h.motion_blur); - let _ = (h.shutter_phase, h.display_start, h.display_start_seconds(), h.display_start_frame()); + let _ = (h.frame_rate(), h.frame_rate_fixed, h.duration_seconds(), h.work_area_start_units, h.work_area_end_units); + let _ = (h.background, h.pixel_aspect.to_f64(), h.pixel_aspect.reduced(), h.shutter_angle, h.motion_blur); + let _ = (h.shutter_phase, h.display_start.map(|r| r.to_f64())); } for layer in comp.layers() { exercise_layer(project, size, &layer); @@ -316,10 +311,8 @@ fn exercise_comp(project: &Project<'_, '_>, comp: &Comp<'_, '_>) { fn exercise(file: &AepFile<'_>) { let Some(project) = Project::new(file) else { return }; for item in project.all_items() { - let _ = (item.kind(), item.name(), item.id(), item.label(), item.used_item_ids(), item.footage(), item.display_name()); - let _ = item - .footage() - .map(|f| (f.duration, f.native_frame_rate, f.bits_per_pixel, f.file_size, f.audio_sample_rate, f.is_sequence, f.sequence_frame_count())); + let _ = (item.kind(), item.name(), item.id(), item.label(), item.footage(), item.display_name()); + let _ = item.footage().map(|f| (f.duration, f.native_frame_rate, f.bits_per_pixel, f.file_size, f.audio_sample_rate, f.is_sequence)); let _ = item.id().and_then(|id| project.item_by_id(id)); if let Some(comp) = item.comp() { exercise_comp(&project, &comp); @@ -572,12 +565,12 @@ fn extreme_values_in_the_decoded_headers() { use craft_aep::{CompHeader, LayerHeader, Rational, ShapePath}; // Every field at its maximum: no overflow, no division by zero, no panic. let h = LayerHeader::parse(&[0xff; 164]).unwrap(); - let _ = (h.in_point(), h.out_point(), h.in_point_seconds(), h.out_point_seconds(), h.start_seconds(), h.stretch_percent()); + let _ = (h.in_point(), h.out_point(), h.start.to_f64(), h.stretch_ratio()); let mut zero_den = [0u8; 164]; zero_den[8..12].copy_from_slice(&u32::MAX.to_be_bytes()); zero_den[12..16].copy_from_slice(&i32::MIN.to_be_bytes()); let h = LayerHeader::parse(&zero_den).unwrap(); - assert_eq!((h.in_point(), h.out_point(), h.start_seconds()), (None, None, None)); + assert_eq!((h.in_point(), h.out_point(), h.start.to_f64()), (None, None, None)); let mut wide = [0u8; 164]; wide[8..12].copy_from_slice(&u32::MAX.to_be_bytes()); wide[12..16].copy_from_slice(&i32::MIN.to_be_bytes()); @@ -585,14 +578,12 @@ fn extreme_values_in_the_decoded_headers() { wide[20..24].copy_from_slice(&i32::MAX.to_be_bytes()); wide[24..28].copy_from_slice(&u32::MAX.to_be_bytes()); let h = LayerHeader::parse(&wide).unwrap(); - let _ = (h.in_point(), h.in_point_seconds()); + let _ = h.in_point(); let c = CompHeader::parse(&[0xff; 204]).unwrap(); - assert_eq!((c.duration_seconds(), c.work_area_start_seconds(), c.work_area_end_units), (None, None, None)); - let _ = (c.frame_rate(), c.frame_rate_from_fixed(), c.background_rgb(), c.pixel_aspect_ratio(), c.frame_rate_exact()); - assert_eq!(c.duration_frames(), Some(1)); + assert_eq!((c.duration_seconds(), c.work_area_end_units), (None, None)); + let _ = (c.frame_rate(), c.pixel_aspect.to_f64()); let zero = CompHeader::parse(&[0; 204]).unwrap(); - assert_eq!((zero.frame_rate(), zero.pixel_aspect_ratio(), zero.duration_seconds()), (None, None, None)); - assert_eq!((zero.frame_rate_exact(), zero.duration_frames()), (None, None)); + assert_eq!((zero.frame_rate(), zero.pixel_aspect.to_f64(), zero.duration_seconds()), (None, None, None)); let all = LayerHeader::parse(&[0xff; 164]).unwrap(); let _ = (all.is_enabled(), all.is_auto_oriented(), all.light_type(), all.blend_mode.code()); assert_eq!(LayerHeader::parse(&[0u8; 164]).unwrap().light_type(), None); @@ -691,7 +682,7 @@ fn hostile_text_dictionaries_and_marker_headers_never_panic() { #[test] fn extreme_values_in_the_batch_3_fields() { - use craft_aep::{CompHeader, Footage, LayerHeader, Rational}; + use craft_aep::{CompHeader, LayerHeader}; // Time stretch: zero and maximal numerators and denominators (bytes 8 and 108), with extreme times. for (num, den) in [(0u32, 0u32), (1, 0), (0, 1), (u32::MAX, 1), (1, u32::MAX), (u32::MAX, u32::MAX), (3, 2)] { let mut ldta = [0u8; 164]; @@ -704,7 +695,7 @@ fn extreme_values_in_the_batch_3_fields() { ldta[28..32].copy_from_slice(&i32::MIN.to_be_bytes()); ldta[32..36].copy_from_slice(&1u32.to_be_bytes()); let h = LayerHeader::parse(&ldta).unwrap(); - let _ = (h.stretch_ratio(), h.stretch_percent(), h.in_point(), h.out_point(), h.in_point_seconds(), h.out_point_seconds()); + let _ = (h.stretch_ratio(), h.in_point(), h.out_point()); if den == 0 { assert_eq!((h.stretch_ratio(), h.in_point(), h.out_point()), (None, None, None)); } @@ -712,34 +703,8 @@ fn extreme_values_in_the_batch_3_fields() { // Display start and shutter phase from extreme bytes; a missing tail leaves them unknown. for fill in [0x00u8, 0x7f, 0x80, 0xff] { let c = CompHeader::parse(&[fill; 204]).unwrap(); - let _ = (c.shutter_phase, c.display_start, c.display_start_seconds(), c.display_start_frame()); + let _ = (c.shutter_phase, c.display_start.map(|r| r.to_f64())); } - let zero_rate = CompHeader::parse(&[0; 204]).unwrap(); - assert_eq!((zero_rate.display_start_seconds(), zero_rate.display_start_frame()), (None, None)); - // Footage durations: zero denominator, negative and maximal numerators, a huge frame rate. - let base = Footage { - file_type: String::new(), - width: 0, - height: 0, - name: None, - is_solid: false, - solid_argb: None, - path: None, - duration: None, - native_frame_rate: 0, - bits_per_pixel: 0, - file_size: 0, - audio_sample_rate: None, - is_sequence: true, - psd_layer: None, - }; - for (num, den, rate) in - [(3i64, 30i64, 30u32), (3, 0, 30), (-3, 30, 30), (i64::MAX, 1, u32::MAX), (i64::MIN, -1, u32::MAX), (1, i64::MAX, 1), (0, 1, 0)] - { - let f = Footage { duration: Some(Rational { num, den }), native_frame_rate: rate, ..base.clone() }; - let _ = f.sequence_frame_count(); - } - assert_eq!(Footage { duration: Some(Rational { num: 3, den: 30 }), native_frame_rate: 30, ..base.clone() }.sequence_frame_count(), Some(3)); - assert_eq!(Footage { duration: Some(Rational { num: 3, den: 0 }), native_frame_rate: 30, ..base.clone() }.sequence_frame_count(), None); - assert_eq!(Footage { duration: None, ..base }.sequence_frame_count(), None); + // A zero denominator has no value. + assert_eq!(CompHeader::parse(&[0; 204]).unwrap().display_start.and_then(|r| r.to_f64()), None); } diff --git a/crates/aep/tests/it/container/text_markers_footage.rs b/crates/aep/tests/it/container/text_markers_footage.rs index 6d666fbee..f6f81eed1 100644 --- a/crates/aep/tests/it/container/text_markers_footage.rs +++ b/crates/aep/tests/it/container/text_markers_footage.rs @@ -13,7 +13,6 @@ fn text_layer_document(name: &str) -> Option { let layer = comp.layers().find(|l| l.name().as_deref() == Some("T")).expect("the text layer T"); let h = layer.header().unwrap(); assert_eq!(h.layer_type, LayerType::Text); - assert!(h.name_is_user_set()); layer.text_document().expect("text document") }) } @@ -192,7 +191,6 @@ fn png_footage_layer() { // The path comes from the alias JSON (the fixture holds a neutral replacement of the original). assert!(f.path.as_deref().is_some_and(|p| p.ends_with("test8x8.png")), "{:?}", f.path); assert_eq!(project.layer_source_size(&layer), Some((8, 8))); - assert_eq!(project.layer_display_name(&layer).as_deref(), Some("png")); // L is still there below it. assert_eq!(comp.layers().count(), 2); } diff --git a/crates/aep/tests/it/container/tree_index.rs b/crates/aep/tests/it/container/tree_index.rs new file mode 100644 index 000000000..c1bed0163 --- /dev/null +++ b/crates/aep/tests/it/container/tree_index.rs @@ -0,0 +1,231 @@ +//! The flat tree index the importer reads ([`TreeIndex`]) against the owned chunk tree, on every +//! file of the fixture directory: the same tree, and the same answers from the typed view. + +use std::fmt::Write as _; + +use craft_aep::index::TreeIndex; +use craft_aep::{ + AepFile, Chunk, CryptomatteData, CurvesData, Effect, HueSaturationData, LevelsData, Limits, MeshData, Project, PropGroup, PropNode, is_aepx, + parse, parse_with_limits, read_aepx, write, +}; + +/// Every `.aep` and `.aepx` in the fixture directory (the real projects included), sorted. +fn every_file() -> Vec { + let Some(dir) = crate::common::dir() else { + crate::common::skipped("*.aep"); + return Vec::new(); + }; + let Ok(entries) = std::fs::read_dir(&dir) else { + crate::common::skipped("*.aep"); + return Vec::new(); + }; + let mut out: Vec = + entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "aep" || x == "aepx")).collect(); + out.sort(); + out +} + +/// What the typed view reads from a project, as text: items, compositions, layers with their +/// headers, transforms, masks, effects with every parameter value, text, markers, the whole +/// property tree with static values and key records, settings and versions. +fn dump(view: &Project<'_, '_>) -> String { + let mut s = String::new(); + let defs = view.effect_definition_index(); + for item in view.all_items() { + let _ = writeln!(s, "item {:?} {:?} {:?} {:?} {:?}", item.kind(), item.name(), item.display_name(), item.id(), item.label()); + let _ = writeln!(s, " footage {:?} {:?} {:?}", item.footage(), item.sequence_info(), item.conform_frame_rate()); + let _ = writeln!(s, " folder {} {}", item.has_folder_contents(), item.folder_contents_unreadable()); + let Some(comp) = item.comp() else { continue }; + let _ = writeln!(s, " comp {:?} {:?} {:?}", comp.time_base(), comp.header(), comp.markers()); + for layer in comp.layers() { + let _ = writeln!(s, " layer {:?} {:?} {:?} {:?}", layer.name(), layer.id(), layer.header(), layer.track_matte()); + let _ = writeln!(s, " transform {:?}", layer.transform(1920, 1080)); + let _ = writeln!(s, " time remap {:?} orientation {:?} {:?}", layer.time_remap(), layer.orientation(), layer.orientation_keys()); + let _ = writeln!(s, " masks {:?}", layer.mask_atoms().iter().map(|m| (&m.mask, &m.path_shapes)).collect::>()); + let _ = writeln!(s, " shapes {:?}", layer.shape_groups()); + let _ = writeln!( + s, + " text {:?} {} {:?}", + layer.text_document(), + layer.text_document_count(), + layer.source_text_property().map(|p| p.is_animated()) + ); + let _ = writeln!(s, " markers {:?} source {:?}", layer.markers(), view.layer_source(&layer).map(|i| i.id())); + for fx in layer.effects() { + let _ = writeln!( + s, + " fx {} {:?} {:?} {:?} {:?}", + fx.match_name(), + fx.display_name(), + fx.enabled(), + defs.source(&fx), + fx.value_record_names() + ); + let _ = + writeln!(s, " names {:?} {:?} {:?} {:?}", fx.name(), fx.user_name(), fx.declared_param_count(), fx.has_own_definitions()); + for p in defs.params(&fx) { + let _ = writeln!(s, " {} {:?} {:?} {:?} {:?}", p.match_name, p.kind, p.name, p.items, p.value()); + arbitrary(&fx, &p.match_name, &mut s); + } + for name in fx.value_record_names() { + arbitrary(&fx, &name, &mut s); + } + } + if let Some(root) = layer.properties() { + tree(&root, 0, &mut s); + } + } + } + s +} + +/// The arbitrary data stored for a parameter and what each decoder reads from it. +fn arbitrary(fx: &Effect<'_, '_>, name: &str, s: &mut String) { + let Some(data) = fx.arbitrary_data(name) else { return }; + let _ = writeln!(s, " arbitrary {name} {data:?}"); + let _ = writeln!(s, " {:?} {:?}", HueSaturationData::parse(data), LevelsData::parse(data)); + let _ = writeln!(s, " {:?} {:?} {:?}", CurvesData::parse(data), MeshData::parse(data), CryptomatteData::parse(data)); +} + +/// Appends a group and everything below it to the dump, depth-limited. +fn tree(group: &PropGroup<'_, '_>, depth: usize, s: &mut String) { + if depth > 32 { + return; + } + let _ = writeln!(s, "{:depth$}group {:?} {:?}", "", group.user_name(), group.flags()); + for e in group.entries() { + match e.node { + PropNode::Group(g) => tree(&g, depth + 1, s), + PropNode::Property(p) => { + let keys: Option>> = p.keys().map(|k| k.records().map(<[u8]>::to_vec).collect()); + let _ = writeln!(s, "{:depth$} {} {:?} {:?} {:?} {:?}", "", e.match_name, p.user_name(), p.header(), p.static_value(), keys); + } + PropNode::Other(c) => { + let _ = writeln!(s, "{:depth$} {} other {:?} {}", "", e.match_name, c.list_type(), c.descendants().count()); + } + } + } +} + +/// The index is the parsed tree and the view reads the same on every file. +#[test] +fn the_index_is_the_parsed_tree_and_the_view_reads_the_same_on_every_file() { + for path in every_file() { + let name = path.display().to_string(); + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{name}: {e}")); + // `.aepx` is read into the chunk tree and indexed from it; `.aep` is indexed in place. + // A file that does not read (a damaged sample) must fail the index the same way. + let file: AepFile<'_> = match if is_aepx(&bytes) { read_aepx(&bytes) } else { parse(&bytes) } { + Ok(file) => file, + Err(e) => { + if !is_aepx(&bytes) { + assert_eq!(TreeIndex::parse(&bytes).err(), Some(e), "{name}"); + } + continue; + } + }; + let index = (if is_aepx(&bytes) { TreeIndex::from_file(&file) } else { TreeIndex::parse(&bytes) }).unwrap_or_else(|e| panic!("{name}: {e}")); + assert!(index.to_file() == file, "{name}: the index is not the parsed tree"); + assert_eq!(index.len(), file.walk().count(), "{name}"); + assert_eq!(index.file_version(), file.file_version(), "{name}"); + assert_eq!(index.saved_by_version(), file.saved_by_version(), "{name}"); + assert_eq!(craft_aep::ProjectSettings::read_index(&index), craft_aep::ProjectSettings::read(&file), "{name}"); + let (Some(a), Some(b)) = (Project::new(&file), Project::from_index(&index)) else { + assert!(Project::new(&file).is_none() && Project::from_index(&index).is_none(), "{name}"); + continue; + }; + let (da, db) = (dump(&a), dump(&b)); + assert!(da == db, "{name}: the view reads differently through the index"); + } +} + +/// The index and the parser fail alike under tight limits. +#[test] +fn the_index_and_the_parser_fail_alike_under_tight_limits() { + for path in every_file().into_iter().filter(|p| p.extension().is_some_and(|x| x == "aep")) { + let name = path.display().to_string(); + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{name}: {e}")); + let total = parse(&bytes).map(|f| f.walk().count()).unwrap_or(0); + for limits in [ + Limits { max_depth: 2, max_chunks: 10_000_000 }, + Limits { max_depth: 6, max_chunks: 10_000_000 }, + Limits { max_depth: 64, max_chunks: total }, + Limits { max_depth: 64, max_chunks: total.saturating_sub(1) }, + Limits { max_depth: 64, max_chunks: total / 2 }, + ] { + let old = parse_with_limits(&bytes, limits); + let new = TreeIndex::parse_with_limits(&bytes, limits); + match (old, new) { + (Ok(f), Ok(i)) => assert!(i.to_file() == f, "{name}: {limits:?}"), + (Err(a), Err(b)) => assert_eq!(a, b, "{name}: {limits:?}"), + (a, b) => panic!("{name}: {limits:?}: {:?} vs {:?}", a.err(), b.err()), + } + } + } +} + +/// A 40-byte NUL-padded match name. +fn tdmn(name: &str) -> Chunk<'static> { + let mut b = name.as_bytes().to_vec(); + b.resize(40, 0); + Chunk::data(*b"tdmn", b) +} + +/// A nested chunk `id` holding one `Utf8` with `text`. +fn utf8(id: [u8; 4], text: &str) -> Chunk<'static> { + Chunk { id, body: craft_aep::Body::Chunks(vec![Chunk::data(*b"Utf8", text.as_bytes().to_vec())]), pad: None } +} + +/// A project with one composition, one layer and one effect whose five parameters carry arbitrary +/// data in the sizes the decoders read (Hue/Saturation, Levels, Curves, a 2 x 2 mesh, Cryptomatte), +/// so the arbitrary-data path runs without the fixture directory. +fn synthetic() -> Vec { + let mut mesh = vec![0u8; 180]; + mesh[..8].copy_from_slice(&[0, 0, 0, 2, 0, 0, 0, 2]); + let mut cry = vec![0u8; 200]; + cry[..4].copy_from_slice(b"cry1"); + cry[32..37].copy_from_slice(b"Layer"); + let mut levels = vec![0u8; 108]; + levels[8..16].copy_from_slice(&1.0f64.to_be_bytes()); + let payloads: [Vec; 5] = [vec![7u8; 180], levels, vec![0u8; CurvesData::SIZE], mesh, cry]; + let (mut part, mut values) = + (vec![Chunk::data(*b"parn", 6u32.to_be_bytes().to_vec())], vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), utf8(*b"tdsn", "Mine")]); + for (i, data) in payloads.into_iter().enumerate() { + let name = format!("FX-{:04}", i + 1); + let mut pard = vec![0u8; 148]; + pard[12..16].copy_from_slice(&11u32.to_be_bytes()); + part.extend([tdmn(&name), Chunk::data(*b"pard", pard)]); + let record = Chunk::list(*b"tdbs", vec![Chunk::data(*b"tdsb", 1u32.to_be_bytes().to_vec()), Chunk::data(*b"cdat", vec![0, 0, 0, 1])]); + values.extend([tdmn(&name), record, Chunk::list(*b"aRbs", vec![Chunk::data(*b"aRbp", data)])]); + } + values.push(tdmn("ADBE Group End")); + let sspc = Chunk::list(*b"sspc", vec![utf8(*b"fnam", "Effect"), Chunk::list(*b"parT", part), Chunk::list(*b"tdgp", values)]); + let parade = Chunk::list(*b"tdgp", vec![tdmn("FX"), sspc, tdmn("ADBE Group End")]); + let root = Chunk::list(*b"tdgp", vec![tdmn("ADBE Effect Parade"), parade, tdmn("ADBE Group End")]); + let layer = Chunk::list(*b"Layr", vec![Chunk::data(*b"ldta", vec![0u8; 160]), Chunk::data(*b"Utf8", b"Layer".to_vec()), root]); + let mut idta = vec![0u8; 64]; + idta[..2].copy_from_slice(&4u16.to_be_bytes()); + idta[16..20].copy_from_slice(&2u32.to_be_bytes()); + let mut cdta = vec![0u8; 200]; + cdta[4..12].copy_from_slice(&[0, 0, 0, 1, 0, 0, 0, 30]); + let item = Chunk::list(*b"Item", vec![Chunk::data(*b"idta", idta), Chunk::data(*b"Utf8", b"Comp".to_vec()), Chunk::data(*b"cdta", cdta), layer]); + let file = + AepFile { chunks: vec![Chunk::data(*b"head", vec![0u8; 20]), Chunk::list(*b"Fold", vec![item])], trailer: std::borrow::Cow::Borrowed(&[]) }; + write(&file).expect("write") +} + +/// The view reads arbitrary effect data the same through the index. +#[test] +fn the_view_reads_arbitrary_effect_data_the_same_through_the_index() { + let bytes = synthetic(); + let file = parse(&bytes).expect("parse"); + let index = TreeIndex::parse(&bytes).expect("index"); + let (a, b) = (Project::new(&file).expect("project"), Project::from_index(&index).expect("project")); + let (da, db) = (dump(&a), dump(&b)); + assert_eq!(da, db); + // The synthetic effect really reaches every decoder (the dump is not empty of them). + assert_eq!(da.matches("arbitrary FX-").count(), 10, "{da}"); + assert!(da.contains("Some(HueSaturationData") && da.contains("Some(LevelsData") && da.contains("Some(CurvesData"), "{da}"); + assert!(da.contains("Some(MeshData") && da.contains("Some(CryptomatteData"), "{da}"); + assert!(da.contains("Some(\"Mine\")"), "the user name is read: {da}"); +} diff --git a/crates/aep/tests/it/container/typed.rs b/crates/aep/tests/it/container/typed.rs index 7299043e9..9be97f3fd 100644 --- a/crates/aep/tests/it/container/typed.rs +++ b/crates/aep/tests/it/container/typed.rs @@ -111,7 +111,7 @@ fn match_names_come_from_the_tdmn_chunks() { assert!(!names.iter().any(|n| n == "ADBE Group End")); assert!(root.find(&["ADBE Transform Group", "ADBE Nonexistent"]).is_none()); // The raw tdmn body is 40 bytes, NUL padded. - let raw = root.chunk().children().iter().find(|c| c.is(b"tdmn")).unwrap(); + let raw = root.chunk().children().find(|c| c.is(b"tdmn")).unwrap(); assert_eq!(raw.bytes().unwrap().len(), 40); } @@ -150,8 +150,8 @@ fn effect_parameter_value() { assert!(instance.is_list(b"sspc")); // The effect's name is in a nested fnam chunk. let fnam = instance.child(b"fnam").unwrap(); - assert!(matches!(fnam.body, Body::Chunks(_))); - assert_eq!(fnam.children()[0].bytes(), Some(&b"Slider Control"[..])); + assert!(matches!(fnam.to_chunk().body, Body::Chunks(_))); + assert_eq!(fnam.children().next().unwrap().bytes(), Some(&b"Slider Control"[..])); // The parameters are a property group inside the instance. let params = PropGroup::from_chunk(instance.child_list(b"tdgp").unwrap()).unwrap(); assert_eq!(params.names(), ["ADBE Slider Control-0000", "ADBE Slider Control-0001", "ADBE Effect Built In Params"]); @@ -186,7 +186,7 @@ fn position_keyframes() { assert_eq!(times, [0, 25_600, 64_000]); let seconds: Vec = times.iter().map(|t| tb.seconds(*t).unwrap()).collect(); assert_eq!(seconds, [0.0, 1.0, 2.5]); - let values: Vec<[f64; 3]> = keys.keyframes().map(|k| k.spatial_value().unwrap()).collect(); + let values: Vec> = keys.keyframes().map(|k| k.value().unwrap()).collect(); assert_eq!(values, [[0.0, 0.0, 0.0], [100.0, 0.0, 0.0], [200.0, 100.0, 0.0]]); } diff --git a/crates/aep/tests/it/container/values.rs b/crates/aep/tests/it/container/values.rs index 17fccf62f..6c3616012 100644 --- a/crates/aep/tests/it/container/values.rs +++ b/crates/aep/tests/it/container/values.rs @@ -119,7 +119,7 @@ fn linear_position_keys() { let values: Vec<_> = keys.iter().map(|k| k.spatial().unwrap().value).collect(); assert_eq!(values, [[0.0, 0.0, 0.0], [100.0, 0.0, 0.0], [200.0, 100.0, 0.0]]); assert_eq!(p.first_key_value(), Some(vec![0.0, 0.0, 0.0])); - assert_eq!(p.is_static_flag_set(), Some(false)); + assert!(p.is_animated()); })); // The transform of the layer reports the animated Position as keyframed (value at the first key). let (t, _) = skip!(transform("055-key-position-3key-inserted-t2.5.aep")); @@ -181,7 +181,7 @@ fn roving_and_label_flags() { assert_eq!(roving, [false, true, false]); assert_eq!(keys[1].time_units(), Some(26509)); assert_eq!(keys[1].seconds(25600), Some(1.0355078125)); - assert_eq!(keys[1].spatial_value(), Some([100.0, 0.0, 0.0])); + assert_eq!(keys[1].value(), Some(vec![100.0, 0.0, 0.0])); assert_eq!(keys[1].flags(), Some(0x0027)); assert_eq!(keys[1].label(), Some(0)); })); @@ -193,7 +193,7 @@ fn roving_and_label_flags() { assert_eq!(keys[1].flags(), Some(0x0247)); assert_eq!(keys[0].flags(), Some(0x0007)); assert_eq!(keys[1].is_roving(), Some(false)); - assert_eq!(keys[1].spatial_value(), Some([100.0, 0.0, 0.0])); + assert_eq!(keys[1].value(), Some(vec![100.0, 0.0, 0.0])); })); } @@ -204,7 +204,6 @@ fn scalar_opacity_keys() { assert!(p.is_animated()); assert_eq!(p.dims(), Some(1)); assert_eq!(p.time_scale(), Some(25600)); - assert_eq!(p.is_static_flag_set(), Some(false)); let list = p.keys().unwrap(); assert_eq!(list.header.record_size, 48); let keys: Vec<_> = list.keyframes().collect(); @@ -243,10 +242,8 @@ fn expression_text_and_flag_bytes() { assert_eq!(p.expression(), None); let flags = p.expression_flags().unwrap(); assert_eq!((flags.byte_76, flags.byte_77, flags.byte_120), (0, 0, 0)); - assert!(!flags.all_set()); // A written static property: tdsb 1, byte 5 of tdb4 has bit 0 set (15 for Position). assert_eq!(p.flags(), Some(1)); - assert_eq!(p.is_static_flag_set(), Some(true)); assert_eq!(p.header().and_then(|h| h.get(5).copied()), Some(15)); })); } diff --git a/crates/audio/README.md b/crates/audio/README.md index a1eb059d2..0c9f63a97 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -26,11 +26,11 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | Feature | Provides | Pulls in | |---|---|---| | `decode` | `decode`, `probe`, `Decoder`, `tracks`, `TrackDecoder`; every format in [Format support](#format-support) | `decode-native`, `symphonia` | -| `decode-native` | the same, native formats only (others are `Unsupported`) | the five decoders below, craft-media `isobmff`/`matroska`/`ogg`, `log` | +| `decode-native` | the same, native formats only (others are `Unsupported`); `wav_pcm`, `aiff_pcm` (a file's integer PCM bit for bit, as `RawPcm`) | the five decoders below, craft-media `isobmff`/`matroska`/`ogg`, `log` | | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | | `encode` | every encoder: the WAV, AIFF and FLAC file writers, and the AAC, ALAC, AC-3/E-AC-3 and MP3 encoders | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | -| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header` | none | +| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | | `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder` | craft-media `bitstream` | | `alac-decode` | `alac::Decoder` | none | diff --git a/crates/audio/src/aac/mod.rs b/crates/audio/src/aac/mod.rs index eb1c7d40a..34b081ea6 100644 --- a/crates/audio/src/aac/mod.rs +++ b/crates/audio/src/aac/mod.rs @@ -113,6 +113,26 @@ pub fn wav_order(channel_config: u8) -> Option<&'static [usize]> { }) } +/// The channel configuration whose speakers a stream has: its own, or for configuration 0 the +/// configuration 3–6 that its program config element spells out. A program config element lists +/// front, side, back and LFE elements in that order, so one that opens with a centre and a front +/// pair and goes on with exactly the elements of a configuration has that configuration's speakers +/// (and [`wav_order`]). Any other list has no speaker order that can be told, and gives 0: ffmpeg's +/// 5.1(side), for one, lists the pair first and already decodes in WAV order. +#[cfg(feature = "aac-decode")] +pub fn speaker_config(asc: &AudioSpecificConfig) -> u8 { + if asc.channel_config != 0 { + return asc.channel_config; + } + let centre_then_pair = asc.pce.as_ref().is_some_and(|p| p.front.iter().map(|e| e.0).eq([false, true])); + if !centre_then_pair { + return 0; + } + let elements = asc.layout(); + let same = |config: &u8| config_layout(*config).is_some_and(|l| l.iter().map(|e| e.0).eq(elements.iter().map(|e| e.0))); + (3..=6).find(same).unwrap_or(0) +} + /// The order the [`Encoder`] takes its input in, from WAV order: for each encoder input channel /// (AAC element order, see [`EncoderConfig::channels`]), the WAV-order channel to feed it. The /// inverse of [`wav_order`] for 3 to 7 channels; `None` for mono and stereo (already in order) and @@ -279,6 +299,30 @@ mod tests { mod order_tests { use super::*; + /// A program config element in the shape of a channel configuration has that configuration's + /// speakers, with the centre first. ffmpeg's 5.1(side) lists its pair first and already decodes + /// in WAV order, so it stays as it is. + #[cfg(feature = "aac-decode")] + #[test] + fn a_program_config_element_takes_the_configuration_it_matches() { + let with = |pce| AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(3, 0) }; + let centre_first = ProgramConfig { front: vec![(false, 0), (true, 0)], back: vec![(true, 1)], lfe: vec![0], ..Default::default() }; + assert_eq!(speaker_config(&with(centre_first)), 6); + let three = ProgramConfig { front: vec![(false, 0), (true, 0)], ..Default::default() }; + assert_eq!(speaker_config(&with(three)), 3); + let ffmpeg = ProgramConfig { front: vec![(true, 0), (false, 0)], side: vec![(false, 1)], back: vec![(true, 1)], ..Default::default() }; + assert_eq!(speaker_config(&with(ffmpeg)), 0); + // the same element types with no front pair: the side pair is not left and right + let no_front_pair = + ProgramConfig { front: vec![(false, 0)], side: vec![(true, 0)], back: vec![(true, 1)], lfe: vec![0], ..Default::default() }; + assert_eq!(speaker_config(&with(no_front_pair)), 0); + // 7.1 in a program config element is not one of the unambiguous configurations + let wide = + ProgramConfig { front: vec![(false, 0), (true, 0)], side: vec![(true, 1)], back: vec![(true, 2)], lfe: vec![0], ..Default::default() }; + assert_eq!(speaker_config(&with(wide)), 0); + assert_eq!(speaker_config(&AudioSpecificConfig::lc(3, 6)), 6); + } + /// `aac_order` undoes `wav_order` for each channel count the encoder maps to a configuration /// (3–6 channels: configurations 3–6; 7: configuration 11). #[test] diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 5916b91e8..4964166a7 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -19,6 +19,9 @@ //! gives [`wav_float_header`]) and FLAC (feature `flac-encode`), whole-buffer or incremental into //! any `Write + Seek`. Feature `lossless-encode` turns on both; feature `encode` turns on //! `lossless-encode` and every codec's encoder. +//! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`], +//! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF +//! file bit for bit, and minimal files around such PCM, for essence embedded in other containers. //! - [`peaks`] (feature `peaks`): min/max/RMS pyramid for waveform drawing. //! - Codec modules for packet-level use, each with its own features: [`aac`] (`aac-decode`, //! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`), [`ac3`] @@ -91,12 +94,16 @@ pub use read::{ DECODE_EXTENSIONS, DEFAULT_MAX_SAMPLES, DecodeOptions, Decoder, TrackInfo, decode, decode_with, detect_container, probe, probe_with, tracks, tracks_of, }; +#[cfg(feature = "decode-native")] +pub use read::{RawPcm, aiff_pcm, wav_pcm}; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; #[cfg(feature = "pcm-encode")] pub use write::wav_float_header; #[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] pub use write::{ENCODE_EXTENSIONS, FileEncoder, encode, encode_format_for}; +#[cfg(feature = "pcm-encode")] +pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; /// Errors from probing, decoding and encoding. #[non_exhaustive] diff --git a/crates/audio/src/read/mod.rs b/crates/audio/src/read/mod.rs index 533e996a6..35a220767 100644 --- a/crates/audio/src/read/mod.rs +++ b/crates/audio/src/read/mod.rs @@ -14,6 +14,7 @@ mod flac; #[cfg(feature = "symphonia")] mod mp4; mod native; +mod raw; mod source; #[cfg(feature = "symphonia")] mod symph; @@ -21,6 +22,7 @@ mod wav; use crate::{AudioBuffer, AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result}; use native::Native; +pub use raw::{RawPcm, aiff_pcm, wav_pcm}; pub use source::SharedSource; use source::Src; use std::sync::Arc; diff --git a/crates/audio/src/read/raw.rs b/crates/audio/src/read/raw.rs new file mode 100644 index 000000000..e63f9d2cb --- /dev/null +++ b/crates/audio/src/read/raw.rs @@ -0,0 +1,58 @@ +//! The integer PCM of a WAV or AIFF file as stored, for a caller that moves it bit for bit +//! (essence embedded in an AAF or OMF file) instead of decoding it to `f32`. + +use super::source::Src; +use super::{aiff, wav}; +use crate::pcm::PcmKind; + +/// Integer PCM taken out of a WAV or AIFF file: interleaved little-endian samples of +/// `bits.div_ceil(8)` bytes each, signed except for 8-bit, which is unsigned (the WAVE convention). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RawPcm { + /// The samples; empty for a header with no data after it (a descriptor's summary). + pub data: Vec, + /// Interleaved channels (at least 1). + pub channels: u16, + /// Sample rate in Hz (at least 1). + pub sample_rate: u32, + /// Bits a sample occupies in `data`: 8, 16, 24 or 32. + pub bits: u16, +} + +/// The samples of a layout: `len` bytes at `start`, as far as the file has them. +fn stored(b: &[u8], start: u64, len: u64) -> &[u8] { + let start = usize::try_from(start).unwrap_or(usize::MAX).min(b.len()); + let end = start.saturating_add(usize::try_from(len).unwrap_or(usize::MAX)).min(b.len()); + b.get(start..end).unwrap_or_default() +} + +/// The integer PCM of a WAV file (plain or `WAVE_FORMAT_EXTENSIBLE` PCM), bit for bit. `None` for +/// anything else: not a WAV, float or compressed samples, no `fmt ` or `data` chunk. A file cut +/// short gives the samples that are there. +pub fn wav_pcm(bytes: &[u8]) -> Option { + let wav::WavParse::Native(layout) = wav::parse(&Src::Slice(bytes)).ok()? else { return None }; + let PcmKind::Int { bytes: width, big_endian: false, .. } = layout.kind else { return None }; + Some(RawPcm { + data: stored(bytes, layout.data_start, layout.data_len).to_vec(), + channels: layout.info.channels, + sample_rate: layout.info.sample_rate, + bits: u16::try_from(width.checked_mul(8)?).ok()?, + }) +} + +/// The integer PCM of an AIFF or AIFF-C (`NONE`, `twos`, `sowt`) file, converted to the layout of +/// [`RawPcm`]: little-endian, and 8-bit samples made unsigned. `None` for anything else. +pub fn aiff_pcm(bytes: &[u8]) -> Option { + let aiff::AiffParse::Native(layout) = aiff::parse(&Src::Slice(bytes)).ok()? else { return None }; + let PcmKind::Int { bytes: width, big_endian, .. } = layout.kind else { return None }; + let stored = stored(bytes, layout.data_start, layout.data_len); + let mut data = Vec::with_capacity(stored.len()); + for s in stored.chunks_exact(width.max(1)) { + match (width, big_endian) { + (1, _) => data.extend(s.iter().map(|b| b ^ 0x80)), + (_, true) => data.extend(s.iter().rev()), + (_, false) => data.extend_from_slice(s), + } + } + Some(RawPcm { data, channels: layout.info.channels, sample_rate: layout.info.sample_rate, bits: u16::try_from(width.checked_mul(8)?).ok()? }) +} diff --git a/crates/audio/src/track.rs b/crates/audio/src/track.rs index 3d9ed7dfb..af984d718 100644 --- a/crates/audio/src/track.rs +++ b/crates/audio/src/track.rs @@ -156,7 +156,8 @@ impl TrackDecoder { let codec = if up.is_some() { CodecId::HeAac } else { CodecId::Aac }; // Only twice the core rate is upsampled to; any other signalled rate plays the core. let out = if up.is_some() { out } else { dec.sample_rate() }; - let cfg = dec.config().channel_config; + // a program config element that spells out a configuration has its speakers + let cfg = aac::speaker_config(dec.config()); let layout = aac_layout(cfg, dec.channels()); let order = layout.is_ordered().then(|| aac::wav_order(cfg)).flatten(); (Inner::Aac { dec: Box::new(dec), up, order, adts_format }, codec, out, layout, SampleFormat::Compressed) @@ -1079,6 +1080,8 @@ mod tests { let mut dec = TrackDecoder::new(&aac_params(), &[&frame]).unwrap(); assert_eq!(dec.channels(), 3); assert_eq!(dec.decode(&frame).unwrap().channels.len(), 3); + // its element lists a centre and a front pair, as configuration 3 does: L R C, in WAV order + assert_eq!(dec.layout(), ChannelLayout::SURROUND_3_0); // no program config element where one is needed let bare = aac::AdtsHeader::write(2, 3, 0, 1, 0x7FF).unwrap(); let bare = [&bare[..], &[0xE0]].concat(); diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 25c9b2528..2355a7b05 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -7,9 +7,13 @@ mod aiff; pub(crate) mod flac; mod pcm; #[cfg(feature = "pcm-encode")] +mod raw; +#[cfg(feature = "pcm-encode")] mod wav; use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, Result}; +#[cfg(feature = "pcm-encode")] +pub use raw::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; use std::io::{Seek, Write}; /// Encode `buf` as WAV/BWF, AIFF/AIFF-C or FLAC. Integer depths clamp samples to [-1, 1]; float diff --git a/crates/audio/src/write/raw.rs b/crates/audio/src/write/raw.rs new file mode 100644 index 000000000..dc9a31649 --- /dev/null +++ b/crates/audio/src/write/raw.rs @@ -0,0 +1,120 @@ +//! Minimal WAVE and AIFF files around integer PCM the caller already has as bytes (essence +//! embedded in an AAF or OMF file): the 44-byte canonical WAVE header and the plain AIFF header, +//! with nothing a reader of such a summary could trip over (no `JUNK`, no extensible `fmt `). +//! [`crate::encode`] writes full WAV/BWF/RF64 and AIFF files from `f32`. +//! +//! PCM here is interleaved little-endian samples of `bits.div_ceil(8)` bytes, 8-bit unsigned +//! (the layout of a WAVE `data` chunk). Sizes saturate at the 32-bit fields instead of wrapping. + +use super::aiff::u32_to_extended; + +/// A complete WAVE file around little-endian PCM. +pub fn pcm_wav_file(pcm: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Vec { + let mut v = pcm_wav_header(u32::try_from(pcm.len()).unwrap_or(u32::MAX), channels, sample_rate, bits); + v.extend_from_slice(pcm); + if pcm.len() % 2 == 1 { + v.push(0); + } + v +} + +/// The 44 bytes of a canonical WAVE file up to and including the `data` chunk header, for +/// `data_len` bytes of PCM. +pub fn pcm_wav_header(data_len: u32, channels: u16, sample_rate: u32, bits: u16) -> Vec { + let block = channels.max(1).saturating_mul(bits.div_ceil(8)); + let mut v = Vec::with_capacity(44); + v.extend_from_slice(b"RIFF"); + v.extend_from_slice(&36u32.saturating_add(data_len).saturating_add(data_len & 1).to_le_bytes()); + v.extend_from_slice(b"WAVEfmt "); + v.extend_from_slice(&16u32.to_le_bytes()); + v.extend_from_slice(&1u16.to_le_bytes()); + v.extend_from_slice(&channels.max(1).to_le_bytes()); + v.extend_from_slice(&sample_rate.to_le_bytes()); + v.extend_from_slice(&sample_rate.saturating_mul(u32::from(block)).to_le_bytes()); + v.extend_from_slice(&block.to_le_bytes()); + v.extend_from_slice(&bits.to_le_bytes()); + v.extend_from_slice(b"data"); + v.extend_from_slice(&data_len.to_le_bytes()); + v +} + +/// A complete AIFF file (big-endian, 8-bit signed) from little-endian PCM. +pub fn pcm_aiff_file(pcm: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Vec { + let width = usize::from(bits.div_ceil(8)).max(1); + let frames = pcm.len() / (width * usize::from(channels.max(1))); + let mut v = pcm_aiff_header(u32::try_from(frames).unwrap_or(u32::MAX), channels, sample_rate, bits); + let head = v.len(); + for s in pcm.chunks_exact(width) { + if width == 1 { + v.extend(s.iter().map(|b| b ^ 0x80)); // WAVE 8-bit is unsigned, AIFF signed + } else { + v.extend(s.iter().rev()); + } + } + if (v.len() - head) % 2 == 1 { + v.push(0); + } + v +} + +/// The 54 bytes of an AIFF file up to the sound data (`FORM`, `COMM`, `SSND` with its offset and +/// block size), for `frames` sample frames. +pub fn pcm_aiff_header(frames: u32, channels: u16, sample_rate: u32, bits: u16) -> Vec { + let data_len = u64::from(frames).saturating_mul(u64::from(channels.max(1))).saturating_mul(u64::from(bits.div_ceil(8))); + let chunk = |extra: u64| u32::try_from(extra.saturating_add(data_len)).unwrap_or(u32::MAX); + let mut v = Vec::with_capacity(54); + v.extend_from_slice(b"FORM"); + v.extend_from_slice(&chunk(4 + 26 + 16 + (data_len & 1)).to_be_bytes()); + v.extend_from_slice(b"AIFFCOMM"); + v.extend_from_slice(&18u32.to_be_bytes()); + v.extend_from_slice(&channels.max(1).to_be_bytes()); + v.extend_from_slice(&frames.to_be_bytes()); + v.extend_from_slice(&bits.to_be_bytes()); + v.extend_from_slice(&u32_to_extended(sample_rate)); + v.extend_from_slice(b"SSND"); + v.extend_from_slice(&chunk(8).to_be_bytes()); + v.extend_from_slice(&[0; 8]); + v +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A descriptor for more than 4 GiB of PCM: the RIFF and FORM size fields saturate. + #[test] + fn huge_headers_saturate() { + let h = pcm_wav_header(u32::MAX, 2, u32::MAX, 24); + assert_eq!(h.get(4..8), Some(&u32::MAX.to_le_bytes()[..])); + assert_eq!(h.get(28..32), Some(&u32::MAX.to_le_bytes()[..]), "byte rate"); + let a = pcm_aiff_header(u32::MAX, u16::MAX, 48_000, 32); + assert_eq!(a.get(4..8), Some(&u32::MAX.to_be_bytes()[..])); + assert_eq!(a.len(), 54); + } + + #[test] + fn headers_have_the_canonical_layout() { + let h = pcm_wav_header(96, 2, 48_000, 24); + assert_eq!(h.len(), 44); + let mut expect = b"RIFF".to_vec(); + expect.extend_from_slice(&132u32.to_le_bytes()); + expect.extend_from_slice(b"WAVEfmt "); + for x in [16u32, 1 | 2 << 16, 48_000, 288_000, 6 | 24 << 16] { + expect.extend_from_slice(&x.to_le_bytes()); + } + expect.extend_from_slice(b"data"); + expect.extend_from_slice(&96u32.to_le_bytes()); + assert_eq!(h, expect); + // zero channels are written as one, and an odd data length counts its pad byte + let odd = pcm_wav_file(&[1, 2, 3], 0, 8_000, 8); + assert_eq!(odd.len(), 48); + assert_eq!(odd.get(4..8), Some(&40u32.to_le_bytes()[..])); + assert_eq!(odd.get(22..24), Some(&1u16.to_le_bytes()[..])); + let a = pcm_aiff_header(8, 2, 44_100, 24); + assert_eq!(a.get(..4), Some(&b"FORM"[..])); + assert_eq!(a.get(4..8), Some(&(46u32 + 48).to_be_bytes()[..])); + // 44 100 Hz as an 80-bit extended float + assert_eq!(a.get(28..38), Some(&[0x40, 0x0E, 0xAC, 0x44, 0, 0, 0, 0, 0, 0][..])); + assert_eq!(a.get(42..46), Some(&(8u32 + 48).to_be_bytes()[..])); + } +} diff --git a/crates/audio/tests/audio/main.rs b/crates/audio/tests/audio/main.rs index f247167b5..8c37256d6 100644 --- a/crates/audio/tests/audio/main.rs +++ b/crates/audio/tests/audio/main.rs @@ -6,6 +6,7 @@ mod flac_damage; mod float_headroom; mod malformed; mod mp4_length; +mod raw_pcm; mod roundtrip; mod stream; mod wav_empty_data; diff --git a/crates/audio/tests/audio/raw_pcm.rs b/crates/audio/tests/audio/raw_pcm.rs new file mode 100644 index 000000000..1b5fed669 --- /dev/null +++ b/crates/audio/tests/audio/raw_pcm.rs @@ -0,0 +1,73 @@ +//! Integer PCM in and out of WAV and AIFF files bit for bit (`wav_pcm`, `aiff_pcm`, `pcm_*`). + +use craft_audio::{ + AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, RawPcm, aiff_pcm, encode, pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header, + wav_pcm, +}; + +fn raw(data: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Option { + Some(RawPcm { data: data.to_vec(), channels, sample_rate, bits }) +} + +#[test] +fn wav_and_aiff_round_trip_bit_for_bit() { + let pcm: Vec = (0..48u8).collect(); // 8 stereo 24-bit frames + let w = pcm_wav_file(&pcm, 2, 48_000, 24); + assert_eq!(wav_pcm(&w), raw(&pcm, 2, 48_000, 24)); + let a = pcm_aiff_file(&pcm, 2, 44_100, 24); + assert_eq!(aiff_pcm(&a), raw(&pcm, 2, 44_100, 24)); + let p16: Vec = (0..32u8).collect(); + assert_eq!(aiff_pcm(&pcm_aiff_file(&p16, 1, 96_000, 16)), raw(&p16, 1, 96_000, 16)); + // 8-bit: unsigned in WAVE and in `RawPcm`, signed in AIFF + let p8 = [0u8, 0x7F, 0x80, 0xFF, 3]; + assert_eq!(wav_pcm(&pcm_wav_file(&p8, 1, 8_000, 8)), raw(&p8, 1, 8_000, 8)); + let a8 = pcm_aiff_file(&p8, 1, 8_000, 8); + assert_eq!(a8.get(54..59), Some(&[0x80, 0xFF, 0x00, 0x7F, 0x83][..])); + assert_eq!(a8.len(), 60, "odd sound data is padded"); + assert_eq!(aiff_pcm(&a8), raw(&p8, 1, 8_000, 8)); + // neither reads the other's container + assert_eq!(wav_pcm(&a), None); + assert_eq!(aiff_pcm(&w), None); +} + +/// A descriptor's summary is the header alone: the format is read, with no samples. +#[test] +fn headers_without_data_give_the_format() { + assert_eq!(wav_pcm(&pcm_wav_header(4800, 2, 48_000, 16)), raw(&[], 2, 48_000, 16)); + assert_eq!(aiff_pcm(&pcm_aiff_header(1200, 2, 48_000, 16)), raw(&[], 2, 48_000, 16)); +} + +#[test] +fn files_cut_short_never_panic_and_give_what_is_there() { + let pcm: Vec = (0..48u8).collect(); + let w = pcm_wav_file(&pcm, 2, 48_000, 24); + let a = pcm_aiff_file(&pcm, 2, 44_100, 24); + for cut in 0..w.len().max(a.len()) { + if let Some(p) = w.get(..cut).and_then(wav_pcm) { + assert_eq!(Some(&p.data[..]), pcm.get(..cut.saturating_sub(44)), "wav cut at {cut}"); + } + if let Some(p) = a.get(..cut).and_then(aiff_pcm) { + assert!(pcm.starts_with(&p.data) && p.data.len() <= cut.saturating_sub(54), "aiff cut at {cut}"); + } + } + assert_eq!(wav_pcm(b"RIFF"), None); + assert_eq!(aiff_pcm(a.get(..30).unwrap()), None); +} + +#[test] +fn only_integer_pcm_is_taken() { + let buf = AudioBuffer::new(48_000, 2, 16); + let float = encode(&buf, &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Float32)).unwrap(); + assert_eq!(wav_pcm(&float), None); + let float = encode(&buf, &EncodeOptions::new(EncodeFormat::Aiff).with_bit_depth(BitDepth::Float32)).unwrap(); + assert_eq!(aiff_pcm(&float), None); + // the full writer's 24-bit WAV (extensible `fmt `, a JUNK chunk before it) is integer PCM too + let int = encode(&buf, &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap(); + assert_eq!(wav_pcm(&int), raw(&[0; 96], 2, 48_000, 24)); + let int = encode(&buf, &EncodeOptions::new(EncodeFormat::Aiff).with_bit_depth(BitDepth::Int16)).unwrap(); + assert_eq!(aiff_pcm(&int), raw(&[0; 64], 2, 48_000, 16)); + // zero channels or a zero rate is not a format + let mut bad = pcm_wav_file(&[0; 8], 1, 48_000, 16); + bad[24..28].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(wav_pcm(&bad), None); +} diff --git a/crates/audio/tests/codecs/routing_oracle.rs b/crates/audio/tests/codecs/routing_oracle.rs index c35a89002..6472979b3 100644 --- a/crates/audio/tests/codecs/routing_oracle.rs +++ b/crates/audio/tests/codecs/routing_oracle.rs @@ -669,10 +669,14 @@ fn adts_with_a_program_config_element_decodes() { assert_eq!(bytes[3] >> 6 | (bytes[2] & 1) << 2, 0, "the fixture signals its layout in a PCE"); let (info, buf) = decode(&bytes, None).unwrap(); assert_eq!((info.container, info.codec, buf.channels.len()), (c.container, c.codec, c.channels)); - assert_eq!(info.layout, c.layout); + // A program config element that lists a centre, a front pair and then the elements of 5.1 has + // 5.1's speakers, in WAV order like ffmpeg's decode; any other list keeps the decoded order, + // which ffmpeg versions write differently. + let ordered = info.layout.is_ordered(); + assert_eq!(info.layout, if ordered { ChannelLayout::SURROUND_5_1_SIDE } else { c.layout }); assert_eq!(buf.frames(), reference(&ff, &path).len() / c.channels); - // A program config's channels come in its own order, and which order ffmpeg writes differs by - // version: each of ours must match a different one of ffmpeg's. + // Each of our channels must match a different one of ffmpeg's: the same one when the layout is + // ordered. let refr = reference(&ff, &path); let mut matched = Vec::new(); for plane in &buf.channels { @@ -686,7 +690,9 @@ fn adts_with_a_program_config_element_decodes() { assert!(s >= c.min_snr, "channel {} matches ffmpeg's {best} at only {s:.1} dB", matched.len()); matched.push(best); } - matched.sort_unstable(); + if !ordered { + matched.sort_unstable(); + } assert_eq!(matched, (0..c.channels).collect::>()); } diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index 81f0e6575..df665336d 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -11,8 +11,11 @@ repository.workspace = true workspace = true [dependencies] +craft-timeline = { workspace = true } craft-xml = { workspace = true } thiserror = { workspace = true } [dev-dependencies] proptest = { workspace = true } +# A second XML reader for the tests: checks of written TTML, and the comparison in tests/it/ttml_xml_views.rs. +roxmltree = "0.21" diff --git a/crates/captions/README.md b/crates/captions/README.md index 927a5dc44..0676d1d72 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -1,7 +1,8 @@ # craft-captions Caption and subtitle files behind one neutral model: bytes in, a `Document` of `Cue`s out, and -back. One module per format. Depends on `craft-xml` (TTML) and `thiserror`. +back. One module per format. Depends on `craft-timeline` (exact time), +`craft-xml` (TTML) and `thiserror`. ```rust use craft_captions::{Format, WriteOptions, detect, parse, write}; @@ -31,8 +32,9 @@ assert!(scc.starts_with(b"Scenarist_SCC V1.0")); `Tick` is an integer count of 1/254 016 000 000 s: a whole number of ticks per millisecond and per frame at every broadcast rate, so no format's times are rounded on the way in. `FrameRate` -is an exact rational. There are no floating-point seconds anywhere. An application with its own -time type converts at the boundary (`Tick(t).0` is the tick count). +is an exact rational. Both are `craft-timeline`'s (`craft_timeline::time`), re-exported here as +`craft_captions::time`, so a caller that already uses that crate passes its values straight in. +No format computes with floating-point seconds. ## Limits @@ -49,14 +51,19 @@ lists at most 20 characters per stream. | SubRip `.srt` | yes | yes | BOM, UTF-16, Windows-1252 fallback, CRLF/CR, missing or wrong indexes, `,` or `.` milliseconds, 1–9 fraction digits, missing hours, SSA coordinates, cues not separated by blank lines. Inline tags are kept as text. | | WebVTT `.vtt` | yes | yes | Cue identifiers, cue settings (verbatim), a leading `` voice span (as the caption's speaker) and STYLE / REGION / NOTE blocks are kept. A missing `WEBVTT` signature is tolerated. | | Scenarist SCC `.scc` | yes | yes | CEA-608 at 29.97 fps, drop-frame or not. Reads pop-on, roll-up and paint-on (channel 1); writes pop-on. | -| MacCaption MCC `.mcc` | yes | yes | One SMPTE ST 334-2 caption distribution packet (CDP) per frame carrying caption data, omitting empty frames, in MacCaption's hex text with letter abbreviations. Writes 29.97 fps (`30DF` / `30`) with CEA-608 field 1 (the SCC schedule) **and** CEA-708 service 1 (two-window pop-on emulation). Reads CEA-608 field 1 when present, else CEA-708 service 1; time code rates 30DF, 30, 60DF, 60, 25, 24, 50. | +| MacCaption MCC `.mcc` | yes | yes | One SMPTE ST 334-2 caption distribution packet (CDP) per frame carrying caption data, omitting empty frames (or on every frame, on request), in MacCaption's hex text with letter abbreviations. Writes 29.97 fps (`30DF` / `30`) with CEA-608 field 1 (the SCC schedule) **and** CEA-708 service 1 (two-window pop-on emulation). Reads CEA-608 field 1 when present, else CEA-708 service 1; time code rates 30DF, 30, 60DF, 60, 25, 24, 50. | | EBU STL `.stl` | yes | yes | EBU Tech 3264-E: GSI block + 128-byte TTI blocks, `STL25.01` (25 fps) or `STL30.01` (read/written as 29.97 fps, non-drop labels), ISO/IEC 6937 Latin text (accents as diacritic + letter), italics / underline codes as `` / ``, extension blocks for long subtitles, start-of-programme (TCP) subtracted. | | TTML `.ttml` (IMSC1) | yes | yes | Writes the IMSC1 Text profile (TTML2 namespaces) with the document's language as `xml:lang` (read back on import): `

` per cue, `
`, styled ``s for `` / `` / ``, `ttm:agent` speakers, exact frame times (`123f`) at the sequence rate. Reads any TTML (TTML1, TTML2, the 2006 `ttaf1` drafts): clock / frame / offset / tick times, `dur`, nested time containers (`body` / `div` begins offset and ends clip their contents; `seq` containers are read as `par` with a warning), timed spans, referenced styles. | | DFXP `.dfxp` | yes | yes | TTML1 with the DFXP presentation profile; clock times in milliseconds (frame-exact after `snap_to_frames`). | All cue times are exact `Tick`s. Milliseconds convert exactly (1 ms = 254 016 000 ticks); SCC frames map through `FrameRate::FPS_29_97`. `Document::snap_to_frames` snaps cues to a frame grid and -removes overlaps. +removes overlaps. SCC and MCC time codes count from `Document::start_timecode`, a time code +label read as a time (`label_time`), so the label carries across rates: 01:00:00:00 at 25 fps is +written as 01:00:00;00 drop-frame or 01:00:00:00 non-drop (`label_frame`). Readers leave it at +zero and keep the file's own time codes, noting the rate and drop-frame mode of its labels in +`Document::labels`; `Document::count_from` then counts the cues back from a start time code, when +every cue is at or after it. ### TTML tick timing @@ -86,6 +93,17 @@ This mapping follows [W3C TTML1, third edition (2018), §§12.1.5–12.2.1](http The [April 2006 TTaf1 draft, §§7.2.1 and 12.1.5–12.2.1](https://www.w3.org/TR/2006/WD-ttaf1-dfxp-20060427/) defines its earlier metadata namespace and agent ID form. +### TTML cue identifiers + +TTML and DFXP writers keep valid explicit cue IDs verbatim unless a style, region or earlier cue +already uses them. Missing, invalid or repeated IDs receive deterministic replacements that also +avoid valid IDs on later cues. Emitted cue, style, region and speaker IDs are unique across the +document. Unicode spelling is preserved without normalization. + +Identifier validation follows the `NCName` production in [Namespaces in XML 1.0, third edition +(2009), §3](https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-NCName), using the character +ranges in [XML 1.0, fifth edition (2008), §2.3](https://www.w3.org/TR/2008/REC-xml-20081126/#NT-NameStartChar). + ### SCC writer Each caption is sent as a pop-on load (RCL, ENM, then per row a preamble address code and tab @@ -93,10 +111,55 @@ offset for centring, then text; control codes doubled) into non-displayed memory Of Caption exactly on the caption's first frame. The load is placed in the latest run of free frames before the caption, so back-to-back captions load while the previous one is on screen. An Erase Displayed Memory clears the caption at its out point unless the next caption replaces it. -Text is wrapped at 32 columns, bottom-aligned (last row 15) and centred. Characters come from the +Text is wrapped at 32 columns, bottom-aligned (last row 15) and centred; text past 15 rows is +cut. Characters come from the 608 basic, special and extended sets (extended characters are preceded by a basic fallback character, as the standard requires); a few have a close stand-in (’ as ', – as -) and others are -dropped. `charset_warnings` names each dropped or replaced character. If there is no room to load a caption +dropped. `charset_warnings` names each dropped or replaced character and each caption cut to 15 +rows, with how many characters it lost. If there is no room to load a caption before its in point (for example a caption at 00:00:00:00), it appears as soon as it is loaded. -# +### MCC writer + +The writer merges the scheduled CEA-608 and CEA-708 frames in timestamp order. Frames without +caption data are omitted, including during a displayed caption; its explicit erase/hide command +still lands at its out point. CDP sequence counters advance per emitted packet, wrapping at 16 bits. +CEA-708 text uses the G0 and G1 (Latin-1) sets and part of G2 (… ‘ ’ “ ” • ™ and a few more); +other characters are sent as `?`, and `charset_warnings` names them. The CEA-708 window holds 12 +rows and the writer loads only those (`mcc::window_rows`), so a longer caption loses its last rows +there, and `charset_warnings` names it too. +Export work and output size therefore follow the scheduled caption data, not the time between +cues or their duration. + +For consumers that need a packet on every video frame (SDI, frame-wrapped MXF with a SMPTE 436M +track), `WriteOptions::every_frame_until` also writes one on every frame without caption data, +from the start to that time: CEA-608 null pairs and CEA-708 padding. The packets are 29.97 fps, +so they line up with the video only at that rate; the caller decides whether to offer it. It is +off by default, covers at most 24 hours (`mcc::MAX_PADDED_FRAMES`), and can be streamed +(`write_to`). + +### EBU STL writer + +Text is encoded in ISO/IEC 6937 (character code table `00`). Characters it has no code for, such as +the ellipsis, the em dash, the euro sign and most scripts other than Latin, are written as `?`; +`charset_warnings` names each one with how often it occurs and the first caption that has it, at the +STL file's own time code. + +### TTML inherited text styles + +On import, italic, bold and underline styles from ``, `

` and timed `` roots appear in +the cue text as balanced ``, `` and `` tags. Descendant overrides and explicit +`normal` / `noUnderline` resets are kept, and `inherit` restores the parent value. Styling +attributes are read from the TTML styling namespaces (and those of the 2006 drafts), with +unqualified attributes as a compatibility fallback; other namespaces are ignored. Named-style +chaining and `xml:space="preserve"` are not supported. The inline text collector does not +recurse. Content style inheritance follows [W3C TTML1, second edition (2013)](https://www.w3.org/TR/2013/REC-ttml1-20130924/#semantics-style-inheritance-content). + +### Literal text and style markup + +Cue text combines style tags with character entities, as WebVTT does. The TTML and EBU STL +readers keep a literal `<` as `<` (and a literal `&` that would read as an entity as `&`), +so it never turns into a tag. The TTML and STL writers decode the eight entities `entity_at` +knows: `&`, `<`, `>`, ` `, `"`, `'`, `‎` and `‏`; other named +entities and numeric references stay literal. The SRT writer keeps stored entities next to real +style tags, so a reimport does not turn a literal bracket into markup. diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index 6b9da1d72..0ba9f2ba5 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -38,11 +38,12 @@ pub mod scc; pub mod srt; pub mod stl; mod text; -pub mod time; +/// Exact time: `craft-timeline`'s ticks, frame rates and timecode fields. +pub use craft_timeline::time; pub mod ttml; pub mod vtt; -pub use text::plain_text; +pub use text::{decode_entities, entity_at, plain_text}; pub use time::{FrameRate, TICKS_PER_SECOND, Tick}; /// The creating program MCC and EBU STL files name when the caller gives none. @@ -148,12 +149,55 @@ pub struct Document { pub blocks: Vec, /// Non-fatal problems found while reading (skipped cues…). pub warnings: Vec, + /// SCC / MCC: the time code label of time zero, read as a time ([`label_time`]: a sequence's + /// start timecode on export). The writers count their time codes from the label it reads as, + /// so 01:00:00:00 at 25 fps is 01:00:00;00 or 01:00:00:00 at 29.97. Readers leave it at zero. + pub start_timecode: Tick, + /// SCC / MCC read from a file: the frame rate of its time code labels and whether they are + /// drop-frame. [`Document::count_from`] needs it. + pub labels: Option<(FrameRate, bool)>, /// BCP 47 language tag of the text, when known: TTML's `xml:lang` on import, the caption /// track's language on export. TTML and DFXP write it (else `en`). pub language: Option, } +/// Frame `frame` of a `rate` time code (drop-frame or not) as its label read as a time: hours, +/// minutes, seconds and the frame's share of a second at the label's nominal rate (25 for 25 fps, +/// 30 for 29.97). Negative frames read as zero. +pub fn label_time(frame: i64, rate: FrameRate, drop_frame: bool) -> Tick { + let base = rate.timecode_base(); + let (_, h, m, s, f) = crate::time::frames_to_fields(frame.max(0), rate, drop_frame && rate.supports_drop_frame()); + let seconds = h.saturating_mul(3600).saturating_add(m.saturating_mul(60)).saturating_add(s); + Tick(TICKS_PER_SECOND.saturating_mul(seconds)) + FrameRate::new(base, 1).tick_of(f) +} + +/// The frame of a `rate` time code (drop-frame or not) whose label reads as `label` (as +/// [`label_time`] gives it), to the nearest frame of the label's nominal rate. +pub fn label_frame(label: Tick, rate: FrameRate, drop_frame: bool) -> i64 { + let nominal = FrameRate::new(rate.timecode_base(), 1); + let n = nominal.frame_at(nominal.snap_nearest(label.max(Tick::ZERO))); + let (_, h, m, s, f) = crate::time::frames_to_fields(n, nominal, false); + crate::time::fields_to_frames(h, m, s, f, rate, drop_frame && rate.supports_drop_frame()) +} + impl Document { + /// SCC / MCC read from a file: count cue times from the time code labelled `start` (as + /// [`Document::start_timecode`]) rather than from 00:00:00:00, the inverse of what the writers + /// do. Only when every cue is at or after it, so a file that counts from zero keeps its times. + /// Returns whether the cues moved. + pub fn count_from(&mut self, start: Tick) -> bool { + let Some((rate, drop_frame)) = self.labels else { return false }; + let origin = rate.tick_of(label_frame(start, rate, drop_frame)); + if origin <= Tick::ZERO || self.cues.iter().any(|c| c.start < origin) { + return false; + } + for c in &mut self.cues { + c.start -= origin; + c.end -= origin; + } + true + } + /// Snap cue times to frame boundaries of `rate` (nearest), keeping every cue at least one frame /// long and removing overlaps (a cue is cut where the next one starts). pub fn snap_to_frames(&mut self, rate: FrameRate) { @@ -266,11 +310,16 @@ pub struct WriteOptions { pub rate: Option, /// MCC / EBU STL: the name written as the creating program ([`PROGRAM`] by default). pub program: &'static str, + /// MCC: a packet on every frame from the start to this time (the end of the programme), with + /// no caption data where there is none, as SDI and frame-wrapped MXF carry one per frame. + /// The frames are MCC's 29.97 fps ones, so this is one packet per video frame only for + /// 29.97 fps video. None (the default) writes only the frames that carry caption data. + pub every_frame_until: Option, } impl Default for WriteOptions { fn default() -> Self { - Self { drop_frame: true, rate: None, program: PROGRAM } + Self { drop_frame: true, rate: None, program: PROGRAM, every_frame_until: None } } } @@ -280,7 +329,7 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { Format::Srt => srt::write(doc).into_bytes(), Format::WebVtt => vtt::write(doc).into_bytes(), Format::Scc => scc::write(doc, opts.drop_frame).into_bytes(), - Format::Mcc => mcc::write_with(doc, opts.drop_frame, true, true, opts.program).into_bytes(), + Format::Mcc => mcc::write_padded(doc, opts.drop_frame, true, true, mcc_pad_frames(opts), opts.program).into_bytes(), Format::Stl => stl::write(doc, opts.rate, opts.program), Format::Ttml => ttml::write(doc, ttml::Flavor::Imsc1, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Dfxp => ttml::write(doc, ttml::Flavor::Dfxp, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), @@ -289,50 +338,117 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { /// How many characters [`charset_warnings`] names one by one per caption stream; the rest share one warning. const LISTED_CHARS: usize = 20; +/// How many cut captions [`charset_warnings`] names one by one per caption stream; the rest share one warning. +const LISTED_CUTS: usize = 20; +/// The rows of 32 columns CEA-608 shows ([`scc::caption_rows`] keeps at most this many). +const ROWS_608: usize = 15; -/// What writing `doc` as `format` does to text the caption data cannot carry. SCC and MCC drop -/// the characters CEA-608 has no code for (…) or send a close one (’ as '), and MCC's CEA-708 -/// service sends `?` for the characters it has no code for. One warning per such character, in -/// order of first use, with how often and the first caption that has it. Other formats: none. +/// What writing `doc` as `format` loses of its text, the characters the caption data cannot carry +/// and the text cut to fit. EBU STL writes `?` for the characters ISO/IEC 6937 has no code for. +/// SCC and MCC drop the characters CEA-608 has no code for (…) or send a close one (’ as '), and +/// MCC's CEA-708 service sends `?` for the characters it has no code for. One warning per such +/// character, in order of first use, with how often and the first caption that has it. CEA-608 +/// shows at most 15 rows of 32 characters and MCC's CEA-708 window 12 rows: one warning per +/// caption cut to fit, with how many characters it lost (spaces not counted) and where the lost +/// text starts. Other formats: none. pub fn charset_warnings(doc: &Document, format: Format, opts: WriteOptions) -> Vec { let mut out = Vec::new(); + // the time code the file has for a caption: counted from the start time code, as the writers do + let origin = label_frame(doc.start_timecode, scc::RATE, opts.drop_frame); + let at_608 = |t: Tick| scc::format_timecode(scc::frame_of(t).saturating_add(origin), opts.drop_frame); + // the rows each writer loads, so the warnings name exactly what the files leave out if matches!(format, Format::Scc | Format::Mcc) { - lossy_chars(doc, "CEA-608", cea608::shown_as, opts.drop_frame, &mut out); + lossy_chars(doc, "CEA-608", |text| changed_in_rows(&scc::caption_rows(text), cea608::shown_as), at_608, &mut out); + cut_rows(doc, &format!("CEA-608 shows {ROWS_608} rows of 32 characters"), scc::caption_rows, at_608, &mut out); } if format == Format::Mcc { - lossy_chars(doc, "CEA-708", |c| Some(mcc::shown_as_708(c)), opts.drop_frame, &mut out); + let shown_as = |c| Some(mcc::shown_as_708(c)); + lossy_chars(doc, "CEA-708", |text| changed_in_rows(&mcc::window_rows(text), shown_as), at_608, &mut out); + let limit = format!("The CEA-708 window holds {} rows of 32 characters", mcc::WINDOW_ROWS); + cut_rows(doc, &limit, mcc::window_rows, at_608, &mut out); + } + if format == Format::Stl { + let unencodable = |text: &str| -> Vec<(char, Option)> { stl::unencodable(text).into_iter().map(|c| (c, Some('?'))).collect() }; + lossy_chars(doc, "EBU STL (ISO/IEC 6937)", unencodable, |t| stl::timecode(t, opts.rate), &mut out); } out } -/// Warnings for the characters of `doc` that `shown_as` does not give back unchanged. -fn lossy_chars(doc: &Document, stream: &str, shown_as: impl Fn(char) -> Option, drop_frame: bool, out: &mut Vec) { - // (character, what a decoder shows instead, count, frame of the first caption with it) - let mut lost: Vec<(char, Option, usize, i64)> = Vec::new(); +/// The characters of the `rows` a writer loads that `shown_as` changes, with what a decoder shows +/// instead. +fn changed_in_rows(rows: &[String], shown_as: impl Fn(char) -> Option) -> Vec<(char, Option)> { + rows.iter().flat_map(|r| r.chars()).map(|c| (c, shown_as(c))).filter(|(c, shown)| *shown != Some(*c)).collect() +} + +/// `n` of `what`, singular for one. +fn count(n: usize, what: &str) -> String { + if n == 1 { format!("1 {what}") } else { format!("{n} {what}s") } +} + +/// Warnings for the captions of `doc` whose text the writer's `rows_of` (the rows it loads for a +/// caption's text) does not hold in full, as `limit` says: how many characters each loses, not +/// counting spaces, and the start of the lost text. +fn cut_rows(doc: &Document, limit: &str, rows_of: impl Fn(&str) -> Vec, at: impl Fn(Tick) -> String, out: &mut Vec) { + let visible = |s: &str| s.chars().filter(|c| !c.is_whitespace()).count(); + let mut cues: Vec<&Cue> = doc.cues.iter().filter(|c| c.end > c.start).collect(); + cues.sort_by_key(|c| c.start); + // (start of the caption, the text it loses) + let mut cut: Vec<(Tick, String)> = Vec::new(); + for cue in cues { + let text = plain_text(&cue.text); + // the rows keep a prefix of the text: the lost part starts at the first character past them + let kept: usize = rows_of(&cue.text).iter().map(|r| visible(r)).sum(); + if let Some((i, _)) = text.char_indices().filter(|(_, c)| !c.is_whitespace()).nth(kept) { + cut.push((cue.start, text[i..].to_string())); + } + } + for (start, lost) in cut.iter().take(LISTED_CUTS) { + // the first characters of the lost text, on one line + let lost_text = lost.split_whitespace().collect::>().join(" "); + let mut from: String = lost_text.chars().take(24).collect(); + if from.len() < lost_text.len() { + from.push('…'); + } + let n = visible(lost); + let what = if n == 1 { "its last character".to_string() } else { format!("its last {n} characters") }; + out.push(format!("{limit}: the caption at {} lost {what}, from \"{from}\"", at(*start))); + } + if let Some(rest) = cut.get(LISTED_CUTS..).filter(|rest| !rest.is_empty()) { + let n = rest.iter().fold(0usize, |n, (_, lost)| n.saturating_add(visible(lost))); + let captions = if rest.len() == 1 { "caption was" } else { "captions were" }; + out.push(format!("{limit}: {} more {captions} cut to fit too, losing {}", rest.len(), count(n, "character"))); + } +} + +/// Warnings for the characters of `doc` that the writer changes (`lost_in` gives them for a +/// caption's text, with what a decoder shows instead), timed by `at`. +fn lossy_chars( + doc: &Document, + stream: &str, + lost_in: impl Fn(&str) -> Vec<(char, Option)>, + at: impl Fn(Tick) -> String, + out: &mut Vec, +) { + // (character, what a decoder shows instead, count, start of the first caption with it) + let mut lost: Vec<(char, Option, usize, Tick)> = Vec::new(); let mut index: std::collections::HashMap = std::collections::HashMap::new(); let mut cues: Vec<&Cue> = doc.cues.iter().filter(|c| c.end > c.start).collect(); cues.sort_by_key(|c| c.start); for cue in cues { - // the text the SCC and MCC writers encode: plain text in 32-column rows - for c in scc::wrap_rows(&plain_text(&cue.text)).iter().flat_map(|r| r.chars()) { - let shown = shown_as(c); - if shown == Some(c) { - continue; - } + for (c, shown) in lost_in(&cue.text) { match index.get(&c).and_then(|&i| lost.get_mut(i)) { Some(entry) => entry.2 = entry.2.saturating_add(1), None => { index.insert(c, lost.len()); - lost.push((c, shown, 1, scc::frame_of(cue.start))); + lost.push((c, shown, 1, cue.start)); } } } } let times = |n: usize| if n == 1 { "once".to_string() } else { format!("{n} times") }; - for &(c, shown, n, frame) in lost.iter().take(LISTED_CHARS) { + for &(c, shown, n, start) in lost.iter().take(LISTED_CHARS) { let what = shown.map_or_else(|| "dropped".to_string(), |s| format!("written as \"{s}\"")); - let at = scc::format_timecode(frame, drop_frame); - out.push(format!("{stream} has no \"{c}\" (U+{:04X}): {what} {}, first in the caption at {at}", c as u32, times(n))); + out.push(format!("{stream} has no \"{c}\" (U+{:04X}): {what} {}, first in the caption at {}", c as u32, times(n), at(start))); } if let Some(rest) = lost.get(LISTED_CHARS..).filter(|rest| !rest.is_empty()) { let n = rest.iter().fold(0usize, |n, e| n.saturating_add(e.2)); @@ -340,6 +456,24 @@ fn lossy_chars(doc: &Document, stream: &str, shown_as: impl Fn(char) -> Option std::io::Result<()> { + match format { + Format::Mcc => mcc::write_padded_to(out, doc, opts.drop_frame, true, true, mcc_pad_frames(opts), opts.program), + _ => out.write_all(&write(doc, format, opts)), + } +} + +/// The MCC frames `opts.every_frame_until` asks for: those that start before it, so a last +/// partial frame gets its packet too. +fn mcc_pad_frames(opts: WriteOptions) -> i64 { + opts.every_frame_until.map_or(0, |end| { + let f = mcc::RATE.frame_at(end); + if mcc::RATE.tick_of(f) < end { f.saturating_add(1) } else { f } + }) +} + /// Decode text bytes: UTF-8 (BOM stripped), UTF-16 with BOM, else Windows-1252. Line endings are /// normalised to `\n`. pub fn decode_text(bytes: &[u8]) -> String { @@ -414,6 +548,31 @@ pub fn format_clock(t: Tick, sep: char) -> String { mod tests { use super::*; + /// A start time code keeps its label from a sequence's rate to the SCC / MCC 29.97 grid. + #[test] + fn start_timecode_labels_carry_across_rates() { + let secs = |s: i64| Tick(TICKS_PER_SECOND * s); + let scc = FrameRate::FPS_29_97; + // 01:00:00:00 at 25, 24 and 29.97 drop-frame all read as one hour + assert_eq!(label_time(90_000, FrameRate::FPS_25, false), secs(3600)); + assert_eq!(label_time(86_400, FrameRate::FPS_23_976, false), secs(3600)); + assert_eq!(label_time(107_892, scc, true), secs(3600)); + assert_eq!(label_time(108_000, scc, false), secs(3600)); + // 01:00:02:00 at 25 fps is 01:00:02;00 drop-frame and 01:00:02:00 non-drop at 29.97 + let two = label_time(90_050, FrameRate::FPS_25, false); + assert_eq!(crate::time::format_timecode_frames(label_frame(two, scc, true), scc, true), "01;00;02;00"); + assert_eq!(crate::time::format_timecode_frames(label_frame(two, scc, false), scc, false), "01:00:02:00"); + // a frame's share of a second goes to the nearest 29.97 label frame + assert_eq!(label_frame(label_time(90_001, FrameRate::FPS_25, false), scc, false), 108_001); + // drop-frame on a rate that has none counts non-drop + assert_eq!(label_time(90_000, FrameRate::FPS_25, true), secs(3600)); + // hostile values neither panic nor go negative + assert_eq!(label_time(-5, FrameRate::FPS_25, false), Tick::ZERO); + assert!(label_time(i64::MAX, FrameRate::FPS_25, false) > Tick::ZERO); + assert_eq!(label_frame(Tick(i64::MIN), scc, true), 0); + assert!(label_frame(Tick(i64::MAX), scc, true) > 0); + } + #[test] fn clock() { assert_eq!(parse_clock("00:00:01,500"), Some(Tick(TICKS_PER_SECOND * 3 / 2))); @@ -466,6 +625,9 @@ mod tests { // CEA-708 carries … (G2) and ’ but not the em dash, which 608 does carry let em_dash = "CEA-708 has no \"—\" (U+2014): written as \"?\" once, first in the caption at 00:00:00;00"; assert_eq!(charset_warnings(&doc, Format::Mcc, opts), [dropped, replaced, em_dash]); + // a document that starts at 01:00:00:00 names the time codes its file has + let master = Document { start_timecode: Tick(3600 * TICKS_PER_SECOND), ..doc.clone() }; + assert!(charset_warnings(&master, Format::Scc, opts)[0].ends_with("first in the caption at 01:00:00;00")); let ndf = charset_warnings(&doc, Format::Scc, WriteOptions { drop_frame: false, ..opts }); assert!(ndf[0].ends_with("00:00:00:00"), "{ndf:?}"); for f in [Format::Srt, Format::WebVtt, Format::Ttml, Format::Dfxp] { @@ -507,6 +669,91 @@ mod tests { assert_eq!(doc.warnings, ["more than 2 cues: the rest were skipped"]); } + /// EBU STL writes `?` for what ISO/IEC 6937 has no code for, and names it with the time code + /// the STL file gives the caption (25 fps, or 29.97 for a 29.97 or 30 fps sequence). + #[test] + fn charset_warnings_name_what_stl_cannot_carry() { + let at = |s: i64| Tick(TICKS_PER_SECOND * s / 5); + let cue = |s: i64, text: &str| Cue { start: at(s), end: at(s + 10), text: text.into(), ..Default::default() }; + let doc = Document { cues: vec![cue(6, "Espere… custa 5 €, não?"), cue(20, "Mais € — Ação ♪")], ..Default::default() }; + // (sequence rate, time code of the first caption, of the second) + for (rate, first, second) in [(None, "00:00:01:05", "00:00:04:00"), (Some(FrameRate::FPS_29_97), "00:00:01:06", "00:00:04:00")] { + let opts = WriteOptions { rate, ..Default::default() }; + let warnings = charset_warnings(&doc, Format::Stl, opts); + assert_eq!( + warnings, + [ + format!("EBU STL (ISO/IEC 6937) has no \"…\" (U+2026): written as \"?\" once, first in the caption at {first}"), + format!("EBU STL (ISO/IEC 6937) has no \"€\" (U+20AC): written as \"?\" 2 times, first in the caption at {first}"), + format!("EBU STL (ISO/IEC 6937) has no \"—\" (U+2014): written as \"?\" once, first in the caption at {second}"), + ], + "{rate:?}" + ); + // what the warnings name is what the file loses + let back = stl::parse(&write(&doc, Format::Stl, opts)).unwrap(); + assert_eq!(back.cues[0].text, "Espere? custa 5 ?, não?"); + } + let clean = Document { cues: vec![cue(0, "Ação “já” ♪ ½ ― Øre")], ..Default::default() }; + assert!(charset_warnings(&clean, Format::Stl, WriteOptions::default()).is_empty()); + } + + /// CEA-608 shows 15 rows of 32 characters and the MCC writer's CEA-708 window 12: a longer + /// caption loses its last rows, and the warning names the caption and exactly what the file + /// leaves out, short rows included. + #[test] + fn charset_warnings_name_captions_cut_to_fit() { + let visible = |s: &str| s.chars().filter(|c| !c.is_whitespace()).count(); + // rows of exactly 32 characters, numbered so the lost part is visible + let full = |k: usize| format!("row{k:02}{}", "x".repeat(27)); + let rows = |n: usize, last: &[&str]| (1..=n).map(full).chain(last.iter().map(|r| r.to_string())).collect::>(); + let doc = |rows: &[String], cues: i64| Document { + cues: (0..cues) + .map(|i| Cue { + start: Tick((2 * i + 1) * TICKS_PER_SECOND), + end: Tick((2 * i + 2) * TICKS_PER_SECOND), + text: rows.join("\n"), + ..Default::default() + }) + .collect(), + ..Default::default() + }; + let row13 = format!("row13{}…", "x".repeat(19)); + let row16 = format!("row16{}…", "x".repeat(19)); + // (case, rows of text, what SCC loses, what MCC's CEA-708 loses: characters and the start) + let cases = [ + ("12 full rows", rows(12, &[]), (0, ""), (0, "")), + ("12 rows, the last short", rows(11, &["end"]), (0, ""), (0, "")), + ("a short row 12, then one character", rows(11, &["end", "z"]), (0, ""), (1, "z")), + ("13 full rows", rows(13, &[]), (0, ""), (32, row13.as_str())), + ("17 full rows", rows(17, &[]), (64, row16.as_str()), (160, row13.as_str())), + ]; + let cut = |limit: &str, (n, from): (usize, &str)| { + let what = if n == 1 { "its last character".to_string() } else { format!("its last {n} characters") }; + (n > 0).then(|| format!("{limit}: the caption at 00:00:01;00 lost {what}, from \"{from}\"")) + }; + let opts = WriteOptions::default(); + for (case, rows, scc_lost, dtv_lost) in cases { + let doc = doc(&rows, 1); + let c608 = cut("CEA-608 shows 15 rows of 32 characters", scc_lost); + let c708 = cut("The CEA-708 window holds 12 rows of 32 characters", dtv_lost); + assert_eq!(charset_warnings(&doc, Format::Scc, opts), Vec::from_iter(c608.clone()), "{case}, SCC"); + assert_eq!(charset_warnings(&doc, Format::Mcc, opts), Vec::from_iter(c608.into_iter().chain(c708)), "{case}, MCC"); + for f in [Format::Srt, Format::WebVtt, Format::Stl, Format::Ttml, Format::Dfxp] { + assert!(charset_warnings(&doc, f, opts).is_empty(), "{case}, {f:?}"); + } + // what the warnings count is what the files leave out + let all = visible(&rows.concat()); + let scc = scc::parse(&String::from_utf8(write(&doc, Format::Scc, opts)).unwrap()).unwrap(); + assert_eq!(all - visible(&scc.cues[0].text), scc_lost.0, "{case}, SCC file"); + let dtv = mcc::parse(&mcc::write_with(&doc, true, false, true, "test")).unwrap(); + assert_eq!(all - visible(&dtv.cues[0].text), dtv_lost.0, "{case}, CEA-708 in the MCC file"); + } + // many cut captions: a bounded list + let w = charset_warnings(&doc(&rows(16, &[]), 23), Format::Scc, opts); + assert_eq!(w.len(), LISTED_CUTS + 1); + assert_eq!(w[LISTED_CUTS], "CEA-608 shows 15 rows of 32 characters: 3 more captions were cut to fit too, losing 96 characters"); + } + #[test] fn normalize_cuts_overlaps() { let c = |s: i64, e: i64| Cue { start: Tick(s), end: Tick(e), text: "x".into(), ..Default::default() }; @@ -515,4 +762,17 @@ mod tests { let r: Vec<(i64, i64)> = d.cues.iter().map(|c| (c.start.0, c.end.0)).collect(); assert_eq!(r, vec![(0, 10), (10, 12), (12, 20)]); } + + /// `write_to` streams the same bytes `write` returns, for every format and a padded MCC. + #[test] + fn write_to_matches_write() { + let cue = Cue { start: Tick(TICKS_PER_SECOND), end: Tick(2 * TICKS_PER_SECOND), text: "Hello".into(), ..Default::default() }; + let doc = Document { cues: vec![cue], ..Default::default() }; + let padded = WriteOptions { every_frame_until: Some(Tick(3 * TICKS_PER_SECOND)), ..Default::default() }; + for (format, opts) in Format::ALL.map(|f| (f, WriteOptions::default())).into_iter().chain([(Format::Mcc, padded)]) { + let mut out = Vec::new(); + write_to(&mut out, &doc, format, opts).unwrap(); + assert_eq!(out, write(&doc, format, opts), "{format:?}"); + } + } } diff --git a/crates/captions/src/mcc.rs b/crates/captions/src/mcc.rs index 0b780ccc1..23f5544c6 100644 --- a/crates/captions/src/mcc.rs +++ b/crates/captions/src/mcc.rs @@ -23,9 +23,9 @@ //! carries a CDP with 20 cc_data triplets; empty frames are omitted. Each CDP contains field 1 CEA-608 //! pop-on data (the same schedule as [SCC](crate::scc)), a null field-2 pair, CEA-708 //! service 1 data and padding. The CEA-708 captions emulate pop-on with two windows: each -//! caption is defined (hidden) and loaded into one window while the other shows, then a -//! DisplayWindows / HideWindows pair switches them on the caption's first frame; HideWindows -//! clears it at its end. +//! caption goes into one window, deleted and defined anew first (hidden, empty, the pen at its +//! top left), while the other shows, then a DisplayWindows / HideWindows pair switches them on +//! the caption's first frame; HideWindows clears it at its end. //! - **Reading:** every CDP's `cc_data`; channel 1 CEA-608 field-1 data is decoded with the SCC //! decoder when present, otherwise CEA-708 service 1 (windows, text, CR, clear / display / //! hide / toggle / delete windows, DefineWindow visibility); a cue starts whenever the visible @@ -240,15 +240,18 @@ pub fn shown_as_708(c: char) -> char { if char_atom(c).is_some() { c } else { '?' } } -/// Atoms that define window `win` hidden and load `rows` into it. +/// Atoms that make window `win` anew, hidden, and load `rows` into it. fn load_atoms(win: u8, rows: &[String]) -> Vec> { let rc = rows.len().clamp(1, 12) as u8 - 1; let cols = rows.iter().map(|r| r.chars().count()).max().unwrap_or(1).clamp(1, 42) as u8 - 1; let mut v = vec![ + // DeleteWindows: the window holds the caption before last. Decoders differ on whether + // redefining it or ClearWindows moves the pen back (CCExtractor keeps it), but a new + // window starts empty with the pen at its top left, for the same bytes as ClearWindows. + vec![0x8c, 1 << win], // DefineWindow: hidden, row/column lock, relative position 90 % down / 50 % across, // anchored at its bottom centre, rows / columns, window style 1, pen style 1 vec![0x98 + win, 0x18, 0x80 | 90, 50, 7 << 4 | rc, cols, 1 << 3 | 1], - vec![0x88, 1 << win], // ClearWindows ]; for (i, r) in rows.iter().enumerate() { if i > 0 { @@ -311,6 +314,18 @@ impl Dtv { } } +/// The rows of the CEA-708 window a caption is loaded into. +pub const WINDOW_ROWS: usize = 12; + +/// The rows the CEA-708 writer loads for caption `text`: the CEA-608 rows (plain text in 32-column +/// rows), as many as the window holds. The rest is left out: past a window's last row, decoders +/// differ (one scrolls the first rows away, another runs the text into the last row). +pub fn window_rows(text: &str) -> Vec { + let mut rows = scc::caption_rows(text); + rows.truncate(WINDOW_ROWS); + rows +} + /// Schedule CEA-708 service 1 pop-on captions (see the module docs). fn schedule_708(doc: &Document) -> BTreeMap> { let mut d = Dtv { frames: BTreeMap::new() }; @@ -322,7 +337,7 @@ fn schedule_708(doc: &Document) -> BTreeMap> { let win = (i % 2) as u8; let s = scc::frame_of(c.start).max(cursor); let e = scc::frame_of(c.end); - let rows = scc::wrap_rows(&crate::plain_text(&c.text)); + let rows = window_rows(&c.text); let load = packets(&load_atoms(win, &rows), &mut seq); let mut f = (s - load.len() as i64).max(cursor); let mut last = f; @@ -578,6 +593,10 @@ impl Dec708 { // File // --------------------------------------------------------------------------------------------- +/// The most frames [`write_padded`] fills: 24 hours of 29.97 fps drop-frame time code, as far +/// as an MCC time code counts. +pub const MAX_PADDED_FRAMES: i64 = 24 * 107_892; + /// Write `doc` as MCC: CEA-608 field 1 and CEA-708 service 1 (see the module docs), with /// [`crate::PROGRAM`] as the creation program. pub fn write(doc: &Document, drop_frame: bool) -> String { @@ -597,45 +616,82 @@ fn header_value(program: &str) -> String { /// An empty document or two disabled streams produces a header with no data lines. /// `program` is named as the file's creation program. pub fn write_with(doc: &Document, drop_frame: bool, cea608: bool, cea708: bool, program: &str) -> String { + write_padded(doc, drop_frame, cea608, cea708, 0, program) +} + +/// [`write_with`], plus a packet with no caption data (CEA-608 nulls, CEA-708 padding) on every +/// frame before `pad_frames` that has none, as SDI and frame-wrapped MXF carry one packet per +/// video frame. Frames with caption data after `pad_frames` are written as usual. At most +/// [`MAX_PADDED_FRAMES`] are filled. +pub fn write_padded(doc: &Document, drop_frame: bool, cea608: bool, cea708: bool, pad_frames: i64, program: &str) -> String { + let mut out = Vec::new(); + // writing into a Vec cannot fail, and the text is UTF-8 (ASCII but for the program name) + let _ = write_padded_to(&mut out, doc, drop_frame, cea608, cea708, pad_frames, program); + String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()) +} + +/// [`write_padded`] into `out` line by line, so a long padded export is never held in memory. +pub fn write_padded_to( + out: &mut dyn std::io::Write, + doc: &Document, + drop_frame: bool, + cea608: bool, + cea708: bool, + pad_frames: i64, + program: &str, +) -> std::io::Result<()> { let program = header_value(program); + let pad = pad_frames.clamp(0, MAX_PADDED_FRAMES); let f1 = if cea608 { scc::schedule(doc) } else { BTreeMap::new() }; let dtv = if cea708 { schedule_708(doc) } else { BTreeMap::new() }; - let mut out = String::from("File Format=MacCaption_MCC V1.0\n\n"); - out.push_str("///////////////////////////////////////////////////////////////////////////////////\n"); - out.push_str(&format!("// Closed captions written by {program}: SMPTE ST 334-2 caption distribution packets\n")); - out.push_str("// carrying CEA-608 field 1 and CEA-708 service 1 data; empty frames omitted.\n"); - out.push_str("///////////////////////////////////////////////////////////////////////////////////\n\n"); + let origin = crate::label_frame(doc.start_timecode, RATE, drop_frame); // time codes count from the start time code + out.write_all(b"File Format=MacCaption_MCC V1.0\n\n")?; + out.write_all(b"///////////////////////////////////////////////////////////////////////////////////\n")?; + writeln!(out, "// Closed captions written by {program}: SMPTE ST 334-2 caption distribution packets")?; + let frames: &[u8] = if pad > 0 { + b"// carrying CEA-608 field 1 and CEA-708 service 1 data; a packet on every frame.\n" + } else { + b"// carrying CEA-608 field 1 and CEA-708 service 1 data; empty frames omitted.\n" + }; + out.write_all(frames)?; + out.write_all(b"///////////////////////////////////////////////////////////////////////////////////\n\n")?; let n = doc.cues.len() as u64; let h = doc .cues .iter() .fold(0xcbf2_9ce4_8422_2325u64 ^ n, |h, c| (h ^ c.start.0 as u64 ^ (c.end.0 as u64).rotate_left(17)).wrapping_mul(0x100_0000_01b3)); - out.push_str(&format!( - "UUID={:08X}-{:04X}-4{:03X}-8{:03X}-{:012X}\n", + writeln!( + out, + "UUID={:08X}-{:04X}-4{:03X}-8{:03X}-{:012X}", h >> 32, (h >> 16) & 0xffff, h & 0xfff, (h >> 20) & 0xfff, h.rotate_left(29) & 0xffff_ffff_ffff - )); - out.push_str(&format!("Creation Program={program}\n")); - out.push_str(&format!("Time Code Rate={}\n\n", if drop_frame { "30DF" } else { "30" })); + )?; + writeln!(out, "Creation Program={program}")?; + writeln!(out, "Time Code Rate={}\n", if drop_frame { "30DF" } else { "30" })?; // Merge the sparse schedules without walking (or allocating for) input-derived time gaps. // Erase/hide commands are scheduled data too, so omitting padding preserves cue end times. + // Padding walks only the frames before `pad`, which the caller chose and is capped. let mut f1 = f1.into_iter().peekable(); let mut dtv = dtv.into_iter().peekable(); let mut seq = 0u16; - while let Some(f) = f1.peek().map(|(f, _)| *f).into_iter().chain(dtv.peek().map(|(f, _)| *f)).min() { + let mut unpadded = 0i64; // the first frame with no packet yet, while it is before `pad` + loop { + let data = f1.peek().map(|(f, _)| *f).into_iter().chain(dtv.peek().map(|(f, _)| *f)).min(); + let Some(f) = data.into_iter().chain((unpadded < pad).then_some(unpadded)).min() else { break }; + unpadded = unpadded.max(f.saturating_add(1)); let data = FrameData { f1: f1.next_if(|(frame, _)| *frame == f).map(|(_, pair)| pair), dtvcc: dtv.next_if(|(frame, _)| *frame == f).map(|(_, pairs)| pairs).unwrap_or_default(), }; - let (_, hh, mm, ss, ff) = frames_to_fields(f, RATE, drop_frame); + let (_, hh, mm, ss, ff) = frames_to_fields(f.saturating_add(origin), RATE, drop_frame); let sep = if drop_frame { ';' } else { ':' }; - out.push_str(&format!("{hh:02}:{mm:02}:{ss:02}{sep}{ff:02}\t{}\n", compress(&build_cdp(seq, &data)))); + writeln!(out, "{hh:02}:{mm:02}:{ss:02}{sep}{ff:02}\t{}", compress(&build_cdp(seq, &data)))?; seq = seq.wrapping_add(1); } - out + Ok(()) } fn tc_rate(v: &str) -> Option<(FrameRate, bool)> { @@ -682,7 +738,9 @@ pub fn parse(text: &str) -> Result { let Some([h, m, s, f]) = parts.as_deref() else { return Err(Error::Syntax { line: n + 1, msg: format!("bad timecode \"{tc}\"") }); }; - let frame = fields_to_frames(*h, *m, *s, *f, rate.0, rate.1 || tc.contains(';')); + let drop_frame = rate.1 || tc.contains(';'); + doc.labels.get_or_insert((rate.0, drop_frame)); + let frame = fields_to_frames(*h, *m, *s, *f, rate.0, drop_frame); let Some(bytes) = expand(data) else { doc.warnings.push(format!("line {}: bad caption data", n + 1)); continue; @@ -788,6 +846,13 @@ mod tests { assert!(parse("garbage").is_err()); } + /// Keep back-to-back captions with the same text separate on the CEA-608 path (the SCC decoder). + #[test] + fn identical_back_to_back_cues_stay_separate_on_608() { + let doc = Document { cues: vec![cue(90, 135, "Ht"), cue(135, 180, "Ht")], ..Default::default() }; + assert_eq!(parse(&write_with(&doc, false, true, false, "test")).unwrap().cues, doc.cues); + } + /// Reject malformed fields instead of silently dropping them from the timecode. #[test] fn rejects_timecodes_with_unparseable_extra_fields() { @@ -829,6 +894,33 @@ mod tests { } } + /// Time codes count from the label of the document's start time code, drop-frame or not; the + /// packets do not change, and `Document::count_from` reads the cues back from it. + #[test] + fn time_codes_count_from_the_start_timecode() { + let doc = Document { cues: vec![cue(60, 120, "Caption")], ..Default::default() }; + let hour = crate::time::Tick(3600 * crate::time::TICKS_PER_SECOND); // the label 01:00:00:00 + let master = Document { start_timecode: hour, ..doc.clone() }; + let lines = |text: &str| -> Vec<(i64, String)> { + text.lines().filter_map(|l| l.split_once('\t')).map(|(tc, data)| (scc::parse_timecode(tc).unwrap(), data.to_string())).collect() + }; + for (drop_frame, origin) in [(true, 107_892), (false, 108_000)] { + let plain = lines(&write(&doc, drop_frame)); + let shifted: Vec<_> = plain.iter().map(|(f, data)| (f + origin, data.clone())).collect(); + let text = write(&master, drop_frame); + assert_eq!(lines(&text), shifted); + assert!(text.contains("\n01:00:0"), "{text}"); + let mut back = parse(&text).unwrap(); + assert_eq!(back.labels, Some((RATE, drop_frame))); + assert_eq!(back.cues[0].start, RATE.tick_of(origin + 60)); + assert!(back.count_from(hour)); + assert_eq!(back.cues, parse(&write(&doc, drop_frame)).unwrap().cues, "read back from the start time code"); + } + let negative = Document { start_timecode: crate::time::Tick(-1), ..doc.clone() }; + assert_eq!(lines(&write(&negative, true)), lines(&write(&doc, true)), "a negative start counts from zero"); + assert!(write(&Document { start_timecode: crate::time::Tick(i64::MAX), ..doc }, true).contains('\t')); + } + /// Bound output for distant or long cues near the tick limit without changing their timing. #[test] fn distant_and_long_cues_round_trip_near_tick_limit() { @@ -853,6 +945,46 @@ mod tests { assert!(!write(&Document::default(), true).contains('\t')); } + /// With padding, every frame to the end has one packet in time code order, numbered and + /// checksummed, empty frames carry no caption data, and the captions read back unchanged. + #[test] + fn padded_export_has_a_packet_on_every_frame() { + let doc = Document { cues: vec![cue(60, 120, "First"), cue(300, 330, "Last")], ..Default::default() }; + let empty = compress(&build_cdp(0, &FrameData::default())); + for drop_frame in [false, true] { + for (cea608, cea708) in [(true, true), (true, false), (false, true)] { + let text = write_padded(&doc, drop_frame, cea608, cea708, 2_000, "test"); + assert!(text.contains("a packet on every frame")); + let lines: Vec<(&str, &str)> = text.lines().filter_map(|line| line.split_once('\t')).collect(); + assert_eq!(lines.len(), 2_000); + for (f, (tc, data)) in lines.iter().enumerate() { + let (_, hh, mm, ss, ff) = frames_to_fields(f as i64, RATE, drop_frame); + let sep = if drop_frame { ';' } else { ':' }; + assert_eq!(*tc, format!("{hh:02}:{mm:02}:{ss:02}{sep}{ff:02}")); + let bytes = expand(data).unwrap(); + assert_eq!(u16::from_be_bytes([bytes[8], bytes[9]]), f as u16); + assert_eq!(bytes[3..76].iter().map(|&b| b as u32).sum::() % 256, 0); + } + // nothing is scheduled at frame 0 (the first load comes later), nor after the last erase + assert_eq!(lines[0].1, empty); + assert_eq!(lines[1_999].1, compress(&build_cdp(1_999, &FrameData::default()))); + assert_eq!(parse(&text).unwrap().cues, doc.cues); + } + } + // caption data after the padded span is still written; no padding is the sparse writer + let sparse = write_with(&doc, true, true, true, "test"); + let tcs = |text: &str| text.lines().filter_map(|line| line.split_once('\t')).map(|(tc, _)| tc.to_string()).collect::>(); + let first_unpadded = scc::format_timecode(200, true); + let later = |tcs: Vec| tcs.into_iter().filter(|tc| *tc >= first_unpadded).collect::>(); + let short = tcs(&write_padded(&doc, true, true, true, 200, "test")); + assert!(!later(short.clone()).is_empty()); + assert_eq!(short.len(), 200 + later(short.clone()).len()); + assert_eq!(later(short), later(tcs(&sparse))); + for pad in [0, -5, i64::MIN] { + assert_eq!(write_padded(&doc, true, true, true, pad, "test"), sparse); + } + } + /// Prevent CEA-708 text and line breaks from overflowing a window's declared dimensions. #[test] fn decoder_keeps_708_text_within_declared_window_dimensions() { @@ -891,4 +1023,92 @@ mod tests { assert!(decoder.cues.iter().map(|c| c.2.len()).sum::() <= MAX_708_TEXT_BYTES); assert!(decoder.open.is_none()); } + + /// Start every CEA-708 caption at the top left of its window, also for a decoder that sets + /// the pen only when a window is created and moves it only on SetPenLocation, carriage return + /// and text. CCExtractor keeps the pen through ClearWindows and a redefined window, so the + /// third caption below once started at the end of the first one, past its smaller window. + #[test] + fn each_708_caption_starts_at_its_window_top_left() { + let doc = Document { + cues: vec![ + cue(60, 120, "Por que você não admite que\nminha mão robótica te assusta?"), + cue(150, 200, "Você partiu meu coração!"), + cue(230, 250, "Eu sei."), + cue(260, 300, "Você me esqueceu na Terra."), + ], + ..Default::default() + }; + // Service 1 bytes in order, out of the scheduled DTVCC packets. + let mut packets: Vec> = Vec::new(); + for (start, a, b) in schedule_708(&doc).into_values().flatten() { + if start { + packets.push(Vec::new()); + } + packets.last_mut().unwrap().extend([a, b]); + } + let mut s = Vec::new(); + for p in &packets { + let mut body = &p[1..]; + while let [h, rest @ ..] = body { + let n = (h & 0x1f) as usize; + if h >> 5 == 1 { + s.extend_from_slice(&rest[..n]); + } + body = &rest[n..]; + } + } + // Pen (row, column), size (rows, columns) and whether defined, per window; where each + // caption's text starts (its first character after a DefineWindow). + let (mut pen, mut size, mut defined, mut cur) = ([(0usize, 0usize); 8], [(0usize, 0usize); 8], [false; 8], 0usize); + let (mut starts, mut loaded, mut i) = (Vec::new(), false, 0); + while let Some(&c) = s.get(i) { + let mut text = false; + i += match c { + 0x80..=0x87 => { + cur = (c - 0x80) as usize; + 1 + } + 0x8c => { + (0..8).filter(|w| s[i + 1] & 1 << w != 0).for_each(|w| defined[w] = false); + 2 + } + 0x88..=0x8b => 2, + 0x92 => { + pen[cur] = (s[i + 1] as usize, s[i + 2] as usize); + 3 + } + 0x98..=0x9f => { + cur = (c - 0x98) as usize; + if !std::mem::replace(&mut defined[cur], true) { + pen[cur] = (0, 0); + } + size[cur] = ((s[i + 4] & 0x0f) as usize + 1, (s[i + 5] & 0x3f) as usize + 1); + loaded = true; + 7 + } + 0x0d => { + pen[cur] = (pen[cur].0 + 1, 0); + 1 + } + 0x10 => { + text = true; + 2 + } + 0x20..=0x7f | 0xa0..=0xff => { + text = true; + 1 + } + _ => 1, + }; + if text { + if std::mem::take(&mut loaded) { + starts.push((cur, pen[cur])); + } + assert!(pen[cur].0 < size[cur].0 && pen[cur].1 < size[cur].1, "window {cur} {:?}: text at {:?}", size[cur], pen[cur]); + pen[cur].1 += 1; + } + } + assert_eq!(starts, [(0, (0, 0)), (1, (0, 0)), (0, (0, 0)), (1, (0, 0))]); + } } diff --git a/crates/captions/src/scc.rs b/crates/captions/src/scc.rs index 3b285ead0..08d023760 100644 --- a/crates/captions/src/scc.rs +++ b/crates/captions/src/scc.rs @@ -11,7 +11,8 @@ //! A tab separates the timecode from the code words. Each line's pairs are sent one per frame //! starting at its timecode. **Reading** runs a channel-1 //! CEA-608 decoder (pop-on, roll-up, paint-on; redundant control codes ignored) and emits a cue -//! whenever the displayed memory changes. **Writing** produces pop-on captions: for each cue the +//! whenever the displayed memory changes or an End of Caption swaps it, so neighbours with the +//! same text stay separate cues. **Writing** produces pop-on captions: for each cue the //! load (RCL, ENM, PAC + tab offset per row, text) is scheduled into free frames before the cue so //! its End of Caption lands exactly on the cue start; an Erase Displayed Memory clears it at the //! cue end (omitted when the next caption replaces it). Rows are bottom-aligned (row 15 last), @@ -116,14 +117,19 @@ impl Decoder { if now == cur { return; } + self.close(f); + if !now.is_empty() { + self.open = Some((f, now)); + } + } + + /// End the cue being shown at frame `f` (dropped if it never reached a frame). + fn close(&mut self, f: i64) { if let Some((s, text)) = self.open.take() && f > s { self.cues.push((s, f, text)); } - if !now.is_empty() { - self.open = Some((f, now)); - } } fn pair(&mut self, f: i64, b1: u8, b2: u8) { @@ -186,6 +192,8 @@ impl Decoder { misc::EOC => { std::mem::swap(&mut self.displayed, &mut self.hidden); self.mode = Mode::PopOn; + // each swap presents its own caption, even one reading the same as the last + self.close(f); } misc::CR => { if let Mode::RollUp(n) = self.mode { @@ -284,6 +292,8 @@ pub fn parse(text: &str) -> Result { let Some(frame) = parse_timecode(tc) else { return Err(Error::Syntax { line: n + 1, msg: format!("bad timecode \"{tc}\"") }); }; + // the first time code says how the file counts (drop-frame or not) + doc.labels.get_or_insert((RATE, tc.contains([';', '.', ',']))); for (k, w) in it.enumerate() { let Ok(v) = u16::from_str_radix(w, 16) else { doc.warnings.push(format!("line {}: bad code word \"{w}\"", n + 1)); @@ -354,10 +364,15 @@ pub fn wrap_rows(text: &str) -> Vec { rows } +/// The rows the CEA-608 writers (SCC, MCC field 1) load for caption `text`: its plain text in at +/// most 15 rows of 32 columns. What does not fit is left out. +pub fn caption_rows(text: &str) -> Vec { + wrap_rows(&crate::plain_text(text)) +} + /// Byte pairs (without parity) that load `text` into non-displayed memory. fn load_pairs(text: &str) -> Vec<(u8, u8)> { - let plain = crate::plain_text(text); - let rows = wrap_rows(&plain); + let rows = caption_rows(text); let mut out = vec![(0x14, misc::RCL), (0x14, misc::RCL), (0x14, misc::ENM), (0x14, misc::ENM)]; let first_row = 16 - rows.len(); for (i, row) in rows.iter().enumerate() { @@ -438,14 +453,32 @@ pub fn schedule(doc: &Document) -> BTreeMap { } let load = load_pairs(&c.text); let n = load.len() as i64; - // Doubled codes must stay adjacent, so the load is one contiguous run of free frames: - // the latest run ending by `s`, else the first run after `cursor` (delaying the caption). - let run_free = |occ: &BTreeMap, b: i64| (b..b + n).all(|f| !occ.contains_key(&f)); - let b = (cursor..=s - n).rev().find(|&b| run_free(&occ, b)).unwrap_or_else(|| (cursor..).find(|&b| run_free(&occ, b)).unwrap_or(cursor)); - for (k, p) in load.into_iter().enumerate() { - occ.insert(b + k as i64, p); + // Erasing displayed memory can interrupt loading non-displayed memory. Keep each + // doubled control/character code adjacent, but allow pauses between those groups. + let plan_load = |mut f: i64| { + let mut plan = Vec::with_capacity(load.len()); + let mut k = 0; + while let Some(&p) = load.get(k) { + let doubled = (0x10..=0x1f).contains(&p.0) && load.get(k + 1) == Some(&p); + let width = if doubled { 2 } else { 1 }; + while (f..f + width).any(|at| occ.contains_key(&at)) { + f += 1; + } + for offset in 0..width { + plan.push((f + offset, p)); + } + f += width; + k += width as usize; + } + (plan, f) + }; + // Prefer the latest load that finishes by the requested start; if it cannot fit, + // use the earliest available frames rather than waiting until the prior cue ends. + let (plan, end) = (cursor..=s - n).rev().map(plan_load).find(|(_, end)| *end <= s).unwrap_or_else(|| plan_load(cursor)); + for (f, p) in plan { + occ.insert(f, p); } - let mut d = s.max(b + n); + let mut d = s.max(end); while occ.contains_key(&d) { d += 1; } @@ -472,6 +505,7 @@ pub fn code_word(p: (u8, u8)) -> u16 { pub fn write(doc: &Document, drop_frame: bool) -> String { let occ = schedule(doc); + let origin = crate::label_frame(doc.start_timecode, RATE, drop_frame); // time codes count from the start time code let mut out = String::from(HEADER); out.push_str("\n\n"); let mut line: Option<(i64, Vec)> = None; @@ -480,13 +514,13 @@ pub fn write(doc: &Document, drop_frame: bool) -> String { if f != last + 1 && let Some((start, words)) = line.take() { - out.push_str(&format!("{}\t{}\n\n", format_timecode(start, drop_frame), words.join(" "))); + out.push_str(&format!("{}\t{}\n\n", format_timecode(start.saturating_add(origin), drop_frame), words.join(" "))); } line.get_or_insert_with(|| (f, Vec::new())).1.push(format!("{:04x}", word(p))); last = f; } if let Some((start, words)) = line { - out.push_str(&format!("{}\t{}\n\n", format_timecode(start, drop_frame), words.join(" "))); + out.push_str(&format!("{}\t{}\n\n", format_timecode(start.saturating_add(origin), drop_frame), words.join(" "))); } out } @@ -528,6 +562,35 @@ mod tests { assert_eq!(parse_timecode("00:10:00;00"), Some(17982)); } + /// Time codes count from the label of the document's start time code, drop-frame or not; the + /// code words do not change, and `Document::count_from` reads the cues back from it. + #[test] + fn time_codes_count_from_the_start_timecode() { + let doc = Document { cues: vec![cue(60, 120, "Hello")], ..Default::default() }; + let hour = Tick(3600 * crate::time::TICKS_PER_SECOND); // the label 01:00:00:00 + let master = Document { start_timecode: hour, ..doc.clone() }; + let lines = |text: &str| -> Vec<(i64, String)> { + text.lines().filter_map(|l| l.split_once('\t')).map(|(tc, words)| (parse_timecode(tc).unwrap(), words.to_string())).collect() + }; + for (drop_frame, origin) in [(true, 107_892), (false, 108_000)] { + let plain = lines(&write(&doc, drop_frame)); + let shifted: Vec<_> = plain.iter().map(|(f, words)| (f + origin, words.clone())).collect(); + let text = write(&master, drop_frame); + assert_eq!(lines(&text), shifted); + assert!(text.contains("\n01:00:0"), "{text}"); + let mut back = parse(&text).unwrap(); + assert_eq!(back.labels, Some((RATE, drop_frame))); + assert_eq!(back.cues[0].start, RATE.tick_of(origin + 60)); + assert!(back.count_from(hour)); + assert_eq!(back.cues, parse(&write(&doc, drop_frame)).unwrap().cues, "read back from the start time code"); + assert!(!back.count_from(hour), "a cue before the start time code keeps its time"); + } + for t in [Tick(i64::MIN), Tick(-1)] { + assert_eq!(write(&Document { start_timecode: t, ..doc.clone() }, true), write(&doc, true), "a negative start counts from zero"); + } + assert!(write(&Document { start_timecode: Tick(i64::MAX), ..doc }, true).contains('\t')); + } + #[test] fn decode_known_popon() { // "HELLO" on row 15 at 00:00:01;00, cleared at 00:00:03;00 @@ -561,6 +624,24 @@ mod tests { assert_eq!(got, vec![(60, 120, "Hello, world!"), (120, 200, "Second caption\nwith two lines"), (260, 300, "Ñandú ♪ {x} * café “q”")]); } + /// Replaying the `scc_back_to_back` proptest failure: neighbours with the same text merged. + #[test] + fn identical_back_to_back_cues_stay_separate() { + let doc = Document { + cues: vec![cue(90, 135, "Ht"), cue(135, 180, "Ht"), cue(180, 225, "Ht"), cue(225, 270, "Other"), cue(270, 315, "Ht")], + ..Default::default() + }; + // The stream carries each boundary: every cue has its own End of Caption on its start frame. + let occ = schedule(&doc); + for start in [90, 135, 180, 225, 270] { + assert_eq!(occ.get(&start), Some(&(0x14, misc::EOC)), "frame {start}"); + } + let s = write(&doc, false); + let back = parse(&s).unwrap(); + assert_eq!(back.cues, doc.cues); + assert_eq!(write(&back, false), s); + } + #[test] fn wraps_long_lines() { let rows = wrap_rows("the quick brown fox jumps over the lazy dog and keeps running far away"); diff --git a/crates/captions/src/srt.rs b/crates/captions/src/srt.rs index cab7fa8f6..83c19275e 100644 --- a/crates/captions/src/srt.rs +++ b/crates/captions/src/srt.rs @@ -34,6 +34,21 @@ fn is_index(line: &str) -> bool { !l.is_empty() && l.len() <= 10 && l.bytes().all(|b| b.is_ascii_digit()) } +const ZWSP: char = '\u{200B}'; + +/// Keep a text line from reading as a timing line: such a line gains a leading zero-width space. +fn escape(line: &str) -> String { + if parse_timing_line(line.trim_start_matches(ZWSP)).is_some() { format!("{ZWSP}{line}") } else { line.to_string() } +} + +/// Reverse [`escape`]: drop one leading zero-width space when the rest still looks like a timing line. +fn unescape_line(line: &str) -> &str { + match line.strip_prefix(ZWSP) { + Some(r) if parse_timing_line(r.trim_start_matches(ZWSP)).is_some() => r, + _ => line, + } +} + pub fn parse(text: &str) -> Result { let text = text.strip_prefix('\u{feff}').unwrap_or(text); let lines: Vec<&str> = text.lines().collect(); @@ -63,7 +78,7 @@ pub fn parse(text: &str) -> Result { if is_index(l) && lines.get(i + 1).is_some_and(|n| parse_timing_line(n).is_some()) { break; } - text_lines.push(l.trim_end()); + text_lines.push(unescape_line(l.trim_end())); i += 1; } if end <= start { @@ -84,7 +99,8 @@ pub fn write(doc: &Document) -> String { out.push_str(&format!("{}\n{} --> {}\n", n + 1, format_clock(c.start, ','), format_clock(c.end, ','))); // blank lines inside text would end the cue: drop them for l in c.text.lines().filter(|l| !l.trim().is_empty()) { - out.push_str(l); + // stored entities stay as they are, so a literal bracket does not become a tag on reimport + out.push_str(&escape(l)); out.push('\n'); } out.push('\n'); @@ -101,6 +117,17 @@ mod tests { Tick(v * TICKS_PER_MS) } + #[test] + fn entities_stay_distinct_from_style_tags_after_reimport() { + let mut d = Document::default(); + d.cues.push(Cue { start: ms(1000), end: ms(2000), text: "1 < 2 & x".into(), ..Default::default() }); + let encoded = write(&d); + assert_eq!(encoded, "1\n00:00:01,000 --> 00:00:02,000\n1 < 2 & x\n\n"); + let decoded = parse(&encoded).unwrap(); + assert_eq!(decoded.cues, d.cues); + assert_eq!(crate::plain_text(&decoded.cues[0].text), "1 < 2 & x"); + } + #[test] fn basic() { let d = parse("1\n00:00:01,000 --> 00:00:02,500\nHello\nWorld\n\n2\n00:00:03,000 --> 00:00:04,000\nBye\n").unwrap(); @@ -120,6 +147,26 @@ mod tests { assert_eq!(got, vec![(1500, 2250, "A"), (3000, 4000, "B"), (5000, 6000, "42")]); } + #[test] + fn round_trips_text_line_that_looks_like_timing() { + let mut d = parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").unwrap(); + d.cues[0].text = "Shift:\n9:00 --> 10:00".into(); + let back = parse(&write(&d)).unwrap(); + assert_eq!(back.cues.len(), 1); + assert_eq!(back.cues[0].text, "Shift:\n9:00 --> 10:00"); + } + + #[test] + fn round_trips_arrow_and_marker_text() { + for text in ["a --> b", "a --&gt; b", "a --> b", "Shift:\n9:00 --> 10:00\n\u{200B}9:00 --> 10:00", "5\n9:00 --> 10:00"] { + let mut d = parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").unwrap(); + d.cues[0].text = text.into(); + let back = parse(&write(&d)).unwrap(); + assert_eq!(back.cues.len(), 1, "{text:?}"); + assert_eq!(back.cues[0].text, text); + } + } + #[test] fn ignores_byte_order_mark() { let d = parse("\u{feff}00:00:01,000 --> 00:00:02,000\nHi\n").unwrap(); diff --git a/crates/captions/src/stl.rs b/crates/captions/src/stl.rs index 8ea82ab04..93dc9b890 100644 --- a/crates/captions/src/stl.rs +++ b/crates/captions/src/stl.rs @@ -189,6 +189,9 @@ fn decode_tf(tf: &[u8], out: &mut String, italic: &mut bool, underline: &mut boo *underline = false; } 0x00..=0x1f | 0x7f..=0x9f => {} + // literal text, kept apart from the style tags this reader makes + b'<' => out.push_str("<"), + b'&' => out.push_str("&"), 0x20..=0x7e => out.push(b as char), 0xc1..=0xcf => { if let Some(&base) = tf.get(i) @@ -209,7 +212,27 @@ fn decode_tf(tf: &[u8], out: &mut String, italic: &mut bool, underline: &mut boo /// Caption text → text-field bytes (``, `` become control codes; other tags dropped). fn encode_text(text: &str) -> Vec { + encode_text_noting(text, &mut Vec::new()) +} + +/// The characters of `text` that ISO/IEC 6937 has no code for, in order: [`write`] sends each +/// as `?`. +pub fn unencodable(text: &str) -> Vec { + let mut lost = Vec::new(); + encode_text_noting(text, &mut lost); + lost +} + +/// [`encode_text`], noting in `lost` each character it writes as `?`. +fn encode_text_noting(text: &str, lost: &mut Vec) -> Vec { let mut out = Vec::new(); + let mut put = |out: &mut Vec, ch: char| match encode_6937(ch) { + Some(b) => out.extend(b), + None => { + lost.push(ch); + out.push(b'?'); + } + }; let mut rest = text; while let Some(ch) = rest.chars().next() { let is_tag_start = ch == '<' @@ -236,14 +259,20 @@ fn encode_text(text: &str) -> Vec { continue; } } + // a stored entity is the character it names + if let Some((decoded, len)) = crate::entity_at(rest) { + put(&mut out, decoded); + rest = rest.get(len..).unwrap_or(""); + continue; + } if is_tag_start && !rest.contains('>') { // This cannot become markup later. Encode the remaining literal text in one pass // instead of searching the shrinking suffix after every opening bracket. - for ch in rest.chars() { + for ch in crate::decode_entities(rest).chars() { if ch == '\n' { out.push(0x8a); } else { - out.extend(encode_6937(ch).unwrap_or_else(|| vec![b'?'])); + put(&mut out, ch); } } break; @@ -251,7 +280,7 @@ fn encode_text(text: &str) -> Vec { if ch == '\n' { out.push(0x8a); } else { - out.extend(encode_6937(ch).unwrap_or_else(|| vec![b'?'])); + put(&mut out, ch); } rest = &rest[ch.len_utf8()..]; } @@ -364,13 +393,26 @@ fn put(buf: &mut [u8], at: usize, len: usize, s: &str) { } } +/// The frame rate and disk format code [`write`] uses for a programme at `rate`: 29.97 fps +/// (`STL30.01`) for 29.97 and 30, else 25 fps (`STL25.01`). +fn file_rate(rate: Option) -> (FrameRate, &'static str) { + match rate { + Some(r) if r == FrameRate::FPS_29_97 || r == FrameRate::FPS_30 => (FrameRate::FPS_29_97, "STL30.01"), + _ => (FrameRate::FPS_25, "STL25.01"), + } +} + +/// The time code [`write`] gives a caption starting at `t` in a programme at `rate`. +pub fn timecode(t: Tick, rate: Option) -> String { + let (rate, _) = file_rate(rate); + let (_, h, m, s, f) = frames_to_fields(rate.frame_at(rate.snap_nearest(t)), rate, false); + format!("{h:02}:{m:02}:{s:02}:{f:02}") +} + /// Write `doc` at `rate` (25 fps → `STL25.01`; 29.97 / 30 → `STL30.01`; others are written at 25). /// `program` goes in the GSI block's originator field (32 characters). pub fn write(doc: &Document, rate: Option, program: &str) -> Vec { - let (rate, dfc) = match rate { - Some(r) if r == FrameRate::FPS_29_97 || r == FrameRate::FPS_30 => (FrameRate::FPS_29_97, "STL30.01"), - _ => (FrameRate::FPS_25, "STL25.01"), - }; + let (rate, dfc) = file_rate(rate); // TTI blocks first (the GSI counts them) let mut ttis: Vec<[u8; TTI]> = Vec::new(); let mut n_subs = 0u16; @@ -549,12 +591,21 @@ mod tests { let encoded = write(&doc, Some(FrameRate::FPS_25), "test"); let decoded = parse(&encoded).expect("valid EBU STL"); assert_eq!(decoded.cues.len(), 1); - assert_eq!(decoded.cues[0].text, literal); + assert_eq!(crate::plain_text(&decoded.cues[0].text), literal); + assert_eq!(write(&decoded, Some(FrameRate::FPS_25), "test"), encoded, "another export preserves literal bytes"); // Recognized styling still becomes STL control bytes. assert_eq!(encode_text("Hi"), vec![0x80, b'H', b'i', 0x81]); assert_eq!(encode_text("Hi"), vec![0x80, b'H', b'i', 0x81]); } + #[test] + fn entities_are_encoded_as_their_characters() { + // a stored `<` is the character, not an entity spelled out; the tag beside it stays a tag + assert_eq!(encode_text("1 < 2 & x"), encode_text("1 < 2 & x")); + assert_eq!(encode_text("x <y> z"), b"x z".to_vec(), "a decoded bracket is text, not a tag"); + assert_eq!(encode_text("a <b"), encode_text("a '), ("nbsp;", '\u{a0}'), ("quot;", '"'), ("apos;", '\''), ("lrm;", '\u{200e}'), ("rlm;", '\u{200f}')]; + +/// The entity at the start of `s`, as the character it names and its length in bytes. Cue text +/// keeps a literal `<` or `&` as `<` / `&` (as a WebVTT import keeps its entities) so that +/// its style tags stay tags; plain text and the writers decode them here. +pub fn entity_at(s: &str) -> Option<(char, usize)> { + let rest = s.strip_prefix('&')?; + ENTITIES.iter().find(|(name, _)| rest.starts_with(name)).map(|(name, ch)| (*ch, name.len() + 1)) +} + +/// `s` with its entities decoded and its tags kept: for a format that has tags but no entities. +pub fn decode_entities(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(ch) = rest.chars().next() { + if let Some((decoded, len)) = entity_at(rest) { + out.push(decoded); + rest = rest.get(len..).unwrap_or(""); + } else { + out.push(ch); + rest = rest.get(ch.len_utf8()..).unwrap_or(""); + } + } + out +} + /// Strip `<…>` tags and decode the common HTML/WebVTT entities. pub fn plain_text(s: &str) -> String { let mut out = String::with_capacity(s.len()); @@ -40,22 +68,12 @@ pub fn plain_text(s: &str) -> String { } } '&' => { - let rest: String = chars.clone().take(8).collect(); - let ents = [ - ("amp;", '&'), - ("lt;", '<'), - ("gt;", '>'), - ("nbsp;", '\u{a0}'), - ("quot;", '"'), - ("apos;", '\''), - ("lrm;", '\u{200e}'), - ("rlm;", '\u{200f}'), - ]; - if let Some((name, ch)) = ents.iter().find(|(n, _)| rest.starts_with(n)) { - for _ in 0..name.len() { + let rest: String = std::iter::once('&').chain(chars.clone().take(8)).collect(); + if let Some((ch, len)) = entity_at(&rest) { + for _ in 1..len { chars.next(); } - out.push(*ch); + out.push(ch); } else { out.push('&'); } @@ -86,4 +104,12 @@ mod tests { assert_eq!(plain_text(&angle), angle); assert_eq!(plain_text(&ssa), ssa); } + + #[test] + fn entities() { + assert_eq!(entity_at("<b"), Some(('<', 4))); + assert_eq!(entity_at("é"), None); + assert_eq!(entity_at("&"), None); + assert_eq!(decode_entities("1 < 2 & x < &"), "1 < 2 & x < &"); + } } diff --git a/crates/captions/src/time.rs b/crates/captions/src/time.rs deleted file mode 100644 index 51bfdca78..000000000 --- a/crates/captions/src/time.rs +++ /dev/null @@ -1,291 +0,0 @@ -//! Exact caption time. -//! -//! All time is an integer number of [`Tick`]s at [`TICKS_PER_SECOND`] = 254 016 000 000/s. That -//! rate divides evenly into a millisecond and into every broadcast frame duration (23.976, 24, -//! 25, 29.97, 30, 50, 59.94, 60 …), so SRT/WebVTT milliseconds and SCC/MCC/STL/TTML frames all -//! convert without rounding. -//! -//! Every conversion is total: a zero or negative rate (from a damaged file) counts as 23.976 fps -//! instead of dividing by zero, and results outside `i64` saturate. - -use std::ops::{Add, AddAssign, Neg, Sub, SubAssign}; - -/// Ticks per second. -pub const TICKS_PER_SECOND: i64 = 254_016_000_000; - -/// A point or duration in time, in ticks. -/// Arithmetic saturates at the i64 storage limits; representable results remain exact. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Tick(pub i64); - -impl Tick { - pub const ZERO: Tick = Tick(0); - - /// Seconds as a float, for display only: nothing in this crate computes with it. - pub fn seconds(self) -> f64 { - self.0 as f64 / TICKS_PER_SECOND as f64 - } - pub fn min(self, o: Tick) -> Tick { - Tick(self.0.min(o.0)) - } - pub fn max(self, o: Tick) -> Tick { - Tick(self.0.max(o.0)) - } -} - -impl Add for Tick { - type Output = Tick; - fn add(self, o: Tick) -> Tick { - Tick(self.0.saturating_add(o.0)) - } -} -impl Sub for Tick { - type Output = Tick; - fn sub(self, o: Tick) -> Tick { - Tick(self.0.saturating_sub(o.0)) - } -} -impl Neg for Tick { - type Output = Tick; - fn neg(self) -> Tick { - Tick(self.0.saturating_neg()) - } -} -impl AddAssign for Tick { - fn add_assign(&mut self, o: Tick) { - self.0 = self.0.saturating_add(o.0); - } -} -impl SubAssign for Tick { - fn sub_assign(&mut self, o: Tick) { - self.0 = self.0.saturating_sub(o.0); - } -} - -/// A frame rate as an exact rational (`num / den` frames per second). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct FrameRate { - pub num: i64, - pub den: i64, -} - -impl Default for FrameRate { - fn default() -> Self { - FrameRate::FPS_23_976 - } -} - -impl FrameRate { - pub const FPS_23_976: FrameRate = FrameRate { num: 24000, den: 1001 }; - pub const FPS_24: FrameRate = FrameRate { num: 24, den: 1 }; - pub const FPS_25: FrameRate = FrameRate { num: 25, den: 1 }; - pub const FPS_29_97: FrameRate = FrameRate { num: 30000, den: 1001 }; - pub const FPS_30: FrameRate = FrameRate { num: 30, den: 1 }; - pub const FPS_50: FrameRate = FrameRate { num: 50, den: 1 }; - pub const FPS_59_94: FrameRate = FrameRate { num: 60000, den: 1001 }; - pub const FPS_60: FrameRate = FrameRate { num: 60, den: 1 }; - - /// The rate in lowest terms. - pub fn new(num: i64, den: i64) -> Self { - let g = i128::from(gcd(num.unsigned_abs(), den.unsigned_abs()).max(1)); - FrameRate { num: (i128::from(num) / g) as i64, den: (i128::from(den) / g) as i64 } - } - - /// This rate if it is positive, else the default (a damaged file can carry a zero - /// or negative rate; every frame computation uses this so it can't divide by zero). - pub fn sane(self) -> FrameRate { - if self.num > 0 && self.den > 0 { self } else { FrameRate::default() } - } - - /// Exact duration of one frame (rounded down only for exotic rates). - /// Values outside the integer tick range saturate at its limit. - pub fn frame_duration(self) -> Tick { - let r = self.sane(); - Tick(clamp_i64((TICKS_PER_SECOND as i128 * r.den as i128) / r.num as i128)) - } - - /// Index of the frame containing `t` (floor), saturated to the integer frame range. - pub fn frame_at(self, t: Tick) -> i64 { - clamp_i64(frame_index(self.sane(), t)) - } - - /// Start tick of frame `f` (ceiling division). - /// - /// Uses ceiling (not floor) so that `frame_at(tick_of(f)) == f` holds for every - /// representable frame boundary with at least one tick per frame, even when the frame duration is not an integer number of ticks - /// (exotic rates like 37.516 fps where `TICKS_PER_SECOND * den / num` has a - /// fractional remainder). Floor division truncates the remainder, causing each - /// frame boundary to drift backward by one tick until `frame_at` returns `f - 1` - /// instead of `f` — frame stepping then stalls or moves backward. - /// Values outside the integer tick range saturate at its limit. - pub fn tick_of(self, f: i64) -> Tick { - Tick(clamp_i64(frame_boundary(self.sane(), i128::from(f)))) - } - - /// Snap `t` down to a frame boundary. - pub fn snap(self, t: Tick) -> Tick { - let r = self.sane(); - Tick(clamp_i64(frame_boundary(r, frame_index(r, t)))) - } - - /// Snap `t` to the nearest frame boundary. - pub fn snap_nearest(self, t: Tick) -> Tick { - let r = self.sane(); - // Keep the frame index and both boundaries wide until choosing the nearest. Saturating - // an unrepresentable upper boundary first would make it seem closer than it really is. - let f = frame_index(r, t); - let a = frame_boundary(r, f); - let b = frame_boundary(r, f.saturating_add(1)); - let t = i128::from(t.0); - Tick(clamp_i64(if t - a <= b - t { a } else { b })) - } - - /// Timecode base (frames counted per timecode second): 30 for 29.97, 24 for 23.976. - pub fn timecode_base(self) -> i64 { - let r = self.sane(); - (r.num / r.den).saturating_add(i64::from(r.num % r.den != 0)).max(1) - } - - /// NTSC (x/1001) rates can use drop-frame timecode. - pub fn is_ntsc(self) -> bool { - self.den == 1001 - } - - /// Whether drop-frame counting applies (29.97 / 59.94 / 119.88). - pub fn supports_drop_frame(self) -> bool { - self.is_ntsc() && self.timecode_base() % 30 == 0 - } -} - -/// Narrow only after applying the storage bounds, never by a wrapping integer cast. -fn clamp_i64(value: i128) -> i64 { - value.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64 -} - -/// Callers pass a positive rate. Products of two i64 values fit in i128. -fn frame_index(rate: FrameRate, t: Tick) -> i128 { - (i128::from(t.0) * i128::from(rate.num)).div_euclid(i128::from(TICKS_PER_SECOND) * i128::from(rate.den)) -} - -/// Ceiling of the rational boundary. An overflowing numerator divided by an i64 rate cannot -/// fit in an i64 tick, so saturating that intermediate preserves the public result. Boundaries -/// derived from frame_index remain within i128 (at most one frame away from an i64 tick). -fn frame_boundary(rate: FrameRate, frame: i128) -> i128 { - let Some(n) = frame.checked_mul(i128::from(TICKS_PER_SECOND)).and_then(|n| n.checked_mul(i128::from(rate.den))) else { - return if frame < 0 { i128::MIN } else { i128::MAX }; - }; - let d = i128::from(rate.num); - // Flooring a fractional boundary puts the tick in the preceding frame. - n.div_euclid(d) + i128::from(n.rem_euclid(d) != 0) -} - -fn gcd(mut a: u64, mut b: u64) -> u64 { - while b != 0 { - (a, b) = (b, a % b); - } - a -} - -/// Drop-frame parameters: frames dropped per minute and nominal base. -fn df_params(rate: FrameRate) -> (i64, i64) { - let base = rate.timecode_base(); - (base / 15, base) // 30 → 2, 60 → 4, 120 → 8 -} - -/// Convert a frame count to SMPTE fields `(negative, h, m, s, f)`. -pub fn frames_to_fields(frame: i64, rate: FrameRate, drop_frame: bool) -> (bool, i64, i64, i64, i64) { - let neg = frame < 0; - let mut n = i128::from(frame).abs(); - let (drop, base) = df_params(rate); - let (drop, base) = (i128::from(drop), i128::from(base)); - if drop_frame && rate.supports_drop_frame() { - let per_min = base * 60 - drop; - let per_10 = per_min * 10 + drop; - let d = n / per_10; - let m = n % per_10; - n = n.saturating_add(drop * 9 * d); - if m > drop { - n = n.saturating_add(drop * ((m - drop) / per_min)); - } - } - let f = n % base; - let s = (n / base) % 60; - let mi = (n / (base * 60)) % 60; - let h = n / (base * 3600); - (neg, clamp_i64(h), clamp_i64(mi), clamp_i64(s), clamp_i64(f)) -} - -/// Convert SMPTE fields back to a frame count. -pub fn fields_to_frames(h: i64, m: i64, s: i64, f: i64, rate: FrameRate, drop_frame: bool) -> i64 { - let (drop, base) = df_params(rate); - let seconds = i128::from(h) * 3600 + i128::from(m) * 60 + i128::from(s); - // Nominal drop-frame labels can exceed i64 even when the final frame count fits. - let mut n = seconds.saturating_mul(i128::from(base)).saturating_add(i128::from(f)); - if drop_frame && rate.supports_drop_frame() { - let total_min = i128::from(h) * 60 + i128::from(m); - n = n.saturating_sub(i128::from(drop) * (total_min - total_min / 10)); - } - clamp_i64(n) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn broadcast_rates_and_milliseconds_are_exact() { - for r in [ - FrameRate::FPS_23_976, - FrameRate::FPS_24, - FrameRate::FPS_25, - FrameRate::FPS_29_97, - FrameRate::FPS_30, - FrameRate::FPS_50, - FrameRate::FPS_59_94, - FrameRate::FPS_60, - ] { - let d = r.frame_duration(); - assert_eq!(i128::from(d.0) * i128::from(r.num), i128::from(TICKS_PER_SECOND) * i128::from(r.den), "{r:?}"); - for f in [-1000, -1, 0, 1, 1799, 107_892, 10_000_000] { - assert_eq!(r.frame_at(r.tick_of(f)), f, "{r:?} {f}"); - } - } - assert_eq!(TICKS_PER_SECOND % 1000, 0); - } - - #[test] - fn drop_frame_known_values() { - let r = FrameRate::FPS_29_97; - let fields = |f, df| frames_to_fields(f, r, df); - assert_eq!(fields(1799, true), (false, 0, 0, 59, 29)); - assert_eq!(fields(1800, true), (false, 0, 1, 0, 2)); - assert_eq!(fields(17982, true), (false, 0, 10, 0, 0)); - assert_eq!(fields(107_892, true), (false, 1, 0, 0, 0)); - assert_eq!(fields(1800, false), (false, 0, 1, 0, 0)); - assert_eq!(frames_to_fields(3600, FrameRate::FPS_59_94, true), (false, 0, 1, 0, 4)); - for f in (0..24 * 107_892).step_by(997) { - let (_, h, m, s, ff) = fields(f, true); - assert_eq!(fields_to_frames(h, m, s, ff, r, true), f); - } - } - - /// A damaged file can carry a zero or negative rate or a huge time: nothing divides by zero - /// or wraps. - #[test] - fn hostile_rates_and_times_saturate() { - for r in [FrameRate { num: 0, den: 0 }, FrameRate { num: 0, den: 1 }, FrameRate { num: 25, den: 0 }, FrameRate { num: -30, den: 1 }] { - assert_eq!(r.tick_of(10), FrameRate::default().tick_of(10)); - assert_eq!(r.frame_at(Tick(TICKS_PER_SECOND)), FrameRate::default().frame_at(Tick(TICKS_PER_SECOND))); - assert!(r.frame_duration() > Tick::ZERO); - assert!(r.timecode_base() >= 1); - let _ = r.snap_nearest(Tick(12345)); - } - assert_eq!(Tick(i64::MAX) + Tick(1), Tick(i64::MAX)); - assert_eq!(Tick(i64::MIN) - Tick(1), Tick(i64::MIN)); - assert_eq!(-Tick(i64::MIN), Tick(i64::MAX)); - assert_eq!(FrameRate::FPS_25.tick_of(i64::MAX), Tick(i64::MAX)); - assert_eq!(FrameRate::new(i64::MAX, 1).frame_at(Tick(i64::MAX)), i64::MAX); - let _ = frames_to_fields(i64::MIN, FrameRate::FPS_29_97, true); - let _ = fields_to_frames(i64::MAX, i64::MAX, i64::MAX, i64::MAX, FrameRate::FPS_29_97, true); - } -} diff --git a/crates/captions/src/ttml.rs b/crates/captions/src/ttml.rs index 797d86c9c..78db4763b 100644 --- a/crates/captions/src/ttml.rs +++ b/crates/captions/src/ttml.rs @@ -53,6 +53,11 @@ const CANONICAL: craft_xml::Canonical<'static> = craft_xml::Canonical::new(&[ ("ttm", NS_TTM), ("ttm10", NS_TTM_DRAFT), ("ttm04", NS_TTM_DRAFT_APRIL), + ("tts", NS_TTS), + ("tts10", "http://www.w3.org/2006/10/ttaf1#style"), + ("tts10s", "http://www.w3.org/2006/10/ttaf1#styling"), + ("tts04", "http://www.w3.org/2006/04/ttaf1#style"), + ("tts04s", "http://www.w3.org/2006/04/ttaf1#styling"), ]); /// The line (from 1) of the root element's start tag, for error messages. @@ -88,6 +93,8 @@ fn esc(s: &str) -> String { '>' => o.push_str(">"), '"' => o.push_str("""), '\'' => o.push_str("'"), + // XML 1.0 forbids these (C0 controls, U+FFFE, U+FFFF), even escaped + c if !craft_xml::is_xml_char(c) => {} c => o.push(c), } } @@ -106,6 +113,75 @@ fn time_expr(t: Tick, rate: Option) -> String { } } +/// Memoised "next occurrence of a quote byte" searches, so unterminated quotes are not rescanned. +#[derive(Default)] +struct QuoteCache { + found: [Option<(usize, Option)>; 2], +} + +impl QuoteCache { + /// Index of the next `quote` byte at or after `from`. + fn next(&mut self, bytes: &[u8], quote: u8, from: usize) -> Option { + let slot = usize::from(quote == b'\''); + if let Some((searched, result)) = self.found[slot] + && searched <= from + && result.is_none_or(|r| r >= from) + { + return result; + } + let result = bytes.get(from..).and_then(|t| t.iter().position(|&c| c == quote)).map(|i| from + i); + self.found[slot] = Some((from, result)); + result + } +} + +/// Parses a tag starting at `bytes[start] == b'<'`: optional `/` (closing), a name of ASCII +/// letters/digits starting with a letter immediately after, then whitespace-separated +/// `name="value"` / `name='value'` attributes, optional `/` before `>`. A `>` inside a quoted +/// value does not end the tag. Returns `(index after '>', closing, lowercase name)`; the name is empty for a self-closing tag. +fn parse_tag(bytes: &[u8], start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> { + let mut i = start + 1; + let closing = bytes.get(i) == Some(&b'/'); + if closing { + i += 1; + } + let name_start = i; + if !bytes.get(i)?.is_ascii_alphabetic() { + return None; + } + while bytes.get(i).is_some_and(u8::is_ascii_alphanumeric) { + i += 1; + } + let name = String::from_utf8_lossy(bytes.get(name_start..i)?).to_ascii_lowercase(); + loop { + let ws_start = i; + while bytes.get(i).is_some_and(u8::is_ascii_whitespace) { + i += 1; + } + match bytes.get(i)? { + b'>' => return Some((i + 1, closing, name)), + // self-closing: no markup + b'/' if !closing && bytes.get(i + 1) == Some(&b'>') => return Some((i + 2, closing, String::new())), + _ => {} + } + if i == ws_start { + return None; + } + let key_start = i; + while bytes.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) { + i += 1; + } + if i == key_start || bytes.get(i) != Some(&b'=') { + return None; + } + let quote = *bytes.get(i + 1)?; + if quote != b'"' && quote != b'\'' { + return None; + } + i = cache.next(bytes, quote, i + 2)? + 1; + } +} + /// Caption text (`\n` lines, ``/``/`` tags) → TTML inline content. fn inline(text: &str) -> String { let mut out = String::new(); @@ -127,25 +203,12 @@ fn inline(text: &str) -> String { } }; let mut rest = text; - // Once no `>` remains, no later `<` can start a tag either. Remember that instead of searching - // the shrinking suffix again after every literal `<`, which made `<<<<…` quadratic. - let mut closer_remains = true; + let mut cache = QuoteCache::default(); while !rest.is_empty() { - let tag_end = match rest.strip_prefix('<') { - Some(after) if closer_remains => { - let end = after.find('>'); - closer_remains = end.is_some(); - end - } - _ => None, - }; - if let Some(end) = tag_end { - let after = &rest[1..]; - let tag = after[..end].trim().to_ascii_lowercase(); - let (closing, name) = match tag.strip_prefix('/') { - Some(n) => (true, n.trim().to_string()), - None => (false, tag.split_whitespace().next().unwrap_or("").to_string()), - }; + // Only a well-formed tag is markup; "1 < 2 and 3 > 2" and "ad" are text. + if rest.starts_with('<') + && let Some((end, closing, name)) = parse_tag(text.as_bytes(), text.len() - rest.len(), &mut cache) + { let attr = match name.as_str() { "i" => Some("tts:fontStyle=\"italic\""), "b" => Some("tts:fontWeight=\"bold\""), @@ -159,11 +222,17 @@ fn inline(text: &str) -> String { active.push(a); } } - rest = &after[end + 1..]; + rest = text.get(end..).unwrap_or(""); continue; } let Some(ch) = rest.chars().next() else { break }; sync(&mut out, &active, &mut emitted); + // a stored entity is the character it names, escaped once for XML + if let Some((decoded, len)) = crate::entity_at(rest) { + out.push_str(&esc(&decoded.to_string())); + rest = rest.get(len..).unwrap_or(""); + continue; + } if ch == '\n' { out.push_str("
"); } else { @@ -177,13 +246,34 @@ fn inline(text: &str) -> String { out } +/// An XML name without a colon (Namespaces in XML, NCName). fn is_ncname(s: &str) -> bool { - let mut c = s.chars(); - c.next().is_some_and(|f| f.is_alphabetic() || f == '_') && c.all(|x| x.is_alphanumeric() || matches!(x, '_' | '-' | '.')) + craft_xml::is_name(s) && !s.contains(':') } -fn cue_id(cue: &Cue, index: usize) -> String { - cue.id.as_deref().filter(|x| is_ncname(x)).map(str::to_string).unwrap_or_else(|| format!("c{}", index + 1)) +fn cue_ids(doc: &Document) -> Vec { + // Reserve every valid explicit ID before allocating fallbacks, including IDs on later cues. + let reserved: HashSet<&str> = + ["s1", "r1"].into_iter().chain(doc.cues.iter().filter_map(|cue| cue.id.as_deref()).filter(|id| is_ncname(id))).collect(); + let mut used: HashSet = ["s1".into(), "r1".into()].into_iter().collect(); + doc.cues + .iter() + .enumerate() + .map(|(index, cue)| { + if let Some(id) = cue.id.as_deref().filter(|id| is_ncname(id)) + && used.insert(id.to_string()) + { + return id.to_string(); + } + let mut id = format!("c{}", index.saturating_add(1)); + // Each collision consumes a distinct reserved or used ID, so this loop is bounded by their combined size. + while reserved.contains(id.as_str()) || used.contains(&id) { + id.push('_'); + } + used.insert(id.clone()); + id + }) + .collect() } /// Write `doc` as TTML. `rate` (IMSC1 only) makes times exact frame offsets; `lang` is the @@ -205,8 +295,9 @@ pub fn write(doc: &Document, flavor: Flavor, rate: Option, lang: &str } o.push_str(&format!(" xml:lang=\"{}\">\n", esc(if lang.is_empty() { "en" } else { lang }))); // Keep agent identifiers distinct from the IDs already emitted for cues, style and region. + let cue_ids = cue_ids(doc); let mut ids: HashSet = ["s1".into(), "r1".into()].into_iter().collect(); - ids.extend(doc.cues.iter().enumerate().map(|(i, c)| cue_id(c, i))); + ids.extend(cue_ids.iter().cloned()); let mut speakers = Vec::new(); let mut speaker_ids = HashMap::new(); for speaker in doc.cues.iter().filter_map(|c| c.speaker.as_deref()) { @@ -235,8 +326,7 @@ pub fn write(doc: &Document, flavor: Flavor, rate: Option, lang: &str " \n \n \n", ); o.push_str(" \n \n

\n"); - for (i, c) in doc.cues.iter().enumerate() { - let id = cue_id(c, i); + for (c, id) in doc.cues.iter().zip(cue_ids) { let agent = c.speaker.as_deref().and_then(|s| speaker_ids.get(s)).map(|id| format!(" ttm:role=\"x-speaker\" ttm:agent=\"{id}\"")).unwrap_or_default(); o.push_str(&format!( @@ -488,98 +578,204 @@ struct Fmt { underline: bool, } -fn style_of(n: &El, styles: &std::collections::HashMap, parent: Fmt) -> Fmt { +/// An explicit `inherit` restores the parent value, even after earlier style references. +#[derive(Clone, Copy)] +enum FmtValue { + Set(bool), + Inherit, +} + +impl FmtValue { + fn resolve(self, inherited: bool) -> bool { + match self { + Self::Set(value) => value, + Self::Inherit => inherited, + } + } +} + +/// The style properties an element or a `café <3", opts); +let mut text = String::new(); +while let Some(token) = lexer.next() { + match token { + Token::Text(t) => text.push_str(&unescape(t)), + // A style sheet's text, for a caller that reads it. + Token::Start(tag) if tag.name == "style" => assert_eq!(lexer.raw_content("style"), "p{}"), + Token::Start(tag) => assert_eq!(tag.attr("class").as_deref(), Some("x")), + Token::End(name) => assert_eq!(name, "b"), + } +} +assert_eq!(text, "café <3"); +assert_eq!(escape(&text), "café <3"); +``` + +## The tokenizer + +`Lexer` is an iterator of `Token::Text`, `Token::Start(Tag)` and `Token::End(name)`, borrowed +from the input. Text and attribute values come as written; `unescape` and `Tag::attr` decode +them. + +- A `<` that starts no tag is text. A tag, comment or raw element that never ends runs to the + end of the input. +- Comments, doctypes, processing instructions and conditional comments never come out. +- `Options::drop`: elements skipped whole, content and end tag included. +- `Options::raw_text`: elements whose content is one text token, not markup. +- `Lexer::raw_content(name)`: after a start tag, take the element's raw content yourself. +- `Limits`: attributes kept per tag (64) and the longest tag name (64 bytes; a longer one has an + empty name). + +## Character references + +`unescape` decodes named, decimal and hex references. The named set is HTML 4's (Latin-1, Greek, +symbols, arrows, mathematics) and a few more. The 94 legacy names decode without their `;` +(`© 2024`), longest match first, as in browsers; `unescape_attr` leaves such a name alone +when a letter, a digit or `=` follows, so a query string keeps its `©=1`. A numeric reference +to 0x80-0x9F means the Windows-1252 character; 0, surrogates, and numbers past U+10FFFF or too +long to be numbers become U+FFFD. Names are looked at for 32 bytes at most, so the work is +linear. + +`escape` writes `& < > " '` as references; `escape_dq` leaves `'`, for content and attribute +values in double quotes. + +## Not here + +- The full HTML5 named reference table (about 2,200 names): only the names above. +- Decoding bytes to text. `declared_charset` gives the label a page names; a decoder for it is + the caller's (`craft-mime::charset` for the WHATWG labels). +- Tree construction, implied end tags, CSS. + +## Provenance + +The tokenizer is MailCraft's (`crates/html/src/tokenizer.rs`), with its policy (which elements to +drop, the caps) turned into options. The character references are WordCraft's +(`crates/formats/src/html/entity.rs`: the name table and the legacy names without `;`), with +MailCraft's Latin-1 and Greek tables and its handling of numbers too long to be numbers. +Written from the HTML Living Standard. diff --git a/crates/html/src/entity.rs b/crates/html/src/entity.rs new file mode 100644 index 000000000..8ece41926 --- /dev/null +++ b/crates/html/src/entity.rs @@ -0,0 +1,388 @@ +//! Character references (`&`, `é`, `é`) and escaping. + +/// The Latin-1 names in code point order, from U+00A0 (`nbsp`) to U+00FF (`yuml`). +const LATIN1: [&str; 96] = [ + "nbsp", "iexcl", "cent", "pound", "curren", "yen", "brvbar", "sect", "uml", "copy", "ordf", "laquo", "not", "shy", "reg", "macr", "deg", + "plusmn", "sup2", "sup3", "acute", "micro", "para", "middot", "cedil", "sup1", "ordm", "raquo", "frac14", "frac12", "frac34", "iquest", "Agrave", + "Aacute", "Acirc", "Atilde", "Auml", "Aring", "AElig", "Ccedil", "Egrave", "Eacute", "Ecirc", "Euml", "Igrave", "Iacute", "Icirc", "Iuml", "ETH", + "Ntilde", "Ograve", "Oacute", "Ocirc", "Otilde", "Ouml", "times", "Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml", "Yacute", "THORN", "szlig", + "agrave", "aacute", "acirc", "atilde", "auml", "aring", "aelig", "ccedil", "egrave", "eacute", "ecirc", "euml", "igrave", "iacute", "icirc", + "iuml", "eth", "ntilde", "ograve", "oacute", "ocirc", "otilde", "ouml", "divide", "oslash", "ugrave", "uacute", "ucirc", "uuml", "yacute", + "thorn", "yuml", +]; + +/// Greek capitals from U+0391; U+03A2 is unassigned. +const GREEK_UPPER: [&str; 25] = [ + "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta", "Eta", "Theta", "Iota", "Kappa", "Lambda", "Mu", "Nu", "Xi", "Omicron", "Pi", "Rho", "", + "Sigma", "Tau", "Upsilon", "Phi", "Chi", "Psi", "Omega", +]; + +/// Greek small letters from U+03B1. +const GREEK_LOWER: [&str; 25] = [ + "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi", "rho", + "sigmaf", "sigma", "tau", "upsilon", "phi", "chi", "psi", "omega", +]; + +/// What a numeric reference to 0x80–0x9F means (HTML Living Standard §13.2.5.80: the +/// Windows-1252 characters, by long tradition). +const C1: [u32; 32] = [ + 0x20AC, 0x81, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x8D, 0x017D, 0x8F, 0x90, 0x2018, 0x2019, + 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x9D, 0x017E, 0x0178, +]; + +/// Longest entity name looked at. +const MAX_NAME: usize = 32; + +/// The legacy names HTML also decodes without a `;`, sorted by bytes. +const BARE_NAMES: &[&str] = &[ + "AElig", "AMP", "Aacute", "Acirc", "Agrave", "Aring", "Atilde", "Auml", "COPY", "Ccedil", "Eacute", "Ecirc", "Egrave", "Euml", "GT", "Iacute", + "Icirc", "Igrave", "Iuml", "LT", "Ntilde", "Oacute", "Ocirc", "Ograve", "Oslash", "Otilde", "Ouml", "QUOT", "REG", "Uacute", "Ucirc", "Ugrave", + "Uuml", "Yacute", "aacute", "acirc", "aelig", "agrave", "amp", "aring", "atilde", "auml", "ccedil", "cent", "copy", "curren", "deg", "divide", + "eacute", "ecirc", "egrave", "euml", "frac12", "frac14", "frac34", "gt", "iacute", "icirc", "iexcl", "igrave", "iquest", "iuml", "laquo", "lt", + "micro", "middot", "nbsp", "ntilde", "oacute", "ocirc", "ograve", "oslash", "otilde", "ouml", "para", "plusmn", "pound", "quot", "raquo", "reg", + "sect", "shy", "sup1", "sup2", "sup3", "szlig", "times", "uacute", "ucirc", "ugrave", "uuml", "yacute", "yen", "yuml", +]; + +/// Text as HTML, for content and for attribute values in either kind of quote: `&`, `<`, `>`, +/// `"` and `'` become character references. +pub fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len().saturating_add(text.len() / 8)); + push_escaped(&mut out, text, true); + out +} + +/// [`escape`] that leaves `'` as it is: for content and for attribute values in double quotes. +pub fn escape_dq(text: &str) -> String { + let mut out = String::with_capacity(text.len().saturating_add(text.len() / 8)); + push_escaped(&mut out, text, false); + out +} + +fn push_escaped(out: &mut String, text: &str, apos: bool) { + for c in text.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' if apos => out.push_str("'"), + c => out.push(c), + } + } +} + +/// The character an entity body names (`amp`, `#38`, `#x26`: what stands between `&` and `;`). +pub fn decode_entity(body: &str) -> Option { + match body.strip_prefix('#') { + Some(_) => reference(body, false).filter(|(_, used)| *used == body.len()).map(|(c, _)| c), + None => named(body), + } +} + +/// Character references in text decoded: named (the HTML 4 set and more), decimal and hex. +/// Anything that is no reference stays as it is. A legacy name decodes without its `;` +/// (`© 2024`), as in browsers. +pub fn unescape(text: &str) -> String { + unescape_in(text, false) +} + +/// [`unescape`] for an attribute value: a legacy name without its `;` stays text when a letter, +/// a digit or `=` follows, so `?a=1©=2` is a query string and not a copyright sign. +pub fn unescape_attr(text: &str) -> String { + unescape_in(text, true) +} + +fn unescape_in(text: &str, attr: bool) -> String { + if !text.contains('&') { + return text.to_string(); + } + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(i) = rest.find('&') { + out.push_str(rest.get(..i).unwrap_or("")); + let after = rest.get(i + 1..).unwrap_or(""); + match reference(after, attr) { + Some((c, used)) => { + out.push(c); + rest = after.get(used..).unwrap_or(""); + } + None => { + out.push('&'); + rest = after; + } + } + } + out.push_str(rest); + out +} + +/// The character a reference names and the bytes it takes, given the text after its `&` +/// (`attr`: inside an attribute value, see [`unescape_attr`]). At most [`MAX_NAME`] bytes are +/// looked at for a name, so a text of stray `&`s is read in linear time. +pub fn reference(s: &str, attr: bool) -> Option<(char, usize)> { + if let Some(num) = s.strip_prefix('#') { + let (digits, radix, skip) = match num.strip_prefix(['x', 'X']) { + Some(hex) => (hex, 16, 2), + None => (num, 10, 1), + }; + let len = digits.bytes().take_while(|b| char::from(*b).is_digit(radix)).count(); + if len == 0 { + return None; + } + // Too many digits is not a character; neither is 0, a surrogate, or anything past U+10FFFF. + let mut code: u32 = 0; + for d in digits.bytes().take(len) { + let d = char::from(d).to_digit(radix).unwrap_or(0); + code = code.checked_mul(radix).and_then(|c| c.checked_add(d)).unwrap_or(u32::MAX); + } + let semicolon = usize::from(digits.as_bytes().get(len) == Some(&b';')); + return Some((numeric(code), skip + len + semicolon)); + } + let len = s.bytes().take(MAX_NAME).take_while(u8::is_ascii_alphanumeric).count(); + if s.as_bytes().get(len) == Some(&b';') + && let Some(c) = s.get(..len).and_then(named) + { + return Some((c, len + 1)); + } + // Without its `;`: the longest legacy name (2 to 6 letters) the text starts with. + let len = (2..=len.min(6)).rev().find(|&l| s.get(..l).is_some_and(|p| BARE_NAMES.binary_search(&p).is_ok()))?; + if attr && s.as_bytes().get(len).is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'=') { + return None; + } + s.get(..len).and_then(named).map(|c| (c, len)) +} + +fn numeric(code: u32) -> char { + let code = match code { + 0x80..=0x9F => C1.get((code - 0x80) as usize).copied().unwrap_or(code), + c => c, + }; + match char::from_u32(code) { + Some('\0') | None => char::REPLACEMENT_CHARACTER, + Some(c) => c, + } +} + +fn named(name: &str) -> Option { + if name.is_empty() { + return None; + } + let c = match name { + "amp" | "AMP" => '&', + "lt" | "LT" => '<', + "gt" | "GT" => '>', + "quot" | "QUOT" => '"', + "apos" | "APOS" => '\'', + "nbsp" | "NBSP" => '\u{00A0}', + "ensp" => '\u{2002}', + "emsp" => '\u{2003}', + "thinsp" => '\u{2009}', + "shy" => '\u{00AD}', + "copy" | "COPY" => '©', + "reg" | "REG" => '®', + "trade" | "TRADE" => '™', + "hellip" => '…', + "mdash" => '—', + "ndash" => '–', + "minus" => '−', + "lsquo" => '‘', + "rsquo" => '’', + "sbquo" => '‚', + "ldquo" => '“', + "rdquo" => '”', + "bdquo" => '„', + "laquo" => '«', + "raquo" => '»', + "bull" => '•', + "middot" => '·', + "deg" => '°', + "plusmn" => '±', + "times" => '×', + "divide" => '÷', + "frac12" => '½', + "frac14" => '¼', + "frac34" => '¾', + "frac13" => '⅓', + "frac23" => '⅔', + "frac18" => '⅛', + "frac38" => '⅜', + "frac58" => '⅝', + "frac78" => '⅞', + "sup1" => '¹', + "sup2" => '²', + "sup3" => '³', + "micro" => 'µ', + "permil" => '‰', + "prime" => '′', + "Prime" => '″', + "oline" => '‾', + "frasl" => '⁄', + "sect" => '§', + "para" => '¶', + "euro" | "EURO" => '€', + "pound" | "POUND" => '£', + "yen" | "YEN" => '¥', + "cent" | "CENT" => '¢', + "curren" => '¤', + "dagger" => '†', + "Dagger" => '‡', + "larr" => '←', + "rarr" => '→', + "uarr" => '↑', + "darr" => '↓', + "harr" => '↔', + "lArr" => '⇐', + "rArr" => '⇒', + "uArr" => '⇑', + "dArr" => '⇓', + "hArr" => '⇔', + "crarr" => '↵', + "forall" => '∀', + "part" => '∂', + "exist" => '∃', + "empty" => '∅', + "nabla" => '∇', + "isin" => '∈', + "notin" => '∉', + "ni" => '∋', + "prod" => '∏', + "sum" => '∑', + "radic" => '√', + "prop" => '∝', + "ang" => '∠', + "and" => '∧', + "or" => '∨', + "cap" => '∩', + "cup" => '∪', + "int" => '∫', + "there4" => '∴', + "sim" => '∼', + "cong" => '≅', + "asymp" | "approx" => '≈', + "ne" => '≠', + "equiv" => '≡', + "le" => '≤', + "ge" => '≥', + "sub" => '⊂', + "sup" => '⊃', + "nsub" => '⊄', + "sube" => '⊆', + "supe" => '⊇', + "oplus" => '⊕', + "otimes" => '⊗', + "perp" => '⊥', + "sdot" => '⋅', + "infin" => '∞', + "loz" => '◊', + "spades" => '♠', + "clubs" => '♣', + "hearts" => '♥', + "diams" => '♦', + "check" => '✓', + "iexcl" => '¡', + "iquest" => '¿', + "szlig" => 'ß', + "auml" => 'ä', + "ouml" => 'ö', + "uuml" => 'ü', + "Auml" => 'Ä', + "Ouml" => 'Ö', + "Uuml" => 'Ü', + "eacute" => 'é', + "egrave" => 'è', + "ecirc" => 'ê', + "euml" => 'ë', + "Eacute" => 'É', + "Egrave" => 'È', + "Ecirc" => 'Ê', + "Euml" => 'Ë', + "aacute" => 'á', + "agrave" => 'à', + "acirc" => 'â', + "atilde" => 'ã', + "Agrave" => 'À', + "Aacute" => 'Á', + "Acirc" => 'Â', + "Atilde" => 'Ã', + "iacute" => 'í', + "igrave" => 'ì', + "icirc" => 'î', + "iuml" => 'ï', + "Iacute" => 'Í', + "Igrave" => 'Ì', + "Icirc" => 'Î', + "Iuml" => 'Ï', + "oacute" => 'ó', + "ograve" => 'ò', + "ocirc" => 'ô', + "otilde" => 'õ', + "Oacute" => 'Ó', + "Ograve" => 'Ò', + "Ocirc" => 'Ô', + "Otilde" => 'Õ', + "uacute" => 'ú', + "ugrave" => 'ù', + "ucirc" => 'û', + "Uacute" => 'Ú', + "Ugrave" => 'Ù', + "Ucirc" => 'Û', + "yacute" => 'ý', + "yuml" => 'ÿ', + "Yacute" => 'Ý', + "ntilde" => 'ñ', + "Ntilde" => 'Ñ', + "ccedil" => 'ç', + "Ccedil" => 'Ç', + "aring" => 'å', + "Aring" => 'Å', + "oslash" => 'ø', + "Oslash" => 'Ø', + "aelig" => 'æ', + "AElig" => 'Æ', + "alpha" => 'α', + "beta" => 'β', + "gamma" => 'γ', + "delta" => 'δ', + "epsilon" => 'ε', + "zeta" => 'ζ', + "eta" => 'η', + "theta" => 'θ', + "iota" => 'ι', + "kappa" => 'κ', + "lambda" => 'λ', + "mu" => 'μ', + "nu" => 'ν', + "xi" => 'ξ', + "pi" => 'π', + "rho" => 'ρ', + "sigma" => 'σ', + "tau" => 'τ', + "upsilon" => 'υ', + "phi" => 'φ', + "chi" => 'χ', + "psi" => 'ψ', + "omega" => 'ω', + "Gamma" => 'Γ', + "Delta" => 'Δ', + "Theta" => 'Θ', + "Lambda" => 'Λ', + "Xi" => 'Ξ', + "Pi" => 'Π', + "Sigma" => 'Σ', + "Upsilon" => 'Υ', + "Phi" => 'Φ', + "Psi" => 'Ψ', + "Omega" => 'Ω', + "zwj" => '\u{200D}', + "zwnj" => '\u{200C}', + "cross" => '\u{2717}', + _ => { + let at = |table: &[&str], base: u32| table.iter().position(|n| *n == name).and_then(|i| char::from_u32(base + i as u32)); + return at(&LATIN1, 0xA0).or_else(|| at(&GREEK_UPPER, 0x391)).or_else(|| at(&GREEK_LOWER, 0x3B1)); + } + }; + Some(c) +} + +#[cfg(test)] +mod tests; diff --git a/crates/html/src/entity/tests.rs b/crates/html/src/entity/tests.rs new file mode 100644 index 000000000..3abd35fdc --- /dev/null +++ b/crates/html/src/entity/tests.rs @@ -0,0 +1,132 @@ +use super::{BARE_NAMES, GREEK_LOWER, GREEK_UPPER, LATIN1, decode_entity, escape, escape_dq, named, reference, unescape, unescape_attr}; + +#[test] +fn escapes_the_five() { + assert_eq!(escape(r#"Tom & 'Jerry'"#), "<a href="x">Tom & 'Jerry'</a>"); + assert_eq!(escape_dq(r#"Tom & 'Jerry'"#), "<a href="x">Tom & 'Jerry'</a>"); + assert_eq!(escape("plain ünïcode"), "plain ünïcode"); + assert_eq!(escape(""), ""); +} + +#[test] +fn bare_names_are_sorted_and_known() { + assert_eq!(BARE_NAMES.len(), 94); + assert!(BARE_NAMES.windows(2).all(|w| w[0] < w[1])); + assert!(BARE_NAMES.iter().all(|n| (2..=6).contains(&n.len()) && named(n).is_some())); +} + +#[test] +fn every_latin_1_and_greek_name_is_its_code_point() { + for (table, base) in [(&LATIN1[..], 0xA0), (&GREEK_UPPER[..], 0x391), (&GREEK_LOWER[..], 0x3B1)] { + for (i, name) in table.iter().enumerate().filter(|(_, n)| !n.is_empty()) { + assert_eq!(named(name), char::from_u32(base + i as u32), "{name}"); + } + } +} + +#[test] +fn named_references() { + assert_eq!(unescape("<b> & "x" 'y'"), " & \"x\" 'y'"); + assert_eq!(unescape("a b"), "a\u{a0}b"); + assert_eq!(unescape("© ® ™ … — –"), "© ® ™ … — –"); + assert_eq!(unescape("‘a’ “b” €5"), "‘a’ “b” €5"); + assert_eq!(unescape("café naïve Über ß ÿ"), "café naïve Über ß ÿ"); + assert_eq!(unescape("αβΩς → ≤ ≠"), "αβΩς → ≤ ≠"); + assert_eq!(unescape("‌¦ÐþΑο✗✓♦"), "\u{200c}¦Ðþ\u{391}ο✗✓♦"); + assert_eq!(unescape("⅓∴⇔◊"), "⅓∴⇔◊"); +} + +#[test] +fn names_are_case_sensitive() { + assert_eq!(unescape("Éé"), "Éé"); + assert_eq!(unescape("&EACUTE;"), "&EACUTE;"); + assert_eq!(unescape("&<"), "&<"); +} + +#[test] +fn numeric_references() { + assert_eq!(unescape("ééé"), "ééé"); + assert_eq!(unescape("😀"), "😀"); + assert_eq!(unescape("😀"), "😀"); + // Without the semicolon. + assert_eq!(unescape("A B."), "A B."); + // Windows-1252 for the C1 range. + assert_eq!(unescape("“hi” € ™"), "“hi” € ™"); +} + +#[test] +fn bad_numbers_become_the_replacement_character() { + assert_eq!(unescape("�"), "\u{fffd}"); + assert_eq!(unescape("�"), "\u{fffd}"); + assert_eq!(unescape("�"), "\u{fffd}"); + assert_eq!(unescape("�"), "\u{fffd}"); + assert_eq!(unescape("�"), "\u{fffd}"); +} + +#[test] +fn invalid_references_are_left_alone() { + for s in ["&", "&&", "& ", "&;", "&#;", "&#x;", "&#xZZ;", "&bogus;", "AT&T", "a & b", "x&y=z", "&#", "&#x", "&eacut", "ünï&", "&Alpha", "&hellip"] + { + assert_eq!(unescape(s), s, "{s}"); + assert_eq!(unescape_attr(s), s, "{s}"); + } +} + +#[test] +fn legacy_names_work_without_a_semicolon() { + assert_eq!(unescape("a < b > c"), "a < b > c"); + assert_eq!(unescape("x "), "x\u{a0}"); + assert_eq!(unescape("&"), "&"); + assert_eq!(unescape("© 2024 café!"), "© 2024 café!"); + // The longest name wins: `∉` is one reference; `¥x;` is `¥` and `x;`. + assert_eq!(unescape("∉ ¥x;"), "∉ ¥x;"); + // In text even inside a word, as browsers read it. + assert_eq!(unescape("&lify ?a=1&=2"), "&lify ?a=1&=2"); +} + +#[test] +fn in_an_attribute_a_bare_name_before_a_letter_digit_or_equals_is_text() { + assert_eq!(unescape_attr("?a=1&=2<=3©=4®1"), "?a=1&=2<=3©=4®1"); + assert_eq!(unescape_attr("&lify"), "&lify"); + assert_eq!(unescape_attr("?a=1&b=2"), "?a=1&b=2"); + assert_eq!(unescape_attr("a < b©"), "a < b©"); + // Numeric references need no `;` anywhere. + assert_eq!(unescape_attr("A=1"), "A=1"); +} + +#[test] +fn an_entity_body_decodes_whole_or_not_at_all() { + assert_eq!(decode_entity("amp"), Some('&')); + assert_eq!(decode_entity("#38"), Some('&')); + assert_eq!(decode_entity("#x26"), Some('&')); + assert_eq!(decode_entity("#150"), Some('–')); + for none in ["", "#", "#x", "#38x", "#3 8", "bogus", "amp;"] { + assert_eq!(decode_entity(none), None, "{none}"); + } + assert_eq!(reference("amp;rest", false), Some(('&', 4))); + assert_eq!(reference("#x41;", true), Some(('A', 5))); +} + +#[test] +fn a_long_run_of_ampersands_is_quick() { + let s = "&".repeat(200_000); + assert_eq!(unescape(&s), s); + let s = "&#".repeat(100_000); + assert_eq!(unescape(&s), s); + let s = "&aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".repeat(20_000); + assert_eq!(unescape(&s), s); +} + +proptest::proptest! { + #[test] + fn unescape_undoes_escape(s in proptest::prelude::any::()) { + proptest::prop_assert_eq!(unescape(&escape(&s)), s.clone()); + proptest::prop_assert_eq!(unescape_attr(&escape_dq(&s)), s); + } + + #[test] + fn unescape_never_panics(s in "[&#xX0-9a-zA-Z;= é]{0,60}") { + let _ = unescape(&s); + let _ = unescape_attr(&s); + } +} diff --git a/crates/html/src/lex.rs b/crates/html/src/lex.rs new file mode 100644 index 000000000..bf6688ffb --- /dev/null +++ b/crates/html/src/lex.rs @@ -0,0 +1,347 @@ +//! A tolerant HTML tokenizer: text, start tags and end tags. +//! +//! It follows the general syntax of the HTML Living Standard closely enough for documents, mail +//! and clipboard fragments, and reads anything: a `<` that starts no tag is text, a tag or +//! comment that never ends runs to the end of the input. Comments, doctypes and processing +//! instructions never leave it. + +use crate::entity::unescape_attr; + +/// What a [`Lexer`] caps. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Most attributes kept per tag; the rest are read and dropped. Default 64. + pub max_attrs: usize, + /// Longest tag name kept, in bytes; a longer one is no real element and its name is empty. + /// Default 64. + pub max_tag_name: usize, +} + +impl Limits { + pub const DEFAULT: Limits = Limits { max_attrs: 64, max_tag_name: 64 }; +} + +impl Default for Limits { + fn default() -> Limits { + Limits::DEFAULT + } +} + +/// How a [`Lexer`] reads. Element names are lower case. +#[derive(Clone, Copy, Debug, Default)] +pub struct Options<'o> { + pub limits: Limits, + /// Elements that never leave the lexer: the start tag, the content (raw text, not markup) + /// and the end tag are skipped. For `script`, `style`, `title` and the like, when the caller + /// has no use for them. A caller that wants a `style`'s text leaves it out of this list and + /// calls [`Lexer::raw_content`] on its start tag. + pub drop: &'o [&'o str], + /// Elements whose content is text, not markup, and is given: after the start tag comes one + /// [`Token::Text`] with everything up to the end tag. For `textarea`, `xmp`, `plaintext`. + pub raw_text: &'o [&'o str], +} + +/// A start tag. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Tag<'a> { + /// Lower case; empty for a name longer than [`Limits::max_tag_name`]. + pub name: String, + /// Names and values as written, in the order written. + pub attrs: Vec<(&'a str, &'a str)>, + /// The tag ends in `/>`. + pub self_close: bool, +} + +impl Tag<'_> { + /// An attribute's value with character references decoded ([`unescape_attr`]); the first + /// of a name wins, as in browsers. Names match in any letter case. + pub fn attr(&self, name: &str) -> Option { + self.raw_attr(name).map(unescape_attr) + } + + /// An attribute's value as written, character references and all. + pub fn raw_attr(&self, name: &str) -> Option<&str> { + self.attrs.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| *v) + } + + /// Whether the tag has the attribute, with or without a value. + pub fn has(&self, name: &str) -> bool { + self.attrs.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) + } + + /// Every attribute in the order written: the name as written, the value decoded. + pub fn attributes(&self) -> impl Iterator + '_ { + self.attrs.iter().map(|(n, v)| (*n, unescape_attr(v))) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Token<'a> { + /// Character data as written: references are not decoded ([`crate::unescape`]). + Text(&'a str), + Start(Tag<'a>), + /// An end tag's name, lower case (empty when longer than [`Limits::max_tag_name`]). + End(String), +} + +/// The tokenizer: an iterator of [`Token`]s over a string. +pub struct Lexer<'a, 'o> { + src: &'a str, + pos: usize, + opts: Options<'o>, + /// Set after the start tag of a raw-text element: its content comes next. + raw: Option, +} + +impl<'a> Lexer<'a, 'static> { + /// A lexer with [`Options::default`]: nothing dropped, no raw-text elements. + pub fn new(src: &'a str) -> Lexer<'a, 'static> { + Lexer::with(src, Options::default()) + } +} + +impl<'a, 'o> Lexer<'a, 'o> { + pub fn with(src: &'a str, opts: Options<'o>) -> Lexer<'a, 'o> { + Lexer { src, pos: 0, opts, raw: None } + } + + /// How far into the input the tokens given so far go, in bytes. + pub fn pos(&self) -> usize { + self.pos + } + + /// The raw content of element `name`, whose start tag was the last token: everything up to + /// its end tag (any letter case), or to the end of the input when it has none. The end tag + /// is consumed. For `style` and `script`, whose content is not markup. + pub fn raw_content(&mut self, name: &str) -> &'a str { + self.raw = None; + let b = self.bytes(); + let end = find_end_tag(b, self.pos, name).unwrap_or(b.len()); + let text = self.slice(self.pos, end); + self.pos = find_byte(b, end, b'>').map_or(b.len(), |i| i + 1); + text + } + + fn bytes(&self) -> &'a [u8] { + self.src.as_bytes() + } + + fn slice(&self, start: usize, end: usize) -> &'a str { + self.src.get(start..end).unwrap_or("") + } + + /// A tag name in lower case; empty when it is too long to be a real element. + fn tag_name(&self, raw: &str) -> String { + if raw.len() > self.opts.limits.max_tag_name { String::new() } else { raw.to_ascii_lowercase() } + } + + /// Whether the `<` at `i` starts a tag, a comment or a declaration (rather than being text). + fn markup_at(&self, i: usize) -> bool { + let b = self.bytes(); + match b.get(i + 1) { + Some(c) if c.is_ascii_alphabetic() => true, + Some(b'!' | b'?') => true, + Some(b'/') => matches!(b.get(i + 2), Some(c) if c.is_ascii_alphabetic() || *c == b'>'), + _ => false, + } + } + + /// The end of the text run that starts at `self.pos`: the next `<` that starts markup. + fn text_end(&self) -> usize { + let b = self.bytes(); + let mut i = self.pos + 1; + loop { + match find_byte(b, i, b'<') { + Some(j) if self.markup_at(j) => return j, + Some(j) => i = j + 1, + None => return b.len(), + } + } + } + + /// Skip a comment, doctype or processing instruction at `self.pos`. + fn skip_declaration(&mut self) { + let b = self.bytes(); + let end = if b.get(self.pos..self.pos + 4) == Some(b"").map_or(b.len(), |i| i + 3) + } + } else { + find_byte(b, self.pos, b'>').map_or(b.len(), |i| i + 1) + }; + self.pos = end.min(b.len()); + } + + /// Read the end tag at `self.pos` (``). + fn close_tag(&mut self) -> Option> { + let b = self.bytes(); + let start = self.pos + 2; + let mut i = start; + while let Some(c) = b.get(i) { + if c.is_ascii_whitespace() || *c == b'/' || *c == b'>' { + break; + } + i += 1; + } + let name = self.slice(start, i); + self.pos = find_byte(b, i, b'>').map_or(b.len(), |j| j + 1); + // `` is nothing at all. + (!name.is_empty()).then(|| Token::End(self.tag_name(name))) + } + + /// Read the start tag at `self.pos` (``). + fn open_tag(&mut self) -> Tag<'a> { + let b = self.bytes(); + let start = self.pos + 1; + let mut i = start; + while let Some(c) = b.get(i) { + if c.is_ascii_whitespace() || *c == b'/' || *c == b'>' { + break; + } + i += 1; + } + let name = self.tag_name(self.slice(start, i)); + let mut attrs = Vec::new(); + let mut self_close = false; + loop { + while matches!(b.get(i), Some(c) if c.is_ascii_whitespace() || *c == b'/') { + self_close = b.get(i) == Some(&b'/') && b.get(i + 1) == Some(&b'>'); + i += 1; + } + match b.get(i) { + None => break, + Some(b'>') => { + i += 1; + break; + } + Some(_) => {} + } + // An attribute name runs to white space, `/`, `>` or `=`; a leading `=` is part of it. + let name_start = i; + i += 1; + while let Some(c) = b.get(i) { + if c.is_ascii_whitespace() || matches!(*c, b'/' | b'>' | b'=') { + break; + } + i += 1; + } + let attr = self.slice(name_start, i); + let (value, next) = self.attr_value(i); + i = next; + if attrs.len() < self.opts.limits.max_attrs { + attrs.push((attr, value)); + } + } + self.pos = i.min(b.len()); + Tag { name, attrs, self_close } + } + + /// The value after an attribute name that ends at `i` (empty when it has none), and where + /// reading goes on. + fn attr_value(&self, i: usize) -> (&'a str, usize) { + let b = self.bytes(); + let mut j = i; + while matches!(b.get(j), Some(c) if c.is_ascii_whitespace()) { + j += 1; + } + if b.get(j) != Some(&b'=') { + return ("", j); + } + j += 1; + while matches!(b.get(j), Some(c) if c.is_ascii_whitespace()) { + j += 1; + } + match b.get(j) { + Some(&q) if q == b'"' || q == b'\'' => { + let end = find_byte(b, j + 1, q).unwrap_or(b.len()); + (self.slice(j + 1, end), (end + 1).min(b.len())) + } + _ => { + let mut end = j; + while let Some(c) = b.get(end) { + if c.is_ascii_whitespace() || *c == b'>' { + break; + } + end += 1; + } + (self.slice(j, end), end) + } + } + } +} + +impl<'a> Iterator for Lexer<'a, '_> { + type Item = Token<'a>; + + fn next(&mut self) -> Option> { + loop { + let b = self.bytes(); + if self.pos >= b.len() { + return None; + } + if let Some(name) = self.raw.take() { + let end = find_end_tag(b, self.pos, &name).unwrap_or(b.len()); + let text = self.slice(self.pos, end); + self.pos = end; + if !text.is_empty() { + return Some(Token::Text(text)); + } + continue; + } + if b.get(self.pos) != Some(&b'<') || !self.markup_at(self.pos) { + let start = self.pos; + self.pos = self.text_end(); + return Some(Token::Text(self.slice(start, self.pos))); + } + match b.get(self.pos + 1) { + Some(b'!' | b'?') => self.skip_declaration(), + Some(b'/') => { + if let Some(token) = self.close_tag() { + return Some(token); + } + } + _ => { + let tag = self.open_tag(); + if self.opts.drop.contains(&tag.name.as_str()) { + self.raw_content(&tag.name); + continue; + } + if self.opts.raw_text.contains(&tag.name.as_str()) { + self.raw = Some(tag.name.clone()); + } + return Some(Token::Start(tag)); + } + } + } + } +} + +fn find_byte(b: &[u8], from: usize, byte: u8) -> Option { + b.get(from..)?.iter().position(|c| *c == byte).map(|i| i + from) +} + +fn find_sub(b: &[u8], from: usize, needle: &[u8]) -> Option { + b.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|i| i + from) +} + +/// Where `` or the end), at or after `from`. +fn find_end_tag(b: &[u8], from: usize, name: &str) -> Option { + let mut i = from; + while let Some(lt) = find_byte(b, i, b'<') { + let after = lt + 2 + name.len(); + let named = b.get(lt + 1) == Some(&b'/') && b.get(lt + 2..after).is_some_and(|n| n.eq_ignore_ascii_case(name.as_bytes())); + if named && b.get(after).is_none_or(|c| c.is_ascii_whitespace() || matches!(*c, b'/' | b'>')) { + return Some(lt); + } + i = lt + 1; + } + None +} + +#[cfg(test)] +mod tests; diff --git a/crates/html/src/lex/tests.rs b/crates/html/src/lex/tests.rs new file mode 100644 index 000000000..4f19e5b7c --- /dev/null +++ b/crates/html/src/lex/tests.rs @@ -0,0 +1,177 @@ +use super::{Lexer, Limits, Options, Token}; + +/// As a mail reader sets it up. +const MAIL: Options<'static> = + Options { limits: Limits { max_attrs: 32, max_tag_name: 24 }, drop: &["script", "style", "title", "iframe"], raw_text: &["textarea", "xmp"] }; + +fn show<'a>(lexer: impl Iterator>) -> Vec { + lexer + .map(|t| match t { + Token::Text(t) => format!("T:{t}"), + Token::Start(tag) => { + let attrs: Vec = tag.attrs.iter().map(|(n, v)| format!("{n}={v}")).collect(); + if attrs.is_empty() { format!("<{}>", tag.name) } else { format!("<{} {}>", tag.name, attrs.join(" ")) } + } + Token::End(n) => format!(""), + }) + .collect() +} + +fn tokens(html: &str) -> Vec { + show(Lexer::with(html, MAIL)) +} + +#[test] +fn text_and_tags() { + assert_eq!(tokens("Hi there!"), ["T:Hi ", "", "T:there", "", "T:!"]); + assert_eq!(tokens(""), Vec::::new()); + assert_eq!(tokens("plain"), ["T:plain"]); + assert_eq!(tokens("

"), ["
", "
"]); +} + +#[test] +fn attributes_in_every_quoting_style() { + assert_eq!(tokens(r#""#), [r#""#]); + assert_eq!(tokens("t"), ["", "T:t"]); + assert_eq!(tokens(""), [""]); + assert_eq!(tokens("

"), ["

"]); + // A `>` inside a quoted value does not end the tag. + assert_eq!(tokens(r#"t"#), ["b>", "T:t", ""]); +} + +#[test] +fn attribute_values_are_decoded_on_demand() { + let mut t = Lexer::new(r#""#); + let Some(Token::Start(tag)) = t.next() else { panic!("no tag") }; + assert_eq!(tag.attr("href").as_deref(), Some("?a=1&b=2©=3")); + assert_eq!(tag.raw_attr("href"), Some("?a=1&b=2©=3")); + assert_eq!(tag.attr("missing"), None); + assert!(tag.has("checked") && !tag.has("check")); + assert_eq!(tag.attributes().map(|(n, _)| n).collect::>(), ["HREF", "href", "Checked"]); +} + +#[test] +fn a_tag_that_closes_itself_says_so() { + let closes = |html: &str| match Lexer::new(html).next() { + Some(Token::Start(tag)) => tag.self_close, + other => panic!("{other:?}"), + }; + for yes in ["
", "
", "", "", ""] { + assert!(closes(yes), "{yes}"); + } + // A `/` that ends an unquoted value, or stands anywhere but before the `>`, is not it. + for no in ["
", "", "
", "", "
d"), ["T:a < b and c > d"]); + assert_eq!(tokens("1<2<3"), ["T:1<2<3"]); + assert_eq!(tokens("<"), ["T:<"]); + assert_eq!(tokens("x<"), ["T:x<"]); + assert_eq!(tokens("<3 <- b"), ["T:a", "T:b"]); +} + +#[test] +fn comments_and_declarations_vanish() { + assert_eq!(tokens("ab"), ["T:a", "T:b"]); + assert_eq!(tokens("

x"), ["

", "T:x"]); + assert_eq!(tokens("x"), ["T:x"]); + assert_eq!(tokens("abc"), ["T:a", "T:b", "T:c"]); + assert_eq!(tokens("shown"), ["T:shown"]); + assert_eq!(tokens("shown"), ["T:shown"]); + // An unfinished comment swallows the rest. + assert_eq!(tokens("a") { + break; + } + } + continue; + } + if t.starts_with('>') { + flush_para(&mut para, &mut out, depth, refs); + parse_quote(lines, &mut i, depth, level, refs, budget, &mut out); + continue; + } + if para.is_empty() + && t.contains('|') + && let Some((aligns, width)) = lines.get(i + 1).and_then(|l| delimiter_row(l, MAX_COLS)) + { + let (head, head_width) = split_row(t, MAX_COLS); + if head_width == width { + let mut table = FTable::default(); + let cell = |s: &str, header: bool, a: Option| { + let p = Para { align: a, inlines: parse_inlines(s, &Fmt::default(), depth, refs), ..Default::default() }; + Cell { blocks: vec![FBlock::Para(p)], header, ..Default::default() } + }; + // The document keeps no more columns or rows than this, nor cells past its budget, + // so those aren't built; their lines are still the table's. + let cols = aligns.len(); + let fits = |rows: usize| rows < MAX_ROWS && budget.get() >= cols; + let mut cut = head_width > cols; + if fits(0) { + budget.set(budget.get() - cols); + table.rows.push(head.iter().zip(&aligns).map(|(s, a)| cell(s, true, *a)).collect()); + } else { + cut = true; + } + i += 2; + while let Some(l) = lines.get(i) { + if is_blank(l) || !l.contains('|') || interrupts(l) { + break; + } + if !table.rows.is_empty() && fits(table.rows.len()) { + budget.set(budget.get() - cols); + let (mut cells, _) = split_row(l, cols); + cells.resize(cols, String::new()); + table.rows.push(cells.iter().zip(&aligns).map(|(s, a)| cell(s, false, *a)).collect()); + } else { + cut = true; + } + i += 1; + } + if cut { + model::dropped(model::Dropped::TableCells); + } + if !table.rows.is_empty() { + out.push(FBlock::Table(table)); + } + continue; + } + } + if let Some(m) = list_marker(t) + && (para.is_empty() || ((!m.ordered || m.start == 1) && !is_blank(t.get(m.len..).unwrap_or("")))) + { + flush_para(&mut para, &mut out, depth, refs); + i = parse_list(lines, i, depth, level, &mut out, refs, budget); + continue; + } + para.push(line.clone()); + i += 1; + } + flush_para(&mut para, &mut out, depth, refs); + out +} + +fn parse_indented_code(lines: &[String], i: &mut usize, out: &mut Vec) { + let mut code: Vec<&str> = Vec::new(); + while let Some(line) = lines.get(*i) { + if is_blank(line) { + code.push(""); + } else if indent(line) >= 4 { + code.push(strip_indent(line, 4)); + } else { + break; + } + *i += 1; + } + while code.last().is_some_and(|line| line.is_empty()) { + code.pop(); + } + out.extend(code.into_iter().map(code_para)); +} + +fn parse_quote(lines: &[String], i: &mut usize, depth: usize, level: u8, refs: &Refs, budget: &std::cell::Cell, out: &mut Vec) { + let mut inner = Vec::new(); + while let Some(line) = lines.get(*i) { + let trimmed = line.trim_start_matches([' ', '\t']); + if indent(line) < 4 && trimmed.starts_with('>') { + let content = &trimmed[1..]; + inner.push(content.strip_prefix(' ').unwrap_or(content).to_string()); + } else if !is_blank(line) && !interrupts(line) && inner.last().is_some_and(|line| !is_blank(line)) { + inner.push(line.clone()); + } else { + break; + } + *i += 1; + } + if depth >= MAX_NEST { + let mut p = Para::new(Kind::Quote); + p.push_text(&inner.join(" "), &Fmt::default()); + out.push(FBlock::Para(p)); + return; + } + for mut block in parse_blocks(&inner, depth + 1, level, refs, budget) { + if let FBlock::Para(p) = &mut block + && p.kind == Kind::Normal + { + p.kind = Kind::Quote; + } + out.push(block); + } +} + +fn marker_space(ind: usize, marker_len: usize, after: &str) -> (usize, usize) { + let mut cols = 0; + let mut bytes = 0; + let mut rest = after; + while let Some(c) = rest.chars().next() { + match c { + ' ' => { + cols += 1; + bytes += 1; + rest = &rest[1..]; + if cols >= 4 { + break; + } + } + '\t' => { + let col = ind + marker_len + cols; + let n = 4 - col % 4; + cols += n; + bytes += 1; + break; + } + _ => break, + } + } + (cols, bytes) +} + +/// Parse a list starting at `lines[i]`; returns the index after it. +fn parse_list(lines: &[String], mut i: usize, depth: usize, level: u8, out: &mut Vec, refs: &Refs, budget: &std::cell::Cell) -> usize { + let Some(first) = lines.get(i).and_then(|l| list_marker(l.trim_start_matches([' ', '\t']))) else { return i + 1 }; + while let Some(line) = lines.get(i) { + let ind = indent(line); + if ind >= 4 { + break; + } + let t = line.trim_start_matches([' ', '\t']); + let Some(m) = list_marker(t) else { break }; + if m.ordered != first.ordered || m.ch != first.ch { + break; + } + let after = t.get(m.len..).unwrap_or(""); + let (spaces, skip) = if indent(after) > 4 { + (1, 1) + } else if after.starts_with([' ', '\t']) { + marker_space(ind, m.len, after) + } else { + (0, 0) + }; + let content_indent = if is_blank(after) { ind + m.len + 1 } else { ind + m.len + spaces }; + let item0 = if is_blank(after) { String::new() } else { after.get(skip.min(after.len())..).unwrap_or("").to_string() }; + let mut item: Vec = vec![item0]; + i += 1; + while let Some(l) = lines.get(i) { + if is_blank(l) { + item.push(String::new()); + } else if indent(l) >= content_indent { + item.push(strip_indent(l, content_indent).to_string()); + } else if item.last().is_some_and(|x| !is_blank(x)) && !interrupts(l) && list_marker(l.trim_start_matches([' ', '\t'])).is_none() { + // Lazy continuation of the item's paragraph. + item.push(l.trim_start_matches([' ', '\t']).to_string()); + } else { + break; + } + i += 1; + } + // Blank lines at the end of an item belong between items. + while item.len() > 1 && item.last().is_some_and(String::is_empty) { + item.pop(); + } + let li = ListInfo { ordered: first.ordered, level: level.min(8), start: first.start, ..Default::default() }; + let inner = if depth >= MAX_NEST { + let mut p = Para::default(); + p.push_text(&item.join(" "), &Fmt::default()); + vec![FBlock::Para(p)] + } else { + parse_blocks(&item, depth + 1, level.saturating_add(1).min(8), refs, budget) + }; + let mut placed = false; + if inner.is_empty() { + out.push(FBlock::Para(Para { list: Some(li), ..Default::default() })); + placed = true; + } + for b in inner { + match b { + FBlock::Para(mut p) if p.list.is_none() => { + if !placed { + p.list = Some(li); + placed = true; + out.push(FBlock::Para(p)); + } else if let Some(FBlock::Para(prev)) = out.last_mut() + && prev.list.is_some_and(|x| x.level == li.level) + { + // A continuation paragraph joins the item with a line break. + prev.push_text("\n", &Fmt::default()); + prev.inlines.extend(p.inlines); + } else { + p.list = Some(li); + out.push(FBlock::Para(p)); + } + } + FBlock::Para(p) => { + if !placed { + // The item starts with a nested list: give it an empty first line. + out.push(FBlock::Para(Para { list: Some(li), ..Default::default() })); + placed = true; + } + out.push(FBlock::Para(p)); + } + other => { + placed = true; + out.push(other); + } + } + } + // Blank lines between items. + while lines.get(i).is_some_and(|l| is_blank(l)) { + let next_is_item = lines.get(i + 1).is_some_and(|l| { + indent(l) < 4 && list_marker(l.trim_start_matches([' ', '\t'])).is_some_and(|m| m.ordered == first.ordered && m.ch == first.ch) + }); + if !next_is_item { + return i; + } + i += 1; + } + } + i +} diff --git a/crates/markdown/src/export.rs b/crates/markdown/src/export.rs new file mode 100644 index 000000000..82fd952e3 --- /dev/null +++ b/crates/markdown/src/export.rs @@ -0,0 +1,448 @@ +use super::blocks::thematic_break; +use super::inlines::{is_punct, within}; +use super::{Align, Arc, Cell, Document, FBlock, FTable, Fmt, Inline, Kind, model}; + +// --------------------------------------------------------------------------------------------- +// Export + +/// Escape text for Markdown (inline context). +pub fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 8); + for c in s.chars() { + match c { + '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '~' | '|' | '&' => { + out.push('\\'); + out.push(c); + } + '\u{000C}' | '\u{000E}' => {} + _ => out.push(c), + } + } + out +} + +/// Escape what would start a block at the beginning of a line. Leading spaces are kept, but at +/// most three (a tab counts as four): four would turn the line into an indented code block. +pub(super) fn escape_line_start(s: String) -> String { + let t = s.trim_start_matches([' ', '\t']); + let lead = s.get(..s.len() - t.len()).unwrap_or(""); + let cols: usize = lead.chars().map(|c| if c == '\t' { 4 } else { 1 }).sum(); + let indent = " ".repeat(cols.min(3)); + let needs = t.starts_with('#') + || t.starts_with('>') + || t.starts_with("- ") + || t.starts_with("+ ") + || t.starts_with("-\t") + || t.starts_with("+\t") + || t == "-" + || t == "+" + || t.starts_with('=') + || (t.starts_with('-') && t.trim_end_matches([' ', '\t']).chars().all(|c| c == '-')) + || thematic_break(t) + || { + let d = t.chars().take_while(char::is_ascii_digit).count(); + d > 0 + && t.get(d..).is_some_and(|r| { + r.starts_with(". ") || r.starts_with(") ") || r.starts_with(".\t") || r.starts_with(")\t") || r == "." || r == ")" + }) + }; + if !needs { + return if cols > 3 || lead.contains('\t') { format!("{indent}{t}") } else { s }; + } + if let Some(d) = t.find(['.', ')']).filter(|_| t.starts_with(|c: char| c.is_ascii_digit())) { + return format!("{indent}{}\\{}", &t[..d], &t[d..]); + } + format!("{indent}\\{t}") +} + +/// [`escape_line_start`] for every line of a body, including those after a manual line break. +fn escape_lines(body: String) -> String { + if !body.contains("\\\n") { + return escape_line_start(body); + } + body.split("\\\n").map(|l| escape_line_start(l.to_string())).collect::>().join("\\\n") +} + +fn code_span(t: &str) -> String { + let t = t.replace("\r\n", " ").replace(['\r', '\n'], " "); + let mut longest = 0; + let mut cur = 0; + for c in t.chars() { + if c == '`' { + cur += 1; + longest = longest.max(cur); + } else { + cur = 0; + } + } + let ticks = "`".repeat(longest + 1); + let pad = if t.starts_with('`') || t.ends_with('`') || (t.starts_with(' ') && t.ends_with(' ') && !t.trim().is_empty()) { " " } else { "" }; + format!("{ticks}{pad}{t}{pad}{ticks}") +} + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +enum Mark { + Bold, + Italic, + Strike, +} + +/// Inline spans → Markdown with properly nested markers. +pub(super) fn inlines_md(inlines: &[Inline]) -> String { + inlines_md_impl(inlines, false) +} + +fn inlines_md_table(inlines: &[Inline]) -> String { + inlines_md_impl(inlines, true) +} + +fn inlines_md_impl(inlines: &[Inline], in_table: bool) -> String { + // Split into (text, fmt) pieces with whitespace moved outside emphasis. + let mut pieces: Vec<(String, Fmt, Option)> = Vec::new(); + let eq = craft_flow::equations_as_text(inlines); + // Markdown keeps no ruby: its base text goes through the text path below. + let inlines = craft_flow::ruby_as_text(&eq); + for i in inlines.iter() { + match i { + Inline::Text(t, f) => { + let has_emph = f.bold || f.italic || f.strike; + if has_emph && !f.code { + let core = t.trim_matches([' ', '\t', '\n']); + let lead = &t[..t.len() - t.trim_start_matches([' ', '\t', '\n']).len()]; + let trail = &t[t.trim_end_matches([' ', '\t', '\n']).len()..]; + let plain = Fmt { bold: false, italic: false, strike: false, ..f.clone() }; + if !lead.is_empty() { + pieces.push((lead.to_string(), plain.clone(), None)); + } + if !core.is_empty() { + pieces.push((core.to_string(), f.clone(), None)); + } + if !trail.is_empty() && !core.is_empty() { + pieces.push((trail.to_string(), plain, None)); + } + } else { + pieces.push((t.clone(), f.clone(), None)); + } + } + Inline::Image(img) => { + let name = format!("image.{}", img.ext); + pieces.push((String::new(), Fmt::default(), Some(format!("![{}]({})", escape(&img.alt), name)))); + } + Inline::Anchor(a) => { + let safe: String = a.chars().filter(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.' | ':')).collect(); + pieces.push((String::new(), Fmt::default(), Some(format!("")))); + } + Inline::Figure(alt) | Inline::Chart(craft_flow::Chart { alt, .. }) => { + pieces.push((String::new(), Fmt::default(), Some(format!("![{}]()", escape(alt))))) + } + Inline::Equation { .. } => {} + // ASK and SET show nothing (see `model::shows_nothing`). + Inline::Field { instr, .. } if model::shows_nothing(instr) => {} + Inline::Field { result, fmt, .. } | Inline::Control { text: result, fmt, .. } => pieces.push((result.clone(), fmt.clone(), None)), + Inline::Note { .. } + | Inline::Comment { .. } + | Inline::CommentEnd(_) + | Inline::Shape { .. } + | Inline::Group { .. } + | Inline::FieldStart(_) + | Inline::FieldEnd + | Inline::AnchorEnd(_) => {} + // Read as its base text by `ruby_as_text` above. + Inline::Ruby { .. } => {} + } + } + let mut out = String::new(); + let mut stack: Vec = Vec::new(); + let mut link: Option> = None; + let close_all = |out: &mut String, stack: &mut Vec| { + while let Some(m) = stack.pop() { + out.push_str(marker(m)); + } + }; + for (text, f, raw) in pieces { + // Links are the outermost construct; a script or other non-web target is plain text. + let f_link = f.link.clone().filter(|l| craft_wordmodel::link::is_safe_href(l)); + if f_link != link || raw.is_some() { + close_all(&mut out, &mut stack); + if let Some(l) = &link { + out.push_str(&format!("]({})", link_target(l))); + } + link = None; + if let Some(r) = raw { + out.push_str(&r); + continue; + } + if let Some(l) = f_link { + out.push('['); + link = Some(l); + } + } + let want: Vec = + [(f.bold, Mark::Bold), (f.italic, Mark::Italic), (f.strike, Mark::Strike)].iter().filter(|x| x.0).map(|x| x.1).collect(); + let body = if f.code { + if in_table { code_span(&text.replace('|', "\\|")) } else { code_span(&text) } + } else { + escape(&text).replace('\n', "\\\n").replace('\t', " ") + }; + // Close until the stack is a prefix of what we want. + let mut close = String::new(); + while let Some(pos) = stack.iter().position(|m| !want.contains(m)) { + while stack.len() > pos { + if let Some(m) = stack.pop() { + close.push_str(marker(m)); + } + } + } + let mut open = String::new(); + for m in want { + if !stack.contains(&m) { + open.push_str(marker(m)); + stack.push(m); + } + } + // CommonMark only reads a closing run after punctuation as closing when whitespace or + // punctuation follows it, and an opening run before punctuation as opening when whitespace + // or punctuation precedes it. Where a letter sits there instead, or an opening run would + // directly follow a closing run (the two would merge into one run), an empty HTML comment (which readers drop) supplies + // the punctuation. + let prev = out.chars().next_back(); + let next = body.chars().next(); + let word = |c: Option| c.is_some_and(|c| !c.is_whitespace() && !is_punct(c)); + out.push_str(&close); + let close_needs = !close.is_empty() && prev.is_some_and(is_punct) && (!open.is_empty() || word(next)); + let open_needs = !open.is_empty() && next.is_some_and(is_punct) && (!close.is_empty() || word(prev)); + if close_needs || open_needs { + out.push_str(EMPTY_COMMENT); + } + out.push_str(&open); + out.push_str(&body); + } + close_all(&mut out, &mut stack); + if let Some(l) = &link { + out.push_str(&format!("]({})", link_target(l))); + } + out +} + +/// `l` as a Markdown link destination that reads back as exactly `l`, the target +/// `is_safe_href` passed. What Markdown would decode (a backslash escape, an entity reference) +/// or end the destination on (`<`, `>`) is backslash-escaped, never deleted: deleting `<` or `>` +/// could turn an accepted relative target into `javascript:…` or `//host`. Control characters +/// can't be written in a destination and are left out, as the safety check ignores them. +fn link_target(l: &str) -> String { + let l: String = l.chars().filter(|c| !c.is_ascii_control()).collect(); + let mut out = String::with_capacity(l.len() + 2); + for (i, c) in l.char_indices() { + let rest = l.get(i + c.len_utf8()..).unwrap_or(""); + match c { + '<' | '>' => out.push('\\'), + // A backslash is literal unless punctuation (or the closing `)`/`>`) follows it. + '\\' if rest.chars().next().is_none_or(|n| n.is_ascii_punctuation()) => out.push('\\'), + '&' if entity_like(rest) => out.push('\\'), + _ => {} + } + out.push(c); + } + if l.contains(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | '<' | '>')) { format!("<{out}>") } else { out } +} + +/// Whether `rest` (the text after a `&`) starts like an entity reference (`amp;`, `#106;`, +/// `#x6A;`), which a Markdown reader would decode. +fn entity_like(rest: &str) -> bool { + let Some(end) = within(rest, 34).find(';') else { return false }; + let body = rest.get(..end).unwrap_or(""); + let body = body.strip_prefix('#').map_or(body, |n| n.strip_prefix(['x', 'X']).unwrap_or(n)); + !body.is_empty() && body.chars().all(|c| c.is_ascii_alphanumeric()) +} + +/// Inline HTML that Markdown readers drop, used to separate emphasis markers from letters. +const EMPTY_COMMENT: &str = ""; + +fn marker(m: Mark) -> &'static str { + match m { + Mark::Bold => "**", + Mark::Italic => "*", + Mark::Strike => "~~", + } +} + +pub(super) fn table_md(t: &FTable, out: &mut Vec) { + let cols = t.cols().max(1); + let cell_md = |c: &Cell| -> String { + let mut parts = Vec::new(); + for b in &c.blocks { + match b { + FBlock::Para(p) => parts.push(inlines_md_table(&p.inlines).replace("\\\n", "
")), + FBlock::Table(inner) => parts.push(escape(&inner.rows.iter().flat_map(|r| r.iter().map(Cell::text)).collect::>().join(" "))), + } + } + parts.join("
").replace('\n', " ") + }; + let align_of = |c: &Cell| c.blocks.iter().find_map(|b| if let FBlock::Para(p) = b { Some(p.align) } else { None }).flatten(); + let row_md = |r: &Vec| -> Vec { + let mut v: Vec = Vec::new(); + for c in r { + v.push(if c.covered { String::new() } else { cell_md(c) }); + for _ in 1..c.colspan.clamp(1, 63) { + v.push(String::new()); + } + } + v.resize(cols, String::new()); + v + }; + let Some(head) = t.rows.first() else { return }; + out.push(format!("| {} |", row_md(head).join(" | "))); + let mut aligns: Vec> = Vec::new(); + for c in head { + aligns.push(align_of(c)); + for _ in 1..c.colspan.clamp(1, 63) { + aligns.push(None); + } + } + aligns.resize(cols, None); + let delim: Vec<&str> = aligns + .iter() + .map(|a| match a { + Some(Align::Center) => ":---:", + Some(Align::Right) => "---:", + Some(Align::Left) => ":---", + _ => "---", + }) + .collect(); + out.push(format!("| {} |", delim.join(" | "))); + for r in t.rows.iter().skip(1) { + out.push(format!("| {} |", row_md(r).join(" | "))); + } +} + +/// Markdown text of a document. +pub fn export(doc: &Document) -> String { + let flow = model::from_doc(doc); + let mut out: Vec = Vec::new(); + write_blocks(&flow.blocks, &mut out); + let mut s = out.join("\n"); + while s.ends_with("\n\n") { + s.pop(); + } + if !s.ends_with('\n') { + s.push('\n'); + } + s +} + +/// A heading's text on one line, with a trailing run of '#' escaped so a reader does not take it +/// for the optional closing sequence (`## Item #` reads back as "Item"). +fn heading_text(body: &str) -> String { + let mut s = body.replace("\\\n", " "); + let t = s.trim_end(); + let core = t.trim_end_matches('#'); + if core.len() != t.len() && (core.is_empty() || core.ends_with([' ', '\t'])) { + s.insert(core.len(), '\\'); + } + s +} + +pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) { + let mut i = 0; + let mut counters = [0u32; 9]; + let mut prev_list = false; + let mut prev_top_ordered = false; + while let Some(b) = blocks.get(i) { + match b { + FBlock::Table(t) => { + table_md(t, out); + out.push(String::new()); + prev_list = false; + } + FBlock::Para(p) if p.kind == Kind::Code && p.list.is_none() => { + let mut lines = Vec::new(); + while let Some(FBlock::Para(q)) = blocks.get(i) { + if q.kind != Kind::Code || q.list.is_some() { + break; + } + lines.push(q.text()); + i += 1; + } + let longest = lines.iter().map(|l| l.chars().filter(|c| *c == '`').count()).max().unwrap_or(0); + // The fence must be longer than the longest run in the content, or a content + // line is read back as the closing fence (the `.min(64)` cap did exactly that). + let fence = "`".repeat(3.max(longest + 1)); + out.push(fence.clone()); + out.extend(lines); + out.push(fence); + out.push(String::new()); + prev_list = false; + continue; + } + FBlock::Para(p) => { + let body = inlines_md(&p.inlines); + match p.list { + Some(li) => { + let lv = li.level.min(8) as usize; + if !prev_list || (lv == 0 && prev_top_ordered != li.ordered) { + counters = [0; 9]; + } + if lv == 0 { + prev_top_ordered = li.ordered; + } + let n = counters.get_mut(lv).map(|c| { + if *c == 0 { + *c = li.start.saturating_sub(1); + } + *c = c.saturating_add(1); + *c + }); + for d in counters.iter_mut().skip(lv + 1) { + *d = 0; + } + let marker = if li.ordered { format!("{}.", n.unwrap_or(1)) } else { "-".to_string() }; + let pad = " ".repeat(4 * lv); + let cont = " ".repeat(4 * lv + marker.len() + 1); + let body = if p.kind == Kind::Code { + code_span(&p.text()) + } else { + let body = escape_lines(body).replace("\\\n", &format!("\\\n{cont}")); + // The bullet marker can turn a short run of hyphens into a rule. + if thematic_break(&format!("{marker} {body}")) { format!("\\{body}") } else { body } + }; + let line = format!("{pad}{marker} {body}").trim_end().to_string(); + // A list inside a block quote stays in it: every line of the item, its + // continuation lines included, takes the quote marker. + let line = if p.kind == Kind::Quote { format!("> {}", line.replace('\n', "\n> ")) } else { line }; + out.push(line); + prev_list = true; + // A list going into or out of a block quote is a new block: without the + // blank line, an unquoted item would be read back into the quote. + let quoted = |k: Kind| k == Kind::Quote; + let next_is_list = matches!(blocks.get(i + 1), Some(FBlock::Para(q)) if q.list.is_some() && quoted(q.kind) == quoted(p.kind)); + if !next_is_list { + out.push(String::new()); + } + } + None => { + prev_list = false; + let line = match p.kind { + Kind::Heading(n) => format!("{} {}", "#".repeat(n.clamp(1, 6) as usize), heading_text(&body)), + Kind::Title => format!("# {}", heading_text(&body)), + Kind::Rule => "---".to_string(), + Kind::Quote => { + let b = escape_lines(body); + format!("> {}", b.replace("\\\n", "\\\n> ")) + } + _ => { + if body.is_empty() { + i += 1; + continue; + } + escape_lines(body) + } + }; + out.push(line); + out.push(String::new()); + } + } + } + } + i += 1; + } +} diff --git a/crates/markdown/src/inlines.rs b/crates/markdown/src/inlines.rs new file mode 100644 index 000000000..99c397246 --- /dev/null +++ b/crates/markdown/src/inlines.rs @@ -0,0 +1,595 @@ +use super::blocks::{MAX_NEST, Refs, ref_label}; +use super::{Arc, Fmt, HashMap, Inline, decode_entity, make_img, model}; + +// ---- inlines ---- + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Emph { + Em, + Strong, + Strike, +} + +enum Node { + Text(String, Fmt), + Inl(Inline), + Delim { ch: char, orig: usize, left: usize, open: bool, close: bool, opens: Vec, closes: Vec }, +} + +pub(super) fn is_punct(c: char) -> bool { + c.is_ascii_punctuation() || (!c.is_alphanumeric() && !c.is_whitespace() && !c.is_control()) +} + +/// Parse inline Markdown into formatted spans (on top of `base`). +pub fn parse_inlines(s: &str, base: &Fmt, depth: usize, refs: &Refs) -> Vec { + let nodes = tokenize(s, base, depth, refs); + emit(nodes) +} + +fn push_text(nodes: &mut Vec, s: &str, f: &Fmt) { + if s.is_empty() { + return; + } + if let Some(Node::Text(t, pf)) = nodes.last_mut() + && pf == f + { + t.push_str(s); + return; + } + nodes.push(Node::Text(s.to_string(), f.clone())); +} + +/// The closing `]` matching the `[` at byte `open` (escapes and code spans respected). Gives up +/// after looking `max` bytes ahead. Records in `known` every bracket pair it passes, and every `[` +/// still open at the end of the text: a scan from one of those would take the same path. +fn matching_bracket(s: &str, open: usize, max: usize, ticks: &Backticks, known: &mut HashMap>) -> Option { + let b = s.as_bytes(); + let mut opens: Vec = Vec::new(); + let mut i = open; + while let Some(&c) = b.get(i) { + if i - open > max { + return None; + } + match c { + b'\\' => i += 1, + b'`' => { + let n = b.get(i..).map(|r| r.iter().take_while(|x| **x == b'`').count()).unwrap_or(1); + if let Some(end) = ticks.find(i + n, n) { + i = end + n - 1; + } else { + i += n - 1; + } + } + b'[' => opens.push(i), + b']' => { + if let Some(o) = opens.pop() { + known.insert(o, Some(i)); + } + if opens.is_empty() { + return Some(i); + } + } + _ => {} + } + i += 1; + } + for o in opens { + known.insert(o, None); + } + None +} + +/// Where a text's runs of backticks start, by run length. Finding the run that closes a code span +/// is then a lookup: scanning the rest of the text for it, again for every run nothing closes +/// (each of a different length) and from every link bracket over them, was superlinear. +struct Backticks(HashMap>); + +impl Backticks { + fn new(s: &str) -> Self { + let b = s.as_bytes(); + let mut runs: HashMap> = HashMap::new(); + let mut i = 0; + while let Some(&c) = b.get(i) { + if c == b'`' { + let k = b.get(i..).map(|r| r.iter().take_while(|x| **x == b'`').count()).unwrap_or(1); + runs.entry(k).or_default().push(i); + i += k; + } else { + i += 1; + } + } + Self(runs) + } + + /// Byte index of a run of exactly `n` backticks at or after `from` (which is not inside a run). + fn find(&self, from: usize, n: usize) -> Option { + let starts = self.0.get(&n)?; + starts.get(starts.partition_point(|&p| p < from)).copied() + } +} + +struct LinkScan<'a> { + text: &'a str, + refs: &'a Refs, + ticks: &'a Backticks, + known: HashMap>, + budget: usize, +} + +impl<'a> LinkScan<'a> { + fn parse_at(&mut self, open: usize) -> Option<(&'a str, Arc, usize)> { + let bytes = self.text.as_bytes(); + let close = match self.known.get(&open).copied() { + Some(found) => found, + None if self.budget > 0 => { + let found = matching_bracket(self.text, open, self.budget, self.ticks, &mut self.known); + self.budget = self.budget.saturating_sub(found.unwrap_or(self.text.len()).saturating_sub(open)); + found + } + None => None, + }?; + if self.budget == 0 { + return None; + } + let label_text = self.text.get(open + 1..close)?; + if bytes.get(close + 1) == Some(&b'(') { + let destination = link_dest(self.text, close + 1); + self.budget = self.budget.saturating_sub(destination.as_ref().map_or(self.text.len(), |d| d.1).saturating_sub(close)); + let (destination, end) = destination?; + return Some((label_text, Arc::from(destination), end)); + } + // Full and shortcut reference links use definitions collected before inline parsing. + if self.refs.is_empty() { + return None; + } + let (label, end) = match self.text.get(close + 1..).and_then(|rest| rest.strip_prefix('[')) { + Some(rest) => { + let ahead = within(rest, self.budget); + let shut = ahead.find(']'); + self.budget = self.budget.saturating_sub(shut.map_or(ahead.len(), |n| n + 1)); + let shut = shut?; + let inner = rest.get(..shut)?; + let label = if inner.trim().is_empty() { label_text } else { inner }; + (label, close + 2 + shut + 1) + } + None => (label_text, close + 1), + }; + // A cached bracket pair still costs a pass over its label. Without charging it, + // nested undefined references normalize every suffix again. + if label.len() > self.budget { + self.budget = 0; + return None; + } + self.budget -= label.len(); + Some((label_text, self.refs.get(&ref_label(label))?.clone(), end)) + } +} + +/// Parse `(dest "title")` at byte `at` (which holds `(`): (destination, index after `)`). +fn link_dest(s: &str, at: usize) -> Option<(String, usize)> { + let rest = s.get(at..)?.strip_prefix('(')?; + let mut i = at + 1; + let ws = rest.len() - rest.trim_start().len(); + i += ws; + let r = s.get(i..)?; + let (dest, used) = if let Some(inner) = r.strip_prefix('<') { + // The first `>` not escaped by a backslash ends it; a line break first means no link. + let b = inner.as_bytes(); + let mut k = 0; + let end = loop { + match b.get(k)? { + b'\\' => k += 1, + b'>' => break k, + b'\n' => return None, + _ => {} + } + k += 1; + }; + (inner.get(..end)?.to_string(), end + 2) + } else { + let mut depth = 0i32; + let mut end = r.len(); + let mut chars = r.char_indices().peekable(); + while let Some((k, c)) = chars.next() { + match c { + '\\' => { + chars.next(); + } + '(' => depth += 1, + ')' if depth == 0 => { + end = k; + break; + } + ')' => depth -= 1, + c if c.is_whitespace() => { + end = k; + break; + } + _ => {} + } + } + (r.get(..end)?.to_string(), end) + }; + i += used; + let r = s.get(i..)?; + let ws = r.len() - r.trim_start().len(); + i += ws; + let r = s.get(i..)?; + if let Some(q) = r.chars().next().filter(|c| matches!(c, '"' | '\'' | '(')) { + let close = if q == '(' { ')' } else { q }; + let end = r.get(1..)?.find(close)?; + i += end + 2; + let r = s.get(i..)?; + i += r.len() - r.trim_start().len(); + } + if s.get(i..)?.starts_with(')') { Some((unescape(&dest), i + 1)) } else { None } +} + +fn unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\\' + && let Some(n) = chars.peek().copied().filter(char::is_ascii_punctuation) + { + out.push(n); + chars.next(); + } else { + out.push(c); + } + } + out +} + +/// The value of attribute `name` in an HTML tag's text. +fn tag_attr(tag: &str, name: &str) -> Option { + let lower = tag.to_ascii_lowercase(); + let mut from = 0; + while let Some(k) = lower.get(from..)?.find(name) { + let at = from + k; + let before = lower.get(..at)?.chars().next_back(); + let after = lower.get(at + name.len()..)?.trim_start(); + if before.is_some_and(char::is_whitespace) && after.starts_with('=') { + let v = after.get(1..)?.trim_start(); + let q = v.chars().next()?; + return Some(if q == '"' || q == '\'' { + let inner = v.get(1..)?; + let off = tag.len() - inner.len(); + let end = inner.find(q)?; + tag.get(off..off + end)?.to_string() + } else { + let end = v.find(|c: char| c.is_whitespace() || c == '>').unwrap_or(v.len()); + let off = tag.len() - v.len(); + tag.get(off..off + end)?.to_string() + }); + } + from = at + name.len(); + } + None +} + +fn tokenize(s: &str, base: &Fmt, depth: usize, refs: &Refs) -> Vec { + let mut nodes: Vec = Vec::new(); + // Bytes the link/image scans and reference-label lookups may read in total. Unmatched + // brackets and nested undefined references would otherwise rescan the rest of the text, + // which is quadratic on hostile input. Once the budget is gone, further brackets are plain + // text. A scan pays for what it reads; earlier bracket matches are looked up in `known`. + let ticks = Backticks::new(s); + let mut links = LinkScan { text: s, refs, ticks: &ticks, known: HashMap::new(), budget: s.len().saturating_mul(8).saturating_add(8192) }; + let b = s.as_bytes(); + let mut i = 0usize; + let mut text_start = 0usize; + macro_rules! flush { + () => { + if text_start < i { + push_text(&mut nodes, s.get(text_start..i).unwrap_or(""), base); + } + }; + } + while let Some(&c) = b.get(i) { + match c { + b'\\' => { + flush!(); + match s.get(i + 1..).and_then(|r| r.chars().next()) { + Some(n) if n.is_ascii_punctuation() => { + push_text(&mut nodes, &n.to_string(), base); + i += 2; + } + _ => { + push_text(&mut nodes, "\\", base); + i += 1; + } + } + text_start = i; + } + b'`' => { + flush!(); + let (code, fmt, end) = code_span(s, i, base, &ticks); + push_text(&mut nodes, &code, &fmt); + i = end; + text_start = i; + } + b'*' | b'_' | b'~' => { + flush!(); + let ch = c as char; + let n = b.get(i..).map(|r| r.iter().take_while(|x| **x == c).count()).unwrap_or(1); + let before = s.get(..i).and_then(|r| r.chars().next_back()).unwrap_or(' '); + let after = s.get(i + n..).and_then(|r| r.chars().next()).unwrap_or(' '); + let lf = !after.is_whitespace() && (!is_punct(after) || before.is_whitespace() || is_punct(before)); + let rf = !before.is_whitespace() && (!is_punct(before) || after.is_whitespace() || is_punct(after)); + let (open, close) = match ch { + '_' => (lf && (!rf || is_punct(before)), rf && (!lf || is_punct(after))), + '~' if n != 2 => (false, false), + _ => (lf, rf), + }; + if open || close { + nodes.push(Node::Delim { ch, orig: n, left: n, open, close, opens: Vec::new(), closes: Vec::new() }); + } else { + push_text(&mut nodes, s.get(i..i + n).unwrap_or(""), base); + } + i += n; + text_start = i; + } + b'!' | b'[' if depth < MAX_NEST => { + let img = c == b'!'; + let open = if img { i + 1 } else { i }; + let parsed = if b.get(open) == Some(&b'[') { links.parse_at(open) } else { None }; + match parsed { + Some((inner, dest, end)) if img => { + flush!(); + let alt: String = parse_inlines(inner, &Fmt::default(), depth + 1, refs) + .iter() + .filter_map(|x| if let Inline::Text(t, _) = x { Some(t.as_str()) } else { None }) + .collect(); + match model::data_uri(&dest).and_then(|d| make_img(d, None, None, &alt)) { + Some(im) => nodes.push(Node::Inl(Inline::Image(im))), + None => push_text(&mut nodes, &alt, base), + } + i = end; + text_start = i; + } + Some((inner, dest, end)) if base.link.is_none() => { + flush!(); + let mut f = base.clone(); + // A destination too long to keep leaves its text unlinked. + f.link = (dest.len() <= model::MAX_LINK).then_some(dest); + if f.link.is_none() { + model::dropped(model::Dropped::Link); + } + for x in parse_inlines(inner, &f, depth + 1, refs) { + nodes.push(Node::Inl(x)); + } + i = end; + text_start = i; + } + _ => i += 1, + } + } + b'<' => { + if let Some((end, parsed)) = angle_inlines(s, i, base) { + flush!(); + nodes.extend(parsed); + i = end; + text_start = end; + } else { + i += 1; + } + } + b'&' => { + let rest = s.get(i..).unwrap_or(""); + match within(rest, 33).find(';').and_then(|k| decode_entity(rest.get(1..k)?).map(|ch| (ch, k))) { + Some((ch, k)) => { + flush!(); + push_text(&mut nodes, &ch, base); + i += k + 1; + text_start = i; + } + None => i += 1, + } + } + _ => i += 1, + } + } + flush!(); + nodes +} + +fn angle_inlines(s: &str, start: usize, base: &Fmt) -> Option<(usize, Vec)> { + if let Some(pos) = s.get(start..).and_then(|rest| rest.strip_prefix("")) { + return Some((start + 4 + pos + 3, Vec::new())); + } + let rest = s.get(start + 1..).unwrap_or(""); + let tag_end = within(rest, MAX_TAG).find('>')?; + let inner = rest.get(..tag_end)?; + let lower = inner.to_ascii_lowercase(); + let end = start + inner.len() + 2; + let mut nodes = Vec::new(); + if !inner.is_empty() + && !inner.contains([' ', '<', '\n']) + && (inner.contains("://") || lower.starts_with("mailto:") || (inner.contains('@') && !inner.contains('/'))) + { + let mut fmt = base.clone(); + fmt.link = Some(if inner.contains('@') && !inner.contains(':') { format!("mailto:{inner}").into() } else { inner.into() }); + push_text(&mut nodes, inner, &fmt); + Some((end, nodes)) + } else if matches!(lower.trim_end_matches('/').trim(), "br") { + push_text(&mut nodes, "\n", base); + Some((end, nodes)) + } else if lower.starts_with("a ") && rest.get(inner.len() + 1..).is_some_and(|tail| tail.to_ascii_lowercase().starts_with("")) { + if let Some(name) = tag_attr(inner, "id").or_else(|| tag_attr(inner, "name")) { + nodes.push(Node::Inl(Inline::Anchor(name))); + } + Some((end + 4, nodes)) + } else { + None + } +} + +fn code_span(s: &str, start: usize, base: &Fmt, ticks: &Backticks) -> (String, Fmt, usize) { + let bytes = s.as_bytes(); + let count = bytes.get(start..).map(|tail| tail.iter().take_while(|byte| **byte == b'`').count()).unwrap_or(1); + let Some(end) = ticks.find(start + count, count) else { + return (s.get(start..start + count).unwrap_or("").to_string(), base.clone(), start + count); + }; + let mut code = s.get(start + count..end).unwrap_or("").replace('\n', " "); + if code.len() >= 2 && code.starts_with(' ') && code.ends_with(' ') && !code.trim().is_empty() { + code = code[1..code.len() - 1].to_string(); + } + let mut fmt = base.clone(); + fmt.code = true; + (code, fmt, end + count) +} + +/// Longest `<...>` tag or autolink taken as inline HTML. +const MAX_TAG: usize = 4096; + +/// The first `n` bytes of `s` (fewer if that would cut a character), so a search for a closing +/// character stays short however long the text is. +pub(super) fn within(s: &str, n: usize) -> &str { + let mut end = n.min(s.len()); + while !s.is_char_boundary(end) { + end -= 1; + } + s.get(..end).unwrap_or("") +} + +fn emph_index(ch: char) -> usize { + match ch { + '*' => 0, + '_' => 1, + _ => 2, + } +} + +/// The CommonMark "process emphasis" pass over the delimiter runs, then flattening into spans. +fn emit(mut nodes: Vec) -> Vec { + // Delimiter stack of node indexes; bottoms per (char, closer length % 3, closer can open). + let mut stack: Vec = Vec::new(); + let mut bottom = [[[None::; 2]; 3]; 3]; + for c in 0..nodes.len() { + let (ch, corig, copen, cclose) = match nodes.get(c) { + Some(Node::Delim { ch, orig, open, close, .. }) => (*ch, *orig, *open, *close), + _ => continue, + }; + if cclose { + loop { + let cleft = match nodes.get(c) { + Some(Node::Delim { left, .. }) => *left, + _ => 0, + }; + if cleft == 0 { + break; + } + let bot = bottom.get(emph_index(ch)).and_then(|x| x.get(corig % 3)).and_then(|x| x.get(copen as usize)).copied().flatten(); + let mut found = None; + for (k, &o) in stack.iter().enumerate().rev() { + if bot.is_some_and(|b| o <= b) { + break; + } + if let Some(Node::Delim { ch: och, orig: oorig, left: oleft, open: oopen, close: oclose, .. }) = nodes.get(o) { + if *och != ch || !*oopen || *oleft == 0 { + continue; + } + if ch == '~' && (*oleft < 2 || cleft < 2) { + continue; + } + let odd = (*oclose || copen) && (oorig + corig) % 3 == 0 && !(oorig % 3 == 0 && corig % 3 == 0); + if odd { + continue; + } + found = Some((k, o, *oleft)); + break; + } + } + let Some((k, o, oleft)) = found else { + if let Some(slot) = bottom.get_mut(emph_index(ch)).and_then(|x| x.get_mut(corig % 3)).and_then(|x| x.get_mut(copen as usize)) { + *slot = Some(c.saturating_sub(1)); + } + break; + }; + let (used, kind) = if ch == '~' { + (2, Emph::Strike) + } else if oleft >= 2 && cleft >= 2 { + (2, Emph::Strong) + } else { + (1, Emph::Em) + }; + if let Some(Node::Delim { left, opens, .. }) = nodes.get_mut(o) { + *left -= used; + opens.push(kind); + } + if let Some(Node::Delim { left, closes, .. }) = nodes.get_mut(c) { + *left -= used; + closes.push(kind); + } + // Delimiters between opener and closer can no longer match. + stack.truncate(k + 1); + if oleft - used == 0 { + stack.truncate(k); + } + } + } + let left = match nodes.get(c) { + Some(Node::Delim { left, .. }) => *left, + _ => 0, + }; + if copen && left > 0 { + stack.push(c); + } + } + // Flatten. + let mut out: Vec = Vec::new(); + let (mut em, mut strong, mut strike) = (0usize, 0usize, 0usize); + let push = |out: &mut Vec, t: &str, f: &Fmt, em: usize, strong: usize, strike: usize| { + if t.is_empty() { + return; + } + let mut f = f.clone(); + f.italic |= em > 0; + f.bold |= strong > 0; + f.strike |= strike > 0; + if let Some(Inline::Text(pt, pf)) = out.last_mut() + && *pf == f + { + pt.push_str(t); + return; + } + out.push(Inline::Text(t.to_string(), f)); + }; + // Delimiter literals take the formatting (link, …) of the text before them: the last text + // node, tracked here rather than searched for backwards from every delimiter (quadratic on + // a paragraph of delimiters). + let mut last_text: Option<&Fmt> = None; + for n in &nodes { + match n { + Node::Text(t, f) => { + push(&mut out, t, f, em, strong, strike); + last_text = Some(f); + } + Node::Inl(Inline::Text(t, f)) => push(&mut out, t, f, em, strong, strike), + Node::Inl(other) => out.push(other.clone()), + Node::Delim { ch, left, opens, closes, .. } => { + for e in closes { + match e { + Emph::Em => em = em.saturating_sub(1), + Emph::Strong => strong = strong.saturating_sub(1), + Emph::Strike => strike = strike.saturating_sub(1), + } + } + if *left > 0 { + let lit: String = std::iter::repeat_n(*ch, *left).collect(); + let f = last_text.map_or_else(Fmt::default, |f| Fmt { bold: false, italic: false, strike: false, ..f.clone() }); + push(&mut out, &lit, &f, em, strong, strike); + } + for e in opens { + match e { + Emph::Em => em += 1, + Emph::Strong => strong += 1, + Emph::Strike => strike += 1, + } + } + } + } + } + out +} diff --git a/crates/markdown/src/lib.rs b/crates/markdown/src/lib.rs new file mode 100644 index 000000000..e7fc9abfc --- /dev/null +++ b/crates/markdown/src/lib.rs @@ -0,0 +1,48 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +// The code came from an app whose lints allow this. +#![allow(clippy::type_complexity)] +//! Markdown: a CommonMark subset plus GitHub tables and strikethrough. +//! +//! Import: ATX and setext headings, paragraphs with soft/hard breaks, block quotes (→ Quote +//! style), fenced and indented code (→ one Code paragraph per line), thematic breaks (→ a +//! bottom-border paragraph), bullet and ordered lists (nested by indentation), GFM pipe tables, +//! and inlines: emphasis/strong (the CommonMark delimiter algorithm), `~~strike~~`, code spans, +//! inline links, autolinks, images (`data:` URIs become pictures, others their alt text), +//! backslash escapes, entities, HTML comments (``), `
` and `` anchors. +//! +//! Export writes the same constructs; pictures become `![alt](media-name)` placeholders. + +#[cfg(doctest)] +#[doc = include_str!("../README.md")] +struct ReadmeExamples; + +use std::collections::HashMap; +use std::sync::Arc; + +use craft_wordmodel::table::{MAX_COLS, MAX_ROWS}; +use craft_wordmodel::{Align, Document}; + +use craft_flow::{self as model, Cell, FBlock, FTable, Fmt, Inline, Kind, ListInfo, Para, make_img}; + +mod blocks; +mod export; +mod inlines; + +pub use craft_flow::MAX_TABLE_CELLS; + +/// The text of an entity body (`amp`, `#38`, `#x26`). +fn decode_entity(body: &str) -> Option { + craft_html::decode_entity(body).map(String::from) +} + +pub use blocks::{Refs, import, import_on, parse}; +pub use export::escape; +pub use export::export; +#[cfg(test)] +use export::{escape_line_start, inlines_md, table_md, write_blocks}; +pub use inlines::parse_inlines; + +#[cfg(test)] +use blocks::split_row; +#[cfg(test)] +mod tests; diff --git a/crates/markdown/src/tests.rs b/crates/markdown/src/tests.rs new file mode 100644 index 000000000..96ad1dc3a --- /dev/null +++ b/crates/markdown/src/tests.rs @@ -0,0 +1,795 @@ +use super::*; + +fn inl(s: &str) -> Vec { + parse_inlines(s, &Fmt::default(), 0, &Refs::new()) +} + +fn spans(s: &str) -> Vec<(String, bool, bool)> { + inl(s).into_iter().filter_map(|i| if let Inline::Text(t, f) = i { Some((t, f.bold, f.italic)) } else { None }).collect() +} + +#[test] +fn emphasis() { + assert_eq!(spans("a *b* c"), vec![("a ".into(), false, false), ("b".into(), false, true), (" c".into(), false, false)]); + assert_eq!(spans("**b**"), vec![("b".into(), true, false)]); + assert_eq!(spans("***x***"), vec![("x".into(), true, true)]); + assert_eq!(spans("*a **b** c*"), vec![("a ".into(), false, true), ("b".into(), true, true), (" c".into(), false, true)]); + assert_eq!(spans("snake_case_name"), vec![("snake_case_name".into(), false, false)]); + assert_eq!(spans("2 * 3 * 4"), vec![("2 * 3 * 4".into(), false, false)]); + assert_eq!(spans("**unclosed"), vec![("**unclosed".into(), false, false)]); + let s = inl("~~gone~~"); + assert!(matches!(&s[0], Inline::Text(t, f) if t == "gone" && f.strike)); +} + +#[test] +fn links_code_escapes() { + let s = inl("see [the *site*](http://x.org \"T\") and `a*b*` \\*lit\\* & "); + let link: Vec<_> = s + .iter() + .filter_map(|i| if let Inline::Text(t, f) = i { f.link.as_ref().map(|l| (t.clone(), l.to_string(), f.italic)) } else { None }) + .collect(); + assert_eq!(link[0], ("the ".into(), "http://x.org".into(), false)); + assert_eq!(link[1], ("site".into(), "http://x.org".into(), true)); + assert!(link.iter().any(|l| l.1 == "https://y.com")); + assert!(s.iter().any(|i| matches!(i, Inline::Text(t, f) if t == "a*b*" && f.code))); + let text: String = s.iter().filter_map(|i| if let Inline::Text(t, _) = i { Some(t.as_str()) } else { None }).collect(); + assert!(text.contains("*lit* & "), "{text}"); +} + +/// Reference links: `[text][label]`, `[text][]` and `[text]` take their destination from a +/// definition line, and the definition itself leaves the document. Before, none of the three +/// was a link and the definition stayed as a paragraph of its own (#3238). +#[test] +fn reference_links_resolve_and_their_definitions_leave_the_body() { + let links = |md: &str| -> Vec<(String, String)> { + match &*parse(md).blocks { + [FBlock::Para(p), ..] => p + .inlines + .iter() + .filter_map(|x| match x { + Inline::Text(t, f) => f.link.as_deref().map(|l| (t.clone(), l.to_string())), + _ => None, + }) + .collect(), + _ => vec![], + } + }; + let def = "\n\n[ref1]: https://example.com/ref\n"; + let to_ref = |text: &str| vec![(text.to_string(), "https://example.com/ref".to_string())]; + + assert_eq!(links(&format!("[click here][ref1]{def}")), to_ref("click here"), "full"); + assert_eq!(links(&format!("[ref1][]{def}")), to_ref("ref1"), "collapsed"); + assert_eq!(links(&format!("[ref1]{def}")), to_ref("ref1"), "shortcut"); + // Labels match case-folded with runs of white space collapsed (CommonMark §4.7). + assert_eq!(links(&format!("[click here][ REF1 ]{def}")), to_ref("click here"), "folded label"); + // An undefined label is not a link: an ordinary bracketed phrase stays text. + assert_eq!(links(&format!("[nope]{def}")), vec![], "undefined"); + // Inline links are unaffected. + assert_eq!(links("[x](https://inline.example)"), vec![("x".into(), "https://inline.example".into())], "inline"); + + // The definition is not a paragraph, and its text is nowhere in the body. + let doc = import(&format!("Reference link: [click here][ref1]{def}")); + let text = doc.plain_text(craft_wordmodel::StoryRef::Body); + assert_eq!(text, "Reference link: click here", "{text:?}"); + + // A definition inside a fence is code, not a definition. + let fenced = "```\n[ref1]: https://example.com/ref\n```\n\n[ref1]\n"; + let body = import(fenced).plain_text(craft_wordmodel::StoryRef::Body); + assert!(body.contains("[ref1]: https://example.com/ref"), "the fenced definition is still code: {body:?}"); + assert_eq!(links(fenced), vec![], "a fenced definition defines nothing"); +} + +/// Cached bracket pairs must not make undefined shortcut references normalize every nested +/// suffix again. One unrelated definition keeps this on the reference-lookup path. +#[test] +fn nested_undefined_reference_labels_have_bounded_work() { + let literal = format!("prefix {}x{} suffix", "[".repeat(128_000), "]".repeat(128_000)); + let src = format!("{literal}\n\n[other]: https://example.com/other\n"); + let started = std::time::Instant::now(); + let doc = import(&src); + let elapsed = started.elapsed(); + assert_eq!(doc.plain_text(craft_wordmodel::StoryRef::Body), literal); + assert!(elapsed < std::time::Duration::from_secs(10), "nested undefined references took {elapsed:?}"); +} + +#[test] +fn reference_lookup_keeps_long_unicode_labels_and_nested_text() { + // The work guard is not a label-length cap. Collapsed/full/shortcut references keep their + // case and whitespace matching, even when lowercasing changes the number of UTF-8 bytes. + let label = format!("{}İ END", "Écho ".repeat(1500)); + let key = label.to_lowercase(); + let src = format!("[{label}] [{label}][] [full][{label}]\n\n[{key}]: https://example.com/long\n"); + let flow = parse(&src); + let FBlock::Para(p) = &flow.blocks[0] else { panic!("paragraph") }; + let links: Vec<_> = p + .inlines + .iter() + .filter_map(|x| match x { + Inline::Text(t, f) if f.link.is_some() => Some((t.as_str(), f.link.as_deref())), + _ => None, + }) + .collect(); + assert_eq!( + links, + vec![ + (label.as_str(), Some("https://example.com/long")), + (label.as_str(), Some("https://example.com/long")), + ("full", Some("https://example.com/long")) + ] + ); + + let refs = Refs::from([("known".into(), Arc::from("https://example.com/known"))]); + let out = parse_inlines("[outer [known]] tail [inline](https://example.com/inline)", &Fmt::default(), 0, &refs); + let text: String = out.iter().filter_map(|x| if let Inline::Text(t, _) = x { Some(t.as_str()) } else { None }).collect(); + assert_eq!(text, "[outer known] tail inline"); + assert!(out.iter().any(|x| matches!(x, Inline::Text(t, f) if t == "known" && f.link.as_deref() == Some("https://example.com/known")))); + assert!(out.iter().any(|x| matches!(x, Inline::Text(t, f) if t == "inline" && f.link.as_deref() == Some("https://example.com/inline")))); +} + +/// A definition has to start a block (CommonMark §4.7), and a fence opens and closes by the +/// same rules the block parser uses. Reading a line without that context deleted text: a +/// definition-shaped line inside a paragraph, and every such line inside a code block whose +/// fence this pass thought had closed. +#[test] +fn a_definition_shaped_line_that_is_not_a_definition_stays_in_the_document() { + let body = |md: &str| import(md).plain_text(craft_wordmodel::StoryRef::Body); + + // A definition cannot interrupt a paragraph: this is the author's text, lines and all. + let para = "Status update\n[Warning]: unstable\nmore text\n"; + assert_eq!(body(para), "Status update [Warning]: unstable more text", "{:?}", body(para)); + + // `` ```rust `` holds an info string, so it does not close a fence: the definition-shaped + // line after it is still code. + let code = "```\n```rust\n[foo]: /bar\n```\n\nSee [foo].\n"; + assert!(body(code).contains("[foo]: /bar"), "{:?}", body(code)); + assert!(body(code).ends_with("See [foo]."), "nothing defines foo: {:?}", body(code)); + + // Four spaces of indentation is code, not a fence, so the definition that follows is + // taken and the reference resolves. + let indented = " ```\n\n[x]: /y\n\nSee [x].\n"; + let doc = import(indented); + let text = doc.plain_text(craft_wordmodel::StoryRef::Body); + assert!(text.contains("```") && text.ends_with("See x."), "{text:?}"); + + // A definition still gives up its line after a blank line, at the start of the document, + // after a heading, and after another definition. + let starts = "[a]: /a\n[b]: /b\n\n# Head\n[c]: /c\n\nSee [a], [b], [c].\n"; + assert_eq!(body(starts), "Head\nSee a, b, c.", "{:?}", body(starts)); + + // A footnote definition is not a link definition: it stays in the body. + let footnote = "x[^1]\n\n[^1]: Note\n"; + assert!(body(footnote).contains("[^1]: Note"), "{:?}", body(footnote)); +} + +#[test] +fn blocks() { + let f = parse( + "# Title\n\nPara one\ncontinues.\n\n> quoted\n\n- a\n- b\n 1. nested\n\n```\ncode *x*\n```\n\n---\n\n| A | B |\n|---|:-:|\n| 1 | 2 |\n", + ); + let kinds: Vec = f + .blocks + .iter() + .map(|b| match b { + FBlock::Para(p) => format!("{:?}{:?}:{}", p.kind, p.list.map(|l| (l.ordered, l.level)), p.text()), + FBlock::Table(t) => format!("table{}", t.rows.len()), + }) + .collect(); + assert_eq!( + kinds, + vec![ + "Heading(1)None:Title", + "NormalNone:Para one continues.", + "QuoteNone:quoted", + "NormalSome((false, 0)):a", + "NormalSome((false, 0)):b", + "NormalSome((true, 1)):nested", + "CodeNone:code *x*", + "RuleNone:", + "table2", + ] + ); +} + +#[test] +fn export_escapes_round_trip() { + let mut p = Para::default(); + p.push_text("1. not a list *really*", &Fmt::default()); + let md = escape_line_start(inlines_md(&p.inlines)); + let back = parse(&md); + let FBlock::Para(q) = &back.blocks[0] else { panic!() }; + assert_eq!(q.text(), "1. not a list *really*"); + assert!(q.list.is_none()); +} + +#[test] +fn export_emphasis_next_to_punctuation_round_trips() { + let marks: [(&str, fn(&mut Fmt)); 3] = [("bold", |f| f.bold = true), ("italic", |f| f.italic = true), ("strike", |f| f.strike = true)]; + let cases: [&[(&str, bool)]; 4] = [ + &[("注意:", true), ("请阅读", false)], + &[("a.", true), ("b", false)], + &[("a", false), ("!", true), ("b", false)], + &[("a", false), ("(x)", true), ("b", false)], + ]; + for (name, set) in marks { + for runs in cases { + let mut p = Para::default(); + for (t, on) in runs { + let mut f = Fmt::default(); + if *on { + set(&mut f); + } + p.push_text(t, &f); + } + let md = inlines_md(&p.inlines); + let back = parse(&md); + let FBlock::Para(q) = &back.blocks[0] else { panic!() }; + let want: String = runs.iter().map(|r| r.0).collect(); + assert_eq!(q.text(), want, "{name} exported as {md:?}"); + let got: Vec<(String, bool)> = q + .inlines + .iter() + .filter_map(|i| if let Inline::Text(t, f) = i { Some((t.clone(), f.bold || f.italic || f.strike)) } else { None }) + .collect(); + let expect: Vec<(String, bool)> = runs.iter().map(|(t, on)| (t.to_string(), *on)).collect(); + assert_eq!(got, expect, "{name} exported as {md:?}"); + } + } +} + +#[test] +fn export_adjacent_emphasis_next_to_punctuation_round_trips() { + let b = Fmt { bold: true, ..Fmt::default() }; + let i = Fmt { italic: true, ..Fmt::default() }; + let s = Fmt { strike: true, ..Fmt::default() }; + let cases: [&[(&str, &Fmt)]; 6] = [ + &[("ab", &b), ("!c", &i)], + &[("ab", &i), ("!c", &b)], + &[("ab", &b), ("!c", &s)], + &[("ab", &s), ("(c)", &b)], + &[("a.", &b), ("b", &i)], + &[("a.", &b), ("!b", &i)], + ]; + for runs in cases { + let mut p = Para::default(); + for (t, f) in runs { + p.push_text(t, f); + } + let md = inlines_md(&p.inlines); + let back = parse(&md); + let FBlock::Para(q) = &back.blocks[0] else { panic!() }; + let got: Vec<(String, bool, bool, bool)> = + q.inlines.iter().filter_map(|x| if let Inline::Text(t, f) = x { Some((t.clone(), f.bold, f.italic, f.strike)) } else { None }).collect(); + let expect: Vec<(String, bool, bool, bool)> = runs.iter().map(|(t, f)| (t.to_string(), f.bold, f.italic, f.strike)).collect(); + assert_eq!(got, expect, "exported as {md:?}"); + } +} + +#[test] +fn escape_line_start_preserves_indentation() { + assert_eq!(escape_line_start(" indented text".to_string()), " indented text"); + assert_eq!(escape_line_start(" # not a heading".to_string()), " \\# not a heading"); + assert_eq!(escape_line_start(" 1. not a list".to_string()), " 1\\. not a list"); + assert_eq!(escape_line_start(" > quote".to_string()), " \\> quote"); + // Four spaces or a tab would make an indented code block: the indent is capped at three. + assert_eq!(escape_line_start(" deep".to_string()), " deep"); + assert_eq!(escape_line_start("\tTabbed # text".to_string()), " Tabbed # text"); + assert_eq!(escape_line_start(" # not a heading".to_string()), " \\# not a heading"); + assert_eq!(escape_line_start(" \t1. not a list".to_string()), " 1\\. not a list"); +} + +#[test] +fn leading_unicode_whitespace_is_kept_and_does_not_start_blocks() { + let kinds_text = |md: &str| -> Vec<(Kind, bool, String)> { + parse(md).blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some((p.kind, p.list.is_some(), p.text())) } else { None }).collect() + }; + assert_eq!(kinds_text("\u{3000}\u{3000}日本語の段落\n"), vec![(Kind::Normal, false, "\u{3000}\u{3000}日本語の段落".to_string())]); + for src in ["\u{a0}# not a heading", "\u{3000}1. not a list", "\u{a0}- x", "\u{a0}> not a quote"] { + let mut p = Para::default(); + p.push_text(src, &Fmt::default()); + let md = escape_line_start(inlines_md(&p.inlines)); + assert_eq!(kinds_text(&md), vec![(Kind::Normal, false, src.to_string())], "{src:?} via {md:?}"); + } +} + +#[test] +fn single_backtick_code_span_escaped_pipe() { + let md = "| Command | Status |\n| --- | --- |\n| `cmd \\| grep` | pass |\n"; + let flow = parse(md); + let FBlock::Table(t) = &flow.blocks[0] else { panic!("expected table") }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[1].len(), 2); + let FBlock::Para(p0) = &t.rows[1][0].blocks[0] else { panic!() }; + assert_eq!(p0.inlines.len(), 1); + assert!(matches!(&p0.inlines[0], Inline::Text(t, f) if t == "cmd | grep" && f.code)); + let FBlock::Para(p1) = &t.rows[1][1].blocks[0] else { panic!() }; + assert_eq!(p1.text(), "pass"); + + let mut out = Vec::new(); + table_md(t, &mut out); + let exported = out.join("\n"); + assert!(exported.contains("`cmd \\| grep`"), "Exported: {exported}"); +} + +#[test] +fn double_backtick_code_span_escaped_pipe() { + let md = "| Syntax | Note |\n| --- | --- |\n| ``a \\| b`` | second |\n"; + let flow = parse(md); + let FBlock::Table(t) = &flow.blocks[0] else { panic!("expected table") }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[1].len(), 2); + let FBlock::Para(p0) = &t.rows[1][0].blocks[0] else { panic!() }; + assert_eq!(p0.inlines.len(), 1); + assert!(matches!(&p0.inlines[0], Inline::Text(t, f) if t == "a | b" && f.code)); + let FBlock::Para(p1) = &t.rows[1][1].blocks[0] else { panic!() }; + assert_eq!(p1.text(), "second"); +} + +#[test] +fn code_span_literal_backtick_and_escaped_pipe() { + let md = "| Expression | Detail |\n| --- | --- |\n| ``a`b\\|c`` | distinct |\n"; + let flow = parse(md); + let FBlock::Table(t) = &flow.blocks[0] else { panic!("expected table") }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[1].len(), 2); + let FBlock::Para(p0) = &t.rows[1][0].blocks[0] else { panic!() }; + assert_eq!(p0.inlines.len(), 1); + assert!(matches!(&p0.inlines[0], Inline::Text(t, f) if t == "a`b|c" && f.code)); + let FBlock::Para(p1) = &t.rows[1][1].blocks[0] else { panic!() }; + assert_eq!(p1.text(), "distinct"); +} + +#[test] +fn three_column_table_with_distinctive_text() { + let md = "| Col1 | Col2 | Col3 |\n| --- | --- | --- |\n| `p1\\|q1` | Distinctive Two | Distinctive Three |\n"; + let flow = parse(md); + let FBlock::Table(t) = &flow.blocks[0] else { panic!("expected table") }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[1].len(), 3); + assert_eq!(t.rows[1][0].text(), "p1|q1"); + assert_eq!(t.rows[1][1].text(), "Distinctive Two"); + assert_eq!(t.rows[1][2].text(), "Distinctive Three"); + let FBlock::Para(p0) = &t.rows[1][0].blocks[0] else { panic!() }; + assert!(matches!(&p0.inlines[0], Inline::Text(_, f) if f.code)); + let FBlock::Para(p1) = &t.rows[1][1].blocks[0] else { panic!() }; + assert!(matches!(&p1.inlines[0], Inline::Text(_, f) if !f.code)); + let FBlock::Para(p2) = &t.rows[1][2].blocks[0] else { panic!() }; + assert!(matches!(&p2.inlines[0], Inline::Text(_, f) if !f.code)); +} + +#[test] +fn table_cells_past_the_document_limits_are_not_built() { + // Every body row was padded to the header's width before any cap (#3701). + let wide = format!("{}|\n{}|\n|\n| b |\n", "|a".repeat(50_000), "|-".repeat(50_000)); + craft_flow::begin_import(); + let flow = parse(&wide); + let FBlock::Table(t) = &flow.blocks[0] else { panic!("expected table") }; + assert_eq!(t.rows.len(), 3); + assert!(t.rows.iter().all(|r| r.len() == MAX_COLS)); + assert_eq!(t.rows[2][0].text(), "b"); + assert!(craft_flow::Dropped::TableCells.reported(), "the columns left out are logged"); + // Rows past the limit still belong to the table, so the text after it reads as before. + let tall = format!("| a |\n| - |\n{}\nafter\n", "| x |\n".repeat(MAX_ROWS + 10)); + craft_flow::begin_import(); + let flow = parse(&tall); + let FBlock::Table(t) = &flow.blocks[0] else { panic!("expected table") }; + assert_eq!(t.rows.len(), MAX_ROWS); + let FBlock::Para(p) = &flow.blocks[1] else { panic!("expected paragraph") }; + assert_eq!(p.text(), "after"); + assert_eq!(flow.blocks.len(), 2); + assert!(craft_flow::Dropped::TableCells.reported(), "the rows left out are logged"); +} + +/// A short row is padded to its header's width, so a small file of one-cell rows under wide +/// headers made millions of cells (CodeRabbit on #3862). The document's tables share one cell +/// budget: rows past it are left out and logged, and their lines make no paragraphs. +#[test] +fn tables_share_one_cell_budget() { + let header = |n: usize| format!("|{}|\n|{}|\n", vec![" h "; n].join("|"), vec!["-"; n].join("|")); + let fits = crate::MAX_TABLE_CELLS / MAX_COLS; + let src = format!("{}{}\nafter\n\n{}| 1 | 2 |\n", header(MAX_COLS), "| x |\n".repeat(fits + 100), header(2)); + craft_flow::begin_import(); + let flow = parse(&src); + let tables: Vec<&FTable> = flow.blocks.iter().filter_map(|b| if let FBlock::Table(t) = b { Some(t) } else { None }).collect(); + let cells: usize = tables.iter().flat_map(|t| &t.rows).map(Vec::len).sum(); + assert!(cells <= crate::MAX_TABLE_CELLS, "{cells} cells"); + assert_eq!(tables.iter().map(|t| t.rows.len()).collect::>(), [fits], "the second table is past the budget"); + let texts: Vec = flow.blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some(p.text()) } else { None }).collect(); + assert_eq!(texts, ["after"]); + assert!(craft_flow::Dropped::TableCells.reported()); + // Within the budget a table is whole and nothing is logged. + craft_flow::begin_import(); + let flow = parse(&format!("{}| 1 | 2 |\n", header(2))); + let [FBlock::Table(t)] = flow.blocks.as_slice() else { panic!("{:?}", flow.blocks) }; + assert_eq!(t.rows.len(), 2); + assert!(!craft_flow::Dropped::TableCells.reported()); +} + +#[test] +fn a_wide_table_still_checks_every_header_and_delimiter_cell() { + // Only the first 63 cells are kept, but every one is counted and checked. + let head = "|a".repeat(100) + "|\n"; + let delim = |bad: Option| (0..100).map(|i| if Some(i) == bad { "|x" } else { "|-" }).collect::() + "|\n"; + let is_table = |md: String| matches!(parse(&md).blocks.first(), Some(FBlock::Table(_))); + assert!(is_table(format!("{head}{}| b |\n", delim(None)))); + assert!(!is_table(format!("{head}{}| b |\n", delim(Some(80)))), "a bad delimiter cell past the kept ones"); + assert!(!is_table(format!("{}|\n{}| b |\n", "|a".repeat(99), delim(None))), "99 header cells, 100 delimiter cells"); + let (cells, n) = split_row(r"| a | b \| c | d |", 2); + assert_eq!((cells, n), (vec!["a".to_string(), "b | c".to_string()], 3)); +} + +#[test] +fn regular_table_cells_containing_escaped_pipes() { + let md = "| Option | Description |\n| --- | --- |\n| Regular \\| Pipe | Normal text cell |\n"; + let flow = parse(md); + let FBlock::Table(t) = &flow.blocks[0] else { panic!("expected table") }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[1].len(), 2); + assert_eq!(t.rows[1][0].text(), "Regular | Pipe"); + assert_eq!(t.rows[1][1].text(), "Normal text cell"); + let FBlock::Para(p0) = &t.rows[1][0].blocks[0] else { panic!() }; + assert!(matches!(&p0.inlines[0], Inline::Text(_, f) if !f.code)); + + let mut out = Vec::new(); + table_md(t, &mut out); + let exported = out.join("\n"); + assert!(exported.contains("Regular \\| Pipe"), "Exported: {exported}"); + assert!(!exported.contains("Regular \\\\| Pipe"), "Exported: {exported}"); +} + +#[test] +fn unescaped_pipes_behave_as_gfm_column_separators() { + let md = "| Header 1 | Header 2 |\n| --- | --- |\n| `raw|pipe` | Extra Column |\n"; + let flow = parse(md); + let FBlock::Table(t) = &flow.blocks[0] else { panic!("expected table") }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[1].len(), 2); + assert_eq!(t.rows[1][0].text(), "`raw"); + assert_eq!(t.rows[1][1].text(), "pipe`"); +} + +#[test] +fn ordinary_tables_and_standalone_code_spans_unchanged() { + let md = "| Alpha | Beta |\n| --- | --- |\n| 1 | 2 |\n"; + let flow = parse(md); + let FBlock::Table(t) = &flow.blocks[0] else { panic!() }; + let mut out = Vec::new(); + table_md(t, &mut out); + assert_eq!(out.join("\n"), "| Alpha | Beta |\n| --- | --- |\n| 1 | 2 |"); + + let mut p = Para::default(); + let f = Fmt { code: true, ..Default::default() }; + p.push_text("cmd | grep", &f); + let exported = inlines_md(&p.inlines); + assert_eq!(exported, "`cmd | grep`"); +} + +#[test] +fn code_span_line_endings_stay_literal_on_export() { + let cases = [ + ("a\n# b", "a # b"), + ("a\n

", "a
b
"), + ("a\n- b", "a - b"), + ("a\n```", "a ```"), + ("a\r# b", "a # b"), + ("a\r\n# b", "a # b"), + ("a\n\n> b", "a > b"), + ("\na\n", " a "), + ("`a\n# b`", "`a # b`"), + ("cmd | grep", "cmd | grep"), + ]; + let shapes = [ + (Kind::Normal, None), + (Kind::Normal, Some(ListInfo { ordered: false, level: 0, start: 1, ..Default::default() })), + (Kind::Code, Some(ListInfo { ordered: true, level: 0, start: 1, ..Default::default() })), + ]; + for (source, expected) in cases { + for (kind, list) in shapes { + let mut p = Para::new(kind); + p.list = list; + p.push_text(source, &Fmt { code: true, ..Default::default() }); + let mut doc = model::to_doc(&model::Flow { blocks: vec![FBlock::Para(p)], ..Default::default() }); + // The flow builder removes CR controls; keep the native document's raw input. + let p = doc.para_mut(craft_wordmodel::StoryRef::Body, &craft_wordmodel::Path::top(0)).unwrap(); + p.text = source.to_string(); + p.runs[0].len = source.len(); + let md = export(&doc); + assert_eq!(md.trim_end().lines().count(), 1, "{source:?} {kind:?} {list:?} -> {md:?}"); + assert!(!md.contains('\r'), "{md:?}"); + let back = import(&md); + let flow = model::from_doc(&back); + let [FBlock::Para(q)] = flow.blocks.as_slice() else { panic!("{md:?}") }; + assert_eq!(q.text(), expected, "{source:?} {kind:?} {list:?} -> {md:?}"); + assert_eq!(q.list, list, "{md:?}"); + assert!(q.inlines.iter().all(|i| matches!(i, Inline::Text(_, f) if f.code)), "{md:?}"); + } + } + let fenced = "```\na\n# b\n```"; + assert_eq!(export(&import(fenced)).trim_end(), fenced); +} + +#[test] +fn code_span_line_endings_in_table_cells_stay_literal() { + for ending in ["\n", "\r", "\r\n"] { + let source = format!("a{ending}# b|c"); + let mut p = Para::default(); + p.push_text(&source, &Fmt { code: true, ..Default::default() }); + let cell = Cell { blocks: vec![FBlock::Para(p)], ..Default::default() }; + let table = FTable { rows: vec![vec![cell, Cell::default()], vec![Cell::default(), Cell::default()]], ..Default::default() }; + let mut doc = model::to_doc(&model::Flow { blocks: vec![FBlock::Table(table)], ..Default::default() }); + let p = doc.para_mut(craft_wordmodel::StoryRef::Body, &craft_wordmodel::Path(vec![0, 0, 0, 0])).unwrap(); + p.text = source.clone(); + p.runs[0].len = source.len(); + let md = export(&doc); + let back = model::from_doc(&import(&md)); + let [FBlock::Table(table), ..] = back.blocks.as_slice() else { panic!("{md:?}") }; + assert!(back.blocks.iter().skip(1).all(|b| matches!(b, FBlock::Para(p) if p.text().is_empty())), "{md:?}"); + assert_eq!(table.rows.len(), 2, "{md:?}"); + assert_eq!(table.rows[0].len(), 2, "{md:?}"); + let [FBlock::Para(p)] = table.rows[0][0].blocks.as_slice() else { panic!("{md:?}") }; + assert_eq!(p.text(), "a # b|c", "{md:?}"); + assert!(p.inlines.iter().all(|i| matches!(i, Inline::Text(_, f) if f.code)), "{md:?}"); + } +} + +#[test] +fn table_code_pipe_export_import_round_trip() { + let mut table = FTable::default(); + let mut cell_a = Cell::default(); + let mut para_a = Para::default(); + let fmt_a = Fmt { code: true, ..Default::default() }; + para_a.push_text("a`b|c", &fmt_a); + cell_a.blocks.push(FBlock::Para(para_a)); + + let mut cell_b = Cell::default(); + let mut para_b = Para::default(); + para_b.push_text("CRITICAL_DISTINCTIVE_INFO", &Fmt::default()); + cell_b.blocks.push(FBlock::Para(para_b)); + + let mut head_a = Cell::default(); + let mut head_para_a = Para::default(); + head_para_a.push_text("Col A", &Fmt::default()); + head_a.blocks.push(FBlock::Para(head_para_a)); + + let mut head_b = Cell::default(); + let mut head_para_b = Para::default(); + head_para_b.push_text("Col B", &Fmt::default()); + head_b.blocks.push(FBlock::Para(head_para_b)); + + table.rows.push(vec![head_a, head_b]); + table.rows.push(vec![cell_a, cell_b]); + + let mut out = Vec::new(); + table_md(&table, &mut out); + let exported_md = out.join("\n"); + + assert!(exported_md.contains("``a`b\\|c``"), "Exported: {exported_md}"); + assert!(exported_md.contains("CRITICAL\\_DISTINCTIVE\\_INFO"), "Exported: {exported_md}"); + + let back_flow = parse(&exported_md); + let FBlock::Table(back_table) = &back_flow.blocks[0] else { panic!("expected table") }; + + assert_eq!(back_table.rows.len(), 2, "Both rows must exist"); + let row1 = &back_table.rows[1]; + assert_eq!(row1.len(), 2, "Both cells must exist in row 1"); + + let back_cell_a = &row1[0]; + let back_cell_b = &row1[1]; + assert_eq!(back_cell_a.text(), "a`b|c", "Cell A text must be preserved"); + assert_eq!(back_cell_b.text(), "CRITICAL_DISTINCTIVE_INFO", "Cell B text must be preserved"); + + let FBlock::Para(back_p_a) = &back_cell_a.blocks[0] else { panic!() }; + assert_eq!(back_p_a.inlines.len(), 1); + assert!( + matches!(&back_p_a.inlines[0], Inline::Text(t, f) if t == "a`b|c" && f.code), + "Code formatting must remain intact on Cell A: {:?}", + back_p_a.inlines + ); + + let FBlock::Para(back_p_b) = &back_cell_b.blocks[0] else { panic!() }; + assert_eq!(back_p_b.inlines.len(), 1); + assert!( + matches!(&back_p_b.inlines[0], Inline::Text(t, f) if t == "CRITICAL_DISTINCTIVE_INFO" && !f.code), + "Cell B formatting must remain plain text: {:?}", + back_p_b.inlines + ); + + assert_eq!(back_cell_a.text(), "a`b|c"); + assert_eq!(back_cell_b.text(), "CRITICAL_DISTINCTIVE_INFO"); + + assert!(!back_cell_a.text().contains("CRITICAL_DISTINCTIVE_INFO")); + assert!(!back_cell_b.text().contains("a`b|c")); + + let doc = import(&exported_md); + let re_exported = export(&doc); + assert!(re_exported.contains("``a`b\\|c``"), "Re-exported: {re_exported}"); + assert!(re_exported.contains("CRITICAL\\_DISTINCTIVE\\_INFO"), "Re-exported: {re_exported}"); + let doc2 = import(&re_exported); + let back_flow2 = model::from_doc(&doc2); + let FBlock::Table(back_table2) = &back_flow2.blocks[0] else { panic!() }; + assert_eq!(back_table2.rows[1][0].text(), "a`b|c"); + assert_eq!(back_table2.rows[1][1].text(), "CRITICAL_DISTINCTIVE_INFO"); +} + +#[test] +fn ordered_list_keeps_start_number() { + assert_eq!(export(&import("5. a\n6. b")).trim_end(), "5. a\n6. b"); +} + +/// A list inside a block quote stays in the quote: its items were imported as quoted list +/// paragraphs but written back without `>`, so the list moved out of the quote. +#[test] +fn a_list_inside_a_quote_stays_quoted() { + let src = "> Intro\n>\n> - one\n> - two\n> - nested\n> 1. first\n\nAfter.\n"; + let want = "> Intro\n\n> - one\n> - two\n> - nested\n> 1. first\n\nAfter."; + let md = export(&import(src)); + assert_eq!(md.trim_end(), want); + assert_eq!(export(&import(&md)).trim_end(), want, "and stays so when read back"); + // An item's continuation line is quoted too. + assert_eq!(export(&import("> - a\\\n> b\n")).trim_end(), "> - a\\\n> b"); + // A list outside a quote is unchanged. + assert_eq!(export(&import("- one\n- two\n")).trim_end(), "- one\n- two"); + // A list after a quoted list stays outside the quote. + let md = export(&import("> - a\n\n2. b\n")); + assert_eq!(md.trim_end(), "> - a\n\n2. b"); + assert_eq!(export(&import(&md)).trim_end(), "> - a\n\n2. b", "and stays so when read back"); +} + +#[test] +fn lines_after_line_break_stay_in_paragraph() { + use craft_wordmodel::{CharProps, Document, Paragraph, StoryRef, para_block}; + let cases = ["Shopping\n- milk\n# not a heading", "a\n1. x", "a\n2) x", "a\n+ x", "a\n---", "a\n***", "a\n==", "a\n--", "a\n> q"]; + for s in cases { + let mut d = Document::new(); + d.body = vec![para_block(Paragraph::with_text(s, CharProps::default()))]; + let md = export(&d); + let back = import(&md); + assert_eq!(back.body.len(), 1, "{s:?} -> {md:?}"); + assert_eq!(back.plain_text(StoryRef::Body), s, "{md:?}"); + } +} + +#[test] +fn lines_after_line_break_stay_in_list_item_and_quote() { + let cases = ["a\n- x", "a\n# h", "a\n1. x", "a\n--", "a\n---", "a\n==", "a\n> q"]; + let shapes: [(Kind, Option); 5] = [ + (Kind::Normal, Some(ListInfo { ordered: false, level: 0, start: 1, ..Default::default() })), + (Kind::Normal, Some(ListInfo { ordered: true, level: 0, start: 1, ..Default::default() })), + (Kind::Normal, Some(ListInfo { ordered: false, level: 1, start: 1, ..Default::default() })), + (Kind::Normal, Some(ListInfo { ordered: true, level: 1, start: 1, ..Default::default() })), + (Kind::Quote, None), + ]; + for s in cases { + for (kind, list) in shapes { + let mut blocks = Vec::new(); + if let Some(li) = list.filter(|l| l.level > 0) { + let mut parent = Para::new(Kind::Normal); + parent.list = Some(ListInfo { ordered: li.ordered, level: 0, start: 1, ..Default::default() }); + parent.push_text("top", &Fmt::default()); + blocks.push(FBlock::Para(parent)); + } + let mut p = Para::new(kind); + p.list = list; + p.push_text(s, &Fmt::default()); + blocks.push(FBlock::Para(p)); + let mut out = Vec::new(); + write_blocks(&blocks, &mut out); + let md = out.join("\n"); + let back = parse(&md); + assert_eq!(back.blocks.len(), blocks.len(), "{s:?} {kind:?} {list:?} -> {md:?}"); + let Some(FBlock::Para(q)) = back.blocks.last() else { panic!("{md:?}") }; + assert_eq!(q.kind, kind, "{md:?}"); + assert_eq!(q.list, list, "{md:?}"); + assert_eq!(q.text(), s, "{md:?}"); + } + } +} + +#[test] +fn table_column_alignments_import_and_export() { + let md = "| Left | Center | Right | Default |\n| :--- | :---: | ---: | --- |\n| 1 | 2 | 3 | 4 |\n"; + let flow = parse(md); + let FBlock::Table(t) = &flow.blocks[0] else { panic!("expected table") }; + assert_eq!(t.rows.len(), 2); + let aligns: Vec> = + t.rows[0].iter().map(|c| c.blocks.iter().find_map(|b| if let FBlock::Para(p) = b { Some(p.align) } else { None }).flatten()).collect(); + assert_eq!(aligns, vec![Some(Align::Left), Some(Align::Center), Some(Align::Right), None]); + + let mut out = Vec::new(); + table_md(t, &mut out); + let exported = out.join("\n"); + assert!(exported.contains("| :--- | :---: | ---: | --- |"), "Exported: {exported}"); +} + +#[test] +fn tab_separated_list_markers() { + let f = parse("-\tbullet item\n*\tstar item\n+\tplus item\n1.\tone item\n2)\ttwo item\n"); + assert_eq!(f.blocks.len(), 5); + for (i, b) in f.blocks.iter().enumerate() { + let FBlock::Para(p) = b else { panic!("block {i} not a para") }; + assert!(p.list.is_some(), "block {i} should be a list item: {:?}", p); + } + let FBlock::Para(p0) = &f.blocks[0] else { panic!() }; + assert_eq!(p0.text(), "bullet item"); + assert!(!p0.list.unwrap().ordered); + + let FBlock::Para(p3) = &f.blocks[3] else { panic!() }; + assert_eq!(p3.text(), "one item"); + assert!(p3.list.unwrap().ordered); +} + +#[test] +fn html_comments_are_ignored_in_blocks_and_inlines() { + let md = "\n\nHello world!\n\n\n\nAfter comment."; + let flow = parse(md); + assert_eq!(flow.blocks.len(), 2); + let texts: Vec = flow.blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some(p.text()) } else { None }).collect(); + assert_eq!(texts, ["Hello world!", "After comment."]); +} + +#[test] +fn a_paragraph_of_delimiters_parses_in_linear_time() { + // #3714: each delimiter's literal looked back for the text before it, to the start of + // the paragraph when there was none (quadratic). + let src = "*_".repeat(200_000); + let t = std::time::Instant::now(); + let out = inl(&src); + // Under a second on a loaded machine; the backwards search ran past 6 minutes. + assert!(t.elapsed() < std::time::Duration::from_secs(10), "{:?}", t.elapsed()); + let text: String = out.iter().filter_map(|i| if let Inline::Text(t, _) = i { Some(t.as_str()) } else { None }).collect(); + assert!(text.chars().all(|c| matches!(c, '*' | '_')), "only delimiters come out"); + // Literal delimiters still take the link of the text before them. + let s = inl("[a](http://x.org) [b*](http://y.org)"); + assert!(s.iter().any(|i| matches!(i, Inline::Text(t, f) if t == "b*" && f.link.as_deref() == Some("http://y.org"))), "{s:?}"); +} + +#[test] +fn exported_link_destinations_read_back_unchanged() { + // Removing `<` and `>` from a destination after the safety check could make a relative + // target a script or network-path one (`java)"); + for l in [ + "javab c", + "javascript:alert(1)", + "javascript:x", + "&", + "javascript\\:x", + "dir\\", + "dir\\(1)\\", + "q?a=1&b=2", + ] { + let out = md(l); + let back = inl(&out); + let got: Vec<_> = back.iter().filter_map(|i| if let Inline::Text(_, f) = i { f.link.as_deref().map(str::to_string) } else { None }).collect(); + assert_eq!(got, [l.to_string()], "{l:?} → {out:?}"); + } + // Ordinary destinations are written as before. + assert_eq!(md("https://example.com/a?b=1&c=2"), "[x](https://example.com/a?b=1&c=2)"); + assert_eq!(md("https://example.com/a b"), "[x]()"); + assert_eq!(md("https://e.com/x\ny"), "[x](https://e.com/xy)"); +} + +#[test] +fn heading_trailing_hash_survives_round_trip() { + let heading = |md: &str| { + let f = parse(md); + let Some(FBlock::Para(p)) = f.blocks.first() else { panic!("no paragraph in {md:?}") }; + assert_eq!(p.kind, Kind::Heading(2), "{md:?}"); + p.text() + }; + for (src, text, want) in [ + ("## Item \\#\n", "Item #", "## Item \\#\n"), + ("## Issue \\##\n", "Issue ##", "## Issue \\##\n"), + ("## \\#\n", "#", "## \\#\n"), + ("## C#\n", "C#", "## C#\n"), + ] { + assert_eq!(heading(src), text, "{src:?}"); + let md = export(&import(src)); + assert_eq!(md, want, "first export of {src:?}"); + assert_eq!(heading(&md), text, "md was {md:?}"); + assert_eq!(export(&import(&md)), want, "second export of {src:?}"); + } +} diff --git a/crates/math/Cargo.toml b/crates/math/Cargo.toml new file mode 100644 index 000000000..6cbc3251e --- /dev/null +++ b/crates/math/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-math" +description = "Equations as one tree (the Office Math object model) with its syntaxes: OMML, MathML, LaTeX math and the UnicodeMath linear format, read and written." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-xml = { workspace = true } +serde = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } +proptest = { workspace = true } diff --git a/crates/math/README.md b/crates/math/README.md new file mode 100644 index 000000000..f1941e0e5 --- /dev/null +++ b/crates/math/README.md @@ -0,0 +1,55 @@ +# craft-math + +Equations as one tree, and the syntaxes it is read from and written to: + +| Module | Syntax | Read | Write | +| --- | --- | --- | --- | +| `math` | the tree: `MNode`, `MRun`, `Math` (an equation with its kept source OMML), modelled on the Office Math object model (ECMA-376 Part 1 §22.1) | | | +| `math_linear` | UnicodeMath, the linear format Word shows (`x=(-b±√(b^2-4ac))/2a`) | `math::parse_linear` | `math::to_linear` | +| `math_latex` | LaTeX math, including MathLive's spellings | `parse_latex` | `to_latex` | +| `omml` | Office Math Markup (`m:oMath`, DOCX/PPTX/XLSX) | `read_omath`, `read_str` | `write_equation`, `write_str` | +| `mathml` | presentation MathML (HTML, ODF formulas, the clipboard) | `parse`, `read`, `to_tree` | `to_mathml`, `linear_to_mathml` | + +Beside them: `math_symbols` (LaTeX names of symbols), `math_tree` (the arguments of a node, a walk +over every run), `symbol_fonts` (Symbol, Wingdings and the other symbol fonts as Unicode) and +`Rgb` (a run's colour). + +```rust +use craft_math::{Math, math, math_latex, mathml, omml}; + +let tree = math_latex::parse_latex(r"\frac{a}{b}+\sqrt{x}"); +assert_eq!(math::to_linear(&tree), "a/b+√x"); + +// OMML out and back. +let eq = Math { nodes: tree.clone(), ..Default::default() }; +let xml = omml::write_str("", false, &eq, None); +let read = omml::read_str(&xml).unwrap(); +assert_eq!(read.nodes, tree); + +// MathML carries the linear format in an annotation, so it reads back exactly. +let ml = mathml::linear_to_mathml("a/b+√x", true); +assert_eq!(mathml::parse(&ml).and_then(|m| mathml::read(&m)), Some(("a/b+√x".to_string(), true))); +``` + +## Reading OMML + +`omml::read_omath` takes an `m:oMath` element of a `craft_xml` tree read with the canonical +prefixes of `omml::NAMESPACES` (`m`, `w` and `mc`, transitional and strict URIs), so a document +reader passes the element it already has. `omml::read_str` and `omml::parse` read a string. The +source XML is kept in `Math::omml`; `write_equation` writes it back unchanged while the +equation's colour is the same and the XML is well formed, so a saved document carries the +equation as Word wrote it. + +## Limits + +Nesting is bounded by `math::MAX_DEPTH` in every reader and writer; `omml::parse` reads at most +`omml::MAX_ELEMENTS` elements and `mathml::parse` keeps at most `mathml::MAX_NODES`; the LaTeX +reader looks at 20,000 characters. Nothing panics on any input. + +## Provenance + +The tree, the linear format, LaTeX, the symbol names, the tree walk, the symbol fonts and `Rgb` +are WordCraft's (`crates/doc`), as moved into craft-wordmodel; OMML is WordCraft's DOCX reader +and writer (`crates/docx/src/read/math.rs`, `write/math.rs`) and MathML its formats crate's +(`crates/formats/src/mathml.rs`), moved onto craft-xml. The MathLive command spellings and the +round-trip corpus in `tests/corpus/` come from equaSHion (storytold/craft-libs#29). diff --git a/crates/math/src/lib.rs b/crates/math/src/lib.rs new file mode 100644 index 000000000..f0196bfb3 --- /dev/null +++ b/crates/math/src/lib.rs @@ -0,0 +1,55 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +// The code came from an app whose lints allow this. +#![allow(clippy::type_complexity)] +//! Equations: one tree and the syntaxes it is read from and written to. +//! +//! - [`math`]: the tree ([`MNode`], [`MRun`], an argument [`Arg`] is a `Vec`), modelled on +//! the Office Math object model (ECMA-376 Part 1 §22.1), and [`Math`], an equation with its kept +//! source OMML. +//! - [`math_linear`]: the linear format (UnicodeMath, the plain text Word shows for an equation), +//! read and written ([`math::parse_linear`], [`math::to_linear`]). +//! - [`math_latex`]: LaTeX math, read and written ([`math_latex::parse_latex`], +//! [`math_latex::to_latex`]), with the named symbols of [`math_symbols`]. +//! - [`omml`]: Office Math Markup, read ([`omml::read_omath`], [`omml::read_str`]) and written +//! ([`omml::write_equation`], [`omml::write_str`]). +//! - [`mathml`]: presentation MathML, written ([`mathml::to_mathml`]) and read +//! ([`mathml::parse`], [`mathml::read`], [`mathml::to_tree`]). +//! - [`math_tree`]: the arguments of a node and a walk over every run. +//! - [`symbol_fonts`]: text in symbol fonts (Symbol, Wingdings…) as Unicode, as OMML runs and +//! Word text need it. +//! - [`Rgb`]: the colour of a run. +//! +//! Every reader is bounded (nesting [`math::MAX_DEPTH`], node budgets) and never panics on any +//! input. +//! +//! ``` +//! use craft_math::{math, math_latex, mathml, omml}; +//! +//! let tree = math::parse_linear("x=(-b±√(b^2-4ac))/2a"); +//! assert_eq!(math::to_linear(&tree), "x=(-b±√(b^2-4ac))/2a"); +//! assert!(math_latex::to_latex(&tree).contains("\\frac")); +//! +//! let eq = math::Math { nodes: tree.clone(), ..Default::default() }; +//! let xml = omml::write_str("", false, &eq, None); +//! assert_eq!(omml::read_str(&xml).map(|m| m.nodes), Some(tree.clone())); +//! +//! let ml = mathml::to_mathml(&tree, false, ""); +//! assert_eq!(mathml::parse(&ml).as_ref().map(mathml::to_tree), Some(tree)); +//! ``` + +#[cfg(doctest)] +#[doc = include_str!("../README.md")] +struct ReadmeExamples; + +pub mod math; +pub mod math_latex; +pub mod math_linear; +pub mod math_symbols; +pub mod math_tree; +pub mod mathml; +pub mod omml; +mod rgb; +pub mod symbol_fonts; + +pub use math::{Arg, MNode, MRun, Math, MathProps}; +pub use rgb::Rgb; diff --git a/crates/math/src/math.rs b/crates/math/src/math.rs new file mode 100644 index 000000000..dc09cd164 --- /dev/null +++ b/crates/math/src/math.rs @@ -0,0 +1,1138 @@ +//! Equations: the Office Math object model (OMML, ECMA-376 Part 1 §22.1) as a tree, its linear +//! format (UnicodeMath, the plain text Word shows for an equation) and a parser for that format. +//! +//! An equation is a list of [`MNode`]s (an *argument*); structures hold arguments of their own +//! (a fraction's numerator and denominator, a radical's degree and base…). Layout reads the tree; +//! DOCX import builds it from OMML and keeps the source XML so a saved file carries the equation +//! exactly as Word wrote it. + +use serde::{Deserialize, Serialize}; + +use crate::rgb::Rgb; + +/// A sequence of math nodes (OMML's `m:e`, `m:num`, `m:sub`…). +pub type Arg = Vec; + +/// Deepest structure nesting kept (parsers stop here; layout draws nothing deeper). +pub const MAX_DEPTH: usize = 64; + +/// Most matrix columns kept (writers pad every row to the widest, so this bounds a row's cost). +pub const MAX_MATRIX_COLS: usize = 64; + +/// Most matrix rows kept. +pub const MAX_MATRIX_ROWS: usize = 1000; + +/// An equation's structure, plus what's needed to write it back. +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Math { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub nodes: Arg, + /// The source `m:oMath` element (DOCX import), written back unchanged on save. Empty for + /// equations made here. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub omml: String, + /// Justification of a display equation. + #[serde(default, skip_serializing_if = "is_default")] + pub jc: MathJc, + /// Shown as its linear-format text (Equation › Convert › Linear) instead of built up. + #[serde(default, skip_serializing_if = "is_default")] + pub linear: bool, +} + +fn is_default(v: &T) -> bool { + *v == T::default() +} + +impl Math { + pub fn is_empty(&self) -> bool { + self.nodes.is_empty() + } + + /// Rough heap bytes a clone copies: every node, its argument lists and its run text. + /// Iterative, so it costs at most the size of the structure. + pub fn heap_bytes(&self) -> usize { + let mut n = self.omml.len(); + let mut todo: Vec<&MNode> = self.nodes.iter().collect(); + while let Some(node) = todo.pop() { + n = n.saturating_add(std::mem::size_of::()); + if let MNode::Run(r) = node { + n = n.saturating_add(r.text.len()).saturating_add(r.font.as_ref().map_or(0, String::len)); + } + each_arg(node, &mut |a| { + n = n.saturating_add(std::mem::size_of::()); + todo.extend(a); + }); + } + n + } +} + +/// Display equation justification (`m:oMathParaPr/m:jc`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MathJc { + #[default] + CenterGroup, + Center, + Left, + Right, +} + +/// Where a display equation too wide for its line breaks at a binary operator (`m:brkBin`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BrkBin { + /// The operator starts the next line. + #[default] + Before, + /// The operator ends the line. + After, + /// The operator ends the line and starts the next one again. + Repeat, +} + +/// How a minus repeats across a break when [`BrkBin::Repeat`] (`m:brkBinSub`): the operator +/// ending the line, then the one starting the next. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BrkBinSub { + /// `--` + #[default] + MinusMinus, + /// `-+` + MinusPlus, + /// `+-` + PlusMinus, +} + +/// Document-wide equation options (`m:mathPr` in the settings part) that layout uses: how long +/// display equations wrap. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct MathProps { + pub brk_bin: BrkBin, + pub brk_bin_sub: BrkBinSub, + /// Indent of a wrapped equation's continuation lines, points (`m:wrapIndent`). + pub wrap_indent: f32, + /// Continuation lines align right instead (`m:wrapRight`). + pub wrap_right: bool, +} + +/// `m:wrapIndent`'s default: 1440 twips, one inch. +pub const DEFAULT_WRAP_INDENT: f32 = 72.0; + +impl Default for MathProps { + fn default() -> Self { + MathProps { brk_bin: BrkBin::Before, brk_bin_sub: BrkBinSub::MinusMinus, wrap_indent: DEFAULT_WRAP_INDENT, wrap_right: false } + } +} + +/// Math run style (`m:sty`): plain, bold, italic, bold italic. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MSty { + Plain, + Bold, + Italic, + BoldItalic, +} + +/// Math alphabet (`m:scr`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MScr { + #[default] + Roman, + Script, + Fraktur, + DoubleStruck, + SansSerif, + Monospace, +} + +/// A run of math text (`m:r`). +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct MRun { + pub text: String, + /// `None`: math default (letters italic, the rest upright). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sty: Option, + #[serde(default, skip_serializing_if = "is_default")] + pub scr: MScr, + /// Normal (non-math) text. + #[serde(default, skip_serializing_if = "is_default")] + pub nor: bool, + /// Literal: no automatic operator handling. + #[serde(default, skip_serializing_if = "is_default")] + pub lit: bool, + /// Font size, points. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + /// Font for normal text. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font: Option, + /// A manual line break before this run in a display equation (`m:brk`): `Some(0)` wraps as + /// usual, `Some(n)` aligns the new line at the `n`th operator of the first line (`m:alnAt`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub brk: Option, +} + +impl MRun { + pub fn new(text: impl Into) -> MRun { + MRun { text: text.into(), ..Default::default() } + } + pub fn plain(text: impl Into) -> MRun { + MRun { text: text.into(), sty: Some(MSty::Plain), ..Default::default() } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FracKind { + /// Stacked with a rule. + #[default] + Bar, + /// Skewed (num ⁄ den). + Skewed, + /// Linear (num/den). + Linear, + /// Stacked without a rule. + NoBar, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ScriptKind { + Sup, + Sub, + SubSup, + /// Pre-scripts (`m:sPre`). + Pre, +} + +/// Where an n-ary operator's limits go. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LimLoc { + /// Under and over the operator. + UndOvr, + /// As sub- and superscripts. + SubSup, +} + +/// Column justification in a matrix. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ColJc { + #[default] + Center, + Left, + Right, +} + +/// A math node. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "t", rename_all = "camelCase")] +pub enum MNode { + Run(MRun), + /// `m:f`. + Frac { + #[serde(default)] + kind: FracKind, + num: Arg, + den: Arg, + }, + /// `m:sSup`, `m:sSub`, `m:sSubSup`, `m:sPre`. + Script { + kind: ScriptKind, + base: Arg, + #[serde(default)] + sub: Arg, + #[serde(default)] + sup: Arg, + }, + /// `m:rad`. + Rad { + #[serde(default)] + deg: Arg, + #[serde(default)] + deg_hide: bool, + e: Arg, + }, + /// `m:nary`: ∑ ∫ ∏ … with limits and an operand. + Nary { + chr: char, + /// `None`: Word's default (integrals take sub/sup limits, the rest under/over). + #[serde(default)] + lim_loc: Option, + #[serde(default)] + grow: bool, + #[serde(default)] + sub_hide: bool, + #[serde(default)] + sup_hide: bool, + #[serde(default)] + sub: Arg, + #[serde(default)] + sup: Arg, + e: Arg, + }, + /// `m:d`: delimiters around elements separated by `sep`. + Delim { + /// `None` = no delimiter. + beg: Option, + end: Option, + #[serde(default)] + sep: Option, + /// Delimiters grow to the content (Word's default). + #[serde(default = "yes")] + grow: bool, + /// Grow to match the content exactly rather than centred on the math axis. + #[serde(default)] + shp_match: bool, + elems: Vec, + }, + /// `m:func`: function name applied to an argument (sin x). + Func { + name: Arg, + e: Arg, + }, + /// `m:limLow` / `m:limUpp`. + Lim { + upper: bool, + e: Arg, + lim: Arg, + }, + /// `m:acc`: accent over the base. + Acc { + chr: char, + e: Arg, + }, + /// `m:bar`: overbar or underbar. + Bar { + top: bool, + e: Arg, + }, + /// `m:borderBox`. `hide`: top, bottom, left, right. `strike`: horizontal, vertical, + /// bottom-left→top-right, top-left→bottom-right. + BorderBox { + #[serde(default)] + hide: [bool; 4], + #[serde(default)] + strike: [bool; 4], + e: Arg, + }, + /// `m:box`. + Boxed { + e: Arg, + }, + /// `m:groupChr`: a stretched character (brace, arrow) under or over the base. + GroupChr { + chr: char, + top: bool, + e: Arg, + }, + /// `m:eqArr`: rows aligned at `&`. + EqArr { + rows: Vec, + }, + /// `m:m`. + Matrix { + rows: Vec>, + #[serde(default)] + col_jc: Vec, + }, + /// `m:phant`. + Phant { + #[serde(default = "yes")] + show: bool, + #[serde(default)] + zero_wid: bool, + #[serde(default)] + zero_asc: bool, + #[serde(default)] + zero_desc: bool, + e: Arg, + }, +} + +fn yes() -> bool { + true +} + +/// A row holds an equation-number mark (`#`) in a top-level run. +pub fn has_number_mark(row: &[MNode]) -> bool { + row.iter().any(|n| matches!(n, MNode::Run(r) if !r.lit && !r.nor && r.text.contains('#'))) +} + +/// Integral signs (their limits default to sub/sup positions). +pub fn is_integral(c: char) -> bool { + matches!(c, '∫' | '∬' | '∭' | '∮' | '∯' | '∰' | '∱' | '∲' | '∳' | '⨌') +} + +/// Characters that take n-ary operator form in the linear format. +pub fn is_nary_char(c: char) -> bool { + is_integral(c) || matches!(c, '∑' | '∏' | '∐' | '⋃' | '⋂' | '⋁' | '⋀' | '⨁' | '⨂' | '⨀' | '⨄' | '⨆') +} + +/// Mathematical alphanumeric for `c` in a style and alphabet (Unicode block U+1D400). +pub fn math_alnum(c: char, bold: bool, italic: bool, scr: MScr) -> char { + let off = |base: u32, k: u32| char::from_u32(base + k).unwrap_or(c); + let upper = c.is_ascii_uppercase(); + let lower = c.is_ascii_lowercase(); + if upper || lower { + let k = if upper { c as u32 - 'A' as u32 } else { c as u32 - 'a' as u32 }; + // Letters that live in the Letterlike Symbols block. + let hole = |table: &[(char, char)]| table.iter().find(|(f, _)| *f == c).map(|(_, t)| *t); + let (base_u, base_l) = match (scr, bold, italic) { + (MScr::Roman, false, false) => return c, + (MScr::Roman, true, false) => (0x1D400, 0x1D41A), + (MScr::Roman, false, true) => { + if c == 'h' { + return '\u{210E}'; + } + (0x1D434, 0x1D44E) + } + (MScr::Roman, true, true) => (0x1D468, 0x1D482), + (MScr::Script, false, _) => { + if let Some(t) = hole(&[ + ('B', 'ℬ'), + ('E', 'ℰ'), + ('F', 'ℱ'), + ('H', 'ℋ'), + ('I', 'ℐ'), + ('L', 'ℒ'), + ('M', 'ℳ'), + ('R', 'ℛ'), + ('e', 'ℯ'), + ('g', 'ℊ'), + ('o', 'ℴ'), + ]) { + return t; + } + (0x1D49C, 0x1D4B6) + } + (MScr::Script, true, _) => (0x1D4D0, 0x1D4EA), + (MScr::Fraktur, false, _) => { + if let Some(t) = hole(&[('C', 'ℭ'), ('H', 'ℌ'), ('I', 'ℑ'), ('R', 'ℜ'), ('Z', 'ℨ')]) { + return t; + } + (0x1D504, 0x1D51E) + } + (MScr::Fraktur, true, _) => (0x1D56C, 0x1D586), + (MScr::DoubleStruck, _, _) => { + if let Some(t) = hole(&[('C', 'ℂ'), ('H', 'ℍ'), ('N', 'ℕ'), ('P', 'ℙ'), ('Q', 'ℚ'), ('R', 'ℝ'), ('Z', 'ℤ')]) { + return t; + } + (0x1D538, 0x1D552) + } + (MScr::SansSerif, false, false) => (0x1D5A0, 0x1D5BA), + (MScr::SansSerif, true, false) => (0x1D5D4, 0x1D5EE), + (MScr::SansSerif, false, true) => (0x1D608, 0x1D622), + (MScr::SansSerif, true, true) => (0x1D63C, 0x1D656), + (MScr::Monospace, _, _) => (0x1D670, 0x1D68A), + }; + return off(if upper { base_u } else { base_l }, k); + } + if c.is_ascii_digit() { + let k = c as u32 - '0' as u32; + return match (scr, bold) { + (MScr::Roman, true) => off(0x1D7CE, k), + (MScr::DoubleStruck, _) => off(0x1D7D8, k), + (MScr::SansSerif, false) => off(0x1D7E2, k), + (MScr::SansSerif, true) => off(0x1D7EC, k), + (MScr::Monospace, _) => off(0x1D7F6, k), + _ => c, + }; + } + // Greek (roman alphabet only). + if scr == MScr::Roman && (bold || italic) { + let (cap, small) = match (bold, italic) { + (true, false) => (0x1D6A8, 0x1D6C2), + (false, true) => (0x1D6E2, 0x1D6FC), + _ => (0x1D71C, 0x1D736), + }; + let u = c as u32; + if (0x391..=0x3A9).contains(&u) && u != 0x3A2 { + return off(cap, u - 0x391); + } + if (0x3B1..=0x3C9).contains(&u) { + return off(small, u - 0x3B1); + } + let extra = match c { + '∂' => Some(25), + 'ϵ' => Some(26), + 'ϑ' => Some(27), + 'ϰ' => Some(28), + 'ϕ' => Some(29), + 'ϱ' => Some(30), + 'ϖ' => Some(31), + _ => None, + }; + if let Some(e) = extra + && italic + { + return off(small, e); + } + } + c +} + +// --------------------------------------------------------------------------------------------- +// Linear format out. + +/// The equation as linear-format text (`x=(-b±√(b^2-4ac))/2a`). +pub fn to_linear(nodes: &[MNode]) -> String { + let mut s = String::new(); + lin_arg(nodes, &mut s, 0); + s +} + +fn lin_arg(a: &[MNode], s: &mut String, depth: usize) { + if depth > MAX_DEPTH { + return; + } + for (i, n) in a.iter().enumerate() { + lin_node(n, s, depth + 1); + // A bare script or limit ends at a space: a letter, digit or period after it is its own item. + if matches!(n, MNode::Script { kind, .. } if *kind != ScriptKind::Pre) || matches!(n, MNode::Lim { .. }) { + let ends_bare = s.chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '.'); + if ends_bare && a.get(i + 1).and_then(first_lin_char).is_some_and(|c| c.is_alphanumeric() || c == '.') { + s.push(' '); + } + } + } +} + +/// The first character `n` is written with, when that is cheap to tell (letters and digits). +fn first_lin_char(n: &MNode) -> Option { + match n { + MNode::Run(r) => r.text.chars().next(), + MNode::Func { name, .. } => name.first().and_then(first_lin_char), + MNode::Script { kind, base, .. } if *kind != ScriptKind::Pre => base.first().and_then(first_lin_char), + MNode::Lim { e, .. } => e.first().and_then(first_lin_char), + MNode::Frac { num, .. } => num.first().and_then(first_lin_char), + _ => None, + } +} + +/// An argument as an operand: bare when it's a single simple atom, parenthesised otherwise. +fn lin_operand(a: &[MNode], s: &mut String, depth: usize) { + let mut inner = String::new(); + lin_arg(a, &mut inner, depth); + let simple = match a { + [MNode::Run(r)] => { + let mut cs = r.text.chars(); + match (cs.next(), cs.next()) { + (Some(c), None) => !"+-−=/^_ ".contains(c), + _ => r.text.chars().all(|c| c.is_alphanumeric() || c == '.'), + } + } + [MNode::Delim { .. }] => true, + _ => false, + }; + if simple && !inner.is_empty() { + s.push_str(&inner); + } else { + s.push('('); + s.push_str(&inner); + s.push(')'); + } +} + +/// A script or limit operand. The parser reads a run of letters and digits up to the next space or +/// operator, so `V_dd` is written bare as Word's Linear format shows it (`V_(dd)` reads back the same). +fn lin_script(a: &[MNode], s: &mut String, depth: usize) { + // Bare only when the parser reads the whole run back, in the same style. + if let [MNode::Run(r)] = a + && r.text.chars().nth(1).is_some() + { + let upright_name = r.sty == Some(MSty::Plain) && crate::math_linear::FUNCTION_NAMES.contains(&r.text.as_str()); + let number = r.text.starts_with(|c: char| c.is_ascii_digit()) && r.text.chars().all(|c| c.is_alphanumeric() || c == '.'); + let word = r.text.starts_with(char::is_alphabetic) && r.text.chars().all(char::is_alphanumeric); + let upright_other = r.sty == Some(MSty::Plain) && !upright_name; + if upright_other || (!number && !word) { + s.push('('); + s.push_str(&r.text); + s.push(')'); + return; + } + } + lin_operand(a, s, depth); +} + +fn lin_node(n: &MNode, s: &mut String, depth: usize) { + match n { + MNode::Run(r) => s.push_str(&r.text), + MNode::Frac { kind, num, den } => { + lin_operand(num, s, depth); + s.push(match kind { + FracKind::Skewed => '⁄', + FracKind::Linear => '∕', + FracKind::NoBar => '¦', + FracKind::Bar => '/', + }); + lin_operand(den, s, depth); + } + MNode::Script { kind, base, sub, sup } => { + if *kind == ScriptKind::Pre { + s.push('_'); + lin_script(sub, s, depth); + s.push('^'); + lin_script(sup, s, depth); + s.push('▒'); + lin_operand(base, s, depth); + return; + } + lin_operand(base, s, depth); + if matches!(kind, ScriptKind::Sub | ScriptKind::SubSup) { + s.push('_'); + lin_script(sub, s, depth); + } + if matches!(kind, ScriptKind::Sup | ScriptKind::SubSup) { + s.push('^'); + lin_script(sup, s, depth); + } + } + MNode::Rad { deg, deg_hide, e } => { + if *deg_hide || deg.is_empty() { + s.push('√'); + lin_operand(e, s, depth); + } else { + s.push_str("√("); + lin_arg(deg, s, depth); + s.push('&'); + lin_arg(e, s, depth); + s.push(')'); + } + } + MNode::Nary { chr, sub_hide, sup_hide, sub, sup, e, .. } => { + s.push(*chr); + if !sub_hide && !sub.is_empty() { + s.push('_'); + lin_script(sub, s, depth); + } + if !sup_hide && !sup.is_empty() { + s.push('^'); + lin_script(sup, s, depth); + } + s.push('▒'); + lin_operand(e, s, depth); + } + MNode::Delim { beg, end, elems, .. } => { + // A standard pair writes as itself; anything else uses explicit `├X … Y┤`. + let pair = matches!((beg, end), (Some(b), Some(e)) if crate::math_linear::closer(*b) == Some(*e)); + let invisible = beg.is_none() && end.is_none(); + if pair { + s.extend(*beg); + } else if invisible { + s.push('〖'); + } else { + s.push('├'); + s.extend(*beg); + } + for (i, e) in elems.iter().enumerate() { + if i > 0 { + s.push('│'); + } + lin_arg(e, s, depth); + } + if pair { + s.extend(*end); + } else if invisible { + s.push('〗'); + } else { + s.extend(*end); + s.push('┤'); + } + } + MNode::Func { name, e } => { + lin_arg(name, s, depth); + s.push('\u{2061}'); + lin_operand(e, s, depth); + } + MNode::Lim { upper, e, lim } => { + lin_operand(e, s, depth); + s.push(if *upper { '┴' } else { '┬' }); + lin_script(lim, s, depth); + } + MNode::Acc { chr, e } => { + lin_operand(e, s, depth); + s.push(*chr); + } + MNode::Bar { top, e } => { + s.push(if *top { '¯' } else { '▁' }); + lin_operand(e, s, depth); + } + MNode::BorderBox { e, .. } => { + s.push('▭'); + lin_operand(e, s, depth); + } + MNode::Boxed { e } => { + s.push('□'); + lin_operand(e, s, depth); + } + MNode::GroupChr { chr, e, .. } => { + s.push(*chr); + lin_operand(e, s, depth); + } + // A numbered equation (`E=mc^2#(1)`) is written as its one row. + MNode::EqArr { rows } if rows.len() == 1 && rows.first().is_some_and(|r| has_number_mark(r)) => { + if let Some(r) = rows.first() { + lin_arg(r, s, depth); + } + } + MNode::EqArr { rows } => { + s.push_str("█("); + for (i, r) in rows.iter().enumerate() { + if i > 0 { + s.push('@'); + } + lin_arg(r, s, depth); + } + s.push(')'); + } + MNode::Matrix { rows, .. } => { + s.push_str("■("); + for (i, r) in rows.iter().enumerate() { + if i > 0 { + s.push('@'); + } + for (j, c) in r.iter().enumerate() { + if j > 0 { + s.push('&'); + } + lin_arg(c, s, depth); + } + } + s.push(')'); + } + MNode::Phant { e, .. } => { + s.push('⟡'); + lin_operand(e, s, depth); + } + } +} + +// --------------------------------------------------------------------------------------------- +// Linear format in. + +/// Parse linear-format text into nodes ([`crate::math_linear`]). Never fails: what isn't +/// understood stays as text. +pub fn parse_linear(s: &str) -> Arg { + crate::math_linear::parse(s) +} + +pub use crate::math_linear::FUNCTION_NAMES; + +/// Spacing class of a math character (TeX's atom classes). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum MClass { + #[default] + Ord, + Op, + Bin, + Rel, + Open, + Close, + Punct, + Inner, +} + +/// The spacing class of a character in an equation. +pub fn math_class(c: char) -> MClass { + match c { + '+' | '−' | '-' | '±' | '∓' | '×' | '÷' | '·' | '∙' | '∗' | '*' | '∘' | '⊕' | '⊖' | '⊗' | '⊘' | '⊙' | '⊚' | '⊛' | '∪' | '∩' | '∧' | '∨' + | '∖' | '⋅' | '⋆' | '⊎' | '⊓' | '⊔' | '⋄' | '⊞' | '⊟' | '⊠' | '⊡' | '⋉' | '⋊' | '⋋' | '⋌' | '⋎' | '⋏' | '⋒' | '⋓' | '∔' | '∸' | '≀' | '⨿' + | '⊼' | '⊻' | '⊽' => MClass::Bin, + '=' | '<' | '>' | '≤' | '≥' | '≠' | '≈' | '≡' | '≢' | '∼' | '≃' | '≅' | '≐' | '∝' | '≪' | '≫' | '≺' | '≻' | '≼' | '≽' | '⊂' | '⊃' | '⊆' + | '⊇' | '⊄' | '⊅' | '⊈' | '⊉' | '⊊' | '⊋' | '∈' | '∉' | '∋' | '∌' | '⊥' | '∥' | '∦' | '∣' | '∤' | '≔' | '≕' | '≝' | '≜' | '≞' | '≟' | '→' + | '←' | '↔' | '⇒' | '⇐' | '⇔' | '↦' | '⟼' | '⟶' | '⟵' | '⟷' | '⟹' | '⟸' | '⟺' | '↑' | '↓' | '↕' | '⇑' | '⇓' | '⇕' | '↗' | '↘' | '↙' | '↖' + | '⊢' | '⊣' | '⊨' | '⊩' | '⊪' | '⊬' | '⊭' | '⊮' | '⊯' | '≲' | '≳' | '≍' | '⊏' | '⊐' | '⊑' | '⊒' | '⋢' | '⋣' | '≶' | '≷' | '≮' | '≯' | '≰' + | '≱' | '≦' | '≧' | '⩽' | '⩾' | ':' | '∶' | '∷' | '∺' | '∻' | '≗' | '≙' | '≚' | '≑' | '≒' | '≓' | '≖' | '⇌' | '⇋' | '⇄' | '⇆' | '⇇' | '⇉' + | '⇈' | '⇊' | '↪' | '↩' | '↼' | '↽' | '⇀' | '⇁' | '↿' | '↾' | '⇃' | '⇂' | '↶' | '↷' | '↺' | '↻' | '⊸' | '↜' | '↝' | '↞' | '↠' | '↢' | '↣' + | '↫' | '↬' | '↭' | '⇚' | '⇛' | '↰' | '↱' | '⇝' | '≁' | '≄' | '≉' | '≇' | '≭' | '≨' | '≩' | '⊀' | '⊁' | '⋠' | '⋡' | '⋦' | '⋧' | '⋨' | '⋩' + | '⋪' | '⋫' | '⋬' | '⋭' | '⋈' | '∴' | '∵' | '≏' | '≎' | '⋘' | '⋙' | '⊲' | '⊳' | '⊴' | '⊵' | '⋐' | '⋑' => { + MClass::Rel + } + '(' | '[' | '{' | '⟨' | '⌈' | '⌊' | '⟦' | '〈' => MClass::Open, + ')' | ']' | '}' | '⟩' | '⌉' | '⌋' | '⟧' | '〉' | '!' => MClass::Close, + ',' | ';' => MClass::Punct, + c if is_nary_char(c) => MClass::Op, + _ => MClass::Ord, + } +} + +/// Merge adjacent runs with the same formatting; recurse into every structure. +pub fn merge_runs(a: Arg) -> Arg { + let mut out: Arg = Vec::with_capacity(a.len()); + for n in a { + let n = match n { + MNode::Run(r) => { + if let Some(MNode::Run(prev)) = out.last_mut() + && prev.sty == r.sty + && prev.scr == r.scr + && prev.nor == r.nor + && prev.lit == r.lit + && prev.size == r.size + && prev.color == r.color + && prev.font == r.font + && r.brk.is_none() + { + prev.text.push_str(&r.text); + continue; + } + MNode::Run(r) + } + other => crate::math_linear::map_args(other, &merge_runs), + }; + out.push(n); + } + out +} + +/// Deepest node (a leaf counts 1) the parsers wrap further. Half of [`MAX_DEPTH`]: serde_json +/// stops reading at 128 nested containers and a node costs two (object and array). +pub const WRAP_DEPTH: usize = MAX_DEPTH / 2; + +/// Calls `f` with every argument of `n`. +fn each_arg<'a>(n: &'a MNode, f: &mut impl FnMut(&'a [MNode])) { + match n { + MNode::Run(_) => {} + MNode::Frac { num, den, .. } => { + f(num); + f(den); + } + MNode::Script { base, sub, sup, .. } => { + f(base); + f(sub); + f(sup); + } + MNode::Rad { deg, e, .. } => { + f(deg); + f(e); + } + MNode::Nary { sub, sup, e, .. } => { + f(sub); + f(sup); + f(e); + } + MNode::Delim { elems, .. } => elems.iter().for_each(|a| f(a)), + MNode::Func { name, e } => { + f(name); + f(e); + } + MNode::Lim { e, lim, .. } => { + f(e); + f(lim); + } + MNode::Acc { e, .. } + | MNode::Bar { e, .. } + | MNode::BorderBox { e, .. } + | MNode::Boxed { e } + | MNode::GroupChr { e, .. } + | MNode::Phant { e, .. } => f(e), + MNode::EqArr { rows } => rows.iter().for_each(|a| f(a)), + MNode::Matrix { rows, .. } => rows.iter().flatten().for_each(|a| f(a)), + } +} + +/// `n` is already nested too deeply to be wrapped in another structure. The parsers use this so +/// `x^1^1^1…` stays shallow (a left-nested tree 10 000 deep overflows the stack in `Clone`, +/// `Drop`, `PartialEq` and serde). Iterative, stops at the first too-deep path; costs at most the +/// size of `n`, which the parsers' input caps bound. +pub fn too_deep(n: &MNode) -> bool { + let mut stack: Vec<(&MNode, usize)> = vec![(n, 1)]; + while let Some((n, d)) = stack.pop() { + if d >= WRAP_DEPTH { + return true; + } + each_arg(n, &mut |a| stack.extend(a.iter().map(|c| (c, d + 1)))); + } + false +} + +/// Any of `a` is too deep to be wrapped ([`too_deep`]). +pub fn any_too_deep(a: &[MNode]) -> bool { + a.iter().any(too_deep) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(t: &str) -> MNode { + MNode::Run(MRun::new(t)) + } + + #[test] + fn quadratic_formula_parses_into_structures() { + let n = parse_linear("x=(-b±√(b^2-4ac))/2a"); + assert_eq!(n.len(), 2, "{n:#?}"); + assert_eq!(n[0], run("x=")); + let MNode::Frac { num, den, .. } = &n[1] else { panic!("{n:#?}") }; + assert_eq!(den, &vec![run("2a")]); + assert!(num.iter().any(|m| matches!(m, MNode::Rad { .. })), "{num:#?}"); + let MNode::Rad { e, .. } = num.iter().find(|m| matches!(m, MNode::Rad { .. })).unwrap() else { panic!() }; + assert!(matches!(e.first(), Some(MNode::Script { kind: ScriptKind::Sup, .. })), "{e:#?}"); + } + + #[test] + fn scripts_and_nary() { + let n = parse_linear("∑_(i=1)^n▒i^2"); + let MNode::Nary { chr, sub, sup, e, .. } = &n[0] else { panic!("{n:#?}") }; + assert_eq!(*chr, '∑'); + assert_eq!(sub, &vec![run("i=1")]); + assert_eq!(sup, &vec![run("n")]); + assert!(matches!(e.first(), Some(MNode::Script { .. }))); + let n = parse_linear("x_i^2"); + assert!(matches!(&n[0], MNode::Script { kind: ScriptKind::SubSup, .. }), "{n:#?}"); + } + + #[test] + fn functions_and_matrices() { + let n = parse_linear("sin x"); + assert!(matches!(&n[0], MNode::Func { .. }), "{n:#?}"); + let n = parse_linear("■(a&b@c&d)"); + let MNode::Matrix { rows, .. } = &n[0] else { panic!("{n:#?}") }; + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].len(), 2); + } + + #[test] + fn linear_round_trip_keeps_structure() { + for s in [ + "x=(-b±√(b^2-4ac))/2a", + "∑_(i=1)^n▒i", + "a/b+c", + "E=mc^2", + "√(3&x)", + "├]a[┤", + "{█(x@y)┤", + "|x|+‖v‖", + "⏞(a+b)┴k", + "_1^n▒Y", + "sin^(−1)⁡x", + "lim┬(n→∞)⁡a_n", + "A⃗+x̂", + "▭(a)+¯(b)+▁(c)", + "(a│b)", + "E=mc^2#(1)", + ] { + let n = parse_linear(s); + let back = parse_linear(&to_linear(&n)); + assert_eq!(n, back, "{s} → {}", to_linear(&n)); + } + } + + //T1 + /// Deepest nesting of `a` (a leaf counts 1), without recursion. + fn depth_of(a: &[MNode]) -> usize { + let mut best = 0; + let mut stack: Vec<(&MNode, usize)> = a.iter().map(|n| (n, 1)).collect(); + while let Some((n, d)) = stack.pop() { + best = best.max(d); + each_arg(n, &mut |a| stack.extend(a.iter().map(|c| (c, d + 1)))); + } + best + } + + /// Run `f` on a thread with a stack far below the 8 MB of a main thread (#1456). + fn on_small_stack(f: impl FnOnce() + Send + 'static) { + std::thread::Builder::new().stack_size(512 * 1024).spawn(f).unwrap().join().unwrap(); + } + + #[test] + fn deeply_chained_input_stays_shallow() { + on_small_stack(|| { + let cases: Vec<(&str, Arg)> = vec![ + ("x^1^1…", parse_linear(&format!("x{}", "^1".repeat(9999)))), + ("a/a/a…", parse_linear(&format!("a{}", "/a".repeat(9999)))), + ("accents", parse_linear(&format!("x{}", "\u{302}".repeat(9999)))), + ("limits", parse_linear(&format!("x{}", "┬a".repeat(9000)))), + ("(a b)^1^1…", parse_linear(&format!("(a b){}", "^1".repeat(9000)))), + ("latex x^1^1…", crate::math_latex::parse_latex(&format!("x{}", "^1".repeat(9999)))), + ("latex \\sum…", crate::math_latex::parse_latex(&"\\sum".repeat(5000))), + ("latex \\sin x^1…", crate::math_latex::parse_latex(&format!("\\sin x{}", "^1".repeat(9000)))), + ]; + for (name, n) in cases { + assert!(!n.is_empty(), "{name}"); + assert!(depth_of(&n) <= 70, "{name}: depth {}", depth_of(&n)); + let copy = n.clone(); + assert_eq!(copy, n, "{name}"); + let _ = to_linear(&n); + let _ = crate::math_latex::to_latex(&n); + let json = serde_json::to_string(&n).unwrap(); + let back: Arg = serde_json::from_str(&json).unwrap(); + assert_eq!(back, n, "{name}"); + } + }); + } + + #[test] + fn ordinary_nesting_is_still_built() { + // Well below the cap: scripts, fractions and operators still wrap. + let n = parse_linear(&format!("x{}", "^1".repeat(10))); + assert_eq!(depth_of(&n), 11, "{n:#?}"); + let n = crate::math_latex::parse_latex(r"\sum_{i}\sum_{j}a_{ij}"); + assert!(matches!(&n[0], MNode::Nary { e, .. } if matches!(e.first(), Some(MNode::Nary { .. }))), "{n:#?}"); + } + + //T2 + #[test] + fn latex_text_escapes_what_latex_reads_as_markup() { + for text in ["a}b\\c", "{x}", "50% of #1", "a_b&c$d~e^f", "\\", "\\alpha", "\\{"] { + let n = vec![MNode::Run(MRun { text: text.into(), nor: true, sty: Some(MSty::Plain), ..Default::default() })]; + let tex = crate::math_latex::to_latex(&n); + assert_eq!(crate::math_latex::parse_latex(&tex), n, "{text:?} → {tex}"); + } + let n = vec![MNode::Run(MRun::new("a\\b"))]; + assert_eq!(crate::math_latex::parse_latex(&crate::math_latex::to_latex(&n)), n); + } + + //T3 + #[test] + fn latex_runs_merge_inside_every_structure() { + use crate::math_latex::parse_latex; + for (tex, lin) in [(r"\overline{ab}", "¯(ab)"), (r"\underline{ab}", "▁(ab)"), (r"\boxed{ab}", "▭(ab)"), (r"\phantom{ab}", "⟡(ab)")] { + assert_eq!(parse_latex(tex), parse_linear(lin), "{tex}"); + } + let n = parse_latex(r"\begin{matrix}a b&c d\\e f&g\end{matrix}"); + let MNode::Matrix { rows, .. } = &n[0] else { panic!("{n:#?}") }; + assert!(rows.iter().flatten().all(|c| c.len() == 1), "{rows:#?}"); + let n = parse_latex(r"\hat{ab}\underbrace{ab}\underset{ab}{cd}"); + let runs = |a: &Arg| a.iter().filter(|n| matches!(n, MNode::Run(_))).count(); + assert!(matches!(&n[0], MNode::Acc { e, .. } if runs(e) == 1), "{n:#?}"); + assert!(matches!(&n[1], MNode::GroupChr { e, .. } if runs(e) == 1), "{n:#?}"); + assert!(matches!(&n[2], MNode::Lim { e, lim, .. } if runs(e) == 1 && runs(lim) == 1), "{n:#?}"); + } + + #[test] + fn multi_letter_scripts_round_trip() { + // Word for Mac 16.113.4 (#1609): a script is the whole run up to a space or operator, and Word's + // Linear format shows it bare (`V_dd`); the parenthesised form reads back identically. + let script = |kind, sub: &str, sup: &str| MNode::Script { kind, base: vec![run("V")], sub: parse_linear(sub), sup: parse_linear(sup) }; + for n in [ + vec![script(ScriptKind::Sub, "dd", "")], + vec![script(ScriptKind::Sup, "", "ab")], + vec![script(ScriptKind::SubSup, "in", "2")], + vec![MNode::Nary { + chr: '∑', + lim_loc: None, + grow: false, + sub_hide: false, + sup_hide: false, + sub: vec![run("ij")], + sup: vec![run("n")], + e: vec![run("x")], + }], + vec![MNode::Lim { upper: false, e: vec![run("⟶")], lim: vec![run("yields")] }], + ] { + assert_eq!(parse_linear(&to_linear(&n)), n, "{}", to_linear(&n)); + } + // Numbers and single letters stay bare. + assert_eq!(to_linear(&[script(ScriptKind::SubSup, "10", "2.5")]), "V_10^2.5"); + assert_eq!(to_linear(&[script(ScriptKind::Sub, "d", "")]), "V_d"); + assert_eq!(to_linear(&[script(ScriptKind::Sub, "dd", "")]), "V_dd"); + assert_eq!(to_linear(&[script(ScriptKind::Sup, "", "ab")]), "V^ab"); + } + + #[test] + fn multi_letter_script_operands_follow_word() { + // #1609, Word for Mac 16.113.4: `V_dd` and `V_(dd)` build up the same; `dd` is all subscript. + let sub_dd = MNode::Script { kind: ScriptKind::Sub, base: vec![run("V")], sub: vec![run("dd")], sup: vec![] }; + assert_eq!(parse_linear("V_dd"), vec![sub_dd.clone()]); + assert_eq!(parse_linear("V_(dd)"), vec![sub_dd]); + let sup_ab = MNode::Script { kind: ScriptKind::Sup, base: vec![run("x")], sub: vec![], sup: vec![run("ab")] }; + assert_eq!(parse_linear("x^ab"), vec![sup_ab.clone()]); + assert_eq!(parse_linear("x^(ab)"), vec![sup_ab]); + // Delimiters still end the operand. + let both = MNode::Script { kind: ScriptKind::SubSup, base: vec![run("x")], sub: vec![run("i")], sup: vec![run("2")] }; + assert_eq!(parse_linear("x_i^2"), vec![both]); + let a_i = MNode::Script { kind: ScriptKind::Sub, base: vec![run("a")], sub: vec![run("i")], sup: vec![] }; + assert_eq!(parse_linear("a_i b"), vec![a_i, run("b")]); + let both2 = MNode::Script { kind: ScriptKind::SubSup, base: vec![run("x")], sub: vec![run("ij")], sup: vec![run("kl")] }; + assert_eq!(parse_linear("x_ij^kl"), vec![both2]); + // Round trip is Word's bare form. + assert_eq!(to_linear(&parse_linear("V_(dd)")), "V_dd"); + } + + #[test] + fn a_bare_script_does_not_absorb_what_follows() { + // #1609 review: `x_i` then `y` must not read back as x with subscript `iy`. + let sc = + |kind, base: &str, sub: &str, sup: &str| MNode::Script { kind, base: vec![run(base)], sub: parse_linear(sub), sup: parse_linear(sup) }; + let sin_x = MNode::Func { name: vec![MNode::Run(MRun::plain("sin"))], e: vec![run("x")] }; + let lim = MNode::Lim { upper: false, e: vec![run("a")], lim: vec![run("n")] }; + for n in [ + vec![sc(ScriptKind::Sub, "x", "i", ""), run("y")], + vec![sc(ScriptKind::Sub, "a", "i", ""), sc(ScriptKind::Sub, "b", "j", "")], + vec![sc(ScriptKind::Sup, "x", "", "2"), run("y")], + vec![sc(ScriptKind::Sup, "x", "", "2"), run("3")], + vec![sc(ScriptKind::Sub, "x", "i", ""), sin_x], + vec![lim.clone(), run("y")], + vec![sc(ScriptKind::Sub, "x", "ab", ""), run("y")], + vec![sc(ScriptKind::Sub, "x", "i", ""), run(".5")], + ] { + let lin = to_linear(&n); + assert_eq!(parse_linear(&lin), n, "{lin}"); + } + assert_eq!(to_linear(&[sc(ScriptKind::Sub, "x", "i", ""), run("y")]), "x_i y"); + // Nothing extra when the script already ends in a bracket or a symbol follows. + assert_eq!(to_linear(&[sc(ScriptKind::Sub, "x", "i", ""), run("+")]), "x_i+"); + } + + #[test] + fn a_function_name_in_a_script_stays_upright() { + // Word for Mac (#1609): `x_max` and `x_(max)` both give an upright function name. + let up = vec![MNode::Script { kind: ScriptKind::Sub, base: vec![run("x")], sub: vec![MNode::Run(MRun::plain("max"))], sup: vec![] }]; + assert_eq!(parse_linear("x_max"), up); + assert_eq!(parse_linear("x_(max)"), up); + assert_eq!(parse_linear(&to_linear(&up)), up, "{}", to_linear(&up)); + // Other upright text is not a function name: it keeps its parentheses. + let other = vec![MNode::Script { kind: ScriptKind::Sub, base: vec![run("x")], sub: vec![MNode::Run(MRun::plain("ab"))], sup: vec![] }]; + assert_eq!(to_linear(&other), "x_(ab)"); + } + + #[test] + fn digits_then_letters_continue_a_script() { + // Word for Mac (#1609): a script runs to a space or operator, so `x_2a` is subscript "2a". + let sub = |t: &str| vec![MNode::Script { kind: ScriptKind::Sub, base: vec![run("x")], sub: vec![run(t)], sup: vec![] }]; + assert_eq!(parse_linear("x_2a"), sub("2a")); + assert_eq!(parse_linear("x_a2"), sub("a2")); + assert_eq!(parse_linear("x_αβ"), sub("αβ")); + assert_eq!(parse_linear("x_10"), sub("10")); + assert_eq!(parse_linear("x_2.5"), sub("2.5")); + assert_eq!(to_linear(&sub("2a")), "x_2a"); + assert_eq!(parse_linear(&to_linear(&sub("2a"))), sub("2a")); + } + + #[test] + fn hostile_linear_never_panics() { + for s in ["", "/", "^", "_", "√", "∑", "((((", "))))", "■(", "█(@@&&", "a/", "/b", "^^^__", "√(&)", "∫_^▒", "lim_", "sin"] { + let _ = to_linear(&parse_linear(s)); + } + let deep = "(".repeat(5000) + &")".repeat(5000); + let _ = parse_linear(&deep); + let deep = "√".repeat(3000); + let _ = parse_linear(&deep); + } + + #[test] + fn a_long_run_of_letters_parses_in_linear_time() { + // Each letter that doesn't start a function name used to rescan (and copy) the rest of + // the run, so a 20,000-letter equation did 200 million steps. (No wall-clock assert: a + // loaded runner would fail it; a regression shows as a slow test.) + for _ in 0..5 { + let e = parse_linear(&"x".repeat(30_000)); + assert!(matches!(e.as_slice(), [MNode::Run(r)] if r.text.len() == 20_000), "{:?}", e.len()); + } + // Function names are still found at the start of a run, and only as whole runs. + assert!(matches!(parse_linear("sin x").as_slice(), [MNode::Func { .. }])); + assert!(matches!(parse_linear("arcsin x").as_slice(), [MNode::Func { .. }])); + assert!(matches!(parse_linear("sinx").as_slice(), [MNode::Run(_)])); + assert!(matches!(parse_linear("arcsinhx").as_slice(), [MNode::Run(_)])); + } +} diff --git a/crates/math/src/math_latex.rs b/crates/math/src/math_latex.rs new file mode 100644 index 000000000..24c0d5541 --- /dev/null +++ b/crates/math/src/math_latex.rs @@ -0,0 +1,1316 @@ +//! LaTeX ↔ math tree (Word's LaTeX equation input and conversion). +//! +//! Input covers the commands people type in equations: `\frac`, `\sqrt[n]{}`, scripts, big +//! operators with limits, `\left…\middle…\right`, matrix and `cases`/`aligned` environments, +//! accents, `\overbrace`/`\underbrace`, `\text`/`\mathrm`/`\mathbf`/`\mathbb`…, function names, +//! spacing and every named symbol in [`crate::math_symbols`]. Unknown commands stay as text. + +use crate::math::{ + Arg, ColJc, FracKind, MAX_DEPTH, MNode, MRun, MScr, MSty, ScriptKind, WRAP_DEPTH, any_too_deep, is_nary_char, math_class, merge_runs, too_deep, +}; +use crate::math_linear::{FUNCTION_NAMES, map_args}; +use crate::math_symbols::{name_of, symbol}; + +#[derive(Clone, Debug, PartialEq)] +enum Tok { + Cmd(String), + Open, + Close, + Sup, + Sub, + Amp, + Row, + Ch(char), +} + +/// Commands whose `{…}` argument is text, where spaces are part of the content. +const TEXT_COMMANDS: &[&str] = &["text", "textrm", "mbox", "hbox", "textnormal", "textbf", "textit", "emph", "textsf"]; + +fn tokenize(s: &str) -> Vec { + let cs: Vec = s.chars().take(20_000).collect(); + let mut out = Vec::new(); + let mut i = 0; + // A text command was just read: its `{` starts text, where spaces count (#448). + let mut text_next = false; + // Brace depth inside a text argument. + let mut text_depth: Option = None; + while let Some(&c) = cs.get(i) { + i += 1; + if text_depth.is_some() && matches!(c, ' ' | '\t' | '\n' | '\r') { + // A run of white space is one space, as in LaTeX. + if out.last() != Some(&Tok::Ch(' ')) { + out.push(Tok::Ch(' ')); + } + continue; + } + let was_text_next = std::mem::take(&mut text_next); + match c { + '\\' => { + let start = i; + while cs.get(i).is_some_and(char::is_ascii_alphabetic) { + i += 1; + } + if i == start { + match cs.get(i) { + Some('\\') => { + i += 1; + out.push(Tok::Row); + } + Some(&c) => { + i += 1; + out.push(Tok::Cmd(c.to_string())); + } + None => {} + } + } else { + let name: String = cs.get(start..i).unwrap_or(&[]).iter().collect(); + text_next = text_depth.is_none() && TEXT_COMMANDS.contains(&name.as_str()); + out.push(Tok::Cmd(name)); + } + } + '{' => { + text_depth = match text_depth { + Some(d) => Some(d.saturating_add(1)), + None if was_text_next => Some(0), + None => None, + }; + out.push(Tok::Open); + } + '}' => { + text_depth = match text_depth { + Some(0) | None => None, + Some(d) => Some(d.saturating_sub(1)), + }; + out.push(Tok::Close); + } + '^' => out.push(Tok::Sup), + '_' => out.push(Tok::Sub), + '&' => out.push(Tok::Amp), + // White space between a text command and its `{` doesn't end the wait. + ' ' | '\t' | '\n' | '\r' => text_next = was_text_next, + '~' => out.push(Tok::Ch('\u{A0}')), + c => out.push(Tok::Ch(c)), + } + } + out +} + +/// Parse LaTeX math into nodes. Never fails. +pub fn parse_latex(s: &str) -> Arg { + let mut p = Lp { t: tokenize(s), i: 0, depth: 0 }; + let mut out = Vec::new(); + while p.i < p.t.len() { + out.extend(p.seq(false)); + // A stray `}` or `&`/`\\` at the top level. + match p.t.get(p.i) { + Some(Tok::Amp) => out.push(run("&")), + Some(Tok::Row) => {} + Some(Tok::Close) => {} + _ => {} + } + p.i += 1; + } + let out = merge_runs(out); + if out.iter().any(|n| matches!(n, MNode::Run(r) if !r.nor && r.text.contains('#'))) { + return vec![MNode::EqArr { rows: vec![out] }]; + } + out +} + +fn run(t: &str) -> MNode { + MNode::Run(MRun::new(t)) +} + +struct Lp { + t: Vec, + i: usize, + depth: usize, +} + +impl Lp { + fn peek(&self) -> Option<&Tok> { + self.t.get(self.i) + } + + /// A sequence up to `}` (in a group), `&`, `\\`, `\right`, `\middle` or `\end`. + fn seq(&mut self, in_group: bool) -> Arg { + self.depth += 1; + let mut out: Arg = Vec::new(); + if self.depth > MAX_DEPTH { + self.i = self.t.len(); + self.depth -= 1; + return out; + } + while let Some(tok) = self.peek().cloned() { + match tok { + Tok::Close if in_group => break, + Tok::Close | Tok::Amp | Tok::Row => break, + Tok::Cmd(ref c) if matches!(c.as_str(), "right" | "middle" | "end") => break, + Tok::Sup | Tok::Sub => { + self.i += 1; + let s = self.arg(); + if out.last().is_some_and(too_deep) { + // Too deep to wrap (`x^1^1^1…`): the operator is dropped, the script kept. + out.extend(s); + } else { + let base = out.pop(); + out.push(script(base, tok == Tok::Sup, s)); + } + } + Tok::Cmd(ref c) if c == "limits" || c == "nolimits" || c == "displaystyle" || c == "textstyle" => { + self.i += 1; + if c == "nolimits" + && let Some(MNode::Nary { lim_loc, .. }) = out.last_mut() + { + *lim_loc = Some(crate::math::LimLoc::SubSup); + } + if c == "limits" + && let Some(MNode::Nary { lim_loc, .. }) = out.last_mut() + { + *lim_loc = Some(crate::math::LimLoc::UndOvr); + } + } + _ => { + let a = self.atom(); + out.extend(a); + } + } + } + self.depth -= 1; + // Big operators take the following term as their operand. + nary_operands(out, self.depth) + } + + /// A command argument: a `{group}` or one token. + fn arg(&mut self) -> Arg { + match self.peek() { + Some(Tok::Open) => { + self.i += 1; + let g = self.seq(true); + if self.peek() == Some(&Tok::Close) { + self.i += 1; + } + g + } + Some(_) => self.atom(), + None => Vec::new(), + } + } + + /// `[optional]` argument. + fn opt(&mut self) -> Option { + if self.peek() != Some(&Tok::Ch('[')) { + return None; + } + self.i += 1; + let mut toks = Vec::new(); + let mut level = 0i32; + while let Some(t) = self.peek().cloned() { + self.i += 1; + match t { + Tok::Ch(']') if level == 0 => break, + Tok::Open => level += 1, + Tok::Close => level -= 1, + _ => {} + } + toks.push(t); + } + let mut p = Lp { t: toks, i: 0, depth: self.depth }; + Some(p.seq(false)) + } + + /// The text of a `{…}` argument, verbatim. + fn raw_arg(&mut self) -> String { + let mut s = String::new(); + if self.peek() != Some(&Tok::Open) { + if let Some(Tok::Ch(c)) = self.peek().cloned() { + self.i += 1; + s.push(c); + } + return s; + } + self.i += 1; + let mut level = 0i32; + // The previous token was a control word (`\backslash{}`: the empty braces end its name). + let mut after_word = false; + while let Some(t) = self.peek().cloned() { + self.i += 1; + let was_word = std::mem::replace(&mut after_word, matches!(&t, Tok::Cmd(c) if c.chars().all(|c| c.is_ascii_alphabetic()))); + match t { + Tok::Close if level == 0 => break, + Tok::Open if was_word && self.peek() == Some(&Tok::Close) => self.i += 1, + Tok::Open => { + level += 1; + s.push('{'); + } + Tok::Close => { + level -= 1; + s.push('}'); + } + Tok::Ch(c) => s.push(c), + Tok::Cmd(c) => { + if c.chars().all(|c| c.is_ascii_alphabetic()) { + match symbol(&c) { + Some(sym) => s.push(sym), + None => s.push_str(&c), + } + } else { + s.push_str(&c); + } + if c == " " { + s.push(' '); + } + } + Tok::Sup => s.push('^'), + Tok::Sub => s.push('_'), + Tok::Amp => s.push('&'), + Tok::Row => s.push('\n'), + } + } + s + } + + /// A delimiter after `\left`, `\right`, `\middle`, `\big…`. + fn delim(&mut self) -> Option { + let t = self.peek().cloned()?; + self.i += 1; + match t { + Tok::Ch('.') => None, + Tok::Ch(c) => Some(c), + Tok::Cmd(c) => match c.as_str() { + "{" => Some('{'), + "}" => Some('}'), + "|" => Some('‖'), + other => symbol(other), + }, + _ => None, + } + } + + fn atom(&mut self) -> Arg { + if self.depth > MAX_DEPTH { + self.i = self.t.len(); + return Vec::new(); + } + self.depth += 1; + let out = self.atom_inner(); + self.depth -= 1; + out + } + + fn atom_inner(&mut self) -> Arg { + let Some(t) = self.peek().cloned() else { return Vec::new() }; + self.i += 1; + match t { + Tok::Open => { + let g = self.seq(true); + if self.peek() == Some(&Tok::Close) { + self.i += 1; + } + g + } + Tok::Ch(c) => vec![run(&c.to_string())], + Tok::Close | Tok::Amp | Tok::Row | Tok::Sup | Tok::Sub => Vec::new(), + Tok::Cmd(c) => self.command(&c), + } + } + + fn command(&mut self, c: &str) -> Arg { + let styled = |a: Arg, sty: Option, scr: MScr, nor: bool| -> Arg { restyle(a, sty, scr, nor) }; + let one = |n: MNode| vec![n]; + match c { + "frac" | "dfrac" | "tfrac" | "cfrac" => { + let num = self.arg(); + let den = self.arg(); + one(MNode::Frac { kind: FracKind::Bar, num, den }) + } + "genfrac" => { + let beg = delim_arg(&self.arg()); + let end = delim_arg(&self.arg()); + let thickness = self.arg(); + let _style = self.arg(); + let num = self.arg(); + let den = self.arg(); + let kind = if is_zero_length(&thickness) { FracKind::NoBar } else { FracKind::Bar }; + let frac = MNode::Frac { kind, num, den }; + if beg.is_none() && end.is_none() { + one(frac) + } else { + one(MNode::Delim { beg, end, sep: None, grow: true, shp_match: false, elems: vec![vec![frac]] }) + } + } + "binom" | "dbinom" | "tbinom" => { + let n = self.arg(); + let k = self.arg(); + one(MNode::Delim { + beg: Some('('), + end: Some(')'), + sep: None, + grow: true, + shp_match: false, + elems: vec![vec![MNode::Frac { kind: FracKind::NoBar, num: n, den: k }]], + }) + } + "sqrt" => { + let deg = self.opt().unwrap_or_default(); + let e = self.arg(); + one(MNode::Rad { deg_hide: deg.is_empty(), deg, e }) + } + "left" => { + let beg = self.delim(); + let mut elems = vec![self.seq(false)]; + let mut sep = None; + let mut end = None; + while let Some(Tok::Cmd(k)) = self.peek().cloned() { + self.i += 1; + if k == "middle" { + sep = self.delim().or(Some('|')); + elems.push(self.seq(false)); + } else { + if k == "right" { + end = self.delim(); + } + break; + } + } + one(MNode::Delim { beg, end, sep, grow: true, shp_match: false, elems }) + } + "bigl" | "Bigl" | "biggl" | "Biggl" | "bigr" | "Bigr" | "biggr" | "Biggr" | "big" | "Big" | "bigg" | "Bigg" => { + self.delim().map(|d| vec![run(&d.to_string())]).unwrap_or_default() + } + "begin" => { + let env = self.raw_arg(); + self.environment(env.trim()) + } + "text" | "textrm" | "mbox" | "hbox" | "textnormal" => { + let t = self.raw_arg(); + one(MNode::Run(MRun { text: t, nor: true, sty: Some(MSty::Plain), ..Default::default() })) + } + "textbf" => { + let t = self.raw_arg(); + one(MNode::Run(MRun { text: t, nor: true, sty: Some(MSty::Bold), ..Default::default() })) + } + "textit" | "emph" => { + let t = self.raw_arg(); + one(MNode::Run(MRun { text: t, nor: true, sty: Some(MSty::Italic), ..Default::default() })) + } + "textsf" => { + let t = self.raw_arg(); + one(MNode::Run(MRun { text: t, nor: true, sty: Some(MSty::Plain), scr: MScr::SansSerif, ..Default::default() })) + } + // MathLive's absolute value, upright constants and differential. + "abs" => { + let e = self.arg(); + one(MNode::Delim { beg: Some('|'), end: Some('|'), sep: None, grow: true, shp_match: false, elems: vec![e] }) + } + "differentialD" => vec![run("d")], + "exponentialE" => vec![MNode::Run(MRun::plain("e"))], + "imaginaryI" => vec![MNode::Run(MRun::plain("i"))], + "operatorname" => { + let starred = self.peek() == Some(&Tok::Ch('*')); + if starred { + self.i += 1; + } + let t = self.raw_arg(); + let name = vec![MNode::Run(MRun::plain(t))]; + if starred && self.peek() == Some(&Tok::Sub) { + self.i += 1; + let lim = self.arg(); + vec![MNode::Lim { upper: false, e: name, lim }] + } else { + self.apply(name) + } + } + "tag" => { + let starred = self.peek() == Some(&Tok::Ch('*')); + if starred { + self.i += 1; + } + let t = self.raw_arg(); + let num_str = if starred { format!("#{t}") } else { format!("# ({t})") }; + let mut r = MRun::new(num_str); + r.lit = false; + vec![MNode::Run(r)] + } + "mathrm" | "rm" => { + let a = self.arg(); + styled(a, Some(MSty::Plain), MScr::Roman, false) + } + "mathbf" | "bf" => { + let a = self.arg(); + styled(a, Some(MSty::Bold), MScr::Roman, false) + } + "mathnormal" => self.arg(), + "mathit" => { + let a = self.arg(); + styled(a, Some(MSty::Italic), MScr::Roman, false) + } + "boldsymbol" | "bm" => { + let a = self.arg(); + styled(a, Some(MSty::BoldItalic), MScr::Roman, false) + } + "mathbb" => { + let a = self.arg(); + styled(a, None, MScr::DoubleStruck, false) + } + "mathcal" | "mathscr" => { + let a = self.arg(); + styled(a, None, MScr::Script, false) + } + "mathfrak" => { + let a = self.arg(); + styled(a, None, MScr::Fraktur, false) + } + "mathsf" => { + let a = self.arg(); + styled(a, None, MScr::SansSerif, false) + } + "mathtt" => { + let a = self.arg(); + styled(a, None, MScr::Monospace, false) + } + "overline" => one(MNode::Bar { top: true, e: self.arg() }), + "underline" => one(MNode::Bar { top: false, e: self.arg() }), + "boxed" | "fbox" => one(MNode::BorderBox { hide: [false; 4], strike: [false; 4], e: self.arg() }), + "phantom" => one(MNode::Phant { show: false, zero_wid: false, zero_asc: false, zero_desc: false, e: self.arg() }), + "overbrace" | "underbrace" | "overparen" | "underparen" | "overbracket" | "underbracket" => { + let top = c.starts_with("over"); + let chr = match c { + "overbrace" => '⏞', + "underbrace" => '⏟', + "overparen" => '⏜', + "underparen" => '⏝', + "overbracket" => '⎴', + _ => '⎵', + }; + let e = self.arg(); + let g = MNode::GroupChr { chr, top, e }; + let want = if top { Tok::Sup } else { Tok::Sub }; + if self.peek() == Some(&want) { + self.i += 1; + let lim = self.arg(); + one(MNode::Lim { upper: top, e: vec![g], lim }) + } else { + one(g) + } + } + "underleftarrow" | "underrightarrow" | "underleftrightarrow" => { + let chr = match c { + "underleftarrow" => '←', + "underrightarrow" => '→', + _ => '↔', + }; + one(MNode::GroupChr { chr, top: false, e: self.arg() }) + } + "stackrel" | "overset" => { + let over = self.arg(); + let base = self.arg(); + one(MNode::Lim { upper: true, e: base, lim: over }) + } + "underset" => { + let under = self.arg(); + let base = self.arg(); + one(MNode::Lim { upper: false, e: base, lim: under }) + } + "hat" | "widehat" | "tilde" | "widetilde" | "dot" | "ddot" | "dddot" | "check" | "breve" | "acute" | "grave" | "vec" | "bar" + | "overrightarrow" | "overleftarrow" | "overleftrightarrow" | "mathring" => { + let chr = match c { + "hat" | "widehat" => '\u{302}', + "tilde" | "widetilde" => '\u{303}', + "dot" => '\u{307}', + "ddot" => '\u{308}', + "dddot" => '\u{20DB}', + "check" => '\u{30C}', + "breve" => '\u{306}', + "acute" => '\u{301}', + "grave" => '\u{300}', + "bar" => '\u{305}', + "overleftarrow" => '\u{20D6}', + "overleftrightarrow" => '\u{20E1}', + "mathring" => '\u{30A}', + _ => '\u{20D7}', + }; + one(MNode::Acc { chr, e: self.arg() }) + } + "," | "thinspace" => vec![run("\u{2009}")], + ":" | ">" | "medspace" => vec![run("\u{205F}")], + ";" | "thickspace" => vec![run("\u{2005}")], + "!" | "negthinspace" => Vec::new(), + " " => vec![run(" ")], + "qquad" => vec![run("\u{2003}\u{2003}")], + "{" | "}" | "%" | "$" | "#" | "&" | "_" => { + // Escaped characters (a literal `#` must not number the equation). + let mut r = MRun::new(c); + r.lit = c == "#"; + vec![MNode::Run(r)] + } + "|" => vec![run("‖")], + name if FUNCTION_NAMES.contains(&name) => { + let plain = vec![MNode::Run(MRun::plain(name))]; + let limits = matches!(name, "lim" | "liminf" | "limsup" | "max" | "min" | "sup" | "inf" | "det" | "gcd" | "Pr"); + let named = if limits && self.peek() == Some(&Tok::Sub) { + self.i += 1; + let lim = self.arg(); + vec![MNode::Lim { upper: false, e: plain, lim }] + } else if matches!(self.peek(), Some(Tok::Sup) | Some(Tok::Sub)) { + let sup = self.peek() == Some(&Tok::Sup); + self.i += 1; + let s = self.arg(); + vec![script(Some(MNode::Run(MRun::plain(name))), sup, s)] + } else { + plain + }; + self.apply(named) + } + name => match symbol(name) { + Some(ch) if is_nary_char(ch) => vec![MNode::Nary { + chr: ch, + lim_loc: None, + grow: false, + sub_hide: true, + sup_hide: true, + sub: Vec::new(), + sup: Vec::new(), + e: Vec::new(), + }], + Some(ch) => vec![run(&ch.to_string())], + None => vec![run(&format!("\\{name}"))], + }, + } + } + + /// A function name applied to the next atom (with its scripts). + fn apply(&mut self, name: Arg) -> Arg { + let mut e = self.atom(); + while let Some(t @ (Tok::Sup | Tok::Sub)) = self.peek().cloned() { + self.i += 1; + let s = self.arg(); + if any_too_deep(&e) { + e.extend(s); + continue; + } + let base = if e.len() == 1 { e.pop() } else { Some(group(std::mem::take(&mut e))) }; + e.push(script(base, t == Tok::Sup, s)); + } + if e.is_empty() { + return name; + } + vec![MNode::Func { name, e }] + } + + fn environment(&mut self, env: &str) -> Arg { + let base = env.trim_end_matches('*'); + let mut col_jc = Vec::new(); + if base == "array" || base == "tabular" { + let _ = self.opt(); + let spec = self.raw_arg(); + for ch in spec.chars() { + match ch { + 'l' | 'L' => col_jc.push(ColJc::Left), + 'r' | 'R' => col_jc.push(ColJc::Right), + 'c' | 'C' => col_jc.push(ColJc::Center), + _ => {} + } + } + } else if base == "aligned" { + let _ = self.opt(); + } + // Rows of `&`-separated cells up to `\end{…}`. + let mut rows: Vec> = vec![vec![]]; + loop { + let cell = self.seq(false); + if let Some(r) = rows.last_mut() { + r.push(cell); + } + match self.peek().cloned() { + Some(Tok::Amp) => self.i += 1, + Some(Tok::Row) => { + self.i += 1; + rows.push(vec![]); + } + Some(Tok::Cmd(k)) if k == "end" => { + self.i += 1; + let _ = self.raw_arg(); + break; + } + Some(Tok::Close) => self.i += 1, + Some(_) => self.i += 1, + None => break, + } + } + // A trailing `\\` leaves an empty last row. + if rows.len() > 1 && rows.last().is_some_and(|r| r.iter().all(|c| c.is_empty())) { + rows.pop(); + } + let delims = match base { + "pmatrix" => Some((Some('('), Some(')'))), + "bmatrix" => Some((Some('['), Some(']'))), + "Bmatrix" => Some((Some('{'), Some('}'))), + "vmatrix" => Some((Some('|'), Some('|'))), + "Vmatrix" => Some((Some('‖'), Some('‖'))), + _ => None, + }; + let wrap = |inner: MNode, beg: Option, end: Option| MNode::Delim { + beg, + end, + sep: None, + grow: true, + shp_match: false, + elems: vec![vec![inner]], + }; + match base { + "matrix" | "pmatrix" | "bmatrix" | "Bmatrix" | "vmatrix" | "Vmatrix" | "smallmatrix" | "array" | "tabular" => { + let m = MNode::Matrix { rows, col_jc }; + match delims { + Some((b, e)) => vec![wrap(m, b, e)], + None => vec![m], + } + } + "cases" | "dcases" => { + let eq = MNode::EqArr { rows: rows.into_iter().map(join_cells).collect() }; + vec![wrap(eq, Some('{'), None)] + } + "rcases" => { + let eq = MNode::EqArr { rows: rows.into_iter().map(join_cells).collect() }; + vec![wrap(eq, None, Some('}'))] + } + _ => vec![MNode::EqArr { rows: rows.into_iter().map(join_cells).collect() }], + } + } +} + +/// Cells of an aligned row joined with `&` alignment marks. +fn join_cells(cells: Vec) -> Arg { + let mut out = Vec::new(); + for (i, c) in cells.into_iter().enumerate() { + if i > 0 { + out.push(run("&")); + } + out.extend(c); + } + merge_runs(out) +} + +fn group(a: Arg) -> MNode { + MNode::Delim { beg: None, end: None, sep: None, grow: true, shp_match: false, elems: vec![a] } +} + +fn script(base: Option, sup: bool, s: Arg) -> MNode { + match base { + Some(MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup: sp, e }) if e.is_empty() => { + if sup { + MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide: false, sub, sup: s, e } + } else { + MNode::Nary { chr, lim_loc, grow, sub_hide: false, sup_hide, sub: s, sup: sp, e } + } + } + Some(MNode::Script { kind: ScriptKind::Sub, base, sub, .. }) if sup => MNode::Script { kind: ScriptKind::SubSup, base, sub, sup: s }, + Some(MNode::Script { kind: ScriptKind::Sup, base, sup: sp, .. }) if !sup => MNode::Script { kind: ScriptKind::SubSup, base, sub: s, sup: sp }, + b => { + let base = b.map(|b| vec![b]).unwrap_or_default(); + if sup { + MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s } + } else { + MNode::Script { kind: ScriptKind::Sub, base, sub: s, sup: Vec::new() } + } + } + } +} + +/// Big operators without an operand take the atoms after them up to a relation or binary operator. +/// `depth` is how deep the operators already sit; past [`WRAP_DEPTH`] they stay without operand +/// (`\sum\sum\sum…` must not nest once per operator). +fn nary_operands(a: Arg, depth: usize) -> Arg { + let mut out: Arg = Vec::with_capacity(a.len()); + let mut it = a.into_iter().peekable(); + while let Some(n) = it.next() { + match n { + MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e } if e.is_empty() && depth < WRAP_DEPTH => { + let mut body = Vec::new(); + while let Some(next) = it.peek() { + let stop = match next { + MNode::Run(r) => r.text.chars().next().is_some_and(|c| { + matches!(math_class(c), crate::math::MClass::Rel | crate::math::MClass::Bin | crate::math::MClass::Punct) || c == '&' + }), + _ => false, + }; + if stop { + break; + } + if let Some(x) = it.next() { + body.push(x); + } + } + let body = merge_runs(nary_operands(body, depth + 1)); + if any_too_deep(&body) { + // No room to wrap the operand: it follows the operator. + out.push(MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e }); + out.extend(body); + } else { + out.push(MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e: body }); + } + } + other => out.push(other), + } + } + out +} + +/// Set a style on every run inside. +fn restyle(a: Arg, sty: Option, scr: MScr, nor: bool) -> Arg { + a.into_iter() + .map(|n| match n { + MNode::Run(mut r) => { + if sty.is_some() { + r.sty = sty; + } + if scr != MScr::Roman { + r.scr = scr; + } + r.nor |= nor; + MNode::Run(r) + } + other => map_args(other, &|a| restyle(a, sty, scr, nor)), + }) + .collect() +} + +// --------------------------------------------------------------------------------------------- +// Out. + +/// The equation as LaTeX. +pub fn to_latex(nodes: &[MNode]) -> String { + let mut s = String::new(); + arg(nodes, &mut s, 0); + s.trim().to_string() +} + +fn arg(a: &[MNode], s: &mut String, depth: usize) { + if depth > MAX_DEPTH { + return; + } + for n in a { + node(n, s, depth + 1); + } +} + +fn braced(a: &[MNode], s: &mut String, depth: usize) { + s.push('{'); + arg(a, s, depth); + s.push('}'); +} + +fn chars(text: &str, s: &mut String) { + for c in text.chars() { + match c { + '{' | '}' | '%' | '$' | '#' | '&' | '_' => { + s.push('\\'); + s.push(c); + } + '\\' => s.push_str("\\backslash "), + '−' => s.push('-'), + c if c.is_ascii() => s.push(c), + c => match name_of(c) { + Some(n) if !matches!(n, "sqrt" | "matrix" | "of" | "above" | "below" | "box" | "rect") => { + s.push('\\'); + s.push_str(n); + s.push(' '); + } + _ => s.push(c), + }, + } + } +} + +/// Text inside `\text{…}`: only what LaTeX would read as markup is escaped. +fn text_chars(text: &str, s: &mut String) { + for c in text.chars() { + match c { + '{' | '}' | '%' | '$' | '#' | '&' | '_' | '~' => { + s.push('\\'); + s.push(c); + } + // `{}` ends the command name without adding a space (spaces count in text). + '\\' => s.push_str("\\backslash{}"), + c => s.push(c), + } + } +} + +/// The delimiter of a `\genfrac` argument: one character, or none for `{}` and anything else. +fn delim_arg(a: &[MNode]) -> Option { + let [MNode::Run(r)] = a else { return None }; + let mut cs = r.text.chars(); + match (cs.next(), cs.next()) { + (Some(c), None) if c != '.' => Some(c), + _ => None, + } +} + +/// Whether a `\genfrac` thickness is a zero length such as `0pt`, `0.0pt` or `0 em`. An empty +/// thickness means the default rule and anything that is not a plain number and unit is not zero. +fn is_zero_length(a: &[MNode]) -> bool { + let mut text = String::new(); + for n in a { + let MNode::Run(r) = n else { return false }; + text.extend(r.text.chars().filter(|c| !c.is_whitespace() && !matches!(c, '\u{2009}' | '\u{205F}' | '\u{2005}'))); + } + let number = text.trim_end_matches(|c: char| c.is_ascii_alphabetic()); + let unit = &text[number.len()..]; + !number.is_empty() + && matches!(unit, "pt" | "em" | "ex" | "mm" | "cm" | "in" | "bp" | "pc" | "sp" | "mu") + && number.parse::().is_ok_and(|v| v == 0.0) +} + +fn delim_tex(c: Option) -> String { + match c { + None => ".".into(), + Some('{') => "\\{".into(), + Some('}') => "\\}".into(), + Some('‖') => "\\|".into(), + Some(c) if c.is_ascii() => c.to_string(), + Some(c) => name_of(c).map(|n| format!("\\{n} ")).unwrap_or_else(|| c.to_string()), + } +} + +fn group_chr_tex(chr: char, top: bool) -> &'static str { + match chr { + '⏜' => "\\overparen", + '⏝' => "\\underparen", + '⎴' => "\\overbracket", + '⎵' => "\\underbracket", + _ if top => "\\overbrace", + _ => "\\underbrace", + } +} + +fn node(node: &MNode, output: &mut String, depth: usize) { + match node { + MNode::Run(run) => run_node(run, output), + MNode::Frac { kind, num, den } => fraction_node(*kind, num, den, output, depth), + MNode::Script { kind, base, sub, sup } => script_node(*kind, base, sub, sup, output, depth), + MNode::Rad { deg, deg_hide, e } => radical_node(deg, *deg_hide, e, output, depth), + MNode::Nary { .. } => nary_node(node, output, depth), + MNode::Delim { beg, end, sep, elems, .. } => delimiter_node(*beg, *end, *sep, elems, output, depth), + MNode::Func { name, e } => { + arg(name, output, depth); + braced(e, output, depth); + } + MNode::Lim { upper, e, lim } => limit_node(*upper, e, lim, output, depth), + MNode::Acc { chr, e } => accent_node(*chr, e, output, depth), + MNode::Bar { top, e } => { + output.push_str(if *top { "\\overline" } else { "\\underline" }); + braced(e, output, depth); + } + MNode::BorderBox { e, .. } => { + output.push_str("\\boxed"); + braced(e, output, depth); + } + MNode::Boxed { e } => braced(e, output, depth), + MNode::GroupChr { chr, top, e } => { + output.push_str(group_chr_tex(*chr, *top)); + braced(e, output, depth); + } + MNode::EqArr { rows } => equation_array_node(rows, output, depth), + MNode::Matrix { rows, .. } => matrix_node(rows, output, depth), + MNode::Phant { e, .. } => { + output.push_str("\\phantom"); + braced(e, output, depth); + } + } +} + +fn run_node(run: &MRun, output: &mut String) { + let (open, close) = if run.nor { + ("\\text{", "}") + } else { + match (run.sty, run.scr) { + (_, MScr::DoubleStruck) => ("\\mathbb{", "}"), + (_, MScr::Script) => ("\\mathcal{", "}"), + (_, MScr::Fraktur) => ("\\mathfrak{", "}"), + (_, MScr::SansSerif) => ("\\mathsf{", "}"), + (_, MScr::Monospace) => ("\\mathtt{", "}"), + (Some(MSty::Bold), _) => ("\\mathbf{", "}"), + (Some(MSty::BoldItalic), _) => ("\\boldsymbol{", "}"), + (Some(MSty::Plain), _) if run.text.chars().any(char::is_alphabetic) => { + if FUNCTION_NAMES.contains(&run.text.as_str()) { + output.push('\\'); + output.push_str(&run.text); + output.push(' '); + return; + } + ("\\mathrm{", "}") + } + _ => ("", ""), + } + }; + output.push_str(open); + if run.nor { + text_chars(&run.text, output) + } else { + chars(&run.text, output) + } + output.push_str(close); +} + +fn fraction_node(kind: FracKind, numerator: &[MNode], denominator: &[MNode], output: &mut String, depth: usize) { + match kind { + FracKind::NoBar => { + output.push_str("\\genfrac{}{}{0pt}{}"); + braced(numerator, output, depth); + braced(denominator, output, depth); + } + FracKind::Linear | FracKind::Skewed => { + braced(numerator, output, depth); + output.push('/'); + braced(denominator, output, depth); + } + FracKind::Bar => { + output.push_str("\\frac"); + braced(numerator, output, depth); + braced(denominator, output, depth); + } + } +} + +fn script_node(kind: ScriptKind, base: &[MNode], sub: &[MNode], sup: &[MNode], output: &mut String, depth: usize) { + if kind == ScriptKind::Pre { + output.push_str("{}_"); + braced(sub, output, depth); + output.push('^'); + braced(sup, output, depth); + braced(base, output, depth); + return; + } + // An operator name takes its scripts directly (`\sin^{2}`): in braces it would no longer apply + // to what follows it when read back. + match base { + [MNode::Run(r)] if is_function_name(r) => run_node(r, output), + _ => braced(base, output, depth), + } + if matches!(kind, ScriptKind::Sub | ScriptKind::SubSup) { + output.push('_'); + braced(sub, output, depth); + } + if matches!(kind, ScriptKind::Sup | ScriptKind::SubSup) { + output.push('^'); + braced(sup, output, depth); + } +} + +/// Is `r` an operator name the writer writes as a command (`\sin`, `\log`)? +fn is_function_name(r: &MRun) -> bool { + !r.nor && r.sty == Some(MSty::Plain) && r.scr == MScr::Roman && FUNCTION_NAMES.contains(&r.text.as_str()) +} + +fn radical_node(degree: &[MNode], degree_hidden: bool, expression: &[MNode], output: &mut String, depth: usize) { + output.push_str("\\sqrt"); + if !degree_hidden && !degree.is_empty() { + output.push('['); + arg(degree, output, depth); + output.push(']'); + } + braced(expression, output, depth); +} + +fn nary_node(node: &MNode, output: &mut String, depth: usize) { + let MNode::Nary { chr, lim_loc, sub_hide, sup_hide, sub, sup, e, .. } = node else { return }; + match name_of(*chr) { + Some(name) => { + output.push('\\'); + output.push_str(name); + } + None => output.push(*chr), + } + match lim_loc { + Some(crate::math::LimLoc::UndOvr) => output.push_str("\\limits"), + Some(crate::math::LimLoc::SubSup) if !crate::math::is_integral(*chr) => output.push_str("\\nolimits"), + _ => {} + } + if !sub_hide && !sub.is_empty() { + output.push('_'); + braced(sub, output, depth); + } + if !sup_hide && !sup.is_empty() { + output.push('^'); + braced(sup, output, depth); + } + output.push(' '); + braced(e, output, depth); +} + +fn delimiter_node(begin: Option, end: Option, separator: Option, elements: &[Arg], output: &mut String, depth: usize) { + output.push_str("\\left"); + output.push_str(&delim_tex(begin)); + let middle = separator.map(|c| format!("\\middle{}", delim_tex(Some(c)))).unwrap_or_else(|| "\\middle|".to_string()); + for (index, element) in elements.iter().enumerate() { + if index > 0 { + output.push_str(&middle); + } + arg(element, output, depth); + } + output.push_str("\\right"); + output.push_str(&delim_tex(end)); +} + +fn limit_node(upper: bool, expression: &[MNode], limit: &[MNode], output: &mut String, depth: usize) { + let simple = matches!(expression, [MNode::Run(run)] if run.sty == Some(MSty::Plain) && FUNCTION_NAMES.contains(&run.text.as_str())); + if simple && !upper { + arg(expression, output, depth); + output.push('_'); + braced(limit, output, depth); + } else if let [MNode::GroupChr { chr, top, e: inner }] = expression { + output.push_str(group_chr_tex(*chr, *top)); + braced(inner, output, depth); + output.push(if upper { '^' } else { '_' }); + braced(limit, output, depth); + } else { + output.push_str(if upper { "\\overset" } else { "\\underset" }); + braced(limit, output, depth); + braced(expression, output, depth); + } +} + +fn accent_node(character: char, expression: &[MNode], output: &mut String, depth: usize) { + let command = match character { + '\u{302}' => "hat", + '\u{303}' => "tilde", + '\u{307}' => "dot", + '\u{308}' => "ddot", + '\u{20DB}' => "dddot", + '\u{30C}' => "check", + '\u{306}' => "breve", + '\u{301}' => "acute", + '\u{300}' => "grave", + '\u{305}' | '\u{AF}' => "bar", + '\u{20D6}' => "overleftarrow", + '\u{20E1}' => "overleftrightarrow", + _ => "vec", + }; + output.push('\\'); + output.push_str(command); + braced(expression, output, depth); +} + +fn equation_array_node(rows: &[Arg], output: &mut String, depth: usize) { + if rows.len() == 1 + && let Some(row) = rows.first() + && crate::math::has_number_mark(row) + { + arg(row, output, depth); + return; + } + output.push_str("\\begin{aligned}"); + for (index, row) in rows.iter().enumerate() { + if index > 0 { + output.push_str("\\\\"); + } + for child_node in row { + match child_node { + MNode::Run(run) if !run.lit && run.text.contains('&') => { + for (index, part) in run.text.split('&').enumerate() { + if index > 0 { + output.push('&'); + } + let mut piece = run.clone(); + piece.text = part.to_string(); + run_node(&piece, output); + } + } + other => node(other, output, depth + 1), + } + } + } + output.push_str("\\end{aligned}"); +} + +fn matrix_node(rows: &[Vec], output: &mut String, depth: usize) { + output.push_str("\\begin{matrix}"); + for (row_index, row) in rows.iter().enumerate() { + if row_index > 0 { + output.push_str("\\\\"); + } + for (column, cell) in row.iter().enumerate() { + if column > 0 { + output.push('&'); + } + arg(cell, output, depth); + } + } + output.push_str("\\end{matrix}"); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::math::{LimLoc, MathJc}; + + #[test] + fn latex_structures() { + let n = parse_latex(r"x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}"); + assert_eq!(crate::math::to_linear(&n), "x=(-b±√(b^2-4ac))/2a"); + let n = parse_latex(r"\sum_{i=1}^{n} i^2 = \frac{n(n+1)(2n+1)}{6}"); + let MNode::Nary { chr, sub, sup, e, .. } = &n[0] else { panic!("{n:#?}") }; + assert_eq!((*chr, sub.len(), sup.len()), ('∑', 1, 1)); + assert!(matches!(e.first(), Some(MNode::Script { .. })), "{e:#?}"); + let n = parse_latex(r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}"); + assert!( + matches!(&n[0], MNode::Delim { beg: Some('('), elems, .. } if matches!(elems[0][0], MNode::Matrix { ref rows, .. } if rows.len() == 2)) + ); + let n = parse_latex(r"f(x)=\begin{cases} x & x\ge 0\\ -x & x<0\end{cases}"); + assert!(n.iter().any(|m| matches!(m, MNode::Delim { beg: Some('{'), end: None, .. })), "{n:#?}"); + let n = parse_latex(r"\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^n"); + assert!(matches!(&n[0], MNode::Func { .. }), "{n:#?}"); + let n = parse_latex(r"\mathbb{R}\hat{x}\text{ if }\overbrace{a+b}^{k}"); + assert!(matches!(&n[0], MNode::Run(r) if r.scr == MScr::DoubleStruck)); + let _ = (LimLoc::UndOvr, MathJc::Center); + } + + #[test] + fn latex_binom_round_trip() { + let a = parse_latex(r"\binom{n}{k}"); + let l = to_latex(&a); + assert_eq!(parse_latex(&l), a, "exported as {l}"); + let nobar = |n: &str, k: &str| MNode::Frac { kind: FracKind::NoBar, num: parse_latex(n), den: parse_latex(k) }; + let b = parse_latex(r"\genfrac{}{}{0pt}{}{n}{k}"); + assert_eq!(b, vec![nobar("n", "k")]); + assert_eq!(parse_latex(&to_latex(&b)), b); + // Other spellings of a zero thickness. + for z in ["0 pt", "0.0pt", r"0\,pt", "0em"] { + let c = parse_latex(&format!(r"\genfrac{{}}{{}}{{{z}}}{{}}{{n}}{{k}}")); + assert_eq!(c, vec![nobar("n", "k")], "thickness {z}"); + } + // A non-zero or default thickness keeps the bar. + for t in ["1pt", "0.4pt", ""] { + let c = parse_latex(&format!(r"\genfrac{{}}{{}}{{{t}}}{{}}{{n}}{{k}}")); + let bar = MNode::Frac { kind: FracKind::Bar, num: parse_latex("n"), den: parse_latex("k") }; + assert_eq!(c, vec![bar], "thickness {t:?}"); + } + // Delimiters are kept. + let d = parse_latex(r"\genfrac(){0pt}{}{n}{k}"); + assert_eq!(d, a); + let e = parse_latex(r"\genfrac[]{0pt}{}{n}{k}"); + assert!(matches!(&e[..], [MNode::Delim { beg: Some('['), end: Some(']'), .. }]), "{e:#?}"); + assert_eq!(parse_latex(&to_latex(&e)), e); + } + + #[test] + fn latex_round_trip() { + for lin in ["x=(-b±√(b^2-4ac))/2a", "∑_(i=1)^n▒i^2", "√(3&x)", "a⃗+x̂", "■(a&b@c&d)", "sin⁡x+cos⁡y", "e^(-x^2)"] { + let n = crate::math::parse_linear(lin); + let tex = to_latex(&n); + let back = parse_latex(&tex); + assert_eq!(crate::math::to_linear(&back), crate::math::to_linear(&n), "{lin} → {tex}"); + } + } + + #[test] + fn group_character_latex_roundtrip() { + for cmd in ["\\overparen{a+b}", "\\underparen{a+b}", "\\overbracket{x}", "\\underbracket{x}"] { + let n = parse_latex(cmd); + let tex = to_latex(&n); + assert_eq!(tex, cmd); + } + } + + #[test] + fn hostile_latex_never_panics() { + for s in ["", "\\", "{", "}", "^", "_", "\\frac", "\\sqrt[", "\\left(", "\\right)", "\\begin{matrix", "&&\\\\", "{{{{", "\\end{x}", "a^^b__c"] + { + let _ = to_latex(&parse_latex(s)); + } + let deep = "{".repeat(5000); + let _ = parse_latex(&deep); + let deep = "\\frac{".repeat(3000); + let _ = parse_latex(&deep); + let deep = "\\sqrt".repeat(5000); + let _ = parse_latex(&deep); + let deep = "\\hat".repeat(5000) + "x"; + let _ = parse_latex(&deep); + } + + #[test] + fn array_column_specs_and_aligned_optional_args() { + let n = parse_latex(r"\begin{array}{lcr} a & b & c \\ d & e & f \end{array}"); + let MNode::Matrix { rows, col_jc } = &n[0] else { panic!("{n:#?}") }; + assert_eq!(col_jc, &[ColJc::Left, ColJc::Center, ColJc::Right]); + assert_eq!(rows.len(), 2); + assert_eq!(crate::math::to_linear(&rows[0][0]), "a"); + assert_eq!(crate::math::to_linear(&rows[0][1]), "b"); + assert_eq!(crate::math::to_linear(&rows[0][2]), "c"); + + let n = parse_latex(r"\begin{aligned}[t] x &= 1 \\ y &= 2 \end{aligned}"); + assert!(matches!(&n[0], MNode::EqArr { rows } if rows.len() == 2)); + } + + #[test] + fn operatorname_starred_and_tag() { + let n = parse_latex(r"\operatorname*{argmin}_{x} f(x)"); + assert!(matches!(&n[0], MNode::Lim { upper: false, .. })); + + let n = parse_latex(r"E=mc^2 \tag{1}"); + let MNode::EqArr { rows } = &n[0] else { panic!("{n:#?}") }; + assert!(crate::math::has_number_mark(&rows[0])); + + let n = parse_latex(r"E=mc^2 \tag*{(A)}"); + let MNode::EqArr { rows } = &n[0] else { panic!("{n:#?}") }; + assert!(crate::math::has_number_mark(&rows[0])); + } + + #[test] + fn delim_preserves_custom_separator() { + let delim = MNode::Delim { + beg: Some('{'), + end: Some('}'), + sep: Some('‖'), + grow: true, + shp_match: false, + elems: vec![vec![MNode::Run(MRun::new("x"))], vec![MNode::Run(MRun::new("y"))]], + }; + let tex = to_latex(&[delim]); + assert!(tex.contains(r"\middle\|"), "Expected \\middle\\|, got: {tex}"); + } + + /// Commands MathLive and typed input use, from equaSHion (storytold/craft-libs#29). + #[test] + fn mathlive_and_other_spellings() { + let lin = |src: &str| crate::math::to_linear(&parse_latex(src)); + assert_eq!(lin(r"\abs{x-1}"), lin(r"\left|x-1\right|")); + assert_eq!(lin(r"\lvert x\rvert+\lVert v\rVert"), "|x|+‖v‖"); + assert_eq!(lin(r"a\nparallel b \backprime"), "a∦b‵"); + assert_eq!(lin(r"\infinity\cross 2"), "∞×2"); + assert_eq!(lin(r"\mathnormal{x}"), "x"); + let runs = parse_latex(r"\exponentialE^{\imaginaryI\pi}\differentialD x"); + assert!( + matches!(&runs[0], MNode::Script { base, .. } if matches!(&base[0], MNode::Run(r) if r.text == "e" && r.sty == Some(MSty::Plain))), + "{runs:?}" + ); + for (src, sty, scr) in [ + (r"\emph{so it is}", MSty::Italic, MScr::Roman), + (r"\textsf{so it is}", MSty::Plain, MScr::SansSerif), + (r"\hbox{so it is}", MSty::Plain, MScr::Roman), + ] { + let a = parse_latex(src); + assert!(matches!(a.as_slice(), [MNode::Run(r)] if r.text == "so it is" && r.nor && r.sty == Some(sty) && r.scr == scr), "{src}: {a:?}"); + } + for (src, want) in [(r"\underrightarrow{AB}", '→'), (r"\underleftarrow{AB}", '←'), (r"\underleftrightarrow{AB}", '↔')] { + assert!(matches!(parse_latex(src).as_slice(), [MNode::GroupChr { chr, top: false, .. }] if *chr == want), "{src}"); + } + // The writer keeps its own names. + assert_eq!(to_latex(&parse_latex(r"\infinity")), to_latex(&parse_latex(r"\infty"))); + } + + /// An operator name with a script still applies to its argument when the LaTeX is read back. + #[test] + fn operator_names_take_their_scripts_directly() { + for src in [r"\sin^2\theta+\cos^2\theta=1", r"\log_2 x", r"\ln^{3}(x+1)"] { + let tree = parse_latex(src); + let tex = to_latex(&tree); + assert_eq!(crate::math::to_linear(&parse_latex(&tex)), crate::math::to_linear(&tree), "{src}: {tex}"); + assert!(!tex.contains(r"{\sin }") && !tex.contains(r"{\log }"), "{tex}"); + } + assert!(to_latex(&parse_latex(r"\sin^2\theta")).starts_with(r"\sin ^{2}")); + // Other bases keep their braces. + assert_eq!(to_latex(&parse_latex("x^2")), "{x}^{2}"); + } +} diff --git a/crates/math/src/math_linear.rs b/crates/math/src/math_linear.rs new file mode 100644 index 000000000..39a25ab5d --- /dev/null +++ b/crates/math/src/math_linear.rs @@ -0,0 +1,762 @@ +//! The linear format (UnicodeMath, the plain text Word builds equations from) → math tree. +//! +//! Grammar, informally: an expression is a sequence of atoms and operators. Atoms are characters, +//! bracket groups (`(…)`, `[…]`, `{…}`, `|…|`, `〖…〗` invisible, `├…┤` one-sided, `│` +//! separators), prefix structures (`√x`, `∑_a^b▒x`, `█(…)`, `■(…)`, `▭x`, `□x`, `¯x`, `▁x`, +//! `⏞x`, `⏟x`, `⟡x`), function names (`sin x`, `log_2 x`, `lim┬(n→∞) x`) and placeholders (`⬚`). +//! Postfix operators apply to the atom before them: `^` `_` scripts, combining accents, `┬` `┴` +//! limits. `/` `⁄` `∕` `¦` take the operands on either side (an operand is a run of atoms up to +//! an operator or space; a parenthesised operand loses its parentheses). `^`/`_` with nothing +//! before them are pre-scripts. A top-level `#` numbers the equation (`E=mc^2#(1)`). + +use crate::math::{Arg, FracKind, MAX_DEPTH, MClass, MNode, MRun, ScriptKind, any_too_deep, is_nary_char, math_class, merge_runs, too_deep}; + +/// Function names set upright and applied to the following operand. +pub const FUNCTION_NAMES: &[&str] = &[ + "arccos", "arccot", "arccsc", "arcsec", "arcsin", "arctan", "arg", "cos", "cosh", "cot", "coth", "csc", "csch", "deg", "det", "dim", "exp", + "gcd", "hom", "inf", "ker", "lg", "lim", "liminf", "limsup", "ln", "log", "max", "min", "mod", "Pr", "sec", "sech", "sin", "sinh", "sup", "tan", + "tanh", +]; + +/// Length of the longest of [`FUNCTION_NAMES`]. +const MAX_NAME: usize = { + let (mut max, mut i) = (0, 0); + while i < FUNCTION_NAMES.len() { + if FUNCTION_NAMES[i].len() > max { + max = FUNCTION_NAMES[i].len(); + } + i += 1; + } + max +}; + +/// Function names whose subscripts go underneath (`lim_(n→∞)`). +const LIMIT_NAMES: &[&str] = &["lim", "liminf", "limsup", "max", "min", "sup", "inf", "det", "gcd", "Pr"]; + +/// The empty-argument placeholder. +pub const PLACEHOLDER: char = '⬚'; + +/// Parse linear-format text. Never fails: what isn't understood stays as text. +pub fn parse(s: &str) -> Arg { + let mut p = P { c: s.chars().take(20_000).collect(), i: 0, depth: 0, no_limits: 0, steps: 0 }; + let mut out = Vec::new(); + // Stray closers at the top level are text. + while p.i < p.c.len() { + out.extend(p.expr(&[])); + if let Some(c) = p.peek() { + p.i += 1; + out.push(text(c)); + } + } + let mut out = clean(out); + // `expr#(n)`: a numbered equation. + if out.iter().any(|n| matches!(n, MNode::Run(r) if r.text.contains('#'))) { + out = vec![MNode::EqArr { rows: vec![out] }]; + } + out +} + +fn text(c: char) -> MNode { + MNode::Run(MRun::new(c.to_string())) +} + +/// Closing bracket for an opening one. +pub fn closer(c: char) -> Option { + Some(match c { + '(' => ')', + '[' => ']', + '{' => '}', + '⟨' => '⟩', + '〈' => '〉', + '⌈' => '⌉', + '⌊' => '⌋', + '⟦' => '⟧', + '〖' => '〗', + _ => return None, + }) +} + +fn is_closer(c: char) -> bool { + matches!(c, ')' | ']' | '}' | '⟩' | '〉' | '⌉' | '⌋' | '⟧' | '〗' | '┤') +} + +/// Prefix characters that make a structure from the operand after them. +fn is_prefix(c: char) -> bool { + matches!(c, '√' | '∛' | '∜' | '█' | '■' | '▭' | '□' | '¯' | '▁' | '⟡' | '⏞' | '⏟' | '⏜' | '⏝' | '⎴' | '⎵') || is_nary_char(c) +} + +/// Combining marks used as accents. +pub fn is_combining(c: char) -> bool { + matches!(c as u32, 0x300..=0x36F | 0x20D0..=0x20FF) +} + +/// Characters that end an operand. +fn is_boundary(c: char) -> bool { + matches!(c, ' ' | '&' | '@' | '#' | '▒' | '│' | '/' | '⁄' | '∕' | '¦' | '\u{2061}') + || is_closer(c) + || matches!(math_class(c), MClass::Bin | MClass::Rel | MClass::Punct) +} + +struct P { + c: Vec, + i: usize, + depth: usize, + /// Inside a brace's operand: limits are left for the brace. + no_limits: usize, + /// Work done (bounds hostile input). + steps: usize, +} + +const MAX_STEPS: usize = 400_000; + +impl P { + fn peek(&self) -> Option { + self.c.get(self.i).copied() + } + fn peek_at(&self, k: usize) -> Option { + self.c.get(self.i + k).copied() + } + fn tired(&mut self) -> bool { + self.steps += 1; + self.steps > MAX_STEPS || self.depth > MAX_DEPTH + } + /// The rest of the input as text (when too deep or too long). + fn rest(&mut self) -> Arg { + let t: String = self.c.get(self.i..).unwrap_or(&[]).iter().collect(); + self.i = self.c.len(); + if t.is_empty() { Vec::new() } else { vec![MNode::Run(MRun::new(t))] } + } + + /// A sequence up to one of `stops` (not consumed) or the end. + fn expr(&mut self, stops: &[char]) -> Arg { + self.depth += 1; + let mut out: Arg = Vec::new(); + if self.tired() { + self.depth -= 1; + return self.rest(); + } + while let Some(c) = self.peek() { + if stops.contains(&c) || (is_closer(c) && !stops.is_empty()) { + break; + } + if self.tired() { + out.extend(self.rest()); + break; + } + match c { + '/' | '⁄' | '∕' | '¦' => { + self.i += 1; + let start = operand_start(&out); + // A numerator that is already deep stays as it is: `/` is text then. + if out.get(start..).is_some_and(any_too_deep) { + out.push(text(c)); + continue; + } + let num = strip_parens(out.drain(start..).collect()); + let den = self.operand(stops); + let kind = match c { + '⁄' => FracKind::Skewed, + '∕' => FracKind::Linear, + '¦' => FracKind::NoBar, + _ => FracKind::Bar, + }; + out.push(MNode::Frac { kind, num, den }); + } + '^' | '_' => { + let pre = match out.last() { + None => true, + Some(MNode::Run(r)) => r.text == " " || r.text.chars().all(|c| is_boundary(c) && c != '#'), + _ => false, + }; + if pre { + out.push(self.prescript(stops)); + } else { + self.i += 1; + let s = self.script_operand(stops); + if out.last().is_some_and(too_deep) { + out.push(text(c)); + out.extend(s); + } else { + let base = out.pop(); + out.push(attach_script(base, c == '^', s)); + } + } + } + '┬' | '┴' => { + self.i += 1; + let lim = self.script_operand(stops); + if out.last().is_some_and(too_deep) { + out.push(text(c)); + out.extend(lim); + } else { + let e = out.pop().map(|n| vec![n]).unwrap_or_default(); + out.push(MNode::Lim { upper: c == '┴', e: strip_parens(e), lim }); + } + } + c if is_combining(c) => { + self.i += 1; + if out.last().is_some_and(too_deep) { + out.push(text(c)); + } else { + let e = out.pop().map(|n| strip_parens(vec![n])).unwrap_or_default(); + out.push(MNode::Acc { chr: c, e }); + } + } + '▒' | '\u{2061}' => self.i += 1, + ' ' => { + self.i += 1; + out.push(text(' ')); + } + _ => { + let atom = self.atom(stops); + out.extend(atom); + } + } + } + self.depth -= 1; + out + } + + /// One atom (a character, a bracket group, a structure or a function application). + fn atom(&mut self, stops: &[char]) -> Arg { + let Some(c) = self.peek() else { return Vec::new() }; + if let Some(close) = closer(c) { + self.i += 1; + return vec![self.group(Some(c), &[close])]; + } + if c == '├' { + self.i += 1; + if let Some(d) = self.explicit_group() { + return vec![d]; + } + return vec![self.group(None, &[')', ']', '}', '⟩', '⌉', '⌋', '|', '‖'])]; + } + if (c == '|' || c == '‖') && self.c.get(self.i + 1..).is_some_and(|r| r.contains(&c)) { + self.i += 1; + return vec![self.group(Some(c), &[c])]; + } + if is_prefix(c) { + self.i += 1; + return vec![self.prefix(c, stops)]; + } + if c.is_ascii_alphabetic() { + return self.word(stops); + } + self.i += 1; + vec![text(c)] + } + + /// A bracket group after its opening character; `closers` end it. + fn group(&mut self, open: Option, closers: &[char]) -> MNode { + let mut stops: Vec = closers.to_vec(); + stops.extend(['┤', '│']); + let mut elems = Vec::new(); + let mut end = None; + loop { + let e = self.expr(&stops); + elems.push(e); + match self.peek() { + Some('│') => self.i += 1, + Some('┤') => { + self.i += 1; + break; + } + Some(c) if closers.contains(&c) => { + self.i += 1; + end = Some(c); + break; + } + // Another closer: the group ends unclosed there. + _ => break, + } + if self.tired() { + break; + } + } + let beg = open.filter(|c| *c != '〖'); + let end = end.filter(|c| *c != '〗'); + let sep = if elems.len() > 1 { Some('|') } else { None }; + MNode::Delim { beg, end, sep, grow: true, shp_match: false, elems } + } + + /// `├X … Y┤`: brackets given explicitly (any bracket characters, either side optional), the + /// cursor just after `├`. `None` (cursor unchanged) when there's no matching `┤`. + fn explicit_group(&mut self) -> Option { + let mut level = 1usize; + let mut k = self.i; + while let Some(c) = self.c.get(k) { + match c { + '├' => level += 1, + '┤' => { + level -= 1; + if level == 0 { + break; + } + } + _ => {} + } + k += 1; + } + if level != 0 { + return None; + } + let bracket = |c: &char| matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | '⟨' | '⟩' | '⌈' | '⌉' | '⌊' | '⌋' | '|' | '‖' | '⟦' | '⟧'); + let mut inner: Vec = self.c.get(self.i..k).unwrap_or(&[]).to_vec(); + self.i = k + 1; + let beg = if inner.first().is_some_and(bracket) { Some(inner.remove(0)) } else { None }; + // A closing bracket at the end that pairs with an opening one inside is content. + let paired = |inner: &[char]| -> bool { + let Some((last, body)) = inner.split_last() else { return false }; + let opener = match last { + ')' => '(', + ']' => '[', + '}' => '{', + '⟩' => '⟨', + '⌉' => '⌈', + '⌋' => '⌊', + '⟧' => '⟦', + _ => return false, + }; + body.iter().filter(|c| **c == opener).count() > body.iter().filter(|c| *c == last).count() + }; + let end = if !inner.is_empty() && inner.last().is_some_and(bracket) && !paired(&inner) { inner.pop() } else { None }; + let mut sub = P { c: inner, i: 0, depth: self.depth + 1, no_limits: 0, steps: self.steps }; + let mut elems = vec![Vec::new()]; + while sub.i < sub.c.len() { + if let Some(e) = elems.last_mut() { + e.extend(sub.expr(&['│'])); + } + match sub.peek() { + Some('│') => { + sub.i += 1; + elems.push(Vec::new()); + } + Some(c) => { + sub.i += 1; + if let Some(e) = elems.last_mut() { + e.push(text(c)); + } + } + None => {} + } + if sub.tired() { + break; + } + } + self.steps = sub.steps; + let sep = if elems.len() > 1 { Some('|') } else { None }; + Some(MNode::Delim { beg, end, sep, grow: true, shp_match: false, elems }) + } + + /// A prefix structure after its character. + fn prefix(&mut self, c: char, stops: &[char]) -> MNode { + match c { + '√'..='∜' => { + let mut deg = match c { + '∛' => vec![text('3')], + '∜' => vec![text('4')], + _ => Vec::new(), + }; + let mut e = self.operand(stops); + if let Some(k) = e.iter().position(|n| matches!(n, MNode::Run(r) if r.text == "&")) { + let rest = e.split_off(k + 1); + e.pop(); + deg = e; + e = rest; + } + MNode::Rad { deg_hide: deg.is_empty(), deg, e } + } + '█' | '■' => { + if self.peek() == Some('(') { + self.i += 1; + let inner = self.expr(&[')']); + if self.peek() == Some(')') { + self.i += 1; + } + grid(c == '■', inner) + } else { + text(c) + } + } + '▭' => MNode::BorderBox { hide: [false; 4], strike: [false; 4], e: self.operand(stops) }, + '□' => MNode::Boxed { e: self.operand(stops) }, + '¯' => MNode::Bar { top: true, e: self.operand(stops) }, + '▁' => MNode::Bar { top: false, e: self.operand(stops) }, + '⟡' => MNode::Phant { show: false, zero_wid: false, zero_asc: false, zero_desc: false, e: self.operand(stops) }, + // A label (`┴`/`┬`) after the operand belongs to the whole brace. + '⏞' | '⏜' | '⎴' | '⏟' | '⏝' | '⎵' => { + self.no_limits += 1; + let e = self.operand(stops); + self.no_limits -= 1; + MNode::GroupChr { chr: c, top: matches!(c, '⏞' | '⏜' | '⎴'), e } + } + _ => { + // N-ary operator: limits, then the operand. + let (mut sub, mut sup) = (Vec::new(), Vec::new()); + let (mut has_sub, mut has_sup) = (false, false); + loop { + match self.peek() { + Some('_') => { + self.i += 1; + sub = self.script_operand(stops); + has_sub = true; + } + Some('^') => { + self.i += 1; + sup = self.script_operand(stops); + has_sup = true; + } + _ => break, + } + } + if self.peek() == Some('▒') { + self.i += 1; + } + let e = if self.peek().is_some_and(|c| c == ' ') { Vec::new() } else { self.operand(stops) }; + MNode::Nary { chr: c, lim_loc: None, grow: false, sub_hide: !has_sub, sup_hide: !has_sup, sub, sup, e } + } + } + } + + /// Letters: a function application when they spell a function name, else one letter. + fn word(&mut self, stops: &[char]) -> Arg { + let start = self.i; + let mut end = start; + // Look no further than the longest name (and one past it, to see the run is longer): a + // scan to the end of every run made a long run of letters quadratic (CWE-407). + while end - start <= MAX_NAME && self.c.get(end).is_some_and(char::is_ascii_alphabetic) { + end += 1; + } + let word: String = if end - start > MAX_NAME { String::new() } else { self.c.get(start..end).unwrap_or(&[]).iter().collect() }; + if !FUNCTION_NAMES.contains(&word.as_str()) { + self.i = start + 1; + return vec![text(self.c.get(start).copied().unwrap_or(' '))]; + } + self.i = end; + let plain = vec![MNode::Run(MRun::plain(word.clone()))]; + // Limits and scripts on the name. + let name = match self.peek() { + Some('┬') | Some('┴') => { + let upper = self.peek() == Some('┴'); + self.i += 1; + let lim = self.script_operand(stops); + vec![MNode::Lim { upper, e: plain, lim }] + } + Some('_') if LIMIT_NAMES.contains(&word.as_str()) => { + self.i += 1; + let lim = self.script_operand(stops); + vec![MNode::Lim { upper: false, e: plain, lim }] + } + Some(c @ ('^' | '_')) => { + self.i += 1; + let s = self.script_operand(stops); + let mut n = attach_script(Some(MNode::Run(MRun::plain(word.clone()))), c == '^', s); + if let Some(c2 @ ('^' | '_')) = self.peek() { + self.i += 1; + let s2 = self.script_operand(stops); + n = attach_script(Some(n), c2 == '^', s2); + } + vec![n] + } + _ => plain, + }; + // The operand, after an optional space or function-application mark. + if matches!(self.peek(), Some(' ') | Some('\u{2061}') | Some('▒')) { + self.i += 1; + } + let next = self.peek(); + let applies = next.is_some_and(|c| !stops.contains(&c) && !is_closer(c) && (!is_boundary(c) || c == '(' || matches!(c, '−' | '-' | '+'))); + if !applies { + return name; + } + let e = self.operand(stops); + if e.is_empty() { + return name; + } + vec![MNode::Func { name, e }] + } + + /// Pre-scripts (`_a^b x`): the scripts, then the base. + fn prescript(&mut self, stops: &[char]) -> MNode { + let (mut sub, mut sup) = (Vec::new(), Vec::new()); + while let Some(c @ ('^' | '_')) = self.peek() { + self.i += 1; + let s = self.script_operand(stops); + if c == '^' { + sup = s; + } else { + sub = s; + } + } + if self.peek() == Some('▒') { + self.i += 1; + } + let base = self.operand(stops); + MNode::Script { kind: ScriptKind::Pre, base, sub, sup } + } + + /// An operand: a parenthesised group (parentheses dropped) or a run of atoms with their + /// postfix scripts, accents and limits, up to an operator or space. + fn operand(&mut self, stops: &[char]) -> Arg { + if self.tired() { + return self.rest(); + } + self.depth += 1; + let mut out: Arg = Vec::new(); + if self.peek() == Some('(') { + self.i += 1; + let g = self.group(Some('('), &[')']); + let inner = match g { + MNode::Delim { elems, end: Some(')'), .. } if elems.len() == 1 => elems.into_iter().next().unwrap_or_default(), + other => vec![other], + }; + out = inner; + self.postfix(&mut out, stops, true); + } else if self.peek() == Some('〖') { + self.i += 1; + let g = self.group(Some('〖'), &['〗']); + out = match g { + MNode::Delim { elems, .. } if elems.len() == 1 => elems.into_iter().next().unwrap_or_default(), + other => vec![other], + }; + self.postfix(&mut out, stops, true); + } else { + // A signed operand (`e^-x`, `−b`). + if let Some(c @ ('−' | '-' | '+' | '±' | '∓')) = self.peek() + && self.peek_at(1).is_some_and(|n| !is_boundary(n)) + { + self.i += 1; + out.push(text(c)); + } + while let Some(c) = self.peek() { + if stops.contains(&c) || is_boundary(c) || self.tired() { + break; + } + let a = self.atom(stops); + if a.is_empty() { + break; + } + out.extend(a); + self.postfix(&mut out, stops, false); + } + if out.is_empty() + && let Some(c) = self.peek() + && c != ' ' + && !stops.contains(&c) + && !is_closer(c) + && !matches!(c, '/' | '⁄' | '∕' | '¦' | '&' | '@' | '#' | '│' | '▒') + { + // A lone operator as operand. + self.i += 1; + out.push(text(c)); + } + } + self.depth -= 1; + out + } + + /// Postfix operators on the last atom of `out` (`whole`: on all of `out` as one group). + fn postfix(&mut self, out: &mut Arg, stops: &[char], whole: bool) { + while let Some(c) = self.peek() { + if self.tired() { + break; + } + let base = |out: &mut Arg| -> Option { + if whole && out.len() != 1 { + if out.is_empty() { + return None; + } + return Some(MNode::Delim { beg: None, end: None, sep: None, grow: true, shp_match: false, elems: vec![std::mem::take(out)] }); + } + out.pop() + }; + if !(matches!(c, '^' | '_') || matches!(c, '┬' | '┴') && self.no_limits == 0 || is_combining(c)) { + break; + } + // The base is already deep: the operator is text (see `too_deep`). + let deep = if whole { any_too_deep(out) } else { out.last().is_some_and(too_deep) }; + self.i += 1; + if deep { + let s = if matches!(c, '^' | '_' | '┬' | '┴') { self.script_operand(stops) } else { Vec::new() }; + out.push(text(c)); + out.extend(s); + continue; + } + match c { + '^' | '_' => { + let s = self.script_operand(stops); + let b = base(out); + out.push(attach_script(b, c == '^', s)); + } + '┬' | '┴' => { + let lim = self.script_operand(stops); + let b = base(out); + out.push(MNode::Lim { upper: c == '┴', e: b.map(|n| vec![n]).unwrap_or_default(), lim }); + } + _ => { + let b = base(out); + out.push(MNode::Acc { chr: c, e: b.map(|n| strip_parens(vec![n])).unwrap_or_default() }); + } + } + } + } + + /// A script or limit: a parenthesised group, a structure, a number, a signed operand, a run of + /// letters (and digits) or one other character. + fn script_operand(&mut self, stops: &[char]) -> Arg { + if self.tired() { + return self.rest(); + } + self.depth += 1; + let out = match self.peek() { + Some('(') => { + self.i += 1; + match self.group(Some('('), &[')']) { + MNode::Delim { elems, end: Some(')'), .. } if elems.len() == 1 => elems.into_iter().next().unwrap_or_default(), + other => vec![other], + } + } + Some('〖') => { + self.i += 1; + match self.group(Some('〖'), &['〗']) { + MNode::Delim { elems, .. } if elems.len() == 1 => elems.into_iter().next().unwrap_or_default(), + other => vec![other], + } + } + Some(c) if is_prefix(c) || closer(c).is_some() => self.atom(stops), + Some(c) if c.is_ascii_digit() => { + let start = self.i; + while self.peek().is_some_and(|k| k.is_alphanumeric() || k == '.') { + self.i += 1; + } + let t: String = self.c.get(start..self.i).unwrap_or(&[]).iter().collect(); + vec![MNode::Run(MRun::new(t))] + } + Some(c @ ('−' | '-' | '+' | '±' | '∓')) if self.peek_at(1).is_some_and(|n| !is_boundary(n)) => { + self.i += 1; + let mut v = vec![text(c)]; + v.extend(self.script_operand(stops)); + v + } + Some(c) if c.is_alphabetic() => { + // Word (#1609): the whole run of letters and digits up to a space or operator, so + // `V_dd` is V with a subscript `dd`, exactly like `V_(dd)`. + let start = self.i; + while self.peek().is_some_and(char::is_alphanumeric) { + self.i += 1; + } + let t: String = self.c.get(start..self.i).unwrap_or(&[]).iter().collect(); + // A known function name stays upright, as Word builds it. + vec![MNode::Run(if FUNCTION_NAMES.contains(&t.as_str()) { MRun::plain(t) } else { MRun::new(t) })] + } + Some(c) if !stops.contains(&c) && c != ' ' && !is_closer(c) => { + self.i += 1; + vec![text(c)] + } + _ => Vec::new(), + }; + self.depth -= 1; + out + } +} + +/// Where the trailing operand of `out` starts (after the last operator or space). +fn operand_start(out: &[MNode]) -> usize { + let mut k = out.len(); + while k > 0 { + match out.get(k - 1) { + Some(MNode::Run(r)) if r.text.chars().all(is_boundary) => break, + _ => k -= 1, + } + } + k +} + +/// A single parenthesised group used as an operand loses its parentheses. +pub fn strip_parens(mut a: Arg) -> Arg { + if a.len() == 1 + && let Some(MNode::Delim { beg: Some('('), end: Some(')'), elems, .. } | MNode::Delim { beg: None, end: None, elems, .. }) = a.first_mut() + && elems.len() == 1 + { + return elems.pop().unwrap_or_default(); + } + a +} + +fn attach_script(base: Option, sup: bool, s: Arg) -> MNode { + match base { + Some(MNode::Script { kind: ScriptKind::Sub, base, sub, .. }) if sup => MNode::Script { kind: ScriptKind::SubSup, base, sub, sup: s }, + Some(MNode::Script { kind: ScriptKind::Sup, base, sup: sp, .. }) if !sup => MNode::Script { kind: ScriptKind::SubSup, base, sub: s, sup: sp }, + b => { + let base = b.map(|b| vec![b]).unwrap_or_default(); + if sup { + MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s } + } else { + MNode::Script { kind: ScriptKind::Sub, base, sub: s, sup: Vec::new() } + } + } + } +} + +/// `█(a@b)` equation array / `■(a&b@c&d)` matrix from the parsed inside. +fn grid(matrix: bool, inner: Arg) -> MNode { + let mut rows: Vec> = vec![vec![Vec::new()]]; + for n in inner { + match &n { + MNode::Run(r) if r.text == "@" => rows.push(vec![Vec::new()]), + MNode::Run(r) if r.text == "&" && matrix => { + if let Some(row) = rows.last_mut() { + row.push(Vec::new()); + } + } + _ => { + if let Some(cell) = rows.last_mut().and_then(|r| r.last_mut()) { + cell.push(n); + } + } + } + } + if matrix { + MNode::Matrix { rows, col_jc: Vec::new() } + } else { + MNode::EqArr { rows: rows.into_iter().map(|r| r.into_iter().flatten().collect()).collect() } + } +} + +/// Drop placeholders and build-up spaces, merge runs; recursively. +fn clean(a: Arg) -> Arg { + let mut out = Vec::with_capacity(a.len()); + for n in a { + match n { + MNode::Run(r) if r.text == " " || r.text.chars().all(|c| c == PLACEHOLDER) => {} + other => out.push(map_args(other, &clean)), + } + } + merge_runs(out) +} + +/// Apply `f` to every argument of a node. +pub fn map_args(n: MNode, f: &dyn Fn(Arg) -> Arg) -> MNode { + match n { + MNode::Run(r) => MNode::Run(r), + MNode::Frac { kind, num, den } => MNode::Frac { kind, num: f(num), den: f(den) }, + MNode::Script { kind, base, sub, sup } => MNode::Script { kind, base: f(base), sub: f(sub), sup: f(sup) }, + MNode::Rad { deg, deg_hide, e } => MNode::Rad { deg: f(deg), deg_hide, e: f(e) }, + MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e } => { + MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub: f(sub), sup: f(sup), e: f(e) } + } + MNode::Delim { beg, end, sep, grow, shp_match, elems } => { + MNode::Delim { beg, end, sep, grow, shp_match, elems: elems.into_iter().map(f).collect() } + } + MNode::Func { name, e } => MNode::Func { name: f(name), e: f(e) }, + MNode::Lim { upper, e, lim } => MNode::Lim { upper, e: f(e), lim: f(lim) }, + MNode::Acc { chr, e } => MNode::Acc { chr, e: f(e) }, + MNode::Bar { top, e } => MNode::Bar { top, e: f(e) }, + MNode::BorderBox { hide, strike, e } => MNode::BorderBox { hide, strike, e: f(e) }, + MNode::Boxed { e } => MNode::Boxed { e: f(e) }, + MNode::GroupChr { chr, top, e } => MNode::GroupChr { chr, top, e: f(e) }, + MNode::EqArr { rows } => MNode::EqArr { rows: rows.into_iter().map(f).collect() }, + MNode::Matrix { rows, col_jc } => MNode::Matrix { rows: rows.into_iter().map(|r| r.into_iter().map(f).collect()).collect(), col_jc }, + MNode::Phant { show, zero_wid, zero_asc, zero_desc, e } => MNode::Phant { show, zero_wid, zero_asc, zero_desc, e: f(e) }, + } +} diff --git a/crates/math/src/math_symbols.rs b/crates/math/src/math_symbols.rs new file mode 100644 index 000000000..279ffd2ca --- /dev/null +++ b/crates/math/src/math_symbols.rs @@ -0,0 +1,399 @@ +//! Named math characters: Math AutoCorrect while typing in an equation (`\alpha` + space → α) +//! and LaTeX conversion. Names are the usual TeX names plus the linear-format operators +//! (`\sqrt` → √, `\above` → ┴, `\matrix` → ■…). + +/// (name without the backslash, character). When a character has several names the first one +/// listed is the one LaTeX output uses. +pub const SYMBOLS: &[(&str, char)] = &[ + // Greek. + ("alpha", 'α'), + ("beta", 'β'), + ("gamma", 'γ'), + ("delta", 'δ'), + ("epsilon", 'ϵ'), + ("varepsilon", 'ε'), + ("zeta", 'ζ'), + ("eta", 'η'), + ("theta", 'θ'), + ("vartheta", 'ϑ'), + ("iota", 'ι'), + ("kappa", 'κ'), + ("varkappa", 'ϰ'), + ("lambda", 'λ'), + ("mu", 'μ'), + ("nu", 'ν'), + ("xi", 'ξ'), + ("omicron", 'ο'), + ("pi", 'π'), + ("varpi", 'ϖ'), + ("rho", 'ρ'), + ("varrho", 'ϱ'), + ("sigma", 'σ'), + ("varsigma", 'ς'), + ("tau", 'τ'), + ("upsilon", 'υ'), + ("phi", 'ϕ'), + ("varphi", 'φ'), + ("chi", 'χ'), + ("psi", 'ψ'), + ("omega", 'ω'), + ("Alpha", 'Α'), + ("Beta", 'Β'), + ("Gamma", 'Γ'), + ("Delta", 'Δ'), + ("Epsilon", 'Ε'), + ("Zeta", 'Ζ'), + ("Eta", 'Η'), + ("Theta", 'Θ'), + ("Iota", 'Ι'), + ("Kappa", 'Κ'), + ("Lambda", 'Λ'), + ("Mu", 'Μ'), + ("Nu", 'Ν'), + ("Xi", 'Ξ'), + ("Omicron", 'Ο'), + ("Pi", 'Π'), + ("Rho", 'Ρ'), + ("Sigma", 'Σ'), + ("Tau", 'Τ'), + ("Upsilon", 'Υ'), + ("Phi", 'Φ'), + ("Chi", 'Χ'), + ("Psi", 'Ψ'), + ("Omega", 'Ω'), + ("digamma", 'ϝ'), + // Binary operators. + ("pm", '±'), + ("mp", '∓'), + ("times", '×'), + ("div", '÷'), + ("cdot", '⋅'), + ("bullet", '∙'), + ("ast", '∗'), + ("star", '⋆'), + ("circ", '∘'), + ("oplus", '⊕'), + ("ominus", '⊖'), + ("otimes", '⊗'), + ("oslash", '⊘'), + ("odot", '⊙'), + ("cup", '∪'), + ("cap", '∩'), + ("uplus", '⊎'), + ("sqcup", '⊔'), + ("sqcap", '⊓'), + ("vee", '∨'), + ("wedge", '∧'), + ("setminus", '∖'), + ("backslash", '\\'), + ("wr", '≀'), + ("diamond", '⋄'), + ("dagger", '†'), + ("ddagger", '‡'), + ("amalg", '⨿'), + ("dotplus", '∔'), + ("ltimes", '⋉'), + ("rtimes", '⋊'), + // Relations. + ("le", '≤'), + ("leq", '≤'), + ("ge", '≥'), + ("geq", '≥'), + ("ne", '≠'), + ("neq", '≠'), + ("approx", '≈'), + ("equiv", '≡'), + ("sim", '∼'), + ("simeq", '≃'), + ("cong", '≅'), + ("propto", '∝'), + ("ll", '≪'), + ("gg", '≫'), + ("prec", '≺'), + ("succ", '≻'), + ("preceq", '≼'), + ("succeq", '≽'), + ("subset", '⊂'), + ("supset", '⊃'), + ("subseteq", '⊆'), + ("supseteq", '⊇'), + ("sqsubseteq", '⊑'), + ("sqsupseteq", '⊒'), + ("in", '∈'), + ("ni", '∋'), + ("notin", '∉'), + ("perp", '⊥'), + ("parallel", '∥'), + ("mid", '∣'), + ("nmid", '∤'), + ("asymp", '≍'), + ("doteq", '≐'), + ("models", '⊨'), + ("vdash", '⊢'), + ("dashv", '⊣'), + ("bowtie", '⋈'), + ("coloneq", '≔'), + ("defeq", '≝'), + ("triangleq", '≜'), + ("nless", '≮'), + ("ngtr", '≯'), + ("nleq", '≰'), + ("ngeq", '≱'), + ("nsim", '≁'), + ("ncong", '≇'), + ("nequiv", '≢'), + ("nsubset", '⊄'), + ("nsupset", '⊅'), + ("nsubseteq", '⊈'), + ("nsupseteq", '⊉'), + ("subsetneq", '⊊'), + ("supsetneq", '⊋'), + ("lesssim", '≲'), + ("gtrsim", '≳'), + ("therefore", '∴'), + ("because", '∵'), + // Arrows. + ("rightarrow", '→'), + ("to", '→'), + ("leftarrow", '←'), + ("gets", '←'), + ("leftrightarrow", '↔'), + ("uparrow", '↑'), + ("downarrow", '↓'), + ("updownarrow", '↕'), + ("Rightarrow", '⇒'), + ("Leftarrow", '⇐'), + ("Leftrightarrow", '⇔'), + ("Uparrow", '⇑'), + ("Downarrow", '⇓'), + ("Updownarrow", '⇕'), + ("longrightarrow", '⟶'), + ("longleftarrow", '⟵'), + ("longleftrightarrow", '⟷'), + ("Longrightarrow", '⟹'), + ("Longleftarrow", '⟸'), + ("Longleftrightarrow", '⟺'), + ("implies", '⟹'), + ("iff", '⟺'), + ("mapsto", '↦'), + ("longmapsto", '⟼'), + ("nearrow", '↗'), + ("searrow", '↘'), + ("swarrow", '↙'), + ("nwarrow", '↖'), + ("hookleftarrow", '↩'), + ("hookrightarrow", '↪'), + ("leftharpoonup", '↼'), + ("leftharpoondown", '↽'), + ("rightharpoonup", '⇀'), + ("rightharpoondown", '⇁'), + ("rightleftharpoons", '⇌'), + ("leftrightharpoons", '⇋'), + ("circlearrowleft", '↺'), + ("circlearrowright", '↻'), + // Big operators. + ("sum", '∑'), + ("prod", '∏'), + ("coprod", '∐'), + ("int", '∫'), + ("iint", '∬'), + ("iiint", '∭'), + ("oint", '∮'), + ("oiint", '∯'), + ("oiiint", '∰'), + ("bigcup", '⋃'), + ("bigcap", '⋂'), + ("bigvee", '⋁'), + ("bigwedge", '⋀'), + ("bigoplus", '⨁'), + ("bigotimes", '⨂'), + ("bigodot", '⨀'), + ("biguplus", '⨄'), + ("bigsqcup", '⨆'), + // Brackets. + ("langle", '⟨'), + ("rangle", '⟩'), + ("lceil", '⌈'), + ("rceil", '⌉'), + ("lfloor", '⌊'), + ("rfloor", '⌋'), + ("lbrack", '['), + ("rbrack", ']'), + ("lbrace", '{'), + ("rbrace", '}'), + ("Vert", '‖'), + ("norm", '‖'), + ("vert", '|'), + ("lbbrack", '⟦'), + ("rbbrack", '⟧'), + // Miscellaneous. + ("infty", '∞'), + ("partial", '∂'), + ("nabla", '∇'), + ("forall", '∀'), + ("exists", '∃'), + ("nexists", '∄'), + ("neg", '¬'), + ("lnot", '¬'), + ("emptyset", '∅'), + ("varnothing", '∅'), + ("hbar", 'ℏ'), + ("ell", 'ℓ'), + ("Re", 'ℜ'), + ("Im", 'ℑ'), + ("wp", '℘'), + ("aleph", 'ℵ'), + ("beth", 'ℶ'), + ("gimel", 'ℷ'), + ("daleth", 'ℸ'), + ("degree", '°'), + ("angle", '∠'), + ("measuredangle", '∡'), + ("sphericalangle", '∢'), + ("rightangle", '∟'), + ("triangle", '△'), + ("square", '□'), + ("blacksquare", '■'), + ("qed", '∎'), + ("top", '⊤'), + ("bot", '⊥'), + ("cdots", '⋯'), + ("ldots", '…'), + ("dots", '…'), + ("vdots", '⋮'), + ("ddots", '⋱'), + ("adots", '⋰'), + ("prime", '′'), + ("dprime", '″'), + ("trprime", '‴'), + ("dd", 'ⅆ'), + ("Dd", 'ⅅ'), + ("ee", 'ⅇ'), + ("ii", 'ⅈ'), + ("jj", 'ⅉ'), + ("imath", 'ı'), + ("jmath", 'ȷ'), + ("complement", '∁'), + ("Angstrom", 'Å'), + ("mho", '℧'), + ("eth", 'ð'), + ("flat", '♭'), + ("natural", '♮'), + ("sharp", '♯'), + ("clubsuit", '♣'), + ("diamondsuit", '♢'), + ("heartsuit", '♡'), + ("spadesuit", '♠'), + // Spaces. + ("quad", '\u{2003}'), + ("emsp", '\u{2003}'), + ("ensp", '\u{2002}'), + ("thicksp", '\u{2005}'), + ("medsp", '\u{205F}'), + ("thinsp", '\u{2009}'), + ("hairsp", '\u{200A}'), + ("nbsp", '\u{A0}'), + ("zwsp", '\u{200B}'), + // Linear-format operators (build-up). + ("sqrt", '√'), + ("cbrt", '∛'), + ("qdrt", '∜'), + ("matrix", '■'), + ("eqarray", '█'), + ("above", '┴'), + ("below", '┬'), + ("of", '▒'), + ("naryand", '▒'), + ("funcapply", '\u{2061}'), + ("box", '□'), + ("rect", '▭'), + ("overbar", '¯'), + ("underbar", '▁'), + ("phantom", '⟡'), + ("overbrace", '⏞'), + ("underbrace", '⏟'), + ("overparen", '⏜'), + ("underparen", '⏝'), + ("atop", '¦'), + ("over", '/'), + ("ldiv", '∕'), + ("sdiv", '⁄'), + ("begin", '〖'), + ("end", '〗'), + ("left", '├'), + ("right", '┤'), + ("eqno", '#'), + ("placeholder", '⬚'), + // Accents (combining, typed after the base). + ("hat", '\u{302}'), + ("check", '\u{30C}'), + ("tilde", '\u{303}'), + ("acute", '\u{301}'), + ("grave", '\u{300}'), + ("dot", '\u{307}'), + ("ddot", '\u{308}'), + ("dddot", '\u{20DB}'), + ("breve", '\u{306}'), + ("bar", '\u{305}'), + ("Bar", '\u{33F}'), + ("vec", '\u{20D7}'), + ("tvec", '\u{20E1}'), + ("lhvec", '\u{20D0}'), + ("hvec", '\u{20D1}'), + // Other spellings (after the names the writer uses, which come first). + ("nparallel", '∦'), + ("backprime", '‵'), + ("lvert", '|'), + ("rvert", '|'), + ("lVert", '‖'), + ("rVert", '‖'), + ("infinity", '∞'), + ("cross", '×'), +]; + +/// The character for a name (`alpha` → α), including `doubleR`, `scriptL`, `frakturg`. +pub fn symbol(name: &str) -> Option { + if let Some((_, c)) = SYMBOLS.iter().find(|(n, _)| *n == name) { + return Some(*c); + } + for (prefix, scr) in [("double", crate::math::MScr::DoubleStruck), ("script", crate::math::MScr::Script), ("fraktur", crate::math::MScr::Fraktur)] + { + if let Some(rest) = name.strip_prefix(prefix) { + let mut cs = rest.chars(); + if let (Some(c), None) = (cs.next(), cs.next()) + && c.is_ascii_alphanumeric() + { + let m = crate::math::math_alnum(c, false, false, scr); + if m != c { + return Some(m); + } + } + } + } + None +} + +/// The (first) name of a character. +pub fn name_of(c: char) -> Option<&'static str> { + SYMBOLS.iter().find(|(_, s)| *s == c).map(|(n, _)| *n) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_resolve() { + assert_eq!(symbol("alpha"), Some('α')); + assert_eq!(symbol("doubleR"), Some('ℝ')); + assert_eq!(symbol("scriptL"), Some('ℒ')); + assert_eq!(symbol("nonesuch"), None); + assert_eq!(name_of('≤'), Some("le")); + // No name is listed twice. + let mut names: Vec<&str> = SYMBOLS.iter().map(|(n, _)| *n).collect(); + names.sort_unstable(); + let before = names.len(); + names.dedup(); + assert_eq!(before, names.len()); + } +} diff --git a/crates/math/src/math_tree.rs b/crates/math/src/math_tree.rs new file mode 100644 index 000000000..45d2c603a --- /dev/null +++ b/crates/math/src/math_tree.rs @@ -0,0 +1,104 @@ +//! Structural access to an equation tree: the arguments of a node, and every run in a tree. + +use crate::math::{Arg, MAX_DEPTH, MNode, MRun}; + +/// Number of child arguments of a node. +pub fn child_count(n: &MNode) -> usize { + match n { + MNode::Run(_) => 0, + MNode::Frac { .. } | MNode::Func { .. } | MNode::Lim { .. } => 2, + MNode::Rad { .. } => 2, + MNode::Script { .. } | MNode::Nary { .. } => 3, + MNode::Delim { elems, .. } => elems.len(), + MNode::EqArr { rows } => rows.len(), + MNode::Matrix { rows, .. } => rows.iter().map(|r| r.len()).sum(), + MNode::Acc { .. } | MNode::Bar { .. } | MNode::BorderBox { .. } | MNode::Boxed { .. } | MNode::GroupChr { .. } | MNode::Phant { .. } => 1, + } +} + +/// Child argument `i` of a node (see [`child_count`] for the numbering: fraction num 0 / den 1; +/// script base 0 / sub 1 / sup 2; radical degree 0 / base 1; n-ary sub 0 / sup 1 / operand 2; +/// function name 0 / argument 1; limit base 0 / limit 1; matrices row by row). +pub fn child(n: &MNode, i: usize) -> Option<&Arg> { + match (n, i) { + (MNode::Frac { num, .. }, 0) => Some(num), + (MNode::Frac { den, .. }, 1) => Some(den), + (MNode::Script { base, .. }, 0) => Some(base), + (MNode::Script { sub, .. }, 1) => Some(sub), + (MNode::Script { sup, .. }, 2) => Some(sup), + (MNode::Rad { deg, .. }, 0) => Some(deg), + (MNode::Rad { e, .. }, 1) => Some(e), + (MNode::Nary { sub, .. }, 0) => Some(sub), + (MNode::Nary { sup, .. }, 1) => Some(sup), + (MNode::Nary { e, .. }, 2) => Some(e), + (MNode::Delim { elems, .. }, i) => elems.get(i), + (MNode::Func { name, .. }, 0) => Some(name), + (MNode::Func { e, .. }, 1) => Some(e), + (MNode::Lim { e, .. }, 0) => Some(e), + (MNode::Lim { lim, .. }, 1) => Some(lim), + ( + MNode::Acc { e, .. } + | MNode::Bar { e, .. } + | MNode::BorderBox { e, .. } + | MNode::Boxed { e } + | MNode::GroupChr { e, .. } + | MNode::Phant { e, .. }, + 0, + ) => Some(e), + (MNode::EqArr { rows }, i) => rows.get(i), + (MNode::Matrix { rows, .. }, i) => rows.iter().flatten().nth(i), + _ => None, + } +} + +pub fn child_mut(n: &mut MNode, i: usize) -> Option<&mut Arg> { + match (n, i) { + (MNode::Frac { num, .. }, 0) => Some(num), + (MNode::Frac { den, .. }, 1) => Some(den), + (MNode::Script { base, .. }, 0) => Some(base), + (MNode::Script { sub, .. }, 1) => Some(sub), + (MNode::Script { sup, .. }, 2) => Some(sup), + (MNode::Rad { deg, .. }, 0) => Some(deg), + (MNode::Rad { e, .. }, 1) => Some(e), + (MNode::Nary { sub, .. }, 0) => Some(sub), + (MNode::Nary { sup, .. }, 1) => Some(sup), + (MNode::Nary { e, .. }, 2) => Some(e), + (MNode::Delim { elems, .. }, i) => elems.get_mut(i), + (MNode::Func { name, .. }, 0) => Some(name), + (MNode::Func { e, .. }, 1) => Some(e), + (MNode::Lim { e, .. }, 0) => Some(e), + (MNode::Lim { lim, .. }, 1) => Some(lim), + ( + MNode::Acc { e, .. } + | MNode::Bar { e, .. } + | MNode::BorderBox { e, .. } + | MNode::Boxed { e } + | MNode::GroupChr { e, .. } + | MNode::Phant { e, .. }, + 0, + ) => Some(e), + (MNode::EqArr { rows }, i) => rows.get_mut(i), + (MNode::Matrix { rows, .. }, i) => rows.iter_mut().flatten().nth(i), + _ => None, + } +} + +/// Call `f` on every run in the tree. +pub fn each_run_mut(root: &mut Arg, f: &mut dyn FnMut(&mut MRun)) { + fn go(a: &mut Arg, f: &mut dyn FnMut(&mut MRun), depth: usize) { + if depth > MAX_DEPTH { + return; + } + for n in a.iter_mut() { + if let MNode::Run(r) = n { + f(r); + } + for c in 0..child_count(n) { + if let Some(ch) = child_mut(n, c) { + go(ch, f, depth + 1); + } + } + } + } + go(root, f, 0); +} diff --git a/crates/math/src/mathml.rs b/crates/math/src/mathml.rs new file mode 100644 index 000000000..9dc2433ac --- /dev/null +++ b/crates/math/src/mathml.rs @@ -0,0 +1,1080 @@ +//! Equations as MathML (W3C MathML Core / Presentation MathML): written into HTML export and the +//! HTML a copy puts on the system clipboard, so programs that read MathML can get a formatted +//! equation instead of its linear text (#816); for a copy of one equation alone, the text of the +//! platform's MathML clipboard formats, which Word reads first when it pastes math (#1297; +//! pasting into Word and LibreOffice not yet verified); and read back from pasted or opened HTML. +//! +//! The writer walks the equation tree ([`MNode`]) and wraps it in `` with the linear +//! format as an `application/x-unicodemath` annotation, which renderers ignore and WordCraft reads +//! back exactly. The reader takes that annotation when present, else a TeX annotation, else +//! builds the tree from the presentation elements (fractions, scripts, radicals, under/over +//! limits, tables, fences); both bound their nesting and size. + +use crate::math::{ + Arg, ColJc, FracKind, LimLoc, MAX_DEPTH, MClass, MNode, MRun, MScr, MSty, ScriptKind, is_integral, is_nary_char, math_alnum, math_class, + to_linear, +}; +use crate::math_linear::FUNCTION_NAMES; + +/// Escape text for HTML or XML content and attribute values. +fn esc(s: &str) -> String { + let mut o = String::with_capacity(s.len() + 8); + for c in s.chars() { + match c { + '&' => o.push_str("&"), + '<' => o.push_str("<"), + '>' => o.push_str(">"), + '"' => o.push_str("""), + '\u{000C}' | '\u{000E}' => {} + _ => o.push(c), + } + } + o +} + +/// The MathML namespace. +pub const NS: &str = "http://www.w3.org/1998/Math/MathML"; +/// The annotation encoding carrying the linear format (UnicodeMath). +pub const UNICODEMATH: &str = "application/x-unicodemath"; + +// --------------------------------------------------------------------------------------------- +// Writer + +/// An equation as a `` element. `linear` (the linear format) goes in an annotation for an +/// exact round trip; empty = taken from the tree. +pub fn to_mathml(nodes: &[MNode], display: bool, linear: &str) -> String { + let mut o = String::new(); + o.push_str(&format!(""); + arg(nodes, &mut o, 0, false); + o.push_str(""); + let linear = if linear.is_empty() { to_linear(nodes) } else { linear.to_string() }; + if !linear.is_empty() { + o.push_str(&format!("{}", esc(&linear))); + } + o.push_str(""); + o +} + +/// An equation known by its linear format, as a `` element. +pub fn linear_to_mathml(linear: &str, display: bool) -> String { + to_mathml(&crate::math::parse_linear(linear), display, linear) +} + +/// An argument as a row of elements. `eq_arr`: a row of an equation array, whose `&` marks are +/// alignment points, not text. +fn arg(a: &[MNode], o: &mut String, depth: usize, eq_arr: bool) { + if depth > MAX_DEPTH { + return; + } + for n in a { + node(n, o, depth + 1, eq_arr); + } +} + +/// An argument as one element (`` around several). +fn group(a: &[MNode], o: &mut String, depth: usize) { + o.push_str(""); + arg(a, o, depth, false); + o.push_str(""); +} + +fn mo(c: char, attrs: &str, o: &mut String) { + o.push_str(&format!("{}", esc(&c.to_string()))); +} + +fn run(r: &MRun, o: &mut String, eq_arr: bool) { + let color = r.color.map(|c| format!(" mathcolor=\"#{}\"", c.hex())).unwrap_or_default(); + if r.nor { + if !r.text.is_empty() { + o.push_str(&format!("{}", esc(&r.text))); + } + return; + } + let bold = matches!(r.sty, Some(MSty::Bold | MSty::BoldItalic)); + let italic = match r.sty { + None => r.scr == MScr::Roman, + Some(s) => matches!(s, MSty::Italic | MSty::BoldItalic), + }; + let cs: Vec = r.text.chars().collect(); + let mut i = 0; + while let Some(&c) = cs.get(i) { + if c.is_ascii_digit() || (c == '.' && cs.get(i + 1).is_some_and(char::is_ascii_digit)) { + let mut num = String::new(); + while let Some(&d) = + cs.get(i).filter(|d| d.is_ascii_digit() || **d == '.' || **d == ',' && cs.get(i + 1).is_some_and(char::is_ascii_digit)) + { + num.push(d); + i += 1; + } + let num: String = if bold { num.chars().map(|d| math_alnum(d, true, false, MScr::Roman)).collect() } else { num }; + o.push_str(&format!("{}", esc(&num))); + continue; + } + i += 1; + if c.is_whitespace() || (eq_arr && c == '&') { + continue; + } + if c.is_alphabetic() { + if bold || r.scr != MScr::Roman { + let m = math_alnum(c, bold, italic, r.scr); + let plain = if m == c && !italic { " mathvariant=\"normal\"" } else { "" }; + o.push_str(&format!("{}", esc(&m.to_string()))); + } else if italic { + o.push_str(&format!("{}", esc(&c.to_string()))); + } else { + o.push_str(&format!("{}", esc(&c.to_string()))); + } + } else if math_class(c) == MClass::Ord && !c.is_ascii_punctuation() && c != '\u{2061}' { + // ∞, ∂, ∅, ℏ…: identifiers, not operators. + o.push_str(&format!("{}", esc(&c.to_string()))); + } else { + mo(c, &color, o); + } + } +} + +/// A function name (`sin`, `lim`): one upright identifier when it's plain text. +fn func_name(name: &[MNode], o: &mut String, depth: usize) { + match name { + [MNode::Run(r)] if !r.nor && r.text.chars().all(char::is_alphabetic) && !r.text.is_empty() => { + o.push_str(&format!("{}", esc(&r.text))); + } + _ => group(name, o, depth), + } +} + +fn fraction(kind: FracKind, num: &[MNode], den: &[MNode], o: &mut String, depth: usize) { + match kind { + FracKind::Bar | FracKind::NoBar => { + o.push_str(if kind == FracKind::NoBar { "" } else { "" }); + group(num, o, depth); + group(den, o, depth); + o.push_str(""); + } + FracKind::Skewed | FracKind::Linear => { + o.push_str(""); + group(num, o, depth); + mo(if kind == FracKind::Skewed { '⁄' } else { '/' }, "", o); + group(den, o, depth); + o.push_str(""); + } + } +} + +fn script(kind: ScriptKind, base: &[MNode], sub: &[MNode], sup: &[MNode], o: &mut String, depth: usize) { + match kind { + ScriptKind::Sup => { + o.push_str(""); + group(base, o, depth); + group(sup, o, depth); + o.push_str(""); + } + ScriptKind::Sub => { + o.push_str(""); + group(base, o, depth); + group(sub, o, depth); + o.push_str(""); + } + ScriptKind::SubSup => { + o.push_str(""); + group(base, o, depth); + group(sub, o, depth); + group(sup, o, depth); + o.push_str(""); + } + ScriptKind::Pre => { + o.push_str(""); + group(base, o, depth); + o.push_str(""); + if sub.is_empty() { + o.push_str(""); + } else { + group(sub, o, depth); + } + if sup.is_empty() { + o.push_str(""); + } else { + group(sup, o, depth); + } + o.push_str(""); + } + } +} + +fn write_nary(n: &MNode, o: &mut String, depth: usize) { + let MNode::Nary { chr, lim_loc, sub_hide, sup_hide, sub, sup, e, .. } = n else { return }; + let under_over = match lim_loc { + Some(l) => *l == LimLoc::UndOvr, + None => !is_integral(*chr), + }; + let has_sub = !*sub_hide && !sub.is_empty(); + let has_sup = !*sup_hide && !sup.is_empty(); + let tag = match (under_over, has_sub, has_sup) { + (_, false, false) => "", + (true, true, true) => "munderover", + (true, true, false) => "munder", + (true, false, true) => "mover", + (false, true, true) => "msubsup", + (false, true, false) => "msub", + (false, false, true) => "msup", + }; + o.push_str(""); + if !tag.is_empty() { + o.push_str(&format!("<{tag}>")); + } + mo(*chr, " largeop=\"true\" movablelimits=\"false\"", o); + if has_sub { + group(sub, o, depth); + } + if has_sup { + group(sup, o, depth); + } + if !tag.is_empty() { + o.push_str(&format!("")); + } + group(e, o, depth); + o.push_str(""); +} + +fn delimiters(n: &MNode, o: &mut String, depth: usize) { + let MNode::Delim { beg, end, sep, grow, elems, .. } = n else { return }; + let stretchy = if *grow { "" } else { " stretchy=\"false\"" }; + o.push_str(""); + if let Some(begin) = beg { + mo(*begin, &format!(" fence=\"true\" form=\"prefix\"{stretchy}"), o); + } + for (i, element) in elems.iter().enumerate() { + if i > 0 { + mo(sep.unwrap_or('|'), &format!(" separator=\"true\"{stretchy}"), o); + } + group(element, o, depth); + } + if let Some(close) = end { + mo(*close, &format!(" fence=\"true\" form=\"postfix\"{stretchy}"), o); + } + o.push_str(""); +} + +fn node(n: &MNode, o: &mut String, depth: usize, eq_arr: bool) { + match n { + MNode::Run(r) => run(r, o, eq_arr), + MNode::Frac { kind, num, den } => fraction(*kind, num, den, o, depth), + MNode::Script { kind, base, sub, sup } => script(*kind, base, sub, sup, o, depth), + MNode::Rad { deg, deg_hide, e } => { + if *deg_hide || deg.is_empty() { + o.push_str(""); + arg(e, o, depth, false); + o.push_str(""); + } else { + o.push_str(""); + group(e, o, depth); + group(deg, o, depth); + o.push_str(""); + } + } + MNode::Nary { .. } => write_nary(n, o, depth), + MNode::Delim { .. } => delimiters(n, o, depth), + MNode::Func { name, e } => { + o.push_str(""); + func_name(name, o, depth); + mo('\u{2061}', "", o); + group(e, o, depth); + o.push_str(""); + } + MNode::Lim { upper, e, lim } => { + let tag = if *upper { "mover" } else { "munder" }; + o.push_str(&format!("<{tag}>")); + func_name(e, o, depth); + group(lim, o, depth); + o.push_str(&format!("")); + } + MNode::Acc { chr, e } => { + o.push_str(""); + group(e, o, depth); + mo(spacing_accent(*chr), "", o); + o.push_str(""); + } + MNode::Bar { top, e } => { + if *top { + o.push_str(""); + group(e, o, depth); + mo('\u{203E}', "", o); + o.push_str(""); + } else { + o.push_str(""); + group(e, o, depth); + mo('_', "", o); + o.push_str(""); + } + } + MNode::BorderBox { hide, strike, e } => { + let mut notation: Vec<&str> = Vec::new(); + for (h, name) in hide.iter().zip(["top", "bottom", "left", "right"]) { + if !h { + notation.push(name); + } + } + if notation.len() == 4 { + notation = vec!["box"]; + } + for (s, name) in strike.iter().zip(["horizontalstrike", "verticalstrike", "updiagonalstrike", "downdiagonalstrike"]) { + if *s { + notation.push(name); + } + } + o.push_str(&format!("", notation.join(" "))); + arg(e, o, depth, false); + o.push_str(""); + } + MNode::Boxed { e } => group(e, o, depth), + MNode::GroupChr { chr, top, e } => { + let tag = if *top { "mover" } else { "munder" }; + o.push_str(&format!("<{tag}>")); + group(e, o, depth); + mo(*chr, " stretchy=\"true\"", o); + o.push_str(&format!("")); + } + MNode::EqArr { rows } => { + // `displaystyle` marks an equation array; a bare one-column table reads as a matrix. + o.push_str(""); + for r in rows { + o.push_str(""); + arg(r, o, depth, true); + o.push_str(""); + } + o.push_str(""); + } + MNode::Matrix { rows, col_jc } => { + o.push_str(""); + for r in rows { + o.push_str(""); + for (k, cell) in r.iter().enumerate() { + match col_jc.get(k) { + Some(ColJc::Left) => o.push_str(""), + Some(ColJc::Right) => o.push_str(""), + _ => o.push_str(""), + } + arg(cell, o, depth, false); + o.push_str(""); + } + o.push_str(""); + } + o.push_str(""); + } + MNode::Phant { show, zero_wid, zero_asc, zero_desc, e } => { + let mut pad = String::new(); + for (z, a) in [(zero_wid, "width"), (zero_asc, "height"), (zero_desc, "depth")] { + if *z { + pad.push_str(&format!(" {a}=\"0\"")); + } + } + if !pad.is_empty() { + o.push_str(&format!("")); + } + o.push_str(if *show { "" } else { "" }); + arg(e, o, depth, false); + o.push_str(if *show { "" } else { "" }); + if !pad.is_empty() { + o.push_str(""); + } + } + } +} + +/// Combining accents (how equations keep them) and the spacing characters MathML puts over the +/// base, both ways. +const ACCENTS: &[(char, char)] = &[ + ('\u{0302}', '^'), + ('\u{0303}', '~'), + ('\u{0304}', '¯'), + ('\u{0305}', '\u{203E}'), + ('\u{0306}', '˘'), + ('\u{0307}', '˙'), + ('\u{0308}', '¨'), + ('\u{030C}', 'ˇ'), + ('\u{0301}', '´'), + ('\u{0300}', '`'), + ('\u{030A}', '˚'), + ('\u{20D7}', '→'), + ('\u{20D6}', '←'), + ('\u{20E1}', '↔'), + ('\u{20D1}', '⇀'), + ('\u{20D0}', '↼'), +]; + +fn spacing_accent(c: char) -> char { + ACCENTS.iter().find(|(comb, _)| *comb == c).map(|(_, s)| *s).unwrap_or(c) +} + +fn combining_accent(c: char) -> Option { + let c = match c { + 'ˆ' => '^', + '˜' => '~', + '‾' => '\u{203E}', + '\u{20D7}' | '\u{0302}' | '\u{0303}' | '\u{0307}' | '\u{0308}' => return Some(c), + c => c, + }; + ACCENTS.iter().find(|(_, s)| *s == c).map(|(comb, _)| *comb) +} + +// --------------------------------------------------------------------------------------------- +// Reader + +/// Most elements read from one `` element. +pub const MAX_NODES: usize = 20_000; + +/// A parsed MathML element (namespace prefixes dropped, names lowercase). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct El { + pub name: String, + pub attrs: Vec<(String, String)>, + pub children: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Item { + El(El), + Text(String), +} + +impl El { + fn attr(&self, name: &str) -> Option<&str> { + self.attrs.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str()) + } + fn els(&self) -> impl Iterator { + self.children.iter().filter_map(|c| match c { + Item::El(e) => Some(e), + Item::Text(_) => None, + }) + } + /// The text inside, all descendants (depth-limited). + pub fn text(&self) -> String { + let mut s = String::new(); + text_into(self, &mut s, 0); + s + } +} + +fn text_into(e: &El, s: &mut String, depth: usize) { + if depth > MAX_DEPTH { + return; + } + for c in &e.children { + match c { + Item::Text(t) => s.push_str(t), + Item::El(c) => text_into(c, s, depth + 1), + } + } +} + +/// The first `` element of XML text (the root or a descendant, any prefix), as an [`El`]: +/// for MathML read from an XML file or a clipboard format. At most [`MAX_NODES`] elements are +/// kept; `None` when there is no `math` element or the text is not XML. +pub fn parse(xml: &str) -> Option { + let limits = craft_xml::Limits { max_nodes: MAX_NODES.saturating_mul(4), max_depth: MAX_DEPTH.saturating_mul(2), ..craft_xml::Limits::DEFAULT }; + let (root, _) = craft_xml::Options { ns_decls: false, ..craft_xml::Options::default() }.with_limits(limits).parse_streaming_partial( + xml.as_bytes(), + &[], + |_| Ok::<(), craft_xml::Error>(()), + ); + let root = root?; + let math = if local(&root.name).eq_ignore_ascii_case("math") { &root } else { root.find(craft_xml::Local("math"))? }; + let mut budget = MAX_NODES; + Some(from_xml(math, 0, &mut budget)) +} + +fn from_xml(e: &craft_xml::El, depth: usize, budget: &mut usize) -> El { + let mut out = El { name: e.name.to_ascii_lowercase(), attrs: e.attrs.clone(), children: Vec::new() }; + if depth > MAX_DEPTH { + return out; + } + for n in &e.children { + match n { + craft_xml::Node::El(c) if *budget > 0 => { + *budget -= 1; + out.children.push(Item::El(from_xml(c, depth + 1, budget))); + } + craft_xml::Node::Text(t) => out.children.push(Item::Text(t.clone())), + _ => {} + } + } + out +} + +/// The element name without a namespace prefix (`m:math`, `mml:mfrac`). +pub fn local(name: &str) -> &str { + name.rsplit(':').next().unwrap_or(name) +} + +/// The linear format of a `` element, and whether it's a display equation. `None` when it +/// holds nothing. +pub fn read(math: &El) -> Option<(String, bool)> { + let display = + math.attr("display").is_some_and(|d| d.eq_ignore_ascii_case("block")) || math.attr("mode").is_some_and(|d| d.eq_ignore_ascii_case("display")); + let linear = linear_of(math); + let linear: String = linear.chars().filter(|c| !c.is_control()).collect(); + let linear = linear.trim().to_string(); + (!linear.is_empty()).then_some((linear, display)) +} + +fn linear_of(math: &El) -> String { + // Our own copy carries the linear format exactly. + if let Some(sem) = math.els().find(|e| local(&e.name) == "semantics") { + let ann = |enc: &dyn Fn(&str) -> bool| { + sem.els() + .filter(|e| local(&e.name) == "annotation") + .find(|e| e.attr("encoding").is_some_and(|v| enc(&v.to_ascii_lowercase()))) + .map(El::text) + .filter(|t| !t.trim().is_empty()) + }; + if let Some(t) = ann(&|v| v == UNICODEMATH) { + return t; + } + let tree = to_tree(math); + if !tree.is_empty() { + return to_linear(&tree); + } + if let Some(t) = ann(&|v| v.contains("tex")) { + return to_linear(&crate::math_latex::parse_latex(&t)); + } + return String::new(); + } + to_linear(&to_tree(math)) +} + +/// A MathML element's children as an equation tree. +pub fn to_tree(math: &El) -> Arg { + let mut budget = MAX_NODES; + crate::math::merge_runs(children(math, 0, &mut budget)) +} + +fn children(e: &El, depth: usize, budget: &mut usize) -> Arg { + let els: Vec<&El> = e.els().collect(); + seq(&els, depth, budget) +} + +/// A sequence of elements; an n-ary operator without an operand takes the next element. +fn seq(els: &[&El], depth: usize, budget: &mut usize) -> Arg { + let mut out: Arg = Vec::new(); + let mut i = 0; + while let Some(el) = els.get(i) { + i += 1; + // A function name (`sin`) applies to the next element even without U+2061, + // so it doesn't merge with it into `sinx`. Before an operator (`(`, U+2061) the runs + // merge and the linear format finds the function itself. + if local(&el.name) == "mi" + && let Some(next) = els.get(i).filter(|n| local(&n.name) != "mo") + { + let t = el.text(); + let t = t.trim(); + if FUNCTION_NAMES.contains(&t) && *budget > 0 { + *budget -= 1; + i += 1; + out.push(MNode::Func { name: vec![MNode::Run(MRun::plain(t))], e: elem(next, depth + 1, budget) }); + continue; + } + } + let mut a = elem(el, depth, budget); + if let [MNode::Nary { e, .. }] = a.as_mut_slice() + && e.is_empty() + && let Some(next) = els.get(i) + { + i += 1; + *e = elem(next, depth, budget); + } + out.extend(a); + } + out +} + +/// The `k`th child element as an argument. +fn nth(e: &El, k: usize, depth: usize, budget: &mut usize) -> Arg { + e.els().nth(k).map(|c| elem(c, depth, budget)).unwrap_or_default() +} + +/// A lone operator character (`∑`). +fn lone_char(a: &[MNode]) -> Option { + match a { + [MNode::Run(r)] => { + let mut cs = r.text.trim().chars(); + let c = cs.next()?; + cs.next().is_none().then_some(c) + } + _ => None, + } +} + +/// A plain word (`lim`, `max`). +fn word(a: &[MNode]) -> bool { + matches!(a, [MNode::Run(r)] if r.text.chars().count() > 1 && r.text.chars().all(char::is_alphabetic)) +} + +fn elem(e: &El, depth: usize, budget: &mut usize) -> Arg { + if depth > MAX_DEPTH || *budget == 0 { + return Vec::new(); + } + *budget -= 1; + let d = depth + 1; + match local(&e.name) { + "mi" | "mn" | "mo" | "ms" => { + let t = e.text(); + let t = t.trim(); + if t.is_empty() { + return Vec::new(); + } + let mut r = MRun::new(t); + if local(&e.name) == "mi" && e.attr("mathvariant") == Some("normal") && t.chars().count() == 1 { + r.sty = Some(MSty::Plain); + } + vec![MNode::Run(r)] + } + "mtext" => { + let t = e.text(); + if t.trim().is_empty() { + return Vec::new(); + } + vec![MNode::Run(MRun { text: t, nor: true, ..Default::default() })] + } + "mfrac" => { + let thin = e.attr("linethickness").is_some_and(|t| { + let s = t.trim(); + s.eq_ignore_ascii_case("none") || s.trim_end_matches(|c: char| c.is_alphabetic() || c == '%').trim() == "0" + }); + let kind = if e.attr("bevelled").is_some_and(|b| b.eq_ignore_ascii_case("true")) { + FracKind::Skewed + } else if thin { + FracKind::NoBar + } else { + FracKind::Bar + }; + vec![MNode::Frac { kind, num: nth(e, 0, d, budget), den: nth(e, 1, d, budget) }] + } + "msqrt" => vec![MNode::Rad { deg: Vec::new(), deg_hide: true, e: children(e, d, budget) }], + "mroot" => vec![MNode::Rad { deg: nth(e, 1, d, budget), deg_hide: false, e: nth(e, 0, d, budget) }], + "msup" | "msub" | "msubsup" => { + let name = local(&e.name); + let base = nth(e, 0, d, budget); + let (sub, sup) = match name { + "msup" => (Vec::new(), nth(e, 1, d, budget)), + "msub" => (nth(e, 1, d, budget), Vec::new()), + _ => (nth(e, 1, d, budget), nth(e, 2, d, budget)), + }; + if let Some(c) = lone_char(&base).filter(|c| is_nary_char(*c)) { + return vec![nary(c, LimLoc::SubSup, sub, sup)]; + } + let kind = match name { + "msup" => ScriptKind::Sup, + "msub" => ScriptKind::Sub, + _ => ScriptKind::SubSup, + }; + vec![MNode::Script { kind, base, sub, sup }] + } + "munder" | "mover" | "munderover" => { + let name = local(&e.name); + let base = nth(e, 0, d, budget); + let (under, over) = match name { + "munder" => (nth(e, 1, d, budget), Vec::new()), + "mover" => (Vec::new(), nth(e, 1, d, budget)), + _ => (nth(e, 1, d, budget), nth(e, 2, d, budget)), + }; + if let Some(c) = lone_char(&base).filter(|c| is_nary_char(*c)) { + return vec![nary(c, LimLoc::UndOvr, under, over)]; + } + if name == "munderover" { + let inner = MNode::Lim { upper: false, e: base, lim: under }; + return vec![MNode::Lim { upper: true, e: vec![inner], lim: over }]; + } + let upper = name == "mover"; + let mark = if upper { lone_char(&over) } else { lone_char(&under) }; + match mark { + Some('\u{203E}' | '¯' | '‾') if upper => vec![MNode::Bar { top: true, e: base }], + Some('_' | '\u{203E}' | '¯') if !upper => vec![MNode::Bar { top: false, e: base }], + Some(c @ ('⏞' | '⏟' | '⏜' | '⏝' | '⎴' | '⎵' | '←' | '→' | '↔' | '⇐' | '⇒' | '⇔')) if !word(&base) => { + vec![MNode::GroupChr { chr: c, top: upper, e: base }] + } + Some(c) if upper && combining_accent(c).is_some() => vec![MNode::Acc { chr: combining_accent(c).unwrap_or(c), e: base }], + _ => vec![MNode::Lim { upper, e: base, lim: if upper { over } else { under } }], + } + } + "mmultiscripts" => { + let els: Vec<&El> = e.els().collect(); + let base = els.first().map(|b| elem(b, d, budget)).unwrap_or_default(); + let pre_at = els.iter().position(|c| local(&c.name) == "mprescripts"); + let script = + |k: usize, budget: &mut usize| els.get(k).filter(|c| local(&c.name) != "none").map(|c| elem(c, d, budget)).unwrap_or_default(); + match pre_at { + Some(p) => { + let sub = script(p + 1, budget); + let sup = script(p + 2, budget); + let pre_node = MNode::Script { kind: ScriptKind::Pre, base, sub, sup }; + if p > 1 { + let post_sub = script(1, budget); + let post_sup = script(2, budget); + let kind = match (post_sub.is_empty(), post_sup.is_empty()) { + (true, true) => return vec![pre_node], + (false, true) => ScriptKind::Sub, + (true, false) => ScriptKind::Sup, + (false, false) => ScriptKind::SubSup, + }; + vec![MNode::Script { kind, base: vec![pre_node], sub: post_sub, sup: post_sup }] + } else { + vec![pre_node] + } + } + None => { + let sub = script(1, budget); + let sup = script(2, budget); + let kind = match (sub.is_empty(), sup.is_empty()) { + (true, true) => return base, + (false, true) => ScriptKind::Sub, + (true, false) => ScriptKind::Sup, + (false, false) => ScriptKind::SubSup, + }; + vec![MNode::Script { kind, base, sub, sup }] + } + } + } + "mfenced" => { + let first = |a: &str, dflt: char| e.attr(a).map(|v| v.trim().chars().next()).unwrap_or(Some(dflt)); + let beg = first("open", '('); + let end = first("close", ')'); + let sep = first("separators", ','); + let elems: Vec = e.els().map(|c| elem(c, d, budget)).collect(); + vec![MNode::Delim { beg, end, sep, grow: true, shp_match: false, elems }] + } + "mtable" => { + let mtr_list: Vec<&El> = e.els().filter(|r| matches!(local(&r.name), "mtr" | "mlabeledtr")).take(256).collect(); + let rows: Vec> = + mtr_list.iter().map(|r| r.els().filter(|c| local(&c.name) == "mtd").take(256).map(|c| children(c, d, budget)).collect()).collect(); + if rows.is_empty() { + return Vec::new(); + } + // One column is an equation array only when marked as one (`displaystyle`, alignment + // marks, labelled rows, as TeX's align and our own writer give); else a column vector. + let marked = + e.attr("displaystyle").is_some_and(|v| v.trim() == "true") || e.els().any(|r| local(&r.name) == "mlabeledtr") || has_align_mark(e, 0); + if marked && rows.iter().all(|r| r.len() <= 1) { + return vec![MNode::EqArr { rows: rows.into_iter().map(|mut r| r.pop().unwrap_or_default()).collect() }]; + } + let mut col_jc: Vec = e + .attr("columnalign") + .map(|ca| { + ca.split_whitespace() + .map(|a| match a { + "left" => ColJc::Left, + "right" => ColJc::Right, + _ => ColJc::Center, + }) + .collect() + }) + .unwrap_or_default(); + if col_jc.is_empty() + && let Some(first_row) = mtr_list.first() + { + let cell_aligns: Vec = first_row + .els() + .filter(|c| local(&c.name) == "mtd") + .map(|c| match c.attr("columnalign") { + Some("left") => ColJc::Left, + Some("right") => ColJc::Right, + _ => ColJc::Center, + }) + .collect(); + if cell_aligns.iter().any(|a| *a != ColJc::Center) { + col_jc = cell_aligns; + } + } + vec![MNode::Matrix { rows, col_jc }] + } + "mpadded" => { + let zero_wid = e.attr("width").is_some_and(|w| w.trim() == "0"); + let zero_asc = e.attr("height").is_some_and(|h| h.trim() == "0"); + let zero_desc = e.attr("depth").is_some_and(|d| d.trim() == "0"); + let ch = children(e, d, budget); + if zero_wid || zero_asc || zero_desc { + if let [MNode::Phant { show, e, .. }] = ch.as_slice() { + vec![MNode::Phant { show: *show, zero_wid, zero_asc, zero_desc, e: e.clone() }] + } else { + vec![MNode::Phant { show: true, zero_wid, zero_asc, zero_desc, e: ch }] + } + } else { + ch + } + } + "mphantom" => vec![MNode::Phant { show: false, zero_wid: false, zero_asc: false, zero_desc: false, e: children(e, d, budget) }], + "menclose" => { + let n = e.attr("notation").unwrap_or("longdiv"); + let has = |k: &str| n.split_whitespace().any(|w| w.eq_ignore_ascii_case(k)); + if has("radical") { + return vec![MNode::Rad { deg: Vec::new(), deg_hide: true, e: children(e, d, budget) }]; + } + // An actuarial symbol is the top and right edges. + let actuarial = has("actuarial"); + let is_box = has("box") || has("roundedbox") || has("circle"); + let (top, right) = (has("top") || actuarial, has("right") || actuarial); + let has_border = is_box || top || has("bottom") || has("left") || right; + let strike = + [has("horizontalstrike"), has("verticalstrike"), has("updiagonalstrike") || has("cross"), has("downdiagonalstrike") || has("cross")]; + if has_border || strike.iter().any(|&s| s) { + let hide = if is_box { + [false; 4] + } else if has_border { + [!top, !has("bottom"), !has("left"), !right] + } else { + [true; 4] + }; + return vec![MNode::BorderBox { hide, strike, e: children(e, d, budget) }]; + } + children(e, d, budget) + } + // The first child of `semantics` is the presentation; annotations aren't content. + "semantics" => e.els().next().map(|c| elem(c, d, budget)).unwrap_or_default(), + "annotation" | "annotation-xml" | "mspace" | "none" | "mprescripts" | "maligngroup" | "malignmark" => Vec::new(), + _ => children(e, d, budget), + } +} + +/// Whether `e` holds a `maligngroup` or `malignmark` near the top (in a cell or a row inside it). +fn has_align_mark(e: &El, depth: usize) -> bool { + depth <= 4 && e.els().any(|c| matches!(local(&c.name), "maligngroup" | "malignmark") || has_align_mark(c, depth + 1)) +} + +fn nary(chr: char, lim_loc: LimLoc, sub: Arg, sup: Arg) -> MNode { + let lim_loc = Some(lim_loc).filter(|l| *l != if is_integral(chr) { LimLoc::SubSup } else { LimLoc::UndOvr }); + MNode::Nary { chr, lim_loc, grow: false, sub_hide: sub.is_empty(), sup_hide: sup.is_empty(), sub, sup, e: Vec::new() } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::math::parse_linear; + + fn ml(linear: &str) -> String { + to_mathml(&parse_linear(linear), false, "") + } + + #[test] + fn runs_split_into_identifiers_numbers_and_operators() { + let m = ml("y=2x"); + assert!(m.starts_with(""), "{m}"); + assert!(m.contains("y=2x"), "{m}"); + assert!(m.contains("y=2x"), "{m}"); + assert!(to_mathml(&parse_linear("x"), true, "").contains("display=\"block\"")); + } + + #[test] + fn structures_become_their_elements() { + for (linear, want) in [ + ("a/b", "ab"), + ("x^2", "x2"), + ("x_s", "xs"), + ("x_i^2", ""), + ("√x", "x"), + ("√(3&x)", "x3"), + ("∑_(i=1)^n▒i", "∑"), + ("∫_0^1▒x", "∫"), + ("(a+b)", "("), + ("sin⁡x", "sin\u{2061}"), + ("■(a&b@c&d)", "ab"), + ] { + let m = ml(linear); + assert!(m.contains(want), "{linear}: {m}"); + } + let acc = to_mathml(&[MNode::Acc { chr: '\u{0302}', e: parse_linear("a") }], false, ""); + assert!(acc.contains("a^"), "{acc}"); + let bar = to_mathml(&[MNode::Bar { top: true, e: parse_linear("a") }], false, ""); + assert!(bar.contains("\u{203E}"), "{bar}"); + let lim = to_mathml(&[MNode::Lim { upper: false, e: parse_linear("lim"), lim: parse_linear("n→∞") }], false, ""); + assert!(lim.contains("limn→∞"), "{lim}"); + let bb = to_mathml(&[MNode::BorderBox { hide: [false; 4], strike: [false; 4], e: parse_linear("a") }], false, ""); + assert!(bb.contains(""), "{bb}"); + let gc = to_mathml(&[MNode::GroupChr { chr: '⏟', top: false, e: parse_linear("a") }], false, ""); + assert!(gc.contains("a⏟"), "{gc}"); + let pre = to_mathml(&[MNode::Script { kind: ScriptKind::Pre, base: parse_linear("C"), sub: parse_linear("n"), sup: vec![] }], false, ""); + assert!(pre.contains("") && pre.contains(""), "{pre}"); + let eq = to_mathml(&[MNode::EqArr { rows: vec![parse_linear("x&=1"), parse_linear("y&=2")] }], false, ""); + assert!(eq.contains("x=1") && !eq.contains("&"), "{eq}"); + let ph = to_mathml(&[MNode::Phant { show: false, zero_wid: true, zero_asc: false, zero_desc: false, e: parse_linear("a") }], false, ""); + assert!(ph.contains(""), "{ph}"); + let styled = to_mathml( + &[ + MNode::Run(MRun { text: "R".into(), scr: MScr::DoubleStruck, ..Default::default() }), + MNode::Run(MRun::plain("d")), + MNode::Run(MRun { text: "speed".into(), nor: true, ..Default::default() }), + ], + false, + "", + ); + assert!( + styled.contains("ℝ") && styled.contains("d") && styled.contains("speed"), + "{styled}" + ); + // Text is escaped. + assert!(ml("a<")); + } + + fn pasted(xml: &str) -> Vec<(String, bool)> { + parse(xml).and_then(|m| read(&m)).into_iter().collect() + } + + #[test] + fn written_mathml_reads_back_exactly() { + for (linear, display) in [("y=2x_s", false), ("x=(-b±√(b^2-4ac))/2a", true), ("∑_(k=1)^n▒k", false), ("■(a&b@c&d)", false)] { + let xml = linear_to_mathml(linear, display); + assert!(xml.starts_with("Before {xml} after

")), vec![(linear.to_string(), display)], "{xml}"); + } + } + + #[test] + fn foreign_mathml_is_read_from_its_elements() { + let cases = [ + ("y=2xs", "y=2x_s"), + ("ab+1", "a/(b+1)"), + ("x", "√x"), + ("∑k=1nk", "∑_(k=1)^n▒k"), + ("ex", "e^x"), + // A TeX annotation is used when the presentation is empty. + ("\\frac{1}{2}", "1/2"), + ]; + for (html, want) in cases { + let got = pasted(html); + assert_eq!(got.first().map(|g| g.0.as_str()), Some(want), "{html}"); + } + assert!(pasted("x").first().is_some_and(|g| g.1)); + // An unclosed element ends with the input. + assert!(!pasted("

x").is_empty()); + // Hostile nesting is bounded. + let deep = format!("{}x{}", "".repeat(5000), "".repeat(5000)); + assert!(pasted(&deep).len() <= 1); + } + + #[test] + fn math_over_the_node_cap_keeps_the_first_elements() { + let xml = format!("{}z", "y".repeat(MAX_NODES * 2)); + let el = parse(&xml).unwrap(); + assert_eq!(el.children.len(), MAX_NODES); + assert!(read(&el).is_some_and(|(l, _)| !l.contains('z'))); + // Not XML, or no math element: nothing. + assert!(parse("").is_none() && parse("

no math

").is_none() && parse("\u{0}<<").is_none()); + } + + #[test] + fn function_names_apply_without_the_invisible_operator() { + let cases = [ + ("sinx", "sin\u{2061}x"), + ("logab", "log\u{2061}ab"), + ("cos\u{2061}x", "cos\u{2061}x"), + ("abx", "abx"), + ]; + for (html, want) in cases { + assert_eq!(pasted(html).first().map(|g| g.0.as_str()), Some(want), "{html}"); + } + let tree = to_tree(&El { + name: "math".into(), + attrs: vec![], + children: vec![ + Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("sin".into())] }), + Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("x".into())] }), + ], + }); + assert!(matches!(tree.as_slice(), [MNode::Func { .. }]), "{tree:?}"); + } + + #[test] + fn one_column_tables_are_column_vectors_unless_marked() { + let tree = |html: &str| { + let linear = pasted(html).first().map(|g| g.0.clone()).unwrap_or_default(); + crate::math::parse_linear(&linear) + }; + let vector = tree("ab"); + assert!(matches!(vector.as_slice(), [MNode::Matrix { rows, .. }] if rows.len() == 2), "{vector:?}"); + for marked in [ + "ab", + "a=1b", + ] { + let t = tree(marked); + assert!(matches!(t.as_slice(), [MNode::EqArr { rows }] if rows.len() == 2), "{marked}: {t:?}"); + } + // Our own equation arrays read back as equation arrays from their elements alone. + let ml = to_mathml(&[MNode::EqArr { rows: vec![parse_linear("x=1"), parse_linear("y=2")] }], false, ""); + let ml = ml.replace("application/x-unicodemath", "x-ignored"); + let t = tree(&ml); + assert!(matches!(t.as_slice(), [MNode::EqArr { .. }]), "{ml}: {t:?}"); + } + + #[test] + fn mmultiscripts_and_borderbox_round_trip() { + let html = "X12"; + let p = pasted(html); + assert!(!p.is_empty(), "should parse mmultiscripts with pre and post scripts"); + + let html_box = "x"; + let p_box = pasted(html_box); + assert!(!p_box.is_empty(), "should parse menclose"); + + let html_tbl = "ab"; + let p_tbl = pasted(html_tbl); + assert!(!p_tbl.is_empty(), "should parse mtable with columnalign"); + + let html_pad = "z"; + let p_pad = pasted(html_pad); + assert!(!p_pad.is_empty(), "should parse mpadded phantom"); + } + + #[test] + fn deep_nesting_is_bounded() { + let mut n = parse_linear("x"); + for _ in 0..500 { + n = vec![MNode::Frac { kind: FracKind::Bar, num: n, den: parse_linear("y") }]; + } + let m = to_mathml(&n, false, "z"); + assert!(m.ends_with("
")); + } + + #[test] + fn test_mfrac_linethickness_none_and_menclose_notations() { + let el_frac = El { + name: "mfrac".into(), + attrs: vec![("linethickness".into(), "none".into())], + children: vec![ + Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("n".into())] }), + Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("k".into())] }), + ], + }; + let mut budget = MAX_NODES; + let tree_frac = elem(&el_frac, 0, &mut budget); + assert!(matches!(tree_frac.as_slice(), [MNode::Frac { kind: FracKind::NoBar, .. }]), "{tree_frac:?}"); + + let el_strike = El { + name: "menclose".into(), + attrs: vec![("notation".into(), "horizontalstrike".into())], + children: vec![Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("x".into())] })], + }; + let mut budget = MAX_NODES; + let tree_strike = elem(&el_strike, 0, &mut budget); + assert!(matches!(tree_strike.as_slice(), [MNode::BorderBox { strike: [true, false, false, false], .. }]), "{tree_strike:?}"); + + let el_cross = El { + name: "menclose".into(), + attrs: vec![("notation".into(), "cross".into())], + children: vec![Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("x".into())] })], + }; + let mut budget = MAX_NODES; + let tree_cross = elem(&el_cross, 0, &mut budget); + assert!(matches!(tree_cross.as_slice(), [MNode::BorderBox { strike: [false, false, true, true], .. }]), "{tree_cross:?}"); + + let el_rad = El { + name: "menclose".into(), + attrs: vec![("notation".into(), "radical".into())], + children: vec![Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("x".into())] })], + }; + let mut budget = MAX_NODES; + let tree_rad = elem(&el_rad, 0, &mut budget); + assert!(matches!(tree_rad.as_slice(), [MNode::Rad { deg_hide: true, .. }]), "{tree_rad:?}"); + } +} diff --git a/crates/math/src/omml.rs b/crates/math/src/omml.rs new file mode 100644 index 000000000..99024ec8b --- /dev/null +++ b/crates/math/src/omml.rs @@ -0,0 +1,232 @@ +//! Office Math Markup (OMML, ECMA-376 Part 1 §22.1) read into and written from the equation tree +//! ([`crate::math`]). +//! +//! The reader takes an `m:oMath` element of a [`craft_xml`] tree read with the canonical +//! prefixes of [`NAMESPACES`] (`m:` for math, `w:` for WordprocessingML, `mc:` for markup +//! compatibility), whatever prefixes the file used; [`parse`] does that for a string. It keeps +//! the source XML in [`Math::omml`], and the writer writes that back unchanged while the +//! equation's colour is the same, so a saved file carries the equation exactly as Word wrote it. +//! The writer otherwise writes the tree: `m:oMath`, inside `m:oMathPara` for a display equation. + +use craft_xml::{Canonical, El, Options}; + +use crate::math::{Math, MathJc}; +use crate::rgb::Rgb; + +mod read; +mod write; + +pub use read::{lift_color, para_jc, read_math_pr, read_omath}; +pub use write::{math_pr, resolve_numbers, write_equation}; + +/// The OMML namespace (transitional), and the strict one. +pub const MATH_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/math"; +pub const MATH_NS_STRICT: &str = "http://purl.oclc.org/ooxml/officeDocument/math"; +/// The WordprocessingML namespace OMML runs borrow (`w:rPr`, `w:t`, `w:sym`), transitional and +/// strict. +pub const W_NS: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; +pub const W_NS_STRICT: &str = "http://purl.oclc.org/ooxml/wordprocessingml/main"; +/// Markup compatibility (`mc:AlternateContent`). +pub const MC_NS: &str = "http://schemas.openxmlformats.org/markup-compatibility/2006"; + +/// The canonical prefixes the reader expects, for [`craft_xml::Canonical`]. +pub const NAMESPACES: &[(&str, &str)] = &[("m", MATH_NS), ("m", MATH_NS_STRICT), ("w", W_NS), ("w", W_NS_STRICT), ("mc", MC_NS)]; + +/// Most elements [`parse`] reads from one string. +pub const MAX_ELEMENTS: usize = 250_000; + +/// OMML text read into a tree with the canonical prefixes of [`NAMESPACES`]: the first +/// `m:oMathPara` or `m:oMath` element in it (the root or any descendant). `None` when there is +/// none, or the text is not XML. Text kept by the reader ([`Math::omml`]) declares no +/// namespaces; its prefixes are already the canonical ones and are read as written. +pub fn parse(xml: &str) -> Option { + let canonical = Canonical::new(NAMESPACES); + let limits = craft_xml::Limits { max_nodes: MAX_ELEMENTS.saturating_mul(2), ..craft_xml::Limits::DEFAULT }; + let first = |root: El| -> Option { + if matches!(root.name.as_str(), "m:oMath" | "m:oMathPara") { + return Some(root); + } + root.find("m:oMathPara").or_else(|| root.find("m:oMath")).cloned() + }; + let read = Options::canonical(&canonical).with_limits(limits).parse(xml.as_bytes()).ok().and_then(first); + read.or_else(|| parse_kept(xml).and_then(first)) +} + +/// Kept OMML (canonical prefixes, no declarations) read as written. +fn parse_kept(xml: &str) -> Option { + let limits = craft_xml::Limits { max_nodes: MAX_ELEMENTS.saturating_mul(2), ..craft_xml::Limits::DEFAULT }; + Options { ns_decls: false, ..Options::default() }.with_limits(limits).parse(xml.as_bytes()).ok() +} + +/// Is `xml` (kept OMML) well-formed enough to write back as it is? +fn is_well_formed(xml: &str) -> bool { + xml.starts_with(" Option { + let e = parse(xml)?; + if e.name == "m:oMathPara" { + let jc = para_jc(&e); + return e.find("m:oMath").map(|m| read_omath(m, jc)); + } + Some(read_omath(&e, MathJc::default())) +} + +/// An equation as OMML text ([`write_equation`] into a string, no XML declaration). +pub fn write_str(linear: &str, display: bool, math: &Math, color: Option) -> String { + let mut w = W::default(); + write_equation(&mut w, linear, display, math, color); + w.s +} + +/// OMML on/off property of WordprocessingML (`w:b`, `w:i`): absent `w:val` = on. +fn on_off(e: &El) -> bool { + match e.attr_or_plain("w:val") { + None => true, + Some(v) => !matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE"), + } +} + +/// Largest absolute length accepted, points (200 inches). +const MAX_LEN_PT: f32 = 14_400.0; + +/// A twips value (`m:wrapIndent`), with or without an ISO 29500 universal measure (`1in`, +/// `2.5cm`, `12pt`), in points. +fn measure_twips(s: Option<&str>) -> Option { + let t = s?.trim(); + if t.is_empty() || t.len() > 40 { + return None; + } + let bytes = t.as_bytes(); + let mut split = t.len(); + let mut in_exp = false; + for (i, &b) in bytes.iter().enumerate() { + if b.is_ascii_digit() || b == b'.' { + in_exp = false; + continue; + } + if (b == b'-' || b == b'+') && (i == 0 || in_exp) { + in_exp = false; + continue; + } + if b == b'e' || b == b'E' { + let rest = bytes.get(i + 1..).unwrap_or_default(); + let after_sign = match rest.first() { + Some(&s) if s == b'+' || s == b'-' => rest.get(1..).unwrap_or_default(), + _ => rest, + }; + if after_sign.first().is_some_and(u8::is_ascii_digit) { + in_exp = true; + continue; + } + } + split = i; + break; + } + let (num, unit) = t.split_at(split); + let v: f64 = num.parse().ok()?; + if !v.is_finite() { + return None; + } + let pt = match unit.trim().to_ascii_lowercase().as_str() { + "" => v / 20.0, + "pt" => v, + "in" => v * 72.0, + "cm" => v * 72.0 / 2.54, + "mm" => v * 72.0 / 25.4, + "pc" | "pi" => v * 12.0, + "px" => v * 0.75, + "emu" => v / 12_700.0, + _ => return None, + }; + let pt = pt as f32; + pt.is_finite().then_some(pt.clamp(-MAX_LEN_PT, MAX_LEN_PT)) +} + +/// Points as a twips attribute value. +fn twips(pt: f32) -> String { + let pt = pt.clamp(-MAX_LEN_PT, MAX_LEN_PT); + let pt = if pt.is_finite() { pt } else { 0.0 }; + ((pt * 20.0).round() as i64).to_string() +} + +fn xml_char_ok(c: char) -> bool { + matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}') +} + +/// Escape text for element content or attribute values (drops characters XML can't carry). +fn esc(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => o.push_str("&"), + '<' => o.push_str("<"), + '>' => o.push_str(">"), + '"' => o.push_str("""), + '\'' => o.push_str("'"), + '\t' => o.push_str(" "), + '\n' => o.push_str(" "), + '\r' => o.push_str(" "), + c if xml_char_ok(c) => o.push(c), + _ => {} + } + } + o +} + +/// A string-building XML writer, as WordprocessingML writers write: names as given, values +/// escaped. +#[derive(Default)] +pub struct W { + pub s: String, +} + +impl W { + fn attrs(&mut self, attrs: &[(&str, &str)]) { + for (k, v) in attrs { + self.s.push(' '); + self.s.push_str(k); + self.s.push_str("=\""); + self.s.push_str(&esc(v)); + self.s.push('"'); + } + } + pub fn open(&mut self, name: &str, attrs: &[(&str, &str)]) { + self.s.push('<'); + self.s.push_str(name); + self.attrs(attrs); + self.s.push('>'); + } + pub fn empty(&mut self, name: &str, attrs: &[(&str, &str)]) { + self.s.push('<'); + self.s.push_str(name); + self.attrs(attrs); + self.s.push_str("/>"); + } + pub fn close(&mut self, name: &str) { + self.s.push_str("'); + } + pub fn text(&mut self, t: &str) { + self.s.push_str(&esc(t)); + } + /// `text`. + pub fn leaf(&mut self, name: &str, attrs: &[(&str, &str)], t: &str) { + self.open(name, attrs); + self.text(t); + self.close(name); + } + /// ``. + pub fn val(&mut self, name: &str, v: &str) { + self.empty(name, &[("w:val", v)]); + } + pub fn raw(&mut self, s: &str) { + self.s.push_str(s); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/math/src/omml/read.rs b/crates/math/src/omml/read.rs new file mode 100644 index 000000000..2f01f6fb4 --- /dev/null +++ b/crates/math/src/omml/read.rs @@ -0,0 +1,359 @@ +//! OMML into the tree. + +use craft_xml::El; + +use super::{measure_twips, on_off}; +use crate::math::{ + Arg, BrkBin, BrkBinSub, ColJc, FracKind, LimLoc, MAX_DEPTH, MNode, MRun, MScr, MSty, Math, MathJc, MathProps, ScriptKind, merge_runs, +}; +use crate::rgb::Rgb; +use crate::symbol_fonts; + +/// An `m:oMath` element as an equation (structure plus its source XML). +pub fn read_omath(e: &El, jc: MathJc) -> Math { + Math { nodes: merge_runs(arg(e, 0)), omml: e.to_xml(), jc, linear: false } +} + +/// A colour every math run shares, taken off the runs: it is the equation's own colour, as +/// [`write_equation`] spreads it (#1467). The source OMML +/// is kept: the writer replaces it only when the colour changes. +pub fn lift_color(math: &mut Math) -> Option { + let (mut shared, mut uniform) = (None, true); + crate::math_tree::each_run_mut(&mut math.nodes, &mut |r| match shared { + None => shared = Some(r.color), + Some(c) => uniform &= c == r.color, + }); + let c = shared.flatten().filter(|_| uniform)?; + crate::math_tree::each_run_mut(&mut math.nodes, &mut |r| r.color = None); + Some(c) +} + +/// `m:oMathParaPr/m:jc`. +pub fn para_jc(para: &El) -> MathJc { + match para.child("m:oMathParaPr").and_then(|p| p.child("m:jc")).and_then(|j| j.attr_or_plain("m:val")) { + Some("left") => MathJc::Left, + Some("right") => MathJc::Right, + Some("center") => MathJc::Center, + _ => MathJc::CenterGroup, + } +} + +/// The settings part's `m:mathPr`: how display equations wrap. +pub fn read_math_pr(e: &El) -> MathProps { + let mut m = MathProps::default(); + let pr = Some(e); + m.brk_bin = match val(pr, "m:brkBin") { + Some("after") => BrkBin::After, + Some("repeat") => BrkBin::Repeat, + _ => BrkBin::Before, + }; + m.brk_bin_sub = match val(pr, "m:brkBinSub") { + Some("-+") => BrkBinSub::MinusPlus, + Some("+-") => BrkBinSub::PlusMinus, + _ => BrkBinSub::MinusMinus, + }; + if let Some(v) = e.child("m:wrapIndent").and_then(|c| measure_twips(c.attr_or_plain("m:val"))).filter(|v| v.is_finite() && *v >= 0.0) { + m.wrap_indent = v.min(1584.0); + } + m.wrap_right = prop(pr, "m:wrapRight", false); + m +} + +/// OMML on/off property: absent `m:val` = on. +fn on(e: &El) -> bool { + match e.attr_or_plain("m:val") { + None => true, + Some(v) => !matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE"), + } +} + +/// An on/off property `name` in the properties element `pr` (absent = `default`). +fn prop(pr: Option<&El>, name: &str, default: bool) -> bool { + pr.and_then(|p| p.child(name)).map(on).unwrap_or(default) +} + +/// A character property (`m:chr`, `m:begChr`…): `None` when absent, `Some(None)` when empty. +fn chr(pr: Option<&El>, name: &str) -> Option> { + let c = pr?.child(name)?; + match c.attr_or_plain("m:val") { + Some(v) => Some(v.chars().next()), + None => Some(None), + } +} + +fn val<'a>(pr: Option<&'a El>, name: &str) -> Option<&'a str> { + pr.and_then(|p| p.child(name)).and_then(|c| c.attr_or_plain("m:val")) +} + +/// The argument held by child `name` of `e`. +fn sub_arg(e: &El, name: &str, depth: usize) -> Arg { + e.child(name).map(|c| arg(c, depth + 1)).unwrap_or_default() +} + +/// Read the math content of an element (`m:oMath`, `m:e`, `m:num`…). +fn arg(e: &El, depth: usize) -> Arg { + let mut out = Vec::new(); + if depth > MAX_DEPTH { + return out; + } + for k in e.elements() { + node(k, depth, &mut out); + } + out +} + +fn node(k: &El, depth: usize, out: &mut Arg) { + let d = depth + 1; + match k.name.as_str() { + "m:r" => { + if let Some(r) = run(k) { + out.push(MNode::Run(r)); + } + } + // Word puts ordinary runs in math zones for normal text in some files. + "w:r" => { + let text = run_text(k); + if !text.is_empty() { + let mut r = MRun { text, nor: true, sty: Some(MSty::Plain), ..Default::default() }; + wrpr(k.child("w:rPr"), &mut r); + out.push(MNode::Run(r)); + } + } + "m:f" => { + let pr = k.child("m:fPr"); + let kind = match val(pr, "m:type") { + Some("skw") => FracKind::Skewed, + Some("lin") => FracKind::Linear, + Some("noBar") => FracKind::NoBar, + _ => FracKind::Bar, + }; + out.push(MNode::Frac { kind, num: sub_arg(k, "m:num", d), den: sub_arg(k, "m:den", d) }); + } + "m:sSup" => out.push(MNode::Script { kind: ScriptKind::Sup, base: sub_arg(k, "m:e", d), sub: Vec::new(), sup: sub_arg(k, "m:sup", d) }), + "m:sSub" => out.push(MNode::Script { kind: ScriptKind::Sub, base: sub_arg(k, "m:e", d), sub: sub_arg(k, "m:sub", d), sup: Vec::new() }), + "m:sSubSup" => { + out.push(MNode::Script { kind: ScriptKind::SubSup, base: sub_arg(k, "m:e", d), sub: sub_arg(k, "m:sub", d), sup: sub_arg(k, "m:sup", d) }) + } + "m:sPre" => { + out.push(MNode::Script { kind: ScriptKind::Pre, base: sub_arg(k, "m:e", d), sub: sub_arg(k, "m:sub", d), sup: sub_arg(k, "m:sup", d) }) + } + "m:rad" => { + let pr = k.child("m:radPr"); + out.push(MNode::Rad { deg: sub_arg(k, "m:deg", d), deg_hide: prop(pr, "m:degHide", false), e: sub_arg(k, "m:e", d) }); + } + "m:nary" => { + let pr = k.child("m:naryPr"); + let chr = chr(pr, "m:chr").map(|c| c.unwrap_or('∫')).unwrap_or('∫'); + let lim_loc = match val(pr, "m:limLoc") { + Some("undOvr") => Some(LimLoc::UndOvr), + Some("subSup") => Some(LimLoc::SubSup), + _ => None, + }; + out.push(MNode::Nary { + chr, + lim_loc, + grow: prop(pr, "m:grow", false), + sub_hide: prop(pr, "m:subHide", false), + sup_hide: prop(pr, "m:supHide", false), + sub: sub_arg(k, "m:sub", d), + sup: sub_arg(k, "m:sup", d), + e: sub_arg(k, "m:e", d), + }); + } + "m:d" => { + let pr = k.child("m:dPr"); + let beg = chr(pr, "m:begChr").unwrap_or(Some('(')); + let end = chr(pr, "m:endChr").unwrap_or(Some(')')); + let sep = chr(pr, "m:sepChr").unwrap_or(Some('|')); + let elems: Vec = k.children("m:e").map(|e| arg(e, d)).collect(); + out.push(MNode::Delim { + beg, + end, + sep, + grow: prop(pr, "m:grow", true), + shp_match: val(pr, "m:shp") == Some("match"), + elems: if elems.is_empty() { vec![Vec::new()] } else { elems }, + }); + } + "m:func" => out.push(MNode::Func { name: sub_arg(k, "m:fName", d), e: sub_arg(k, "m:e", d) }), + "m:limLow" => out.push(MNode::Lim { upper: false, e: sub_arg(k, "m:e", d), lim: sub_arg(k, "m:lim", d) }), + "m:limUpp" => out.push(MNode::Lim { upper: true, e: sub_arg(k, "m:e", d), lim: sub_arg(k, "m:lim", d) }), + "m:acc" => { + let c = chr(k.child("m:accPr"), "m:chr").map(|c| c.unwrap_or('\u{302}')).unwrap_or('\u{302}'); + out.push(MNode::Acc { chr: c, e: sub_arg(k, "m:e", d) }); + } + "m:bar" => out.push(MNode::Bar { top: val(k.child("m:barPr"), "m:pos") == Some("top"), e: sub_arg(k, "m:e", d) }), + "m:borderBox" => { + let pr = k.child("m:borderBoxPr"); + out.push(MNode::BorderBox { + hide: [prop(pr, "m:hideTop", false), prop(pr, "m:hideBot", false), prop(pr, "m:hideLeft", false), prop(pr, "m:hideRight", false)], + strike: [ + prop(pr, "m:strikeH", false), + prop(pr, "m:strikeV", false), + prop(pr, "m:strikeBLTR", false), + prop(pr, "m:strikeTLBR", false), + ], + e: sub_arg(k, "m:e", d), + }); + } + "m:box" => out.push(MNode::Boxed { e: sub_arg(k, "m:e", d) }), + "m:groupChr" => { + let pr = k.child("m:groupChrPr"); + let c = chr(pr, "m:chr").map(|c| c.unwrap_or('\u{23DF}')).unwrap_or('\u{23DF}'); + out.push(MNode::GroupChr { chr: c, top: val(pr, "m:pos") == Some("top"), e: sub_arg(k, "m:e", d) }); + } + "m:eqArr" => out.push(MNode::EqArr { rows: k.children("m:e").map(|e| arg(e, d)).collect() }), + "m:m" => { + let mut col_jc = Vec::new(); + if let Some(mcs) = k.child("m:mPr").and_then(|p| p.child("m:mcs")) { + for mc in mcs.children("m:mc") { + let pr = mc.child("m:mcPr"); + let jc = match val(pr, "m:mcJc") { + Some("left") => ColJc::Left, + Some("right") => ColJc::Right, + _ => ColJc::Center, + }; + let count = val(pr, "m:count").and_then(|c| c.trim().parse::().ok()).unwrap_or(1).clamp(1, 64); + for _ in 0..count { + if col_jc.len() < 64 { + col_jc.push(jc); + } + } + } + } + let rows = k.children("m:mr").take(1000).map(|r| r.children("m:e").take(64).map(|e| arg(e, d)).collect()).collect(); + out.push(MNode::Matrix { rows, col_jc }); + } + "m:phant" => { + let pr = k.child("m:phantPr"); + out.push(MNode::Phant { + show: prop(pr, "m:show", true), + zero_wid: prop(pr, "m:zeroWid", false), + zero_asc: prop(pr, "m:zeroAsc", false), + zero_desc: prop(pr, "m:zeroDesc", false), + e: sub_arg(k, "m:e", d), + }); + } + // Tracked insertions show; deletions don't. Hyperlinks, simple fields and direction + // wrappers (EG_PContentMath, §22.1.2.77) keep their runs (#1273). + "w:ins" | "w:moveTo" | "w:smartTag" | "w:customXml" | "w:hyperlink" | "w:fldSimple" | "w:dir" | "w:bdo" | "m:oMath" if depth <= MAX_DEPTH => { + for c in k.elements() { + node(c, d, out); + } + } + // Markup compatibility: the math choice (we read math), else the fallback. + "mc:AlternateContent" if depth <= MAX_DEPTH => { + if let Some(c) = k.child("mc:Choice").or_else(|| k.child("mc:Fallback")) { + for c in c.elements() { + node(c, d, out); + } + } + } + "w:sdt" => { + if let Some(c) = k.child("w:sdtContent") { + for c in c.elements() { + node(c, d, out); + } + } + } + _ => {} + } +} + +/// `m:t` (and `w:t`) text of a run, with symbol characters (`w:sym`) and special hyphens. +/// Text in a symbol font (Symbol, Wingdings…) becomes its Unicode equivalent: the math font has +/// no glyphs at those private-use codes (#1273). +fn run_text(r: &El) -> String { + let font = r + .child("w:rPr") + .and_then(|p| p.child("w:rFonts")) + .and_then(|f| f.attr_or_plain("w:ascii").or_else(|| f.attr_or_plain("w:hAnsi"))) + .unwrap_or(""); + let mut s = String::new(); + for c in r.elements() { + match c.name.as_str() { + "m:t" | "w:t" => s.push_str(&symbol_fonts::map_text(font, &c.text())), + "w:tab" => s.push('\t'), + "w:noBreakHyphen" => s.push('\u{2011}'), + "w:sym" => { + let ch = c + .attr_or_plain("w:char") + .and_then(|h| u32::from_str_radix(h.trim(), 16).ok()) + .and_then(char::from_u32) + .filter(|c| *c as u32 >= 0x20); + if let Some(ch) = ch { + let f = c.attr_or_plain("w:font").unwrap_or(font); + s.push(symbol_fonts::symbol_char(f, ch).unwrap_or(ch)); + } + } + _ => {} + } + } + s +} + +fn run(r: &El) -> Option { + let text = run_text(r); + if text.is_empty() { + return None; + } + let mut out = MRun { text, ..Default::default() }; + if let Some(pr) = r.child("m:rPr") { + out.sty = match pr.child("m:sty").and_then(|s| s.attr_or_plain("m:val")) { + Some("p") => Some(MSty::Plain), + Some("b") => Some(MSty::Bold), + Some("i") => Some(MSty::Italic), + Some("bi") => Some(MSty::BoldItalic), + _ => None, + }; + out.scr = match pr.child("m:scr").and_then(|s| s.attr_or_plain("m:val")) { + Some("script") => MScr::Script, + Some("fraktur") => MScr::Fraktur, + Some("double-struck") => MScr::DoubleStruck, + Some("sans-serif") => MScr::SansSerif, + Some("monospace") => MScr::Monospace, + _ => MScr::Roman, + }; + out.nor = pr.child("m:nor").is_some_and(on); + out.lit = pr.child("m:lit").is_some_and(on); + if let Some(b) = pr.child("m:brk") { + let aln = b.attr_or_plain("m:alnAt").and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + out.brk = Some(aln.min(255) as u8); + } + } + wrpr(r.child("w:rPr"), &mut out); + Some(out) +} + +/// The run formatting a math run takes from `w:rPr`: size, colour, normal-text font and weight. +fn wrpr(pr: Option<&El>, out: &mut MRun) { + let Some(pr) = pr else { return }; + if let Some(sz) = pr.child("w:sz").and_then(|s| s.attr_or_plain("w:val")).and_then(|v| v.trim().parse::().ok()) { + let pt = sz / 2.0; + if pt.is_finite() && (1.0..=1638.0).contains(&pt) { + out.size = Some(pt); + } + } + if let Some(c) = pr.child("w:color").and_then(|c| c.attr_or_plain("w:val")).and_then(Rgb::parse) { + out.color = Some(c); + } + if out.nor { + // Symbol-font text was mapped to Unicode: it takes the text font. + if let Some(f) = pr + .child("w:rFonts") + .and_then(|f| f.attr_or_plain("w:ascii").or_else(|| f.attr_or_plain("w:hAnsi"))) + .filter(|f| !symbol_fonts::is_symbol_font(f)) + { + out.font = Some(f.to_string()); + } + let bold = pr.child("w:b").is_some_and(on_off); + let italic = pr.child("w:i").is_some_and(on_off); + if bold || italic { + out.sty = Some(match (bold, italic) { + (true, true) => MSty::BoldItalic, + (true, false) => MSty::Bold, + _ => MSty::Italic, + }); + } + } +} diff --git a/crates/math/src/omml/tests.rs b/crates/math/src/omml/tests.rs new file mode 100644 index 000000000..863bacf4f --- /dev/null +++ b/crates/math/src/omml/tests.rs @@ -0,0 +1,191 @@ +use super::*; +use crate::math::*; + +fn omath(inner: &str) -> El { + let x = format!( + r#"{inner}"# + ); + parse(&x).unwrap() +} + +#[test] +fn reads_fraction_radical_and_scripts() { + let e = omath( + r#"x=-b±b2-4ac2a"#, + ); + let m = read_omath(&e, MathJc::CenterGroup); + assert_eq!(m.nodes.len(), 2); + let MNode::Frac { num, den, kind } = &m.nodes[1] else { panic!("{:#?}", m.nodes) }; + assert_eq!(*kind, FracKind::Bar); + assert_eq!(den, &vec![MNode::Run(MRun::new("2a"))]); + let MNode::Rad { deg_hide, e, .. } = &num[1] else { panic!() }; + assert!(*deg_hide); + assert!(matches!(e[0], MNode::Script { kind: ScriptKind::Sup, .. })); + assert_eq!(crate::math::to_linear(&m.nodes), "x=(-b±√(b^2-4ac))/2a"); + assert!(m.omml.starts_with("")); +} + +#[test] +fn reads_nary_delims_matrix_and_defaults() { + let e = omath( + r#"iiab"#, + ); + let m = read_omath(&e, MathJc::CenterGroup); + let MNode::Nary { chr, lim_loc, .. } = &m.nodes[0] else { panic!() }; + assert_eq!((*chr, *lim_loc), ('∑', Some(LimLoc::UndOvr))); + let MNode::Delim { beg, end, sep, elems, .. } = &m.nodes[1] else { panic!() }; + assert_eq!((*beg, *end, *sep, elems.len()), (Some('['), None, Some('|'), 2)); + assert!(matches!(m.nodes[2], MNode::Nary { chr: '∫', .. })); + assert!(matches!(&m.nodes[3], MNode::Matrix { rows, .. } if rows.len() == 1 && rows[0].len() == 2)); +} + +/// Every run's text in the tree, in reading order. +fn texts(m: &mut Math) -> Vec { + let mut out = Vec::new(); + crate::math_tree::each_run_mut(&mut m.nodes, &mut |r| out.push(r.text.clone())); + out +} + +fn t(s: &str) -> String { + format!("{s}") +} + +/// #1273: one equation using every Office Math element of ECMA-376 §22.1 (each argument +/// holding a distinct marker) keeps every argument's text: nothing is silently dropped. +#[test] +fn every_omml_element_keeps_its_content() { + let parts = [ + format!("{}", t("A1")), + format!("{}", t("B1")), + format!("{}", t("C1")), + format!("{}", t("D1")), + format!("{}{}", t("E1"), t("E2")), + format!("{}{}", t("F1"), t("F2")), + format!("{}{}", t("G1"), t("G2")), + format!("{}{}", t("H1"), t("H2")), + format!("{}", t("I1")), + format!("{}{}", t("J1"), t("J2")), + format!("{}{}", t("K1"), t("K2")), + format!("{}{}{}", t("L1"), t("L2"), t("L3")), + format!( + "{}{}{}", + t("M1"), + t("M2"), + t("M3") + ), + format!("{}", t("N1")), + format!("{}{}", t("O1"), t("O2")), + format!("{}{}{}", t("P1"), t("P2"), t("P3")), + format!("{}{}", t("Q1"), t("Q2")), + format!("{}{}{}", t("R1"), t("R2"), t("R3")), + format!("{}{}", t("S1"), t("S2")), + // Run-level wrappers allowed in math (EG_PContentMath): hyperlinks, simple fields, + // tracked insertions, content controls, markup compatibility. + format!("{}", t("T1")), + format!("{}", t("T2")), + format!("{}", t("T3")), + format!("{}", t("T4")), + format!( + "{}picture", + t("T5") + ), + "T6".to_string(), + ]; + let x = format!( + r#"{}"#, + parts.concat() + ); + let e = parse(&x).unwrap(); + let mut m = read_omath(&e, MathJc::CenterGroup); + let got = texts(&mut m).concat(); + let markers = [ + "A1", "B1", "C1", "D1", "E1", "E2", "F1", "F2", "G1", "G2", "H1", "H2", "I1", "J1", "J2", "K1", "K2", "L1", "L2", "L3", "M1", "M2", "M3", + "N1", "O1", "O2", "P1", "P2", "P3", "Q1", "Q2", "R1", "R2", "R3", "S1", "S2", "T1", "T2", "T3", "T4", "T5", "T6", + ]; + for k in markers { + assert!(got.contains(k), "{k} dropped from {got}"); + } + assert!(!got.contains("picture"), "the math choice wins over the fallback: {got}"); +} + +/// #1273: deleted text stays out; symbol characters and symbol-font text become Unicode. +#[test] +fn symbols_and_deletions_in_math() { + let e = omath( + r#"xgone"#, + ); + let mut m = read_omath(&e, MathJc::CenterGroup); + let got = texts(&mut m).concat(); + assert_eq!(got, "xαβ\u{2011}γ"); + let mut font = None; + crate::math_tree::each_run_mut(&mut m.nodes, &mut |r| { + if r.nor { + font = Some(r.font.clone()); + } + }); + assert_eq!(font, Some(None), "mapped symbol text takes the text font"); +} + +/// Hostile nesting through the wrappers is bounded (no stack overflow, no panic). +#[test] +fn deeply_nested_wrappers_are_bounded() { + // Deeper than the math limit, within the XML parser's own depth limit. + let n = 120; + let inner = format!("{}{}{}", "".repeat(n), t("deep"), "".repeat(n)); + let e = omath(&inner); + let _ = read_omath(&e, MathJc::CenterGroup); + let inner = format!( + "{}{}{}", + "".repeat(n), + t("deep"), + "".repeat(n) + ); + let e = omath(&inner); + let _ = read_omath(&e, MathJc::CenterGroup); +} + +#[test] +fn text_entry_points_find_the_equation_and_refuse_junk() { + let ns = r#"xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math""#; + // Any prefix, inside other markup, as a display paragraph with its justification. + let x = r#"

x

"#; + let m = read_str(x).unwrap(); + assert_eq!((crate::math::to_linear(&m.nodes).as_str(), m.jc), ("x", MathJc::Left)); + // The strict OOXML namespace. + let strict = r#"y"#; + assert_eq!(read_str(strict).map(|m| crate::math::to_linear(&m.nodes)).as_deref(), Some("y")); + // Kept OMML, prefixes without declarations. + assert_eq!(read_str("z").map(|m| crate::math::to_linear(&m.nodes)).as_deref(), Some("z")); + for junk in ["", "

", "not xml", "").is_none() && read_str("").is_none()); + // More elements than the reader keeps: refused, not read in part. + let wide = format!("{}", "".repeat(MAX_ELEMENTS * 2 + 1)); + assert!(parse(&wide).is_none()); + let fits = format!("{}", "a".repeat(1000)); + assert!(parse(&fits).is_some()); + // Deep nesting is bounded. + let deep = format!("{}x{}", "".repeat(5000), "".repeat(5000)); + let _ = read_str(&deep); +} + +#[test] +fn kept_omml_is_written_back_only_when_well_formed() { + let m = read_str(r#"x"#).unwrap(); + assert_eq!(write_str("", false, &m, None), m.omml); + let broken = Math { omml: "".into(), ..m.clone() }; + let out = write_str("", false, &broken, None); + assert!(out.starts_with("") && out.ends_with("") && out.contains(">x"), "{out}"); + // A colour that differs from the kept one rewrites the equation from the tree, with the colour. + let red = write_str("", false, &m, Some(Rgb(255, 0, 0))); + assert!(red.contains(r#""#), "{red}"); +} + +proptest::proptest! { + #[test] + fn any_text_reads_without_panicking(s in "[<>/=\"a-z:m ]{0,120}") { + let _ = read_str(&s); + let _ = crate::mathml::parse(&s).map(|e| crate::mathml::to_tree(&e)); + } +} diff --git a/crates/math/src/omml/write.rs b/crates/math/src/omml/write.rs new file mode 100644 index 000000000..9f09aab67 --- /dev/null +++ b/crates/math/src/omml/write.rs @@ -0,0 +1,480 @@ +//! The tree as OMML. + +use super::read::{lift_color, read_omath}; +use super::{W, is_well_formed, parse_kept, twips}; +use crate::math::{ + Arg, BrkBin, BrkBinSub, ColJc, FracKind, LimLoc, MAX_DEPTH, MAX_MATRIX_COLS, MAX_MATRIX_ROWS, MNode, MRun, MScr, MSty, Math, MathJc, MathProps, + ScriptKind, parse_linear, +}; +use crate::rgb::Rgb; + +/// Write an equation: `m:oMath`, inside `m:oMathPara` for a display equation. The source OMML +/// is written back unchanged when the equation came from a file. `color` (the equation's run +/// colour) goes on every math run without its own: OMML has no equation-level colour (#1467). +pub fn write_equation(w: &mut W, linear: &str, display: bool, math: &Math, color: Option) { + let tinted; + let math = if color == omml_color(&math.omml) { + math + } else { + // The kept source XML has the old colour baked in: write from the nodes instead. + let mut m = math.clone(); + if m.nodes.is_empty() { + m.nodes = parse_linear(linear); + } + if let Some(c) = color { + crate::math_tree::each_run_mut(&mut m.nodes, &mut |r| { + r.color.get_or_insert(c); + }); + } + m.omml.clear(); + tinted = m; + &tinted + }; + if display { + w.open("m:oMathPara", &[]); + let jc = match math.jc { + MathJc::CenterGroup => None, + MathJc::Center => Some("center"), + MathJc::Left => Some("left"), + MathJc::Right => Some("right"), + }; + if let Some(jc) = jc { + w.open("m:oMathParaPr", &[]); + w.empty("m:jc", &[("m:val", jc)]); + w.close("m:oMathParaPr"); + } + } + if !math.omml.is_empty() && math.omml.starts_with(" Option { + if !display { + return None; + } + let [MNode::EqArr { rows }] = math.nodes.as_slice() else { return None }; + let mut out = rows.clone(); + let mut changed = false; + for row in out.iter_mut() { + if !crate::math::has_number_mark(row) { + continue; + } + *counter = counter.saturating_add(1); + // Nothing after the `#`: an automatic number. + let mut after = false; + let mut empty = true; + for n in row.iter() { + match n { + MNode::Run(r) if !after => { + if let Some(k) = r.text.find('#') { + after = true; + if !r.text.get(k + 1..).unwrap_or("").is_empty() { + empty = false; + } + } + } + _ if after => empty = false, + _ => {} + } + } + if empty { + let n = vec![MNode::Run(MRun::new(counter.to_string()))]; + row.push(MNode::Delim { beg: Some('('), end: Some(')'), sep: None, grow: true, shp_match: false, elems: vec![n] }); + changed = true; + } + } + changed.then(|| Math { nodes: vec![MNode::EqArr { rows: out }], omml: String::new(), ..math.clone() }) +} + +/// The equation colour the kept source OMML carries, as the reader lifts it. +fn omml_color(omml: &str) -> Option { + if omml.is_empty() { + return None; + } + let root = parse_kept(omml)?; + let e = if root.name == "m:oMath" { &root } else { root.find("m:oMath")? }; + lift_color(&mut read_omath(e, MathJc::default())) +} + +/// The settings part's `m:mathPr` (CT_MathPr order; `m:wrapIndent` and `m:wrapRight` are a choice). +pub fn math_pr(w: &mut W, m: &MathProps) { + w.open("m:mathPr", &[]); + let bin = match m.brk_bin { + BrkBin::Before => "before", + BrkBin::After => "after", + BrkBin::Repeat => "repeat", + }; + val(w, "m:brkBin", bin); + let sub = match m.brk_bin_sub { + BrkBinSub::MinusMinus => "--", + BrkBinSub::MinusPlus => "-+", + BrkBinSub::PlusMinus => "+-", + }; + val(w, "m:brkBinSub", sub); + if m.wrap_right { + w.empty("m:wrapRight", &[]); + } else { + let indent = if m.wrap_indent.is_finite() { m.wrap_indent.clamp(0.0, 1584.0) } else { crate::math::DEFAULT_WRAP_INDENT }; + val(w, "m:wrapIndent", &twips(indent)); + } + w.close("m:mathPr"); +} + +fn val(w: &mut W, name: &str, v: &str) { + w.empty(name, &[("m:val", v)]); +} + +fn arg(w: &mut W, name: &str, a: &[MNode], depth: usize) { + if a.is_empty() { + w.empty(name, &[]); + return; + } + w.open(name, &[]); + arg_inner(w, a, depth + 1); + w.close(name); +} + +fn arg_inner(w: &mut W, a: &[MNode], depth: usize) { + if depth > MAX_DEPTH { + return; + } + for n in a { + node(w, n, depth); + } +} + +fn ctrl(w: &mut W) { + w.open("m:ctrlPr", &[]); + w.open("w:rPr", &[]); + w.empty("w:rFonts", &[("w:ascii", "Cambria Math"), ("w:hAnsi", "Cambria Math")]); + w.empty("w:i", &[]); + w.close("w:rPr"); + w.close("m:ctrlPr"); +} + +fn char_prop(w: &mut W, name: &str, c: Option) { + let s = c.map(|c| c.to_string()).unwrap_or_default(); + val(w, name, &s); +} + +fn write_matrix(w: &mut W, n: &MNode, depth: usize) { + let MNode::Matrix { rows, col_jc } = n else { return }; + // Every row is padded to the widest one, so a ragged matrix is clamped to the reader's + // caps rather than written as rows × widest cells (#3643). + let rows = rows.get(..rows.len().min(MAX_MATRIX_ROWS)).unwrap_or_default(); + let cols = rows.iter().map(|r| r.len()).max().unwrap_or(0).clamp(1, MAX_MATRIX_COLS); + w.open("m:m", &[]); + w.open("m:mPr", &[]); + w.open("m:mcs", &[]); + for c in 0..cols { + let jc = match col_jc.get(c).copied().unwrap_or_default() { + ColJc::Center => "center", + ColJc::Left => "left", + ColJc::Right => "right", + }; + w.open("m:mc", &[]); + w.open("m:mcPr", &[]); + val(w, "m:count", "1"); + val(w, "m:mcJc", jc); + w.close("m:mcPr"); + w.close("m:mc"); + } + w.close("m:mcs"); + ctrl(w); + w.close("m:mPr"); + for row in rows { + w.open("m:mr", &[]); + for c in 0..cols { + arg(w, "m:e", row.get(c).map(|v| v.as_slice()).unwrap_or(&[]), depth); + } + w.close("m:mr"); + } + w.close("m:m"); +} + +fn write_nary(w: &mut W, n: &MNode, depth: usize) { + let MNode::Nary { chr, lim_loc, grow, sub_hide, sup_hide, sub, sup, e } = n else { return }; + w.open("m:nary", &[]); + w.open("m:naryPr", &[]); + if *chr != '∫' { + char_prop(w, "m:chr", Some(*chr)); + } + match lim_loc { + Some(LimLoc::UndOvr) => val(w, "m:limLoc", "undOvr"), + Some(LimLoc::SubSup) => val(w, "m:limLoc", "subSup"), + None => {} + } + if *grow { + val(w, "m:grow", "1"); + } + if *sub_hide { + val(w, "m:subHide", "1"); + } + if *sup_hide { + val(w, "m:supHide", "1"); + } + ctrl(w); + w.close("m:naryPr"); + arg(w, "m:sub", sub, depth); + arg(w, "m:sup", sup, depth); + arg(w, "m:e", e, depth); + w.close("m:nary"); +} + +fn node(w: &mut W, n: &MNode, depth: usize) { + match n { + MNode::Run(r) => run(w, r), + MNode::Frac { kind, num, den } => { + w.open("m:f", &[]); + w.open("m:fPr", &[]); + match kind { + FracKind::Bar => {} + FracKind::Skewed => val(w, "m:type", "skw"), + FracKind::Linear => val(w, "m:type", "lin"), + FracKind::NoBar => val(w, "m:type", "noBar"), + } + ctrl(w); + w.close("m:fPr"); + arg(w, "m:num", num, depth); + arg(w, "m:den", den, depth); + w.close("m:f"); + } + MNode::Script { kind, base, sub, sup } => { + let (el, pr) = match kind { + ScriptKind::Sup => ("m:sSup", "m:sSupPr"), + ScriptKind::Sub => ("m:sSub", "m:sSubPr"), + ScriptKind::SubSup => ("m:sSubSup", "m:sSubSupPr"), + ScriptKind::Pre => ("m:sPre", "m:sPrePr"), + }; + w.open(el, &[]); + w.open(pr, &[]); + ctrl(w); + w.close(pr); + if *kind == ScriptKind::Pre { + arg(w, "m:sub", sub, depth); + arg(w, "m:sup", sup, depth); + arg(w, "m:e", base, depth); + } else { + arg(w, "m:e", base, depth); + if matches!(kind, ScriptKind::Sub | ScriptKind::SubSup) { + arg(w, "m:sub", sub, depth); + } + if matches!(kind, ScriptKind::Sup | ScriptKind::SubSup) { + arg(w, "m:sup", sup, depth); + } + } + w.close(el); + } + MNode::Rad { deg, deg_hide, e } => { + w.open("m:rad", &[]); + w.open("m:radPr", &[]); + if *deg_hide { + val(w, "m:degHide", "1"); + } + ctrl(w); + w.close("m:radPr"); + arg(w, "m:deg", deg, depth); + arg(w, "m:e", e, depth); + w.close("m:rad"); + } + MNode::Nary { .. } => write_nary(w, n, depth), + MNode::Delim { beg, end, sep, grow, shp_match, elems } => { + w.open("m:d", &[]); + w.open("m:dPr", &[]); + if *beg != Some('(') { + char_prop(w, "m:begChr", *beg); + } + if *sep != Some('|') { + char_prop(w, "m:sepChr", *sep); + } + if *end != Some(')') { + char_prop(w, "m:endChr", *end); + } + if !grow { + val(w, "m:grow", "0"); + } + if *shp_match { + val(w, "m:shp", "match"); + } + ctrl(w); + w.close("m:dPr"); + for e in elems { + arg(w, "m:e", e, depth); + } + w.close("m:d"); + } + MNode::Func { name, e } => { + w.open("m:func", &[]); + w.open("m:funcPr", &[]); + ctrl(w); + w.close("m:funcPr"); + arg(w, "m:fName", name, depth); + arg(w, "m:e", e, depth); + w.close("m:func"); + } + MNode::Lim { upper, e, lim } => { + let (el, pr) = if *upper { ("m:limUpp", "m:limUppPr") } else { ("m:limLow", "m:limLowPr") }; + w.open(el, &[]); + w.open(pr, &[]); + ctrl(w); + w.close(pr); + arg(w, "m:e", e, depth); + arg(w, "m:lim", lim, depth); + w.close(el); + } + MNode::Acc { chr, e } => { + w.open("m:acc", &[]); + w.open("m:accPr", &[]); + char_prop(w, "m:chr", Some(*chr)); + ctrl(w); + w.close("m:accPr"); + arg(w, "m:e", e, depth); + w.close("m:acc"); + } + MNode::Bar { top, e } => { + w.open("m:bar", &[]); + w.open("m:barPr", &[]); + val(w, "m:pos", if *top { "top" } else { "bot" }); + ctrl(w); + w.close("m:barPr"); + arg(w, "m:e", e, depth); + w.close("m:bar"); + } + MNode::BorderBox { hide, strike, e } => { + w.open("m:borderBox", &[]); + w.open("m:borderBoxPr", &[]); + for (on, name) in hide.iter().zip(["m:hideTop", "m:hideBot", "m:hideLeft", "m:hideRight"]) { + if *on { + val(w, name, "1"); + } + } + for (on, name) in strike.iter().zip(["m:strikeH", "m:strikeV", "m:strikeBLTR", "m:strikeTLBR"]) { + if *on { + val(w, name, "1"); + } + } + ctrl(w); + w.close("m:borderBoxPr"); + arg(w, "m:e", e, depth); + w.close("m:borderBox"); + } + MNode::Boxed { e } => { + w.open("m:box", &[]); + w.open("m:boxPr", &[]); + ctrl(w); + w.close("m:boxPr"); + arg(w, "m:e", e, depth); + w.close("m:box"); + } + MNode::GroupChr { chr, top, e } => { + w.open("m:groupChr", &[]); + w.open("m:groupChrPr", &[]); + char_prop(w, "m:chr", Some(*chr)); + val(w, "m:pos", if *top { "top" } else { "bot" }); + val(w, "m:vertJc", if *top { "bot" } else { "top" }); + ctrl(w); + w.close("m:groupChrPr"); + arg(w, "m:e", e, depth); + w.close("m:groupChr"); + } + MNode::EqArr { rows } => { + w.open("m:eqArr", &[]); + w.open("m:eqArrPr", &[]); + // Numbered rows (`#`) stretch across the line so the number reaches the margin. + if rows.iter().any(|r| crate::math::has_number_mark(r)) { + val(w, "m:maxDist", "1"); + } + ctrl(w); + w.close("m:eqArrPr"); + for r in rows { + arg(w, "m:e", r, depth); + } + w.close("m:eqArr"); + } + MNode::Matrix { .. } => write_matrix(w, n, depth), + MNode::Phant { show, zero_wid, zero_asc, zero_desc, e } => { + w.open("m:phant", &[]); + w.open("m:phantPr", &[]); + val(w, "m:show", if *show { "1" } else { "0" }); + for (on, name) in [(*zero_wid, "m:zeroWid"), (*zero_asc, "m:zeroAsc"), (*zero_desc, "m:zeroDesc")] { + if on { + val(w, name, "1"); + } + } + ctrl(w); + w.close("m:phantPr"); + arg(w, "m:e", e, depth); + w.close("m:phant"); + } + } +} + +fn run(w: &mut W, r: &MRun) { + w.open("m:r", &[]); + let sty = r.sty.map(|s| match s { + MSty::Plain => "p", + MSty::Bold => "b", + MSty::Italic => "i", + MSty::BoldItalic => "bi", + }); + let scr = match r.scr { + MScr::Roman => None, + MScr::Script => Some("script"), + MScr::Fraktur => Some("fraktur"), + MScr::DoubleStruck => Some("double-struck"), + MScr::SansSerif => Some("sans-serif"), + MScr::Monospace => Some("monospace"), + }; + if sty.is_some() || scr.is_some() || r.nor || r.lit || r.brk.is_some() { + w.open("m:rPr", &[]); + if r.lit { + w.empty("m:lit", &[]); + } + if r.nor { + w.empty("m:nor", &[]); + } + if let Some(s) = scr { + val(w, "m:scr", s); + } + if let Some(s) = sty { + val(w, "m:sty", s); + } + match r.brk { + Some(0) => w.empty("m:brk", &[]), + Some(n) => w.empty("m:brk", &[("m:alnAt", &n.to_string())]), + None => {} + } + w.close("m:rPr"); + } + w.open("w:rPr", &[]); + let font = r.font.as_deref().filter(|_| r.nor).unwrap_or("Cambria Math"); + w.empty("w:rFonts", &[("w:ascii", font), ("w:hAnsi", font)]); + if let Some(c) = r.color { + w.val("w:color", &c.hex()); + } + if let Some(sz) = r.size { + let hp = (sz * 2.0).round().clamp(2.0, 3276.0) as i64; + w.val("w:sz", &hp.to_string()); + w.val("w:szCs", &hp.to_string()); + } + w.close("w:rPr"); + w.leaf("m:t", &[("xml:space", "preserve")], &r.text); + w.close("m:r"); +} diff --git a/crates/math/src/rgb.rs b/crates/math/src/rgb.rs new file mode 100644 index 000000000..f624cda15 --- /dev/null +++ b/crates/math/src/rgb.rs @@ -0,0 +1,173 @@ +//! An sRGB colour, the one type of colour every Craft document model and this crate share. + +use serde::{Deserialize, Serialize}; + +/// An sRGB colour. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Default)] +pub struct Rgb(pub u8, pub u8, pub u8); + +impl<'de> Deserialize<'de> for Rgb { + /// Reads what it writes (`[r, g, b]`) and also a string [`Rgb::parse`] reads, so the colours in + /// `CharProps` / `ParaProps` take the `RRGGBB` that `para.borders` and `table.shading` take (#865). + fn deserialize>(d: D) -> Result { + use serde::de::{Error, SeqAccess, Unexpected, Visitor}; + struct V; + impl<'de> Visitor<'de> for V { + type Value = Rgb; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("`[r, g, b]`, `RRGGBB` or `#RRGGBB`") + } + fn visit_str(self, s: &str) -> Result { + Rgb::parse(s).ok_or_else(|| E::invalid_value(Unexpected::Str(s), &self)) + } + fn visit_seq>(self, mut a: A) -> Result { + let mut c = [0u8; 3]; + for (i, x) in c.iter_mut().enumerate() { + *x = a.next_element()?.ok_or_else(|| A::Error::invalid_length(i, &self))?; + } + if a.next_element::()?.is_some() { + return Err(A::Error::invalid_length(4, &self)); + } + Ok(Rgb(c[0], c[1], c[2])) + } + } + d.deserialize_any(V) + } +} + +impl Rgb { + pub const BLACK: Rgb = Rgb(0, 0, 0); + pub const WHITE: Rgb = Rgb(255, 255, 255); + /// `RRGGBB` (no `#`). + pub fn hex(self) -> String { + format!("{:02X}{:02X}{:02X}", self.0, self.1, self.2) + } + /// Parse `RRGGBB` or `#RRGGBB`. + pub fn parse(s: &str) -> Option { + let s = s.trim(); + let s = s.strip_prefix('#').unwrap_or(s); + if s.len() != 6 || !s.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let p = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); + Some(Rgb(p(0)?, p(2)?, p(4)?)) + } + /// This colour with the DrawingML colour modifier `name` (`lumMod`, `lumOff`, `tint`, + /// `shade`, `satMod`, ECMA-376 §20.1.2.3) at `v` (1.0 = 100%); other names leave it + /// unchanged. + pub fn modified(self, name: &str, v: f64) -> Rgb { + match name { + "lumMod" => adjust_lum(self, |l| l * v), + "lumOff" => adjust_lum(self, |l| l + v), + "tint" => mix(self, 255.0, v), + "shade" => mix(self, 0.0, v), + "satMod" => { + let (h, sat, l) = to_hsl(self); + from_hsl(h, (sat * v).clamp(0.0, 1.0), l) + } + _ => self, + } + } + /// The colour with hue `h` (0..1 of a turn), saturation `s` and lightness `l` (0..1). + pub fn from_hsl(h: f64, s: f64, l: f64) -> Rgb { + from_hsl(h, s, l) + } + /// This colour with its HSL luminance changed by `f`. + pub fn with_lum(self, f: impl Fn(f64) -> f64) -> Rgb { + adjust_lum(self, f) + } + pub fn luma(self) -> f32 { + 0.299 * self.0 as f32 + 0.587 * self.1 as f32 + 0.114 * self.2 as f32 + } +} + +/// `tint` (towards `to` = 255) and `shade` (towards 0): `v` is the share of the original colour kept. +fn mix(c: Rgb, to: f64, v: f64) -> Rgb { + let f = |x: u8| (x as f64 * v + to * (1.0 - v)).round().clamp(0.0, 255.0) as u8; + Rgb(f(c.0), f(c.1), f(c.2)) +} + +/// `c` with its HSL luminance changed by `f`. +fn adjust_lum(c: Rgb, f: impl Fn(f64) -> f64) -> Rgb { + let (h, s, l) = to_hsl(c); + from_hsl(h, s, f(l).clamp(0.0, 1.0)) +} + +fn to_hsl(c: Rgb) -> (f64, f64, f64) { + let (r, g, b) = (c.0 as f64 / 255.0, c.1 as f64 / 255.0, c.2 as f64 / 255.0); + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let l = (max + min) / 2.0; + if max == min { + return (0.0, 0.0, l); + } + let d = max - min; + let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; + let h = if max == r { + (g - b) / d + if g < b { 6.0 } else { 0.0 } + } else if max == g { + (b - r) / d + 2.0 + } else { + (r - g) / d + 4.0 + }; + (h / 6.0, s, l) +} + +fn from_hsl(h: f64, s: f64, l: f64) -> Rgb { + let byte = |v: f64| (v * 255.0).round().clamp(0.0, 255.0) as u8; + if s == 0.0 { + return Rgb(byte(l), byte(l), byte(l)); + } + let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; + let p = 2.0 * l - q; + let channel = |t: f64| { + let t = t.rem_euclid(1.0); + let v = if t < 1.0 / 6.0 { + p + (q - p) * 6.0 * t + } else if t < 0.5 { + q + } else if t < 2.0 / 3.0 { + p + (q - p) * (2.0 / 3.0 - t) * 6.0 + } else { + p + }; + byte(v) + }; + Rgb(channel(h + 1.0 / 3.0), channel(h), channel(h - 1.0 / 3.0)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rgb_hex() { + assert_eq!(Rgb(255, 0, 16).hex(), "FF0010"); + assert_eq!(Rgb::parse("#FF0010"), Some(Rgb(255, 0, 16))); + assert_eq!(Rgb::parse("zzzzzz"), None); + assert_eq!(Rgb::parse("é1234"), None); + } + + #[test] + fn rgb_parse_rejects_non_hex() { + assert_eq!(Rgb::parse("+1+2+3"), None); + assert_eq!(Rgb::parse("-1-2-3"), None); + assert_eq!(Rgb::parse("##ff0000"), None); + assert_eq!(Rgb::parse("ff00 0"), None); + assert_eq!(Rgb::parse("#ff0000"), Some(Rgb(255, 0, 0))); + assert_eq!(Rgb::parse("ff0000"), Some(Rgb(255, 0, 0))); + } + + /// #865: an [`Rgb`] reads `RRGGBB` / `#RRGGBB` as well as the `[r, g, b]` it still writes. + #[test] + fn rgb_reads_hex_and_keeps_its_serialized_form() { + let read = |j: &str| serde_json::from_str::(j); + let ink = Rgb(0x1B, 0x16, 0x11); + assert_eq!(serde_json::to_string(&ink).unwrap(), "[27,22,17]", "written as before"); + for j in ["[27,22,17]", r#""1B1611""#, r##""#1b1611""##] { + assert_eq!(read(j).unwrap(), ink, "{j}"); + } + for bad in ["[27,22]", "[27,22,17,0]", "[27,22,300]", "[-1,0,0]", r#""auto""#, r#""1B161""#, r#""""#, "7", "null", r#"{"r":1}"#] { + assert!(read(bad).is_err(), "{bad}"); + } + } +} diff --git a/crates/math/src/symbol_fonts.rs b/crates/math/src/symbol_fonts.rs new file mode 100644 index 000000000..1d5175540 --- /dev/null +++ b/crates/math/src/symbol_fonts.rs @@ -0,0 +1,316 @@ +//! Word's symbol fonts — Symbol, Wingdings, Wingdings 2, Wingdings 3 and Webdings — mapped to +//! standard Unicode characters, so text set in them shows the intended symbols when the font +//! isn't installed (they are proprietary and never bundled) and exports as real characters. +//! +//! Word stores a symbol-font character either as the private-use code U+F000 + the font's own +//! 8-bit code (U+F020–U+F0FF, what Insert › Symbol and `w:sym` write) or as the plain 8-bit code +//! (U+0020–U+00FF) in a run whose font is the symbol font. Both map the same way. The stored text +//! never changes: the mapping is for display, layout and plain-text output only. +//! +//! Sources (Unicode's own published data; no font file was read): +//! - Symbol: the Adobe Symbol encoding table published by Unicode, +//! (codes it maps to the +//! private use area are left out; 0x6D maps to GREEK SMALL LETTER MU). +//! - Wingdings, Wingdings 2, Wingdings 3, Webdings: the correspondence tables in "Status of +//! encoding of Wingdings and Webdings Symbols", Unicode L2/12-368 (WG2 N4384, M. Suignard, +//! 2012), the frozen repertoire of the Unicode 7.0 encoding (earlier drafts L2/11-052, +//! L2/11-344), checked against the Unicode Character Database names. The one character not +//! encoded (Wingdings 0xFF) has no entry. +//! +//! Tables are indexed by code − 0x20; 0 = no Unicode equivalent. + +/// The symbol table for a single family name, by lowercase family name. +fn single_table(family: &str) -> Option<&'static [u32; 224]> { + let f = family.trim(); + if f.eq_ignore_ascii_case("symbol") || f.eq_ignore_ascii_case("symbol (pcl6)") { + Some(&SYMBOL) + } else if f.eq_ignore_ascii_case("wingdings") { + Some(&WINGDINGS) + } else if f.eq_ignore_ascii_case("wingdings 2") { + Some(&WINGDINGS_2) + } else if f.eq_ignore_ascii_case("wingdings 3") { + Some(&WINGDINGS_3) + } else if f.eq_ignore_ascii_case("webdings") { + Some(&WEBDINGS) + } else { + None + } +} + +/// The symbol fonts this module knows, by lowercase family name. +fn table(family: &str) -> Option<&'static [u32; 224]> { + if family.contains(';') { family.split(';').map(str::trim).filter(|s| !s.is_empty()).find_map(single_table) } else { single_table(family) } +} + +/// Whether `family` is one of Word's symbol fonts (Symbol, Wingdings, Wingdings 2, Wingdings 3, +/// Webdings), whose characters [`symbol_char`] maps. +pub fn is_symbol_font(family: &str) -> bool { + table(family).is_some() +} + +/// The standard Unicode character for `c` in a run set in the symbol font `family`: `c` is the +/// font's code stored as U+F020–U+F0FF or as U+0020–U+00FF (except the soft hyphen U+00AD). +/// `None` for other fonts, other characters and codes with no Unicode equivalent. +pub fn symbol_char(family: &str, c: char) -> Option { + let t = table(family)?; + let u = u32::from(c); + let code = match u { + 0xF020..=0xF0FF => u - 0xF000, + // A soft hyphen stays a soft hyphen (Word stores `w:softHyphen` as U+00AD). + 0xAD => return None, + 0x20..=0xFF => u, + _ => return None, + }; + let i = usize::try_from(code.checked_sub(0x20)?).ok()?; + t.get(i).copied().filter(|v| *v != 0).and_then(char::from_u32) +} + +/// `text` (in a run set in `family`) with every symbol-font character replaced by its Unicode +/// equivalent; unchanged for other fonts. +pub fn map_text(family: &str, text: &str) -> String { + if !is_symbol_font(family) { + return text.to_string(); + } + text.chars().map(|c| symbol_char(family, c).unwrap_or(c)).collect() +} + +const SYMBOL: [u32; 224] = [ + 0x0020, 0x0021, 0x2200, 0x0023, 0x2203, 0x0025, 0x0026, 0x220B, // 0x20 + 0x0028, 0x0029, 0x2217, 0x002B, 0x002C, 0x2212, 0x002E, 0x002F, // 0x28 + 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, // 0x30 + 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, // 0x38 + 0x2245, 0x0391, 0x0392, 0x03A7, 0x0394, 0x0395, 0x03A6, 0x0393, // 0x40 + 0x0397, 0x0399, 0x03D1, 0x039A, 0x039B, 0x039C, 0x039D, 0x039F, // 0x48 + 0x03A0, 0x0398, 0x03A1, 0x03A3, 0x03A4, 0x03A5, 0x03C2, 0x03A9, // 0x50 + 0x039E, 0x03A8, 0x0396, 0x005B, 0x2234, 0x005D, 0x22A5, 0x005F, // 0x58 + 0x0000, 0x03B1, 0x03B2, 0x03C7, 0x03B4, 0x03B5, 0x03C6, 0x03B3, // 0x60 + 0x03B7, 0x03B9, 0x03D5, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BF, // 0x68 + 0x03C0, 0x03B8, 0x03C1, 0x03C3, 0x03C4, 0x03C5, 0x03D6, 0x03C9, // 0x70 + 0x03BE, 0x03C8, 0x03B6, 0x007B, 0x007C, 0x007D, 0x223C, 0x0000, // 0x78 + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0x80 + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0x88 + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0x90 + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0x98 + 0x20AC, 0x03D2, 0x2032, 0x2264, 0x2044, 0x221E, 0x0192, 0x2663, // 0xA0 + 0x2666, 0x2665, 0x2660, 0x2194, 0x2190, 0x2191, 0x2192, 0x2193, // 0xA8 + 0x00B0, 0x00B1, 0x2033, 0x2265, 0x00D7, 0x221D, 0x2202, 0x2022, // 0xB0 + 0x00F7, 0x2260, 0x2261, 0x2248, 0x2026, 0x0000, 0x0000, 0x21B5, // 0xB8 + 0x2135, 0x2111, 0x211C, 0x2118, 0x2297, 0x2295, 0x2205, 0x2229, // 0xC0 + 0x222A, 0x2283, 0x2287, 0x2284, 0x2282, 0x2286, 0x2208, 0x2209, // 0xC8 + 0x2220, 0x2207, 0x0000, 0x0000, 0x0000, 0x220F, 0x221A, 0x22C5, // 0xD0 + 0x00AC, 0x2227, 0x2228, 0x21D4, 0x21D0, 0x21D1, 0x21D2, 0x21D3, // 0xD8 + 0x25CA, 0x2329, 0x0000, 0x0000, 0x0000, 0x2211, 0x0000, 0x0000, // 0xE0 + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0xE8 + 0x0000, 0x232A, 0x222B, 0x2320, 0x0000, 0x2321, 0x0000, 0x0000, // 0xF0 + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0xF8 +]; + +const WEBDINGS: [u32; 224] = [ + 0x0020, 0x1F577, 0x1F578, 0x1F572, 0x1F576, 0x1F3C6, 0x1F396, 0x1F587, // 0x20 + 0x1F5E8, 0x1F5E9, 0x1F5F0, 0x1F5F1, 0x1F336, 0x1F397, 0x1F67E, 0x1F67C, // 0x28 + 0x1F5D5, 0x1F5D6, 0x1F5D7, 0x23F4, 0x23F5, 0x23F6, 0x23F7, 0x23EA, // 0x30 + 0x23E9, 0x23EE, 0x23ED, 0x23F8, 0x23F9, 0x23FA, 0x1F5DA, 0x1F5F3, // 0x38 + 0x1F6E0, 0x1F3D7, 0x1F3D8, 0x1F3D9, 0x1F3DA, 0x1F3DC, 0x1F3ED, 0x1F3DB, // 0x40 + 0x1F3E0, 0x1F3D6, 0x1F3DD, 0x1F6E3, 0x1F50D, 0x1F3D4, 0x1F441, 0x1F442, // 0x48 + 0x1F3DE, 0x1F3D5, 0x1F6E4, 0x1F3DF, 0x1F6F3, 0x1F56C, 0x1F56B, 0x1F568, // 0x50 + 0x1F508, 0x1F394, 0x1F395, 0x1F5EC, 0x1F67D, 0x1F5ED, 0x1F5EA, 0x1F5EB, // 0x58 + 0x2B94, 0x2714, 0x1F6B2, 0x2B1C, 0x1F6E1, 0x1F4E6, 0x1F6F1, 0x2B1B, // 0x60 + 0x1F691, 0x1F6C8, 0x1F6E9, 0x1F6F0, 0x1F7C8, 0x1F574, 0x2B24, 0x1F6E5, // 0x68 + 0x1F694, 0x1F5D8, 0x1F5D9, 0x2753, 0x1F6F2, 0x1F687, 0x1F68D, 0x26F3, // 0x70 + 0x29B8, 0x2296, 0x1F6AD, 0x1F5EE, 0x23D0, 0x1F5EF, 0x1F5F2, 0x0000, // 0x78 + 0x1F6B9, 0x1F6BA, 0x1F6C9, 0x1F6CA, 0x1F6BC, 0x1F47D, 0x1F3CB, 0x26F7, // 0x80 + 0x1F3C2, 0x1F3CC, 0x1F3CA, 0x1F3C4, 0x1F3CD, 0x1F3CE, 0x1F698, 0x1F5E0, // 0x88 + 0x1F6E2, 0x1F4B0, 0x1F3F7, 0x1F4B3, 0x1F46A, 0x1F5E1, 0x1F5E2, 0x1F5E3, // 0x90 + 0x272F, 0x1F584, 0x1F585, 0x1F583, 0x1F586, 0x1F5B9, 0x1F5BA, 0x1F5BB, // 0x98 + 0x1F575, 0x1F570, 0x1F5BD, 0x1F5BE, 0x1F4CB, 0x1F5D2, 0x1F5D3, 0x1F56E, // 0xA0 + 0x1F4DA, 0x1F5DE, 0x1F5DF, 0x1F5C3, 0x1F5C2, 0x1F5BC, 0x1F3AD, 0x1F39C, // 0xA8 + 0x1F398, 0x1F399, 0x1F3A7, 0x1F4BF, 0x1F39E, 0x1F4F7, 0x1F39F, 0x1F3AC, // 0xB0 + 0x1F4FD, 0x1F4F9, 0x1F4FE, 0x1F4FB, 0x1F39A, 0x1F39B, 0x1F4FA, 0x1F4BB, // 0xB8 + 0x1F5A5, 0x1F5A6, 0x1F5A7, 0x1F579, 0x1F3AE, 0x1F57B, 0x1F57C, 0x1F4DF, // 0xC0 + 0x1F581, 0x1F580, 0x1F5A8, 0x1F5A9, 0x1F5BF, 0x1F5AA, 0x1F5DC, 0x1F512, // 0xC8 + 0x1F513, 0x1F5DD, 0x1F4E5, 0x1F4E4, 0x1F573, 0x1F323, 0x1F324, 0x1F325, // 0xD0 + 0x1F326, 0x2601, 0x1F328, 0x1F327, 0x1F329, 0x1F32A, 0x1F32C, 0x1F32B, // 0xD8 + 0x1F31C, 0x1F321, 0x1F6CB, 0x1F6CF, 0x1F37D, 0x1F378, 0x1F6CE, 0x1F6CD, // 0xE0 + 0x24C5, 0x267F, 0x1F6C6, 0x1F588, 0x1F393, 0x1F5E4, 0x1F5E5, 0x1F5E6, // 0xE8 + 0x1F5E7, 0x1F6EA, 0x1F43F, 0x1F426, 0x1F41F, 0x1F415, 0x1F408, 0x1F66C, // 0xF0 + 0x1F66E, 0x1F66D, 0x1F66F, 0x1F5FA, 0x1F30D, 0x1F30F, 0x1F30E, 0x1F54A, // 0xF8 +]; + +const WINGDINGS: [u32; 224] = [ + 0x0020, 0x1F589, 0x2702, 0x2701, 0x1F453, 0x1F56D, 0x1F56E, 0x1F56F, // 0x20 + 0x1F57F, 0x2706, 0x1F582, 0x1F583, 0x1F4EA, 0x1F4EB, 0x1F4EC, 0x1F4ED, // 0x28 + 0x1F5C0, 0x1F5C1, 0x1F5CE, 0x1F5CF, 0x1F5D0, 0x1F5C4, 0x23F3, 0x1F5AE, // 0x30 + 0x1F5B0, 0x1F5B2, 0x1F5B3, 0x1F5B4, 0x1F5AB, 0x1F5AC, 0x2707, 0x270D, // 0x38 + 0x1F58E, 0x270C, 0x1F58F, 0x1F44D, 0x1F44E, 0x261C, 0x261E, 0x261D, // 0x40 + 0x1F597, 0x1F590, 0x263A, 0x1F610, 0x2639, 0x1F4A3, 0x1F571, 0x1F3F3, // 0x48 + 0x1F3F1, 0x2708, 0x263C, 0x1F322, 0x2744, 0x1F546, 0x271E, 0x1F548, // 0x50 + 0x2720, 0x2721, 0x262A, 0x262F, 0x1F549, 0x2638, 0x2648, 0x2649, // 0x58 + 0x264A, 0x264B, 0x264C, 0x264D, 0x264E, 0x264F, 0x2650, 0x2651, // 0x60 + 0x2652, 0x2653, 0x1F670, 0x1F675, 0x26AB, 0x1F53E, 0x25FC, 0x1F78F, // 0x68 + 0x1F790, 0x2751, 0x2752, 0x1F79F, 0x29EB, 0x25C6, 0x2756, 0x1F799, // 0x70 + 0x2327, 0x2BB9, 0x2318, 0x1F3F5, 0x1F3F6, 0x1F676, 0x1F677, 0x0000, // 0x78 + 0x1F10B, 0x2780, 0x2781, 0x2782, 0x2783, 0x2784, 0x2785, 0x2786, // 0x80 + 0x2787, 0x2788, 0x2789, 0x1F10C, 0x278A, 0x278B, 0x278C, 0x278D, // 0x88 + 0x278E, 0x278F, 0x2790, 0x2791, 0x2792, 0x2793, 0x1F662, 0x1F660, // 0x90 + 0x1F661, 0x1F663, 0x1F65E, 0x1F65C, 0x1F65D, 0x1F65F, 0x2219, 0x2022, // 0x98 + 0x2B1D, 0x2B58, 0x1F786, 0x1F788, 0x1F78A, 0x1F78B, 0x1F53F, 0x25AA, // 0xA0 + 0x1F78E, 0x1F7C1, 0x1F7C5, 0x2605, 0x1F7CB, 0x1F7CF, 0x1F7D3, 0x1F7D1, // 0xA8 + 0x2BD0, 0x2316, 0x2BCE, 0x2BCF, 0x2BD1, 0x272A, 0x2730, 0x1F550, // 0xB0 + 0x1F551, 0x1F552, 0x1F553, 0x1F554, 0x1F555, 0x1F556, 0x1F557, 0x1F558, // 0xB8 + 0x1F559, 0x1F55A, 0x1F55B, 0x2BB0, 0x2BB1, 0x2BB2, 0x2BB3, 0x2BB4, // 0xC0 + 0x2BB5, 0x2BB6, 0x2BB7, 0x1F66A, 0x1F66B, 0x1F655, 0x1F654, 0x1F657, // 0xC8 + 0x1F656, 0x1F650, 0x1F651, 0x1F652, 0x1F653, 0x232B, 0x2326, 0x2B98, // 0xD0 + 0x2B9A, 0x2B99, 0x2B9B, 0x2B88, 0x2B8A, 0x2B89, 0x2B8B, 0x1F868, // 0xD8 + 0x1F86A, 0x1F869, 0x1F86B, 0x1F86C, 0x1F86D, 0x1F86F, 0x1F86E, 0x1F878, // 0xE0 + 0x1F87A, 0x1F879, 0x1F87B, 0x1F87C, 0x1F87D, 0x1F87F, 0x1F87E, 0x21E6, // 0xE8 + 0x21E8, 0x21E7, 0x21E9, 0x2B04, 0x21F3, 0x2B01, 0x2B00, 0x2B03, // 0xF0 + 0x2B02, 0x1F8AC, 0x1F8AD, 0x1F5F6, 0x2713, 0x1F5F7, 0x1F5F9, 0x0000, // 0xF8 +]; + +const WINGDINGS_2: [u32; 224] = [ + 0x0020, 0x1F58A, 0x1F58B, 0x1F58C, 0x1F58D, 0x2704, 0x2700, 0x1F57E, // 0x20 + 0x1F57D, 0x1F5C5, 0x1F5C6, 0x1F5C7, 0x1F5C8, 0x1F5C9, 0x1F5CA, 0x1F5CB, // 0x28 + 0x1F5CC, 0x1F5CD, 0x1F4CB, 0x1F5D1, 0x1F5D4, 0x1F5B5, 0x1F5B6, 0x1F5B7, // 0x30 + 0x1F5B8, 0x1F5AD, 0x1F5AF, 0x1F5B1, 0x1F592, 0x1F593, 0x1F598, 0x1F599, // 0x38 + 0x1F59A, 0x1F59B, 0x1F448, 0x1F449, 0x1F59C, 0x1F59D, 0x1F59E, 0x1F59F, // 0x40 + 0x1F5A0, 0x1F5A1, 0x1F446, 0x1F447, 0x1F5A2, 0x1F5A3, 0x1F591, 0x1F5F4, // 0x48 + 0x1F5F8, 0x1F5F5, 0x2611, 0x2BBD, 0x2612, 0x2BBE, 0x2BBF, 0x1F6C7, // 0x50 + 0x29B8, 0x1F671, 0x1F674, 0x1F672, 0x1F673, 0x203D, 0x1F679, 0x1F67A, // 0x58 + 0x1F67B, 0x1F666, 0x1F664, 0x1F665, 0x1F667, 0x1F65A, 0x1F658, 0x1F659, // 0x60 + 0x1F65B, 0x24EA, 0x2460, 0x2461, 0x2462, 0x2463, 0x2464, 0x2465, // 0x68 + 0x2466, 0x2467, 0x2468, 0x2469, 0x24FF, 0x2776, 0x2777, 0x2778, // 0x70 + 0x2779, 0x277A, 0x277B, 0x277C, 0x277D, 0x277E, 0x277F, 0x0000, // 0x78 + 0x2609, 0x1F315, 0x263D, 0x263E, 0x2E3F, 0x271D, 0x1F547, 0x1F55C, // 0x80 + 0x1F55D, 0x1F55E, 0x1F55F, 0x1F560, 0x1F561, 0x1F562, 0x1F563, 0x1F564, // 0x88 + 0x1F565, 0x1F566, 0x1F567, 0x1F668, 0x1F669, 0x22C5, 0x1F784, 0x2981, // 0x90 + 0x25CF, 0x25CB, 0x1F785, 0x1F787, 0x1F789, 0x2299, 0x29BF, 0x1F78C, // 0x98 + 0x1F78D, 0x25FE, 0x25A0, 0x25A1, 0x1F791, 0x1F792, 0x1F793, 0x1F794, // 0xA0 + 0x25A3, 0x1F795, 0x1F796, 0x1F797, 0x1F798, 0x2B29, 0x2B25, 0x25C7, // 0xA8 + 0x1F79A, 0x25C8, 0x1F79B, 0x1F79C, 0x1F79D, 0x1F79E, 0x2B2A, 0x2B27, // 0xB0 + 0x25CA, 0x1F7A0, 0x25D6, 0x25D7, 0x2BCA, 0x2BCB, 0x2BC0, 0x2BC1, // 0xB8 + 0x2B1F, 0x2BC2, 0x2B23, 0x2B22, 0x2BC3, 0x2BC4, 0x1F7A1, 0x1F7A2, // 0xC0 + 0x1F7A3, 0x1F7A4, 0x1F7A5, 0x1F7A6, 0x1F7A7, 0x1F7A8, 0x1F7A9, 0x1F7AA, // 0xC8 + 0x1F7AB, 0x1F7AC, 0x1F7AD, 0x1F7AE, 0x1F7AF, 0x1F7B0, 0x1F7B1, 0x1F7B2, // 0xD0 + 0x1F7B3, 0x1F7B4, 0x1F7B5, 0x1F7B6, 0x1F7B7, 0x1F7B8, 0x1F7B9, 0x1F7BA, // 0xD8 + 0x1F7BB, 0x1F7BC, 0x1F7BD, 0x1F7BE, 0x1F7BF, 0x1F7C0, 0x1F7C2, 0x1F7C4, // 0xE0 + 0x1F7C6, 0x1F7C9, 0x1F7CA, 0x2736, 0x1F7CC, 0x1F7CE, 0x1F7D0, 0x1F7D2, // 0xE8 + 0x2739, 0x1F7C3, 0x1F7C7, 0x272F, 0x1F7CD, 0x1F7D4, 0x2BCC, 0x2BCD, // 0xF0 + 0x203B, 0x2042, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0xF8 +]; + +const WINGDINGS_3: [u32; 224] = [ + 0x0020, 0x2B60, 0x2B62, 0x2B61, 0x2B63, 0x2B66, 0x2B67, 0x2B69, // 0x20 + 0x2B68, 0x2B70, 0x2B72, 0x2B71, 0x2B73, 0x2B76, 0x2B78, 0x2B7B, // 0x28 + 0x2B7D, 0x2B64, 0x2B65, 0x2B6A, 0x2B6C, 0x2B6B, 0x2B6D, 0x2B4D, // 0x30 + 0x2BA0, 0x2BA1, 0x2BA2, 0x2BA3, 0x2BA4, 0x2BA5, 0x2BA6, 0x2BA7, // 0x38 + 0x2B90, 0x2B91, 0x2B92, 0x2B93, 0x2B80, 0x2B83, 0x2B7E, 0x2B7F, // 0x40 + 0x2B84, 0x2B86, 0x2B85, 0x2B87, 0x2B8F, 0x2B8D, 0x2B8E, 0x2B8C, // 0x48 + 0x2B6E, 0x2B6F, 0x238B, 0x2324, 0x2303, 0x2325, 0x2423, 0x237D, // 0x50 + 0x21EA, 0x2BB8, 0x1F8A0, 0x1F8A1, 0x1F8A2, 0x1F8A3, 0x1F8A4, 0x1F8A5, // 0x58 + 0x1F8A6, 0x1F8A7, 0x1F8A8, 0x1F8A9, 0x1F8AA, 0x1F8AB, 0x1F850, 0x1F852, // 0x60 + 0x1F851, 0x1F853, 0x1F854, 0x1F855, 0x1F857, 0x1F856, 0x1F858, 0x1F859, // 0x68 + 0x25B2, 0x25BC, 0x25B3, 0x25BD, 0x25C0, 0x25B6, 0x25C1, 0x25B7, // 0x70 + 0x25E3, 0x25E2, 0x25E4, 0x25E5, 0x1F780, 0x1F782, 0x1F781, 0x0000, // 0x78 + 0x1F783, 0x2BC5, 0x2BC6, 0x2BC7, 0x2BC8, 0x2B9C, 0x2B9E, 0x2B9D, // 0x80 + 0x2B9F, 0x1F810, 0x1F812, 0x1F811, 0x1F813, 0x1F814, 0x1F816, 0x1F815, // 0x88 + 0x1F817, 0x1F818, 0x1F81A, 0x1F819, 0x1F81B, 0x1F81C, 0x1F81E, 0x1F81D, // 0x90 + 0x1F81F, 0x1F800, 0x1F802, 0x1F801, 0x1F803, 0x1F804, 0x1F806, 0x1F805, // 0x98 + 0x1F807, 0x1F808, 0x1F80A, 0x1F809, 0x1F80B, 0x1F820, 0x1F822, 0x1F824, // 0xA0 + 0x1F826, 0x1F828, 0x1F82A, 0x1F82C, 0x1F89C, 0x1F89D, 0x1F89E, 0x1F89F, // 0xA8 + 0x1F82E, 0x1F830, 0x1F832, 0x1F834, 0x1F836, 0x1F838, 0x1F83A, 0x1F839, // 0xB0 + 0x1F83B, 0x1F898, 0x1F89A, 0x1F899, 0x1F89B, 0x1F83C, 0x1F83E, 0x1F83D, // 0xB8 + 0x1F83F, 0x1F840, 0x1F842, 0x1F841, 0x1F843, 0x1F844, 0x1F846, 0x1F845, // 0xC0 + 0x1F847, 0x2BA8, 0x2BA9, 0x2BAA, 0x2BAB, 0x2BAC, 0x2BAD, 0x2BAE, // 0xC8 + 0x2BAF, 0x1F860, 0x1F862, 0x1F861, 0x1F863, 0x1F864, 0x1F865, 0x1F867, // 0xD0 + 0x1F866, 0x1F870, 0x1F872, 0x1F871, 0x1F873, 0x1F874, 0x1F875, 0x1F877, // 0xD8 + 0x1F876, 0x1F880, 0x1F882, 0x1F881, 0x1F883, 0x1F884, 0x1F885, 0x1F887, // 0xE0 + 0x1F886, 0x1F890, 0x1F892, 0x1F891, 0x1F893, 0x1F894, 0x1F896, 0x1F895, // 0xE8 + 0x1F897, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0xF0 + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0xF8 +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn both_storage_forms_map_alike() { + for f in ["Symbol", "Wingdings", "Wingdings 2", "Wingdings 3", "Webdings"] { + assert!(is_symbol_font(f)); + for code in 0x20u32..=0xFF { + let (Some(pua), Some(plain)) = (char::from_u32(0xF000 + code), char::from_u32(code)) else { continue }; + if code == 0xAD { + assert_eq!(symbol_char(f, plain), None); + continue; + } + assert_eq!(symbol_char(f, pua), symbol_char(f, plain), "{f} {code:#X}"); + } + } + } + + #[test] + fn pcl6_symbol_encoding() { + for family in ["Symbol (PCL6)", " symbol (pcl6) "] { + assert!(is_symbol_font(family)); + for code in 0x20..=0xFF { + let c = char::from_u32(code).unwrap(); + assert_eq!(symbol_char(family, c), symbol_char("Symbol", c)); + let pua = char::from_u32(0xF000 + code).unwrap(); + assert_eq!(symbol_char(family, pua), symbol_char("Symbol", pua)); + } + assert_eq!(symbol_char(family, '\u{F0B3}'), Some('≥')); + } + assert!(!is_symbol_font("Symbol (unknown)")); + } + + #[test] + fn symbol_uses_the_adobe_symbol_encoding() { + assert_eq!(symbol_char("Symbol", '\u{F061}'), Some('α')); + assert_eq!(symbol_char("symbol", 'a'), Some('α')); + assert_eq!(symbol_char("Symbol", 'm'), Some('μ')); + assert_eq!(symbol_char("Symbol", 'W'), Some('Ω')); + assert_eq!(symbol_char("Symbol", '\u{F0B7}'), Some('•')); + assert_eq!(symbol_char("Symbol", '\u{F0A5}'), Some('∞')); + assert_eq!(symbol_char("Symbol", '\u{F0D6}'), Some('√')); + // The radical extender is private use in the Adobe table: no equivalent. + assert_eq!(symbol_char("Symbol", '\u{F060}'), None); + } + + #[test] + fn wingdings_codes() { + assert_eq!(symbol_char("Wingdings", '\u{F04A}'), Some('☺')); + assert_eq!(symbol_char("Wingdings", 'J'), Some('☺')); + assert_eq!(symbol_char("Wingdings", 'L'), Some('☹')); + assert_eq!(symbol_char("Wingdings", '\u{F0FC}'), Some('✓')); + assert_eq!(symbol_char("Wingdings", '\u{F0FE}'), Some('\u{1F5F9}')); + assert_eq!(symbol_char("Wingdings", '\u{F06E}'), Some('◼')); + assert_eq!(symbol_char("Wingdings", '\u{F0A7}'), Some('▪')); + assert_eq!(symbol_char("Wingdings", '\u{F076}'), Some('❖')); + assert_eq!(symbol_char("Wingdings", '\u{F028}'), Some('\u{1F57F}')); + // The one character Unicode didn't encode. + assert_eq!(symbol_char("Wingdings", '\u{F0FF}'), None); + } + + #[test] + fn wingdings_2_3_and_webdings_codes() { + assert_eq!(symbol_char("Wingdings 2", '\u{F050}'), Some('\u{1F5F8}')); + assert_eq!(symbol_char("Wingdings 2", 'O'), Some('\u{1F5F4}')); + assert_eq!(symbol_char("Wingdings 2", '\u{F0FA}'), None); + assert_eq!(symbol_char("Wingdings 3", '\u{F021}'), Some('⭠')); + assert_eq!(symbol_char("Wingdings 3", '\u{F0F1}'), None); + assert_eq!(symbol_char("Webdings", '\u{F059}'), Some('\u{1F394}')); + assert_eq!(symbol_char("Webdings", 'a'), Some('\u{2714}')); + assert_eq!(symbol_char("Webdings", '\u{F0FF}'), Some('\u{1F54A}')); + } + + #[test] + fn other_fonts_and_characters_are_left_alone() { + assert!(!is_symbol_font("Arial")); + assert_eq!(symbol_char("Arial", '\u{F04A}'), None); + assert_eq!(symbol_char("Wingdings", '\u{1F600}'), None); + assert_eq!(symbol_char("Wingdings", '\u{10FFFF}'), None); + assert_eq!(symbol_char("Wingdings", '\u{1F}'), None); + assert_eq!(map_text("Wingdings", "J\u{F04C}é"), "☺☹\u{1F879}"); + assert_eq!(map_text("Arial", "J\u{F04C}"), "J\u{F04C}"); + } +} diff --git a/crates/math/tests/corpus.rs b/crates/math/tests/corpus.rs new file mode 100644 index 000000000..383b77783 --- /dev/null +++ b/crates/math/tests/corpus.rs @@ -0,0 +1,75 @@ +//! Round trips over equaSHion's corpus (storytold/craft-libs#29): its typed LaTeX equations +//! (`corpus/equations.tsv`), the MathLive-style LaTeX of `corpus/latex.tsv` and its OMML samples +//! from WordCraft and DeckCraft files (`corpus/omml/`). + +use craft_math::{Math, math, math_latex, mathml, omml}; + +const DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/corpus"); + +fn rows(file: &str) -> Vec> { + let text = std::fs::read_to_string(format!("{DIR}/{file}")).unwrap(); + text.lines().filter(|l| !l.trim().is_empty() && !l.starts_with('#')).map(|l| l.split('\t').map(str::to_string).collect()).collect() +} + +/// The equations of `equations.tsv`: (id, tree, display). +fn equations() -> Vec<(String, math::Arg, bool)> { + let v: Vec<_> = rows("equations.tsv").into_iter().map(|f| (f[0].clone(), math_latex::parse_latex(&f[1]), f[2].trim() == "1")).collect(); + assert!(v.len() >= 40, "{} rows", v.len()); + v +} + +#[test] +fn every_corpus_equation_reads_without_unknown_commands() { + for (id, tree, _) in equations() { + let lin = math::to_linear(&tree); + assert!(!tree.is_empty() && !lin.contains('\\'), "{id}: {lin}"); + } + for f in rows("latex.tsv") { + let lin = math::to_linear(&math_latex::parse_latex(&f[0])); + assert!(!lin.contains('\\'), "{}: {lin}", f[0]); + } +} + +#[test] +fn every_corpus_equation_survives_omml() { + for (id, tree, display) in equations() { + let eq = Math { nodes: tree.clone(), ..Default::default() }; + let xml = omml::write_str("", display, &eq, None); + let back = omml::read_str(&xml).unwrap_or_else(|| panic!("{id}: {xml}")); + // The writer states matrix column alignment the parser left implicit; the text is the same. + assert_eq!(math::to_linear(&back.nodes), math::to_linear(&tree), "{id}: {xml}"); + // And the OMML written from what was read is the same OMML. + let again = omml::write_str("", display, &Math { omml: String::new(), ..back }, None); + assert_eq!(again, xml, "{id}"); + } +} + +#[test] +fn every_corpus_equation_survives_mathml_and_latex() { + for (id, tree, display) in equations() { + let lin = math::to_linear(&tree); + let ml = mathml::to_mathml(&tree, display, ""); + assert_eq!(mathml::parse(&ml).and_then(|m| mathml::read(&m)), Some((lin.clone(), display)), "{id}: {ml}"); + let tex = math_latex::to_latex(&tree); + assert_eq!(math::to_linear(&math_latex::parse_latex(&tex)), lin, "{id}: {tex}"); + } +} + +#[test] +fn omml_samples_read_and_write_back() { + let mut n = 0; + for e in std::fs::read_dir(format!("{DIR}/omml")).unwrap().flatten() { + let xml = std::fs::read_to_string(e.path()).unwrap(); + let name = e.file_name(); + let m = omml::read_str(&xml).unwrap_or_else(|| panic!("{name:?}")); + assert!(!m.nodes.is_empty() && m.omml.starts_with("ab diff --git a/crates/math/tests/corpus/omml/deckcraft_pptx_roundtrip_frac_rpr.xml b/crates/math/tests/corpus/omml/deckcraft_pptx_roundtrip_frac_rpr.xml new file mode 100644 index 000000000..ca4636abf --- /dev/null +++ b/crates/math/tests/corpus/omml/deckcraft_pptx_roundtrip_frac_rpr.xml @@ -0,0 +1 @@ +x2 diff --git a/crates/math/tests/corpus/omml/wordcraft_docx_fixture_ssup.xml b/crates/math/tests/corpus/omml/wordcraft_docx_fixture_ssup.xml new file mode 100644 index 000000000..de1ea3b30 --- /dev/null +++ b/crates/math/tests/corpus/omml/wordcraft_docx_fixture_ssup.xml @@ -0,0 +1 @@ +x2 diff --git a/crates/math/tests/corpus/omml/wordcraft_docx_roundtrip_display_rad.xml b/crates/math/tests/corpus/omml/wordcraft_docx_roundtrip_display_rad.xml new file mode 100644 index 000000000..38a71f375 --- /dev/null +++ b/crates/math/tests/corpus/omml/wordcraft_docx_roundtrip_display_rad.xml @@ -0,0 +1 @@ +x diff --git a/crates/math/tests/corpus/omml/wordcraft_docx_roundtrip_foreign_attrs.xml b/crates/math/tests/corpus/omml/wordcraft_docx_roundtrip_foreign_attrs.xml new file mode 100644 index 000000000..270088e0b --- /dev/null +++ b/crates/math/tests/corpus/omml/wordcraft_docx_roundtrip_foreign_attrs.xml @@ -0,0 +1 @@ +x diff --git a/crates/math/tests/corpus/omml/wordcraft_docx_roundtrip_frac.xml b/crates/math/tests/corpus/omml/wordcraft_docx_roundtrip_frac.xml new file mode 100644 index 000000000..e13045b5e --- /dev/null +++ b/crates/math/tests/corpus/omml/wordcraft_docx_roundtrip_frac.xml @@ -0,0 +1 @@ +ab+1 diff --git a/crates/math/tests/omml_latex.rs b/crates/math/tests/omml_latex.rs new file mode 100644 index 000000000..6ecd9adc1 --- /dev/null +++ b/crates/math/tests/omml_latex.rs @@ -0,0 +1,41 @@ +//! OMML read into the tree and written as LaTeX means what GridCraft's direct OMML-to-LaTeX +//! reader (`crates/xlsx/src/omml.rs`) gave for its test cases, so GridCraft can read equations in +//! drawings through this crate. The LaTeX is compared by what it reads back as, not byte for byte. + +use craft_math::{math, math_latex, omml}; +fn tex(inner: &str) -> String { + let x = format!(r#"{inner}"#); + math_latex::to_latex(&omml::read_str(&x).unwrap().nodes) +} +#[test] +fn gridcraft_omml_cases_mean_the_same_latex() { + let brace = |chr: &str, pos: &str| { + format!( + "x" + ) + }; + let lim = "n"; + let under = format!("{}{lim}", brace("\u{23DF}", "bot")); + let cases: Vec<(String, &str)> = vec![ + ("x+1".into(), "x+1"), + ("ab".into(), "\\frac{a}{b}"), + ("x2".into(), "{x}^{2}"), + ("π".into(), "\\sqrt{\\pi }"), + ("i=1ni".into(), "\\sum_{i=1}^{n} {i}"), + ("f".into(), "\\int {f}"), + ("1001".into(), "\\left[ \\begin{matrix}1 & 0 \\\\ 0 & 1\\end{matrix} \\right]"), + ("sinx".into(), "\\sin x"), + ("R".into(), "\\mathbb{R}"), + ("if {x}".into(), "\\text{if \\{x\\}}"), + ("x".into(), "\\hat{x}"), + (under.clone(), "\\underbrace{x}_{n}"), + (format!("{under}2"), "{\\underbrace{x}_{n}}^{2}"), + (format!("{}{lim}", brace("\u{23DE}", "top")), "\\overbrace{x}^{n}"), + (format!("a{lim}"), "\\underset{n}{a}"), + (format!("{}+1{lim}", brace("\u{23DF}", "bot")), "\\underset{n}{\\underbrace{x}+1}"), + ]; + for (x, want) in cases { + let got = tex(&x); + assert_eq!(math::to_linear(&math_latex::parse_latex(&got)), math::to_linear(&math_latex::parse_latex(want)), "{x}: {got} for {want}"); + } +} diff --git a/crates/media-testkit/src/hostile.rs b/crates/media-testkit/src/hostile.rs new file mode 100644 index 000000000..1051d0405 --- /dev/null +++ b/crates/media-testkit/src/hostile.rs @@ -0,0 +1,89 @@ +//! Deterministic hostile-input hammer: truncations, bit flips and extreme-value overwrites of a +//! valid seed, each run under `catch_unwind` with a time budget. No dependencies, no `unsafe`. + +use std::fmt::Write as _; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::time::{Duration, Instant}; + +/// xorshift64* PRNG. +pub struct Rng(pub u64); + +impl Rng { + /// The next value. + pub fn next_u64(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + /// A value below `n` (0 for `n` = 0). + pub fn below(&mut self, n: usize) -> usize { + (self.next_u64() % n.max(1) as u64) as usize + } +} + +const EXTREMES: [u64; 8] = [0, 1, 0x7F, 0x80, 0xFF, 0xFFFF, 0x8000_0000, u64::MAX]; + +fn run_one(name: &str, what: &str, data: &[u8], run: &dyn Fn(&[u8])) { + let t = Instant::now(); + let r = catch_unwind(AssertUnwindSafe(|| run(data))); + let el = t.elapsed(); + assert!(r.is_ok(), "{name}: PANIC on {what} (len {})", data.len()); + assert!(el < Duration::from_secs(5), "{name}: HANG/slow ({el:?}) on {what} (len {})", data.len()); +} + +/// Run `run` over every truncation of `seed` (stepped beyond 4096 lengths), then `iters` random +/// mutations (bit flips, random bytes, 1/2/4/8-byte extreme-value overwrites in both +/// endiannesses, deletions, truncation). Panics, naming the mutation, on the first panic or on +/// a run slower than 5 s. +pub fn hammer(name: &str, seed: &[u8], iters: usize, run: impl Fn(&[u8])) { + run_one(name, "the unmodified seed", seed, &run); + let step = (seed.len() / 4096).max(1); + for n in (0..seed.len()).step_by(step) { + run_one(name, &format!("truncation to {n}"), &seed[..n], &run); + } + let mut rng = Rng((0x5EED_F00D ^ seed.len() as u64) | 1); + // CRAFT_MEDIA_HOSTILE_MULT=10 runs ten times the iterations (soak runs). + let mult = std::env::var("CRAFT_MEDIA_HOSTILE_MULT").ok().and_then(|v| v.parse::().ok()).unwrap_or(1); + for _ in 0..iters.saturating_mul(mult) { + let mut d = seed.to_vec(); + let mut what = String::new(); + for _ in 0..1 + rng.below(4) { + if d.is_empty() { + break; + } + let pos = rng.below(d.len()); + match rng.below(7) { + 0 => { + let b = rng.below(8); + d[pos] ^= 1 << b; + let _ = write!(what, "flip[{pos}].{b} "); + } + 1 => { + d[pos] = rng.next_u64() as u8; + let _ = write!(what, "set[{pos}]={:#x} ", d[pos]); + } + 2..=4 => { + let w = [1usize, 2, 4, 8][rng.below(4)]; + let v = EXTREMES[rng.below(EXTREMES.len())]; + let be = rng.below(2) == 0; + let bytes = if be { v.to_be_bytes()[8 - w..].to_vec() } else { v.to_le_bytes()[..w].to_vec() }; + let end = (pos + w).min(d.len()); + d[pos..end].copy_from_slice(&bytes[..end - pos]); + let _ = write!(what, "put{w}{}[{pos}]={v:#x} ", if be { "be" } else { "le" }); + } + 5 => { + let n = 1 + rng.below(16); + let end = (pos + n).min(d.len()); + d.drain(pos..end); + let _ = write!(what, "del[{pos}..{end}] "); + } + _ => { + d.truncate(pos); + let _ = write!(what, "trunc{pos} "); + } + } + } + run_one(name, &what, &d, &run); + } +} diff --git a/crates/media-testkit/src/lib.rs b/crates/media-testkit/src/lib.rs index 1b82f223d..6d3a75525 100644 --- a/crates/media-testkit/src/lib.rs +++ b/crates/media-testkit/src/lib.rs @@ -11,9 +11,14 @@ //! Fixtures are generated into `$CRAFT_MEDIA_FIXTURES_DIR` or `/target/fixtures`, one //! directory per crate or format, and never committed. //! +//! [`hostile::hammer`] runs a parser over truncations and mutations of a valid input and fails on +//! a panic or a slow run; `CRAFT_MEDIA_HOSTILE_MULT=10` runs ten times the iterations. +//! //! Failing loudly is what a test helper is for: a wrong `CRAFT_MEDIA_*` setting or an unwritable //! fixture directory panics, which fails the test that asked. +pub mod hostile; + use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::OnceLock; diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index fba89c899..cdbf28349 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -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 and AVI demuxers." +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." version.workspace = true edition.workspace = true license.workspace = true @@ -22,6 +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`). +mpegts = [] # Ogg demuxer (Ogg Opus and Vorbis mapping, `craft_media::ogg`). ogg = [] # Serialize and Deserialize for `Container`, `CodecId`, `CodecParams` and `PcmFormat`. @@ -57,6 +59,10 @@ required-features = ["isobmff"] name = "oracle_matroska" required-features = ["matroska"] +[[test]] +name = "oracle_mpegts" +required-features = ["mpegts"] + [[test]] name = "oracle_mux" required-features = ["isobmff"] diff --git a/crates/media/README.md b/crates/media/README.md index e270fb520..387ab8cdd 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -2,7 +2,7 @@ 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) and Matroska (MKV, WebM) and MXF demuxers and muxers, and -Ogg and AVI demuxers, written from the public specifications. No `unsafe`, no panics on malformed +Ogg, AVI and MPEG-2 Systems (transport and program stream) 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). @@ -21,12 +21,13 @@ that codec crates use to describe a file and configure a decoder. | `ogg` | `craft_media::ogg` | none | | `avi` | `craft_media::avi` | none | | `mxf` | `craft_media::mxf` | `chrono` | +| `mpegts` | `craft_media::mpegts` | none | | (none) | `Container`, `CodecId`, `CodecParams`, `PcmFormat`, `xiph_lace`, `ByteSource`, `ReadSeekSource` | none | | `serde` | `Serialize`/`Deserialize` on `Container`, `CodecId`, `CodecParams` and `PcmFormat` | `serde` | `default = ["isobmff"]`, so `bitstream` and `isobmff` build. `matroska` is opt-in: it is about as much code as `isobmff`, and most users of MP4/MOV (LightCraft, FigCraft, SoundCraft, EffectCraft) -do not read Matroska. `ogg`, `avi` and `mxf` are opt-in as well. The features are independent. +do not read Matroska. `ogg`, `avi`, `mxf` and `mpegts` are opt-in as well. The features are independent. ```toml craft-media = { git = "https://github.com/storytold/craft-libs", rev = "", features = ["matroska"] } @@ -115,7 +116,7 @@ Other differences: - `isobmff::ByteSource`, `matroska::ByteSource` and `ogg::ByteSource` are one trait, `craft_media::ByteSource` (with `ReadSeekSource`, which was Matroska's). A type FilmCraft implements both traits for keeps one of its two impls. -- `isobmff::Track`, `matroska::Track`, `ogg::Stream`, `avi::Stream` and `mxf::EssenceTrack` have `codec_params()`, all returning a +- `isobmff::Track`, `matroska::Track`, `ogg::Stream`, `avi::Stream`, `mxf::EssenceTrack` and `mpegts::Stream` have `codec_params()`, all returning a `CodecParams` (`CodecId::Unknown` for a codec without an identifier). The MP4 one describes the first sample's sample description; `codec_params_for(description_index)` gives any other, and `has_mixed_descriptions()` says whether the samples use more than one. @@ -480,8 +481,11 @@ hold. `Stream::codec_params()` maps `biCompression` and the `WAVEFORMATEX` format tag to a `CodecId` (Motion JPEG, H.264, HEVC, MPEG-4 Part 2, MPEG-2, VP8/VP9, AV1, ProRes, DNxHD; PCM, ADPCM, A-law, -µ-law, MP2, MP3, AAC, AC-3, Vorbis, FLAC). AVI stores H.264 and HEVC as Annex B, so `extradata` -is the bytes after the format header as stored, not an `avcC` / `hvcC` record. Uncompressed video +µ-law, MP2, MP3, AAC, AC-3, Vorbis, FLAC). `extradata` is the bytes after the format header +as stored. For H.264 and HEVC, `Stream::nal_framing()` says what they are: nothing (parameter sets in +the chunks), Annex B parameter sets (a file written with global headers) or an `avcC` / `hvcC` record +(a stream copied from MP4, whose chunks are then length-prefixed by the size it gives; +`bitstream::length_prefixed_nals` splits them). Uncompressed video is `CodecId::Unknown` with the FourCC in `tag`. Differences from `filmcraft-avi`: `ByteSource` is `craft_media::ByteSource`; `Error::Io` holds the @@ -492,6 +496,98 @@ Tests: hand-built files for every index path, truncation, every single-byte muta multi-byte damage (never a panic). `tests/oracle_avi.rs` checks ffmpeg-made files (Motion JPEG, H.264 with B-frames, BGR24, YUY2; PCM and MP3) against ffprobe; the ignored `opendml_file_past_1_gb` checks a 1.16 GB OpenDML file with `AVIX` extensions. +## `mpegts` + +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. + +```rust +use craft_media::mpegts::{Kind, open}; + +let file = open(&bytes)?; // any ByteSource +for s in &file.streams { + println!("{:?} {} {} units", s.id, s.codec.name(), s.units.len()); +} +let v = file.find(Kind::Video, |_| true).unwrap(); +let au: Vec = file.read_unit(&bytes, v, 0)?; // the first access unit +``` + +- **Transport streams**: 188-byte packets, 192-byte BDAV packets (sync byte after a 4-byte + arrival timestamp) and 204-byte packets; the packet size is sniffed from five consecutive sync + bytes. Lost sync resynchronises on the next aligned run. PSI sections are reassembled across + packets and checked with the MPEG CRC-32; the first program of the PAT is demuxed. Continuity + counter errors, CRC errors and resyncs are reported as warnings. +- **Program streams**: MPEG-2 and MPEG-1 packs, system headers, the program stream map (stream + types for elementary stream ids), padding, private stream 2 (DVD navigation) skipped, private + stream 1 split by sub-stream id. Garbage resynchronises on the next pack or PES start code. +- **Streams**: MPEG-1/2 video, H.264, HEVC, MPEG audio, AAC (ADTS, LATM/LOAS), AC-3, E-AC-3, + DTS, TrueHD, Blu-ray LPCM, DVD LPCM (format from the sub-stream header), PGS / DVB / teletext + subtitles; ISO 639 language from the PMT. +- **Access units**, found while the file is scanned (one pass, streaming; only a few bytes of + each stream are buffered): + - MPEG-1/2 video: a coded frame — a frame picture, or two field pictures (paired by + picture_structure) — with the sequence / GOP headers before it; picture type, temporal + reference, field structure, top_field_first, repeat_first_field, progressive_frame, closed + GOP / broken link. A PTS belongs to the unit whose picture start code is in that PES. + - H.264 / HEVC: PES packets with a timestamp (a PES without one continues the previous unit); + random access from IDR / IRAP NAL types; disposable when every slice is a non-reference. + - Audio: one frame per unit from the frame headers (sync re-hunted after garbage; a header + found while hunting is confirmed by the next one); a PTS belongs to the first frame starting + in the PES. + - LPCM and everything else: one PES packet per unit. +- **Timestamps**: 33-bit PTS/DTS unwrapped across the wrap (and back, for B pictures shown + before a wrap that came earlier); PCR / SCR range. +- **Reading**: a unit records only the position of its first packet and its offset in that + packet's payload; `read_unit` re-reads from there (the index costs a few dozen bytes per + unit, not per packet). + +`frame_bytes`, `frame_info` and `sei_has_recovery_point` are public: other containers that store +MPEG audio or AC-3 frames in chunks that do not follow them (AVI) find the frames again with them. + +`Codec::codec_id()` and `Stream::codec_params()` give the crate-wide `CodecId` / `CodecParams`. +MPEG-1 video reports `Mpeg2Video`; MPEG audio reports `Mp2` whatever its layer (the layer is in +each frame header: `frame_info(..).variant`); ADTS and LATM AAC both report `Aac`; DTS, TrueHD and +subtitles have no identifier (`Unknown`). The streams carry their configuration in band, so +`extradata` is empty; DVD LPCM fills `sample_rate`, `channels` and `pcm`. + +Limits, each with a test: 2²³ access units per stream (the rest are not indexed, with a warning), +128 MiB per unit read (`MAX_UNIT_BYTES`), a PES header given up after 1024 bytes, 16 stuffing bytes +in an MPEG-1 packet header, a pack header sniffed behind at most 64 zero bytes, and E-AC-3 frames of +at least 8 bytes. + +### Specifications + +| Document | Edition | Used for | +|---|---|---| +| ITU-T H.222.0 \| ISO/IEC 13818-1 | 2000 (second edition) | TS packets, adaptation fields, PCR, PSI (PAT / PMT, CRC-32 of Annex A), PES headers, PTS/DTS, program streams (pack, system header, program stream map), stream types | +| ISO/IEC 11172-1 | 1993 | MPEG-1 system streams (pack header, PES header stuffing / STD buffer / timestamps) | +| Blu-ray / AVCHD BDAV MPEG-2 TS layout (192-byte source packets with a 4-byte TP_extra_header; registration `HDMV`; stream types 0x80-0x92) | public descriptions | `.m2ts` / `.mts` | +| DVD-Video private stream 1 sub-stream layout (AC-3 / DTS 0x80-0x8F with a 3-byte header, LPCM 0xA0-0xAF with a 6-byte header, sub-pictures 0x20-0x3F) | public descriptions | `.vob` | +| ETSI EN 300 468 (descriptors 0x56, 0x59, 0x6A, 0x7A, 0x7B), ATSC A/52 Annex A (AC-3 in TS) | — | identifying private PES streams | +| ISO/IEC 11172-3, 13818-3 (frame headers), ISO/IEC 13818-7 (ADTS), 14496-3 (LOAS), ATSC A/52 (syncinfo, E-AC-3 frmsiz) | — | audio frame lengths for splitting | + +### Gaps + +- One program per TS (the first in the PAT); no program switching, no section-based + metadata (SDT / EIT), no scrambled streams. +- H.264 / HEVC access units follow PES packets: streams that put several pictures in one PES + packet (rare in practice; not seen in broadcast, AVCHD or FFmpeg output) would be indexed as + one unit. +- DVD navigation (IFO / NAV packets), multiple VOB concatenation and angle interleaving are not + handled; each file opens on its own. + +Differences from `filmcraft-mpegts`: `ByteSource` is `craft_media::ByteSource`; +`Error` is written by hand, without `thiserror`, and is `#[non_exhaustive]`; +`Codec::codec_id()` and `Stream::codec_params()` are new. + +Tests: a small TS muxer and PS writer (every access unit reads back byte-identical with its PTS, +key and disposable flags), 33-bit unwrap, truncation and mutation, streams of every codec filled +with random start codes and sync words, damaged PSI sections with valid CRCs, and the frame-header +helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares ten ffmpeg-made files (MPEG-2, H.264 +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. ## `mxf` @@ -577,7 +673,8 @@ sample rate, channels and (for plain PCM) the little-endian `PcmFormat`. MXF ess configuration in band, so `extradata` is empty. Limits, each with a test: a run-in of at most 65 535 bytes before the header partition pack, a -metadata or index value of at most 64 MiB (larger is refused before it is read), 16 MiB scanned +metadata or index value of at most 64 MiB (larger is refused before it is read) and 256 MiB of +them in all, 16 MiB scanned for the next partition pack after a lost KLV sync, an index position that cannot make a sparse table, at most 256 sound channels (8 in an AES3 element), a PCM block alignment of at most 4096 bytes, and a sound request of at most 2²⁴ samples past the stored essence. @@ -638,9 +735,13 @@ w.finish()?; ### Differences from `filmcraft-mxf` - `ByteSource` is `craft_media::ByteSource`. -- `WriterConfig::new` sets `company` and `product` to `craft-media` (FilmCraft: `FilmCraft`), and - the identification set's product UID is derived from `craft-media MXF writer`. Apps set their - own names; `write_opatom_pcm` always writes the defaults. +- `WriterConfig::new` sets `company` and `product` to `craft-media` (FilmCraft: `FilmCraft`) and + `version` to this crate's. Apps set their own; `write_opatom_pcm_as` takes them for the + in-memory OP-Atom PCM writer (`write_opatom_pcm` writes the defaults). The identification + set's product UID is derived from `" MXF writer"`, so `company` and `product` of + `FilmCraft` with FilmCraft's version string write the bytes `filmcraft-mxf` wrote. +- Everything read while opening (partition packs, primers, metadata sets, index segments) shares + a budget of 256 MiB; past it the file is refused. `filmcraft-mxf` bounded each value only. - `EssenceTrack::sync_before` returns 0 for a track without picture samples (a sound track); it indexed an empty table and panicked. - `Timecode::format` saturates for a drop-frame start near `i64::MAX`; it overflowed (a panic in @@ -664,7 +765,7 @@ sound. Always built, with no dependencies, so codec crates share them: - `Container`: the file format (`Wav`, `Aiff`, `Flac`, `Mp4`, `QuickTime`, `Matroska`, `WebM`, - `Ogg`, `Caf`, `Adts`, `MpegAudio`, `Ac3`, `Avi`, `Mxf`), with `name()`. + `Ogg`, `Caf`, `Adts`, `MpegAudio`, `Ac3`, `Avi`, `Mxf`, `MpegTs`, `MpegPs`), with `name()`. - `CodecId`: audio and video codecs (`Aac`, `HeAac`, `Opus`, `Eac3`, `Speex`, …, `H264`, `Hevc`, `Av1`, `ProRes`, `Dnxhd`, `Apv`, `Theora`, …, `Unknown`), with `name()`, `is_audio()`, `is_video()`. @@ -686,7 +787,7 @@ All are `#[non_exhaustive]`: new formats and fields are minor changes. `craft_media::ByteSource` (`len`, `read_at(offset, buf)`) is what every demuxer reads from. It is always built, so a crate that uses only `bitstream` can name it too. `isobmff::ByteSource`, -`matroska::ByteSource`, `ogg::ByteSource`, `avi::ByteSource` and `mxf::ByteSource` are the same trait. It is implemented for `[u8]`, +`matroska::ByteSource`, `ogg::ByteSource`, `avi::ByteSource`, `mxf::ByteSource` and `mpegts::ByteSource` are the same trait. It is implemented for `[u8]`, `Vec`, `&T`, `Arc`, `Box` and `std::fs::File` (not on wasm). `ReadSeekSource` adapts any `Read + Seek`; it is `Send + Sync` when the reader is `Send`. Implement the trait once for a custom source (a web `Blob`, a network range reader) to use every container with it. diff --git a/crates/media/src/avi/mod.rs b/crates/media/src/avi/mod.rs index 85b504cf6..592139cef 100644 --- a/crates/media/src/avi/mod.rs +++ b/crates/media/src/avi/mod.rs @@ -196,13 +196,49 @@ pub struct Stream { super_index: Vec, } +/// How the NAL units of an H.264 or HEVC stream are framed ([`Stream::nal_framing`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NalFraming { + /// Start codes (Annex B). With `header_sets`, the bytes after the format header are parameter + /// sets in Annex B, which a decoder needs before the first chunk: the chunks need not repeat + /// them. + AnnexB { + /// The stream header carries parameter sets. + header_sets: bool, + }, + /// Length prefixes of this many bytes (1 to 4): the bytes after the format header are an + /// `avcC` / `hvcC` record, as in a stream copied from MP4 as it is. + LengthPrefixed(usize), +} + impl Stream { + /// How the chunks of an H.264 or HEVC stream frame their NAL units, from the bytes after the + /// format header (`BitmapInfo::extra`); `None` for any other stream. A record (first byte 1) + /// gives the length-prefix size it declares, start codes mean parameter sets in Annex B, and + /// anything else leaves the stream as Annex B with its sets in band. + pub fn nal_framing(&self) -> Option { + let extra = &self.video.as_ref()?.extra; + // lengthSizeMinusOne: byte 4 of an avcC record, byte 21 of an hvcC record + let size_at = match self.codec_params().codec { + crate::CodecId::H264 => 4, + crate::CodecId::Hevc => 21, + _ => return None, + }; + Some(if extra.first() == Some(&1) { + NalFraming::LengthPrefixed(extra.get(size_at).map_or(4, |b| usize::from(b & 3) + 1)) + } else { + NalFraming::AnnexB { header_sets: extra.starts_with(&[0, 0, 1]) || extra.starts_with(&[0, 0, 0, 1]) } + }) + } + /// What a decoder needs for this stream, in the container-neutral form the codec crates take. /// /// The codec comes from `biCompression` (video) or the format tag (audio). `tag` is the video - /// FourCC as stored. `extradata` is the bytes after the format header as stored: AVI keeps - /// H.264 and HEVC as Annex B, so it is not an `avcC` / `hvcC` record, and it may be empty - /// (the parameter sets are then in the stream). Uncompressed video is [`CodecId::Unknown`] + /// FourCC as stored. `extradata` is the bytes after the format header as stored. For H.264 + /// and HEVC that is one of three things, which [`Stream::nal_framing`] tells apart: nothing + /// (the parameter sets are in the chunks), Annex B parameter sets (a file written with global + /// headers), or an `avcC` / `hvcC` record (a stream copied from MP4, whose chunks are then + /// length-prefixed). Uncompressed video is [`CodecId::Unknown`] /// with its FourCC (or `BI_RGB` / `BI_BITFIELDS`) in `tag`; see [`BitmapInfo`] for its layout. /// /// [`CodecId::Unknown`]: crate::CodecId::Unknown diff --git a/crates/media/src/avi/tests.rs b/crates/media/src/avi/tests.rs index 9ae5cdf86..2edac310b 100644 --- a/crates/media/src/avi/tests.rs +++ b/crates/media/src/avi/tests.rs @@ -1,5 +1,7 @@ use super::*; +mod hostile; + #[test] fn stream_number_supports_decimal_and_hex_ids() { assert_eq!(Stream::number(b"10dc"), Some(10)); @@ -633,3 +635,32 @@ fn random_damage_never_panics() { } } } + +/// The bytes after an H.264 / HEVC format header say how the chunks are framed: nothing (sets in +/// band), Annex B parameter sets, or an `avcC` / `hvcC` record with its length-prefix size. +#[test] +fn nal_framing_reads_the_stream_header_setup() { + let f = open(&avi(true, false, false)).unwrap(); + let mut s = f.streams[0].clone(); + assert_eq!(s.nal_framing(), None, "Motion JPEG has no NAL units"); + assert_eq!(f.streams[1].nal_framing(), None, "nor has audio"); + let mut framing = |fourcc: &[u8; 4], extra: &[u8]| { + let b = s.video.as_mut().unwrap(); + (b.compression, b.extra) = (*fourcc, extra.to_vec()); + (s.nal_framing(), s.codec_params().extradata == extra) + }; + assert_eq!(framing(b"H264", &[]), (Some(NalFraming::AnnexB { header_sets: false }), true)); + assert_eq!(framing(b"H264", &[0, 0, 0, 1, 0x67, 0x64]), (Some(NalFraming::AnnexB { header_sets: true }), true)); + assert_eq!(framing(b"hevc", &[0, 0, 1, 0x40, 1]), (Some(NalFraming::AnnexB { header_sets: true }), true)); + // avcC: version 1, profile, compatibility, level, then 6 reserved bits and lengthSizeMinusOne + assert_eq!(framing(b"avc1", &[1, 0x64, 0, 0x1F, 0xFF, 0xE1]), (Some(NalFraming::LengthPrefixed(4)), true)); + assert_eq!(framing(b"avc1", &[1, 0x64, 0, 0x1F, 0xFD]), (Some(NalFraming::LengthPrefixed(2)), true)); + // hvcC keeps it in byte 21 + let mut hvcc = vec![1u8; 23]; + hvcc[21] = 0xF2; + assert_eq!(framing(b"hvc1", &hvcc), (Some(NalFraming::LengthPrefixed(3)), true)); + // a record cut short still frames the chunks, with the usual four bytes + assert_eq!(framing(b"hvc1", &[1, 2, 3]), (Some(NalFraming::LengthPrefixed(4)), true)); + // setup that is neither: left as Annex B with the sets in band + assert_eq!(framing(b"H264", &[9, 9, 9]), (Some(NalFraming::AnnexB { header_sets: false }), true)); +} diff --git a/crates/media/src/avi/tests/hostile.rs b/crates/media/src/avi/tests/hostile.rs new file mode 100644 index 000000000..b4f57db41 --- /dev/null +++ b/crates/media/src/avi/tests/hostile.rs @@ -0,0 +1,25 @@ +//! Hostile-input hammer: truncation, bit flips and extreme field values must never panic or hang. + +use super::*; + +fn exercise(d: &[u8]) { + for opts in [OpenOptions::default(), OpenOptions { ignore_odml: true, ..Default::default() }] { + if let Ok(f) = open_with(d, opts) { + for (s, st) in f.streams.iter().enumerate() { + let n = st.chunks.len(); + for k in [0, n / 2, n.saturating_sub(1), n, usize::MAX] { + let _ = f.read_chunk(d, s, k); + } + } + } + } +} + +#[test] +fn hostile_input_never_panics() { + let (_, at) = avi_odml([0, 0]); + let seeds = [avi(true, false, false), avi(true, true, true), avi(false, false, false), avi_odml(at).0]; + for (i, s) in seeds.iter().enumerate() { + craft_media_testkit::hostile::hammer(&format!("avi seed {i}"), s, 30_000, exercise); + } +} diff --git a/crates/media/src/id.rs b/crates/media/src/id.rs index 7862546f3..00b63d004 100644 --- a/crates/media/src/id.rs +++ b/crates/media/src/id.rs @@ -40,6 +40,10 @@ pub enum Container { Avi, /// MXF (SMPTE ST 377-1): OP1a, OP-Atom. Mxf, + /// MPEG-2 transport stream (TS, M2TS). + MpegTs, + /// MPEG-1/2 program stream (MPG, VOB). + MpegPs, } impl Container { @@ -60,6 +64,8 @@ impl Container { Container::Ac3 => "AC-3", Container::Avi => "AVI", Container::Mxf => "MXF", + Container::MpegTs => "MPEG-TS", + Container::MpegPs => "MPEG-PS", } } } diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index eaaea04ed..a9c812318 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -10,10 +10,12 @@ //! - `ogg` (feature `ogg`): a clean-room Ogg demuxer with Ogg Opus and Ogg Vorbis stream mapping. //! - `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). //! - [`Container`] and [`CodecId`] (no feature): the identifiers the codec crates report a file's //! container and codec with. //! -//! `bitstream` and `isobmff` are on by default; `matroska`, `ogg`, `avi` and `mxf` are opt-in. A crate that needs +//! `bitstream` and `isobmff` are on by default; `matroska`, `ogg`, `avi`, `mxf` and `mpegts` are opt-in. A crate that needs //! only bit I/O uses `default-features = false, features = ["bitstream"]`. #[cfg(feature = "avi")] @@ -25,6 +27,8 @@ mod id; pub mod isobmff; #[cfg(feature = "matroska")] pub mod matroska; +#[cfg(feature = "mpegts")] +pub mod mpegts; #[cfg(feature = "mxf")] pub mod mxf; #[cfg(feature = "ogg")] diff --git a/crates/media/src/mpegts/es.rs b/crates/media/src/mpegts/es.rs new file mode 100644 index 000000000..8568c7cba --- /dev/null +++ b/crates/media/src/mpegts/es.rs @@ -0,0 +1,902 @@ +//! Splitting elementary streams into access units while the file is scanned. +//! +//! The scanners feed each stream's payload bytes chunk by chunk (a TS packet's payload, a PS +//! packet's payload). A chunk is identified by the position the reader restarts from (`pos`) and +//! the elementary-stream offset of its first byte. Splitting needs only a few bytes beyond a +//! boundary, so only the most recent chunks are remembered. + +use std::collections::VecDeque; + +use super::{Codec, PictureInfo, Unit}; + +/// How a stream is cut into units. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + /// MPEG-1/2 video: one coded frame (a frame picture or two field pictures) per unit. + MpegVideo, + /// H.264 / HEVC: one access unit per unit (the first of a PES packet keeps its timestamps); + /// NAL types give the flags. + Nal { hevc: bool }, + /// Framed audio with self-describing frame headers. + Audio(AudioSync), + /// One PES packet per unit. + Pes, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum AudioSync { + Mpa, + Adts, + Loas, + Ac3, +} + +impl Mode { + fn of(codec: &Codec) -> Mode { + match codec { + Codec::Mpeg1Video | Codec::Mpeg2Video => Mode::MpegVideo, + Codec::H264 => Mode::Nal { hevc: false }, + Codec::Hevc => Mode::Nal { hevc: true }, + Codec::MpegAudio => Mode::Audio(AudioSync::Mpa), + Codec::AacAdts => Mode::Audio(AudioSync::Adts), + Codec::AacLatm => Mode::Audio(AudioSync::Loas), + Codec::Ac3 | Codec::Eac3 => Mode::Audio(AudioSync::Ac3), + _ => Mode::Pes, + } + } +} + +#[derive(Clone, Copy)] +struct PesMark { + es_start: u64, + pts: Option, + dts: Option, + used: bool, +} + +/// A unit whose end is not known yet. +#[derive(Clone, Copy)] +struct Open { + start: u64, + pos: u64, + offset: u32, + pts: Option, + dts: Option, + key: bool, + disposable: bool, + /// A coded slice has been seen (H.264 / HEVC). + vcl: bool, + picture: Option, +} + +/// MPEG video picture waiting for its coding extension (to tell fields from frames). +#[derive(Clone, Copy)] +struct PendingPicture { + /// Start of the unit if the picture begins one (its first sequence / GOP header). + unit_start: u64, + /// The picture start code (timestamps belong to the unit whose picture starts in the PES). + at: u64, + info: PictureInfo, +} + +pub(crate) struct Splitter { + mode: Mode, + /// Elementary-stream bytes fed so far. + es_pos: u64, + /// Recent chunks: (reader position, ES offset of the first byte). + chunks: VecDeque<(u64, u64)>, + pes: VecDeque, + /// Unconsumed bytes (start codes / frame headers spanning chunks), starting at `buf_start`. + buf: Vec, + buf_start: u64, + open: Option, + pub units: Vec, + pub skipped: u64, + /// Units beyond [`MAX_UNITS`] were dropped. + pub truncated: bool, + max_units: usize, + // MPEG video state + header_start: Option, + seq_in_unit: bool, + gop: Option<(bool, bool)>, + pending: Option, + open_field: Option, + // audio state + next_frame: Option, +} + +/// AC-3 frame sizes in 16-bit words for 48 / 44.1 / 32 kHz (A/52 Table 5.18), by +/// frmsizecod / 2; 44.1 kHz adds a word for odd frmsizecod. +const AC3_KBPS: [u32; 19] = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640]; + +pub(crate) fn ac3_frame_bytes(fscod: u8, frmsizecod: u8) -> Option { + let kbps = *AC3_KBPS.get((frmsizecod / 2) as usize)?; + let words = match fscod { + 0 => kbps * 2, + 1 => kbps * 96_000 / 44_100 + (frmsizecod & 1) as u32, + 2 => kbps * 3, + _ => return None, + }; + Some(words as usize * 2) +} + +const MPA_KBPS: [[u16; 15]; 5] = [ + [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448], // MPEG-1 layer I + [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384], // MPEG-1 layer II + [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320], // MPEG-1 layer III + [0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256], // MPEG-2/2.5 layer I + [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160], // MPEG-2/2.5 layers II, III +]; + +/// MPEG audio frame header (ISO/IEC 11172-3 §2.4.2.3, 13818-3 LSF): (frame bytes, sample rate, +/// samples per frame). +pub(crate) fn mpa_header(b: &[u8]) -> Option<(usize, u32, u32)> { + if b.len() < 4 || b[0] != 0xFF || b[1] & 0xE0 != 0xE0 { + return None; + } + let version = (b[1] >> 3) & 3; // 0: 2.5, 2: MPEG-2, 3: MPEG-1 + let layer = (b[1] >> 1) & 3; // 3: I, 2: II, 1: III + let br = (b[2] >> 4) as usize; + let sr = (b[2] >> 2) & 3; + let pad = ((b[2] >> 1) & 1) as usize; + if version == 1 || layer == 0 || br == 0 || br == 15 || sr == 3 { + return None; + } + let rate = [44_100u32, 48_000, 32_000][sr as usize] + >> match version { + 3 => 0, + 2 => 1, + _ => 2, + }; + let table = match (version == 3, layer) { + (true, 3) => 0, + (true, 2) => 1, + (true, _) => 2, + (false, 3) => 3, + (false, _) => 4, + }; + let kbps = MPA_KBPS[table][br] as usize; + let (bytes, samples) = match layer { + 3 => ((12 * kbps * 1000 / rate as usize + pad) * 4, 384), + 2 => (144 * kbps * 1000 / rate as usize + pad, 1152), + _ if version == 3 => (144 * kbps * 1000 / rate as usize + pad, 1152), + _ => (72 * kbps * 1000 / rate as usize + pad, 576), + }; + (bytes >= 4).then_some((bytes, rate, samples)) +} + +/// What an audio frame header says. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FrameInfo { + /// Samples per second. + pub sample_rate: u32, + /// Channel count. + pub channels: u32, + /// Samples per channel in the frame. + pub samples: u32, + /// MPEG audio layer (1-3); AC-3 bsid; ADTS object type (profile + 1). + pub variant: u8, +} + +const ADTS_RATES: [u32; 13] = [96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000, 12_000, 11_025, 8_000, 7_350]; + +/// Bytes of the audio frame whose header starts `b` (MPEG audio, ADTS, LATM, AC-3, E-AC-3), or +/// `None` without a valid header there. For containers that store frames in chunks that need not +/// follow them (AVI): the frames are found again with it. +pub fn frame_bytes(codec: &Codec, b: &[u8]) -> Option { + let sync = match codec { + Codec::MpegAudio => AudioSync::Mpa, + Codec::AacAdts => AudioSync::Adts, + Codec::AacLatm => AudioSync::Loas, + Codec::Ac3 | Codec::Eac3 => AudioSync::Ac3, + _ => return None, + }; + frame_len(sync, b) +} + +/// Sample rate, channels and samples of the audio frame whose header starts `b` (the codecs of +/// [`frame_bytes`] except LATM), or `None` without a valid header there. +pub fn frame_info(codec: &Codec, b: &[u8]) -> Option { + match codec { + Codec::MpegAudio => { + let (_, sample_rate, samples) = mpa_header(b)?; + let layer = 4 - ((b[1] >> 1) & 3); + Some(FrameInfo { sample_rate, channels: if b[3] >> 6 == 3 { 1 } else { 2 }, samples, variant: layer }) + } + Codec::AacAdts => { + frame_len(AudioSync::Adts, b)?; + let sf = ((b[2] >> 2) & 15) as usize; + let ch = (((b[2] & 1) << 2) | (b[3] >> 6)) as u32; + Some(FrameInfo { + sample_rate: *ADTS_RATES.get(sf)?, + channels: if ch == 0 { + 2 + } else if ch == 7 { + 8 + } else { + ch + }, + samples: 1024 * ((b[6] & 3) as u32 + 1), + variant: (b[2] >> 6) + 1, + }) + } + Codec::Ac3 | Codec::Eac3 => { + frame_len(AudioSync::Ac3, b)?; + let bsid = b[5] >> 3; + if bsid > 10 { + // E-AC-3: fscod(2) numblkscod(2) acmod(3) lfeon(1) + let fscod = b[4] >> 6; + let (rate, blocks) = if fscod == 3 { + // fscod2 3 is reserved (no sample rate) + (*[24_000, 22_050, 16_000].get(((b[4] >> 4) & 3) as usize)?, 6) + } else { + ([48_000, 44_100, 32_000][fscod as usize], [1, 2, 3, 6][((b[4] >> 4) & 3) as usize]) + }; + let acmod = (b[4] >> 1) & 7; + return Some(FrameInfo { + sample_rate: rate, + channels: AC3_CHANNELS[acmod as usize] + (b[4] & 1) as u32, + samples: 256 * blocks, + variant: bsid, + }); + } + let fscod = b[4] >> 6; + let rate = *[48_000u32, 44_100, 32_000].get(fscod as usize)?; + // bsi: bsid(5) bsmod(3) acmod(3) [cmixlev(2)] [surmixlev(2)] [dsurmod(2)] lfeon(1) + let b6 = *b.get(6)?; + let acmod = b6 >> 5; + let mut bit = 3; // bits of byte 6 consumed + if acmod & 1 != 0 && acmod != 1 { + bit += 2; + } + if acmod & 4 != 0 { + bit += 2; + } + if acmod == 2 { + bit += 2; + } + let word = u16::from_be_bytes([b6, *b.get(7)?]); + let lfe = (word >> (15 - bit)) & 1; + Some(FrameInfo { sample_rate: rate, channels: AC3_CHANNELS[acmod as usize] + lfe as u32, samples: 1536, variant: bsid }) + } + _ => None, + } +} + +/// Whether the syncframe at the start of `b` is E-AC-3 (bsid 11-16) other than independent +/// substream 0: a dependent substream (strmtyp 1) or another program (A/52 §E2.3.1.1-2). +fn eac3_joins_unit(b: &[u8]) -> bool { + match b.get(2..6) { + Some(&[b2, _, _, b5]) => (11..=16).contains(&(b5 >> 3)) && (b2 >> 6 == 1 || (b2 >> 3) & 7 != 0), + _ => false, + } +} + +/// Bytes of an SEI NAL scanned for a recovery point message; a longer NAL is judged by its start. +const SEI_WINDOW: usize = 2048; + +/// Whether an H.264 SEI NAL (`nal` is the NAL header byte and the payload, as in the stream) +/// holds a recovery point message (payloadType 6, H.264 D.1.7) with recovery_frame_cnt 0. +pub fn sei_has_recovery_point(nal: &[u8]) -> bool { + // undo emulation prevention so that payload sizes are in RBSP bytes + let mut b = Vec::with_capacity(nal.len()); + let mut zeros = 0; + for &x in nal.iter().skip(1) { + if zeros >= 2 && x == 3 { + zeros = 0; + continue; + } + zeros = if x == 0 { zeros + 1 } else { 0 }; + b.push(x); + } + // payloadType / payloadSize: bytes of 0xFF followed by the last byte + let read = |i: &mut usize| { + let mut v = 0usize; + while let Some(&x) = b.get(*i) { + *i += 1; + v = v.saturating_add(x as usize); + if x != 0xFF { + break; + } + } + v + }; + let mut i = 0; + // each message takes at least two bytes, so the loop ends at the end of the NAL + while i + 2 <= b.len() { + let ty = read(&mut i); + let size = read(&mut i); + // recovery_frame_cnt is ue(v): a leading 1 bit is the value 0, i.e. decoding from here is + // correct at once. A count above 0 (gradual intra refresh) is not a safe seek point. + if ty == 6 && b.get(i).is_some_and(|x| x & 0x80 != 0) { + return true; + } + i = i.saturating_add(size); + } + false +} + +/// Shortest E-AC-3 syncframe accepted. A real syncframe holds the 6 header bytes read here plus +/// bsi and audio blocks (the smallest real ones are tens of bytes), so shorter "frames" +/// (`0B 77 00 01` is 4 bytes) are noise; they would otherwise turn every 4 input bytes into a +/// 64-byte `Unit`. +const EAC3_MIN_FRAME: usize = 8; + +/// Most units one stream may index. A `Unit` is 64 bytes, so this bounds a stream's table to +/// 512 MiB. It is 47 hours of 48 kHz AAC (the densest audio, 46.9 units/s), 9 hours of 240 fps +/// video: far beyond any real file, while a hostile file (a unit per 7 input bytes) cannot grow +/// the table without limit. +pub(crate) const MAX_UNITS: usize = 1 << 23; + +/// Full-bandwidth channels per AC-3 audio coding mode (A/52 Table 5.8). +const AC3_CHANNELS: [u32; 8] = [2, 1, 2, 3, 3, 4, 4, 5]; + +/// Frame length at the start of `b` for the given sync type (`None`: no valid header; `Some(0)` +/// is never returned). +fn frame_len(sync: AudioSync, b: &[u8]) -> Option { + match sync { + AudioSync::Mpa => mpa_header(b).map(|h| h.0), + AudioSync::Adts => { + if b.len() < 7 || b[0] != 0xFF || b[1] & 0xF6 != 0xF0 { + return None; + } + let len = ((b[3] as usize & 3) << 11) | (b[4] as usize) << 3 | (b[5] as usize) >> 5; + (len >= 7).then_some(len) + } + AudioSync::Loas => { + if b.len() < 3 || b[0] != 0x56 || b[1] & 0xE0 != 0xE0 { + return None; + } + let len = ((b[1] as usize & 0x1F) << 8) | b[2] as usize; + (len > 0).then_some(len + 3) + } + AudioSync::Ac3 => { + if b.len() < 6 || b[0] != 0x0B || b[1] != 0x77 { + return None; + } + let bsid = b[5] >> 3; + if bsid <= 10 { + ac3_frame_bytes(b[4] >> 6, b[4] & 0x3F) + } else if bsid <= 16 { + // E-AC-3: frmsiz + let len = ((((b[2] & 7) as usize) << 8) | b[3] as usize) * 2 + 2; + (len >= EAC3_MIN_FRAME).then_some(len) + } else { + None + } + } + } +} + +impl Splitter { + pub fn new(codec: &Codec) -> Splitter { + Splitter { + mode: Mode::of(codec), + es_pos: 0, + chunks: VecDeque::new(), + pes: VecDeque::new(), + buf: Vec::new(), + buf_start: 0, + open: None, + units: Vec::new(), + skipped: 0, + truncated: false, + max_units: MAX_UNITS, + header_start: None, + seq_in_unit: false, + gop: None, + pending: None, + open_field: None, + next_frame: None, + } + } + + /// A PES packet starts (its payload follows in the next chunks). + pub fn pes_start(&mut self, pts: Option, dts: Option) { + self.pes.push_back(PesMark { es_start: self.es_pos, pts, dts, used: false }); + while self.pes.len() > 64 { + self.pes.pop_front(); + } + match self.mode { + Mode::Pes => self.begin_pes_unit(true), + Mode::Nal { .. } => self.begin_pes_unit(pts.is_some() || dts.is_some()), + _ => {} + } + } + + /// PES-delimited units: a packet with a timestamp (or any packet in plain PES mode) starts a + /// new unit; one without continues the previous unit. + fn begin_pes_unit(&mut self, new: bool) { + if !new && self.open.is_some() { + return; + } + let at = self.es_pos; + self.close(at); + // the chunk of this position arrives with the next feed: resolved there + let mut o = Open { start: at, pos: u64::MAX, offset: 0, pts: None, dts: None, key: false, disposable: false, vcl: false, picture: None }; + if let Some((pts, dts)) = self.timestamps_at(at) { + o.pts = pts; + o.dts = dts; + } + if self.mode == Mode::Pes { + o.key = true; + } + self.open = Some(o); + } + + /// The unused timestamps of the PES packet holding `at` (consumed). + fn timestamps_at(&mut self, at: u64) -> Option<(Option, Option)> { + let m = self.pes.iter_mut().rev().find(|m| m.es_start <= at)?; + if m.used || (m.pts.is_none() && m.dts.is_none()) { + return None; + } + m.used = true; + Some((m.pts, m.dts)) + } + + /// Reader position and offset of elementary-stream byte `at`. + fn locate(&self, at: u64) -> Option<(u64, u32)> { + let c = self.chunks.iter().rev().find(|c| c.1 <= at)?; + Some((c.0, (at - c.1) as u32)) + } + + /// End the open unit at `end`. + fn close(&mut self, end: u64) { + let Some(o) = self.open.take() else { return }; + if end <= o.start || o.pos == u64::MAX { + return; + } + if self.units.len() >= self.max_units { + self.truncated = true; + return; + } + let size = (end - o.start).min(u32::MAX as u64) as u32; + self.units.push(Unit { + pts: o.pts, + dts: o.dts, + key: o.key, + disposable: o.disposable, + size, + pos: o.pos, + offset: o.offset, + picture: o.picture, + }); + } + + /// Payload bytes of one chunk (`pos`: where the reader restarts to find them). + pub fn feed(&mut self, pos: u64, data: &[u8]) { + if data.is_empty() { + return; + } + // PES-delimited modes resolve a unit's position from `pos` right here and never look a + // chunk up again, so remembering chunks there would only grow without bound (NAL streams + // keep theirs: an access unit can start inside a PES; `keep_from` prunes them) + if matches!(self.mode, Mode::MpegVideo | Mode::Audio(_) | Mode::Nal { .. }) { + self.chunks.push_back((pos, self.es_pos)); + } + if let Some(o) = self.open.as_mut() + && o.pos == u64::MAX + && o.start == self.es_pos + { + o.pos = pos; + o.offset = 0; + } + let start = self.es_pos; + self.es_pos += data.len() as u64; + match self.mode { + Mode::Pes => {} + Mode::Nal { hevc } => self.scan_nal(start, data, hevc), + Mode::MpegVideo => self.scan_mpeg(start, data), + Mode::Audio(sync) => self.scan_audio(start, data, sync), + } + // forget chunks no pending position can refer to + let keep_from = self.buf_start.min(self.pending.map_or(u64::MAX, |p| p.unit_start.min(p.at))).min(self.header_start.unwrap_or(u64::MAX)); + while self.chunks.len() > 2 && self.chunks[1].1 <= keep_from { + self.chunks.pop_front(); + } + } + + /// Append to the window and return it with its start. + fn window(&mut self, start: u64, data: &[u8]) { + if self.buf.is_empty() || self.buf_start + self.buf.len() as u64 != start { + self.buf.clear(); + self.buf_start = start; + } + self.buf.extend_from_slice(data); + } + + /// Keep only the last `keep` bytes of the window. + fn trim(&mut self, keep: usize) { + if self.buf.len() > keep { + let drop = self.buf.len() - keep; + self.buf.drain(..drop); + self.buf_start += drop as u64; + } + } + + /// Start codes in the window from index `from`: (window index of `00 00 01`, code). + fn next_start_code(&self, from: usize) -> Option { + let b = &self.buf; + let mut i = from; + while i + 3 <= b.len() { + match b[i + 2] { + 1 if b[i] == 0 && b[i + 1] == 0 => return Some(i), + 0 => i += 1, + _ => i += 3, + } + } + None + } + + fn scan_nal(&mut self, start: u64, data: &[u8], hevc: bool) { + self.window(start, data); + let mut i = 0; + let mut blocked = None; + while let Some(k) = self.next_start_code(i) { + // NAL header byte(s) and the first byte of the slice header needed + if k + if hevc { 6 } else { 5 } > self.buf.len() { + blocked = Some(k); + break; + } + // a four-byte start code begins with the zero_byte that belongs to its NAL + let at = self.buf_start + k as u64 - (k > 0 && self.buf.get(k - 1) == Some(&0)) as u64; + let (Some(&h), Some(&h1)) = (self.buf.get(k + 3), self.buf.get(k + if hevc { 5 } else { 4 })) else { + blocked = Some(k); + break; + }; + let (key, vcl, non_ref, au_start) = if hevc { + let t = (h >> 1) & 0x3F; + ( + (16..=23).contains(&t), + t < 32, + // sub-layer non-reference pictures (TRAIL_N, TSA_N, STSA_N, RADL_N, RASL_N) + t < 16 && t.is_multiple_of(2), + // first_slice_segment_in_pic_flag, or a NAL that precedes the first slice + // (VPS, SPS, PPS, AUD, prefix SEI, 41..=44, 48..=55; H.265 7.4.2.4.4) + if t < 32 { h1 & 0x80 != 0 } else { matches!(t, 32..=35 | 39 | 41..=44 | 48..=55) }, + ) + } else { + let t = h & 0x1F; + ( + t == 5, + (1..=5).contains(&t), + h & 0x60 == 0, + // first_mb_in_slice == 0 (ue(v) "1"), or a NAL that precedes the first slice + // (SEI, SPS, PPS, AUD, 14..=18; H.264 7.4.1.2.3) + match t { + 1 | 2 | 5 => h1 & 0x80 != 0, + 6..=9 | 14..=18 => true, + _ => false, + }, + ) + }; + let mut recovery = false; + if !hevc && h & 0x1F == 6 { + // the whole SEI NAL is needed to find a recovery point message among others + let end = self.next_start_code(k + 3); + if end.is_none() && self.buf.len() - k < SEI_WINDOW { + blocked = Some(k); + break; + } + let nal = self.buf.get(k + 3..end.unwrap_or(self.buf.len())).unwrap_or(&[]); + recovery = sei_has_recovery_point(nal); + } + // a unit holds one access unit: a new one starts at the first NAL that cannot belong + // to the slices already seen (a unit opened later than this NAL is left alone) + if au_start && self.open.as_ref().is_some_and(|o| o.vcl && at > o.start) { + self.begin_access_unit(at); + } + if let Some(o) = self.open.as_mut() + && at >= o.start + { + // a recovery point is a random-access point (the pictures before its recovery + // frame count completes may be imperfect) + o.key |= recovery; + if vcl { + o.key |= key; + // disposable while every slice is non-reference + o.disposable = if o.vcl { o.disposable && non_ref } else { non_ref }; + o.vcl = true; + } + } + i = k + 3; + } + self.keep_tail(i, blocked); + } + + /// Close the open unit and start the next access unit at `at`: it has no timestamp (the PES + /// timestamps belong to the first access unit of the packet). + fn begin_access_unit(&mut self, at: u64) { + self.close(at); + let (pos, offset) = self.locate(at).unwrap_or((u64::MAX, 0)); + self.open = Some(Open { start: at, pos, offset, pts: None, dts: None, key: false, disposable: false, vcl: false, picture: None }); + } + + /// Drop the scanned part of the window: keep from a start code waiting for more bytes, or + /// the last bytes a split start code may begin in. + fn keep_tail(&mut self, i: usize, blocked: Option) { + let len = self.buf.len(); + let resume = blocked.unwrap_or_else(|| i.max(len.saturating_sub(3))); + self.trim(len - resume.min(len)); + } + + fn scan_mpeg(&mut self, start: u64, data: &[u8]) { + self.window(start, data); + let mut i = 0; + let mut blocked = None; + while let Some(k) = self.next_start_code(i) { + // up to 5 bytes after the code are inspected + if k + 9 > self.buf.len() { + blocked = Some(k); + break; + } + let at = self.buf_start + k as u64; + let code = self.buf[k + 3]; + let p = [self.buf[k + 4], self.buf[k + 5], self.buf[k + 6], self.buf[k + 7], self.buf[k + 8]]; + match code { + 0xB3 => { + self.settle_pending(); + self.header_start.get_or_insert(at); + self.seq_in_unit = true; + } + 0xB8 => { + self.settle_pending(); + self.header_start.get_or_insert(at); + self.gop = Some((p[3] & 0x40 != 0, p[3] & 0x20 != 0)); + } + 0x00 => { + self.settle_pending(); + let info = PictureInfo { + coding_type: (p[1] >> 3) & 7, + temporal_reference: ((p[0] as u16) << 2) | (p[1] >> 6) as u16, + structure: 3, + progressive_frame: true, + sequence_header: self.seq_in_unit, + gop: self.gop.is_some(), + closed_gop: self.gop.is_some_and(|g| g.0), + broken_link: self.gop.is_some_and(|g| g.1), + ..Default::default() + }; + let unit_start = self.header_start.take().unwrap_or(at); + self.seq_in_unit = false; + self.gop = None; + self.pending = Some(PendingPicture { unit_start, at, info }); + } + 0xB5 if p[0] >> 4 == 8 => { + if let Some(pp) = self.pending.as_mut() { + pp.info.structure = p[2] & 3; + pp.info.top_field_first = p[3] & 0x80 != 0; + pp.info.repeat_first_field = p[3] & 0x02 != 0; + pp.info.progressive_frame = p[4] & 0x80 != 0; + } + self.settle_pending(); + } + 0xB5 | 0xB2 => {} + _ => self.settle_pending(), + } + i = k + 3; + } + self.keep_tail(i, blocked); + } + + /// A picture's structure is known: start a unit, or join a first field. + fn settle_pending(&mut self) { + let Some(pp) = self.pending.take() else { return }; + let s = pp.info.structure; + if let Some(first) = self.open_field + && s != 3 + && first != s + && s != 0 + { + self.open_field = None; + return; + } + self.close(pp.unit_start); + let (pos, offset) = self.locate(pp.unit_start).unwrap_or((u64::MAX, 0)); + let mut o = Open { + start: pp.unit_start, + pos, + offset, + pts: None, + dts: None, + key: matches!(pp.info.coding_type, 1 | 4), + disposable: pp.info.coding_type == 3, + vcl: true, + picture: Some(pp.info), + }; + if let Some((pts, dts)) = self.timestamps_at(pp.at) { + o.pts = pts; + o.dts = dts; + } + self.open = Some(o); + self.open_field = (s == 1 || s == 2).then_some(s); + } + + fn scan_audio(&mut self, start: u64, data: &[u8], sync: AudioSync) { + let end = start + data.len() as u64; + // skip whole chunks inside the current frame + if let Some(n) = self.next_frame + && n >= end + { + return; + } + self.window(start, data); + loop { + let at = match self.next_frame { + Some(n) if n >= self.buf_start => n, + _ => self.buf_start, + }; + let i = (at - self.buf_start) as usize; + if i + 8 > self.buf.len() { + // not enough bytes for a header yet + self.trim(self.buf.len().saturating_sub(i)); + return; + } + match frame_len(sync, &self.buf[i..]) { + Some(len) if self.next_frame == Some(at) || self.confirmed(sync, i, len) => { + // an E-AC-3 dependent substream or further program joins the access unit of + // the independent substream 0 before it, as in MP4 and Matroska + if !(sync == AudioSync::Ac3 && self.open.is_some() && eac3_joins_unit(&self.buf[i..])) { + self.close(at); + let (pos, offset) = self.locate(at).unwrap_or((u64::MAX, 0)); + let mut o = Open { start: at, pos, offset, pts: None, dts: None, key: true, disposable: false, vcl: false, picture: None }; + if let Some((pts, dts)) = self.timestamps_at(at) { + o.pts = pts; + o.dts = dts; + } + self.open = Some(o); + } + self.next_frame = Some(at + len as u64); + if at + len as u64 >= self.buf_start + self.buf.len() as u64 { + self.buf.clear(); + self.buf_start = at + len as u64; + return; + } + } + _ => { + // lost sync: look for the next header from the following byte + self.next_frame = None; + self.skipped += 1; + let next = self.buf[i + 1..].iter().position(|&b| { + matches!((sync, b), (AudioSync::Ac3, 0x0B) | (AudioSync::Loas, 0x56) | (AudioSync::Mpa | AudioSync::Adts, 0xFF)) + }); + match next { + Some(d) => { + self.skipped += d as u64; + // Keep a cursor into the current window rather than draining its + // prefix for every false sync candidate. + self.next_frame = Some(at + 1 + d as u64); + } + None => { + self.skipped += (self.buf.len() - i - 1) as u64; + // A split header can begin in the final few bytes; compact once. + self.trim(7); + return; + } + } + } + } + } + } + + /// A header found while hunting for sync is accepted when the next frame's header follows + /// it (or the data ends before it). + fn confirmed(&self, sync: AudioSync, i: usize, len: usize) -> bool { + let j = i + len; + if j + 8 > self.buf.len() { + return true; + } + frame_len(sync, &self.buf[j..]).is_some() + } + + /// End of stream: close the open unit. + pub fn finish(&mut self) { + self.settle_pending(); + let end = match (self.mode, self.next_frame) { + (Mode::Audio(_), Some(n)) => n.min(self.es_pos), + _ => self.es_pos, + }; + if let (Mode::Audio(_), Some(o)) = (self.mode, self.open) { + // a truncated last frame is dropped + if self.next_frame.is_some_and(|n| n > self.es_pos) { + self.skipped += self.es_pos - o.start; + self.open = None; + } + } + self.close(end); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn audio_frame_sizes() { + // MPEG-1 layer II 48 kHz 192 kb/s: 576 bytes; layer III 44.1 kHz 128 kb/s with padding: 418 + assert_eq!(mpa_header(&[0xFF, 0xFD, 0xA4, 0x00]), Some((576, 48_000, 1152))); + assert_eq!(mpa_header(&[0xFF, 0xFB, 0x92, 0x00]), Some((418, 44_100, 1152))); + // MPEG-2 layer III 24 kHz 64 kb/s: 192 bytes, 576 samples + assert_eq!(mpa_header(&[0xFF, 0xF3, 0x84, 0x00]), Some((192, 24_000, 576))); + // AC-3 448 kb/s at 48 kHz = 1792 bytes; 44.1 kHz 192 kb/s odd code = 836 bytes + assert_eq!(ac3_frame_bytes(0, 30), Some(1792)); + assert_eq!(ac3_frame_bytes(1, 21), Some(836)); + assert_eq!(ac3_frame_bytes(2, 0), Some(192)); + } + + #[test] + fn eac3_dependent_substreams_join_the_access_unit() { + // 16-byte E-AC-3 syncframes (frmsiz 7), 48 kHz six blocks stereo: independent, dependent + // (7.1 extension), independent, dependent + let frame = |strmtyp: u8| { + let mut f = vec![0x0B, 0x77, strmtyp << 6, 7, (3 << 4) | (2 << 1), 16 << 3]; + f.resize(16, 0); + f + }; + let es: Vec = [frame(0), frame(1), frame(0), frame(1)].concat(); + let mut s = Splitter::new(&Codec::Eac3); + s.feed(0, &es); + s.finish(); + assert_eq!(s.units.iter().map(|u| u.size).collect::>(), vec![32, 32]); + assert_eq!(frame_info(&Codec::Eac3, &es).map(|f| f.samples), Some(1536)); + // AC-3 frames are never joined + assert!(!eac3_joins_unit(&[0x0B, 0x77, 0x40, 0, 0, 8 << 3])); + } + + #[test] + fn ac3_header_prefix_of_six_bytes_is_not_indexed_out_of_bounds() { + // exactly the six bytes frame_len() guarantees: byte 6 (acmod) is missing + assert_eq!(frame_info(&Codec::Ac3, &[0x0B, 0x77, 0, 0, 0x1E, 0x40]), None); + assert_eq!(frame_info(&Codec::Ac3, &[0x0B, 0x77, 0, 0, 0x1E, 0x40, 0]), None); + } + + #[test] + fn eac3_reserved_sample_rate_is_refused() { + // fscod 3 and fscod2 3: no sample rate + let mut f = vec![0x0B, 0x77, 0, 7, 0xF0, 16 << 3]; + f.resize(16, 0); + assert_eq!(frame_info(&Codec::Eac3, &f), None); + f[4] = 0xE0; // fscod2 2: 16 kHz + assert_eq!(frame_info(&Codec::Eac3, &f).map(|i| i.sample_rate), Some(16_000)); + } + + #[test] + fn four_byte_eac3_frames_make_no_units() { + let es: Vec = [0x0B, 0x77, 0x00, 0x01].repeat(10_000); + let mut s = Splitter::new(&Codec::Eac3); + s.feed(0, &es); + s.finish(); + assert!(s.units.is_empty(), "{} units from 40000 noise bytes", s.units.len()); + } + + #[test] + fn pes_delimited_modes_do_not_retain_chunks() { + for codec in [Codec::LpcmBluray, Codec::Unknown(0x99)] { + let mut s = Splitter::new(&codec); + for k in 0..5000u64 { + s.pes_start(Some(k as i64), None); + s.feed(k * 188, &[0x11; 184]); + } + s.finish(); + assert!(s.chunks.len() <= 2, "{codec:?}: {} chunks retained", s.chunks.len()); + assert_eq!(s.units.len(), 5000, "{codec:?}"); + assert!(s.units.iter().enumerate().all(|(k, u)| u.pos == k as u64 * 188 && u.offset == 0), "{codec:?}"); + } + } + + #[test] + fn unit_table_is_capped() { + let frame = |k: u8| { + let mut v = vec![0x0B, 0x77, 0, 7, (3 << 4) | (2 << 1), 16 << 3]; + v.resize(16, k); + v + }; + let mut s = Splitter::new(&Codec::Eac3); + s.max_units = 10; + let es: Vec = (0..100).flat_map(frame).collect(); + s.feed(0, &es); + s.finish(); + assert_eq!(s.units.len(), 10); + assert!(s.truncated); + } +} diff --git a/crates/media/src/mpegts/hostile_tests.rs b/crates/media/src/mpegts/hostile_tests.rs new file mode 100644 index 000000000..3990acaef --- /dev/null +++ b/crates/media/src/mpegts/hostile_tests.rs @@ -0,0 +1,209 @@ +//! Hostile input: streams of every codec filled with start codes and sync words at random, +//! damaged containers, and the public frame-header helpers on arbitrary bytes. Errors and empty +//! tables are fine; a panic (an index out of range, an overflow in a debug build) is not. + +use super::tests::{TsMux, pes}; +use super::*; + +/// Deterministic xorshift. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } +} + +/// Random bytes with the patterns the splitters look for scattered through them: start codes of +/// every kind, MPEG audio / ADTS / LOAS / AC-3 sync words, with header bytes at the extremes. +/// At least one byte, at most about `max`. +fn soup(r: &mut Rng, max: usize) -> Vec { + let n = 1 + r.below(max); + let mut v = Vec::with_capacity(n + 16); + while v.len() < n { + let edge = [0x00u8, 0xFF, 0x80, 0x7F, r.next() as u8][r.below(5)]; + match r.below(12) { + 0 => v.extend([0, 0, 1, r.next() as u8]), + 1 => v.extend([0, 0, 1, [0x00, 0xB3, 0xB5, 0xB8, 0x09, 0x65, 0x41, 0x06, 0x26, 0x40, 0x46][r.below(11)], edge, edge]), + 2 => v.extend([0, 0, 0, 1, r.next() as u8, edge]), + 3 => v.extend([0xFF, 0xF0 | (r.next() as u8 & 0x0F), r.next() as u8, edge, edge, edge, edge]), + 4 => v.extend([0x0B, 0x77, edge, edge, r.next() as u8, r.next() as u8, edge]), + 5 => v.extend([0x56, 0xE0 | (r.next() as u8 & 0x1F), r.next() as u8]), + 6 => v.extend([edge; 3]), + _ => v.push(r.next() as u8), + } + } + v +} + +/// Opens and reads; returns how many units the tables hold. +fn open_and_read_all(data: &[u8]) -> usize { + let Ok(f) = open(data) else { return 0 }; + let _ = (f.format.name(), f.pcr_range); + for (s, st) in f.streams.iter().enumerate() { + let _ = (st.codec_params(), st.codec.name(), st.pts_range()); + let n = st.units.len(); + // every unit of a small table, a spread of a large one + for i in (0..n).step_by((n / 64).max(1)).chain(n.checked_sub(1)) { + let _ = f.read_unit(data, s, i); + } + } + let _ = f.read_unit(data, f.streams.len(), 0); + f.streams.iter().map(|s| s.units.len()).sum() +} + +/// Every stream type the PMT maps, each on its own PID. +const TYPES: [u8; 16] = [0x01, 0x02, 0x03, 0x04, 0x0F, 0x11, 0x1B, 0x24, 0x80, 0x81, 0x83, 0x84, 0x87, 0x90, 0x06, 0x42]; + +fn soup_ts(r: &mut Rng, m2ts: bool, packets: usize) -> Vec { + let mut mux = TsMux::new(m2ts); + let streams: Vec<(u8, u16)> = TYPES.iter().enumerate().map(|(i, &t)| (t, 0x200 + i as u16)).collect(); + mux.psi(&streams); + for _ in 0..packets { + let (_, pid) = streams[r.below(streams.len())]; + let payload = soup(r, 700); + let pts = (r.below(3) > 0).then(|| r.next() as i64 & ((1 << 33) - 1)); + let dts = pts.filter(|_| r.below(2) == 0).map(|p| p.wrapping_sub(3600) & ((1 << 33) - 1)); + mux.pes(pid, &pes([0xE0, 0xC0, 0xBD, 0xFD][r.below(4)], pts, dts, &payload, r.below(2) == 0)); + } + mux.out +} + +fn soup_ps(r: &mut Rng, mpeg1: bool, packets: usize) -> Vec { + let mut out = Vec::new(); + for _ in 0..packets { + if mpeg1 { + out.extend([0, 0, 1, 0xBA, 0x21, 0, 1, 0, 1, 0x80, 0, 1]); + } else { + out.extend([0, 0, 1, 0xBA, 0x44, 0, 4, 0, 4, 1, 1, 0x89, 0xC3, 0xF8 | r.below(8) as u8]); + out.extend(std::iter::repeat_n(0xFF, r.below(8))); + } + let mut payload = soup(r, 1500); + let id = [0xE0, 0xE1, 0xC0, 0xC1, 0xBD, 0xBD, 0xBD, 0xBB, 0xBC, 0xBE, 0xBF][r.below(11)]; + if id == 0xBD { + // DVD sub-streams: AC-3, DTS, LPCM (every format byte), sub-pictures + payload[0] = [0x80, 0x88, 0xA0, 0xA1, 0x20, r.next() as u8][r.below(6)]; + } + let pts = (r.below(3) > 0).then(|| r.next() as i64 & ((1 << 33) - 1)); + out.extend(pes(id, pts, None, &payload, true)); + } + out.extend([0, 0, 1, 0xB9]); + out +} + +#[test] +fn streams_of_start_codes_and_sync_words_never_panic() { + let mut r = Rng(0x1234_5678_9ABC_DEF1); + let (mut ts, mut ps) = (0, 0); + for round in 0..40 { + ts += open_and_read_all(&soup_ts(&mut r, round % 2 == 1, 150)); + ps += open_and_read_all(&soup_ps(&mut r, round % 2 == 1, 60)); + } + // the streams reach the splitters: they are cut into units, not rejected up front + assert!(ts > 2000 && ps > 500, "{ts} transport stream units, {ps} program stream units"); +} + +#[test] +fn damaged_containers_never_panic() { + let mut r = Rng(0xDEAD_BEEF_0BAD_F00D); + let bases = [soup_ts(&mut r, false, 60), soup_ts(&mut r, true, 60), soup_ps(&mut r, false, 40), soup_ps(&mut r, true, 40)]; + for base in &bases { + for _ in 0..300 { + let mut d = base.clone(); + for _ in 0..1 + r.below(24) { + let at = r.below(d.len()); + // header bytes at their extremes, lengths that run past the packet, lost sync + d[at] = [0x00, 0xFF, 0x47, 0x01, 0x80, 0xBA, r.next() as u8][r.below(7)]; + } + match r.below(4) { + 0 => d.truncate(r.below(d.len())), + // a run cut out of the middle: the packet grid shifts + 1 => { + let at = r.below(d.len()); + d.drain(at..(at + r.below(300)).min(d.len())); + } + _ => {} + } + open_and_read_all(&d); + } + } +} + +/// Program-specific information with every length field wrong. +#[test] +fn damaged_psi_sections_never_panic() { + let mut r = Rng(0x0F0F_1234_5555_AAAA); + for _ in 0..3000 { + let mut mux = TsMux::new(false); + // sections the muxer signs with a valid CRC, so the parsers see the damage + let mut pat = vec![0x00, 0xB0, 13, 0, 1, 0xC1, 0, 0, 0, 1, 0xE1, 0x00]; + let mut pmt = vec![0x02, 0xB0, 0, 0, 1, 0xC1, 0, 0, 0xE1, 0x00, 0xF0, 0]; + for _ in 0..r.below(6) { + pmt.extend([TYPES[r.below(TYPES.len())], 0xE2, r.next() as u8, 0xF0 | r.below(16) as u8, r.next() as u8]); + pmt.extend(soup(&mut r, 12)); + } + let len = pmt.len() - 3 + 4; + pmt[1] = 0xB0 | (len >> 8) as u8; + pmt[2] = len as u8; + for sec in [&mut pat, &mut pmt] { + for _ in 0..r.below(3) { + let at = r.below(sec.len()); + sec[at] = [0x00, 0xFF, 0x0F, 0xF0, r.next() as u8][r.below(5)]; + } + } + mux.section(0, &pat); + mux.section(0x100, &pmt); + for i in 0..8u16 { + mux.pes(0x200 + i, &pes(0xE0, Some(0), None, &soup(&mut r, 200), false)); + } + // enough packets for the sniffer + open_and_read_all(&mux.out); + } +} + +#[test] +fn frame_header_helpers_never_panic_on_any_bytes() { + let mut r = Rng(0x5EED_5EED_5EED_5EED); + let codecs = [Codec::MpegAudio, Codec::AacAdts, Codec::AacLatm, Codec::Ac3, Codec::Eac3, Codec::H264, Codec::LpcmDvd]; + for _ in 0..20_000 { + let b = soup(&mut r, 24); + for cut in 0..=b.len() { + let b = &b[..cut]; + for c in &codecs { + if let Some(n) = frame_bytes(c, b) { + assert!(n > 0, "{c:?}: an empty frame would never advance"); + } + let _ = frame_info(c, b); + } + let _ = (sei_has_recovery_point(b), pes::parse(b), sniff(b)); + let _ = ts::codec_of(b.first().copied().unwrap_or(6), b, cut % 2 == 0); + } + } + // every MPEG audio, ADTS and AC-3 header value in its first four bytes + for h in 0..=0xFFFFu32 { + for sync in [[0xFFu8, 0xE0], [0x0B, 0x77]] { + let b = [sync[0], sync[1] | (h >> 12) as u8, (h >> 4) as u8, (h << 4) as u8, h as u8, (h >> 8) as u8, 0xFF, 0x00]; + for c in &codecs[..5] { + let _ = (frame_bytes(c, &b), frame_info(c, &b)); + } + } + } +} + +/// A pack header is looked for behind at most 64 zero bytes. +#[test] +fn a_pack_header_behind_too_many_zero_bytes_is_not_sniffed() { + let pack = [0u8, 0, 1, 0xBA, 0x44, 0, 4, 0, 4, 1, 1, 0x89, 0xC3, 0xF8]; + let behind = |zeros: usize| [vec![0u8; zeros], pack.to_vec()].concat(); + assert_eq!(sniff(&behind(0)), Some(Format::Ps { mpeg1: false })); + assert_eq!(sniff(&behind(62)), Some(Format::Ps { mpeg1: false })); + assert_eq!(sniff(&behind(63)), None); + assert_eq!(sniff(&behind(5000)), None); + assert!(matches!(open(&behind(5000)), Err(Error::NotMpeg))); +} diff --git a/crates/media/src/mpegts/mod.rs b/crates/media/src/mpegts/mod.rs new file mode 100644 index 000000000..a0a62efa5 --- /dev/null +++ b/crates/media/src/mpegts/mod.rs @@ -0,0 +1,506 @@ +//! Clean-room MPEG-2 Systems demuxer (ITU-T H.222.0 | ISO/IEC 13818-1). +//! +//! - **Transport Stream**: 188-byte packets, 192-byte BDAV / AVCHD packets (`.m2ts`, `.mts`: +//! a 4-byte arrival timestamp before each packet) and 204-byte packets (Reed-Solomon parity). +//! PAT / PMT (sections reassembled across packets, CRC checked), PES reassembly, PCR, PTS/DTS +//! (33-bit wrap-around unwrapped), discontinuity indicators. +//! - **Program Stream** (`.mpg`, `.vob`, `.mod`, `.tod`): MPEG-2 and ISO/IEC 11172-1 (MPEG-1) +//! packs, system headers, program stream maps, DVD private stream 1 sub-streams (AC-3, DTS, +//! LPCM). +//! - **Elementary streams** are split into access units on open — coded frames for MPEG-1/2 +//! video (picture start codes, field pairs), H.264 and HEVC (access unit delimiters / first +//! slice of a picture), audio frames for MPEG audio, ADTS / LATM AAC, AC-3 and E-AC-3, PES +//! packets for LPCM — each with its PTS/DTS (a PES timestamp belongs to the first access unit +//! that starts in the packet), random-access flag and, for MPEG video, picture type, temporal +//! 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. +//! +//! The module does no decoding. No dependencies beyond `std`, no `unsafe`, builds for +//! `wasm32-unknown-unknown`. +//! +//! From FilmCraft's `filmcraft-mpegts` (storytold/filmcraft@4bec22b). Public items keep their names. +//! `ByteSource` is the crate's one source trait. + +#![warn(missing_docs)] + +mod es; +pub use es::{FrameInfo, frame_bytes, frame_info, sei_has_recovery_point}; +mod pes; +mod ps; +mod ts; + +use std::fmt; +use std::io; + +pub use crate::source::{ByteSource, ReadSeekSource}; + +/// Errors from reading a transport or program stream. +#[non_exhaustive] +#[derive(Debug)] +pub enum Error { + /// Neither a transport stream nor a program stream. + NotMpeg, + /// Reading the source failed. + Io(io::Error), + /// Structurally invalid data. + Invalid(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::NotMpeg => write!(f, "not an MPEG transport or program stream"), + Error::Io(e) => write!(f, "I/O: {e}"), + Error::Invalid(s) => write!(f, "invalid stream: {s}"), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Io(e) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: io::Error) -> Self { + Error::Io(e) + } +} + +/// Result alias for this module. +pub type Result = std::result::Result; + +/// Read as much as is available at `offset` (up to `buf.len()`); returns the count. +pub(crate) fn read_some(src: &S, offset: u64, buf: &mut [u8]) -> io::Result { + let len = src.len(); + if offset >= len { + return Ok(0); + } + let n = ((len - offset) as usize).min(buf.len()); + src.read_at(offset, &mut buf[..n])?; + Ok(n) +} + +/// The container layout. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Format { + /// Transport stream with `packet_size`-byte packets whose 0x47 sync byte is at `sync_offset` + /// (4 for 192-byte BDAV packets). + Ts { + /// 188, 192 or 204. + packet_size: usize, + /// Offset of the sync byte in a packet. + sync_offset: usize, + }, + /// Program stream (`mpeg1`: ISO/IEC 11172-1 packs). + Ps { + /// ISO/IEC 11172-1 packs. + mpeg1: bool, + }, +} + +impl Format { + /// A display name: `"MPEG-2 TS"`, `"MPEG-2 PS"`… + pub fn name(&self) -> &'static str { + match self { + Format::Ts { packet_size: 192, .. } => "MPEG-2 TS (BDAV/AVCHD)", + Format::Ts { .. } => "MPEG-2 TS", + Format::Ps { mpeg1: true } => "MPEG-1 System", + Format::Ps { mpeg1: false } => "MPEG-2 PS", + } + } +} + +/// Recognise a transport stream (five consecutive sync bytes at one of the packet sizes, within +/// the first packets) or a program stream (a pack header). +pub fn sniff(head: &[u8]) -> Option { + for (size, off) in [(188usize, 0usize), (192, 4), (204, 0)] { + for start in 0..size.min(head.len()) { + let ok = (0..5).all(|k| head.get(start + off + k * size) == Some(&0x47)); + if ok { + return Some(Format::Ts { packet_size: size, sync_offset: off }); + } + } + } + // a pack header, possibly after a few zero bytes + let z = head.iter().take(64).take_while(|&&b| b == 0).count(); + let p = z.saturating_sub(2); + if head.len() >= p + 5 && head[p..p + 4] == [0, 0, 1, 0xBA] { + return Some(Format::Ps { mpeg1: head[p + 4] >> 6 != 1 }); + } + None +} + +/// What kind of media a stream carries. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// Pictures. + Video, + /// Sound. + Audio, + /// Subtitles (PGS, DVB, teletext). + Subtitle, + /// Anything else. + Other, +} + +/// What an elementary stream carries. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Codec { + /// MPEG-1 video (ISO/IEC 11172-2). + Mpeg1Video, + /// MPEG-2 video (H.262). + Mpeg2Video, + /// H.264 / AVC, Annex B. + H264, + /// H.265 / HEVC, Annex B. + Hevc, + /// MPEG-1/2 audio (layers I-III; the layer is in each frame header). + MpegAudio, + /// AAC in ADTS frames. + AacAdts, + /// AAC in LATM/LOAS frames. + AacLatm, + /// AC-3. + Ac3, + /// E-AC-3. + Eac3, + /// DTS. + Dts, + /// Dolby TrueHD. + TrueHd, + /// Blu-ray / AVCHD LPCM (a 4-byte header per PES packet, big-endian samples). + LpcmBluray, + /// DVD LPCM (program stream private stream 1; format in [`Stream::lpcm`]). + LpcmDvd, + /// Subtitles; the text names the format. + Subtitle(&'static str), + /// Anything else: the stream type. + Unknown(u8), +} + +impl Codec { + /// A display name: `"H.264"`, `"AAC (ADTS)"`, `"stream type 0x42"`. + pub fn name(&self) -> String { + match self { + Codec::Mpeg1Video => "MPEG-1 Video".into(), + Codec::Mpeg2Video => "MPEG-2 Video".into(), + Codec::H264 => "H.264".into(), + Codec::Hevc => "HEVC".into(), + Codec::MpegAudio => "MPEG Audio".into(), + Codec::AacAdts => "AAC (ADTS)".into(), + Codec::AacLatm => "AAC (LATM)".into(), + Codec::Ac3 => "AC-3".into(), + Codec::Eac3 => "E-AC-3".into(), + Codec::Dts => "DTS".into(), + Codec::TrueHd => "Dolby TrueHD".into(), + Codec::LpcmBluray => "LPCM (Blu-ray)".into(), + Codec::LpcmDvd => "LPCM (DVD)".into(), + Codec::Subtitle(s) => (*s).into(), + Codec::Unknown(t) => format!("stream type 0x{t:02x}"), + } + } + /// The crate-wide identifier. MPEG-1 video reports [`CodecId::Mpeg2Video`] (an MPEG-2 + /// decoder decodes it), MPEG audio reports [`CodecId::Mp2`] whatever its layer (the layer is + /// in each frame header: [`frame_info`]'s `variant`), and DTS, TrueHD and subtitles have no + /// identifier. + /// + /// [`CodecId::Mpeg2Video`]: crate::CodecId::Mpeg2Video + /// [`CodecId::Mp2`]: crate::CodecId::Mp2 + pub fn codec_id(&self) -> crate::CodecId { + use crate::CodecId as Id; + match self { + Codec::Mpeg1Video | Codec::Mpeg2Video => Id::Mpeg2Video, + Codec::H264 => Id::H264, + Codec::Hevc => Id::Hevc, + Codec::MpegAudio => Id::Mp2, + Codec::AacAdts | Codec::AacLatm => Id::Aac, + Codec::Ac3 => Id::Ac3, + Codec::Eac3 => Id::Eac3, + Codec::LpcmBluray | Codec::LpcmDvd => Id::Pcm, + Codec::Dts | Codec::TrueHd | Codec::Subtitle(_) | Codec::Unknown(_) => Id::Unknown, + } + } + + /// The kind of media. + pub fn kind(&self) -> Kind { + match self { + Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::H264 | Codec::Hevc => Kind::Video, + Codec::MpegAudio + | Codec::AacAdts + | Codec::AacLatm + | Codec::Ac3 + | Codec::Eac3 + | Codec::Dts + | Codec::TrueHd + | Codec::LpcmBluray + | Codec::LpcmDvd => Kind::Audio, + Codec::Subtitle(_) => Kind::Subtitle, + Codec::Unknown(_) => Kind::Other, + } + } +} + +/// MPEG-1/2 video picture properties of an access unit (its first picture). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PictureInfo { + /// 1 I, 2 P, 3 B, 4 D. + pub coding_type: u8, + /// `temporal_reference`: display order within the GOP. + pub temporal_reference: u16, + /// 1 top field, 2 bottom field, 3 frame (two field pictures form one unit). + pub structure: u8, + /// `top_field_first` of the picture coding extension. + pub top_field_first: bool, + /// `repeat_first_field` (pulldown). + pub repeat_first_field: bool, + /// `progressive_frame`. + pub progressive_frame: bool, + /// A sequence header precedes the picture in this unit. + pub sequence_header: bool, + /// A GOP header precedes the picture (and its flags). + pub gop: bool, + /// `closed_gop` of that GOP header. + pub closed_gop: bool, + /// `broken_link` of that GOP header. + pub broken_link: bool, +} + +/// One access unit (a coded frame, an audio frame, or an LPCM PES packet). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Unit { + /// Presentation / decoding time stamps, 90 kHz, 33-bit wrap-around unwrapped. + pub pts: Option, + /// See `pts`. + pub dts: Option, + /// Decoding can start here (I / IDR / IRAP pictures; every audio frame). + pub key: bool, + /// No other unit depends on it (B pictures of MPEG-1/2 video, non-reference H.264/HEVC). + pub disposable: bool, + /// Bytes of elementary stream. + pub size: u32, + /// TS: byte offset of the packet holding the first byte; PS: byte offset of its PES packet. + pub(crate) pos: u64, + /// Offset of the first byte within that packet's elementary-stream payload. + pub(crate) offset: u32, + /// MPEG-1/2 video: the picture's properties. + pub picture: Option, +} + +/// DVD LPCM format (from the private stream 1 header). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LpcmFormat { + /// Samples per second. + pub sample_rate: u32, + /// Channel count. + pub channels: u32, + /// Bits per sample (16, 20 or 24). + pub bits: u32, +} + +/// Where a stream's PES packets come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StreamId { + /// Transport stream PID. + Pid(u16), + /// Program stream stream_id, and the private stream 1 sub-stream id. + Ps { + /// PES stream_id. + stream_id: u8, + /// Private stream 1 sub-stream id. + sub_id: Option, + }, +} + +/// One elementary stream and its access-unit table. +#[derive(Clone, Debug)] +pub struct Stream { + /// Where its PES packets come from. + pub id: StreamId, + /// PMT stream_type (TS), or the equivalent for program streams. + pub stream_type: u8, + /// What it carries. + pub codec: Codec, + /// ISO 639 language code from the PMT. + pub language: Option, + /// The access units, in stream order. + pub units: Vec, + /// DVD LPCM: the sample format. + pub lpcm: Option, + /// PES packets seen. + pub pes_packets: u64, + /// Bytes of payload ignored because the stream could not be split (e.g. before the first + /// frame header). + pub skipped_bytes: u64, +} + +impl Stream { + /// The kind of media. + pub fn kind(&self) -> Kind { + self.codec.kind() + } + /// What a decoder needs for this stream, in the container-neutral form the codec crates take: + /// the codec ([`Codec::codec_id`]) and, for DVD LPCM, the sample format (big-endian). These + /// streams carry their configuration in band, so `extradata` is empty: H.264 and HEVC are + /// Annex B with their parameter sets, AAC is ADTS or LATM frames, and a Blu-ray LPCM packet + /// starts with its own 4-byte format header. + pub fn codec_params(&self) -> crate::CodecParams { + let mut p = crate::CodecParams::new(self.codec.codec_id()); + if let Some(f) = self.lpcm { + let n = |v: u32| u16::try_from(v).unwrap_or(0); + p = p.with_sample_rate(f.sample_rate).with_channels(n(f.channels)).with_pcm(crate::PcmFormat::int(n(f.bits), true, true)); + } + p + } + /// First and last presentation timestamps (90 kHz) of the stream's units. + pub fn pts_range(&self) -> Option<(i64, i64)> { + let mut it = self.units.iter().filter_map(|u| u.pts); + let first = it.next()?; + Some(it.fold((first, first), |(a, b), p| (a.min(p), b.max(p)))) + } +} + +/// A demuxed file: its streams with their access-unit tables. +#[derive(Clone, Debug)] +pub struct File { + /// The container layout. + pub format: Format, + /// The elementary streams (TS: in PMT order). + pub streams: Vec, + /// Program number of the program the streams belong to (TS). + pub program: Option, + /// Smallest and largest PCR (27 MHz, unwrapped) or SCR. For a transport stream this is the + /// clock of the PMT's PCR_PID; without a PMT, of the first PID seen carrying a PCR. `None` if + /// that PID never carries one. + pub pcr_range: Option<(i64, i64)>, + /// Problems found while scanning (lost sync, CRC errors, continuity errors…). + pub warnings: Vec, +} + +/// Largest unit `read_unit` returns. The biggest real units are intra pictures (a few MB at +/// 4K/8K broadcast rates); a stream without PES timestamps can make one unit of a whole PID. +pub const MAX_UNIT_BYTES: u32 = 128 << 20; + +/// Bytes reserved up front by `read_unit`; the buffer grows beyond this only as data is read. +const UNIT_PREALLOC: usize = 1 << 20; + +impl File { + /// The first stream of `kind` whose codec satisfies `f`. + pub fn find(&self, kind: Kind, f: impl Fn(&Codec) -> bool) -> Option { + self.streams.iter().position(|s| s.kind() == kind && !s.units.is_empty() && f(&s.codec)) + } + + /// Read access unit `i` of stream `s`. + pub fn read_unit(&self, src: &S, s: usize, i: usize) -> Result> { + let st = self.streams.get(s).ok_or_else(|| Error::Invalid("no such stream".into()))?; + let u = st.units.get(i).ok_or_else(|| Error::Invalid("no such unit".into()))?; + if u.size > MAX_UNIT_BYTES { + return Err(Error::Invalid(format!("unit {i} is {} bytes (limit {MAX_UNIT_BYTES})", u.size))); + } + // grow as bytes arrive: a damaged table must not reserve more than the file can supply + let mut out = Vec::with_capacity((u.size as usize).min(UNIT_PREALLOC)); + match self.format { + Format::Ts { packet_size, sync_offset } => ts::read(src, packet_size, sync_offset, st, u, &mut out)?, + Format::Ps { .. } => ps::read(src, st, u, &mut out)?, + } + if out.len() < u.size as usize { + return Err(Error::Invalid(format!("unit {i} truncated ({} of {} bytes)", out.len(), u.size))); + } + Ok(out) + } +} + +/// Scan a transport or program stream and index its access units. +pub fn open(src: &S) -> Result { + let mut head = vec![0u8; 64 * 1024]; + let n = read_some(src, 0, &mut head)?; + head.truncate(n); + match sniff(&head).ok_or(Error::NotMpeg)? { + Format::Ts { packet_size, sync_offset } => ts::scan(src, packet_size, sync_offset), + Format::Ps { mpeg1 } => ps::scan(src, mpeg1), + } +} + +/// Unwraps the 33-bit PTS/DTS of ONE stream into an i64 timeline. Values are absolute, not +/// relative to the first one: the first timestamp comes back unchanged, every later wrap adds +/// 2^33, and a timestamp from just before a wrap that arrives after it (B pictures, slightly +/// out-of-order audio) is mapped below the wrap (negative if the stream started after it). +/// Keep one `Unwrap` per clock: the streams of a program share one. +#[derive(Default, Clone, Copy)] +pub(crate) struct Unwrap { + last: Option, + base: i64, +} + +impl Unwrap { + const WRAP: i64 = 1 << 33; + /// 1 minute at 90 kHz: how close to the wrap point a pre-wrap timestamp must be. + const NEAR_WRAP: i64 = 90_000 * 60; + /// Start a stream-local unwrapper at a value already aligned to its program's clock epoch. + pub fn aligned(raw: i64, value: i64) -> Self { + Self { last: Some(value), base: value.saturating_sub(raw) } + } + /// Advance a program-level epoch anchor to a stream that has progressed farther. + pub fn observe(&mut self, stream: Self) { + if stream.last > self.last { + *self = stream; + } + } + pub fn unwrap(&mut self, raw: i64) -> i64 { + let mut v = raw.saturating_add(self.base); + if let Some(l) = self.last { + if v < l.saturating_sub(Self::WRAP / 2) { + self.base = self.base.saturating_add(Self::WRAP); + v = v.saturating_add(Self::WRAP); + } else if v > l.saturating_add(Self::WRAP / 2) && raw >= Self::WRAP - Self::NEAR_WRAP && l < self.base.saturating_add(Self::NEAR_WRAP) { + // a timestamp from before the wrap: it does not move the timeline. Before the + // first wrap and after later wraps this applies only right at the boundary; any + // other forward jump is a new time base (spliced capture) and is followed. + return v.saturating_sub(Self::WRAP); + } + } + self.last = Some(v); + v + } +} + +/// Unwraps the 27 MHz clock reference (PCR/SCR: 33-bit base × 300 + 9-bit extension) of one +/// clock into an i64 timeline and keeps the smallest and largest value seen. +#[derive(Default, Clone, Copy)] +pub(crate) struct ClockRange { + last: Option, + base: i64, + range: Option<(i64, i64)>, +} + +impl ClockRange { + /// 33-bit base × 300 wraps at 2^33·300. + const WRAP: i64 = (1 << 33) * 300; + /// The (min, max) of the unwrapped values so far. + pub fn range(&self) -> Option<(i64, i64)> { + self.range + } + pub fn push(&mut self, raw: i64) { + let mut v = raw.saturating_add(self.base); + if let Some(l) = self.last + && v < l.saturating_sub(Self::WRAP / 2) + { + self.base = self.base.saturating_add(Self::WRAP); + v = v.saturating_add(Self::WRAP); + } + self.last = Some(v); + self.range = Some(self.range.map_or((v, v), |(a, b)| (a.min(v), b.max(v)))); + } +} + +#[cfg(test)] +mod hostile_tests; +#[cfg(test)] +mod tests; +#[cfg(test)] +mod work_tests; diff --git a/crates/media/src/mpegts/pes.rs b/crates/media/src/mpegts/pes.rs new file mode 100644 index 000000000..06c7a2abf --- /dev/null +++ b/crates/media/src/mpegts/pes.rs @@ -0,0 +1,126 @@ +//! PES packet headers (H.222.0 §2.4.3.6; ISO/IEC 11172-1 §2.4.3.3 for MPEG-1 packets). + +/// A parsed PES header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PesHeader { + /// Bytes from the packet start code to the first payload byte. + pub header_len: usize, + /// Raw 33-bit timestamps. + pub pts: Option, + pub dts: Option, +} + +/// Stream ids whose packets have no optional header (§2.4.3.7). +pub(crate) fn plain_stream(id: u8) -> bool { + matches!(id, 0xBC | 0xBE | 0xBF | 0xF0 | 0xF1 | 0xF2 | 0xF8 | 0xFF) +} + +pub(crate) fn timestamp(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 +} + +/// Parse a PES header at the start of `b` (which begins with `00 00 01 stream_id`). `None` when +/// `b` is too short to hold the whole header or it is malformed. +pub(crate) fn parse(b: &[u8]) -> Option { + if b.len() < 6 || b[0] != 0 || b[1] != 0 || b[2] != 1 { + return None; + } + if plain_stream(b[3]) { + return Some(PesHeader { header_len: 6, pts: None, dts: None }); + } + if b.len() >= 9 && b[6] & 0xC0 == 0x80 { + // ISO/IEC 13818-1 syntax + let flags = b[7]; + let header_len = 9 + b[8] as usize; + if b.len() < header_len { + return None; + } + let (mut pts, mut dts) = (None, None); + if flags & 0x80 != 0 && header_len >= 14 { + pts = Some(timestamp(&b[9..14])); + if flags & 0x40 != 0 && header_len >= 19 { + dts = Some(timestamp(&b[14..19])); + } + } + return Some(PesHeader { header_len, pts, dts }); + } + // ISO/IEC 11172-1 syntax: stuffing, STD buffer, timestamps + let mut p = 6; + let mut stuffing = 0; + while b.get(p) == Some(&0xFF) { + p += 1; + stuffing += 1; + if stuffing > 16 { + return None; + } + } + let c = *b.get(p)?; + if c >> 6 == 1 { + p += 2; + } + let c = *b.get(p)?; + let (mut pts, mut dts) = (None, None); + match c >> 4 { + 2 => { + pts = Some(timestamp(b.get(p..p + 5)?)); + p += 5; + } + 3 => { + pts = Some(timestamp(b.get(p..p + 5)?)); + dts = Some(timestamp(b.get(p + 5..p + 10)?)); + p += 10; + } + 0 if c == 0x0F => p += 1, + _ => return None, + } + Some(PesHeader { header_len: p, pts, dts }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ts_bytes(prefix: u8, v: i64) -> [u8; 5] { + [ + (prefix << 4) | (((v >> 30) & 7) as u8) << 1 | 1, + (v >> 22) as u8, + (((v >> 15) & 0x7F) as u8) << 1 | 1, + (v >> 7) as u8, + ((v & 0x7F) as u8) << 1 | 1, + ] + } + + #[test] + fn mpeg2_and_mpeg1_headers() { + let pts = 0x1_2345_6789i64; + let dts = 0x0_8765_4321i64; + let mut b = vec![0, 0, 1, 0xE0, 0, 0, 0x80, 0xC0, 10]; + b.extend(ts_bytes(3, pts)); + b.extend(ts_bytes(1, dts)); + b.push(0xAA); + let h = parse(&b).unwrap(); + assert_eq!((h.header_len, h.pts, h.dts), (19, Some(pts), Some(dts))); + // MPEG-1: stuffing, STD buffer, PTS only + let mut b = vec![0, 0, 1, 0xC0, 0, 20, 0xFF, 0xFF, 0x40, 0x20]; + b.extend(ts_bytes(2, 90_000)); + let h = parse(&b).unwrap(); + assert_eq!((h.header_len, h.pts, h.dts), (15, Some(90_000), None)); + assert_eq!(parse(&[0, 0, 1, 0xC0, 0, 1, 0x0F]).unwrap().header_len, 7); + assert_eq!(parse(&[0, 0, 1, 0xBE, 0, 4]).unwrap().header_len, 6); + assert!(parse(&[0, 0, 1, 0xE0, 0, 0, 0x80, 0x80]).is_none()); + } + + /// MPEG-1 packets: at most 16 stuffing bytes before the timestamps. + #[test] + fn mpeg1_stuffing_past_the_limit_is_refused() { + let with = |stuffing: usize| { + let mut b = vec![0, 0, 1, 0xC0, 0, 40]; + b.extend(std::iter::repeat_n(0xFF, stuffing)); + b.extend(ts_bytes(2, 90_000)); + parse(&b) + }; + assert_eq!(with(16).map(|h| (h.header_len, h.pts)), Some((6 + 16 + 5, Some(90_000)))); + assert_eq!(with(17), None); + assert_eq!(with(5000), None); + } +} diff --git a/crates/media/src/mpegts/ps.rs b/crates/media/src/mpegts/ps.rs new file mode 100644 index 000000000..71baaba20 --- /dev/null +++ b/crates/media/src/mpegts/ps.rs @@ -0,0 +1,389 @@ +//! Program streams (H.222.0 §2.5; ISO/IEC 11172-1 §2.4.3): packs, system headers, the program +//! stream map, PES packets, and the DVD sub-streams of private stream 1. + +use std::collections::HashMap; + +use super::es::Splitter; +use super::pes; +use super::{ByteSource, ClockRange, Codec, Error, File, Format, LpcmFormat, Result, Stream, StreamId, Unit, Unwrap, read_some}; + +/// Sequential reader with a refillable window. +struct Win<'a, S: ByteSource + ?Sized> { + src: &'a S, + buf: Vec, + start: u64, + /// Bytes zero-filled by window refills (tests count them). + #[cfg(test)] + zero_filled: usize, +} + +impl<'a, S: ByteSource + ?Sized> Win<'a, S> { + fn new(src: &'a S) -> Self { + Self { + src, + buf: Vec::new(), + start: 0, + #[cfg(test)] + zero_filled: 0, + } + } + /// The bytes [pos, pos + n) (fewer at the end of the file). + fn get(&mut self, pos: u64, n: usize) -> Result<&[u8]> { + let have = pos >= self.start && pos + n as u64 <= self.start + self.buf.len() as u64; + if !have { + // never more than the file still holds past `pos`: `read_some` would not fill it, and + // zeroing a megabyte for every packet near the end of the file is wasted work + let remaining = self.src.len().saturating_sub(pos); + let want = (n.max(1 << 20) as u64).min(remaining) as usize; + #[cfg(test)] + { + self.zero_filled += want.saturating_sub(self.buf.len()); + } + self.buf.resize(want, 0); + let got = read_some(self.src, pos, &mut self.buf)?; + self.buf.truncate(got); + self.start = pos; + } + let i = (pos - self.start) as usize; + let end = (i + n).min(self.buf.len()); + Ok(&self.buf[i.min(end)..end]) + } +} + +/// How many bytes of a private stream 1 payload precede the elementary stream, by sub-stream id +/// (DVD-Video: AC-3 / DTS 4, LPCM 7, sub-pictures 1). +fn sub_header(sub: u8) -> usize { + match sub { + 0x80..=0x8F => 4, + 0xA0..=0xAF => 7, + _ => 1, + } +} + +fn codec_for(stream_id: u8, sub: Option, psm: &HashMap, mpeg1: bool) -> Codec { + if let Some(&t) = psm.get(&stream_id) { + let c = super::ts::codec_of(t, &[], false); + if !matches!(c, Codec::Unknown(_)) { + return c; + } + } + match (stream_id, sub) { + (0xE0..=0xEF, _) => { + if mpeg1 { + Codec::Mpeg1Video + } else { + Codec::Mpeg2Video + } + } + (0xC0..=0xDF, _) => Codec::MpegAudio, + (0xBD, Some(0x80..=0x87)) => Codec::Ac3, + (0xBD, Some(0x88..=0x8F)) => Codec::Dts, + (0xBD, Some(0xA0..=0xAF)) => Codec::LpcmDvd, + (0xBD, Some(0x20..=0x3F)) => Codec::Subtitle("DVD sub-pictures"), + (id, _) => Codec::Unknown(id), + } +} + +/// DVD LPCM header bytes after the sub-stream id (and the frame count / pointer). +fn lpcm_format(h: &[u8]) -> Option { + let b = *h.get(4)?; + let bits = [16, 20, 24, 0][(b >> 6) as usize]; + let sample_rate = [48_000, 96_000, 44_100, 32_000][((b >> 4) & 3) as usize]; + let channels = (b & 7) as u32 + 1; + (bits > 0).then_some(LpcmFormat { sample_rate, channels, bits }) +} + +struct EsState { + stream: Stream, + split: Splitter, + /// Progression is unwrapped per stream after its first timestamp is aligned to the program. + unwrap: Option, +} + +fn unwrap_time(epoch: &mut Unwrap, stream: &mut Option, raw: i64) -> i64 { + if let Some(unwrap) = stream { + let value = unwrap.unwrap(raw); + epoch.observe(*unwrap); + value + } else { + let value = epoch.unwrap(raw); + *stream = Some(Unwrap::aligned(raw, value)); + value + } +} + +/// Length of the packet (pack header, system header, PES…) starting at `b` (which begins with a +/// start code), `None` if it is not one. +fn packet_len(b: &[u8]) -> Option { + if b.len() < 6 || b[0] != 0 || b[1] != 0 || b[2] != 1 { + return None; + } + match b[3] { + 0xBA => { + if b[4] >> 6 == 1 { + let stuff = (*b.get(13)? & 7) as usize; + Some(14 + stuff) + } else if b[4] >> 4 == 2 { + // MPEG-1 pack header: start code, 5-byte SCR, 3-byte mux rate. A file cut inside + // it is not a pack header yet (`scan` reads the SCR from the first 9 bytes). + b.get(..12)?; + Some(12) + } else { + None + } + } + 0xB9 => Some(4), + 0xBB..=0xFF => Some(6 + u16::from_be_bytes([b[4], b[5]]) as usize), + _ => None, + } +} + +pub(crate) fn scan(src: &S, mpeg1: bool) -> Result { + let len = src.len(); + let mut win = Win::new(src); + let mut pos = 0u64; + let mut streams: HashMap<(u8, Option), EsState> = HashMap::new(); + let mut order = Vec::new(); + let mut psm: HashMap = HashMap::new(); + let mut scr = ClockRange::default(); + // Program-stream elementary streams share one clock epoch. The anchor follows the farthest + // progressed stream so a stream first seen after a wrap joins that epoch, while each stream + // keeps independent progression so its reordered timestamps cannot move another stream. + let mut timestamp_epoch = Unwrap::default(); + let mut resyncs = 0u64; + while pos + 4 <= len { + let head = win.get(pos, 32)?; + let Some(plen) = packet_len(head) else { + // resynchronise on the next pack header or PES start code + resyncs += 1; + let mut p = pos + 1; + let found = loop { + let w = win.get(p, 1 << 16)?; + if w.len() < 4 { + break None; + } + if let Some(i) = w.windows(4).position(|x| x[0] == 0 && x[1] == 0 && x[2] == 1 && (x[3] == 0xBA || (0xBD..=0xEF).contains(&x[3]))) { + break Some(p + i as u64); + } + p += (w.len() - 3) as u64; + }; + match found { + Some(f) => { + pos = f; + continue; + } + None => break, + } + }; + let id = head[3]; + if id == 0xBA { + // SCR (MPEG-2: 33 bits base, 9 bits extension; MPEG-1: 33 bits) + let v = if head[4] >> 6 == 1 { + let b = &head[4..10]; + let base = (((b[0] >> 3) & 7) as i64) << 30 + | ((b[0] & 3) as i64) << 28 + | (b[1] as i64) << 20 + | ((b[2] >> 3) as i64) << 15 + | ((b[2] & 3) as i64) << 13 + | (b[3] as i64) << 5 + | (b[4] >> 3) as i64; + let ext = (((b[4] & 3) as i64) << 7) | (b[5] >> 1) as i64; + base * 300 + ext + } else { + pes::timestamp(&head[4..9]) * 300 + }; + scr.push(v); + } else if id == 0xBC { + // program stream map: elementary stream id → stream_type + let body = win.get(pos, plen)?; + if body.len() >= 12 { + let info = u16::from_be_bytes([body[8], body[9]]) as usize; + let mut i = 10 + info; + if i + 2 <= body.len() { + let map_len = u16::from_be_bytes([body[i], body[i + 1]]) as usize; + i += 2; + let end = (i + map_len).min(body.len()); + while i + 4 <= end { + psm.insert(body[i + 1], body[i]); + i += 4 + u16::from_be_bytes([body[i + 2], body[i + 3]]) as usize; + } + } + } + } else if id == 0xBD || (0xC0..=0xEF).contains(&id) || id == 0xFD { + let pkt = win.get(pos, plen)?; + if pkt.len() < plen { + break; // truncated + } + if let Some(h) = pes::parse(pkt) { + let payload = &pkt[h.header_len.min(plen)..]; + let (sub, skip) = if id == 0xBD { + match payload.first() { + Some(&s) => (Some(s), sub_header(s).min(payload.len())), + None => (None, 0), + } + } else { + (None, 0) + }; + let key = (id, sub); + let e = streams.entry(key).or_insert_with(|| { + let codec = codec_for(id, sub, &psm, mpeg1); + let lpcm = if codec == Codec::LpcmDvd { lpcm_format(&payload[1.min(payload.len())..]) } else { None }; + order.push(key); + let stream = Stream { + id: StreamId::Ps { stream_id: id, sub_id: sub }, + stream_type: psm.get(&id).copied().unwrap_or(0), + codec: codec.clone(), + language: None, + units: Vec::new(), + lpcm, + pes_packets: 0, + skipped_bytes: 0, + }; + EsState { stream, split: Splitter::new(&codec), unwrap: None } + }); + e.stream.pes_packets += 1; + let pts = h.pts.map(|t| unwrap_time(&mut timestamp_epoch, &mut e.unwrap, t)); + let dts = h.dts.map(|t| unwrap_time(&mut timestamp_epoch, &mut e.unwrap, t)); + e.split.pes_start(pts, dts); + e.split.feed(pos, &payload[skip..]); + } + } + pos += plen as u64; + } + let mut warnings = Vec::new(); + if resyncs > 0 { + warnings.push(format!("resynchronised {resyncs} time(s)")); + } + let mut out = Vec::new(); + for key in order { + let Some(mut e) = streams.remove(&key) else { continue }; + e.split.finish(); + e.stream.units = std::mem::take(&mut e.split.units); + e.stream.skipped_bytes = e.split.skipped; + out.push(e.stream); + } + if out.is_empty() { + return Err(Error::Invalid("program stream without elementary streams".into())); + } + Ok(File { format: Format::Ps { mpeg1 }, streams: out, program: None, pcr_range: scr.range(), warnings }) +} + +/// Collect unit `u` of stream `st`, starting at the PES packet at `u.pos`. +pub(crate) fn read(src: &S, st: &Stream, u: &Unit, out: &mut Vec) -> Result<()> { + let StreamId::Ps { stream_id, sub_id } = st.id else { return Err(Error::Invalid("not a PS stream".into())) }; + let need = u.size as usize; + let mut skip = u.offset as usize; + let mut pos = u.pos; + let len = src.len(); + let mut win = Win::new(src); + while out.len() < need && pos + 4 <= len { + let head = win.get(pos, 32)?; + let Some(plen) = packet_len(head) else { + // corrupt: stop at what we have + return Ok(()); + }; + if head[3] == stream_id { + let pkt = win.get(pos, plen)?; + if let Some(h) = pes::parse(pkt) { + let payload = &pkt[h.header_len.min(pkt.len())..]; + let matches = stream_id != 0xBD || payload.first().copied() == sub_id; + if matches { + let s0 = if stream_id == 0xBD { sub_id.map_or(0, sub_header).min(payload.len()) } else { 0 }; + let mut bytes = &payload[s0..]; + if skip > 0 { + let s = skip.min(bytes.len()); + skip -= s; + bytes = &bytes[s..]; + } + let take = bytes.len().min(need - out.len()); + out.extend_from_slice(&bytes[..take]); + } + } + } + pos += plen as u64; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The window refill before the zero-fill cap: always `max(n, 1 MiB)` bytes, counted when the + /// buffer has to grow. + struct OldWin<'a> { + src: &'a [u8], + buf: Vec, + start: u64, + zero_filled: usize, + } + + impl OldWin<'_> { + fn get(&mut self, pos: u64, n: usize) -> Vec { + let have = pos >= self.start && pos + n as u64 <= self.start + self.buf.len() as u64; + if !have { + let want = n.max(1 << 20); + self.zero_filled += want.saturating_sub(self.buf.len()); + self.buf.resize(want, 0); + let got = read_some(self.src, pos, &mut self.buf).unwrap(); + self.buf.truncate(got); + self.start = pos; + } + let i = (pos - self.start) as usize; + let end = (i + n).min(self.buf.len()); + self.buf[i.min(end)..end].to_vec() + } + } + + fn data(len: usize) -> Vec { + (0..len).map(|i| (i * 31 + i / 7) as u8).collect() + } + + #[test] + fn capped_window_returns_what_the_uncapped_window_returned() { + for len in [0usize, 1, 31, 32, 33, 1000, (1 << 20) - 1, 1 << 20, (1 << 20) + 5, (3 << 20) + 17] { + let d = data(len); + let mut new = Win::new(d.as_slice()); + let mut old = OldWin { src: &d, buf: Vec::new(), start: 0, zero_filled: 0 }; + let len64 = len as u64; + let mut positions = vec![ + 0, + 1, + 31, + 32, + 1 << 19, + 1 << 20, + (1 << 20) - 1, + (1 << 20) + 1, + 2 << 20, + len64.saturating_sub(40), + len64.saturating_sub(1), + len64, + len64 + 1, + len64 + 100, + ]; + positions.extend((0..10).map(|k| len64.saturating_sub(100) + k * 13)); + for &pos in &positions { + for n in [0usize, 1, 33, 1000, 65_541, 1 << 20, (1 << 20) + 1] { + assert_eq!(new.get(pos, n).unwrap(), old.get(pos, n).as_slice(), "len {len} pos {pos} n {n}"); + } + } + } + } + + #[test] + fn misses_near_the_end_zero_at_most_the_bytes_that_are_left() { + let len = (2 << 20) + 1000; + let d = data(len); + let mut new = Win::new(d.as_slice()); + let mut old = OldWin { src: &d, buf: Vec::new(), start: 0, zero_filled: 0 }; + // a PES packet whose length runs past the end of the file, asked for once per packet + let first = (2u64 << 20) as usize; + for k in 0..500 { + let pos = (first + k) as u64; + assert_eq!(new.get(pos, 2000).unwrap(), old.get(pos, 2000).as_slice()); + } + assert!(new.zero_filled <= 1000, "zeroed {} bytes, only 1000 are left in the file", new.zero_filled); + assert!(old.zero_filled > 499 * ((1 << 20) - 1000), "the reference zeroes about a megabyte per miss: {}", old.zero_filled); + } +} diff --git a/crates/media/src/mpegts/tests.rs b/crates/media/src/mpegts/tests.rs new file mode 100644 index 000000000..0215680ad --- /dev/null +++ b/crates/media/src/mpegts/tests.rs @@ -0,0 +1,1125 @@ +//! Synthetic transport and program streams: a small muxer writes known access units, the +//! demuxer must give them back exactly (bytes, timestamps, flags); truncation and mutation never +//! panic. + +use super::*; + +mod hostile; + +fn ts_bytes(prefix: u8, v: i64) -> [u8; 5] { + let v = v & ((1 << 33) - 1); + [ + (prefix << 4) | (((v >> 30) & 7) as u8) << 1 | 1, + (v >> 22) as u8, + (((v >> 15) & 0x7F) as u8) << 1 | 1, + (v >> 7) as u8, + ((v & 0x7F) as u8) << 1 | 1, + ] +} + +pub(super) fn pes(stream_id: u8, pts: Option, dts: Option, payload: &[u8], bounded: bool) -> Vec { + let mut h = Vec::new(); + match (pts, dts) { + (Some(p), Some(d)) => { + h.extend(ts_bytes(3, p)); + h.extend(ts_bytes(1, d)); + } + (Some(p), None) => h.extend(ts_bytes(2, p)), + _ => {} + } + let flags = match (pts, dts) { + (Some(_), Some(_)) => 0xC0, + (Some(_), None) => 0x80, + _ => 0, + }; + let len = if bounded { 3 + h.len() + payload.len() } else { 0 }; + let mut v = vec![0, 0, 1, stream_id, (len >> 8) as u8, len as u8, 0x80, flags, h.len() as u8]; + v.extend(h); + v.extend_from_slice(payload); + v +} + +fn ps_pack() -> [u8; 14] { + [0, 0, 1, 0xBA, 0x44, 0, 4, 0, 4, 1, 1, 0x89, 0xC3, 0xF8] +} + +/// A tiny TS muxer: PAT, PMT and PES packets cut into 188-byte packets (192 with `m2ts`). +pub(super) struct TsMux { + pub(super) out: Vec, + cc: std::collections::HashMap, + m2ts: bool, +} + +impl TsMux { + pub(super) fn new(m2ts: bool) -> Self { + Self { out: Vec::new(), cc: Default::default(), m2ts } + } + fn packet(&mut self, pid: u16, pusi: bool, payload: &[u8]) -> usize { + let cc = self.cc.entry(pid).or_insert(0); + let mut p = vec![0x47, (pusi as u8) << 6 | (pid >> 8) as u8, pid as u8]; + let n = payload.len().min(184); + if n < 184 { + // adaptation field stuffing + let al = 183 - n; + p.push(0x30 | *cc); + p.push(al as u8); + if al > 0 { + p.push(0); + p.extend(std::iter::repeat_n(0xFF, al - 1)); + } + } else { + p.push(0x10 | *cc); + } + *cc = (*cc + 1) & 15; + p.extend_from_slice(&payload[..n]); + assert_eq!(p.len(), 188); + if self.m2ts { + self.out.extend_from_slice(&[0, 0, 0, 0]); + } + self.out.extend(p); + n + } + pub(super) fn section(&mut self, pid: u16, body: &[u8]) { + let mut s = body.to_vec(); + let crc = super::ts::crc32_mpeg(&s); + s.extend(crc.to_be_bytes()); + let mut payload = vec![0]; + payload.extend(s); + self.packet(pid, true, &payload); + } + pub(super) fn psi(&mut self, streams: &[(u8, u16)]) { + self.psi_pcr(streams, 0x100); + } + /// PAT and PMT; the PMT names `pcr_pid` as the PCR PID. The streams' ES info is empty. + fn psi_pcr(&mut self, streams: &[(u8, u16)], pcr_pid: u16) { + let descs: Vec<(u8, u16, Vec)> = streams.iter().map(|&(st, pid)| (st, pid, Vec::new())).collect(); + self.psi_full(&descs, pcr_pid); + } + /// PAT and PMT with ES descriptors per stream. + fn psi_full(&mut self, streams: &[(u8, u16, Vec)], pcr_pid: u16) { + // PAT: program 1 → PMT PID 0x100 + let pat = [0x00, 0xB0, 13, 0, 1, 0xC1, 0, 0, 0, 1, 0xE1, 0x00]; + self.section(0, &pat); + let mut pmt = vec![0x02, 0xB0, 0, 0, 1, 0xC1, 0, 0, 0xE0 | (pcr_pid >> 8) as u8, pcr_pid as u8, 0xF0, 0]; + for (st, pid, desc) in streams { + pmt.extend([*st, 0xE0 | (*pid >> 8) as u8, *pid as u8, 0xF0 | (desc.len() >> 8) as u8, desc.len() as u8]); + pmt.extend_from_slice(desc); + } + let len = pmt.len() - 3 + 4; + pmt[1] = 0xB0 | (len >> 8) as u8; + pmt[2] = len as u8; + self.section(0x100, &pmt); + } + /// An adaptation-field-only packet carrying a PCR with the given 33-bit base. + fn pcr(&mut self, pid: u16, base: i64) { + let cc = self.cc.entry(pid).or_insert(0); + let b = base & ((1 << 33) - 1); + let mut p = vec![0x47, (pid >> 8) as u8, pid as u8, 0x20 | *cc, 183, 0x10]; + p.extend([(b >> 25) as u8, (b >> 17) as u8, (b >> 9) as u8, (b >> 1) as u8, ((b & 1) as u8) << 7 | 0x7E, 0]); + p.resize(188, 0xFF); + if self.m2ts { + self.out.extend_from_slice(&[0, 0, 0, 0]); + } + self.out.extend(p); + } + pub(super) fn pes(&mut self, pid: u16, data: &[u8]) { + let mut rest = data; + let mut first = true; + while !rest.is_empty() { + let n = self.packet(pid, first, rest); + rest = &rest[n..]; + first = false; + } + } +} + +/// An MPEG-2 coded frame: sequence header (on I), GOP, picture header, picture coding +/// extension and a slice of filler; or a field pair. +fn mpeg2_frame(coding_type: u8, tref: u16, fields: bool, filler: usize) -> Vec { + let mut v = Vec::new(); + if coding_type == 1 { + v.extend([0, 0, 1, 0xB3, 0x14, 0x00, 0xF0, 0x13, 0xFF, 0xFF, 0xE0, 0x18]); + v.extend([0, 0, 1, 0xB8, 0, 8, 0, 0x40]); + } + let pics: &[u8] = if fields { &[1, 2] } else { &[3] }; + for &s in pics { + v.extend([0, 0, 1, 0x00, (tref >> 2) as u8, ((tref & 3) << 6) as u8 | coding_type << 3, 0xFF, 0xF8]); + v.extend([0, 0, 1, 0xB5, 0x8F, 0xFF, 0xF0 | s, 0x80, 0x80]); + v.extend([0, 0, 1, 0x01]); + v.extend((0..filler).map(|i| (i % 200) as u8 | 0x10)); + } + v +} + +/// MPEG-1 layer II frame, 48 kHz 192 kb/s (576 bytes). +fn mp2_frame(k: u8) -> Vec { + let mut v = vec![0xFF, 0xFD, 0xA4, 0x00]; + v.extend((0..572).map(|i| (i as u8) ^ k)); + v +} + +#[test] +fn transport_stream_units_round_trip() { + for m2ts in [false, true] { + let mut mux = TsMux::new(m2ts); + mux.psi(&[(0x02, 0x1011), (0x03, 0x1100)]); + // decode order I0 P3 B1 B2 with PTS = display time, DTS on anchors + let frames = [(1u8, 0u16, false), (2, 3, false), (3, 1, true), (3, 2, false)]; + let mut expect_video = Vec::new(); + for (k, &(t, tref, fields)) in frames.iter().enumerate() { + let f = mpeg2_frame(t, tref, fields, 300 + 97 * k); + let pts = 90_000 + tref as i64 * 3600; + let dts = (t != 3).then_some(90_000 - 3600 + k as i64 * 3600); + mux.pes(0x1011, &pes(0xE0, Some(pts), dts, &f, false)); + expect_video.push((f, pts, t)); + // two audio frames per PES, the second without its own timestamp + let a: Vec = [mp2_frame(2 * k as u8), mp2_frame(2 * k as u8 + 1)].concat(); + mux.pes(0x1100, &pes(0xC0, Some(90_000 + 2160 * 2 * k as i64), None, &a, true)); + } + let data = mux.out; + let f = open(&data).unwrap(); + assert_eq!(f.format, Format::Ts { packet_size: if m2ts { 192 } else { 188 }, sync_offset: if m2ts { 4 } else { 0 } }); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + assert_eq!(f.program, Some(1)); + let v = f.find(Kind::Video, |_| true).unwrap(); + let s = &f.streams[v]; + assert_eq!(s.codec, Codec::Mpeg2Video); + assert_eq!(s.units.len(), 4); + for (i, (bytes, pts, t)) in expect_video.iter().enumerate() { + let u = &s.units[i]; + assert_eq!(f.read_unit(&data, v, i).unwrap(), *bytes, "unit {i}"); + assert_eq!(u.pts, Some(*pts)); + assert_eq!(u.key, *t == 1); + assert_eq!(u.disposable, *t == 3); + assert_eq!(u.picture.unwrap().coding_type, *t); + } + assert_eq!(s.units[2].picture.unwrap().structure, 1, "field pair in one unit"); + assert!(s.units[0].picture.unwrap().sequence_header && s.units[0].picture.unwrap().gop); + let a = f.find(Kind::Audio, |c| *c == Codec::MpegAudio).unwrap(); + let s = &f.streams[a]; + assert_eq!(s.units.len(), 8); + for (i, u) in s.units.iter().enumerate() { + assert_eq!(f.read_unit(&data, a, i).unwrap(), mp2_frame(i as u8)); + assert_eq!(u.pts, (i % 2 == 0).then_some(90_000 + 2160 * i as i64)); + } + } +} + +#[test] +fn program_stream_units_round_trip() { + // packs of ≤ 2048 bytes: frames are split across PES packets + let frames: Vec> = (0..5).map(|k| mpeg2_frame(if k == 0 { 1 } else { 2 }, k as u16, k == 3, 2500 + 300 * k)).collect(); + let es: Vec = frames.concat(); + let mut starts = Vec::new(); + let mut acc = 0; + for f in &frames { + starts.push(acc); + acc += f.len(); + } + let mut out = Vec::new(); + let mut p = 0; + let mut a = 0u8; + while p < es.len() { + out.extend([0, 0, 1, 0xBA, 0x44, 0, 4, 0, 4, 1, 1, 0x89, 0xC3, 0xF8]); + let n = (es.len() - p).min(2000); + // a timestamp when a frame starts in this packet + let k = starts.iter().position(|&s| s >= p && s < p + n); + out.extend(pes(0xE0, k.map(|k| 3600 * k as i64), None, &es[p..p + n], true)); + p += n; + // AC-3 in private stream 1 (sub-stream 0x80, 4-byte header), 448 kb/s frames + let mut ac3 = vec![0x80, 1, 0, 1, 0x0B, 0x77, 0, 0, 30, 0x40]; + ac3.extend(std::iter::repeat_n(a, 1792 - 6)); + a += 1; + out.extend(pes(0xBD, Some(1000 + 2880 * a as i64), None, &ac3, true)); + } + out.extend([0, 0, 1, 0xB9]); + let f = open(&out).unwrap(); + assert_eq!(f.format, Format::Ps { mpeg1: false }); + let v = f.find(Kind::Video, |_| true).unwrap(); + assert_eq!(f.streams[v].units.len(), 5); + for (i, fr) in frames.iter().enumerate() { + assert_eq!(&f.read_unit(&out, v, i).unwrap(), fr); + assert_eq!(f.streams[v].units[i].pts, Some(3600 * i as i64)); + } + let a = f.find(Kind::Audio, |c| *c == Codec::Ac3).unwrap(); + assert_eq!(f.streams[a].id, StreamId::Ps { stream_id: 0xBD, sub_id: Some(0x80) }); + assert_eq!(f.streams[a].units.len(), a_count(&out)); + let u0 = f.read_unit(&out, a, 0).unwrap(); + assert_eq!(&u0[..2], &[0x0B, 0x77]); + assert_eq!(u0.len(), 1792); +} + +fn a_count(ps: &[u8]) -> usize { + ps.windows(4).filter(|w| *w == [0, 0, 1, 0xBD]).count() +} + +#[test] +fn sniffing() { + assert_eq!(sniff(&[0, 0, 1, 0xBA, 0x44]), Some(Format::Ps { mpeg1: false })); + assert_eq!(sniff(&[0, 0, 1, 0xBA, 0x21]), Some(Format::Ps { mpeg1: true })); + assert_eq!(sniff(&[0, 0, 1, 0xB3, 0x44]), None); + let mut ts = vec![0u8; 188 * 6]; + for k in 0..6 { + ts[k * 188] = 0x47; + } + assert!(matches!(sniff(&ts), Some(Format::Ts { packet_size: 188, .. }))); +} + +#[test] +fn truncation_and_mutation_never_panic() { + let mut mux = TsMux::new(false); + mux.psi(&[(0x02, 0x1011), (0x0F, 0x1100), (0x1B, 0x1200)]); + for k in 0..6u16 { + mux.pes(0x1011, &pes(0xE0, Some(3600 * k as i64), None, &mpeg2_frame(if k == 0 { 1 } else { 3 }, k, k % 2 == 1, 400), false)); + let mut adts = vec![0xFF, 0xF1, 0x50, 0x80, 0x0C, 0x9F, 0xFC]; + adts.extend([0x21u8; 93]); + mux.pes(0x1100, &pes(0xC0, Some(1920 * k as i64), None, &adts, true)); + mux.pes(0x1200, &pes(0xE1, Some(3600 * k as i64), None, &[0, 0, 0, 1, 0x09, 0xF0, 0, 0, 1, 0x65, 0x88, 1, 2, 3], false)); + } + let data = mux.out; + let full = open(&data).unwrap(); + assert_eq!(full.streams.len(), 3); + assert_eq!(full.streams[1].units.len(), 6, "ADTS frames"); + assert!(full.streams[2].units.iter().all(|u| u.key), "IDR access units"); + for cut in (0..data.len()).step_by(37) { + if let Ok(f) = open(&data[..cut].to_vec()) { + for (s, st) in f.streams.iter().enumerate() { + for i in 0..st.units.len() { + let _ = f.read_unit(&data[..cut].to_vec(), s, i); + } + } + } + } + let mut x = 0x9E37_79B9u32; + for _ in 0..400 { + let mut m = data.clone(); + for _ in 0..8 { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let i = x as usize % m.len(); + m[i] = (x >> 8) as u8; + } + if let Ok(f) = open(&m) { + for (s, st) in f.streams.iter().enumerate() { + for i in 0..st.units.len() { + let _ = f.read_unit(&m, s, i); + } + } + } + } +} + +/// Opens `data` and reads every unit; errors are fine, panics are not. +fn open_and_read_all(data: &[u8]) { + let data = data.to_vec(); + if let Ok(f) = open(&data) { + for (s, st) in f.streams.iter().enumerate() { + for i in 0..st.units.len() { + let _ = f.read_unit(&data, s, i); + } + } + } +} + +#[test] +fn program_stream_cut_inside_a_pack_header_never_panics() { + // MPEG-1 pack header cut after the 4-byte start code + 3 bytes (once panicked in `scan`). + open_and_read_all(&[0, 0, 1, 0xBA, 0x21, 0, 0]); + for n in 4..=12 { + let mpeg1 = [0u8, 0, 1, 0xBA, 0x21, 0, 1, 0, 1, 0x80, 0, 1]; + open_and_read_all(&mpeg1[..n]); + } +} + +#[test] +fn program_stream_truncation_at_every_length_never_panics() { + let frames: Vec> = (0..3).map(|k| mpeg2_frame(if k == 0 { 1 } else { 2 }, k as u16, false, 300)).collect(); + let es: Vec = frames.concat(); + for mpeg1 in [false, true] { + let mut out = Vec::new(); + for (k, chunk) in es.chunks(500).enumerate() { + if mpeg1 { + out.extend([0, 0, 1, 0xBA, 0x21, 0, 1, 0, 1, 0x80, 0, 1]); + } else { + out.extend([0, 0, 1, 0xBA, 0x44, 0, 4, 0, 4, 1, 1, 0x89, 0xC3, 0xF8]); + } + out.extend(pes(0xE0, Some(3600 * k as i64), None, chunk, true)); + } + out.extend([0, 0, 1, 0xB9]); + assert!(open(&out).is_ok(), "the untruncated stream opens (mpeg1: {mpeg1})"); + for cut in 0..=out.len() { + open_and_read_all(&out[..cut]); + } + } +} + +#[test] +fn timestamps_unwrap_across_the_33_bit_wrap() { + let mut u = Unwrap::default(); + let near = (1i64 << 33) - 3000; + assert_eq!(u.unwrap(near), near); + assert_eq!(u.unwrap(600), (1 << 33) + 600); + // a B picture timestamp from just before the wrap + assert_eq!(u.unwrap(near + 1000), near + 1000); + assert_eq!(u.unwrap(4200), (1 << 33) + 4200); +} + +#[test] +fn pcr_range_follows_the_pmt_pcr_pid() { + // two PIDs carry PCRs on unrelated time bases; only the PMT's PCR_PID counts + let mut mux = TsMux::new(false); + mux.psi_pcr(&[(0x02, 0x101)], 0x101); + for k in 0..3i64 { + mux.pcr(0x101, 1000 + 40_500 * k); + mux.pcr(0x102, (1 << 32) + 5000 + 40_500 * k); + } + let f = open(&mux.out).unwrap(); + assert_eq!(f.pcr_range, Some((1000 * 300, (1000 + 81_000) * 300))); + // the other PID is the clock reference instead + let mut mux = TsMux::new(false); + mux.psi_pcr(&[(0x02, 0x101)], 0x102); + for k in 0..3i64 { + mux.pcr(0x101, 1000 + 40_500 * k); + mux.pcr(0x102, (1 << 32) + 5000 + 40_500 * k); + } + let f = open(&mux.out).unwrap(); + assert_eq!(f.pcr_range, Some((((1 << 32) + 5000) * 300, ((1 << 32) + 5000 + 81_000) * 300))); +} + +#[test] +fn pcr_range_without_a_usable_pcr_pid() { + // the PMT says "no PCR" (0x1FFF) or names a PID that never carries one + for pcr_pid in [0x1FFF, 0x150] { + let mut mux = TsMux::new(false); + mux.psi_pcr(&[(0x02, 0x101)], pcr_pid); + for base in [1000, 2000, 3000, 4000] { + mux.pcr(0x101, base); + } + assert_eq!(open(&mux.out).unwrap().pcr_range, None, "pcr_pid {pcr_pid:#x}"); + } + // no PMT at all: the first PID seen with a PCR stands in + let mut mux = TsMux::new(false); + for k in 0..6i64 { + mux.pcr(0x101, 1000 + 500 * k); + mux.pcr(0x102, (1 << 32) + 5000 + 500 * k); + } + let f = open(&mux.out).unwrap(); + assert_eq!(f.pcr_range, Some((1000 * 300, 3500 * 300))); +} + +#[test] +fn pcr_range_unwraps_the_33_bit_base() { + let mut mux = TsMux::new(false); + mux.psi_pcr(&[(0x02, 0x101)], 0x101); + let near = (1i64 << 33) - 1000; + for base in [near, near + 500, 2000, 2500] { + mux.pcr(0x101, base); + } + let f = open(&mux.out).unwrap(); + assert_eq!(f.pcr_range, Some((near * 300, ((1 << 33) + 2500) * 300))); +} + +#[test] +fn pcr_range_continues_when_a_later_pmt_changes_the_pcr_pid() { + let mut mux = TsMux::new(false); + let pat = [0x00, 0xB0, 13, 0, 1, 0xC1, 0, 0, 0, 1, 0xE1, 0x00]; + mux.section(0, &pat); + mux.section(0x100, &pmt_section_for(1, 0, true, 0x101, &[(0x03, 0x1100)])); + let near = (1i64 << 33) - 1000; + mux.pcr(0x101, near); + mux.section(0x100, &pmt_section_for(1, 1, true, 0x102, &[(0x03, 0x1100)])); + mux.pcr(0x101, near + 500); // no longer active + mux.pcr(0x102, 500); + mux.pes(0x1100, &pes(0xC0, Some(90_000), None, &mp2_frame(0), true)); + let f = open(&mux.out).unwrap(); + assert_eq!(f.pcr_range, Some((near * 300, ((1 << 33) + 500) * 300))); +} + +#[test] +fn pcr_before_the_pmt_is_kept_when_the_pmt_confirms_its_pid() { + let mut mux = TsMux::new(false); + mux.pcr(0x101, 1000); + mux.psi_pcr(&[(0x03, 0x1100)], 0x101); + mux.pcr(0x101, 2000); + mux.pes(0x1100, &pes(0xC0, Some(90_000), None, &mp2_frame(0), true)); + let f = open(&mux.out).unwrap(); + assert_eq!(f.pcr_range, Some((1000 * 300, 2000 * 300))); +} + +#[test] +fn pcr_before_the_pmt_is_kept_when_another_pid_carried_the_first_pcr() { + // PID 0x102 carries the first PCR, but the PMT names 0x101: its earlier PCRs still count + let mut mux = TsMux::new(false); + mux.pcr(0x102, 500); + mux.pcr(0x101, 1000); + mux.pcr(0x101, 2000); + mux.psi_pcr(&[(0x03, 0x1100)], 0x101); + mux.pes(0x1100, &pes(0xC0, Some(90_000), None, &mp2_frame(0), true)); + let f = open(&mux.out).unwrap(); + assert_eq!(f.pcr_range, Some((1000 * 300, 2000 * 300))); +} + +#[test] +fn streams_sharing_a_clock_stay_in_step_across_the_33_bit_wrap() { + // video's first PTS is just before the wrap, audio's just after: one clock, so audio is + // 2^33 + 500, not 500 (26.5 hours apart) + let w = 1i64 << 33; + for audio_first in [false, true] { + let mut mux = TsMux::new(false); + mux.psi(&[(0x03, 0x1100), (0x03, 0x1101)]); + let (v0, a0) = (w - 1000, 500); + let video = |mux: &mut TsMux, k: u8| mux.pes(0x1101, &pes(0xC0, Some((v0 + 2160 * k as i64) % w), None, &mp2_frame(k), true)); + let audio = |mux: &mut TsMux, k: u8| mux.pes(0x1100, &pes(0xC0, Some(a0 + 2160 * k as i64), None, &mp2_frame(k), true)); + for k in 0..3u8 { + if audio_first { + audio(&mut mux, k); + video(&mut mux, k); + } else { + video(&mut mux, k); + audio(&mut mux, k); + } + } + let f = open(&mux.out).unwrap(); + let pts = |s: usize| f.streams[s].units.iter().map(|u| u.pts.unwrap()).collect::>(); + // one timeline: audio starts 1500 ticks after video (-1000 and 500 around the wrap), whichever + // stream the unwrapper saw first, and video steps by 2160 + let (a, v) = (pts(0), pts(1)); + assert_eq!(a[0] - v[0], 1500, "audio_first {audio_first}: audio {a:?} video {v:?}"); + assert_eq!(v[1] - v[0], 2160, "video {v:?}"); + } +} + +#[test] +fn a_late_pre_wrap_timestamp_first_after_the_wrap_goes_below_zero() { + let mut u = Unwrap::default(); + assert_eq!(u.unwrap(5), 5); + // a B picture from just before the wrap, arriving after the wrapped one + assert_eq!(u.unwrap((1 << 33) - 3), -3); + assert_eq!(u.unwrap(10), 10, "the late one did not shift the timeline"); +} + +#[test] +fn a_forward_jump_from_a_small_first_timestamp_is_followed() { + // spliced capture: new time base far above the first value, no wrap involved + let mut u = Unwrap::default(); + let a = u.unwrap(90_000); + let b = u.unwrap(0x1_8000_0000); + let c = u.unwrap(0x1_8000_0000 + 3_000); + assert_eq!((a, b, c), (90_000, 0x1_8000_0000, 0x1_8000_0000 + 3_000)); +} + +#[test] +fn a_forward_jump_after_a_wrap_stays_in_the_current_epoch() { + let wrap = 1i64 << 33; + let mut u = Unwrap::default(); + assert_eq!(u.unwrap(wrap - 1000), wrap - 1000); + assert_eq!(u.unwrap(500), wrap + 500); + let jump = 0x1_8000_0000; + assert_eq!(u.unwrap(jump), wrap + jump); + assert_eq!(u.unwrap(jump + 3000), wrap + jump + 3000); +} + +#[test] +fn program_streams_share_their_initial_wrap_epoch() { + let wrap = 1i64 << 33; + for audio_first in [false, true] { + let video = pes(0xE0, Some(wrap - 1000), None, &mpeg2_frame(1, 0, false, 100), true); + let audio = pes(0xC0, Some(500), None, &mp2_frame(0), true); + let mut out = ps_pack().to_vec(); + if audio_first { + out.extend(audio); + out.extend(video); + } else { + out.extend(video); + out.extend(audio); + } + out.extend([0, 0, 1, 0xB9]); + let f = open(&out).unwrap(); + let pts = |id| { + f.streams + .iter() + .find(|s| s.id == (StreamId::Ps { stream_id: id, sub_id: None })) + .and_then(|s| s.units.first()) + .and_then(|u| u.pts) + .unwrap() + }; + assert_eq!(pts(0xC0) - pts(0xE0), 1500, "audio_first {audio_first}"); + } +} + +#[test] +fn a_program_stream_first_seen_after_a_wrap_joins_the_current_epoch() { + let wrap = 1i64 << 33; + let mut out = ps_pack().to_vec(); + out.extend(pes(0xC0, Some(wrap - 1000), None, &mp2_frame(0), true)); + out.extend(pes(0xC0, Some(500), None, &mp2_frame(1), true)); + out.extend(pes(0xC1, Some(600), None, &mp2_frame(2), true)); + out.extend([0, 0, 1, 0xB9]); + let f = open(&out).unwrap(); + let pts = |id| { + f.streams.iter().find(|s| s.id == (StreamId::Ps { stream_id: id, sub_id: None })).and_then(|s| s.units.first()).and_then(|u| u.pts).unwrap() + }; + assert_eq!(pts(0xC1), wrap + 600); +} + +#[test] +fn program_stream_scr_is_unwrapped_and_ordered() { + // two packs, the SCR wraps between them: the range is first..last, not a 2^33 jump backwards + fn scr_pack(base: i64) -> Vec { + let b = base & ((1 << 33) - 1); + let mut v = vec![0, 0, 1, 0xBA]; + v.extend([ + 0x44 | (((b >> 30) & 7) as u8) << 3 | ((b >> 28) & 3) as u8, + (b >> 20) as u8, + 0x04 | (((b >> 15) & 0x1F) as u8) << 3 | ((b >> 13) & 3) as u8, + (b >> 5) as u8, + 0x04 | ((b & 0x1F) as u8) << 3, + 1, + 1, + 0x89, + 0xC3, + 0xF8, + ]); + v + } + let near = (1i64 << 33) - 1000; + let mut out = scr_pack(near); + out.extend(pes(0xE0, Some(0), None, &mpeg2_frame(1, 0, false, 100), true)); + out.extend(scr_pack(2000)); + out.extend(pes(0xE0, Some(3600), None, &mpeg2_frame(2, 1, false, 100), true)); + out.extend([0, 0, 1, 0xB9]); + let f = open(&out).unwrap(); + assert_eq!(f.pcr_range, Some((near * 300, ((1 << 33) + 2000) * 300))); +} + +#[test] +fn language_descriptor_accepts_only_three_letters() { + let cases: [([u8; 3], Option<&str>); 5] = [(*b"ger", Some("ger")), (*b"ENG", Some("eng")), ([0, 0, 0], None), (*b"e\0g", None), (*b"d e", None)]; + for (code, want) in cases { + let mut desc = vec![0x0A, 4]; + desc.extend(code); + desc.push(0); + let mut mux = TsMux::new(false); + mux.psi_full(&[(0x03, 0x1100, desc)], 0x100); + mux.pes(0x1100, &pes(0xC0, Some(0), None, &mp2_frame(0), true)); + let f = open(&mux.out).unwrap(); + assert_eq!(f.streams[0].language.as_deref(), want, "{code:?}"); + } +} + +/// Audio-only TS: `n` PES packets of two MPEG-1 layer II frames each (7 transport packets apiece). +fn audio_ts(n: u8) -> Vec { + let mut mux = TsMux::new(false); + mux.psi(&[(0x03, 0x1100)]); + for k in 0..n { + let a: Vec = [mp2_frame(2 * k), mp2_frame(2 * k + 1)].concat(); + mux.pes(0x1100, &pes(0xC0, Some(90_000 + 4320 * k as i64), None, &a, true)); + } + mux.out +} + +/// Byte offset of the `n`-th (0-based) packet of `pid` that has no unit start. +fn nth_continuation(data: &[u8], pid: u16, n: usize) -> usize { + (0..data.len() / 188) + .map(|i| i * 188) + .filter(|&o| data[o] == 0x47 && (((data[o + 1] & 0x1F) as u16) << 8 | data[o + 2] as u16) == pid && data[o + 1] & 0x40 == 0) + .nth(n) + .expect("packet exists") +} + +fn audio_bytes(f: &File, data: &[u8]) -> Vec> { + let a = f.find(Kind::Audio, |_| true).unwrap(); + (0..f.streams[a].units.len()).map(|i| f.read_unit(data, a, i).unwrap()).collect() +} + +#[test] +fn packet_with_transport_error_indicator_is_dropped() { + let clean = audio_ts(6); + let base = open(&clean).unwrap(); + assert!(base.warnings.is_empty(), "{:?}", base.warnings); + let mut data = clean.clone(); + let o = nth_continuation(&data, 0x1100, 10); + data[o + 1] |= 0x80; + // a corrupted payload must not reach the splitter either + data[o + 20] ^= 0xFF; + let f = open(&data).unwrap(); + assert!(f.warnings.iter().any(|w| w.contains("1 packet(s) with the transport error indicator")), "{:?}", f.warnings); + let a = f.find(Kind::Audio, |_| true).unwrap(); + let total = |f: &File| f.streams[a].units.iter().map(|u| u.size as u64).sum::(); + assert!(total(&f) < total(&base), "the 184 payload bytes of the flagged packet are gone"); + for unit in audio_bytes(&f, &data) { + assert!(!unit.is_empty()); + } +} + +/// An Annex B NAL unit: start code, header bytes and `n` bytes of payload (no zero runs). +fn nal(header: &[u8], body: &[u8]) -> Vec { + let mut v = vec![0, 0, 0, 1]; + v.extend(header); + v.extend(body); + v +} + +/// A slice of `n` filler bytes after the first byte of the slice header (0x88: first_mb 0). +fn slice(header: &[u8], first: u8, n: usize) -> Vec { + let mut body = vec![first]; + body.extend((0..n).map(|i| 0x40 | (i % 31) as u8)); + nal(header, &body) +} + +const AUD: [u8; 2] = [0x09, 0xF0]; + +fn h264_idr(n: usize) -> Vec { + [nal(&AUD, &[]), nal(&[0x67], &[0x42, 0x80, 0x1E]), nal(&[0x68], &[0xCE, 0x38, 0x80]), slice(&[0x65], 0x88, n)].concat() +} + +fn h264_p(n: usize) -> Vec { + [nal(&AUD, &[]), slice(&[0x41], 0x88, n)].concat() +} + +/// A non-reference B picture (nal_ref_idc 0). +fn h264_b(n: usize) -> Vec { + [nal(&AUD, &[]), slice(&[0x01], 0x88, n)].concat() +} + +/// A non-IDR I picture introduced by SEI with a buffering period message and a recovery point. +fn h264_recovery_i(n: usize) -> Vec { + let sei = nal(&[0x06], &[0x00, 0x02, 0xAA, 0xBB, 0x06, 0x01, 0x84, 0x80]); + [nal(&AUD, &[]), sei, slice(&[0x41], 0x88, n)].concat() +} + +fn h264_units(aus: &[(Option, Vec)]) -> (Vec, File) { + let mut mux = TsMux::new(false); + mux.psi(&[(0x1B, 0x1011)]); + for (pts, au) in aus { + mux.pes(0x1011, &pes(0xE0, *pts, None, au, false)); + } + let data = mux.out; + let f = open(&data).unwrap(); + (data, f) +} + +#[test] +fn h264_recovery_point_is_a_random_access_point() { + let aus = [(Some(90_000), h264_idr(300)), (Some(93_600), h264_p(300)), (Some(97_200), h264_recovery_i(300)), (Some(100_800), h264_p(300))]; + let (data, f) = h264_units(&aus); + let s = &f.streams[0]; + assert_eq!(s.codec, Codec::H264); + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [true, false, true, false]); + for (i, (pts, au)) in aus.iter().enumerate() { + assert_eq!(f.read_unit(&data, 0, i).unwrap(), *au, "unit {i}"); + assert_eq!(s.units[i].pts, *pts); + } + // a stream cut so that it starts at a recovery point (no IDR at all) has a key unit + let (_, f) = h264_units(&[(Some(1000), h264_recovery_i(400)), (Some(4600), h264_p(400)), (Some(8200), h264_p(400))]); + assert_eq!(f.streams[0].units.iter().map(|u| u.key).collect::>(), [true, false, false]); + // SEI without a recovery point message is not one + let sei = nal(&[0x06], &[0x00, 0x02, 0xAA, 0xBB, 0x80]); + let au = [nal(&AUD, &[]), sei, slice(&[0x41], 0x88, 600)].concat(); + let (_, f) = h264_units(&[(Some(1000), au)]); + assert!(!f.streams[0].units[0].key); +} + +#[test] +fn h264_intra_refresh_recovery_point_is_not_a_random_access_point() { + // recovery_frame_cnt 1 (ue(v) "010"): decoding from here shows broken pictures + let sei = nal(&[0x06], &[0x00, 0x02, 0xAA, 0xBB, 0x06, 0x01, 0x44, 0x80]); + let au = [nal(&AUD, &[]), sei, slice(&[0x41], 0x88, 300)].concat(); + let (_, f) = h264_units(&[(Some(1000), au), (Some(4600), h264_p(300))]); + assert_eq!(f.streams[0].units.iter().map(|u| u.key).collect::>(), [false, false]); +} + +#[test] +fn h264_several_access_units_in_one_pes_are_separate_units() { + // IDR, then in one PES a non-reference B picture and a reference P picture, only the first + // access unit of the PES has a timestamp + let (idr, b, p) = (h264_idr(400), h264_b(300), h264_p(250)); + let (data, f) = h264_units(&[(Some(90_000), idr.clone()), (Some(93_600), [b.clone(), p.clone()].concat()), (Some(100_800), h264_p(100))]); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 4); + assert_eq!(s.units.iter().map(|u| u.pts).collect::>(), [Some(90_000), Some(93_600), None, Some(100_800)]); + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [true, false, false, false]); + assert_eq!(s.units.iter().map(|u| u.disposable).collect::>(), [false, true, false, false]); + assert_eq!(f.read_unit(&data, 0, 0).unwrap(), idr); + assert_eq!(f.read_unit(&data, 0, 1).unwrap(), b); + assert_eq!(f.read_unit(&data, 0, 2).unwrap(), p); +} + +#[test] +fn h264_units_without_delimiters_split_at_the_first_slice() { + // no AUD or SEI: a slice with first_mb_in_slice 0 starts the next access unit, a further + // slice of the same picture (first_mb != 0) does not + let two_slices = [slice(&[0x41], 0x88, 300), slice(&[0x41], 0x42, 300)].concat(); + let idr = slice(&[0x65], 0x88, 200); + let (data, f) = h264_units(&[(Some(0), [idr.clone(), two_slices.clone(), two_slices.clone()].concat())]); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 3); + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [true, false, false]); + assert_eq!(f.read_unit(&data, 0, 1).unwrap(), two_slices); + assert_eq!(f.read_unit(&data, 0, 0).unwrap(), idr); +} + +#[test] +fn h264_one_access_unit_per_pes_is_unchanged() { + // parameter sets inside the access unit (after the AUD, before the slices) do not split it + let aus: Vec<(Option, Vec)> = + (0..6).map(|k| (Some(90_000 + 3600 * k), if k % 3 == 0 { h264_idr(500) } else { h264_p(150 + 70 * k as usize) })).collect(); + let (data, f) = h264_units(&aus); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 6); + for (i, (pts, au)) in aus.iter().enumerate() { + assert_eq!(f.read_unit(&data, 0, i).unwrap(), *au); + assert_eq!(s.units[i].pts, *pts); + assert_eq!(s.units[i].key, i % 3 == 0); + assert!(!s.units[i].disposable); + } +} + +#[test] +fn scrambled_packet_is_skipped_with_a_warning() { + let clean = audio_ts(6); + let base = open(&clean).unwrap(); + let mut data = clean.clone(); + let o = nth_continuation(&data, 0x1100, 10); + data[o + 3] |= 0x80; // transport_scrambling_control = 2 (even key) + let f = open(&data).unwrap(); + assert!(f.warnings.iter().any(|w| w.contains("1 scrambled packet(s) skipped")), "{:?}", f.warnings); + assert!(!f.warnings.iter().any(|w| w.contains("continuity")), "{:?}", f.warnings); + let a = f.find(Kind::Audio, |_| true).unwrap(); + let total = |f: &File| f.streams[a].units.iter().map(|u| u.size as u64).sum::(); + assert!(total(&f) < total(&base)); +} + +#[test] +fn duplicate_packet_is_dropped_but_a_different_payload_with_the_same_counter_is_kept() { + let clean = audio_ts(6); + let base = open(&clean).unwrap(); + let expect = audio_bytes(&base, &clean); + let o = nth_continuation(&clean, 0x1100, 10); + // exact duplicate right behind the original + let mut dup = clean.clone(); + let copy = dup[o..o + 188].to_vec(); + dup.splice(o + 188..o + 188, copy); + let f = open(&dup).unwrap(); + assert!(f.warnings.iter().any(|w| w.contains("1 duplicate packet(s) dropped")), "{:?}", f.warnings); + assert!(!f.warnings.iter().any(|w| w.contains("continuity")), "{:?}", f.warnings); + assert_eq!(audio_bytes(&f, &dup), expect, "the repeated payload is not fed twice"); + // same counter but other content: not a duplicate, kept + let mut other = clean.clone(); + let mut copy = other[o..o + 188].to_vec(); + copy[187] ^= 0x55; + other.splice(o + 188..o + 188, copy); + let f = open(&other).unwrap(); + assert!(!f.warnings.iter().any(|w| w.contains("duplicate")), "{:?}", f.warnings); + let a = f.find(Kind::Audio, |_| true).unwrap(); + let total = |f: &File| f.streams[a].units.iter().map(|u| u.size as u64).sum::(); + assert!(total(&f) > total(&base), "the differing packet's payload is kept"); +} + +/// A PMT section with the given program, version, applicability, PCR PID and streams (valid CRC). +fn pmt_section_for(program: u16, version: u8, current_next: bool, pcr_pid: u16, streams: &[(u8, u16)]) -> Vec { + let mut pmt = vec![ + 0x02, + 0xB0, + 0, + (program >> 8) as u8, + program as u8, + 0xC0 | (version << 1) | current_next as u8, + 0, + 0, + 0xE0 | (pcr_pid >> 8) as u8, + pcr_pid as u8, + 0xF0, + 0, + ]; + for &(st, pid) in streams { + pmt.extend([st, 0xE0 | (pid >> 8) as u8, pid as u8, 0xF0, 0]); + } + let len = pmt.len() - 3 + 4; + pmt[1] = 0xB0 | (len >> 8) as u8; + pmt[2] = len as u8; + pmt +} + +/// A PMT section for program 1 with the given version / current_next / streams (valid CRC). +fn pmt_section(version: u8, current_next: bool, streams: &[(u8, u16)]) -> Vec { + pmt_section_for(1, version, current_next, 0x100, streams) +} + +#[test] +fn later_pmt_adds_streams_but_never_changes_or_removes_known_ones() { + let mut mux = TsMux::new(false); + mux.psi(&[(0x03, 0x1100)]); + let audio = |mux: &mut TsMux, k: u8| { + let a: Vec = [mp2_frame(2 * k), mp2_frame(2 * k + 1)].concat(); + mux.pes(0x1100, &pes(0xC0, Some(90_000 + 4320 * k as i64), None, &a, true)); + }; + audio(&mut mux, 0); + // version 1: the PID becomes AAC and a second stream appears; version 2: PID removed + mux.section(0x100, &pmt_section(1, true, &[(0x0F, 0x1100), (0x03, 0x1200)])); + audio(&mut mux, 1); + mux.section(0x100, &pmt_section(2, true, &[(0x03, 0x1200)])); + mux.section(0x100, &pmt_section(2, true, &[(0x03, 0x1200)])); + audio(&mut mux, 2); + let f = open(&mux.out).unwrap(); + assert!(f.streams.iter().any(|s| s.id == StreamId::Pid(0x1200)), "the PID added by a later PMT is read"); + assert_eq!(f.streams[0].id, StreamId::Pid(0x1100)); + assert_eq!(f.streams[0].codec, Codec::MpegAudio); + assert_eq!(f.streams[0].units.len(), 6, "audio kept flowing through the first PMT's splitter"); + assert_eq!(f.warnings.iter().filter(|w| w.contains("program map table changed")).count(), 1, "{:?}", f.warnings); +} + +#[test] +fn audio_pid_announced_in_a_later_pmt_is_read_without_warning() { + let mut mux = TsMux::new(false); + mux.psi(&[(0x03, 0x1100)]); + let a: Vec = [mp2_frame(0), mp2_frame(1)].concat(); + mux.pes(0x1100, &pes(0xC0, Some(90_000), None, &a, true)); + // version 1 keeps 0x1100 as it was and announces a second audio PID + mux.section(0x100, &pmt_section(1, true, &[(0x03, 0x1100), (0x03, 0x1200)])); + let b: Vec = [mp2_frame(2), mp2_frame(3)].concat(); + mux.pes(0x1200, &pes(0xC0, Some(90_000 + 8640), None, &b, true)); + let f = open(&mux.out).unwrap(); + let late = f.streams.iter().find(|s| s.id == StreamId::Pid(0x1200)).expect("late audio PID"); + assert!(!late.units.is_empty(), "the late stream has units"); + assert!(f.warnings.iter().all(|w| !w.contains("program map table")), "{:?}", f.warnings); +} + +#[test] +fn pmt_not_yet_applicable_is_ignored() { + let mut mux = TsMux::new(false); + let pat = [0x00, 0xB0, 13, 0, 1, 0xC1, 0, 0, 0, 1, 0xE1, 0x00]; + mux.section(0, &pat); + // current_next_indicator 0: describes a future table, must not be used + mux.section(0x100, &pmt_section(3, false, &[(0x03, 0x1200)])); + mux.section(0x100, &pmt_section(0, true, &[(0x03, 0x1100)])); + let a: Vec = [mp2_frame(0), mp2_frame(1)].concat(); + mux.pes(0x1100, &pes(0xC0, Some(90_000), None, &a, true)); + let f = open(&mux.out).unwrap(); + assert_eq!(f.streams.len(), 1); + assert_eq!(f.streams[0].id, StreamId::Pid(0x1100)); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); +} + +#[test] +fn a_bad_crc_on_the_current_pmt_version_is_reported() { + let mut mux = TsMux::new(false); + mux.psi(&[(0x03, 0x1100)]); + mux.section(0x100, &pmt_section(0, true, &[(0x03, 0x1100)])); + // A short PSI section is placed at the end of its stuffed packet, so the final byte is CRC. + if let Some(last) = mux.out.last_mut() { + *last ^= 1; + } + mux.pes(0x1100, &pes(0xC0, Some(90_000), None, &mp2_frame(0), true)); + let f = open(&mux.out).unwrap(); + assert!(f.warnings.iter().any(|w| w == "1 PSI section(s) with bad CRC"), "{:?}", f.warnings); +} + +#[test] +fn a_pmt_for_another_program_on_the_same_pid_is_ignored() { + let mut mux = TsMux::new(false); + let pat = [0x00, 0xB0, 13, 0, 1, 0xC1, 0, 0, 0, 1, 0xE1, 0x00]; + mux.section(0, &pat); + // The other program deliberately has the same PMT version and arrives first. + mux.section(0x100, &pmt_section_for(2, 0, true, 0x102, &[(0x03, 0x1200)])); + mux.section(0x100, &pmt_section_for(1, 0, true, 0x101, &[(0x03, 0x1100)])); + mux.pcr(0x101, 1000); + mux.pcr(0x101, 2000); + mux.pcr(0x102, 50_000); + mux.pes(0x1100, &pes(0xC0, Some(90_000), None, &mp2_frame(0), true)); + let f = open(&mux.out).unwrap(); + assert_eq!(f.program, Some(1)); + assert_eq!(f.streams.len(), 1); + assert_eq!(f.streams[0].id, StreamId::Pid(0x1100)); + assert_eq!(f.pcr_range, Some((1000 * 300, 2000 * 300))); +} + +#[test] +fn hevc_several_access_units_in_one_pes_are_separate_units() { + let aud = nal(&[0x46, 0x01], &[0x50]); + let idr = [aud.clone(), slice(&[0x26, 0x01], 0x80, 300)].concat(); + // TRAIL_N picture: sub-layer non-reference + let trail_n = [aud.clone(), slice(&[0x00, 0x01], 0x80, 300)].concat(); + let trail_r = [aud, slice(&[0x02, 0x01], 0x80, 200)].concat(); + let mut mux = TsMux::new(false); + mux.psi(&[(0x24, 0x1011)]); + mux.pes(0x1011, &pes(0xE0, Some(90_000), None, &idr, false)); + mux.pes(0x1011, &pes(0xE0, Some(93_600), None, &[trail_n.clone(), trail_r.clone()].concat(), false)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.codec, Codec::Hevc); + assert_eq!(s.units.iter().map(|u| u.pts).collect::>(), [Some(90_000), Some(93_600), None]); + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [true, false, false]); + assert_eq!(s.units.iter().map(|u| u.disposable).collect::>(), [false, true, false]); + assert_eq!(f.read_unit(&mux.out, 0, 1).unwrap(), trail_n); + assert_eq!(f.read_unit(&mux.out, 0, 2).unwrap(), trail_r); +} + +fn adts_frame(k: u8) -> Vec { + let mut v = vec![0xFF, 0xF1, 0x50, 0x80, 0x0C, 0x9F, 0xFC]; + v.extend([k; 93]); + v +} + +#[test] +fn non_pes_payload_is_dropped_until_the_next_unit_start() { + // a unit start whose payload is not a PES header, then continuation packets that happen to + // hold ADTS frames: nothing of it may become a unit + let mut mux = TsMux::new(false); + mux.psi(&[(0x0F, 0x1100)]); + mux.packet(0x1100, true, &[0x55; 184]); + for k in 0..10 { + mux.packet(0x1100, false, &adts_frame(k)); + } + let f = open(&mux.out).unwrap(); + assert_eq!(f.streams.first().map(|s| s.units.len()), Some(0)); + // a real PES packet afterwards is indexed again + let mut mux2 = TsMux::new(false); + mux2.psi(&[(0x0F, 0x1100)]); + mux2.packet(0x1100, true, &[0x55; 184]); + mux2.packet(0x1100, false, &adts_frame(1)); + mux2.pes(0x1100, &pes(0xC0, Some(9000), None, &adts_frame(2), true)); + let f = open(&mux2.out).unwrap(); + let u = &f.streams[0].units; + assert_eq!(u.len(), 1); + assert_eq!(u[0].pts, Some(9000)); +} + +#[test] +fn adaptation_field_only_unit_start_keeps_the_pes_in_progress() { + let mut mux = TsMux::new(false); + mux.psi(&[(0x03, 0x1100)]); + let data = pes(0xC0, Some(9000), None, &[mp2_frame(0), mp2_frame(1)].concat(), true); + mux.packet(0x1100, true, &data[..184]); + // PUSI set, adaptation field only (no payload) + let cc = mux.cc.get(&0x1100).copied().unwrap_or(0); + let mut af = vec![0x47, 0x40 | 0x11, 0x00, 0x20 | cc, 183, 0x00]; + af.resize(188, 0xFF); + mux.out.extend(af); + for chunk in data[184..].chunks(184) { + mux.packet(0x1100, false, chunk); + } + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 2); + assert_eq!(s.units[0].pts, Some(9000)); + assert_eq!(f.read_unit(&mux.out, 0, 1).unwrap(), mp2_frame(1)); +} + +#[test] +fn oversized_unit_is_refused_without_reserving_it() { + let f = File { + format: Format::Ts { packet_size: 188, sync_offset: 0 }, + streams: vec![Stream { + id: StreamId::Pid(0x100), + stream_type: 0x1B, + codec: Codec::H264, + language: None, + units: vec![Unit { pts: None, dts: None, key: true, disposable: false, size: u32::MAX, pos: 0, offset: 0, picture: None }], + lpcm: None, + pes_packets: 0, + skipped_bytes: 0, + }], + program: None, + pcr_range: None, + warnings: Vec::new(), + }; + assert!(matches!(f.read_unit(&Vec::::new(), 0, 0), Err(Error::Invalid(_)))); +} + +/// A `ByteSource` that counts the bytes requested through `read_at`. +struct Counting<'a> { + data: &'a [u8], + read: std::cell::Cell, +} + +impl ByteSource for Counting<'_> { + fn len(&self) -> u64 { + self.data.len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + self.read.set(self.read.get() + buf.len() as u64); + self.data.read_at(offset, buf) + } +} + +#[test] +fn bad_adaptation_fields_do_not_amplify_reads() { + // aligned packets whose adaptation_field_length (255) overruns the packet: the packet grid is + // intact, so this must cost one pass over the file, not one block read per packet + let mut data = Vec::new(); + for _ in 0..3000 { + data.extend([0x47, 0x11, 0x00, 0x30]); + data.extend(std::iter::repeat_n(0xFF, 184)); + } + let src = Counting { data: &data, read: Default::default() }; + let f = open(&src).unwrap(); + assert!(f.warnings.iter().any(|w| w.contains("adaptation field")), "{:?}", f.warnings); + assert!(!f.warnings.iter().any(|w| w.contains("lost packet sync")), "{:?}", f.warnings); + let read = src.read.get(); + assert!(read <= 4 * data.len() as u64, "read {read} bytes of a {}-byte file", data.len()); +} + +#[test] +fn garbage_without_sync_does_not_amplify_reads() { + // a sync byte every 189 bytes: five-in-a-row never lines up, every 0x47 is a false candidate + let mut data = Vec::new(); + for _ in 0..3000 { + data.extend([0x47]); + data.extend(std::iter::repeat_n(0x11, 188)); + } + let head: Vec = (0..188 * 8).map(|i| if i % 188 == 0 { 0x47 } else { 0 }).collect(); + let mut all = head; + all.extend(data); + let src = Counting { data: &all, read: Default::default() }; + let f = open(&src).unwrap(); + assert!(f.warnings.iter().any(|w| w.contains("lost packet sync")), "{:?}", f.warnings); + let read = src.read.get(); + assert!(read <= 4 * all.len() as u64, "read {read} bytes of a {}-byte file", all.len()); +} + +#[test] +fn transport_stream_resyncs_after_garbage() { + const BLOCK_PACKETS: usize = 4096; + for m2ts in [false, true] { + let ps = if m2ts { 192 } else { 188 }; + // garbage in front of the stream (shorter than 8 packets) and, at a few places around the + // first block boundary, between two frames; lengths that are not a multiple of the packet + for (delta, glen) in [(0usize, 100usize), (1, 37), (2, 188), (3, 301), (5, 5), (8, 1000)] { + let edge = (BLOCK_PACKETS - delta) * ps; + let mut mux = TsMux::new(m2ts); + mux.out.extend([0x11, 0x47, 0x22]); // garbage prefix with a lone 0x47 + mux.psi(&[(0x02, 0x1011)]); + let mut expect = Vec::new(); + let mut placed = false; + let mut k = 0usize; + while k < 3000 || !placed { + if !placed && mux.out.len() >= edge { + // garbage between two PES packets, with lone sync bytes inside + let mut g: Vec = (0..glen).map(|i| 0x10 + (i % 7) as u8).collect(); + if let Some(b) = g.get_mut(3) { + *b = 0x47; + } + mux.out.extend(g); + placed = true; + } + let f = mpeg2_frame(if k == 0 { 1 } else { 2 }, (k % 1000) as u16, false, 40 + k % 300); + mux.pes(0x1011, &pes(0xE0, Some(90_000 + 3600 * k as i64), None, &f, false)); + expect.push(f); + k += 1; + } + assert!(mux.out.len() > (BLOCK_PACKETS + 4) * ps, "stream must cross a block boundary"); + let data = mux.out; + let f = open(&data).unwrap(); + assert!(f.warnings.iter().any(|w| w.contains("lost packet sync")), "{:?}", f.warnings); + let v = f.find(Kind::Video, |_| true).unwrap(); + let s = &f.streams[v]; + assert_eq!(s.units.len(), expect.len(), "m2ts {m2ts} delta {delta} glen {glen}"); + for (i, fr) in expect.iter().enumerate() { + assert_eq!(&f.read_unit(&data, v, i).unwrap(), fr, "unit {i} (m2ts {m2ts} delta {delta} glen {glen})"); + assert_eq!(s.units[i].pts, Some(90_000 + 3600 * i as i64)); + } + } + } +} diff --git a/crates/media/src/mpegts/tests/hostile.rs b/crates/media/src/mpegts/tests/hostile.rs new file mode 100644 index 000000000..ff1784fc8 --- /dev/null +++ b/crates/media/src/mpegts/tests/hostile.rs @@ -0,0 +1,99 @@ +//! Hostile-input hammer: truncation, bit flips and extreme field values must never panic or hang. + +use super::*; + +fn exercise(d: &[u8]) { + let data = d.to_vec(); + let _ = sniff(d); + let Ok(f) = open(&data) else { return }; + for (s, st) in f.streams.iter().enumerate() { + let _ = (st.kind(), st.pts_range(), st.codec.name()); + let n = st.units.len(); + for i in [0, n / 2, n.saturating_sub(1), n, usize::MAX] { + let _ = f.read_unit(&data, s, i); + } + } + let _ = f.find(Kind::Video, |_| true); +} + +fn ts_seed(m2ts: bool) -> Vec { + let mut mux = TsMux::new(m2ts); + mux.psi(&[(0x02, 0x1011), (0x0F, 0x1100), (0x1B, 0x1200), (0x81, 0x1300), (0x24, 0x1400), (0x03, 0x1500)]); + for k in 0..6u16 { + mux.pes( + 0x1011, + &pes(0xE0, Some(3600 * k as i64), Some(3600 * k as i64 - 7200), &mpeg2_frame(if k == 0 { 1 } else { 3 }, k, k % 2 == 1, 400), false), + ); + mux.pes(0x1100, &pes(0xC0, Some(1920 * k as i64), None, &adts_frame(k as u8), true)); + mux.pes(0x1200, &pes(0xE1, Some(3600 * k as i64), None, &[0, 0, 0, 1, 0x09, 0xF0, 0, 0, 1, 0x65, 0x88, 1, 2, 3], false)); + let mut ac3 = vec![0x0B, 0x77, 0, 0, 30, 0x40]; + ac3.extend(std::iter::repeat_n(k as u8, 1792 - 6)); + mux.pes(0x1300, &pes(0xBD, Some(2880 * k as i64), None, &ac3, true)); + mux.pes(0x1400, &pes(0xE2, Some(3600 * k as i64), None, &[0, 0, 0, 1, 0x46, 0x01, 0x50, 0, 0, 0, 1, 0x26, 0x01, 0xAF, 1, 2], false)); + mux.pes(0x1500, &pes(0xC1, Some(2880 * k as i64), None, &mp2_frame(k as u8), true)); + } + mux.out +} + +fn ps_seed() -> Vec { + let frames: Vec> = (0..5).map(|k| mpeg2_frame(if k == 0 { 1 } else { 2 }, k as u16, k == 3, 900 + 100 * k)).collect(); + let es: Vec = frames.concat(); + let mut out = Vec::new(); + let mut a = 0u8; + for (i, chunk) in es.chunks(700).enumerate() { + out.extend([0, 0, 1, 0xBA, 0x44, 0, 4, 0, 4, 1, 1, 0x89, 0xC3, 0xF8]); + out.extend(pes(0xE0, Some(3600 * i as i64), None, chunk, true)); + let mut ac3 = vec![0x80, 1, 0, 1, 0x0B, 0x77, 0, 0, 30, 0x40]; + ac3.extend(std::iter::repeat_n(a, 1792 - 6)); + a += 1; + out.extend(pes(0xBD, Some(1000 + 2880 * a as i64), None, &ac3, true)); + // LPCM in private stream 1, system header and PSM-ish noise between packs + out.extend([0, 0, 1, 0xBB, 0, 6, 0x80, 0, 1, 4, 0xE1, 0xFF]); + out.extend(pes(0xBD, Some(5000 + 100 * i as i64), None, &[0xA0, 1, 0, 4, 0, 0x01, 0x81, 1, 2, 3, 4, 5, 6, 7, 8], true)); + } + out.extend([0, 0, 1, 0xB9]); + out +} + +#[test] +fn hostile_input_never_panics() { + let mut seeds = vec![ts_seed(false), ts_seed(true), ps_seed()]; + seeds.push(work_tests::big_program_stream(false, 40).0); + seeds.push(work_tests::big_program_stream(true, 40).0); + // fewer rounds than FilmCraft's 40 000: tests here build without optimisation, and the two + // large program streams cost a megabyte of window refill per unit read + for (i, s) in seeds.iter().enumerate() { + craft_media_testkit::hostile::hammer(&format!("mpegts seed {i}"), s, if i < 3 { 4_000 } else { 150 }, exercise); + } +} + +#[test] +fn elementary_stream_frame_parsers_never_panic() { + let codecs = [ + Codec::Mpeg1Video, + Codec::Mpeg2Video, + Codec::H264, + Codec::Hevc, + Codec::MpegAudio, + Codec::AacAdts, + Codec::AacLatm, + Codec::Ac3, + Codec::Eac3, + Codec::Dts, + Codec::TrueHd, + Codec::LpcmBluray, + Codec::LpcmDvd, + Codec::Unknown(0x55), + ]; + let mut ac3 = vec![0x0B, 0x77, 0, 0, 30, 0x40]; + ac3.extend([1u8; 60]); + let seeds = [adts_frame(3), mp2_frame(1), ac3, mpeg2_frame(1, 0, false, 64), vec![0x56, 0xE0, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80]]; + for (i, s) in seeds.iter().enumerate() { + craft_media_testkit::hostile::hammer(&format!("es seed {i}"), s, 40_000, |d| { + for c in &codecs { + let _ = frame_bytes(c, d); + let _ = frame_info(c, d); + } + }); + } +} diff --git a/crates/media/src/mpegts/ts.rs b/crates/media/src/mpegts/ts.rs new file mode 100644 index 000000000..a4c01a986 --- /dev/null +++ b/crates/media/src/mpegts/ts.rs @@ -0,0 +1,749 @@ +//! Transport streams (H.222.0 §2.4.3): packets, PSI (PAT/PMT), PES reassembly. + +use std::collections::HashMap; + +use super::es::Splitter; +use super::pes::{self, PesHeader}; +use super::{ByteSource, ClockRange, Codec, Error, File, Format, Result, Stream, StreamId, Unit, Unwrap, read_some}; + +/// Byte-wise table for the MSB-first CRC-32 (polynomial 0x04C11DB7): entry `i` is the CRC register +/// after shifting the byte `i` through eight bit steps. +const CRC_TABLE: [u32; 256] = { + let mut t = [0u32; 256]; + let mut i = 0; + while i < 256 { + let mut crc = (i as u32) << 24; + let mut bit = 0; + while bit < 8 { + crc = if crc & 0x8000_0000 != 0 { (crc << 1) ^ 0x04C1_1DB7 } else { crc << 1 }; + bit += 1; + } + t[i] = crc; + i += 1; + } + t +}; + +/// CRC-32 of PSI sections (MSB-first, polynomial 0x04C11DB7, initial value all ones; Annex A). +pub(crate) fn crc32_mpeg(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc = (crc << 8) ^ CRC_TABLE[((crc >> 24) as u8 ^ b) as usize]; + } + crc +} + +/// A packet's fields. +struct Packet<'a> { + pusi: bool, + pid: u16, + cc: u8, + has_payload: bool, + discontinuity: bool, + pcr: Option, + payload: &'a [u8], +} + +/// Why a packet could not be parsed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Bad { + /// No sync byte (or too short): the packet grid is lost. + Sync, + /// Sync byte present but the adaptation field overruns the packet: the grid is intact, the + /// packet carries nothing usable. + Adaptation, +} + +fn packet(p: &[u8]) -> std::result::Result, Bad> { + if p.len() < 188 || p[0] != 0x47 { + return Err(Bad::Sync); + } + let pusi = p[1] & 0x40 != 0; + let pid = (((p[1] & 0x1F) as u16) << 8) | p[2] as u16; + let afc = (p[3] >> 4) & 3; + let cc = p[3] & 15; + let mut start = 4; + let mut pcr = None; + let mut discontinuity = false; + if afc & 2 != 0 { + let al = p[4] as usize; + start = 5 + al; + if start > 188 { + return Err(Bad::Adaptation); + } + if al > 0 { + let flags = p[5]; + discontinuity = flags & 0x80 != 0; + if flags & 0x10 != 0 && al >= 7 { + let base = ((p[6] as i64) << 25) | ((p[7] as i64) << 17) | ((p[8] as i64) << 9) | ((p[9] as i64) << 1) | (p[10] as i64 >> 7); + let ext = (((p[10] & 1) as i64) << 8) | p[11] as i64; + pcr = Some(base * 300 + ext); + } + } + } + let has_payload = afc & 1 != 0; + Ok(Packet { pusi, pid, cc, has_payload, discontinuity, pcr, payload: if has_payload { &p[start..188] } else { &[] } }) +} + +/// `(transport_error_indicator, scrambled)` of a packet whose first byte is the sync byte (H.222.0 +/// §2.4.3.3). Both are false for anything without a sync byte or too short for the header. +fn skip_flags(p: &[u8]) -> (bool, bool) { + match (p.first(), p.get(1), p.get(3)) { + (Some(0x47), Some(b1), Some(b3)) => (b1 & 0x80 != 0, b3 >> 6 != 0), + _ => (false, false), + } +} + +/// Drops an exact duplicate packet (§2.4.3.3: a packet may be sent twice, same continuity counter +/// and same content). Conservative: only a payload-bearing packet with the previous payload-bearing +/// packet's counter and identical payload bytes counts; a packet that signals a discontinuity +/// starts a new sequence and is never a duplicate; anything else is kept. +struct DupGuard { + cc: Option, + len: usize, + data: [u8; 188], +} + +impl Default for DupGuard { + fn default() -> Self { + Self { cc: None, len: 0, data: [0; 188] } + } +} + +impl DupGuard { + /// Whether `pk` repeats the previous packet of its PID; remembers `pk` as the previous one. + fn is_dup(&mut self, pk: &Packet<'_>) -> bool { + if pk.discontinuity { + // a restart: the saved counter and payload belong to the old sequence, even when + // this packet carries only an adaptation field + self.cc = None; + } + if !pk.has_payload { + return false; + } + let dup = !pk.discontinuity && self.cc == Some(pk.cc) && self.data.get(..self.len) == Some(pk.payload); + if !dup { + self.cc = Some(pk.cc); + self.len = pk.payload.len().min(self.data.len()); + if let (Some(dst), Some(src)) = (self.data.get_mut(..self.len), pk.payload.get(..self.len)) { + dst.copy_from_slice(src); + } + } + dup + } +} + +/// Reassembles a PES header that may span packets; yields each packet's elementary-stream bytes. +#[derive(Default)] +pub(crate) struct PesAsm { + hdr: Vec, + waiting: bool, + /// The packet that started the current unit was not a PES packet: its continuation packets + /// are dropped until the next unit start. + dropping: bool, +} + +impl PesAsm { + /// The PES header completed by this packet (if any) and the packet's ES payload bytes. + pub fn packet<'a>(&mut self, pusi: bool, payload: &'a [u8]) -> (Option, &'a [u8]) { + if pusi { + if payload.is_empty() { + // an adaptation-field-only packet carries no PES data: it must not cut short + // the PES packet in progress + return (None, &[]); + } + self.hdr.clear(); + self.waiting = true; + self.dropping = false; + } else if self.dropping { + return (None, &[]); + } else if !self.waiting { + return (None, payload); + } + let before = self.hdr.len(); + self.hdr.extend_from_slice(payload); + // `pes::parse` only succeeds once the whole header (`header_len` bytes) is buffered + if let Some(h) = pes::parse(&self.hdr) { + self.waiting = false; + let skip = h.header_len.saturating_sub(before).min(payload.len()); + return (Some(h), &payload[skip..]); + } + if self.hdr.len() > 1024 || (self.hdr.len() >= 6 && !(self.hdr[0] == 0 && self.hdr[1] == 0 && self.hdr[2] == 1)) { + // not a PES packet after all: drop until the next unit start + self.waiting = false; + self.dropping = true; + self.hdr.clear(); + return (None, &[]); + } + (None, &[]) + } +} + +/// PSI section reassembly for one PID. +#[derive(Default)] +struct Psi { + buf: Vec, +} + +impl Psi { + /// Feed a packet payload; returns completed sections. + fn feed(&mut self, pusi: bool, payload: &[u8]) -> Vec> { + let mut out = Vec::new(); + if pusi { + let Some(&ptr) = payload.first() else { return out }; + let ptr = ptr as usize; + if !self.buf.is_empty() { + self.buf.extend_from_slice(payload.get(1..1 + ptr).unwrap_or(&[])); + self.drain(&mut out); + } + self.buf = payload.get(1 + ptr..).unwrap_or(&[]).to_vec(); + } else if !self.buf.is_empty() { + self.buf.extend_from_slice(payload); + } + self.drain(&mut out); + out + } + + fn drain(&mut self, out: &mut Vec>) { + while self.buf.len() >= 3 { + if self.buf[0] == 0xFF { + self.buf.clear(); + return; + } + let total = 3 + ((((self.buf[1] & 0x0F) as usize) << 8) | self.buf[2] as usize); + if self.buf.len() < total { + if total > 4096 { + self.buf.clear(); + } + return; + } + out.push(self.buf[..total].to_vec()); + self.buf.drain(..total); + } + } +} + +/// Elementary stream of the selected program. +struct EsState { + stream: Stream, + split: Splitter, + asm: PesAsm, + cc: Option, + dup: DupGuard, +} + +/// Map a PMT stream_type (and the ES descriptors) to a codec. `hdmv`: a Blu-ray / AVCHD stream +/// (registration descriptor "HDMV", or 192-byte packets). +pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { + let mut tags = Vec::new(); + let mut reg = None; + let mut i = 0; + while i + 2 <= desc.len() { + let (tag, len) = (desc[i], desc[i + 1] as usize); + let body = desc.get(i + 2..i + 2 + len).unwrap_or(&[]); + tags.push(tag); + if tag == 5 && body.len() >= 4 { + reg = Some([body[0], body[1], body[2], body[3]]); + } + i += 2 + len; + } + match stream_type { + 0x01 => Codec::Mpeg1Video, + 0x02 => Codec::Mpeg2Video, + 0x03 | 0x04 => Codec::MpegAudio, + 0x0F => Codec::AacAdts, + 0x11 => Codec::AacLatm, + 0x1B => Codec::H264, + 0x24 => Codec::Hevc, + 0x80 if hdmv => Codec::LpcmBluray, + 0x80 => Codec::Mpeg2Video, + 0x81 => Codec::Ac3, + 0x82 | 0x85 | 0x86 | 0xA2 if hdmv => Codec::Dts, + 0x83 if hdmv => Codec::TrueHd, + 0x84 | 0xA1 if hdmv => Codec::Eac3, + 0x87 => Codec::Eac3, + 0x90 if hdmv => Codec::Subtitle("PGS subtitles"), + 0x92 if hdmv => Codec::Subtitle("Text subtitles"), + 0x06 => { + if tags.contains(&0x6A) || reg == Some(*b"AC-3") { + Codec::Ac3 + } else if tags.contains(&0x7A) || reg == Some(*b"EAC3") { + Codec::Eac3 + } else if tags.contains(&0x7B) || matches!(reg, Some([b'D', b'T', b'S', _])) { + Codec::Dts + } else if tags.contains(&0x59) { + Codec::Subtitle("DVB subtitles") + } else if tags.contains(&0x56) { + Codec::Subtitle("Teletext") + } else { + Codec::Unknown(6) + } + } + t => Codec::Unknown(t), + } +} + +fn language(desc: &[u8]) -> Option { + let mut i = 0; + while i + 2 <= desc.len() { + let (tag, len) = (desc[i], desc[i + 1] as usize); + if tag == 0x0A && len >= 3 { + let b = desc.get(i + 2..i + 5)?; + // ISO 639-2 codes are three ASCII letters; anything else is garbage + return b.iter().all(u8::is_ascii_alphabetic).then(|| b.to_ascii_lowercase().iter().map(|&c| c as char).collect()); + } + i += 2 + len; + } + None +} + +/// First file offset at which `packet_size`-byte packets line up (sync byte at `sync_offset`). +fn first_sync(head: &[u8], packet_size: usize, sync_offset: usize) -> Option { + (0..packet_size.min(head.len())).find(|&s| (0..5).all(|k| head.get(s + sync_offset + k * packet_size) == Some(&0x47))) +} + +/// Find where packets line up again, searching `block` from byte `from`: the first packet start +/// `i` whose sync byte and the next four packets' sync bytes are all 0x47. Returns `(i, false)` +/// when found. Returns `(i, true)` when the block ran out first: `i` is where to refill from (a +/// candidate whose five-packet window does not fit yet, or the last place a whole packet fits). +/// At the end of the file (`at_end`) a candidate is accepted with as many sync bytes as exist. +fn resync(block: &[u8], from: usize, packet_size: usize, sync_offset: usize, at_end: bool) -> (usize, bool) { + let mut i = from; + while i + packet_size <= block.len() { + if block.get(i + sync_offset) == Some(&0x47) { + let mut aligned = true; + let mut complete = true; + for k in 1..5 { + match block.get(i + sync_offset + k * packet_size) { + Some(&0x47) => {} + Some(_) => { + aligned = false; + break; + } + None => { + complete = false; + break; + } + } + } + if aligned { + return (i, !complete && !at_end); + } + } + i += 1; + } + (i, true) +} + +/// Register the elementary streams a (CRC-checked) PMT section announces and that are not yet known. +/// For a `later` PMT version, returns whether it changed a known stream's type or left one out. +fn add_pmt_streams(sec: &[u8], packet_size: usize, later: bool, es: &mut HashMap, order: &mut Vec) -> bool { + let mut changed = false; + let mut listed: Vec = Vec::new(); + let pinfo = (((sec[10] & 0x0F) as usize) << 8) | sec[11] as usize; + let prog_desc = sec.get(12..12 + pinfo).unwrap_or(&[]); + let hdmv = packet_size == 192 || prog_desc.windows(4).any(|w| w == b"HDMV"); + let mut i = 12 + pinfo; + let end = sec.len() - 4; + while i + 5 <= end { + let st = sec[i]; + let pid = (((sec[i + 1] & 0x1F) as u16) << 8) | sec[i + 2] as u16; + let ilen = (((sec[i + 3] & 0x0F) as usize) << 8) | sec[i + 4] as usize; + let desc = sec.get(i + 5..(i + 5 + ilen).min(end)).unwrap_or(&[]); + i += 5 + ilen; + listed.push(pid); + if let Some(old) = es.get(&pid) { + if later && old.stream.stream_type != st { + changed = true; + } + continue; + } + let mut codec = codec_of(st, desc, hdmv); + if codec == Codec::Unknown(6) && prog_desc.windows(4).any(|w| w == b"AC-3") { + codec = Codec::Ac3; + } + let stream = Stream { + id: StreamId::Pid(pid), + stream_type: st, + codec: codec.clone(), + language: language(desc), + units: Vec::new(), + lpcm: None, + pes_packets: 0, + skipped_bytes: 0, + }; + es.insert(pid, EsState { stream, split: Splitter::new(&codec), asm: PesAsm::default(), cc: None, dup: DupGuard::default() }); + order.push(pid); + } + changed || (later && es.keys().any(|p| !listed.contains(p))) +} + +/// The PSI state gathered while scanning: the selected program and its PMT, the PMT's PCR_PID +/// and whether a later PMT version added streams mid-stream. +#[derive(Default)] +struct PmtState { + pmt_pid: Option, + program: Option, + pmt: Psi, + pmt_version: Option, + pcr_pid: Option, + pmt_changed: bool, +} + +/// One program clock across every PCR_PID that is active in packet order. Until the first PMT +/// names the clock, each PID carrying a PCR keeps its own candidate (a fixed-size min/max, so at +/// most one per 13-bit PID); the named PID's candidate becomes the clock. Without a PMT, the first +/// PID carrying a PCR stands in. +#[derive(Default)] +struct ProgramClock { + clock: ClockRange, + candidates: HashMap, + first_pid: Option, +} + +impl ProgramClock { + /// A PCR on `pid`, with the PMT's PCR_PID so far. + fn push(&mut self, pcr_pid: Option, pid: u16, pcr: i64) { + match pcr_pid { + Some(p) if p == pid => self.clock.push(pcr), + Some(_) => {} + None => { + self.first_pid.get_or_insert(pid); + self.candidates.entry(pid).or_default().push(pcr); + } + } + } + + /// The first PMT names `pid`: the PCRs it carried before count, the other candidates go + /// (0x1fff, "no PCR PID", has none). + fn named(&mut self, pid: u16) { + self.clock = self.candidates.remove(&pid).unwrap_or_default(); + self.candidates = HashMap::new(); + } + + fn range(&self, pcr_pid: Option) -> Option<(i64, i64)> { + match (pcr_pid, self.first_pid) { + (None, Some(pid)) => self.candidates.get(&pid).and_then(ClockRange::range), + _ => self.clock.range(), + } + } +} + +/// Feed one PAT section stream: the first program's PMT PID is chosen; later PAT repeats +/// cannot change it. +fn feed_pat(pk: &Packet<'_>, pat: &mut Psi, pmt: &mut PmtState, crc_errors: &mut u64) { + for sec in pat.feed(pk.pusi, pk.payload) { + if sec.len() < 12 || sec[0] != 0 { + continue; + } + if sec[5] & 1 == 0 { + // not yet applicable (current_next_indicator 0) + continue; + } + if crc32_mpeg(&sec) != 0 { + *crc_errors += 1; + continue; + } + let body = &sec[8..sec.len() - 4]; + for e in body.as_chunks::<4>().0 { + let num = u16::from_be_bytes([e[0], e[1]]); + let pid = (((e[2] & 0x1F) as u16) << 8) | e[3] as u16; + if num != 0 && pmt.pmt_pid.is_none() { + pmt.pmt_pid = Some(pid); + pmt.program = Some(num); + } + } + } +} + +/// Feed one PMT section stream: the PMT's PCR_PID becomes the file clock and new PIDs are +/// registered; a later PMT version may only add PIDs, existing streams are never re-mapped or +/// dropped. +fn feed_pmt<'a>(pk: &Packet<'a>, pmt: &mut PmtState, packet_size: usize, es: &mut HashMap, order: &mut Vec, crc_errors: &mut u64) { + for sec in pmt.pmt.feed(pk.pusi, pk.payload) { + if sec.len() < 16 || sec[0] != 2 { + continue; + } + // current_next_indicator 0: not yet applicable; a PMT is one section (0 of 0) + if sec[5] & 1 == 0 || sec[6] != 0 || sec[7] != 0 { + continue; + } + if Some(u16::from_be_bytes([sec[3], sec[4]])) != pmt.program { + continue; + } + if crc32_mpeg(&sec) != 0 { + *crc_errors += 1; + continue; + } + let version = (sec[5] >> 1) & 0x1F; + if pmt.pmt_version == Some(version) { + // a repeat of the PMT already used: no need to check it again + continue; + } + let later = pmt.pmt_version.is_some(); + pmt.pmt_version = Some(version); + pmt.pcr_pid = Some((((sec[8] & 0x1F) as u16) << 8) | sec[9] as u16); + if add_pmt_streams(&sec, packet_size, later, es, order) { + pmt.pmt_changed = true; + } + } +} + +pub(crate) fn scan(src: &S, packet_size: usize, sync_offset: usize) -> Result { + let len = src.len(); + let mut head = vec![0u8; packet_size * 8]; + let n = read_some(src, 0, &mut head)?; + let mut off = first_sync(&head[..n], packet_size, sync_offset).ok_or(Error::NotMpeg)? as u64; + let mut warnings: Vec = Vec::new(); + let mut pat = Psi::default(); + let mut pmt = PmtState::default(); + let mut es: HashMap = HashMap::new(); + let mut order: Vec = Vec::new(); + // one timestamp unwrapper for the program: its streams share one clock, so a stream whose + // first timestamp lies just after the 33-bit wrap stays in step with one just before it + let mut unwrap = Unwrap::default(); + let mut pcr_clock = ProgramClock::default(); + let (mut lost_sync, mut cc_errors, mut crc_errors) = (0u64, 0u64, 0u64); + let (mut tei_dropped, mut scrambled, mut duplicates) = (0u64, 0u64, 0u64); + const BLOCK: usize = 4096; + let mut block = vec![0u8; BLOCK * packet_size]; + let mut bad_adaptation = 0u64; + while off + packet_size as u64 <= len { + let got = read_some(src, off, &mut block)?; + if got < packet_size { + break; + } + let at_end = off + got as u64 >= len; + // `p`: byte index of the next packet in `block`. Packets are parsed in place; a lost + // sync is repaired inside the loaded block, and the block is refilled from the file + // (at `off + p`) only when it is used up, so the bytes read stay close to the file size. + let mut p = 0usize; + while p + packet_size <= got { + let pos = off + p as u64; + let raw = &block[p..p + packet_size]; + let (tei, is_scrambled) = skip_flags(&raw[sync_offset..]); + if tei { + // transport_error_indicator: the payload (and the header) cannot be trusted + tei_dropped += 1; + p += packet_size; + continue; + } + let pk = match packet(&raw[sync_offset..]) { + Ok(pk) => pk, + Err(Bad::Adaptation) => { + // the packet grid is intact: this packet just has no usable payload + bad_adaptation += 1; + p += packet_size; + continue; + } + Err(Bad::Sync) => { + lost_sync += 1; + let (next, exhausted) = resync(&block[..got], p + 1, packet_size, sync_offset, at_end); + p = next; + if exhausted { + break; + } + continue; + } + }; + p += packet_size; + if let Some(pcr) = pk.pcr { + pcr_clock.push(pmt.pcr_pid, pk.pid, pcr); + } + if is_scrambled { + // encrypted payload is noise to the splitter; keep the counter in step + scrambled += 1; + if let Some(e) = es.get_mut(&pk.pid) + && pk.has_payload + { + e.cc = Some(pk.cc); + } + continue; + } + if pk.pid == 0 { + feed_pat(&pk, &mut pat, &mut pmt, &mut crc_errors); + continue; + } + if Some(pk.pid) == pmt.pmt_pid { + let had_pcr_pid = pmt.pcr_pid.is_some(); + feed_pmt(&pk, &mut pmt, packet_size, &mut es, &mut order, &mut crc_errors); + if !had_pcr_pid && let Some(pid) = pmt.pcr_pid { + pcr_clock.named(pid); + } + continue; + } + let Some(e) = es.get_mut(&pk.pid) else { continue }; + if e.dup.is_dup(&pk) { + duplicates += 1; + continue; + } + if pk.has_payload { + if let Some(prev) = e.cc + && !pk.discontinuity + && pk.cc != (prev + 1) & 15 + && pk.cc != prev + { + cc_errors += 1; + } + e.cc = Some(pk.cc); + } + let (hdr, bytes) = e.asm.packet(pk.pusi, pk.payload); + if let Some(h) = hdr { + e.stream.pes_packets += 1; + let pts = h.pts.map(|t| unwrap.unwrap(t)); + let dts = h.dts.map(|t| unwrap.unwrap(t)); + e.split.pes_start(pts, dts); + } + e.split.feed(pos, bytes); + } + // `p >= 1` here (the loop ran at least once or `resync` moved past the failed packet) + off += p.max(1) as u64; + } + if lost_sync > 0 { + warnings.push(format!("lost packet sync {lost_sync} time(s)")); + } + if bad_adaptation > 0 { + warnings.push(format!("{bad_adaptation} packet(s) with an invalid adaptation field")); + } + if cc_errors > 0 { + warnings.push(format!("{cc_errors} continuity counter error(s)")); + } + if tei_dropped > 0 { + warnings.push(format!("{tei_dropped} packet(s) with the transport error indicator dropped")); + } + if scrambled > 0 { + warnings.push(format!("{scrambled} scrambled packet(s) skipped")); + } + if duplicates > 0 { + warnings.push(format!("{duplicates} duplicate packet(s) dropped")); + } + if pmt.pmt_changed { + warnings.push("program map table changed mid-stream; new streams were added, changes to or removal of known ones ignored".into()); + } + if crc_errors > 0 { + warnings.push(format!("{crc_errors} PSI section(s) with bad CRC")); + } + if pmt.pmt_pid.is_none() { + warnings.push("no program association table".into()); + } + let mut streams = Vec::new(); + for pid in order { + let Some(mut e) = es.remove(&pid) else { continue }; + e.split.finish(); + e.stream.units = std::mem::take(&mut e.split.units); + e.stream.skipped_bytes = e.split.skipped; + if e.split.truncated { + warnings.push(format!("PID {pid}: more than {} access units, the rest are not indexed", super::es::MAX_UNITS)); + } + streams.push(e.stream); + } + let pcr_range = pcr_clock.range(pmt.pcr_pid); + Ok(File { format: Format::Ts { packet_size, sync_offset }, streams, program: pmt.program, pcr_range, warnings }) +} + +/// Collect unit `u` of stream `st`: from the packet at `u.pos`, the PID's elementary-stream bytes. +pub(crate) fn read(src: &S, packet_size: usize, sync_offset: usize, st: &Stream, u: &Unit, out: &mut Vec) -> Result<()> { + let StreamId::Pid(pid) = st.id else { return Err(Error::Invalid("not a TS stream".into())) }; + let need = u.size as usize; + let mut skip = u.offset as usize; + let mut off = u.pos; + let mut asm = PesAsm::default(); + let mut dup = DupGuard::default(); + let mut first = true; + let mut block = vec![0u8; 512 * packet_size]; + while out.len() < need { + let got = read_some(src, off, &mut block)?; + let whole = got / packet_size; + if whole == 0 { + break; + } + for k in 0..whole { + let raw = &block[k * packet_size..(k + 1) * packet_size]; + if skip_flags(&raw[sync_offset..]).0 { + continue; + } + let pk = match packet(&raw[sync_offset..]) { + Ok(pk) => pk, + Err(Bad::Sync) => return Ok(()), + Err(Bad::Adaptation) => continue, + }; + if pk.pid != pid || skip_flags(&raw[sync_offset..]).1 || dup.is_dup(&pk) { + continue; + } + // a unit starting in a PES packet's first packet: the header is skipped + let (_, bytes) = if first && !pk.pusi { (None, pk.payload) } else { asm.packet(pk.pusi, pk.payload) }; + first = false; + let bytes = if skip > 0 { + let s = skip.min(bytes.len()); + skip -= s; + &bytes[s..] + } else { + bytes + }; + let take = bytes.len().min(need - out.len()); + out.extend_from_slice(&bytes[..take]); + if out.len() >= need { + return Ok(()); + } + } + off += (whole * packet_size) as u64; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A unit start that never completes a PES header (MPEG-1 syntax, stuffing without end) is + /// given up after 1024 bytes: the bytes are not kept, and the next unit start is read again. + #[test] + fn a_pes_header_that_never_ends_is_not_buffered_past_the_limit() { + let mut asm = PesAsm::default(); + let mut first = vec![0, 0, 1, 0xC0, 0, 0]; + first.resize(184, 0xFF); + assert_eq!(asm.packet(true, &first), (None, &[][..])); + let stuffing = [0xFFu8; 184]; + for k in 0..200 { + assert_eq!(asm.packet(false, &stuffing), (None, &[][..]), "packet {k}"); + assert!(asm.hdr.len() <= 1024 + 184, "{} header bytes buffered", asm.hdr.len()); + } + assert!(asm.dropping && asm.hdr.is_empty()); + let (h, es) = asm.packet(true, &[0, 0, 1, 0xC0, 0, 0, 0x80, 0, 0, 0xAA, 0xBB]); + assert_eq!((h.map(|h| h.header_len), es), (Some(9), &[0xAA, 0xBB][..])); + } +} + +#[cfg(test)] +mod dup_tests { + use super::*; + + #[test] + fn a_discontinuity_packet_is_never_a_duplicate() { + let payload = [7u8; 20]; + let pk = |discontinuity| Packet { pusi: true, pid: 0x100, cc: 3, has_payload: true, discontinuity, pcr: None, payload: &payload }; + let mut g = DupGuard::default(); + assert!(!g.is_dup(&pk(false))); + assert!(!g.is_dup(&pk(true)), "same counter and payload, but the stream restarts here"); + assert!(g.is_dup(&pk(false)), "the discontinuity packet is the new reference"); + } + + #[test] + fn an_adaptation_only_discontinuity_resets_the_duplicate_history() { + let payload = [7u8; 20]; + let pk = |has_payload, discontinuity| Packet { + pusi: true, + pid: 0x100, + cc: 3, + has_payload, + discontinuity, + pcr: None, + payload: if has_payload { &payload } else { &[] }, + }; + let mut g = DupGuard::default(); + assert!(!g.is_dup(&pk(true, false))); + assert!(!g.is_dup(&pk(false, true)), "adaptation-only packets are never dropped"); + assert!(!g.is_dup(&pk(true, false)), "payload A with CC=3 after the restart is new"); + assert!(g.is_dup(&pk(true, false)), "a real repeat is still dropped"); + } +} diff --git a/crates/media/src/mpegts/work_tests.rs b/crates/media/src/mpegts/work_tests.rs new file mode 100644 index 000000000..d92aca42a --- /dev/null +++ b/crates/media/src/mpegts/work_tests.rs @@ -0,0 +1,115 @@ +//! Equality and counting tests for the redundant-work removals: the old implementation is kept +//! here as the reference, the new one must give the same results. + +use super::*; + +/// The bitwise CRC-32 that `ts::crc32_mpeg` replaced. +fn crc32_bitwise(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= (b as u32) << 24; + for _ in 0..8 { + crc = if crc & 0x8000_0000 != 0 { (crc << 1) ^ 0x04C1_1DB7 } else { crc << 1 }; + } + } + crc +} + +/// Deterministic xorshift bytes. +fn noise(seed: u32, n: usize) -> Vec { + let mut x = seed | 1; + (0..n) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + (x >> 8) as u8 + }) + .collect() +} + +#[test] +fn table_crc_equals_the_bitwise_crc() { + // the standard check value of CRC-32/MPEG-2 + assert_eq!(ts::crc32_mpeg(b"123456789"), 0x0376_E6E7); + assert_eq!(ts::crc32_mpeg(&[]), 0xFFFF_FFFF); + for b in 0..=255u8 { + assert_eq!(ts::crc32_mpeg(&[b]), crc32_bitwise(&[b])); + } + for n in [0usize, 1, 2, 3, 4, 5, 15, 16, 17, 183, 184, 1023, 1024, 4096] { + for seed in 1..6u32 { + let d = noise(seed * 7919 + n as u32, n); + assert_eq!(ts::crc32_mpeg(&d), crc32_bitwise(&d), "len {n} seed {seed}"); + } + } + // a section followed by its own CRC checks to zero + let mut sec = noise(5, 40); + let crc = ts::crc32_mpeg(&sec); + sec.extend(crc.to_be_bytes()); + assert_eq!(ts::crc32_mpeg(&sec), 0); +} + +/// MPEG-1 layer II frame, 48 kHz 192 kb/s (576 bytes), distinct per `k` and `salt`. +fn mp2_frame(k: usize, salt: u8) -> Vec { + let mut v = vec![0xFF, 0xFD, 0xA4, 0x00]; + v.extend((0..572).map(|i| (i as u8) ^ (k as u8) ^ salt)); + v +} + +fn pes_packet(stream_id: u8, payload: &[u8]) -> Vec { + let len = 3 + payload.len(); + let mut v = vec![0, 0, 1, stream_id, (len >> 8) as u8, len as u8, 0x80, 0, 0]; + v.extend_from_slice(payload); + v +} + +/// Two audio streams interleaved in maximal PES packets over more than three window refills, +/// with a pack header per PES packet; MPEG-2 or MPEG-1 pack headers. +pub(super) fn big_program_stream(mpeg1: bool, frames: usize) -> (Vec, Vec>, Vec>) { + let a: Vec> = (0..frames).map(|k| mp2_frame(k, 0)).collect(); + let b: Vec> = (0..frames).map(|k| mp2_frame(k, 0x55)).collect(); + let (ea, eb) = (a.concat(), b.concat()); + let mut out = Vec::new(); + for (ca, cb) in ea.chunks(60_000).zip(eb.chunks(60_000)) { + for (id, chunk) in [(0xC0, ca), (0xC1, cb)] { + if mpeg1 { + out.extend([0, 0, 1, 0xBA, 0x21, 0, 1, 0, 1, 0x80, 0, 1]); + } else { + out.extend([0, 0, 1, 0xBA, 0x44, 0, 4, 0, 4, 1, 1, 0x89, 0xC3, 0xF8]); + } + out.extend(pes_packet(id, chunk)); + } + } + out.extend([0, 0, 1, 0xB9]); + (out, a, b) +} + +#[test] +fn program_stream_with_large_pes_packets_gives_back_every_frame() { + for mpeg1 in [false, true] { + let (data, a, b) = big_program_stream(mpeg1, 2000); // about 1.2 MB per stream + assert!(data.len() > 2 << 20, "more than the 1 MiB window twice"); + let f = open(&data).unwrap(); + assert_eq!(f.format, Format::Ps { mpeg1 }); + assert_eq!(f.streams.len(), 2); + for (s, frames) in f.streams.iter().zip([&a, &b]) { + assert_eq!(s.units.len(), frames.len()); + // a read refills a 1 MiB window: every seventh unit and the last ones keep a debug build quick + for (i, fr) in frames.iter().enumerate().filter(|(i, _)| i % 7 == 0 || i + 4 > frames.len()) { + assert_eq!(&f.read_unit(&data, f.streams.iter().position(|x| std::ptr::eq(x, s)).unwrap(), i).unwrap(), fr, "mpeg1 {mpeg1} unit {i}"); + } + } + // cut inside the last packets: never panics, and the units before the cut are intact + for cut in [data.len() - 1, data.len() - 4, data.len() - 30_000, data.len() - 61_000, 100_000, 1 << 20] { + let d = &data[..cut]; + let Ok(f) = open(d) else { continue }; + for (si, frames) in [&a, &b].into_iter().enumerate() { + let Some(s) = f.streams.get(si) else { continue }; + let n = s.units.len().saturating_sub(1); + for (i, frame) in frames.iter().enumerate().take(n).filter(|(i, _)| i % 61 == 0 || i + 8 > n) { + assert_eq!(&f.read_unit(d, si, i).unwrap(), frame, "cut {cut} stream {si} unit {i}"); + } + } + } + } +} diff --git a/crates/media/src/mxf/essence.rs b/crates/media/src/mxf/essence.rs index bf6caa9b5..27f893dc5 100644 --- a/crates/media/src/mxf/essence.rs +++ b/crates/media/src/mxf/essence.rs @@ -148,6 +148,9 @@ pub struct PictureInfo { pub display_height: u32, /// 0 full frame, 1 separate fields, 2 single field, 3 mixed fields, 4 segmented frame. pub frame_layout: u8, + /// The temporally first field of an interlaced layout: 1 (field 1, the default) or 2; 0 when + /// the descriptor does not say. + pub field_dominance: u8, /// Display aspect ratio of the whole image. pub aspect_ratio: Rational, pub component_depth: u32, @@ -178,6 +181,20 @@ impl PictureInfo { let d = self.component_depth; d > 0 && self.black_ref_level == Some(0) && self.white_ref_level == Some((1u32 << d.min(31)) - 1) } + /// The ITU-T H.273 code points its colour labels name, as (colour primaries, transfer + /// characteristics, matrix coefficients), for the labels the writer uses: Rec. 709 and BT.2020 + /// primaries and coding equations, and the Rec. 709, SMPTE ST 2084 (PQ) and ARIB STD-B67 (HLG) + /// transfers. A missing label, or one not among these, is `None`. + pub fn color_codes(&self) -> (Option, Option, Option) { + use crate::mxf::write::labels::{CE_709, CE_2020, CP_709, CP_2020, TC_709, TC_HLG, TC_PQ}; + let code = + |label: &Option