diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000000..2408084cf9 --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,6 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json +reviews: + auto_review: + # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them. + ignore_usernames: + - "dependabot[bot]" diff --git a/.github/workflows/ai-core.yml b/.github/workflows/ai-core.yml index 4733eaee8e..5f2204f7c2 100644 --- a/.github/workflows/ai-core.yml +++ b/.github/workflows/ai-core.yml @@ -21,7 +21,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy targets: wasm32-unknown-unknown diff --git a/.github/workflows/atomic.yml b/.github/workflows/atomic.yml index 25423780e3..d2112768d7 100644 --- a/.github/workflows/atomic.yml +++ b/.github/workflows/atomic.yml @@ -21,7 +21,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy - name: Install ACL tools diff --git a/.github/workflows/docpath.yml b/.github/workflows/docpath.yml index 557f00f52d..3aaaa97ed5 100644 --- a/.github/workflows/docpath.yml +++ b/.github/workflows/docpath.yml @@ -21,7 +21,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy - run: cargo fmt --check diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml index d7e6f5b5af..a973e37f45 100644 --- a/.github/workflows/i18n.yml +++ b/.github/workflows/i18n.yml @@ -21,7 +21,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy - run: cargo fmt --check diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml new file mode 100644 index 0000000000..272abab88b --- /dev/null +++ b/.github/workflows/media.yml @@ -0,0 +1,61 @@ +name: Shared media + +on: + push: + branches: [main] + paths: ["crates/media/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + pull_request: + paths: ["crates/media/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: shared-media-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + timeout-minutes: 10 + name: Media lint, feature sets, WASM + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + with: + components: rustfmt, clippy + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: craft-media-lint + - run: cargo fmt -p craft-media --check + - run: cargo clippy -p craft-media --all-targets --locked --no-default-features -- -D warnings + - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features bitstream -- -D warnings + - run: cargo clippy -p craft-media --all-targets --locked -- -D warnings + - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features matroska -- -D warnings + - run: cargo clippy -p craft-media --all-targets --locked --all-features -- -D warnings + - run: cargo check -p craft-media --all-features --locked --target wasm32-unknown-unknown + test: + timeout-minutes: 15 + name: Media tests with ffmpeg oracles + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: craft-media-test + - name: Build tests while installing ffmpeg + run: | + # The man-db index rebuild after dpkg is slow on hosted runners. + sudo rm -f /var/lib/man-db/auto-update + (sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends ffmpeg) > "$RUNNER_TEMP/apt.log" 2>&1 & + apt=$! + cargo test -p craft-media --all-features --locked --no-run + wait "$apt" || { cat "$RUNNER_TEMP/apt.log"; exit 1; } + ffmpeg -hide_banner -version | sed -n 1p + - run: cargo test -p craft-media --all-features --locked + env: + CRAFT_MEDIA_REQUIRE_ORACLES: "1" + CRAFT_MEDIA_FIXTURES_DIR: ${{ runner.temp }}/media-fixtures diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml index e0d9fcf1be..c2f8c3f60f 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -27,10 +27,10 @@ jobs: RUSTFLAGS: --cfg craft_pdf_unicode_fixtures steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: craft-pdf - uses: actions/setup-python@v5 @@ -51,8 +51,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: craft-pdf-backends - run: bash scripts/test-pdf-backends.sh @@ -64,10 +64,10 @@ jobs: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: craft-pdf-wasm - uses: actions/setup-python@v5 diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index ea0696e3fd..270ac75e8f 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -18,7 +18,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy - run: cargo fmt --check diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml new file mode 100644 index 0000000000..ecee45a6d8 --- /dev/null +++ b/.github/workflows/sonarcloud.yml @@ -0,0 +1,20 @@ +name: SonarCloud + +on: + push: + branches: [main] + pull_request: + types: [opened, synchronize, reopened] + +permissions: + contents: read + +concurrency: + group: sonarcloud-${{ github.ref }} + cancel-in-progress: true + +jobs: + sonarcloud: + # Tracked at @main so org-wide CI improvements propagate without PR churn. + uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + secrets: inherit diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 79845a4498..3db33478d3 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -32,10 +32,10 @@ jobs: sudo apt-get update sudo apt-get install -y mesa-vulkan-drivers libvulkan1 echo 'WGPU_BACKEND=vulkan' >> "$GITHUB_ENV" - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: craft-ui - run: cargo fmt --check @@ -49,10 +49,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: craft-ui-wasm - run: cargo check -p craft-ui --all-features --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/window.yml b/.github/workflows/window.yml new file mode 100644 index 0000000000..80aa86b68b --- /dev/null +++ b/.github/workflows/window.yml @@ -0,0 +1,36 @@ +name: Window decorations + +on: + workflow_dispatch: + push: + branches: [main] + paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] + pull_request: + paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] + +permissions: + contents: read + +jobs: + window: + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + with: + # The token isn't needed after checkout; cargo runs build scripts and proc macros from + # dependencies, so don't leave it in .git/config for that third-party code to read. + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + with: + components: rustfmt, clippy + - run: cargo fmt --check + # Default (no egui) and the egui feature both build and lint cleanly. + - run: cargo clippy -p craft-window --all-targets --locked -- -D warnings + - run: cargo clippy -p craft-window --all-targets --locked --features egui -- -D warnings + - run: cargo test -p craft-window --locked -- --nocapture + - run: cargo test -p craft-window --locked --features egui -- --nocapture diff --git a/Cargo.lock b/Cargo.lock index 69b0144257..3c57880256 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -135,6 +135,126 @@ dependencies = [ "libloading", ] +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.5", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.5", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.5", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + [[package]] name = "async-trait" version = "0.1.92" @@ -206,7 +326,16 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" dependencies = [ - "bit-vec", + "bit-vec 0.9.1", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.1", ] [[package]] @@ -215,6 +344,16 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit-vec" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -254,6 +393,43 @@ dependencies = [ "objc2 0.6.5", ] +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "brotli" version = "8.0.4" @@ -633,6 +809,15 @@ dependencies = [ "tempfile", ] +[[package]] +name = "craft-media" +version = "0.1.0" +dependencies = [ + "proptest", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -649,6 +834,23 @@ dependencies = [ "wasm-bindgen-test", ] +[[package]] +name = "craft-platform" +version = "0.1.0" +dependencies = [ + "async-channel", + "async-io", + "async-process", + "egui", + "futures-lite", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test", + "web-sys", + "zbus", +] + [[package]] name = "craft-print" version = "0.1.0" @@ -695,6 +897,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-window" +version = "0.1.0" +dependencies = [ + "egui", + "wayland-client", +] + [[package]] name = "craft-winprint-gdi" version = "0.1.0" @@ -1068,6 +1278,12 @@ dependencies = [ "simdutf8", ] +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + [[package]] name = "enum-map" version = "2.7.3" @@ -1088,6 +1304,27 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "epaint" version = "0.36.2" @@ -1150,6 +1387,26 @@ dependencies = [ "num-traits", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -1335,6 +1592,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-sink" version = "0.3.34" @@ -1933,7 +2203,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" dependencies = [ "byteorder-lite", - "quick-error", + "quick-error 2.0.1", ] [[package]] @@ -2254,6 +2524,15 @@ dependencies = [ "libc", ] +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "mime" version = "0.3.17" @@ -2342,7 +2621,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" dependencies = [ "arrayvec", - "bit-set", + "bit-set 0.10.0", "bitflags 2.13.2", "cfg-if", "cfg_aliases", @@ -2803,6 +3082,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -2960,6 +3255,17 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -3105,12 +3411,38 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set 0.11.1", + "bit-vec 0.10.1", + "bitflags 2.13.2", + "chacha20", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + [[package]] name = "pxfm" version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quick-error" version = "2.0.1" @@ -3230,6 +3562,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -3343,6 +3684,12 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "renderdoc-sys" version = "1.1.0" @@ -3563,6 +3910,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + [[package]] name = "rustybuzz" version = "0.20.1" @@ -3712,6 +4071,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "serde_spanned" version = "1.1.2" @@ -3761,6 +4131,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "signature" version = "2.2.0" @@ -4342,7 +4722,7 @@ dependencies = [ "fax", "flate2", "half", - "quick-error", + "quick-error 2.0.1", "weezl", "zune-jpeg", ] @@ -4619,6 +4999,23 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unic-langid" version = "0.9.6" @@ -4757,6 +5154,11 @@ name = "uuid" version = "1.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] [[package]] name = "vello_common" @@ -4838,6 +5240,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "walkdir" version = "2.5.0" @@ -5152,8 +5563,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" dependencies = [ "arrayvec", - "bit-set", - "bit-vec", + "bit-set 0.10.0", + "bit-vec 0.9.1", "bitflags 2.13.2", "bytemuck", "cfg_aliases", @@ -5225,7 +5636,7 @@ dependencies = [ "android_system_properties", "arrayvec", "ash", - "bit-set", + "bit-set 0.10.0", "bitflags 2.13.2", "block2 0.6.2", "bytemuck", @@ -5812,6 +6223,76 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.5", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.6", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + [[package]] name = "zerocopy" version = "0.8.62" @@ -5933,3 +6414,44 @@ checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ "zune-core", ] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.6", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.6", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml index c9def5c7f2..5be2b27bdb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] # internal: add each crate here as `craft- = { path = "crates/" }` +craft-platform = { path = "crates/platform" } craft-ai-core = { path = "crates/ai-core" } craft-pdf = { path = "crates/pdf", version = "=0.1.0" } krilla = { version = "=0.8.2", default-features = false, features = ["raster-images"] } @@ -25,14 +26,17 @@ craft-cms = { path = "crates/cms" } craft-docpath = { path = "crates/docpath" } craft-i18n = { path = "crates/i18n" } craft-keymap = { path = "crates/keymap" } +craft-media = { path = "crates/media" } craft-print = { path = "crates/print" } craft-quit = { path = "crates/quit" } craft-settings = { path = "crates/settings" } craft-ui = { path = "crates/ui" } +craft-window = { path = "crates/window" } egui = { version = "0.36", default-features = false } rayon = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" +proptest = "1" [workspace.lints.rust] unsafe_code = "forbid" diff --git a/NOTICE b/NOTICE index 9467671f33..38a65fcfbe 100644 --- a/NOTICE +++ b/NOTICE @@ -106,3 +106,20 @@ Compact ICC Profiles by Clinton Ingram (CC0-1.0), and dependency CMaps (BSD-3-Cl Their licences and per-file hashes are retained in vendor/hayro-interpret/assets, licenses/pdf-backend and ATTRIBUTION.md. These are existing reader dependency assets; applications retain their own document-font selection and licensing policy. + +Platform lifecycle source provenance + +The optional crates/platform services adapt the preserved local platform candidate +9b135779a1e7136438a217c18afe1693ea23f1ab (dialog outcomes and browser resource ownership), +and current application implementations: +- PdfCraft crates/platform/src/desktop_theme.rs, a8cd797a917b1007544575c7280c9a0ce6a17e8f. +- CADCraft apps/cadcraft/src/desktop_theme.rs, 0cc66ad3066e71f2c3d4cacb7de905e79ba1c95b. +- ArtCraft Launcher apps/artcraft-launcher/src/system_theme.rs, f1676dfb41c226b5be490721f486ee6427419d80. +- Earlier PhotoCraft, FilmCraft and EffectCraft appearance services at revisions + 0c72d95425dece90ef9a1cceb49e3315c96e22d5, 794a25fc9ed2e3f6fab51a254625bc9b99a88015 + and 1b4d47f34f2b1c1b4a89f4b7348889def8fd648b respectively. +Sources: https://github.com/storytold/pdfcraft, https://github.com/storytold/cadcraft, +https://github.com/storytold/craft-launcher, https://github.com/storytold/photocraft, +https://github.com/storytold/filmcraft, https://github.com/storytold/effectcraft. +Copyright (c) 2026 ArtCraft Team and the respective application and craft-libs contributors. +All adapted source is licensed MIT OR Apache-2.0. diff --git a/README.md b/README.md index 0e2b540ffe..ea305fea08 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ Craft App Libraries =================== +Scanned by SonarCloud + This repo contains libraries used by the various Craft Apps. It's a Rust monorepo workspace, and the libraries can be included by any Craft Apps that need them. In the future this may grow to include non-Rust library code. @@ -23,6 +25,8 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = " = { git = "https://github.com/storytold/craft-libs", rev = " Vec { let mut kinds: Vec = self.items.iter().map(|i| i.kind).collect(); + if !self.param_names.is_empty() { + kinds.push(PayloadKind::Text); + } kinds.sort(); kinds.dedup(); kinds @@ -242,6 +246,17 @@ mod tests { assert!(ledger.needs_consent(&d, 0)); } + #[test] + fn parameters_alone_still_need_consent() { + let only_params = Request::new(CapabilityId::parse("image.inpaint").unwrap()).with_param("negative", "a private note".into()); + let d = disclosure_for(&only_params); + assert_eq!(d.kinds(), vec![PayloadKind::Text]); + let mut ledger = ConsentLedger::default(); + assert!(ledger.needs_consent(&d, 0)); + ledger.grant(&d); + assert!(!ledger.needs_consent(&d, 0)); + } + fn upscale_req() -> Request { Request::new(CapabilityId::parse("image.upscale").unwrap()).with_input(InputRole::Source, Payload::inline("image/png", vec![0; 10]).unwrap()) } diff --git a/crates/ai-core/src/secret.rs b/crates/ai-core/src/secret.rs index b6bb9c9433..0a40b834db 100644 --- a/crates/ai-core/src/secret.rs +++ b/crates/ai-core/src/secret.rs @@ -40,13 +40,32 @@ impl fmt::Display for SecretString { } /// Replaces every occurrence of each non-empty secret in `text` with `[redacted]`. +/// +/// Matches are found in `text` itself, never in the markers already written, so the output is at +/// most a fixed multiple of the input whatever the secrets are. Overlapping matches of different +/// secrets become one marker. pub fn redact(text: &str, secrets: &[&SecretString]) -> String { - let mut out = text.to_owned(); - for secret in secrets { - if !secret.is_empty() { - out = out.replace(secret.expose(), "[redacted]"); + const MARKER: &str = "[redacted]"; + let mut values: Vec<&str> = secrets.iter().map(|s| s.expose()).filter(|v| !v.is_empty()).collect(); + values.sort_unstable(); + values.dedup(); + let mut spans: Vec<(usize, usize)> = values.iter().flat_map(|v| text.match_indices(v).map(|(at, m)| (at, at + m.len()))).collect(); + spans.sort_unstable(); + let mut out = String::with_capacity(text.len()); + let mut done = 0; + let mut i = 0; + while i < spans.len() { + let (start, mut end) = spans[i]; + i += 1; + while i < spans.len() && spans[i].0 < end { + end = end.max(spans[i].1); + i += 1; } + out.push_str(&text[done..start]); + out.push_str(MARKER); + done = end; } + out.push_str(&text[done..]); out } @@ -69,6 +88,24 @@ mod tests { assert_eq!(out, "bad key [redacted] ([redacted])"); } + #[test] + fn redact_never_searches_its_own_markers() { + // Each secret matches the marker the one before it wrote; replacing in turn doubled the + // text for every secret. + let r = SecretString::new("r"); + let marker = SecretString::new("[redacted]"); + let secrets: Vec<&SecretString> = std::iter::once(&r).chain(std::iter::repeat_n(&marker, 64)).collect(); + assert_eq!(redact("rrrr", &secrets), "[redacted][redacted][redacted][redacted]"); + } + + #[test] + fn redact_merges_overlapping_secrets() { + let a = SecretString::new("abc"); + let b = SecretString::new("bcd"); + assert_eq!(redact("xabcdx", &[&a, &b]), "x[redacted]x"); + assert_eq!(redact("abcabc", &[&a]), "[redacted][redacted]"); + } + #[test] fn redact_ignores_empty_secret() { let s = SecretString::new(""); diff --git a/crates/ai-core/src/spec.rs b/crates/ai-core/src/spec.rs index 424ac90508..0712e26699 100644 --- a/crates/ai-core/src/spec.rs +++ b/crates/ai-core/src/spec.rs @@ -37,8 +37,11 @@ pub const SPEC_VERSION: u32 = 1; pub const MAX_SPEC_BYTES: usize = 32 * 1024; /// Most models one spec may offer. pub const MAX_MODELS: usize = 16; -/// Largest rendered or stored template (a body, serialized). +/// Largest stored template (a body, serialized). pub const MAX_TEMPLATE_BYTES: usize = 4 * 1024; +/// Most text one rendered template may hold, summed over its strings with every substitution made. +/// A slot may repeat, so this, not [`MAX_TEMPLATE_BYTES`], bounds what a prompt can grow to. +pub const MAX_RENDERED_BYTES: usize = 4 * 1024 * 1024; /// Deepest JSON pointer. pub const MAX_POINTER_DEPTH: usize = 8; /// Most entries in a status table. diff --git a/crates/ai-core/src/spec/template.rs b/crates/ai-core/src/spec/template.rs index d276ab610b..bc1d79b4c9 100644 --- a/crates/ai-core/src/spec/template.rs +++ b/crates/ai-core/src/spec/template.rs @@ -114,23 +114,40 @@ pub fn value_slots(template: &Value) -> Result, String> { Ok(out) } +/// Renders one string. Fails past [`MAX_RENDERED_BYTES`](crate::spec::MAX_RENDERED_BYTES). pub fn render_text(text: &str, values: &Values<'_>) -> Result { + let mut left = crate::spec::MAX_RENDERED_BYTES; + render_text_within(text, values, &mut left) +} + +/// Renders `text`, taking its length from `left`; a template that repeats a slot cannot outgrow it. +fn render_text_within(text: &str, values: &Values<'_>, left: &mut usize) -> Result { let mut out = String::new(); for piece in pieces(text)? { - match piece { - Piece::Text(t) => out.push_str(&t), - Piece::Slot(slot, name) => out.push_str(values.get(slot).ok_or_else(|| format!("{{{name}}} is not available in this call"))?), - } + let add = match &piece { + Piece::Text(t) => t.as_str(), + Piece::Slot(slot, name) => values.get(*slot).ok_or_else(|| format!("{{{name}}} is not available in this call"))?, + }; + *left = left.checked_sub(add.len()).ok_or_else(|| format!("a rendered template is at most {} bytes", crate::spec::MAX_RENDERED_BYTES))?; + out.push_str(add); } Ok(out) } -/// Renders every string value of `template`. Keys are never substituted. +/// Renders every string value of `template`. Keys are never substituted. All strings together +/// share one [`MAX_RENDERED_BYTES`](crate::spec::MAX_RENDERED_BYTES) budget. pub fn render_value(template: &Value, values: &Values<'_>) -> Result { + let mut left = crate::spec::MAX_RENDERED_BYTES; + render_value_within(template, values, &mut left) +} + +fn render_value_within(template: &Value, values: &Values<'_>, left: &mut usize) -> Result { Ok(match template { - Value::String(s) => Value::String(render_text(s, values)?), - Value::Array(items) => Value::Array(items.iter().map(|i| render_value(i, values)).collect::>()?), - Value::Object(map) => Value::Object(map.iter().map(|(k, v)| Ok((k.clone(), render_value(v, values)?))).collect::>()?), + Value::String(s) => Value::String(render_text_within(s, values, left)?), + Value::Array(items) => Value::Array(items.iter().map(|i| render_value_within(i, values, left)).collect::>()?), + Value::Object(map) => { + Value::Object(map.iter().map(|(k, v)| Ok((k.clone(), render_value_within(v, values, left)?))).collect::>()?) + } other => other.clone(), }) } diff --git a/crates/ai-core/tests/spec_template.rs b/crates/ai-core/tests/spec_template.rs index f5689f6722..8c7deeeded 100644 --- a/crates/ai-core/tests/spec_template.rs +++ b/crates/ai-core/tests/spec_template.rs @@ -65,3 +65,15 @@ fn a_slot_with_no_value_is_an_error_not_an_empty_string() { let why = render_text("/jobs/{job_id}", &v).unwrap_err(); assert!(why.contains("{job_id} is not available"), "{why}"); } + +#[test] +fn repeated_slots_share_one_rendered_budget() { + let prompt = "x".repeat(64 * 1024); + let v = Values { prompt: Some(&prompt), ..values() }; + let slots = vec![json!("{prompt}"); 16]; + assert!(render_value(&json!({ "a": slots }), &v).is_ok()); + let slots = vec![json!("{prompt}{prompt}{prompt}{prompt}"); 32]; + let why = render_value(&json!({ "a": slots }), &v).unwrap_err(); + assert!(why.contains("at most"), "{why}"); + assert!(render_text(&"{prompt}".repeat(128), &v).is_err()); +} diff --git a/crates/cms/src/clut.rs b/crates/cms/src/clut.rs index e551638d0c..dd0315c20f 100644 --- a/crates/cms/src/clut.rs +++ b/crates/cms/src/clut.rs @@ -223,15 +223,22 @@ impl Clut { } fn multilinear(&self, input: &[f32], out: &mut [f32]) { - let n = self.inputs; + // Only dimensions that sit between two grid points spread over corners. A singleton + // dimension, or an input on a node, takes its lower corner with weight 1, so a table of + // many such dimensions costs no more than the dimensions that actually interpolate. let mut base = 0usize; let mut r = [0.0f32; MAX_CHANNELS]; let mut s = [0usize; MAX_CHANNELS]; - for d in 0..n { - let (b, rr, ss) = self.locate(d, input[d]); + let mut n = 0; + for (d, &v) in input.iter().enumerate().take(self.inputs) { + let (b, rr, ss) = self.locate(d, v); base += b; - r[d] = rr; - s[d] = ss; + // `!= 0.0` keeps a NaN fraction, so a NaN input still gives a NaN result. + if ss > 0 && rr != 0.0 { + r[n] = rr; + s[n] = ss; + n += 1; + } } let o = self.outputs; out[..o].iter_mut().for_each(|v| *v = 0.0); @@ -309,4 +316,38 @@ mod tests { c.eval(&[0.5, 0.25], &mut o).unwrap(); assert!((o[0] - 0.75).abs() < 1e-6); } + + #[test] + fn a_nan_input_still_gives_nan() { + let c = Clut::sample(vec![2; 5], 1, |p, o| o[0] = p.iter().sum()).unwrap(); + let mut o = [0.0]; + c.eval_multilinear(&[0.5, f32::NAN, 0.5, 0.5, 0.5], &mut o).unwrap(); + assert!(o[0].is_nan(), "{o:?}"); + } + + #[test] + fn singleton_dimensions_do_not_multiply_corners() { + // Fifteen inputs, all but two on a single grid point: the result interpolates only those + // two, and matches the same table built with two inputs. + let mut grid = vec![1usize; 15]; + grid[3] = 2; + grid[9] = 3; + let wide = Clut::sample(grid, 2, |p, o| { + o[0] = p[3] * 0.5 + p[9] * 0.25; + o[1] = p[3] * p[9]; + }) + .unwrap(); + let narrow = Clut::sample(vec![2, 3], 2, |p, o| { + o[0] = p[0] * 0.5 + p[1] * 0.25; + o[1] = p[0] * p[1]; + }) + .unwrap(); + let mut input = [0.4f32; 15]; + input[3] = 0.3; + input[9] = 0.7; + let (mut a, mut b) = ([0.0; 2], [0.0; 2]); + wide.eval_multilinear(&input, &mut a).unwrap(); + narrow.eval_multilinear(&[0.3, 0.7], &mut b).unwrap(); + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "{a:?} {b:?}"); + } } diff --git a/crates/cms/src/curve.rs b/crates/cms/src/curve.rs index f50f2d6639..2ea74a91cd 100644 --- a/crates/cms/src/curve.rs +++ b/crates/cms/src/curve.rs @@ -85,6 +85,20 @@ impl Curve { } } + /// [`eval_inverse64`](Self::eval_inverse64) for many values. A table's flat ends are found + /// once here instead of on every call, so building an output table from a long, flat table + /// costs one scan of it, not one per entry. + pub fn inverse64_many(&self) -> impl Fn(f64) -> f64 + '_ { + let edges = match self { + Curve::Table(t) if t.len() >= 2 => Some((edge_index(t, true), edge_index(t, false))), + _ => None, + }; + move |y| match (self, edges) { + (Curve::Table(t), Some((first, last))) => table_inverse_with(t, y as f32, |start| if start { first } else { last }) as f64, + _ => self.eval_inverse64(y), + } + } + #[inline] pub fn eval_inverse(&self, y: f32) -> f32 { match self { @@ -240,6 +254,11 @@ fn table(t: &[f32], x: f32) -> f32 { /// Exact inverse of a piecewise-linear table (binary search), for increasing or decreasing tables. fn table_inverse(t: &[f32], y: f32) -> f32 { + table_inverse_with(t, y, |start| edge_index(t, start)) +} + +/// [`table_inverse`] with the flat-run ends from `edge` (see [`edge_index`]). +fn table_inverse_with(t: &[f32], y: f32, edge: impl Fn(bool) -> f32) -> f32 { let n = t.len(); if n < 2 { return y; @@ -248,10 +267,10 @@ fn table_inverse(t: &[f32], y: f32) -> f32 { let (lo_v, hi_v) = if increasing { (t[0], t[n - 1]) } else { (t[n - 1], t[0]) }; if y <= lo_v { // Flat start: choose the last index still at the lowest value. - return if increasing { edge_index(t, true) } else { edge_index(t, false) }; + return edge(increasing); } if y >= hi_v { - return if increasing { edge_index(t, false) } else { edge_index(t, true) }; + return edge(!increasing); } let (mut lo, mut hi) = (0usize, n - 1); while hi - lo > 1 { @@ -329,6 +348,23 @@ mod tests { assert!((dec.eval_inverse(0.25) - 0.75).abs() < 1e-6); } + #[test] + fn batch_inverse_matches_single_inverse() { + let mut flat = vec![0.25f32; 300]; + flat.extend((0..300).map(|i| 0.25 + i as f32 / 600.0)); + flat.extend([0.75f32; 300]); + for t in [flat.clone(), flat.iter().rev().copied().collect(), vec![0.5; 1000], Curve::Gamma(2.2).sample(256)] { + let c = Curve::Table(t); + let many = c.inverse64_many(); + for i in 0..=200 { + let y = i as f64 / 200.0; + assert_eq!(many(y), c.eval_inverse64(y), "{y}"); + } + } + let g = Curve::Gamma(2.2); + assert_eq!(g.inverse64_many()(0.3), g.eval_inverse64(0.3)); + } + #[test] fn hdr_and_negative_extension() { let c = srgb_trc(); diff --git a/crates/cms/src/transform.rs b/crates/cms/src/transform.rs index 1dc59e8271..7a8aeb0a86 100644 --- a/crates/cms/src/transform.rs +++ b/crates/cms/src/transform.rs @@ -150,10 +150,11 @@ impl Transform { let tables = cs .iter() .map(|c| { + let inverse = c.inverse64_many(); (0..OUT_TABLE) .map(|i| { let u = i as f64 / (OUT_TABLE - 1) as f64; - c.eval_inverse64(u * u * u * u).clamp(0.0, 1.0) as f32 + inverse(u * u * u * u).clamp(0.0, 1.0) as f32 }) .collect() }) diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml new file mode 100644 index 0000000000..dd1db2c68f --- /dev/null +++ b/crates/media/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "craft-media" +description = "Bit-level I/O and clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) demuxers and muxers." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = ["isobmff"] +bitstream = [] +isobmff = ["bitstream", "dep:thiserror"] +matroska = [] + +[dependencies] +thiserror = { workspace = true, optional = true } + +[dev-dependencies] +proptest = { workspace = true } +serde_json = { workspace = true } + +[[test]] +name = "fuzz" +required-features = ["isobmff"] + +[[test]] +name = "fuzz_matroska" +required-features = ["matroska"] + +[[test]] +name = "oracle_demux" +required-features = ["isobmff"] + +[[test]] +name = "oracle_matroska" +required-features = ["matroska"] + +[[test]] +name = "oracle_mux" +required-features = ["isobmff"] + +[[test]] +name = "roundtrip" +required-features = ["isobmff"] diff --git a/crates/media/README.md b/crates/media/README.md new file mode 100644 index 0000000000..f80b920dff --- /dev/null +++ b/crates/media/README.md @@ -0,0 +1,367 @@ +# craft-media + +Media containers and bit-level I/O for the Craft apps: an MSB-first bit reader and writer, and +clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) demuxers and muxers written +from the public specifications. No `unsafe`, no panics on malformed input, and it builds for +`wasm32-unknown-unknown`. The only dependency is `thiserror` (for `isobmff`). + +## Features + +| Feature | Module | Enables | +|---|---|---| +| `bitstream` | `craft_media::bitstream` | none | +| `isobmff` | `craft_media::isobmff` | `bitstream`, `thiserror` | +| `matroska` | `craft_media::matroska` | none | + +`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. The features are independent; `matroska` does not need the other two. + +```toml +craft-media = { git = "https://github.com/storytold/craft-libs", rev = "", features = ["matroska"] } +``` + +A crate that needs only bit I/O (a codec) uses: + +```toml +craft-media = { git = "https://github.com/storytold/craft-libs", rev = "", default-features = false, features = ["bitstream"] } +``` + +## Boundaries + +- In scope: bit-level reading and writing, and container demuxing and muxing (boxes, sample + tables, sample entries and codec configuration records). +- Out of scope for now: codecs (H.264, HEVC, ProRes, AAC and others). They stay in the apps. + Ogg and other containers can join later as their own features. + +## Origin and API + +The code comes from FilmCraft's `filmcraft-bitstream`, `filmcraft-isobmff` and +`filmcraft-matroska` crates at +[storytold/filmcraft@6c3948a](https://github.com/storytold/filmcraft/commit/6c3948a36c80e4996d924766ba7157eec4fca85e). +Every public item keeps its name, signature and behavior for valid input, so FilmCraft can turn +all three crates into re-exports (`pub use craft_media::isobmff::*;`). The differences: + +- `bitstream::BitReader::read_ue_plus` (from DeckCraft's copy) is new. +- `isobmff::boxes` is new: FilmCraft's private box iterator and byte reader, made public (see + [Box reader](#box-reader)). +- `BitReader::peek`, `BitReader::read_bits` and `BitWriter::write_bits` accept widths above 32 + without a debug assertion: `peek` and `read_bits` return the low 32 bits of the field (use + `read_bits_u64` for wide fields), and `write_bits` writes leading zero bits, at most 64 bits in + all. +- `bitstream::length_prefixed_nals` returns `BitError::Eof` for a zero `length_size` on non-empty + data and cannot overflow on a hostile length prefix. +- `isobmff::PcmConfig::bytes_per_frame` saturates at `u32::MAX` for a hostile channel count. +- `matroska`: a cluster timestamp above `i64::MAX` saturates at `i64::MAX` (FilmCraft wraps it to + a negative value), and adding a block's relative timestamp saturates instead of overflowing (a + debug-build panic in FilmCraft). +- `matroska::MkvWriter` writes `MuxingApp` = `craft-media`, and `MuxOptions::default()` has + `writing_app` = `craft-media` (FilmCraft: `filmcraft-matroska` and `filmcraft`). Apps set + `writing_app` to their own name. +- `matroska::ByteSource` stays a separate trait from `isobmff::ByteSource`, with the same shape. + FilmCraft implements both for one type, which a single shared trait would reject as conflicting + impls. + +## `bitstream` + +- `BitReader`: MSB-first reader with Exp-Golomb (`ue(v)`, `se(v)`, `te(v)`), as used by + H.264/HEVC/AV1 headers. +- `BitWriter`: the matching writer, for encoders and header rewriting. +- `unescape_rbsp` / `escape_rbsp`: remove or insert H.264/HEVC emulation-prevention bytes. +- `annexb_nals` / `length_prefixed_nals`: split Annex-B byte streams and AVCC/HVCC samples into + NAL units. +- `crc32`: CRC-32 (IEEE), as used by Matroska and PNG. + +## `isobmff` + +### Demuxing + +```rust +use craft_media::isobmff::{open, TrackKind}; + +let file = std::fs::File::open("clip.mov")?; +let mp4 = open(&file)?; // any ByteSource: &[u8], Vec, Arc<[u8]>, File, ... +let v = mp4.track_of_kind(TrackKind::Video).unwrap(); +let track = &mp4.tracks[v]; +let i = track.sample_at_presentation_time(1000).unwrap(); // track timescale, edit-adjusted +let key = track.sync_sample_before(i); // decode from here +let bytes = mp4.read_sample(&file, v, key)?; // raw sample (AVCC/HVCC length-prefixed NALs, ...) +``` + +- `ByteSource` (`len`, `read_at(offset, buf)`) is the input abstraction. Implementations exist for `[u8]`, + `Vec`, `&T`, `Arc`, `Box`, and `std::fs::File` on non-wasm targets. +- `open` reads only top-level box headers, `ftyp`, `moov` and every `moof`. It never reads `mdat`. + The one exception is the first sample of a `tmcd` track, which it reads (4 bytes) to get the timecode + start frame. +- `Mp4File`: brands, `is_quicktime`, movie `timescale`/`duration`, `tracks`, `metadata`, `fragmented`, + `fragment_count`. +- `Track`: `id`, `kind` (Video/Audio/Timecode/Subtitle/Other), `handler`, `timescale`, `duration`, + `language`, `tkhd` fields (size, matrix, volume, enabled), `entries: Vec`, `samples`, + `edits`, `edit_offset`, `references` (`tref`), `sdtp`, `sample_groups` (`sbgp`+`sgpd`, raw), `pcm_chunked`. + Helpers: `codec()`, `video()`, `audio()`, `presentation_pts(i)`, `sample_at_pts(pts)`, + `sample_at_presentation_time(t)`, `sync_sample_before(i)`, `sync_samples()`. +- `Sample`: `offset`, `size`, `dts`, `pts` (dts + ctts), `duration`, `is_sync` (all samples are sync when + `stss` is absent), `description_index`. All times are raw media time in the track timescale. +- **Edit lists:** `edits` holds the `elst` entries unchanged. `edit_offset` is + `leading empty edits (rescaled to media timescale) − first non-empty edit's media_time`, so + `presentation time = pts + edit_offset`. This matches ffprobe's timestamps for the common cases + (B-frame delay, AAC priming, empty-edit offsets). Multi-segment edits, dwells and rate changes are exposed + raw for the caller to interpret. +- **Uncompressed PCM** (`lpcm`, `sowt`, `twos`, `in24`, `in32`, `fl32`, `fl64`, `raw `, `ipcm`, `fpcm`) is + merged to one `Sample` per chunk (`pcm_chunked = true`), with `duration` in frames. This avoids one + table entry per audio frame. + +#### Parsed boxes +`ftyp`, `moov/mvhd`, `trak/tkhd`, `edts/elst` (v0/v1), `tref`, `mdia/mdhd` (v0/v1, ISO and Mac language +codes), `hdlr` (ISO and Pascal names), `minf/stbl`: `stsd`, `stts`, `ctts` (v0/v1, read as signed), `stss`, +`stsc`, `stsz`/`stz2` (4/8/16-bit), `stco`/`co64`, `sdtp`, `sbgp`/`sgpd`. Also `mvex/trex`, `moof/traf/tfhd/tfdt/trun` +(every `tfhd` base-offset mode and multiple `moof`s), and `udta` metadata (QuickTime `©xxx` atoms, +`meta/ilst`, and `meta/keys` (mdta)). `uuid`, `free`, `skip`, `wide`, `sidx` and `mfra` are skipped. +Boxes with 64-bit sizes and with size 0 (runs to the end of the file) are supported. + +#### Sample entries → `CodecConfig` +| Format | Config | +|---|---| +| `avc1`/`avc3` + `avcC` | `Avc(AvcConfig)`: profile, level, length size, SPS/PPS, extension bytes | +| `hvc1`/`hev1` + `hvcC` | `Hevc(HevcConfig)`: all header fields plus NAL arrays (`vps()/sps()/pps()`) | +| `av01` + `av1C` | `Av1(Av1Config)` | +| `vp09` + `vpcC` | `Vp9(VpcConfig)` | +| `apch apcn apcs apco ap4h ap4x` | `ProRes { fourcc }` | +| `jpeg mjpa mjpb` | `Jpeg { fourcc }` | +| `AVdn AVdh` | `Dnx { fourcc }` | +| `mp4a` + `esds` (in `wave` too) | `Aac(AacConfig)`: ASC bytes + decoded object type/rate/channels; `Mp3` for OTI 0x69/0x6B | +| `.mp3`/`.mp2` | `Mp3`: MPEG-1/2 audio of any layer (each frame header names it) | +| PCM fourccs | `Pcm(PcmConfig)`: bits, float, endianness (`enda`, lpcm flags, `pcmC`), channels, rate | +| `alac` | `Alac { cookie }` | +| `Opus` + `dOps` | `Opus(OpusConfig)` | +| `fLaC` + `dfLa` | `Flac(FlacConfig)` (STREAMINFO decoded) | +| `ac-3`/`ec-3` | `Ac3 { dac3 }` / `Eac3 { dec3 }` | +| `tmcd` | `Timecode(TimecodeConfig)`: flags (drop frame), timescale, frame duration, fps, start frame, reel name; `format_frame()` | +| anything else | `Unknown { fourcc, raw }` | + +Video entries also parse `colr` (`nclx`/`nclc`/ICC), `pasp`, `clap`, `fiel`, `gama` and `btrt` into +`VideoParams`. Audio entries parse QuickTime sound description v0/v1/v2 into `AudioParams`. + +#### Robustness +The parser does not panic on malformed input; every error comes back as an `Error`. Table counts are +checked against the bytes in their box before anything is allocated. A constant-size `stsz` count is +clamped to what fits in the file. `trun` counts are checked, and each track is capped at 2²⁶ samples. +`moov`/`moof` are capped at 1 GiB. Compressed movie headers (`cmov`) are rejected with +`Error::Unsupported`. + +### Muxing + +```rust +use craft_media::isobmff::*; +let mut w = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4))?; +let v = w.add_track(TrackConfig::new(SampleEntry::avc(avcc, 1920, 1080), 90_000))?; +let mut acfg = TrackConfig::new(SampleEntry::aac(asc, 2, 48_000), 48_000); +acfg.media_start = Some(1024); // AAC encoder delay → edit list +let a = w.add_track(acfg)?; +w.write_sample(v, WriteSample { data: &au, duration: 3000, composition_offset: 6000, is_sync: true })?; +// ... interleave samples in decode order ... +let bytes = w.finish_faststart()?.into_inner(); // or finish() for moov-at-end +``` + +- `Mp4Writer` streams samples into a single `mdat`. `finish()` appends `moov`. + `finish_faststart()` (needs `W: Read + Write + Seek`) moves the media data forward in place and writes + `moov` before it. If `mdat` goes past 4 GiB the header becomes a large-size header, and chunk offsets + switch to `co64` when needed. +- Brands: `Brand::Mp4` writes `isom` with `isom iso2 avc1 mp41 mp42`. `Brand::Mov` writes `qt `, uses + QuickTime `hdlr`/Pascal names, and sets `wide` as the placeholder box. +- Tables written: `stts`, `ctts` (v1 when an offset is negative), `stss` (omitted when every sample is + sync), `stsc`, `stsz` (constant or table), `stco`/`co64`. Consecutive samples of one track share a chunk. +- Sample entries come from `SampleEntry` (`avc`, `hevc`, `prores`, `jpeg`, `aac`, `pcm`, or any demuxed + entry). Remuxing copies codec config, `colr`, `pasp`, `clap`, `fiel`, `gama` and `btrt`. + PCM is written as `sowt`/`twos` (16-bit) or `raw ` (8-bit) or sound description v2 `lpcm` in MOV, and as + `ipcm`/`fpcm` + `pcmC` in MP4. A PCM `write_sample` call can hold any whole number of frames, and the + track timescale must equal the sample rate. +- Edit lists: set `TrackConfig::edits` explicitly, or use `media_start` to get a single edit. +- Timecode: `add_timecode_track(video, TimecodeConfig, start_frame)` adds a `tmcd` track (with `gmhd`) + and a `tref/tmcd` link from the video track. +- `WriterOptions::metadata` writes `©xxx` text atoms to `udta`. +- `FragmentedWriter` writes fMP4. The init segment is `ftyp` + `moov` with `mvex/trex`. Each + `flush_fragment()` then writes `moof` (`mfhd`, `traf` with default-base-is-moof `tfhd`, `tfdt` v1, + `trun` with per-sample duration, size, flags and composition offset) followed by `mdat`. + +### Box reader + +`isobmff::boxes` gives direct access to the box format, for files and boxes the demuxer does not +model: CR3 `uuid` boxes, HEIF `meta` items, JPEG 2000 (JP2, JPX, JPM, MJ2) boxes. + +```rust +use craft_media::isobmff::boxes::{BoxIter, Reader}; + +for b in BoxIter::new(&bytes) { + let b = b?; + if b.kind == b"uuid" && b.user_type == Some(CANON_UUID) { + for c in BoxIter::within(&bytes, b.payload_range()) { /* CMT1..CMT4, THMB */ } + } +} +``` + +- `BoxIter::new(data)` yields the sibling boxes in `data`; `BoxIter::within(data, range)` yields + those in `data[range]` with offsets relative to `data`, so a walker keeps file offsets as it + descends. Each `BoxRef` has `kind`, `user_type` (the 16-byte extended type of a `uuid` box), + `offset`, `header_len`, `payload`, `payload_range()`, `range()` and `end()`. +- 64-bit `largesize` and size 0 (runs to the end of the range) are handled. A malformed header or a + box larger than the range yields one `Err` and ends the iteration; `allow_truncated()` instead + yields that last box cut at the end of the range, with `truncated` set. A 32-bit zero terminator + (QuickTime) ends the iteration. +- `BoxHeader::parse(buf)` reads one header (up to `BoxHeader::MAX_LEN` = 32 bytes), for scanning a + file through `ByteSource` without loading it. +- `Reader` is the bounds-checked big-endian cursor the demuxer uses: `u8` to `u64`, `i16` to + `i64`, `f64`, `u24`, `fourcc`, `full_header` (version and flags), `bytes`, `skip`, `rest` and + `count` (an entry count checked against the bytes left, before allocating). +- The iterator does not recurse. The caller bounds nesting depth and box count. + +### Limitations +- `presentation time = pts + edit_offset` only applies the leading empty edits and the first media + edit. Multi-segment edit lists, dwell edits and non-unity rates are exposed raw. ffmpeg handles an edit + that starts mid-frame differently: it snaps to the frame. +- Other data references (external `alis`/`url ` files), encrypted entries (`encv`/`enca`, `sinf`, + `senc`), `cmov`, and QuickTime reference movies are not supported. +- `sidx`/`mfra` are ignored, because the demuxer scans every top-level box. `stsd` entries with a + QuickTime color table are not decoded. +- Subtitle and text tracks (`tx3g`, `c608`, `wvtt`) and `mp4v` show up as `Unknown`. +- Muxer: one `mdat`, no chunk-size or duration limits (the caller controls interleaving), no `sdtp`, + `sgpd`/`sbgp` or `cslg` output, ISO-style `meta/ilst` metadata is not written, and the fragmented + writer has no PCM, `sidx` or `mfra`. + +## `matroska` + +A clean-room Matroska (MKV) and WebM demuxer, plus a minimal muxer, written from RFC 8794 (EBML), +RFC 9559 (Matroska), the Matroska codec mappings and the WebM container guidelines. No GPL or LGPL +code (FFmpeg, libmatroska, mkvtoolnix) was consulted; FFmpeg is a test oracle only. + +### Demuxing + +```rust +use craft_media::matroska::{Demuxer, TrackKind, open}; + +// Sample tables in the same shape as isobmff (any ByteSource: &[u8], Vec, Arc<[u8]>, File, ...) +let file = std::fs::File::open("clip.mkv")?; +let mkv = open(&file)?; +let v = mkv.track_of_kind(TrackKind::Video).unwrap(); +let k = mkv.keyframe_before(v, 2_000_000_000).unwrap(); // sample index +let frame = mkv.read_sample(&file, v, k)?; + +// Streaming packets and seeking (from a ByteSource, any Read + Seek, or a byte slice) +let mut d = Demuxer::from_reader(std::io::BufReader::new(std::fs::File::open("clip.webm")?))?; +let sp = d.seek(v, 2_000_000_000)?; // lands on the keyframe with pts <= 2 s +while let Some(p) = d.next_packet()? { // file order, all tracks + // p.track, p.pts (ticks), p.pts_ns, p.duration, p.keyframe, p.data +} +``` + +- **Open** (`open`, `open_with(src, &OpenOptions { index, verify_crc })`): EBML header (DocType + `matroska` or `webm`), the first Segment, and its level-1 elements: SeekHead (followed for + elements after the clusters), Info, Tracks, Cues, Chapters, Tags, Attachments (listed with offset + and size; payloads are not read). With `index: true` (the default) every Cluster is scanned, + element and block headers only, to build per-track `Sample` tables (`offset`, `size`, `pts`, + `duration`, `keyframe`, cluster, block offset, lace index, `BlockAdditional` location) and + keyframe lists. With `index: false`, `open` stops at the first Cluster. +- **Timestamps:** Matroska ticks are `TimestampScale` ns (usually 1 ms); `Track::timebase` is that + as a reduced fraction of a second. `pts` is in ticks, `pts_ns` in exact nanoseconds. `CodecDelay` + is subtracted (RFC 9559), as FFmpeg does, so Opus and Vorbis priming gives negative pts. Laced + frames get `block ts + i × (BlockDuration or DefaultDuration) / n`; when neither is known, later + laces repeat the block timestamp and have `duration == 0` (`Packet::lace` tells which). +- **Keyframes:** the SimpleBlock keyframe flag; a BlockGroup is a keyframe when it has no + ReferenceBlock. +- **Lacing:** Xiph, fixed-size and EBML. **Unknown sizes:** a Segment (live or streamed output) and + Clusters end at the next top-level element. **CRC-32:** optional verification of level-1 + elements and clusters; mismatches go to `MkvFile::crc_errors` and are not fatal. +- **Damage:** an undecodable or oversized element starts a byte scan for the next plausible level-1 + element (a Cluster whose first child is Timestamp, or a sized metadata element); a truncated final + block is dropped. Problems are listed in `MkvFile::warnings`. +- **Seeking** (`Demuxer::seek(track, time_ns)`): uses the sample index when present, otherwise Cues + (refined by scanning the cued cluster for the exact keyframe), otherwise builds the index by + scanning all clusters. `Demuxer::keyframe_index(track)` returns the keyframe list. +- **Block additions:** `MkvFile::read_sample_addition` returns the `BlockAdditional` with + `BlockAddID` 1 of an unlaced block (in WebM, the VP8/VP9 alpha layer). +- **Tracks:** number, UID, type, flags, `DefaultDuration`, name, language (and BCP 47), CodecID, + CodecPrivate, CodecName, `CodecDelay`, `SeekPreRoll`; `VideoInfo` (pixel and display size, crop, + interlacing, stereo, alpha mode, `pixel_aspect()`, `display_rotation()`), `Color` (matrix, + range, transfer, primaries, subsampling and siting, MaxCLL/MaxFALL, SMPTE 2086 mastering + metadata); `AudioInfo` (rate, output rate, channels, bit depth); `ContentEncoding`s. +- **Content encodings:** header stripping is undone in every packet and in `read_sample`. zlib, + bzlib and lzo compression and encryption are reported (`Track::frames_readable() == false`); + packets are then returned as stored and `read_sample` fails with `Unsupported`. +- `matroska::ebml` (public) has the EBML primitives: variable-length integers, element headers, + typed values, CRC-32 and lacing. `matroska::element_ids` lists the element IDs. + +#### Codec mapping (`Codec`) + +| CodecID | `Codec` | Payload | +|---|---|---| +| `V_MPEG4/ISO/AVC` | `Avc` | avcC (CodecPrivate) | +| `V_MPEGH/ISO/HEVC` | `Hevc` | hvcC | +| `V_VP8`, `V_VP9` | `Vp8`, `Vp9` | VP9 CodecPrivate features | +| `V_AV1` | `Av1` | av1C | +| `V_APV` | `Apv` | apvC | +| `V_PRORES` | `ProRes` | FourCC; frames get the 8-byte `size` + `icpf` header re-added | +| `V_MJPEG`, `V_MS/VFW/FOURCC` (MJPG) | `Mjpeg` | | +| `V_MS/VFW/FOURCC` (other) | `VfwFourcc` | BITMAPINFOHEADER | +| `A_AAC`, legacy `A_AAC/MPEG{2,4}/...` | `Aac` | AudioSpecificConfig (synthesized for legacy IDs, SBR included) | +| `A_OPUS` | `Opus` | OpusHead | +| `A_VORBIS` | `Vorbis` | three headers split from the Xiph-laced CodecPrivate | +| `A_FLAC` | `Flac` | `fLaC` + metadata blocks | +| `A_PCM/INT/LIT`, `A_PCM/INT/BIG`, `A_PCM/FLOAT/IEEE` | `Pcm` | bit depth from Audio | +| `A_AC3`, `A_EAC3`, `A_MPEG/L3`, `A_MPEG/L2`, `A_MPEG/L1` | `Ac3`, `Eac3`, `Mp3`, `Mp2`, `Mp1` | | +| `S_TEXT/UTF8` | `SubRip` | | +| `S_TEXT/WEBVTT`, `D_WEBVTT/*` (WebM) | `WebVtt` | WebM blocks keep `id\nsettings\npayload` | +| `S_TEXT/ASS`, `S_TEXT/SSA` | `Ass` | script header | +| anything else | `Other(id)` | `Track::codec_private` | + +`Codec::name()` matches FFmpeg's `codec_name` for these. + +### Muxing + +`MkvWriter::new(w: Write + Seek, Vec, MuxOptions)`, then `write_frame(track, pts_ns, +keyframe, data, duration_ns)` per frame, then `finish()`. It writes the EBML header, Segment, +SeekHead, Info (with Duration), Tracks, Clusters of SimpleBlocks (a new cluster at a video keyframe +after `cluster_duration_ns`), BlockGroups for frames whose duration differs from the track's +`default_duration_ns`, optional audio lacing (Xiph, EBML, fixed-size), and Cues (video keyframes, +or the first frame of each track per cluster). `MuxOptions::doc_type` = `"webm"` writes WebM. +CodecPrivate is fixed when the writer is created, so a codec whose configuration arrives with the +first frame (AV1 from `rav1e`) creates the writer after that frame. + +### Limitations + +- Only the first Segment is read (no linked or chained segments, no ordered-chapter playback). +- zlib, bzlib and lzo compressed and encrypted tracks are detected, but their frames are not + decoded. `EncryptedBlock` is ignored. +- `TrackTimestampScale` (deprecated) is ignored. +- Lace timestamps without any duration information repeat the block timestamp (FFmpeg derives them + from codec parsers). +- Muxer: no CRC-32, Chapters, Tags, Attachments, content encodings or block additions. + +## Tests + +- Unit tests cover the bit reader and writer, the box reader (64-bit, size-0, `uuid`, truncated and + hostile sizes), hand-built `stbl` edge cases, codec configuration round trips and allocation + guards. For Matroska: EBML integers, typed values, CRC-32, every lacing mode, codec mapping, a + hand-built file (unknown-size Segment and Clusters, header stripping, BlockGroups, block + additions, color and mastering metadata, Chapters, Tags, Attachments, CRC-32, Cue-less seek, + hostile cluster timestamps) and mux-demux round trips. +- `tests/roundtrip.rs`: property tests that write random multi-track files (progressive and + fragmented) and read them back. +- `tests/oracle_demux.rs` and `tests/oracle_mux.rs` compare the demuxer and muxer with ffprobe and + ffmpeg on generated fixtures in `target/fixtures/isobmff/` (`$CRAFT_MEDIA_FIXTURES_DIR` + overrides it). Fixtures are never committed. +- `tests/oracle_matroska.rs` compares every packet (stream, size, keyframe flag, pts, duration), + codec names, time bases, dimensions and audio parameters with ffprobe on fixtures in + `target/fixtures/matroska/`: H.264+AAC, VP9+Opus WebM, FLAC, Vorbis, SRT+ASS, WebVTT WebM, Cues + at the front, a streamed file without Cues, HEVC with HDR color, ProRes+PCM, MJPEG+AC-3, AV1. + Seeks must land on the latest keyframe at or before the target. The muxer's laced output is read + back by ffprobe. A damaged file must resync. +- `tests/fuzz.rs` and `tests/fuzz_matroska.rs`: deterministic mutation fuzzing; nothing may panic. + `fuzz.rs` also walks every box of a mutated file as a container and checks that each payload + range stays inside its parent. + +ffmpeg and ffprobe are test oracles only, never linked. They are looked up in +`$CRAFT_MEDIA_FFMPEG` / `$CRAFT_MEDIA_FFPROBE`, then `PATH`, then common install directories. When +a tool is missing, the oracle tests print `SKIPPED` and pass; `CRAFT_MEDIA_REQUIRE_ORACLES=1` turns +a skip into a failure. CI (`.github/workflows/media.yml`) sets it and installs Ubuntu's ffmpeg. +Generate every fixture ahead of time with +`cargo test -p craft-media --all-features -- --ignored generate_fixtures`. diff --git a/crates/media/src/bitstream.rs b/crates/media/src/bitstream.rs new file mode 100644 index 0000000000..f56f36196b --- /dev/null +++ b/crates/media/src/bitstream.rs @@ -0,0 +1,548 @@ +//! Bit-level reading and writing for codec and container code. +//! +//! - [`BitReader`]: MSB-first reader with Exp-Golomb (`ue(v)`, `se(v)`), as used by H.264/HEVC/AV1 headers. +//! - [`BitWriter`]: the matching writer (for encoders and header rewriting). +//! - [`unescape_rbsp`] / [`escape_rbsp`]: remove/insert H.264/HEVC emulation-prevention bytes. +//! - [`annexb_nals`] / [`length_prefixed_nals`]: split Annex-B byte streams and AVCC/HVCC samples into NAL units. + +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BitError { + /// Tried to read past the end of the buffer. + Eof, + /// An Exp-Golomb code longer than 32 leading zeros. + InvalidExpGolomb, +} + +impl fmt::Display for BitError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BitError::Eof => f.write_str("unexpected end of bitstream"), + BitError::InvalidExpGolomb => f.write_str("invalid Exp-Golomb code"), + } + } +} +impl std::error::Error for BitError {} + +pub type Result = std::result::Result; + +/// MSB-first bit reader over a byte slice. +#[derive(Clone)] +pub struct BitReader<'a> { + data: &'a [u8], + /// Position in bits. + pos: usize, +} + +impl<'a> BitReader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Self { data, pos: 0 } + } + pub fn data(&self) -> &'a [u8] { + self.data + } + /// Bit position from the start. + pub fn position(&self) -> usize { + self.pos + } + pub fn bits_left(&self) -> usize { + self.data.len().saturating_mul(8).saturating_sub(self.pos) + } + pub fn is_byte_aligned(&self) -> bool { + self.pos.is_multiple_of(8) + } + pub fn byte_align(&mut self) { + self.pos = self.pos.div_ceil(8) * 8; + } + /// Byte offset of the current position (rounded down). + pub fn byte_pos(&self) -> usize { + self.pos / 8 + } + pub fn seek_bits(&mut self, pos: usize) { + self.pos = pos; + } + + /// Peek `n` bits without consuming, zero-padded past the end. For `n` above 32 this returns + /// what [`read_bits`](Self::read_bits) would: the low 32 bits of the `n`-bit field. + #[inline] + pub fn peek(&self, n: u32) -> u32 { + if n > 32 { + let mut r = self.clone(); + r.pos = r.pos.saturating_add((n - 32) as usize); + return r.peek(32); + } + if n == 0 { + return 0; + } + let byte = self.pos / 8; + let shift = self.pos % 8; + let mut v: u64 = 0; + for i in 0..5 { + v = (v << 8) | *self.data.get(byte.saturating_add(i)).unwrap_or(&0) as u64; + } + // v holds 40 bits starting at `byte` + ((v << (24 + shift)) >> (64 - n)) as u32 + } + + /// Read `n` bits. For `n` above 32 this consumes `n` bits and returns the low 32 of them. + #[inline] + pub fn read_bits(&mut self, n: u32) -> Result { + if n as usize > self.bits_left() { + return Err(BitError::Eof); + } + if n > 32 { + self.pos += (n - 32) as usize; + return self.read_bits(32); + } + let v = self.peek(n); + self.pos += n as usize; + Ok(v) + } + + pub fn read_bits_u64(&mut self, n: u32) -> Result { + if n <= 32 { + return self.read_bits(n).map(u64::from); + } + let hi = self.read_bits(n - 32)? as u64; + let lo = self.read_bits(32)? as u64; + Ok((hi << 32) | lo) + } + + #[inline] + pub fn read_bit(&mut self) -> Result { + self.read_bits(1).map(|b| b == 1) + } + pub fn read_flag(&mut self) -> Result { + self.read_bit() + } + + pub fn skip(&mut self, n: usize) -> Result<()> { + if n > self.bits_left() { + return Err(BitError::Eof); + } + self.pos += n; + Ok(()) + } + + /// Raw Exp-Golomb codeNum, up to 32 leading zeros (so below 2^33). + fn read_code_num(&mut self) -> Result { + let mut zeros = 0u32; + while !self.read_bit()? { + zeros += 1; + if zeros > 32 { + return Err(BitError::InvalidExpGolomb); + } + } + if zeros == 0 { + return Ok(0); + } + let v = self.read_bits_u64(zeros)?; + Ok((1u64 << zeros) - 1 + v) + } + + /// Unsigned Exp-Golomb `ue(v)`. + pub fn read_ue(&mut self) -> Result { + u32::try_from(self.read_code_num()?).map_err(|_| BitError::InvalidExpGolomb) + } + + /// `ue(v) + add` (the `..._minus1` / `..._minus8` fields), failing instead of overflowing on a + /// hostile value near `u32::MAX`. + pub fn read_ue_plus(&mut self, add: u32) -> Result { + self.read_ue()?.checked_add(add).ok_or(BitError::InvalidExpGolomb) + } + + /// Signed Exp-Golomb `se(v)`. + pub fn read_se(&mut self) -> Result { + // codeNum 2^32 is -2^31, so the mapping is done before narrowing to 32 bits. + let k = self.read_code_num()? as i64; + let v = if k & 1 == 1 { (k + 1) / 2 } else { -(k / 2) }; + i32::try_from(v).map_err(|_| BitError::InvalidExpGolomb) + } + + /// Truncated Exp-Golomb `te(v)` with range `max`. + pub fn read_te(&mut self, max: u32) -> Result { + if max > 1 { self.read_ue() } else { Ok(!self.read_bit()? as u32) } + } + + /// H.264/HEVC `more_rbsp_data()`: true if there is data before the rbsp trailing bits. + pub fn more_rbsp_data(&self) -> bool { + let total = self.data.len().saturating_mul(8); + if self.pos >= total { + return false; + } + // find last set bit (the rbsp_stop_one_bit) + let mut last = None; + for (i, &b) in self.data.iter().enumerate().rev() { + if b != 0 { + last = Some(i.saturating_mul(8).saturating_add(7 - b.trailing_zeros() as usize)); + break; + } + } + match last { + Some(stop) => self.pos < stop, + None => false, + } + } +} + +/// MSB-first bit writer. +#[derive(Default, Clone)] +pub struct BitWriter { + buf: Vec, + acc: u64, + nbits: u32, +} + +impl BitWriter { + pub fn new() -> Self { + Self::default() + } + /// Write the low `n` bits of `value`. For `n` above 32 the extra high bits are zeros; + /// `n` above 64 writes 64 bits. + pub fn write_bits(&mut self, value: u32, n: u32) { + let mut n = n.min(64); + while n > 32 { + let pad = (n - 32).min(32); + self.write_bits(0, pad); + n -= pad; + } + if n == 0 { + return; + } + let v = (value as u64) & ((1u64 << n) - 1); + self.acc = (self.acc << n) | v; + self.nbits += n; + while self.nbits >= 8 { + self.nbits -= 8; + self.buf.push((self.acc >> self.nbits) as u8); + } + self.acc &= (1u64 << self.nbits) - 1; + } + pub fn write_bit(&mut self, b: bool) { + self.write_bits(b as u32, 1); + } + pub fn write_ue(&mut self, v: u32) { + self.write_code_num(u64::from(v)); + } + /// Exp-Golomb codeNum up to 2^32 (the code of `se(v)` -2^31). + fn write_code_num(&mut self, v: u64) { + let x = v + 1; + let len = 64 - x.leading_zeros(); + let zeros = len - 1; + for _ in 0..zeros { + self.write_bit(false); + } + if len > 32 { + self.write_bits((x >> 32) as u32, len - 32); + self.write_bits(x as u32, 32); + } else { + self.write_bits(x as u32, len); + } + } + pub fn write_se(&mut self, v: i32) { + let m = u64::from(v.unsigned_abs()) * 2; + self.write_code_num(if v > 0 { m - 1 } else { m }); + } + pub fn bit_len(&self) -> usize { + self.buf.len() * 8 + self.nbits as usize + } + pub fn is_byte_aligned(&self) -> bool { + self.nbits == 0 + } + /// Pad with zero bits to a byte boundary. + pub fn align_zero(&mut self) { + if self.nbits > 0 { + self.write_bits(0, 8 - self.nbits); + } + } + /// `rbsp_trailing_bits()`: a one bit then zeros to alignment. + pub fn rbsp_trailing(&mut self) { + self.write_bit(true); + self.align_zero(); + } + pub fn write_bytes(&mut self, bytes: &[u8]) { + if self.nbits == 0 { + self.buf.extend_from_slice(bytes); + } else { + for &b in bytes { + self.write_bits(b as u32, 8); + } + } + } + pub fn finish(mut self) -> Vec { + self.align_zero(); + self.buf + } + pub fn bytes(&self) -> &[u8] { + &self.buf + } +} + +/// Remove emulation-prevention bytes (`00 00 03` → `00 00`) from a NAL payload. +pub fn unescape_rbsp(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len()); + let mut zeros = 0; + for &b in data { + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + out.push(b); + zeros = if b == 0 { zeros + 1 } else { 0 }; + } + out +} + +/// Insert emulation-prevention bytes so no `00 00 0x` (x ≤ 3) sequence appears. +pub fn escape_rbsp(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len() + data.len() / 64); + let mut zeros = 0; + for &b in data { + if zeros >= 2 && b <= 3 { + out.push(3); + zeros = 0; + } + out.push(b); + zeros = if b == 0 { zeros + 1 } else { 0 }; + } + out +} + +/// Split an Annex-B byte stream (start codes `00 00 01` / `00 00 00 01`) into NAL units (escaped payloads). +pub fn annexb_nals(data: &[u8]) -> Vec<&[u8]> { + let mut starts = Vec::new(); + let mut i = 0; + while i + 3 <= data.len() { + if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 { + starts.push(i + 3); + i += 3; + } else { + i += 1; + } + } + let mut out = Vec::with_capacity(starts.len()); + for (k, &s) in starts.iter().enumerate() { + let mut e = if k + 1 < starts.len() { starts[k + 1] - 3 } else { data.len() }; + // trim trailing zero bytes (part of a 4-byte start code or trailing_zero_8bits) + while e > s && data[e - 1] == 0 { + e -= 1; + } + if e > s { + out.push(&data[s..e]); + } + } + out +} + +/// Split a length-prefixed sample (AVCC/HVCC, `length_size` 1/2/4 bytes) into NAL units. +/// A zero `length_size` cannot split non-empty data and returns [`BitError::Eof`]. +pub fn length_prefixed_nals(data: &[u8], length_size: usize) -> Result> { + let mut out = Vec::new(); + let mut i = 0; + while i < data.len() { + // Compare against the remaining length so a hostile prefix cannot overflow `usize` + // (32-bit on wasm). + if length_size == 0 || length_size > data.len() - i { + return Err(BitError::Eof); + } + let mut len = 0usize; + for k in 0..length_size { + len = (len << 8) | data[i + k] as usize; + } + i += length_size; + if len > data.len() - i { + return Err(BitError::Eof); + } + out.push(&data[i..i + len]); + i += len; + } + Ok(out) +} + +/// CRC-32 (IEEE, reflected) — used by containers (e.g. Matroska CRC-32 elements, PNG). +pub fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= b as u32; + for _ in 0..8 { + crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + !crc +} + +#[cfg(test)] +mod tests { + use super::*; + use proptest::prelude::*; + + #[test] + fn reads_bits() { + let d = [0b1010_1100, 0b0101_0011]; + let mut r = BitReader::new(&d); + assert_eq!(r.read_bits(1).unwrap(), 1); + assert_eq!(r.read_bits(3).unwrap(), 0b010); + assert_eq!(r.read_bits(8).unwrap(), 0b1100_0101); + assert_eq!(r.bits_left(), 4); + assert_eq!(r.read_bits(5), Err(BitError::Eof)); + } + + #[test] + fn exp_golomb_known() { + // 1 | 010 | 011 | 00100 | 00101 -> 0,1,2,3,4 + let mut w = BitWriter::new(); + for v in 0..5 { + w.write_ue(v); + } + let b = w.finish(); + let mut r = BitReader::new(&b); + for v in 0..5 { + assert_eq!(r.read_ue().unwrap(), v); + } + let mut w = BitWriter::new(); + for v in [0, 1, -1, 2, -2, 1000, -1000] { + w.write_se(v); + } + let b = w.finish(); + let mut r = BitReader::new(&b); + for v in [0, 1, -1, 2, -2, 1000, -1000] { + assert_eq!(r.read_se().unwrap(), v); + } + } + + #[test] + fn signed_exp_golomb_extremes_roundtrip() { + let vals = [0, 1, -1, i32::MAX, i32::MIN]; + let mut w = BitWriter::new(); + for v in vals { + w.write_se(v); + } + let b = w.finish(); + let mut r = BitReader::new(&b); + for v in vals { + assert_eq!(r.read_se(), Ok(v)); + } + } + + #[test] + fn signed_exp_golomb_reads_minimum_from_spec_bits() { + // 32 zero bits, 1, then the 32-bit suffix 1: codeNum = 2^32 -> -2^31. + let bytes = [0, 0, 0, 0, 0x80, 0, 0, 0, 0x80]; + assert_eq!(BitReader::new(&bytes).read_se(), Ok(i32::MIN)); + } + + #[test] + fn signed_exp_golomb_rejects_positive_overflow() { + // 32 zero bits, 1, then 32 zero bits: codeNum = 2^32 - 1 -> +2^31, not an i32. + let bytes = [0, 0, 0, 0, 0x80, 0, 0, 0, 0]; + assert_eq!(BitReader::new(&bytes).read_se(), Err(BitError::InvalidExpGolomb)); + } + + #[test] + fn unsigned_exp_golomb_keeps_u32_range() { + // codeNum = 2^32 is a valid se(v) code but does not fit ue(v)'s u32. + let bytes = [0, 0, 0, 0, 0x80, 0, 0, 0, 0x80]; + assert_eq!(BitReader::new(&bytes).read_ue(), Err(BitError::InvalidExpGolomb)); + } + + #[test] + fn emulation_prevention() { + let raw = [0, 0, 1, 0, 0, 0, 5, 0, 0, 3]; + let esc = escape_rbsp(&raw); + assert_eq!(esc, vec![0, 0, 3, 1, 0, 0, 3, 0, 5, 0, 0, 3, 3]); + assert_eq!(unescape_rbsp(&esc), raw); + } + + #[test] + fn annexb_split() { + let s = [0, 0, 0, 1, 0x67, 1, 2, 0, 0, 1, 0x68, 3, 0, 0, 0, 1, 0x65, 9, 9]; + let n = annexb_nals(&s); + assert_eq!(n, vec![&[0x67, 1, 2][..], &[0x68, 3][..], &[0x65, 9, 9][..]]); + let l = [0, 0, 0, 2, 0x67, 1, 0, 0, 0, 1, 0x68]; + assert_eq!(length_prefixed_nals(&l, 4).unwrap(), vec![&[0x67, 1][..], &[0x68][..]]); + } + + #[test] + fn more_rbsp() { + let d = [0b1100_0000]; + let mut r = BitReader::new(&d); + assert!(r.more_rbsp_data()); + r.read_bit().unwrap(); + assert!(!r.more_rbsp_data()); + } + + #[test] + fn crc() { + assert_eq!(crc32(b"123456789"), 0xCBF4_3926); + } + + #[test] + fn read_ue_plus_rejects_overflow() { + let mut w = BitWriter::new(); + w.write_ue(7); + w.write_ue(u32::MAX - 1); + w.rbsp_trailing(); + let b = w.finish(); + let mut r = BitReader::new(&b); + assert_eq!(r.read_ue_plus(1).unwrap(), 8); + assert_eq!(r.read_ue_plus(2), Err(BitError::InvalidExpGolomb)); + } + + #[test] + fn length_prefixed_rejects_zero_width_and_oversized_length() { + assert_eq!(length_prefixed_nals(&[], 0).unwrap(), Vec::<&[u8]>::new()); + assert_eq!(length_prefixed_nals(&[1, 2, 3], 0), Err(BitError::Eof)); + assert_eq!(length_prefixed_nals(&[0, 0, 1, 7], 3).unwrap(), vec![&[7u8][..]]); + assert_eq!(length_prefixed_nals(&[0xFF, 0xFF, 0xFF, 0xFF, 1], 4), Err(BitError::Eof)); + assert_eq!(length_prefixed_nals(&[0, 0, 0, 1, 9], 4).unwrap(), vec![&[9u8][..]]); + assert_eq!(length_prefixed_nals(&[0, 1], usize::MAX), Err(BitError::Eof)); + } + + #[test] + fn widths_above_32_bits_do_not_panic() { + let mut w = BitWriter::new(); + w.write_bits(0xABCD_EF01, 40); + w.write_bits(1, 60); + let b = w.finish(); + assert_eq!(b.len(), 13); + assert_eq!(&b[..5], &[0x00, 0xAB, 0xCD, 0xEF, 0x01]); + let mut r = BitReader::new(&b); + assert_eq!(r.peek(40), 0xABCD_EF01); + assert_eq!(r.read_bits(40).unwrap(), 0xABCD_EF01); + assert_eq!(r.peek(60), 1); + assert_eq!(r.read_bits_u64(60).unwrap(), 1); + assert_eq!(r.bits_left(), 4); + assert_eq!(r.read_bits(40), Err(BitError::Eof)); + } + + #[test] + fn huge_write_width_is_capped_at_64_bits() { + let mut w = BitWriter::new(); + w.write_bits(0xFFFF_FFFF, u32::MAX); + assert_eq!(w.finish(), [0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF]); + } + + proptest! { + #[test] + fn roundtrip(vals in proptest::collection::vec((0u32..u32::MAX, 1u32..=32), 0..200), ues in proptest::collection::vec(0u32..u32::MAX - 1, 0..50)) { + let mut w = BitWriter::new(); + for &(v, n) in &vals { w.write_bits(v, n); } + for &u in &ues { w.write_ue(u); } + let b = w.finish(); + let mut r = BitReader::new(&b); + for &(v, n) in &vals { + let mask = if n == 32 { u32::MAX } else { (1 << n) - 1 }; + prop_assert_eq!(r.read_bits(n).unwrap(), v & mask); + } + for &u in &ues { prop_assert_eq!(r.read_ue().unwrap(), u); } + } + + #[test] + fn escape_roundtrip(data in proptest::collection::vec(0u8..4, 0..300)) { + let e = escape_rbsp(&data); + prop_assert_eq!(unescape_rbsp(&e), data); + for w in e.windows(3) { prop_assert!(!(w[0] == 0 && w[1] == 0 && w[2] < 3)); } + } + } +} diff --git a/crates/media/src/isobmff/boxes.rs b/crates/media/src/isobmff/boxes.rs new file mode 100644 index 0000000000..a4135248ea --- /dev/null +++ b/crates/media/src/isobmff/boxes.rs @@ -0,0 +1,480 @@ +//! Box-level access to ISO BMFF data: a box header parser, an iterator over the boxes in a byte +//! slice, and a bounds-checked big-endian [`Reader`] for box payloads. +//! +//! The same box format is used by MP4, QuickTime, HEIF/AVIF, CR3, JPEG 2000 (JP2, JPX, JPM, MJ2) +//! and 3GP. Use this module to read boxes that [`open`](super::open) does not model, such as +//! `uuid` boxes or HEIF `meta` items. +//! +//! ``` +//! use craft_media::isobmff::boxes::{BoxIter, Reader}; +//! +//! // `ftyp` with major brand `crx `, then a `uuid` box with one child. +//! let mut file = vec![0, 0, 0, 16, b'f', b't', b'y', b'p', b'c', b'r', b'x', b' ', 0, 0, 0, 1]; +//! file.extend_from_slice(&[0, 0, 0, 36, b'u', b'u', b'i', b'd']); +//! file.extend_from_slice(&[0x85; 16]); +//! file.extend_from_slice(&[0, 0, 0, 12, b'C', b'M', b'T', b'1', 1, 2, 3, 4]); +//! +//! for b in BoxIter::new(&file) { +//! let b = b?; +//! if b.kind == b"ftyp" { +//! assert_eq!(Reader::new(b.payload).fourcc()?, b"crx "); +//! } +//! if b.kind == b"uuid" && b.user_type == Some([0x85; 16]) { +//! // Iterate the children in place; offsets stay relative to `file`. +//! for c in BoxIter::within(&file, b.payload_range()) { +//! let c = c?; +//! assert_eq!((c.kind, c.offset, c.payload), (b"CMT1".into(), 40, &[1u8, 2, 3, 4][..])); +//! } +//! } +//! } +//! # Ok::<(), craft_media::isobmff::Error>(()) +//! ``` +//! +//! Nothing here recurses. A caller that walks nested boxes bounds its own depth and box count. + +use crate::isobmff::bytes::FourCc; +use crate::isobmff::error::{Error, Result}; +use std::ops::Range; + +/// Bounds-checked big-endian cursor over a byte slice. +/// +/// Every read checks the remaining length and returns [`Error::Truncated`] with the reader's label +/// when the data ends early. A failed read leaves the position unchanged. +#[derive(Clone, Debug)] +pub struct Reader<'a> { + data: &'a [u8], + pos: usize, + what: &'static str, +} + +impl<'a> Reader<'a> { + /// A reader at the start of `data`. Errors name the data `"box payload"`. + pub fn new(data: &'a [u8]) -> Self { + Self::labeled(data, "box payload") + } + /// A reader whose [`Error::Truncated`] errors name the data `what`. + pub fn labeled(data: &'a [u8], what: &'static str) -> Self { + Reader { data, pos: 0, what } + } + /// The whole slice the reader was created with. + pub fn data(&self) -> &'a [u8] { + self.data + } + /// Bytes read so far. + pub fn position(&self) -> usize { + self.pos + } + /// Bytes left to read. + pub fn remaining(&self) -> usize { + self.data.len().saturating_sub(self.pos) + } + /// True when no bytes are left. + pub fn is_empty(&self) -> bool { + self.remaining() == 0 + } + /// The unread bytes, without consuming them. + pub fn rest(&self) -> &'a [u8] { + self.data.get(self.pos..).unwrap_or(&[]) + } + /// Read `n` bytes. + pub fn bytes(&mut self, n: usize) -> Result<&'a [u8]> { + let end = self.pos.checked_add(n).ok_or(Error::Truncated(self.what))?; + let s = self.data.get(self.pos..end).ok_or(Error::Truncated(self.what))?; + self.pos = end; + Ok(s) + } + /// Skip `n` bytes. + pub fn skip(&mut self, n: usize) -> Result<()> { + self.bytes(n).map(|_| ()) + } + /// Read `N` bytes into an array. + pub fn array(&mut self) -> Result<[u8; N]> { + let s = self.bytes(N)?; + let mut a = [0u8; N]; + a.copy_from_slice(s); + Ok(a) + } + pub fn u8(&mut self) -> Result { + let [b] = self.array::<1>()?; + Ok(b) + } + pub fn u16(&mut self) -> Result { + Ok(u16::from_be_bytes(self.array()?)) + } + pub fn i16(&mut self) -> Result { + Ok(i16::from_be_bytes(self.array()?)) + } + pub fn u24(&mut self) -> Result { + let [a, b, c] = self.array::<3>()?; + Ok(u32::from_be_bytes([0, a, b, c])) + } + pub fn u32(&mut self) -> Result { + Ok(u32::from_be_bytes(self.array()?)) + } + pub fn i32(&mut self) -> Result { + Ok(i32::from_be_bytes(self.array()?)) + } + pub fn u64(&mut self) -> Result { + Ok(u64::from_be_bytes(self.array()?)) + } + pub fn i64(&mut self) -> Result { + Ok(i64::from_be_bytes(self.array()?)) + } + pub fn f64(&mut self) -> Result { + Ok(f64::from_be_bytes(self.array()?)) + } + pub fn fourcc(&mut self) -> Result { + Ok(FourCc(self.array()?)) + } + /// Full-box header: `(version, flags)`. + pub fn full_header(&mut self) -> Result<(u8, u32)> { + let v = self.u32()?; + Ok(((v >> 24) as u8, v & 0x00FF_FFFF)) + } + /// Read a 32-bit entry count and check that `count * entry_size` bytes remain, so a hostile + /// count cannot drive a large allocation. + pub fn count(&mut self, entry_size: usize) -> Result { + let n = self.u32()? as usize; + self.check_count(n, entry_size)?; + Ok(n) + } + /// Check that `n * entry_size` bytes remain. + pub fn check_count(&self, n: usize, entry_size: usize) -> Result<()> { + match n.checked_mul(entry_size) { + Some(b) if b <= self.remaining() => Ok(()), + _ => Err(Error::Truncated(self.what)), + } + } +} + +/// The header of one box. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct BoxHeader { + /// Box type. + pub kind: FourCc, + /// Header length in bytes: 8, plus 8 for a 64-bit `largesize`, plus 16 for a `uuid` user type. + pub header_len: u64, + /// Total box size including the header. `None` for a size field of 0: the box runs to the end + /// of its container (or of the file at top level). + pub size: Option, + /// The 16-byte extended type of a `uuid` box. + pub user_type: Option<[u8; 16]>, +} + +impl BoxHeader { + /// The longest possible header: size, type, `largesize` and a `uuid` user type. + pub const MAX_LEN: usize = 32; + + /// Parse a box header from the start of `buf`. Pass at least [`MAX_LEN`](Self::MAX_LEN) bytes + /// when that many are available; fewer are enough for headers without `largesize` or a user + /// type. + /// + /// Errors: [`Error::Truncated`] when `buf` ends inside the header, [`Error::Invalid`] when the + /// declared size is smaller than the header. + pub fn parse(buf: &[u8]) -> Result { + let mut c = Reader::labeled(buf, "box header"); + let size32 = c.u32()?; + let kind = c.fourcc()?; + let mut header_len = 8u64; + let size = match size32 { + 0 => None, + 1 => { + header_len += 8; + Some(c.u64()?) + } + s => Some(u64::from(s)), + }; + let user_type = if kind == b"uuid" { + header_len += 16; + Some(c.array::<16>()?) + } else { + None + }; + if let Some(s) = size + && s < header_len + { + return Err(Error::Invalid(format!("box '{kind}' size {s} smaller than its header"))); + } + Ok(BoxHeader { kind, header_len, size, user_type }) + } + + /// Payload size (box size minus header), or `None` when the box runs to the end. + pub fn payload_size(&self) -> Option { + self.size.map(|s| s.saturating_sub(self.header_len)) + } +} + +/// One box found by [`BoxIter`]. Offsets are relative to the slice the iterator was created with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct BoxRef<'a> { + /// Box type. + pub kind: FourCc, + /// The 16-byte extended type of a `uuid` box. The payload starts after it. + pub user_type: Option<[u8; 16]>, + /// Offset of the box's first header byte. + pub offset: usize, + /// Header length in bytes, including `largesize` and the `uuid` user type. + pub header_len: usize, + /// The box contents after the header. + pub payload: &'a [u8], + /// The size field was 0, so the box runs to the end of the iterated range. + pub extends_to_end: bool, + /// The declared size went past the end of the range and the payload was cut there. Only + /// [`BoxIter::allow_truncated`] produces this. + pub truncated: bool, +} + +impl BoxRef<'_> { + /// Offset one past the box's last byte (where the next sibling starts). + pub fn end(&self) -> usize { + self.offset.saturating_add(self.header_len).saturating_add(self.payload.len()) + } + /// The byte range of the whole box, header included. + pub fn range(&self) -> Range { + self.offset..self.end() + } + /// The byte range of the payload. + pub fn payload_range(&self) -> Range { + self.offset.saturating_add(self.header_len)..self.end() + } +} + +/// Iterator over the sibling boxes in a byte range. +/// +/// Yields each complete box in order. A malformed header or a box larger than the remaining range +/// yields one `Err` and ends the iteration, so the iterator always terminates and never reads +/// outside the range. Fewer than 8 trailing bytes that are all zero (the QuickTime 32-bit +/// terminator) end the iteration silently; other short trailing data is an error. +#[derive(Clone, Debug)] +pub struct BoxIter<'a> { + data: &'a [u8], + pos: usize, + end: usize, + allow_truncated: bool, + done: bool, +} + +impl<'a> BoxIter<'a> { + /// Iterate the boxes in all of `data`. + pub fn new(data: &'a [u8]) -> Self { + Self::within(data, 0..data.len()) + } + + /// Iterate the boxes in `data[range]`, reporting offsets relative to `data`. Use it to walk + /// into a box's [`payload_range`](BoxRef::payload_range) (or a part of it, after a full-box + /// header or a sample entry's fixed fields) and keep file offsets. A range that reaches past + /// `data` is cut at its end. + pub fn within(data: &'a [u8], range: Range) -> Self { + let end = range.end.min(data.len()); + let pos = range.start.min(end); + BoxIter { data, pos, end, allow_truncated: false, done: false } + } + + /// Accept a last box whose declared size runs past the end of the range: it is yielded with + /// the payload cut at the end and [`BoxRef::truncated`] set, and the iteration ends. For + /// partially downloaded or cut files. + pub fn allow_truncated(mut self) -> Self { + self.allow_truncated = true; + self + } + + /// Offset where the next box would start, relative to the iterated slice. + pub fn offset(&self) -> usize { + self.pos + } + + fn step(&mut self) -> Option>> { + let rest = self.data.get(self.pos..self.end).unwrap_or(&[]); + if rest.is_empty() { + return None; + } + if rest.len() < 8 { + if rest.iter().all(|&b| b == 0) { + return None; + } + return Some(Err(Error::Truncated("box header"))); + } + let h = match BoxHeader::parse(rest) { + Ok(h) => h, + Err(e) => return Some(Err(e)), + }; + let avail = rest.len() as u64; + let (size, truncated) = match h.size { + None => (avail, false), + Some(s) if s <= avail => (s, false), + Some(_) if self.allow_truncated => (avail, true), + Some(s) => { + return Some(Err(Error::Invalid(format!("box '{}' size {s} exceeds its container ({avail} bytes left)", h.kind)))); + } + }; + // `size <= rest.len()` and `header_len <= size` (or the header could not have parsed from + // `rest`), so both fit in usize. + let (size, header_len) = (size as usize, h.header_len as usize); + let payload = rest.get(header_len..size)?; + let b = BoxRef { kind: h.kind, user_type: h.user_type, offset: self.pos, header_len, payload, extends_to_end: h.size.is_none(), truncated }; + self.pos += size; + if truncated { + self.done = true; + } + Some(Ok(b)) + } +} + +impl<'a> Iterator for BoxIter<'a> { + type Item = Result>; + fn next(&mut self) -> Option { + if self.done { + return None; + } + let item = self.step(); + if !matches!(item, Some(Ok(_))) { + self.done = true; + } + item + } +} + +impl std::iter::FusedIterator for BoxIter<'_> {} + +/// Iterate the boxes in all of `data`; the same as [`BoxIter::new`]. +pub fn boxes(data: &[u8]) -> BoxIter<'_> { + BoxIter::new(data) +} + +/// The payload of the first box of type `kind` in `data`. Boxes after a malformed one are not +/// searched. +pub fn find<'a>(data: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> { + boxes(data).map_while(|b| b.ok()).find(|b| b.kind == kind).map(|b| b.payload) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::isobmff::bytes::BoxBuf; + + fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec { + let mut v = ((payload.len() + 8) as u32).to_be_bytes().to_vec(); + v.extend_from_slice(kind); + v.extend_from_slice(payload); + v + } + + #[test] + fn header_forms() { + let h = BoxHeader::parse(&[0, 0, 0, 16, b'f', b'r', b'e', b'e']).unwrap(); + assert_eq!((h.kind, h.header_len, h.size, h.payload_size()), (FourCc(*b"free"), 8, Some(16), Some(8))); + let h = BoxHeader::parse(&[0, 0, 0, 0, b'm', b'd', b'a', b't']).unwrap(); + assert_eq!((h.size, h.payload_size()), (None, None)); + let mut v = vec![0, 0, 0, 1, b'm', b'd', b'a', b't']; + v.extend_from_slice(&100u64.to_be_bytes()); + let h = BoxHeader::parse(&v).unwrap(); + assert_eq!((h.header_len, h.size), (16, Some(100))); + let mut v = vec![0, 0, 0, 30, b'u', b'u', b'i', b'd']; + v.extend_from_slice(&[7u8; 16]); + let h = BoxHeader::parse(&v).unwrap(); + assert_eq!((h.header_len, h.user_type), (24, Some([7u8; 16]))); + assert!(BoxHeader::parse(&[0, 0, 0, 4, b'f', b'r', b'e', b'e']).is_err()); + assert!(BoxHeader::parse(&[0, 0, 0]).is_err()); + // A uuid box whose size does not cover its user type. + let mut v = vec![0, 0, 0, 20, b'u', b'u', b'i', b'd']; + v.extend_from_slice(&[7u8; 16]); + assert!(BoxHeader::parse(&v).is_err()); + } + + #[test] + fn iterate_children() { + let mut b = BoxBuf::new(); + b.leaf(b"aaaa", &[1, 2]); + let m = b.start(b"bbbb"); + b.leaf(b"cccc", &[]); + b.end(m); + b.u32(0); // QT terminator + let kids: Vec<_> = boxes(&b.buf).collect::>>().unwrap(); + assert_eq!(kids.len(), 2); + assert_eq!(kids[0].payload, &[1, 2]); + assert_eq!((kids[1].offset, kids[1].payload_range(), kids[1].range()), (10, 18..26, 10..26)); + assert_eq!(find(&b.buf, b"bbbb").map(|p| p.len()), Some(8)); + let inner: Vec<_> = BoxIter::within(&b.buf, kids[1].payload_range()).map(|r| r.unwrap().offset).collect(); + assert_eq!(inner, [18]); + // Oversized child → one error, then the iterator stops. + let bad = [0u8, 0, 0, 99, b'x', b'x', b'x', b'x', 0]; + let mut it = boxes(&bad); + assert!(it.next().unwrap().is_err()); + assert!(it.next().is_none()); + } + + #[test] + fn large_size_zero_size_and_uuid() { + let mut large = vec![0, 0, 0, 1, b'm', b'd', b'a', b't']; + large.extend_from_slice(&19u64.to_be_bytes()); + large.extend_from_slice(&[9, 9, 9]); + let mut uuid = vec![0, 0, 0, 26, b'u', b'u', b'i', b'd']; + uuid.extend_from_slice(&[0xAB; 16]); + uuid.extend_from_slice(&[1, 2]); + let tail = [0, 0, 0, 0, b'm', b'd', b'a', b't', 5, 6, 7]; + let file = [large, uuid, tail.to_vec()].concat(); + let all: Vec<_> = boxes(&file).collect::>>().unwrap(); + assert_eq!(all.len(), 3); + assert_eq!((all[0].header_len, all[0].payload), (16, &[9u8, 9, 9][..])); + assert_eq!((all[1].user_type, all[1].header_len, all[1].payload), (Some([0xAB; 16]), 24, &[1u8, 2][..])); + assert_eq!((all[2].offset, all[2].extends_to_end, all[2].payload), (45, true, &[5u8, 6, 7][..])); + // Size 0 inside a range runs to the end of the range, not of the slice. + let in_range: Vec<_> = BoxIter::within(&file, 45..53).map(|r| r.unwrap().payload.len()).collect(); + assert_eq!(in_range, [0]); + } + + #[test] + fn truncated_last_box() { + let mut file = bx(b"ftyp", b"jp2 "); + let mut cut = bx(b"jp2c", &[0xFF, 0x4F, 0xFF, 0x51, 0, 0]); + cut.truncate(10); + file.extend_from_slice(&cut); + assert!(boxes(&file).nth(1).unwrap().is_err()); + let all: Vec<_> = boxes(&file).allow_truncated().collect::>>().unwrap(); + assert_eq!(all.len(), 2); + assert!(!all[0].truncated); + assert_eq!((all[1].truncated, all[1].payload), (true, &[0xFF, 0x4F][..])); + } + + #[test] + fn hostile_sizes_never_panic() { + let headers: [&[u8]; 6] = [ + &[0xFF, 0xFF, 0xFF, 0xFF, b'a', b'b', b'c', b'd'], + &[0, 0, 0, 1, b'a', b'b', b'c', b'd', 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], + &[0, 0, 0, 1, b'a', b'b', b'c', b'd', 0, 0, 0, 0, 0, 0, 0, 3], + &[0, 0, 0, 1, b'u', b'u', b'i', b'd', 0, 0, 0, 0, 0, 0, 0, 30], + &[0, 0, 0, 0, b'u', b'u', b'i', b'd', 1, 2, 3], + &[0, 0, 0, 7, b'a', b'b', b'c', b'd'], + ]; + for h in headers { + for lenient in [false, true] { + let mut it = BoxIter::new(h); + if lenient { + it = it.allow_truncated(); + } + assert!(it.count() <= 1); + } + } + // Ranges outside the data are clipped. + assert_eq!(BoxIter::within(&[0, 0, 0, 8, 1, 2, 3, 4], 4..100).count(), 1); + #[allow(clippy::reversed_empty_ranges)] + let backwards = 6..2; + assert_eq!(BoxIter::within(&[0; 8], backwards).count(), 0); + assert_eq!(BoxIter::within(&[0; 8], 50..60).count(), 0); + } + + #[test] + fn reader_bounds() { + let mut c = Reader::labeled(&[0, 0, 0, 5, 1], "t"); + assert!(c.count(1).is_err()); + let mut c = Reader::new(&[0xFF, 0xFF, 0xFF, 0xFF]); + assert!(c.count(usize::MAX).is_err()); + let mut c = Reader::new(&[1, 2, 3, 4, 5]); + assert_eq!(c.u24().unwrap(), 0x010203); + assert!(c.u32().is_err()); + assert_eq!((c.position(), c.rest()), (3, &[4u8, 5][..])); + assert!(matches!(Reader::labeled(&[], "x").u8(), Err(Error::Truncated("x")))); + } +} diff --git a/crates/media/src/isobmff/bytes.rs b/crates/media/src/isobmff/bytes.rs new file mode 100644 index 0000000000..92ea81aaf4 --- /dev/null +++ b/crates/media/src/isobmff/bytes.rs @@ -0,0 +1,127 @@ +//! Four-character codes and a box builder for the muxers. Box reading lives in +//! [`boxes`](super::boxes). + +pub(crate) use crate::isobmff::boxes::{BoxHeader, Reader as Cur, boxes, find}; +use std::fmt; + +/// A four-character code (box type, sample entry format, brand, handler type…). +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] +pub struct FourCc(pub [u8; 4]); + +impl FourCc { + pub const fn new(b: &[u8; 4]) -> Self { + FourCc(*b) + } + pub fn as_u32(self) -> u32 { + u32::from_be_bytes(self.0) + } + /// Lossy string form; `©` (0xA9) is mapped to U+00A9, other non-printables to `?`. + pub fn to_string_lossy(self) -> String { + self.0 + .iter() + .map(|&b| match b { + 0xA9 => '©', + 0x20..=0x7E => b as char, + _ => '?', + }) + .collect() + } +} + +impl fmt::Display for FourCc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_string_lossy()) + } +} +impl fmt::Debug for FourCc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "FourCc({:?})", self.to_string_lossy()) + } +} +impl From<&[u8; 4]> for FourCc { + fn from(b: &[u8; 4]) -> Self { + FourCc(*b) + } +} +impl PartialEq<[u8; 4]> for FourCc { + fn eq(&self, other: &[u8; 4]) -> bool { + &self.0 == other + } +} +impl PartialEq<&[u8; 4]> for FourCc { + fn eq(&self, other: &&[u8; 4]) -> bool { + &self.0 == *other + } +} +impl PartialEq<&&[u8; 4]> for FourCc { + fn eq(&self, other: &&&[u8; 4]) -> bool { + &self.0 == **other + } +} + +/// Growable buffer for building boxes. +#[derive(Default, Clone, Debug)] +pub(crate) struct BoxBuf { + pub buf: Vec, +} + +impl BoxBuf { + pub fn new() -> Self { + Self::default() + } + /// Begin a box; returns a marker to pass to [`end`](Self::end). + pub fn start(&mut self, kind: &[u8; 4]) -> usize { + let at = self.buf.len(); + self.buf.extend_from_slice(&[0, 0, 0, 0]); + self.buf.extend_from_slice(kind); + at + } + pub fn start_full(&mut self, kind: &[u8; 4], version: u8, flags: u32) -> usize { + let at = self.start(kind); + self.u32(((version as u32) << 24) | (flags & 0xFF_FFFF)); + at + } + pub fn end(&mut self, at: usize) { + let size = (self.buf.len() - at) as u32; + self.buf[at..at + 4].copy_from_slice(&size.to_be_bytes()); + } + /// Append a complete box with the given payload. + pub fn leaf(&mut self, kind: &[u8; 4], payload: &[u8]) { + let at = self.start(kind); + self.bytes(payload); + self.end(at); + } + pub fn u8(&mut self, v: u8) { + self.buf.push(v); + } + pub fn u16(&mut self, v: u16) { + self.buf.extend_from_slice(&v.to_be_bytes()); + } + pub fn i16(&mut self, v: i16) { + self.buf.extend_from_slice(&v.to_be_bytes()); + } + pub fn u32(&mut self, v: u32) { + self.buf.extend_from_slice(&v.to_be_bytes()); + } + pub fn i32(&mut self, v: i32) { + self.buf.extend_from_slice(&v.to_be_bytes()); + } + pub fn u64(&mut self, v: u64) { + self.buf.extend_from_slice(&v.to_be_bytes()); + } + pub fn i64(&mut self, v: i64) { + self.buf.extend_from_slice(&v.to_be_bytes()); + } + pub fn f64(&mut self, v: f64) { + self.buf.extend_from_slice(&v.to_be_bytes()); + } + pub fn bytes(&mut self, b: &[u8]) { + self.buf.extend_from_slice(b); + } + pub fn zeros(&mut self, n: usize) { + self.buf.resize(self.buf.len() + n, 0); + } + pub fn len(&self) -> usize { + self.buf.len() + } +} diff --git a/crates/media/src/isobmff/codec.rs b/crates/media/src/isobmff/codec.rs new file mode 100644 index 0000000000..b4935c9f65 --- /dev/null +++ b/crates/media/src/isobmff/codec.rs @@ -0,0 +1,1803 @@ +//! Sample entries (`stsd` children) and codec configuration records: parsing and serialization. + +use crate::bitstream::BitReader; +use crate::isobmff::bytes::{BoxBuf, Cur, FourCc, boxes}; +use crate::isobmff::error::{Error, Result}; + +/// One sample description (an entry of `stsd`). +#[derive(Clone, Debug, PartialEq)] +pub struct SampleEntry { + /// Sample entry format (`avc1`, `mp4a`, `apch`, …). + pub format: FourCc, + pub data_reference_index: u16, + pub codec: CodecConfig, + /// Present for visual sample entries. + pub video: Option, + /// Present for audio sample entries. + pub audio: Option, + /// `btrt` box. + pub bitrate: Option, +} + +/// Fields common to all visual sample entries plus the optional descriptive boxes. +#[derive(Clone, Debug, PartialEq, Default)] +pub struct VideoParams { + pub width: u16, + pub height: u16, + /// Horizontal/vertical resolution in pixels per inch (16.16 fixed point; 72 dpi = 0x0048_0000). + pub horiz_resolution: u32, + pub vert_resolution: u32, + pub frame_count: u16, + pub compressor_name: String, + pub depth: u16, + /// QuickTime `vendor` / version fields (zero in ISO files). + pub vendor: FourCc, + pub temporal_quality: u32, + pub spatial_quality: u32, + pub color: Option, + /// `pasp`: (hSpacing, vSpacing). + pub pixel_aspect: Option<(u32, u32)>, + pub clean_aperture: Option, + pub field_info: Option, + /// QuickTime `gama` (16.16 fixed point). + pub gamma: Option, + /// `mdcv`: mastering display color volume (SMPTE ST 2086). + pub mastering_display: Option, + /// `clli`: content light level (MaxCLL, MaxFALL in cd/m²; 0 = unknown). + pub content_light: Option<(u16, u16)>, +} + +/// SMPTE ST 2086 mastering display metadata, in the units of the `mdcv` box and the H.264/HEVC +/// SEI: chromaticities in 0.00002 steps (order G, B, R as the SEI), luminance in 0.0001 cd/m². +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MasteringDisplay { + pub primaries: [(u16, u16); 3], + pub white_point: (u16, u16), + pub max_luminance: u32, + pub min_luminance: u32, +} + +impl MasteringDisplay { + /// BT.2020 primaries, D65, with the given peak and black in cd/m². + pub fn bt2020(max_nits: f64, min_nits: f64) -> Self { + let q = |v: f64| (v / 0.00002).round() as u16; + MasteringDisplay { + primaries: [(q(0.170), q(0.797)), (q(0.131), q(0.046)), (q(0.708), q(0.292))], + white_point: (q(0.3127), q(0.3290)), + max_luminance: (max_nits * 10_000.0).round() as u32, + min_luminance: (min_nits * 10_000.0).round() as u32, + } + } + pub fn max_nits(&self) -> f64 { + self.max_luminance as f64 / 10_000.0 + } + /// The 24-byte payload shared by `mdcv` and the SEI message. + pub fn to_bytes(&self) -> Vec { + let mut v = Vec::with_capacity(24); + for (x, y) in self.primaries { + v.extend_from_slice(&x.to_be_bytes()); + v.extend_from_slice(&y.to_be_bytes()); + } + v.extend_from_slice(&self.white_point.0.to_be_bytes()); + v.extend_from_slice(&self.white_point.1.to_be_bytes()); + v.extend_from_slice(&self.max_luminance.to_be_bytes()); + v.extend_from_slice(&self.min_luminance.to_be_bytes()); + v + } + pub fn parse(p: &[u8]) -> Option { + if p.len() < 24 { + return None; + } + let u16_at = |i: usize| u16::from_be_bytes([p[i], p[i + 1]]); + let u32_at = |i: usize| u32::from_be_bytes([p[i], p[i + 1], p[i + 2], p[i + 3]]); + Some(MasteringDisplay { + primaries: [(u16_at(0), u16_at(2)), (u16_at(4), u16_at(6)), (u16_at(8), u16_at(10))], + white_point: (u16_at(12), u16_at(14)), + max_luminance: u32_at(16), + min_luminance: u32_at(20), + }) + } +} + +/// `colr` box contents. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ColorInfo { + /// ISO `nclx` (with full-range flag). + Nclx { primaries: u16, transfer: u16, matrix: u16, full_range: bool }, + /// QuickTime `nclc`. + Nclc { primaries: u16, transfer: u16, matrix: u16 }, + /// Embedded ICC profile (`prof` restricted/unrestricted `rICC`). + Icc { kind: FourCc, profile: Vec }, +} + +/// `clap` clean aperture (all rationals num/den; offsets are signed). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CleanAperture { + pub width: (u32, u32), + pub height: (u32, u32), + pub horiz_offset: (i32, u32), + pub vert_offset: (i32, u32), +} + +/// QuickTime `fiel`: field count (1 progressive, 2 interlaced) and ordering detail +/// (0, 1 = top first, 6 = bottom first, 9 / 14 per the QuickTime spec). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FieldInfo { + pub fields: u8, + pub detail: u8, +} + +/// `btrt` box. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BitRate { + pub buffer_size: u32, + pub max_bitrate: u32, + pub avg_bitrate: u32, +} + +/// Fields of audio sample entries (ISO v0 plus QuickTime sound description v1/v2 extensions). +#[derive(Clone, Debug, PartialEq, Default)] +pub struct AudioParams { + /// QuickTime sound description version (0, 1, 2). ISO files use 0. + pub qt_version: u16, + pub channels: u32, + /// Bits per sample from the entry (16 for most compressed formats). + pub sample_size: u16, + pub sample_rate: f64, + pub compression_id: i16, + /// v1 fields. + pub samples_per_packet: u32, + pub bytes_per_packet: u32, + pub bytes_per_frame: u32, + pub bytes_per_sample: u32, + /// v2 fields. + pub const_bits_per_channel: u32, + pub lpcm_flags: u32, + pub const_bytes_per_packet: u32, + pub const_frames_per_packet: u32, + /// `enda` little-endian flag inside a QuickTime `wave` box. + pub little_endian: Option, +} + +/// Codec configuration decoded from the sample entry. +#[derive(Clone, Debug, PartialEq)] +pub enum CodecConfig { + Avc(AvcConfig), + Hevc(HevcConfig), + Av1(Av1Config), + Vp9(VpcConfig), + /// Apple ProRes; fourcc is `apch`/`apcn`/`apcs`/`apco`/`ap4h`/`ap4x`. + ProRes { + fourcc: FourCc, + }, + /// Motion JPEG (`jpeg`, `mjpa`, `mjpb`). + Jpeg { + fourcc: FourCc, + }, + /// Avid DNxHD/DNxHR (`AVdn`, `AVdh`). + Dnx { + fourcc: FourCc, + }, + /// Advanced Professional Video (`apv1` + `apvC`). + Apv(ApvConfig), + Aac(AacConfig), + /// MPEG-1/2 audio (esds object type 0x69/0x6B, or QuickTime `.mp3` / `.mp2`). Usually layer + /// III, but these name no layer: ffmpeg stores MP2 as `mp4a` + 0x6B. Each frame header has it. + Mp3, + Pcm(PcmConfig), + /// ALAC magic cookie (ALACSpecificConfig, 24 bytes, optionally followed by a channel layout). + Alac { + cookie: Vec, + }, + Opus(OpusConfig), + Flac(FlacConfig), + /// `dac3` payload. + Ac3 { + dac3: Vec, + }, + /// `dec3` payload. + Eac3 { + dec3: Vec, + }, + Timecode(TimecodeConfig), + /// Anything else; `raw` is the full sample entry payload (after the 8-byte box header). + Unknown { + fourcc: FourCc, + raw: Vec, + }, +} + +impl CodecConfig { + /// A short human-readable codec name. + pub fn name(&self) -> &'static str { + match self { + CodecConfig::Avc(_) => "h264", + CodecConfig::Hevc(_) => "hevc", + CodecConfig::Av1(_) => "av1", + CodecConfig::Vp9(_) => "vp9", + CodecConfig::ProRes { .. } => "prores", + CodecConfig::Jpeg { .. } => "mjpeg", + CodecConfig::Dnx { .. } => "dnxhd", + CodecConfig::Apv(_) => "apv", + CodecConfig::Aac(_) => "aac", + CodecConfig::Mp3 => "mp3", + CodecConfig::Pcm(_) => "pcm", + CodecConfig::Alac { .. } => "alac", + CodecConfig::Opus(_) => "opus", + CodecConfig::Flac(_) => "flac", + CodecConfig::Ac3 { .. } => "ac3", + CodecConfig::Eac3 { .. } => "eac3", + CodecConfig::Timecode(_) => "timecode", + CodecConfig::Unknown { .. } => "unknown", + } + } +} + +/// `avcC` — AVCDecoderConfigurationRecord (ISO/IEC 14496-15 §5.3.3). +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct AvcConfig { + pub profile: u8, + pub compatibility: u8, + pub level: u8, + /// NAL length field size in bytes (1, 2 or 4). + pub length_size: u8, + pub sps: Vec>, + pub pps: Vec>, + /// Bytes after the PPS list (high-profile extension: chroma format, bit depths, SPS-ext). + pub ext: Vec, +} + +impl AvcConfig { + /// Build from parameter sets (NAL units without start codes); profile/level taken from the first SPS. + pub fn new(sps: Vec>, pps: Vec>, length_size: u8) -> Self { + let (profile, compatibility, level) = sps.first().filter(|s| s.len() >= 4).map(|s| (s[1], s[2], s[3])).unwrap_or((0, 0, 0)); + AvcConfig { profile, compatibility, level, length_size, sps, pps, ext: Vec::new() } + } + + pub fn parse(data: &[u8]) -> Result { + let mut c = Cur::labeled(data, "avcC"); + let _version = c.u8()?; + let profile = c.u8()?; + let compatibility = c.u8()?; + let level = c.u8()?; + let length_size = (c.u8()? & 3) + 1; + let nsps = (c.u8()? & 0x1F) as usize; + let mut sps = Vec::with_capacity(nsps); + for _ in 0..nsps { + let n = c.u16()? as usize; + sps.push(c.bytes(n)?.to_vec()); + } + let npps = c.u8()? as usize; + let mut pps = Vec::with_capacity(npps); + for _ in 0..npps { + let n = c.u16()? as usize; + pps.push(c.bytes(n)?.to_vec()); + } + Ok(AvcConfig { profile, compatibility, level, length_size, sps, pps, ext: c.rest().to_vec() }) + } + + pub fn to_bytes(&self) -> Vec { + let mut b = BoxBuf::new(); + b.u8(1); + b.u8(self.profile); + b.u8(self.compatibility); + b.u8(self.level); + b.u8(0xFC | (self.length_size.clamp(1, 4) - 1)); + b.u8(0xE0 | (self.sps.len().min(31) as u8)); + for s in self.sps.iter().take(31) { + b.u16(s.len() as u16); + b.bytes(s); + } + b.u8(self.pps.len().min(255) as u8); + for p in self.pps.iter().take(255) { + b.u16(p.len() as u16); + b.bytes(p); + } + b.bytes(&self.ext); + b.buf + } +} + +/// One NAL array of an `hvcC` record. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct HevcNalArray { + pub completeness: bool, + pub nal_type: u8, + pub nalus: Vec>, +} + +/// `hvcC` — HEVCDecoderConfigurationRecord (ISO/IEC 14496-15 §8.3.3). +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct HevcConfig { + pub general_profile_space: u8, + pub general_tier_flag: bool, + pub general_profile_idc: u8, + pub general_profile_compatibility_flags: u32, + /// 48 bits of general constraint indicator flags. + pub general_constraint_indicator_flags: u64, + pub general_level_idc: u8, + pub min_spatial_segmentation_idc: u16, + pub parallelism_type: u8, + pub chroma_format_idc: u8, + pub bit_depth_luma: u8, + pub bit_depth_chroma: u8, + pub avg_frame_rate: u16, + pub constant_frame_rate: u8, + pub num_temporal_layers: u8, + pub temporal_id_nested: bool, + pub length_size: u8, + pub arrays: Vec, +} + +impl HevcConfig { + pub fn parse(data: &[u8]) -> Result { + let mut c = Cur::labeled(data, "hvcC"); + let _version = c.u8()?; + let b = c.u8()?; + let compat = c.u32()?; + let hi = c.u16()? as u64; + let lo = c.u32()? as u64; + let level = c.u8()?; + let min_seg = c.u16()? & 0x0FFF; + let par = c.u8()? & 3; + let chroma = c.u8()? & 3; + let bdl = (c.u8()? & 7) + 8; + let bdc = (c.u8()? & 7) + 8; + let afr = c.u16()?; + let x = c.u8()?; + let narrays = c.u8()? as usize; + let mut arrays = Vec::new(); + for _ in 0..narrays { + let t = c.u8()?; + let n = c.u16()? as usize; + c.check_count(n, 2)?; + let mut nalus = Vec::with_capacity(n); + for _ in 0..n { + let len = c.u16()? as usize; + nalus.push(c.bytes(len)?.to_vec()); + } + arrays.push(HevcNalArray { completeness: t & 0x80 != 0, nal_type: t & 0x3F, nalus }); + } + Ok(HevcConfig { + general_profile_space: b >> 6, + general_tier_flag: b & 0x20 != 0, + general_profile_idc: b & 0x1F, + general_profile_compatibility_flags: compat, + general_constraint_indicator_flags: (hi << 32) | lo, + general_level_idc: level, + min_spatial_segmentation_idc: min_seg, + parallelism_type: par, + chroma_format_idc: chroma, + bit_depth_luma: bdl, + bit_depth_chroma: bdc, + avg_frame_rate: afr, + constant_frame_rate: x >> 6, + num_temporal_layers: (x >> 3) & 7, + temporal_id_nested: x & 4 != 0, + length_size: (x & 3) + 1, + arrays, + }) + } + + pub fn to_bytes(&self) -> Vec { + let mut b = BoxBuf::new(); + b.u8(1); + b.u8((self.general_profile_space << 6) | ((self.general_tier_flag as u8) << 5) | (self.general_profile_idc & 0x1F)); + b.u32(self.general_profile_compatibility_flags); + b.u16((self.general_constraint_indicator_flags >> 32) as u16); + b.u32(self.general_constraint_indicator_flags as u32); + b.u8(self.general_level_idc); + b.u16(0xF000 | (self.min_spatial_segmentation_idc & 0x0FFF)); + b.u8(0xFC | (self.parallelism_type & 3)); + b.u8(0xFC | (self.chroma_format_idc & 3)); + b.u8(0xF8 | (self.bit_depth_luma.saturating_sub(8) & 7)); + b.u8(0xF8 | (self.bit_depth_chroma.saturating_sub(8) & 7)); + b.u16(self.avg_frame_rate); + b.u8((self.constant_frame_rate << 6) + | ((self.num_temporal_layers & 7) << 3) + | ((self.temporal_id_nested as u8) << 2) + | (self.length_size.clamp(1, 4) - 1)); + b.u8(self.arrays.len() as u8); + for a in &self.arrays { + b.u8(((a.completeness as u8) << 7) | (a.nal_type & 0x3F)); + b.u16(a.nalus.len() as u16); + for n in &a.nalus { + b.u16(n.len() as u16); + b.bytes(n); + } + } + b.buf + } + + fn nalus_of(&self, t: u8) -> Vec<&[u8]> { + self.arrays.iter().filter(|a| a.nal_type == t).flat_map(|a| a.nalus.iter().map(|n| n.as_slice())).collect() + } + pub fn vps(&self) -> Vec<&[u8]> { + self.nalus_of(32) + } + pub fn sps(&self) -> Vec<&[u8]> { + self.nalus_of(33) + } + pub fn pps(&self) -> Vec<&[u8]> { + self.nalus_of(34) + } +} + +/// `av1C` — AV1CodecConfigurationRecord. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct Av1Config { + pub seq_profile: u8, + pub seq_level_idx_0: u8, + pub seq_tier_0: bool, + pub high_bitdepth: bool, + pub twelve_bit: bool, + pub monochrome: bool, + pub chroma_subsampling_x: bool, + pub chroma_subsampling_y: bool, + pub chroma_sample_position: u8, + pub initial_presentation_delay_minus_one: Option, + pub config_obus: Vec, +} + +impl Av1Config { + pub fn parse(data: &[u8]) -> Result { + let mut c = Cur::labeled(data, "av1C"); + let m = c.u8()?; + if m & 0x80 == 0 { + return Err(Error::Invalid("av1C marker bit not set".into())); + } + let a = c.u8()?; + let b = c.u8()?; + let d = c.u8()?; + Ok(Av1Config { + seq_profile: a >> 5, + seq_level_idx_0: a & 0x1F, + seq_tier_0: b & 0x80 != 0, + high_bitdepth: b & 0x40 != 0, + twelve_bit: b & 0x20 != 0, + monochrome: b & 0x10 != 0, + chroma_subsampling_x: b & 0x08 != 0, + chroma_subsampling_y: b & 0x04 != 0, + chroma_sample_position: b & 3, + initial_presentation_delay_minus_one: if d & 0x10 != 0 { Some(d & 0x0F) } else { None }, + config_obus: c.rest().to_vec(), + }) + } + pub fn to_bytes(&self) -> Vec { + let mut b = BoxBuf::new(); + b.u8(0x81); + b.u8((self.seq_profile << 5) | (self.seq_level_idx_0 & 0x1F)); + b.u8(((self.seq_tier_0 as u8) << 7) + | ((self.high_bitdepth as u8) << 6) + | ((self.twelve_bit as u8) << 5) + | ((self.monochrome as u8) << 4) + | ((self.chroma_subsampling_x as u8) << 3) + | ((self.chroma_subsampling_y as u8) << 2) + | (self.chroma_sample_position & 3)); + b.u8(match self.initial_presentation_delay_minus_one { + Some(d) => 0x10 | (d & 0x0F), + None => 0, + }); + b.bytes(&self.config_obus); + b.buf + } +} + +/// `vpcC` — VP codec configuration (version 1). +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct VpcConfig { + pub profile: u8, + pub level: u8, + pub bit_depth: u8, + pub chroma_subsampling: u8, + pub full_range: bool, + pub color_primaries: u8, + pub transfer_characteristics: u8, + pub matrix_coefficients: u8, + pub codec_init: Vec, +} + +impl VpcConfig { + pub fn parse(data: &[u8]) -> Result { + let mut c = Cur::labeled(data, "vpcC"); + let (version, _) = c.full_header()?; + if version == 0 { + // Version 0 draft layout: profile, level, bitDepth(4)|colorSpace(4), chroma(4)|transfer(3)|range(1) + let profile = c.u8()?; + let level = c.u8()?; + let a = c.u8()?; + let b = c.u8()?; + return Ok(VpcConfig { profile, level, bit_depth: a >> 4, chroma_subsampling: b >> 4, full_range: b & 1 != 0, ..Default::default() }); + } + let profile = c.u8()?; + let level = c.u8()?; + let a = c.u8()?; + let color_primaries = c.u8()?; + let transfer_characteristics = c.u8()?; + let matrix_coefficients = c.u8()?; + let n = c.u16()? as usize; + let codec_init = c.bytes(n)?.to_vec(); + Ok(VpcConfig { + profile, + level, + bit_depth: a >> 4, + chroma_subsampling: (a >> 1) & 7, + full_range: a & 1 != 0, + color_primaries, + transfer_characteristics, + matrix_coefficients, + codec_init, + }) + } + pub fn to_bytes(&self) -> Vec { + let mut b = BoxBuf::new(); + b.u32(1 << 24); + b.u8(self.profile); + b.u8(self.level); + b.u8((self.bit_depth << 4) | ((self.chroma_subsampling & 7) << 1) | self.full_range as u8); + b.u8(self.color_primaries); + b.u8(self.transfer_characteristics); + b.u8(self.matrix_coefficients); + b.u16(self.codec_init.len() as u16); + b.bytes(&self.codec_init); + b.buf + } +} + +/// AAC (MPEG-4 audio) configuration from `esds`. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct AacConfig { + /// AudioSpecificConfig bytes (DecoderSpecificInfo). + pub asc: Vec, + /// Audio object type (2 = AAC-LC, 5 = SBR/HE-AAC, 29 = PS …) as signaled first in the ASC. + pub object_type: u8, + /// Sampling rate signaled by the ASC (core rate; 0 if the ASC is missing). + pub sample_rate: u32, + /// Channel configuration from the ASC (0 = defined elsewhere). + pub channel_config: u8, + /// DecoderConfigDescriptor fields. + pub max_bitrate: u32, + pub avg_bitrate: u32, + pub buffer_size: u32, +} + +const AAC_RATES: [u32; 13] = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; + +impl AacConfig { + /// Build from an AudioSpecificConfig, decoding its header fields. + pub fn from_asc(asc: Vec) -> Self { + let (object_type, sample_rate, channel_config) = parse_asc(&asc).unwrap_or((0, 0, 0)); + AacConfig { asc, object_type, sample_rate, channel_config, max_bitrate: 0, avg_bitrate: 0, buffer_size: 0 } + } + /// Channel count implied by the channel configuration (ISO/IEC 14496-3 Table 1.19 with Amd 4: + /// 7 and 12 are 7.1 front / back, 11 is 6.1, 13 is 22.2, 14 is 7.1 with front heights), 0 if + /// unspecified (a PCE) or reserved. + pub fn channels(&self) -> u32 { + match self.channel_config { + 1..=6 => self.channel_config as u32, + 11 => 7, + 7 | 12 | 14 => 8, + 13 => 24, + _ => 0, + } + } +} + +/// Decode (audio object type, sampling frequency, channel configuration) from an AudioSpecificConfig. +pub fn parse_asc(asc: &[u8]) -> Option<(u8, u32, u8)> { + let mut r = BitReader::new(asc); + let aot = |r: &mut BitReader| -> Option { + let t = r.read_bits(5).ok()? as u8; + if t == 31 { Some(32 + r.read_bits(6).ok()? as u8) } else { Some(t) } + }; + let rate = |r: &mut BitReader| -> Option { + let i = r.read_bits(4).ok()? as usize; + if i == 15 { r.read_bits(24).ok() } else { AAC_RATES.get(i).copied() } + }; + let t = aot(&mut r)?; + let sr = rate(&mut r)?; + let ch = r.read_bits(4).ok()? as u8; + Some((t, sr, ch)) +} + +/// Uncompressed PCM description. +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub struct PcmConfig { + pub bits: u16, + pub float: bool, + pub big_endian: bool, + /// Signed integer samples (8-bit `raw ` is unsigned). + pub signed: bool, + pub channels: u32, + pub sample_rate: f64, +} + +impl PcmConfig { + /// Bytes per interleaved audio frame (all channels). + /// Saturates at `u32::MAX` for a hostile channel count or sample size. + pub fn bytes_per_frame(&self) -> u32 { + (self.bits as u32).div_ceil(8).saturating_mul(self.channels.max(1)) + } +} + +/// `dOps` — Opus specific box. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct OpusConfig { + pub output_channels: u8, + pub pre_skip: u16, + pub input_sample_rate: u32, + pub output_gain: i16, + pub channel_mapping_family: u8, + /// StreamCount, CoupledCount and ChannelMapping bytes when family != 0. + pub channel_mapping: Vec, +} + +impl OpusConfig { + pub fn parse(data: &[u8]) -> Result { + let mut c = Cur::labeled(data, "dOps"); + let _version = c.u8()?; + Ok(OpusConfig { + output_channels: c.u8()?, + pre_skip: c.u16()?, + input_sample_rate: c.u32()?, + output_gain: c.i16()?, + channel_mapping_family: c.u8()?, + channel_mapping: c.rest().to_vec(), + }) + } + pub fn to_bytes(&self) -> Vec { + let mut b = BoxBuf::new(); + b.u8(0); + b.u8(self.output_channels); + b.u16(self.pre_skip); + b.u32(self.input_sample_rate); + b.i16(self.output_gain); + b.u8(self.channel_mapping_family); + b.bytes(&self.channel_mapping); + b.buf + } +} + +/// `dfLa` — FLAC metadata blocks, with STREAMINFO decoded. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct FlacConfig { + /// Raw metadata blocks (each with its 4-byte header) as stored in `dfLa`. + pub metadata_blocks: Vec, + pub sample_rate: u32, + pub channels: u8, + pub bits_per_sample: u8, + pub total_samples: u64, +} + +impl FlacConfig { + pub fn parse(data: &[u8]) -> Result { + let mut c = Cur::labeled(data, "dfLa"); + c.full_header()?; + let blocks = c.rest().to_vec(); + let mut cfg = FlacConfig { metadata_blocks: blocks.clone(), ..Default::default() }; + let mut b = Cur::labeled(&blocks, "dfLa"); + let hdr = b.u32()?; + if (hdr >> 24) & 0x7F == 0 { + let si = b.bytes(((hdr & 0xFF_FFFF) as usize).min(34))?; + if si.len() >= 18 { + let mut r = BitReader::new(&si[10..18]); + cfg.sample_rate = r.read_bits(20).unwrap_or(0); + cfg.channels = r.read_bits(3).unwrap_or(0) as u8 + 1; + cfg.bits_per_sample = r.read_bits(5).unwrap_or(0) as u8 + 1; + cfg.total_samples = r.read_bits_u64(36).unwrap_or(0); + } + } + Ok(cfg) + } +} + +/// QuickTime timecode sample description (`tmcd`) plus the start frame read from its first sample. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct TimecodeConfig { + /// Bit 0 drop frame, bit 1 24-hour max, bit 2 negative times OK, bit 3 counter. + pub flags: u32, + pub timescale: u32, + pub frame_duration: u32, + /// Nominal frames per second (`numberOfFrames`), e.g. 30 for 29.97. + pub frames_per_second: u8, + /// Frame number of the first timecode sample (filled in by the demuxer). + pub start_frame: Option, + /// Source reel name (`name` box) if present. + pub name: Option, +} + +impl TimecodeConfig { + pub fn drop_frame(&self) -> bool { + self.flags & 1 != 0 + } + /// Format a frame number as `HH:MM:SS:FF` (`;` before the frames when drop-frame). + pub fn format_frame(&self, frame: u32) -> String { + let fps = self.frames_per_second.max(1) as u64; + let mut f = frame as u64; + if self.drop_frame() && fps >= 30 { + let drop = (fps / 30) * 2; // 2 frames per minute at 30, 4 at 60 + let per_min = fps * 60 - drop; + let per_10 = per_min * 10 + drop; + let d = f / per_10; + let m = f % per_10; + f += drop * 9 * d + if m > drop { drop * ((m - drop) / per_min) } else { 0 }; + } + let ff = f % fps; + let s = (f / fps) % 60; + let mi = (f / fps / 60) % 60; + let h = (f / fps / 3600) % 24; + let sep = if self.drop_frame() { ';' } else { ':' }; + format!("{h:02}:{mi:02}:{s:02}{sep}{ff:02}") + } +} + +/// `apvC` — APVDecoderConfigurationBox (`FullBox('apvC', version = 0, flags = 0)` containing +/// `APVDecoderConfigurationRecord`). +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct ApvConfig { + pub profile_idc: u8, + pub level_idc: u8, + pub band_idc: u8, + pub frame_width: u32, + pub frame_height: u32, + pub chroma_format_idc: u8, + pub bit_depth_minus8: u8, + pub capture_time_distance: u8, + pub capture_time_distance_ignored: bool, + pub color_description_present: bool, + pub color_primaries: u8, + pub transfer_characteristics: u8, + pub matrix_coefficients: u8, + pub full_range: bool, + /// Raw `APVDecoderConfigurationRecord` bytes (after the 4-byte FullBox header). + pub raw_record: Vec, +} + +impl ApvConfig { + /// Build from a raw `APVDecoderConfigurationRecord` (starting with `configurationVersion = 1`). + pub fn from_record(record: Vec) -> Result { + let mut c = Cur::labeled(&record, "apvC"); + let version = c.u8()?; + if version != 1 { + return Err(Error::Invalid(format!("unsupported APVDecoderConfigurationRecord version {version}"))); + } + let num_entries = c.u8()?; + let mut cfg = ApvConfig { raw_record: record.clone(), ..Default::default() }; + if num_entries >= 1 && c.remaining() >= 2 { + let _pbu_type = c.u8()?; + let num_fi = c.u8()?; + if num_fi >= 1 && c.remaining() >= 14 { + let flags = c.u8()?; + cfg.color_description_present = (flags & 0x02) != 0; + cfg.capture_time_distance_ignored = (flags & 0x01) != 0; + cfg.profile_idc = c.u8()?; + cfg.level_idc = c.u8()?; + cfg.band_idc = c.u8()?; + cfg.frame_width = c.u32()?; + cfg.frame_height = c.u32()?; + let cb = c.u8()?; + cfg.chroma_format_idc = cb >> 4; + cfg.bit_depth_minus8 = cb & 0x0F; + cfg.capture_time_distance = c.u8()?; + if cfg.color_description_present && c.remaining() >= 4 { + cfg.color_primaries = c.u8()?; + cfg.transfer_characteristics = c.u8()?; + cfg.matrix_coefficients = c.u8()?; + cfg.full_range = (c.u8()? & 0x80) != 0; + } + } + } + Ok(cfg) + } + + /// Parse the payload of an `apvC` box (with or without the 4-byte `FullBox` header). + pub fn parse(data: &[u8]) -> Result { + if data.len() >= 5 && data[..4] == [0, 0, 0, 0] && data[4] == 1 { + Self::from_record(data[4..].to_vec()) + } else if !data.is_empty() && data[0] == 1 { + Self::from_record(data.to_vec()) + } else { + let mut c = Cur::labeled(data, "apvC"); + let (v, _) = c.full_header()?; + if v != 0 { + return Err(Error::Invalid(format!("unsupported apvC FullBox version {v}"))); + } + Self::from_record(c.rest().to_vec()) + } + } + + /// Serialize the full `apvC` box payload (4-byte `FullBox` header + `APVDecoderConfigurationRecord`). + pub fn to_bytes(&self) -> Vec { + let mut b = BoxBuf::new(); + b.u32(0); // FullBox version = 0, flags = 0 + if !self.raw_record.is_empty() { + b.bytes(&self.raw_record); + return b.buf; + } + b.u8(1); // configurationVersion = 1 + b.u8(1); // number_of_configuration_entry = 1 + b.u8(1); // pbu_type = 1 (primary frame) + b.u8(1); // number_of_frame_info = 1 + let flags = (if self.color_description_present { 0x02 } else { 0 }) | (if self.capture_time_distance_ignored { 0x01 } else { 0 }); + b.u8(flags); + b.u8(self.profile_idc); + b.u8(self.level_idc); + b.u8(self.band_idc); + b.u32(self.frame_width); + b.u32(self.frame_height); + b.u8((self.chroma_format_idc << 4) | (self.bit_depth_minus8 & 0x0F)); + b.u8(self.capture_time_distance); + if self.color_description_present { + b.u8(self.color_primaries); + b.u8(self.transfer_characteristics); + b.u8(self.matrix_coefficients); + b.u8(if self.full_range { 0x80 } else { 0 }); + } + b.buf + } +} + +// --------------------------------------------------------------------------------------------- +// Parsing + +fn is_video_fourcc(f: &[u8; 4]) -> bool { + matches!( + f, + b"avc1" + | b"avc3" + | b"hvc1" + | b"hev1" + | b"av01" + | b"vp09" + | b"vp08" + | b"apch" + | b"apcn" + | b"apcs" + | b"apco" + | b"ap4h" + | b"ap4x" + | b"apv1" + | b"jpeg" + | b"mjpa" + | b"mjpb" + | b"AVdn" + | b"AVdh" + | b"mp4v" + | b"encv" + | b"raw " + | b"2vuy" + | b"v210" + ) +} + +fn is_audio_fourcc(f: &[u8; 4]) -> bool { + matches!( + f, + b"mp4a" + | b"lpcm" + | b"sowt" + | b"twos" + | b"in24" + | b"in32" + | b"fl32" + | b"fl64" + | b"ipcm" + | b"fpcm" + | b"alac" + | b"Opus" + | b"fLaC" + | b"ac-3" + | b"ec-3" + | b".mp3" + | b".mp2" + | b"enca" + | b"ulaw" + | b"alaw" + | b"NONE" + ) +} + +/// Parse one `stsd` entry. `handler` is the track handler type; `is_qt` selects QuickTime +/// interpretation of the sound description version field. +pub(crate) fn parse_sample_entry(format: FourCc, payload: &[u8], handler: FourCc, is_qt: bool) -> Result { + let mut c = Cur::labeled(payload, "sample entry"); + c.skip(6)?; + let data_reference_index = c.u16()?; + let f = &format.0; + let unknown = || CodecConfig::Unknown { fourcc: format, raw: payload.to_vec() }; + if f == b"tmcd" || (handler == b"tmcd" && !is_video_fourcc(f)) { + let mut tc = TimecodeConfig::default(); + c.skip(4)?; + tc.flags = c.u32()?; + tc.timescale = c.u32()?; + tc.frame_duration = c.u32()?; + tc.frames_per_second = c.u8()?; + c.skip(1)?; + for b in boxes(c.rest()).map_while(|b| b.ok()) { + if b.kind == b"name" && b.payload.len() >= 4 { + let n = u16::from_be_bytes([b.payload[0], b.payload[1]]) as usize; + let s = b.payload.get(4..4 + n).unwrap_or(&b.payload[4..]); + tc.name = Some(String::from_utf8_lossy(s).into_owned()); + } + } + return Ok(SampleEntry { format, data_reference_index, codec: CodecConfig::Timecode(tc), video: None, audio: None, bitrate: None }); + } + // `raw ` names both uncompressed video and 8-bit unsigned PCM; the handler decides. + let raw_audio = f == b"raw " && handler == b"soun"; + let video_like = (is_video_fourcc(f) && !raw_audio) || (handler == b"vide" && !is_audio_fourcc(f)); + let audio_like = is_audio_fourcc(f) || (handler == b"soun" && !video_like); + if video_like { + let mut v = VideoParams::default(); + let _version = c.u16()?; + let _revision = c.u16()?; + v.vendor = c.fourcc()?; + v.temporal_quality = c.u32()?; + v.spatial_quality = c.u32()?; + v.width = c.u16()?; + v.height = c.u16()?; + v.horiz_resolution = c.u32()?; + v.vert_resolution = c.u32()?; + c.skip(4)?; + v.frame_count = c.u16()?; + let name = c.bytes(32)?; + let n = (name[0] as usize).min(31); + v.compressor_name = String::from_utf8_lossy(&name[1..1 + n]).into_owned(); + v.depth = c.u16()?; + let _ctab = c.i16()?; + let mut codec = None; + let mut bitrate = None; + for b in boxes(c.rest()).map_while(|b| b.ok()) { + let p = b.payload; + match &b.kind.0 { + b"avcC" if matches!(f, b"avc1" | b"avc3") => codec = Some(CodecConfig::Avc(AvcConfig::parse(p)?)), + b"hvcC" if matches!(f, b"hvc1" | b"hev1") => codec = Some(CodecConfig::Hevc(HevcConfig::parse(p)?)), + b"av1C" if f == b"av01" => codec = Some(CodecConfig::Av1(Av1Config::parse(p)?)), + b"vpcC" if f == b"vp09" => codec = Some(CodecConfig::Vp9(VpcConfig::parse(p)?)), + b"apvC" if f == b"apv1" => codec = Some(CodecConfig::Apv(ApvConfig::parse(p)?)), + b"colr" => v.color = parse_colr(p).ok(), + b"mdcv" => v.mastering_display = MasteringDisplay::parse(p), + b"clli" if p.len() >= 4 => v.content_light = Some((u16::from_be_bytes([p[0], p[1]]), u16::from_be_bytes([p[2], p[3]]))), + b"pasp" => { + let mut c = Cur::labeled(p, "pasp"); + v.pixel_aspect = Some((c.u32()?, c.u32()?)); + } + b"clap" => { + let mut c = Cur::labeled(p, "clap"); + v.clean_aperture = Some(CleanAperture { + width: (c.u32()?, c.u32()?), + height: (c.u32()?, c.u32()?), + horiz_offset: (c.i32()?, c.u32()?), + vert_offset: (c.i32()?, c.u32()?), + }); + } + b"fiel" => { + let mut c = Cur::labeled(p, "fiel"); + v.field_info = Some(FieldInfo { fields: c.u8()?, detail: c.u8()? }); + } + b"gama" => v.gamma = Some(Cur::labeled(p, "gama").u32()?), + b"btrt" => bitrate = Some(parse_btrt(p)?), + _ => {} + } + } + let codec = match codec { + Some(c) => c, + None => match f { + b"apch" | b"apcn" | b"apcs" | b"apco" | b"ap4h" | b"ap4x" => CodecConfig::ProRes { fourcc: format }, + b"jpeg" | b"mjpa" | b"mjpb" => CodecConfig::Jpeg { fourcc: format }, + b"AVdn" | b"AVdh" => CodecConfig::Dnx { fourcc: format }, + b"apv1" => CodecConfig::Apv(ApvConfig::default()), + _ => unknown(), + }, + }; + return Ok(SampleEntry { format, data_reference_index, codec, video: Some(v), audio: None, bitrate }); + } + if audio_like { + let mut a = AudioParams { qt_version: c.u16()?, ..Default::default() }; + let _revision = c.u16()?; + let _vendor = c.u32()?; + a.channels = c.u16()? as u32; + a.sample_size = c.u16()?; + a.compression_id = c.i16()?; + let _packet_size = c.u16()?; + a.sample_rate = c.u32()? as f64 / 65536.0; + if is_qt && a.qt_version == 1 { + a.samples_per_packet = c.u32()?; + a.bytes_per_packet = c.u32()?; + a.bytes_per_frame = c.u32()?; + a.bytes_per_sample = c.u32()?; + } else if is_qt && a.qt_version == 2 { + let _size_of_struct = c.u32()?; + a.sample_rate = c.f64()?; + a.channels = c.u32()?; + let _always = c.u32()?; + a.const_bits_per_channel = c.u32()?; + a.lpcm_flags = c.u32()?; + a.const_bytes_per_packet = c.u32()?; + a.const_frames_per_packet = c.u32()?; + } + // Flatten QuickTime `wave` children into the list of extension boxes. + let mut ext: Vec<(FourCc, &[u8])> = Vec::new(); + for b in boxes(c.rest()).map_while(|b| b.ok()) { + if b.kind == b"wave" { + for w in boxes(b.payload).map_while(|b| b.ok()) { + ext.push((w.kind, w.payload)); + } + } else { + ext.push((b.kind, b.payload)); + } + } + let get = |k: &[u8; 4]| ext.iter().find(|(kk, _)| kk == k).map(|(_, p)| *p); + if let Some(p) = get(b"enda") { + let v = if p.len() >= 2 { u16::from_be_bytes([p[0], p[1]]) } else { p.first().copied().unwrap_or(0) as u16 }; + a.little_endian = Some(v != 0); + } + let bitrate = get(b"btrt").and_then(|p| parse_btrt(p).ok()); + let codec = match f { + b"mp4a" => match get(b"esds") { + Some(p) => parse_esds(p)?, + None => unknown(), + }, + b".mp3" | b".mp2" => CodecConfig::Mp3, + b"alac" => match get(b"alac") { + Some(p) if p.len() >= 4 => CodecConfig::Alac { cookie: p[4..].to_vec() }, + _ => unknown(), + }, + b"Opus" => match get(b"dOps") { + Some(p) => CodecConfig::Opus(OpusConfig::parse(p)?), + None => unknown(), + }, + b"fLaC" => match get(b"dfLa") { + Some(p) => CodecConfig::Flac(FlacConfig::parse(p)?), + None => unknown(), + }, + b"ac-3" => CodecConfig::Ac3 { dac3: get(b"dac3").unwrap_or(&[]).to_vec() }, + b"ec-3" => CodecConfig::Eac3 { dec3: get(b"dec3").unwrap_or(&[]).to_vec() }, + b"lpcm" | b"sowt" | b"twos" | b"in24" | b"in32" | b"fl32" | b"fl64" | b"raw " | b"NONE" => CodecConfig::Pcm(qt_pcm(f, &a)), + b"ipcm" | b"fpcm" => { + let mut pcm = PcmConfig { + bits: a.sample_size, + float: f == b"fpcm", + big_endian: true, + signed: true, + channels: a.channels, + sample_rate: a.sample_rate, + }; + if let Some(p) = get(b"pcmC") { + let mut c = Cur::labeled(p, "pcmC"); + c.full_header()?; + let flags = c.u8()?; + pcm.big_endian = flags & 1 == 0; + pcm.bits = c.u8()? as u16; + } + CodecConfig::Pcm(pcm) + } + _ => unknown(), + }; + return Ok(SampleEntry { format, data_reference_index, codec, video: None, audio: Some(a), bitrate }); + } + Ok(SampleEntry { format, data_reference_index, codec: unknown(), video: None, audio: None, bitrate: None }) +} + +fn qt_pcm(f: &[u8; 4], a: &AudioParams) -> PcmConfig { + let mut p = PcmConfig { channels: a.channels, sample_rate: a.sample_rate, signed: true, ..Default::default() }; + match f { + b"lpcm" => { + p.bits = a.const_bits_per_channel as u16; + p.float = a.lpcm_flags & 1 != 0; + p.big_endian = a.lpcm_flags & 2 != 0; + p.signed = a.lpcm_flags & 4 != 0 || p.float; + if p.bits == 0 { + p.bits = a.sample_size; + } + } + b"sowt" => { + p.bits = if a.sample_size == 0 { 16 } else { a.sample_size }; + } + b"twos" => { + p.bits = if a.sample_size == 0 { 16 } else { a.sample_size }; + p.big_endian = true; + } + b"raw " | b"NONE" => { + p.bits = if a.sample_size == 0 { 8 } else { a.sample_size }; + p.signed = p.bits != 8; + p.big_endian = true; + } + b"in24" | b"in32" | b"fl32" | b"fl64" => { + p.bits = match f { + b"in24" => 24, + b"in32" | b"fl32" => 32, + _ => 64, + }; + p.float = f[0] == b'f'; + p.big_endian = !a.little_endian.unwrap_or(false); + } + _ => {} + } + p +} + +fn parse_btrt(p: &[u8]) -> Result { + let mut c = Cur::labeled(p, "btrt"); + Ok(BitRate { buffer_size: c.u32()?, max_bitrate: c.u32()?, avg_bitrate: c.u32()? }) +} + +fn parse_colr(p: &[u8]) -> Result { + let mut c = Cur::labeled(p, "colr"); + let kind = c.fourcc()?; + Ok(match &kind.0 { + b"nclx" => { + ColorInfo::Nclx { primaries: c.u16()?, transfer: c.u16()?, matrix: c.u16()?, full_range: c.u8().map(|v| v & 0x80 != 0).unwrap_or(false) } + } + b"nclc" => ColorInfo::Nclc { primaries: c.u16()?, transfer: c.u16()?, matrix: c.u16()? }, + _ => ColorInfo::Icc { kind, profile: c.rest().to_vec() }, + }) +} + +fn descriptor(c: &mut Cur) -> Result<(u8, usize)> { + let tag = c.u8()?; + let mut len = 0usize; + for _ in 0..4 { + let b = c.u8()?; + len = (len << 7) | (b & 0x7F) as usize; + if b & 0x80 == 0 { + break; + } + } + Ok((tag, len)) +} + +fn parse_esds(p: &[u8]) -> Result { + let mut c = Cur::labeled(p, "esds"); + c.full_header()?; + let (tag, len) = descriptor(&mut c)?; + if tag != 3 { + return Err(Error::Invalid(format!("esds: expected ES_Descriptor, got tag {tag}"))); + } + let es = c.bytes(len.min(c.remaining()))?; + let mut c = Cur::labeled(es, "ES_Descriptor"); + c.u16()?; + let fl = c.u8()?; + if fl & 0x80 != 0 { + c.u16()?; + } + if fl & 0x40 != 0 { + let n = c.u8()? as usize; + c.skip(n)?; + } + if fl & 0x20 != 0 { + c.u16()?; + } + while c.remaining() > 0 { + let (tag, len) = descriptor(&mut c)?; + let body = c.bytes(len.min(c.remaining()))?; + if tag != 4 { + continue; + } + let mut d = Cur::labeled(body, "DecoderConfigDescriptor"); + let oti = d.u8()?; + let _stream_type = d.u8()?; + let buffer_size = d.u24()?; + let max_bitrate = d.u32()?; + let avg_bitrate = d.u32()?; + let mut asc = Vec::new(); + while d.remaining() > 0 { + let (t, l) = descriptor(&mut d)?; + let b = d.bytes(l.min(d.remaining()))?; + if t == 5 { + asc = b.to_vec(); + break; + } + } + return Ok(match oti { + 0x69 | 0x6B => CodecConfig::Mp3, + _ => { + let mut a = AacConfig::from_asc(asc); + a.max_bitrate = max_bitrate; + a.avg_bitrate = avg_bitrate; + a.buffer_size = buffer_size; + CodecConfig::Aac(a) + } + }); + } + Err(Error::Invalid("esds without DecoderConfigDescriptor".into())) +} + +// --------------------------------------------------------------------------------------------- +// Serialization (muxer) + +fn put_descriptor(b: &mut BoxBuf, tag: u8, body: &[u8]) { + b.u8(tag); + let n = body.len() as u32; + // Always use the 4-byte length form for simplicity (as many encoders do). + b.u8(0x80 | ((n >> 21) & 0x7F) as u8); + b.u8(0x80 | ((n >> 14) & 0x7F) as u8); + b.u8(0x80 | ((n >> 7) & 0x7F) as u8); + b.u8((n & 0x7F) as u8); + b.bytes(body); +} + +pub(crate) fn esds_payload(oti: u8, asc: &[u8], max_bitrate: u32, avg_bitrate: u32, buffer_size: u32) -> Vec { + let mut dcd = BoxBuf::new(); + dcd.u8(oti); + dcd.u8(0x15); // streamType audio (5) << 2 | upstream 0 | reserved 1 + dcd.u8((buffer_size >> 16) as u8); + dcd.u16(buffer_size as u16); + dcd.u32(max_bitrate); + dcd.u32(avg_bitrate); + if !asc.is_empty() { + put_descriptor(&mut dcd, 5, asc); + } + let mut es = BoxBuf::new(); + es.u16(1); // ES_ID + es.u8(0); + put_descriptor(&mut es, 4, &dcd.buf); + put_descriptor(&mut es, 6, &[2]); // SLConfigDescriptor, predefined = 2 (MP4) + let mut b = BoxBuf::new(); + b.u32(0); + put_descriptor(&mut b, 3, &es.buf); + b.buf +} + +impl SampleEntry { + /// Convenience constructor for a video entry. + pub fn video(format: FourCc, codec: CodecConfig, width: u16, height: u16) -> Self { + let compressor_name = match &codec { + CodecConfig::ProRes { fourcc } => match &fourcc.0 { + b"apch" => "Apple ProRes 422 HQ", + b"apcn" => "Apple ProRes 422", + b"apcs" => "Apple ProRes 422 LT", + b"apco" => "Apple ProRes 422 Proxy", + b"ap4h" => "Apple ProRes 4444", + _ => "Apple ProRes 4444 XQ", + }, + CodecConfig::Jpeg { .. } => "Photo - JPEG", + _ => "", + }; + SampleEntry { + format, + data_reference_index: 1, + codec, + video: Some(VideoParams { + width, + height, + horiz_resolution: 0x0048_0000, + vert_resolution: 0x0048_0000, + frame_count: 1, + compressor_name: compressor_name.into(), + depth: 24, + ..Default::default() + }), + audio: None, + bitrate: None, + } + } + + /// Convenience constructor for an audio entry (ISO v0 layout; the muxer upgrades PCM in MOV to v2). + pub fn audio(format: FourCc, codec: CodecConfig, channels: u32, sample_rate: f64, sample_size: u16) -> Self { + SampleEntry { + format, + data_reference_index: 1, + codec, + video: None, + audio: Some(AudioParams { channels, sample_rate, sample_size, ..Default::default() }), + bitrate: None, + } + } + + /// H.264 entry (`avc1`). + pub fn avc(cfg: AvcConfig, width: u16, height: u16) -> Self { + Self::video(FourCc(*b"avc1"), CodecConfig::Avc(cfg), width, height) + } + /// HEVC entry (`hvc1`, parameter sets in the config only). + pub fn hevc(cfg: HevcConfig, width: u16, height: u16) -> Self { + Self::video(FourCc(*b"hvc1"), CodecConfig::Hevc(cfg), width, height) + } + /// AV1 entry (`av01`). + pub fn av1(cfg: Av1Config, width: u16, height: u16) -> Self { + Self::video(FourCc(*b"av01"), CodecConfig::Av1(cfg), width, height) + } + /// ProRes entry; `fourcc` one of `apch`/`apcn`/`apcs`/`apco`/`ap4h`/`ap4x`. + pub fn prores(fourcc: FourCc, width: u16, height: u16) -> Self { + let mut e = Self::video(fourcc, CodecConfig::ProRes { fourcc }, width, height); + if let Some(v) = e.video.as_mut() + && matches!(&fourcc.0, b"ap4h" | b"ap4x") + { + v.depth = 32; + } + e + } + /// Avid DNxHD / DNxHR entry (`AVdn`, or `AVdh` for DNxHR). + pub fn dnx(fourcc: FourCc, width: u16, height: u16) -> Self { + let mut e = Self::video(fourcc, CodecConfig::Dnx { fourcc }, width, height); + if let Some(v) = e.video.as_mut() { + v.depth = 24; + } + e + } + /// Advanced Professional Video entry (`apv1` + `apvC`). + pub fn apv(cfg: ApvConfig, width: u16, height: u16) -> Self { + let mut e = Self::video(FourCc(*b"apv1"), CodecConfig::Apv(cfg), width, height); + if let Some(v) = e.video.as_mut() { + v.compressor_name = "APV".into(); + } + e + } + /// Motion-JPEG entry (`jpeg`). + pub fn jpeg(width: u16, height: u16) -> Self { + let f = FourCc(*b"jpeg"); + Self::video(f, CodecConfig::Jpeg { fourcc: f }, width, height) + } + /// AAC entry (`mp4a` + `esds`) from an AudioSpecificConfig. + pub fn aac(asc: Vec, channels: u32, sample_rate: u32) -> Self { + Self::audio(FourCc(*b"mp4a"), CodecConfig::Aac(AacConfig::from_asc(asc)), channels, sample_rate as f64, 16) + } + /// FLAC entry (`fLaC` + `dfLa`) from the 34-byte STREAMINFO body: the only metadata block. + pub fn flac(streaminfo: &[u8; 34]) -> Self { + let mut blocks = vec![0x80, 0, 0, 34]; + blocks.extend_from_slice(streaminfo); + let mut full = vec![0; 4]; + full.extend_from_slice(&blocks); + let cfg = FlacConfig::parse(&full).unwrap_or(FlacConfig { metadata_blocks: blocks, ..Default::default() }); + let (channels, rate, bits) = (u32::from(cfg.channels), f64::from(cfg.sample_rate), u16::from(cfg.bits_per_sample)); + Self::audio(FourCc(*b"fLaC"), CodecConfig::Flac(cfg), channels, rate, bits) + } + /// PCM entry. The muxer picks the on-disk format (`sowt`/`twos`/`lpcm` for MOV, `ipcm`/`fpcm` for MP4). + pub fn pcm(cfg: PcmConfig) -> Self { + Self::audio(FourCc(*b"lpcm"), CodecConfig::Pcm(cfg), cfg.channels, cfg.sample_rate, cfg.bits) + } + + /// Serialize as a complete sample entry box. For PCM the format is chosen from the brand. + pub(crate) fn write(&self, b: &mut BoxBuf, qt: bool) -> Result<()> { + if let CodecConfig::Unknown { fourcc, raw } = &self.codec { + let m = b.start(&fourcc.0); + b.bytes(raw); + b.end(m); + return Ok(()); + } + if let CodecConfig::Timecode(tc) = &self.codec { + let m = b.start(b"tmcd"); + b.zeros(6); + b.u16(self.data_reference_index); + b.u32(0); + b.u32(tc.flags); + b.u32(tc.timescale); + b.u32(tc.frame_duration); + b.u8(tc.frames_per_second); + b.u8(0); + if let Some(name) = &tc.name { + let n = b.start(b"name"); + b.u16(name.len() as u16); + b.u16(0); + b.bytes(name.as_bytes()); + b.end(n); + } + b.end(m); + return Ok(()); + } + if let Some(v) = &self.video { + let m = b.start(&self.format.0); + b.zeros(6); + b.u16(self.data_reference_index); + b.u16(0); + b.u16(0); + b.u32(v.vendor.as_u32()); + b.u32(v.temporal_quality); + b.u32(v.spatial_quality); + b.u16(v.width); + b.u16(v.height); + b.u32(v.horiz_resolution); + b.u32(v.vert_resolution); + b.u32(0); + b.u16(v.frame_count); + let name = v.compressor_name.as_bytes(); + let n = name.len().min(31); + let mut nb = [0u8; 32]; + nb[0] = n as u8; + nb[1..1 + n].copy_from_slice(&name[..n]); + b.bytes(&nb); + b.u16(v.depth); + b.i16(-1); + match &self.codec { + CodecConfig::Avc(c) => b.leaf(b"avcC", &c.to_bytes()), + CodecConfig::Hevc(c) => b.leaf(b"hvcC", &c.to_bytes()), + CodecConfig::Av1(c) => b.leaf(b"av1C", &c.to_bytes()), + CodecConfig::Vp9(c) => b.leaf(b"vpcC", &c.to_bytes()), + CodecConfig::Apv(c) => b.leaf(b"apvC", &c.to_bytes()), + _ => {} + } + if let Some(g) = v.gamma { + b.leaf(b"gama", &g.to_be_bytes()); + } + if let Some(fi) = v.field_info { + b.leaf(b"fiel", &[fi.fields, fi.detail]); + } + if let Some(ci) = &v.color { + let m = b.start(b"colr"); + match ci { + ColorInfo::Nclx { primaries, transfer, matrix, full_range } => { + b.bytes(b"nclx"); + b.u16(*primaries); + b.u16(*transfer); + b.u16(*matrix); + b.u8(if *full_range { 0x80 } else { 0 }); + } + ColorInfo::Nclc { primaries, transfer, matrix } => { + b.bytes(b"nclc"); + b.u16(*primaries); + b.u16(*transfer); + b.u16(*matrix); + } + ColorInfo::Icc { kind, profile } => { + b.bytes(&kind.0); + b.bytes(profile); + } + } + b.end(m); + } + if let Some(md) = &v.mastering_display { + b.leaf(b"mdcv", &md.to_bytes()); + } + if let Some((cll, fall)) = v.content_light { + let mut d = cll.to_be_bytes().to_vec(); + d.extend_from_slice(&fall.to_be_bytes()); + b.leaf(b"clli", &d); + } + if let Some((h, vv)) = v.pixel_aspect { + let m = b.start(b"pasp"); + b.u32(h); + b.u32(vv); + b.end(m); + } + if let Some(c) = v.clean_aperture { + let m = b.start(b"clap"); + b.u32(c.width.0); + b.u32(c.width.1); + b.u32(c.height.0); + b.u32(c.height.1); + b.i32(c.horiz_offset.0); + b.u32(c.horiz_offset.1); + b.i32(c.vert_offset.0); + b.u32(c.vert_offset.1); + b.end(m); + } + if let Some(br) = self.bitrate { + write_btrt(b, br); + } + b.end(m); + return Ok(()); + } + let a = self.audio.clone().ok_or_else(|| Error::Mux("sample entry has neither video nor audio params".into()))?; + // Choose the on-disk format and sound description version. + let (format, version, pcm) = match &self.codec { + CodecConfig::Pcm(p) => { + if qt { + // Version 0 stores the rate as 16.16 fixed point; `raw ` is unsigned and + // `twos`/`sowt` are signed. Everything else needs `lpcm` v2. + let v0_rate = p.sample_rate < 65536.0; + if v0_rate && p.bits == 16 && !p.float && p.signed { + (if p.big_endian { *b"twos" } else { *b"sowt" }, 0u16, Some(*p)) + } else if v0_rate && p.bits == 8 && !p.float { + (if p.signed { *b"twos" } else { *b"raw " }, 0, Some(*p)) + } else { + (*b"lpcm", 2, Some(*p)) + } + } else { + (if p.float { *b"fpcm" } else { *b"ipcm" }, 0, Some(*p)) + } + } + _ => (self.format.0, if qt { a.qt_version.min(2) } else { 0 }, None), + }; + let m = b.start(&format); + b.zeros(6); + b.u16(self.data_reference_index); + if version == 2 { + let p = pcm.unwrap_or_default(); + b.u16(2); + b.u16(0); + b.u32(0); + b.u16(3); + b.u16(16); + b.i16(-2); + b.u16(0); + b.u32(65536); + b.u32(72); + b.f64(p.sample_rate); + b.u32(p.channels); + b.u32(0x7F00_0000); + b.u32(p.bits as u32); + let flags = (p.float as u32) | ((p.big_endian as u32) << 1) | (((p.signed && !p.float) as u32) << 2) | 8; + b.u32(flags); + b.u32(p.bytes_per_frame()); + b.u32(1); + } else { + b.u16(version); + b.u16(0); + b.u32(0); + b.u16(a.channels.min(u16::MAX as u32) as u16); + b.u16(match pcm { + Some(p) => p.bits, + None => { + if a.sample_size == 0 { + 16 + } else { + a.sample_size + } + } + }); + b.i16(if version == 1 { a.compression_id } else { 0 }); + b.u16(0); + let sr = if a.sample_rate < 65536.0 { (a.sample_rate * 65536.0).round() as u32 } else { 0 }; + b.u32(sr); + if version == 1 { + b.u32(a.samples_per_packet); + b.u32(a.bytes_per_packet); + b.u32(a.bytes_per_frame); + b.u32(a.bytes_per_sample); + } + } + match &self.codec { + CodecConfig::Aac(c) => { + b.leaf(b"esds", &esds_payload(0x40, &c.asc, c.max_bitrate, c.avg_bitrate, c.buffer_size)); + } + CodecConfig::Mp3 if format == *b"mp4a" => { + b.leaf(b"esds", &esds_payload(0x6B, &[], 0, 0, 0)); + } + CodecConfig::Alac { cookie } => { + let m = b.start_full(b"alac", 0, 0); + b.bytes(cookie); + b.end(m); + } + CodecConfig::Opus(o) => b.leaf(b"dOps", &o.to_bytes()), + CodecConfig::Flac(fl) => { + let m = b.start_full(b"dfLa", 0, 0); + b.bytes(&fl.metadata_blocks); + b.end(m); + } + CodecConfig::Ac3 { dac3 } => b.leaf(b"dac3", dac3), + CodecConfig::Eac3 { dec3 } => b.leaf(b"dec3", dec3), + CodecConfig::Pcm(p) if !qt => { + let m = b.start_full(b"pcmC", 0, 0); + b.u8(if p.big_endian { 0 } else { 1 }); + b.u8(p.bits as u8); + b.end(m); + } + CodecConfig::Pcm(p) if p.channels == 6 => { + // QuickTime channel layout: kAudioChannelLayoutTag_MPEG_5_1_A (L R C LFE Ls Rs) + let m = b.start_full(b"chan", 0, 0); + b.u32((121 << 16) | 6); + b.u32(0); + b.u32(0); + b.end(m); + } + _ => {} + } + if let Some(br) = self.bitrate { + write_btrt(b, br); + } + b.end(m); + Ok(()) + } +} + +fn write_btrt(b: &mut BoxBuf, br: BitRate) { + let m = b.start(b"btrt"); + b.u32(br.buffer_size); + b.u32(br.max_bitrate); + b.u32(br.avg_bitrate); + b.end(m); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roundtrip(e: &SampleEntry, qt: bool, handler: &[u8; 4]) -> SampleEntry { + let mut b = BoxBuf::new(); + e.write(&mut b, qt).unwrap(); + let bx = crate::isobmff::bytes::boxes(&b.buf).next().unwrap().unwrap(); + parse_sample_entry(bx.kind, bx.payload, FourCc(*handler), qt).unwrap() + } + + #[test] + fn avcc_roundtrip() { + let cfg = AvcConfig::new(vec![vec![0x67, 0x64, 0x00, 0x1F, 0xAC]], vec![vec![0x68, 0xEB]], 4); + assert_eq!(cfg.profile, 0x64); + assert_eq!(AvcConfig::parse(&cfg.to_bytes()).unwrap(), cfg); + let mut e = SampleEntry::avc(cfg, 1920, 1080); + e.video.as_mut().unwrap().color = Some(ColorInfo::Nclx { primaries: 1, transfer: 1, matrix: 1, full_range: false }); + e.video.as_mut().unwrap().pixel_aspect = Some((4, 3)); + e.video.as_mut().unwrap().field_info = Some(FieldInfo { fields: 2, detail: 9 }); + e.video.as_mut().unwrap().clean_aperture = + Some(CleanAperture { width: (1920, 1), height: (1080, 1), horiz_offset: (-2, 1), vert_offset: (0, 1) }); + e.video.as_mut().unwrap().mastering_display = Some(MasteringDisplay::bt2020(1000.0, 0.0001)); + e.video.as_mut().unwrap().content_light = Some((1000, 400)); + e.bitrate = Some(BitRate { buffer_size: 1, max_bitrate: 2, avg_bitrate: 3 }); + assert_eq!(roundtrip(&e, false, b"vide"), e); + assert_eq!(MasteringDisplay::bt2020(1000.0, 0.0001).max_nits(), 1000.0); + } + + #[test] + fn hvcc_roundtrip() { + let cfg = HevcConfig { + general_profile_idc: 1, + general_profile_compatibility_flags: 0x6000_0000, + general_constraint_indicator_flags: 0x9000_0000_0000, + general_level_idc: 93, + chroma_format_idc: 1, + bit_depth_luma: 8, + bit_depth_chroma: 8, + length_size: 4, + num_temporal_layers: 1, + temporal_id_nested: true, + arrays: vec![ + HevcNalArray { completeness: true, nal_type: 32, nalus: vec![vec![0x40, 1]] }, + HevcNalArray { completeness: true, nal_type: 33, nalus: vec![vec![0x42, 1, 2]] }, + HevcNalArray { completeness: true, nal_type: 34, nalus: vec![vec![0x44, 1]] }, + ], + ..Default::default() + }; + let back = HevcConfig::parse(&cfg.to_bytes()).unwrap(); + assert_eq!(back, cfg); + assert_eq!(back.sps(), vec![&[0x42u8, 1, 2][..]]); + } + + #[test] + fn av1_vp9_opus_roundtrip() { + let a = Av1Config { seq_profile: 1, seq_level_idx_0: 8, high_bitdepth: true, config_obus: vec![1, 2], ..Default::default() }; + assert_eq!(Av1Config::parse(&a.to_bytes()).unwrap(), a); + let v = VpcConfig { + profile: 2, + level: 31, + bit_depth: 10, + chroma_subsampling: 1, + full_range: true, + color_primaries: 9, + transfer_characteristics: 16, + matrix_coefficients: 9, + codec_init: vec![], + }; + assert_eq!(VpcConfig::parse(&v.to_bytes()).unwrap(), v); + let o = OpusConfig { + output_channels: 2, + pre_skip: 312, + input_sample_rate: 48000, + output_gain: 0, + channel_mapping_family: 0, + channel_mapping: vec![], + }; + assert_eq!(OpusConfig::parse(&o.to_bytes()).unwrap(), o); + } + + #[test] + fn aac_channel_configuration_is_an_index() { + // 48 kHz AAC LC: configuration → channels (Table 1.19 with Amd 4; #922) + let channels = |c: u16| AacConfig::from_asc(((2 << 11) | (3 << 7) | (c << 3)).to_be_bytes().to_vec()).channels(); + assert_eq!([0, 1, 6, 7, 8, 11, 12, 13, 14, 15].map(channels), [0, 1, 6, 8, 0, 7, 8, 24, 8, 0]); + } + + #[test] + fn aac_esds_roundtrip() { + let e = SampleEntry::aac(vec![0x12, 0x10], 2, 44100); + match &e.codec { + CodecConfig::Aac(a) => { + assert_eq!((a.object_type, a.sample_rate, a.channel_config), (2, 44100, 2)); + } + _ => panic!(), + } + assert_eq!(roundtrip(&e, false, b"soun"), e); + assert_eq!(roundtrip(&e, true, b"soun"), e); + } + + /// QuickTime's `.mp2` entry (what ffmpeg writes for MP2 in MOV) is MPEG audio, as `.mp3` is, + /// even under a handler that does not say "sound" (#800). + #[test] + fn quicktime_mpeg_audio_entries() { + for fourcc in [*b".mp3", *b".mp2"] { + let e = SampleEntry::audio(FourCc(fourcc), CodecConfig::Mp3, 2, 48000.0, 16); + for handler in [b"soun", b"\0\0\0\0"] { + let back = roundtrip(&e, true, handler); + assert_eq!(back.codec, CodecConfig::Mp3, "{fourcc:?} {handler:?}"); + assert_eq!(back.audio.map(|a| (a.channels, a.sample_rate)), Some((2, 48000.0)), "{fourcc:?} {handler:?}"); + } + } + } + + fn qt_v2_lpcm(channels: u32, bits: u32) -> Vec { + let mut p = vec![0; 6]; + let u16b = |p: &mut Vec, v: u16| p.extend(v.to_be_bytes()); + let u32b = |p: &mut Vec, v: u32| p.extend(v.to_be_bytes()); + u16b(&mut p, 1); + u16b(&mut p, 2); + u16b(&mut p, 0); + u32b(&mut p, 0); + u16b(&mut p, 2); + u16b(&mut p, 16); + u16b(&mut p, 0); + u16b(&mut p, 0); + u32b(&mut p, 65536); + u32b(&mut p, 72); + p.extend(48000.0f64.to_be_bytes()); + u32b(&mut p, channels); + u32b(&mut p, 0); + u32b(&mut p, bits); + u32b(&mut p, 0); + u32b(&mut p, 0); + u32b(&mut p, 1); + p + } + + #[test] + fn pcm_frame_size_saturates_on_a_hostile_channel_count() { + assert_eq!(PcmConfig { bits: 16, channels: 2, sample_rate: 48000.0, ..Default::default() }.bytes_per_frame(), 4); + assert_eq!(PcmConfig { bits: 24, channels: 0, ..Default::default() }.bytes_per_frame(), 3); + assert_eq!(PcmConfig { bits: 16, channels: u32::MAX, ..Default::default() }.bytes_per_frame(), u32::MAX); + let ok = parse_sample_entry(FourCc(*b"lpcm"), &qt_v2_lpcm(2, 16), FourCc(*b"soun"), true).unwrap(); + assert!(matches!(ok.codec, CodecConfig::Pcm(p) if p.bytes_per_frame() == 4)); + let hostile = parse_sample_entry(FourCc(*b"lpcm"), &qt_v2_lpcm(u32::MAX, 16), FourCc(*b"soun"), true).unwrap(); + assert!(matches!(hostile.codec, CodecConfig::Pcm(p) if p.bytes_per_frame() == u32::MAX)); + } + + #[test] + fn pcm_entries() { + for (bits, float, be, qt) in [ + (16, false, false, true), + (16, false, true, true), + (24, false, false, true), + (32, true, false, true), + (24, false, true, false), + (32, true, false, false), + ] { + let p = PcmConfig { bits, float, big_endian: be, signed: true, channels: 2, sample_rate: 48000.0 }; + let e = SampleEntry::pcm(p); + let back = roundtrip(&e, qt, b"soun"); + assert_eq!(back.codec, CodecConfig::Pcm(p), "{bits} {float} {be} {qt}"); + } + } + + #[test] + fn mov_pcm_keeps_high_rates_and_signedness() { + let pcm = |bits, signed, sample_rate| PcmConfig { bits, float: false, big_endian: true, signed, channels: 2, sample_rate }; + for (p, format) in [ + (pcm(16, true, 48000.0), b"twos"), + (pcm(16, true, 96000.0), b"lpcm"), + (pcm(16, false, 48000.0), b"lpcm"), + (pcm(8, false, 48000.0), b"raw "), + (pcm(8, true, 48000.0), b"twos"), + (pcm(8, false, 192000.0), b"lpcm"), + ] { + let mut b = BoxBuf::new(); + SampleEntry::pcm(p).write(&mut b, true).unwrap(); + let bx = crate::isobmff::bytes::boxes(&b.buf).next().unwrap().unwrap(); + assert_eq!(&bx.kind.0, format, "{p:?}"); + let back = roundtrip(&SampleEntry::pcm(p), true, b"soun"); + assert_eq!(back.codec, CodecConfig::Pcm(p)); + assert_eq!(back.audio.unwrap().sample_rate, p.sample_rate); + } + } + + #[test] + fn timecode_and_prores() { + let tc = + TimecodeConfig { flags: 1, timescale: 30000, frame_duration: 1001, frames_per_second: 30, start_frame: None, name: Some("reel".into()) }; + let e = SampleEntry { + format: FourCc(*b"tmcd"), + data_reference_index: 1, + codec: CodecConfig::Timecode(tc.clone()), + video: None, + audio: None, + bitrate: None, + }; + assert_eq!(roundtrip(&e, true, b"tmcd"), e); + assert_eq!(tc.format_frame(107892), "01:00:00;00"); + let nd = TimecodeConfig { flags: 0, frames_per_second: 24, ..Default::default() }; + assert_eq!(nd.format_frame(86400), "01:00:00:00"); + let p = SampleEntry::prores(FourCc(*b"apch"), 1920, 1080); + assert_eq!(roundtrip(&p, true, b"vide"), p); + } + + #[test] + fn asc_parse() { + assert_eq!(parse_asc(&[0x11, 0x90]), Some((2, 48000, 2))); + assert_eq!(parse_asc(&[]), None); + } +} diff --git a/crates/media/src/isobmff/demux.rs b/crates/media/src/isobmff/demux.rs new file mode 100644 index 0000000000..8926ddbdaa --- /dev/null +++ b/crates/media/src/isobmff/demux.rs @@ -0,0 +1,1347 @@ +//! Demuxer: parses box structure lazily (headers + `moov`/`moof` only) and builds per-track sample tables. + +use crate::isobmff::bytes::{BoxHeader, Cur, FourCc, boxes, find}; +use crate::isobmff::codec::{CodecConfig, SampleEntry, parse_sample_entry}; +use crate::isobmff::error::{Error, Result, invalid}; +use crate::isobmff::source::ByteSource; +use std::collections::HashMap; + +/// Hard cap on the sample count of the whole file, all tracks and fragments (after PCM chunk merging). +const MAX_SAMPLES: usize = 1 << 26; +/// Hard cap on the size of an in-memory `moov`/`moof` box. +const MAX_HEADER_BOX: u64 = 1 << 30; +/// Most text all metadata entries may hold together; entries past it are dropped. One `keys` +/// name can be named by many `ilst` items, each a copy, so the file's size does not bound this. +const MAX_METADATA_BYTES: usize = 4 << 20; +/// What an entry costs beyond its text, so that empty entries are bounded too. +const METADATA_ENTRY_COST: usize = 64; + +/// What is left of the file-wide limits while tracks and fragments are parsed. +struct SampleBudget { + /// Samples (`MAX_SAMPLES` minus those already built). + samples: usize, + /// Bytes of file for samples whose count no table entry backs (constant-size `stsz`, `trun` + /// without per-sample fields). Each such sample claims at least one byte, so a file can't + /// describe more of them than it has bytes, however many tracks or fragments repeat the claim. + implied_bytes: u64, +} + +impl SampleBudget { + fn take(&mut self, n: usize) -> Result<()> { + self.samples = self.samples.checked_sub(n).ok_or(Error::TooLarge("sample count"))?; + Ok(()) + } +} + +/// One sample (access unit) of a track, in the track's media timescale. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub struct Sample { + /// Absolute byte offset in the file. + pub offset: u64, + pub size: u32, + /// Decode timestamp (raw media time, edit lists not applied). + pub dts: i64, + /// Presentation timestamp = dts + composition offset (raw media time). + pub pts: i64, + pub duration: u32, + pub is_sync: bool, + /// 1-based index into [`Track::entries`]. + pub description_index: u32, +} + +/// One edit list entry (`elst`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Edit { + /// Duration of this edit in the movie timescale. + pub segment_duration: u64, + /// Start time within the media (track timescale); `-1` marks an empty edit. + pub media_time: i64, + /// Media rate as 16.16 fixed point (0x0001_0000 = normal speed, 0 = dwell). + pub media_rate: i32, +} + +/// Broad classification of a track by its handler. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TrackKind { + Video, + Audio, + Timecode, + Subtitle, + Other, +} + +/// A sample-to-group mapping (`sbgp`) with the matching descriptions (`sgpd`) kept raw. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct SampleGroup { + pub grouping_type: FourCc, + /// (sample_count, group_description_index) runs. + pub runs: Vec<(u32, u32)>, + /// Raw description entries from `sgpd`. + pub descriptions: Vec>, +} + +/// A demuxed track. +#[derive(Clone, Debug, PartialEq)] +pub struct Track { + pub id: u32, + pub kind: TrackKind, + pub handler: FourCc, + pub handler_name: String, + /// Media timescale (`mdhd`). + pub timescale: u32, + /// Media duration in the media timescale (`mdhd`). + pub duration: u64, + /// Track duration in the movie timescale (`tkhd`). + pub tkhd_duration: u64, + /// ISO 639-2/T language code (e.g. `und`, `eng`). + pub language: String, + /// `tkhd` presentation size (16.16 fixed point converted to integer pixels, rounded down). + pub width: u32, + pub height: u32, + pub enabled: bool, + pub alternate_group: u16, + /// `tkhd` volume (8.8 fixed point). + pub volume: i16, + /// `tkhd` transformation matrix. + pub matrix: [i32; 9], + pub entries: Vec, + pub samples: Vec, + pub edits: Vec, + /// Offset to add to raw pts to get presentation time (track timescale), derived from the + /// leading empty edits and the first non-empty edit's `media_time`. + pub edit_offset: i64, + /// Track references (`tref`): (type, track ids). + pub references: Vec<(FourCc, Vec)>, + /// Raw `sdtp` bytes (one per sample) if present. + pub sdtp: Vec, + pub sample_groups: Vec, + /// True if uncompressed audio samples were merged into one [`Sample`] per chunk. + pub pcm_chunked: bool, + sync_index: Vec, + pts_order: Vec, +} + +impl Track { + /// The first sample entry's codec configuration. + pub fn codec(&self) -> Option<&CodecConfig> { + self.entries.first().map(|e| &e.codec) + } + pub fn video(&self) -> Option<&crate::isobmff::codec::VideoParams> { + self.entries.first().and_then(|e| e.video.as_ref()) + } + /// Clockwise quarter turns (0–3) the `tkhd` matrix applies for display, or None when it is not + /// a pure 0/90/180/270° rotation (mirrored, scaled or sheared — left to the caller). + /// + /// ISO/IEC 14496-12 §8.3.2: a sample point (p, q) is displayed at p′ = a·p + c·q + x, + /// q′ = b·p + d·q + y for the matrix {a, b, u, c, d, v, x, y, w}, with y pointing down. So + /// {0, 1, −1, 0} sends the top row to the right-hand column (90° clockwise — iPhone portrait + /// video), {−1, 0, 0, −1} is 180° and {0, −1, 1, 0} is 270°. Only the signs matter: a·d − b·c + /// carries the scale, which the presentation size already reflects. + pub fn display_rotation(&self) -> Option { + let [a, b, _, c, d, _, _, _, _] = self.matrix; + match (a.signum(), b.signum(), c.signum(), d.signum()) { + (1, 0, 0, 1) => Some(0), + (0, 1, -1, 0) => Some(1), + (-1, 0, 0, -1) => Some(2), + (0, -1, 1, 0) => Some(3), + _ => None, + } + } + pub fn audio(&self) -> Option<&crate::isobmff::codec::AudioParams> { + self.entries.first().and_then(|e| e.audio.as_ref()) + } + /// Presentation (edit-adjusted) pts of sample `i`. + pub fn presentation_pts(&self, i: usize) -> Option { + self.samples.get(i).map(|s| s.pts.saturating_add(self.edit_offset)) + } + /// Index of the sample being presented at raw media time `pts` (the last sample, in + /// presentation order, whose pts is ≤ `pts`; the first sample if `pts` precedes all). + pub fn sample_at_pts(&self, pts: i64) -> Option { + if self.pts_order.is_empty() { + return None; + } + let k = self.pts_order.partition_point(|&i| self.samples[i as usize].pts <= pts); + Some(self.pts_order[k.saturating_sub(1)] as usize) + } + /// Like [`sample_at_pts`](Self::sample_at_pts) but for edit-adjusted presentation time. + pub fn sample_at_presentation_time(&self, t: i64) -> Option { + self.sample_at_pts(t.saturating_sub(self.edit_offset)) + } + /// The closest sync sample at or before `index` (decode order); 0 if there is none. + pub fn sync_sample_before(&self, index: usize) -> usize { + let k = self.sync_index.partition_point(|&i| i as usize <= index); + if k == 0 { 0 } else { self.sync_index[k - 1] as usize } + } + /// Indices of all sync samples. + pub fn sync_samples(&self) -> &[u32] { + &self.sync_index + } + + fn finish_indexes(&mut self) { + self.sync_index = self.samples.iter().enumerate().filter(|(_, s)| s.is_sync).map(|(i, _)| i as u32).collect(); + let mut order: Vec = (0..self.samples.len() as u32).collect(); + order.sort_by_key(|&i| (self.samples[i as usize].pts, i)); + self.pts_order = order; + } +} + +/// Text metadata from `udta` (QuickTime `©xxx` atoms and iTunes-style `meta/ilst`, incl. `keys`). +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct Metadata { + pub entries: Vec<(String, String)>, +} + +impl Metadata { + pub fn get(&self, key: &str) -> Option<&str> { + self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()) + } + /// Title from `©nam` or the `com.apple.quicktime.title` key. + pub fn title(&self) -> Option<&str> { + self.get("©nam").or_else(|| self.get("com.apple.quicktime.title")).or_else(|| self.get("title")) + } +} + +/// A parsed MP4/MOV file (headers and sample tables; media data stays in the source). +#[derive(Clone, Debug, PartialEq)] +pub struct Mp4File { + pub major_brand: FourCc, + pub minor_version: u32, + pub compatible_brands: Vec, + /// QuickTime file (major brand `qt ` or no `ftyp`). + pub is_quicktime: bool, + /// Movie timescale (`mvhd`). + pub timescale: u32, + /// Movie duration in the movie timescale (`mvhd`; for fragmented files, the longest track). + pub duration: u64, + pub tracks: Vec, + pub metadata: Metadata, + /// File uses movie fragments (`mvex` present). + pub fragmented: bool, + /// Byte offset of the `moov` box. + pub moov_offset: u64, + /// Number of `moof` boxes found. + pub fragment_count: usize, +} + +impl Mp4File { + /// Read the bytes of sample `index` of track `track` (index into [`tracks`](Self::tracks)). + pub fn read_sample(&self, src: &S, track: usize, index: usize) -> Result> { + let t = self.tracks.get(track).ok_or(Error::NoSuchTrack(track))?; + let s = t.samples.get(index).ok_or(Error::NoSuchSample(index))?; + read_range(src, s.offset, s.size as u64) + } + pub fn sample_at_pts(&self, track: usize, pts: i64) -> Option { + self.tracks.get(track)?.sample_at_pts(pts) + } + pub fn sync_sample_before(&self, track: usize, index: usize) -> Option { + Some(self.tracks.get(track)?.sync_sample_before(index)) + } + /// First track of the given kind. + pub fn track_of_kind(&self, kind: TrackKind) -> Option { + self.tracks.iter().position(|t| t.kind == kind) + } +} + +fn read_range(src: &S, offset: u64, size: u64) -> Result> { + let end = offset.checked_add(size).ok_or(Error::Truncated("sample"))?; + if end > src.len() { + return Err(Error::Truncated("sample data")); + } + let mut v = vec![0u8; size as usize]; + src.read_at(offset, &mut v)?; + Ok(v) +} + +/// Parse an MP4/MOV file. Only box headers, `ftyp`, `moov` and `moof` boxes are read. +pub fn open(src: S) -> Result { + let len = src.len(); + let mut offset = 0u64; + let mut ftyp: Option> = None; + let mut moov: Option<(u64, Vec)> = None; + let mut moofs: Vec<(u64, Vec)> = Vec::new(); + while offset + 8 <= len { + let n = (len - offset).min(32) as usize; + let mut hb = [0u8; 32]; + src.read_at(offset, &mut hb[..n])?; + let h = BoxHeader::parse(&hb[..n])?; + let size = h.size.unwrap_or(len - offset); + let end = offset.saturating_add(size).min(len); + let body_len = end.saturating_sub(offset + h.header_len); + let read_body = |max: u64| -> Result> { + if body_len > max { + return Err(Error::TooLarge("header box")); + } + read_range(&src, offset + h.header_len, body_len) + }; + match &h.kind.0 { + b"ftyp" if ftyp.is_none() => ftyp = Some(read_body(1 << 16)?), + b"moov" if moov.is_none() => moov = Some((offset, read_body(MAX_HEADER_BOX)?)), + b"moof" => moofs.push((offset, read_body(MAX_HEADER_BOX)?)), + _ => {} + } + if h.size.is_none() { + break; + } + // A box that claims to run past the end of the file ends the scan. + offset = end; + } + let (moov_offset, moov) = moov.ok_or(Error::NoMoov)?; + let mut file = Mp4File { + major_brand: FourCc::default(), + minor_version: 0, + compatible_brands: Vec::new(), + is_quicktime: true, + timescale: 0, + duration: 0, + tracks: Vec::new(), + metadata: Metadata::default(), + fragmented: false, + moov_offset, + fragment_count: moofs.len(), + }; + if let Some(f) = &ftyp { + let mut c = Cur::labeled(f, "ftyp"); + file.major_brand = c.fourcc()?; + file.minor_version = c.u32().unwrap_or(0); + while c.remaining() >= 4 { + file.compatible_brands.push(c.fourcc()?); + } + file.is_quicktime = file.major_brand == b"qt "; + } + let mut trex: HashMap = HashMap::new(); + let mut trak_payloads = Vec::new(); + let mut meta_left = MAX_METADATA_BYTES; + for b in boxes(&moov) { + let b = b?; + match &b.kind.0 { + b"cmov" => return Err(Error::Unsupported("compressed movie header (cmov)".into())), + b"mvhd" => { + let mut c = Cur::labeled(b.payload, "mvhd"); + let (v, _) = c.full_header()?; + if v == 1 { + c.skip(16)?; + file.timescale = c.u32()?; + file.duration = c.u64()?; + } else { + c.skip(8)?; + file.timescale = c.u32()?; + file.duration = c.u32()? as u64; + } + } + b"trak" => trak_payloads.push(b.payload), + b"mvex" => { + file.fragmented = true; + for m in boxes(b.payload).map_while(|b| b.ok()) { + if m.kind == b"trex" { + let mut c = Cur::labeled(m.payload, "trex"); + c.full_header()?; + let id = c.u32()?; + trex.insert(id, Trex { description_index: c.u32()?, duration: c.u32()?, size: c.u32()?, flags: c.u32()? }); + } + } + } + b"udta" => parse_udta(b.payload, &mut file.metadata, &mut meta_left), + b"meta" => parse_meta(b.payload, &mut file.metadata, &mut meta_left), + _ => {} + } + } + let mut budget = SampleBudget { samples: MAX_SAMPLES, implied_bytes: len }; + for p in trak_payloads { + let t = parse_trak(p, &file, len, &mut budget)?; + file.tracks.push(t); + } + // Movie fragments. + let mut next_dts: Vec = + file.tracks.iter().map(|t| t.samples.last().map(|s| s.dts.saturating_add(i64::from(s.duration))).unwrap_or(0)).collect(); + for (moof_off, moof) in &moofs { + parse_moof(*moof_off, moof, &mut file.tracks, &trex, &mut next_dts, &mut budget)?; + } + for t in &mut file.tracks { + if file.fragmented && !moofs.is_empty() { + let d: u64 = t.samples.iter().map(|s| s.duration as u64).sum(); + t.duration = t.duration.max(d); + if t.timescale > 0 && file.timescale > 0 { + let md = (t.duration as u128 * file.timescale as u128 / t.timescale as u128) as u64; + file.duration = file.duration.max(md); + } + } + t.finish_indexes(); + // Timecode start frame from the first sample. + if let Some(CodecConfig::Timecode(tc)) = t.entries.first_mut().map(|e| &mut e.codec) + && let Some(s) = t.samples.first() + && s.size >= 4 + { + let mut b = [0u8; 4]; + if src.read_at(s.offset, &mut b).is_ok() { + tc.start_frame = Some(u32::from_be_bytes(b)); + } + } + } + Ok(file) +} + +#[derive(Clone, Copy, Debug, Default)] +struct Trex { + description_index: u32, + duration: u32, + size: u32, + flags: u32, +} + +fn parse_language(code: u16) -> String { + if code < 0x400 { + // QuickTime Macintosh language code. + return if code == 0 { "eng".into() } else { "und".into() }; + } + let c = |s: u16| (((code >> s) & 0x1F) as u8 + 0x60) as char; + let s: String = [c(10), c(5), c(0)].into_iter().collect(); + if s.chars().all(|ch| ch.is_ascii_lowercase()) { s } else { "und".into() } +} + +fn rescale(v: i128, from: u32, to: u32) -> i64 { + if from == 0 { + return 0; + } + (v * to as i128 / from as i128).clamp(i64::MIN as i128, i64::MAX as i128) as i64 +} + +fn parse_trak(p: &[u8], file: &Mp4File, file_len: u64, budget: &mut SampleBudget) -> Result { + let mut t = Track { + id: 0, + kind: TrackKind::Other, + handler: FourCc::default(), + handler_name: String::new(), + timescale: 0, + duration: 0, + tkhd_duration: 0, + language: "und".into(), + width: 0, + height: 0, + enabled: true, + alternate_group: 0, + volume: 0, + matrix: [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x4000_0000], + entries: Vec::new(), + samples: Vec::new(), + edits: Vec::new(), + edit_offset: 0, + references: Vec::new(), + sdtp: Vec::new(), + sample_groups: Vec::new(), + pcm_chunked: false, + sync_index: Vec::new(), + pts_order: Vec::new(), + }; + let mut mdia = None; + for b in boxes(p) { + let b = b?; + match &b.kind.0 { + b"tkhd" => { + let mut c = Cur::labeled(b.payload, "tkhd"); + let (v, flags) = c.full_header()?; + t.enabled = flags & 1 != 0; + if v == 1 { + c.skip(16)?; + t.id = c.u32()?; + c.skip(4)?; + t.tkhd_duration = c.u64()?; + } else { + c.skip(8)?; + t.id = c.u32()?; + c.skip(4)?; + t.tkhd_duration = c.u32()? as u64; + } + c.skip(8)?; + let _layer = c.i16()?; + t.alternate_group = c.u16()?; + t.volume = c.i16()?; + c.skip(2)?; + for m in t.matrix.iter_mut() { + *m = c.i32()?; + } + t.width = c.u32()? >> 16; + t.height = c.u32()? >> 16; + } + b"edts" => { + if let Some(e) = find(b.payload, b"elst") { + let mut c = Cur::labeled(e, "elst"); + let (v, _) = c.full_header()?; + let n = c.count(if v == 1 { 20 } else { 12 })?; + for _ in 0..n { + let (segment_duration, media_time) = if v == 1 { (c.u64()?, c.i64()?) } else { (c.u32()? as u64, c.i32()? as i64) }; + t.edits.push(Edit { segment_duration, media_time, media_rate: c.i32()? }); + } + } + } + b"tref" => { + for r in boxes(b.payload).map_while(|b| b.ok()) { + let ids = r.payload.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]])).collect(); + t.references.push((r.kind, ids)); + } + } + b"mdia" => mdia = Some(b.payload), + _ => {} + } + } + let mdia = mdia.ok_or_else(|| Error::Invalid("trak without mdia".into()))?; + let mut minf = None; + for b in boxes(mdia) { + let b = b?; + match &b.kind.0 { + b"mdhd" => { + let mut c = Cur::labeled(b.payload, "mdhd"); + let (v, _) = c.full_header()?; + if v == 1 { + c.skip(16)?; + t.timescale = c.u32()?; + t.duration = c.u64()?; + } else { + c.skip(8)?; + t.timescale = c.u32()?; + t.duration = c.u32()? as u64; + } + t.language = parse_language(c.u16()?); + } + b"hdlr" => { + let mut c = Cur::labeled(b.payload, "hdlr"); + c.full_header()?; + let _pre = c.u32()?; + t.handler = c.fourcc()?; + c.skip(12)?; + let name = c.rest(); + // ISO: null-terminated UTF-8; QuickTime: Pascal string. + let s = if !name.is_empty() && name[0] as usize == name.len() - 1 && name.len() > 1 { + &name[1..] + } else { + name.split(|&b| b == 0).next().unwrap_or(&[]) + }; + t.handler_name = String::from_utf8_lossy(s).into_owned(); + } + b"minf" => minf = Some(b.payload), + _ => {} + } + } + t.kind = match &t.handler.0 { + b"vide" => TrackKind::Video, + b"soun" => TrackKind::Audio, + b"tmcd" => TrackKind::Timecode, + b"text" | b"sbtl" | b"subt" | b"clcp" => TrackKind::Subtitle, + _ => TrackKind::Other, + }; + // Edit offset in media timescale. + let mut empty = 0i128; + for e in &t.edits { + if e.media_time == -1 { + empty += e.segment_duration as i128; + } else { + t.edit_offset = rescale(empty, file.timescale, t.timescale).saturating_sub(e.media_time); + break; + } + } + if let Some(stbl) = minf.and_then(|m| find(m, b"stbl")) { + parse_stbl(stbl, &mut t, file.is_quicktime, file_len, budget)?; + } + Ok(t) +} + +struct SttsCursor<'a> { + runs: &'a [(u32, u32)], + run: usize, + used: u32, +} + +impl SttsCursor<'_> { + /// Advance by `n` samples, returning the summed duration. + fn take(&mut self, mut n: u64) -> u64 { + let mut total = 0u64; + while n > 0 && self.run < self.runs.len() { + let (count, delta) = self.runs[self.run]; + let avail = (count - self.used) as u64; + let k = avail.min(n); + total = total.saturating_add(k.saturating_mul(delta as u64)); + n -= k; + self.used += k as u32; + if self.used >= count { + self.run += 1; + self.used = 0; + } + } + total + } + fn next_value(&mut self) -> u32 { + while self.run < self.runs.len() && self.runs[self.run].0 == 0 { + self.run += 1; + } + let Some(&(_, d)) = self.runs.get(self.run) else { return 0 }; + self.take(1); + d + } +} + +fn parse_stbl(stbl: &[u8], t: &mut Track, is_qt: bool, file_len: u64, budget: &mut SampleBudget) -> Result<()> { + let mut stts: Vec<(u32, u32)> = Vec::new(); + let mut ctts: Vec<(u32, u32)> = Vec::new(); + let mut stss: Option> = None; + let mut stsc: Vec<(u32, u32, u32)> = Vec::new(); + let mut const_size = 0u32; + let mut sample_count = 0usize; + let mut sizes: Vec = Vec::new(); + let mut chunks: Vec = Vec::new(); + let mut sbgp: Vec<(FourCc, Vec<(u32, u32)>)> = Vec::new(); + let mut sgpd: HashMap>> = HashMap::new(); + for b in boxes(stbl) { + let b = b?; + let mut c = Cur::labeled(b.payload, "stbl child"); + match &b.kind.0 { + b"stsd" => { + c.full_header()?; + let n = c.count(8)?; + for e in boxes(c.rest()).take(n) { + let e = e?; + t.entries.push(parse_sample_entry(e.kind, e.payload, t.handler, is_qt)?); + } + } + b"stts" => { + c.full_header()?; + let n = c.count(8)?; + stts = (0..n).map(|_| Ok((c.u32()?, c.u32()?))).collect::>()?; + } + b"ctts" => { + c.full_header()?; + let n = c.count(8)?; + ctts = (0..n).map(|_| Ok((c.u32()?, c.u32()?))).collect::>()?; + } + b"stss" => { + c.full_header()?; + let n = c.count(4)?; + let mut v: Vec = (0..n).map(|_| c.u32()).collect::>()?; + v.sort_unstable(); + stss = Some(v); + } + b"stsc" => { + c.full_header()?; + let n = c.count(12)?; + stsc = (0..n).map(|_| Ok((c.u32()?, c.u32()?, c.u32()?))).collect::>()?; + } + b"stsz" => { + c.full_header()?; + const_size = c.u32()?; + let n = c.u32()? as usize; + if const_size == 0 { + c.check_count(n, 4)?; + sizes = (0..n).map(|_| c.u32()).collect::>()?; + sample_count = n; + } else { + // Samples of constant size must fit in the file: clamp absurd counts. + sample_count = (n as u64).min(file_len / const_size as u64) as usize; + } + } + b"stz2" => { + c.full_header()?; + let field = c.u32()? & 0xFF; + let n = c.u32()? as usize; + let bits = match field { + 4 | 8 | 16 => field as usize, + _ => return invalid(format!("stz2 field size {field}")), + }; + if n.checked_mul(bits).is_none_or(|b| b.div_ceil(8) > c.remaining()) { + return Err(Error::Truncated("stz2")); + } + let d = c.rest(); + sizes = (0..n) + .map(|i| match bits { + 4 => ((d[i / 2] >> if i % 2 == 0 { 4 } else { 0 }) & 0xF) as u32, + 8 => d[i] as u32, + _ => u16::from_be_bytes([d[2 * i], d[2 * i + 1]]) as u32, + }) + .collect(); + sample_count = n; + } + b"stco" => { + c.full_header()?; + let n = c.count(4)?; + chunks = (0..n).map(|_| c.u32().map(|v| v as u64)).collect::>()?; + } + b"co64" => { + c.full_header()?; + let n = c.count(8)?; + chunks = (0..n).map(|_| c.u64()).collect::>()?; + } + b"sdtp" => { + c.full_header()?; + t.sdtp = c.rest().to_vec(); + } + b"sbgp" => { + let (v, _) = c.full_header()?; + let gt = c.fourcc()?; + if v == 1 { + c.u32()?; + } + let n = c.count(8)?; + let runs = (0..n).map(|_| Ok((c.u32()?, c.u32()?))).collect::>()?; + sbgp.push((gt, runs)); + } + b"sgpd" => { + let (v, _) = c.full_header()?; + let gt = c.fourcc()?; + let default_len = if v >= 1 { c.u32()? } else { 0 }; + if v >= 2 { + c.u32()?; + } + let n = c.count(0)?; + let mut descs = Vec::new(); + for _ in 0..n { + let l = if v >= 1 && default_len == 0 { c.u32()? } else { default_len }; + if l == 0 { + // Version 0 without known length: keep the remainder as a single entry. + descs.push(c.rest().to_vec()); + break; + } + descs.push(c.bytes(l as usize)?.to_vec()); + } + sgpd.insert(gt, descs); + } + _ => {} + } + } + t.sample_groups = + sbgp.into_iter().map(|(gt, runs)| SampleGroup { grouping_type: gt, runs, descriptions: sgpd.remove(>).unwrap_or_default() }).collect(); + if sample_count == 0 || chunks.is_empty() || stsc.is_empty() { + return Ok(()); + } + if stsc[0].0 == 0 || stsc.windows(2).any(|w| w[1].0 <= w[0].0) { + return invalid("stsc first_chunk values are not increasing from 1"); + } + let pcm = match t.entries.first().map(|e| &e.codec) { + Some(CodecConfig::Pcm(p)) if const_size != 0 => Some(*p), + _ => None, + }; + let mut stts_c = SttsCursor { runs: &stts, run: 0, used: 0 }; + let mut ctts_c = SttsCursor { runs: &ctts, run: 0, used: 0 }; + let mut samples = Vec::new(); + let mut sidx = 0usize; + let mut dts = 0i64; + let mut stsc_i = 0usize; + if let Some(p) = pcm { + t.pcm_chunked = true; + let a = t.audio().cloned().unwrap_or_default(); + let frame_bytes = |frames: u64| -> u64 { + if a.qt_version == 1 && a.bytes_per_frame > 0 && a.samples_per_packet > 0 { + frames / a.samples_per_packet as u64 * a.bytes_per_frame as u64 + } else if const_size > 1 { + frames * const_size as u64 + } else { + frames * p.bytes_per_frame() as u64 + } + }; + if chunks.len() > budget.samples { + return Err(Error::TooLarge("chunk count")); + } + samples.reserve(chunks.len()); + for (ci, &off) in chunks.iter().enumerate() { + while stsc_i + 1 < stsc.len() && stsc[stsc_i + 1].0 as usize <= ci + 1 { + stsc_i += 1; + } + let spc = (stsc[stsc_i].1 as usize).min(sample_count - sidx); + if spc == 0 { + continue; + } + let dur = stts_c.take(spc as u64); + let size = frame_bytes(spc as u64).min(u32::MAX as u64) as u32; + samples.push(Sample { + offset: off, + size, + dts, + pts: dts, + duration: dur.min(u32::MAX as u64) as u32, + is_sync: true, + description_index: stsc[stsc_i].2, + }); + dts = dts.saturating_add(dur.min(i64::MAX as u64) as i64); + sidx += spc; + if sidx >= sample_count { + break; + } + } + } else { + if const_size != 0 { + sample_count = sample_count.min((budget.implied_bytes / const_size as u64) as usize); + } + if sample_count > budget.samples { + return Err(Error::TooLarge("sample count")); + } + // Reserve only what the chunk map can place. A declared count far past it would keep + // capacity the budget below never charges, track after track. + let mut mapped = 0usize; + let mut map_i = 0usize; + for ci in 0..chunks.len() { + while map_i + 1 < stsc.len() && stsc[map_i + 1].0 as usize <= ci + 1 { + map_i += 1; + } + mapped = mapped.saturating_add(stsc.get(map_i).map_or(0, |e| e.1 as usize)); + if mapped >= sample_count { + break; + } + } + samples.try_reserve(sample_count.min(mapped)).map_err(|_| Error::TooLarge("sample count"))?; + let mut stss_i = 0usize; + 'chunks: for (ci, &off) in chunks.iter().enumerate() { + while stsc_i + 1 < stsc.len() && stsc[stsc_i + 1].0 as usize <= ci + 1 { + stsc_i += 1; + } + let (_, spc, sdi) = stsc[stsc_i]; + let mut pos = off; + for _ in 0..spc { + if sidx >= sample_count { + break 'chunks; + } + let size = if const_size != 0 { const_size } else { sizes[sidx] }; + let duration = stts_c.next_value(); + let cts = ctts_c.next_value() as i32 as i64; + let is_sync = match &stss { + None => true, + Some(v) => { + while stss_i < v.len() && (v[stss_i] as usize) < sidx + 1 { + stss_i += 1; + } + stss_i < v.len() && v[stss_i] as usize == sidx + 1 + } + }; + samples.push(Sample { offset: pos, size, dts, pts: dts.saturating_add(cts), duration, is_sync, description_index: sdi }); + pos = pos.saturating_add(size as u64); + dts = dts.saturating_add(duration as i64); + sidx += 1; + } + } + } + if pcm.is_none() && const_size != 0 { + budget.implied_bytes -= samples.len() as u64 * const_size as u64; + } + budget.take(samples.len())?; + t.samples = samples; + Ok(()) +} + +fn parse_moof( + moof_off: u64, + moof: &[u8], + tracks: &mut [Track], + trex: &HashMap, + next_dts: &mut [i64], + budget: &mut SampleBudget, +) -> Result<()> { + // End of data of the previous traf, for the base-offset default of subsequent trafs. + let mut prev_end: Option = None; + for b in boxes(moof) { + let b = b?; + if b.kind != b"traf" { + continue; + } + let mut tfhd = None; + let mut tfdt = None; + let mut truns = Vec::new(); + for c in boxes(b.payload) { + let c = c?; + match &c.kind.0 { + b"tfhd" => tfhd = Some(c.payload), + b"tfdt" => tfdt = Some(c.payload), + b"trun" => truns.push(c.payload), + _ => {} + } + } + let tfhd = tfhd.ok_or_else(|| Error::Invalid("traf without tfhd".into()))?; + let mut c = Cur::labeled(tfhd, "tfhd"); + let (_, fl) = c.full_header()?; + let id = c.u32()?; + let Some(ti) = tracks.iter().position(|t| t.id == id) else { continue }; + let d = trex.get(&id).copied().unwrap_or_default(); + let base = if fl & 1 != 0 { + c.u64()? + } else if fl & 0x20000 != 0 { + moof_off + } else { + prev_end.unwrap_or(moof_off) + }; + let sdi = if fl & 2 != 0 { c.u32()? } else { d.description_index }; + let def_dur = if fl & 8 != 0 { c.u32()? } else { d.duration }; + let def_size = if fl & 0x10 != 0 { c.u32()? } else { d.size }; + let def_flags = if fl & 0x20 != 0 { c.u32()? } else { d.flags }; + if let Some(p) = tfdt { + let mut c = Cur::labeled(p, "tfdt"); + let (v, _) = c.full_header()?; + let t = if v == 1 { c.u64()? } else { c.u32()? as u64 }; + next_dts[ti] = t.min(i64::MAX as u64) as i64; + } + let mut data_pos = base; + for tr in truns { + let mut c = Cur::labeled(tr, "trun"); + let (v, tf) = c.full_header()?; + let per = [0x100u32, 0x200, 0x400, 0x800].iter().filter(|&&f| tf & f != 0).count() * 4; + let n = c.u32()? as usize; + if per > 0 { + c.check_count(n, per)?; + } else { + let implied = (n as u64).saturating_mul(def_size.max(1) as u64); + budget.implied_bytes = budget.implied_bytes.checked_sub(implied).ok_or(Error::TooLarge("trun sample count"))?; + } + budget.take(n)?; + if tf & 1 != 0 { + data_pos = base.wrapping_add_signed(c.i32()? as i64); + } + let first_flags = if tf & 4 != 0 { Some(c.u32()?) } else { None }; + let t = &mut tracks[ti]; + t.samples.reserve(n); + for i in 0..n { + let dur = if tf & 0x100 != 0 { c.u32()? } else { def_dur }; + let size = if tf & 0x200 != 0 { c.u32()? } else { def_size }; + let flags = if tf & 0x400 != 0 { c.u32()? } else { def_flags }; + // first_sample_flags overrides the flags of the first sample only. + let flags = if i == 0 { first_flags.unwrap_or(flags) } else { flags }; + let cto = if tf & 0x800 != 0 { + let raw = c.u32()?; + if v == 0 { raw as i64 } else { raw as i32 as i64 } + } else { + 0 + }; + let dts = next_dts[ti]; + t.samples.push(Sample { + offset: data_pos, + size, + dts, + pts: dts.saturating_add(cto), + duration: dur, + is_sync: flags & 0x1_0000 == 0, + description_index: sdi, + }); + data_pos = data_pos.saturating_add(size as u64); + next_dts[ti] = dts.saturating_add(dur as i64); + } + } + prev_end = Some(data_pos); + } + Ok(()) +} + +/// Takes an entry of `key_len` and `value_len` bytes from `left`; false once it would not fit. +fn charge_metadata(left: &mut usize, key_len: usize, value_len: usize) -> bool { + let cost = key_len.saturating_add(value_len).saturating_add(METADATA_ENTRY_COST); + match left.checked_sub(cost) { + Some(rest) => { + *left = rest; + true + } + None => false, + } +} + +/// Length of `String::from_utf8_lossy(bytes)` without building it: each invalid sequence +/// becomes one three-byte U+FFFD. +fn lossy_len(bytes: &[u8]) -> usize { + bytes.utf8_chunks().map(|c| c.valid().len() + if c.invalid().is_empty() { 0 } else { 3 }).sum() +} + +fn parse_udta(p: &[u8], md: &mut Metadata, left: &mut usize) { + for b in boxes(p).map_while(|b| b.ok()) { + if b.kind == b"meta" { + parse_meta(b.payload, md, left); + } else if b.kind.0[0] == 0xA9 && b.payload.len() >= 4 { + let n = u16::from_be_bytes([b.payload[0], b.payload[1]]) as usize; + // Charged at the stored text's length, before the value is converted. + let key = b.kind.to_string_lossy(); + if let Some(s) = b.payload.get(4..4 + n) + && charge_metadata(left, key.len(), lossy_len(s)) + { + md.entries.push((key, String::from_utf8_lossy(s).into_owned())); + } + } + } +} + +fn parse_meta(p: &[u8], md: &mut Metadata, left: &mut usize) { + // QuickTime `meta` is a plain box; ISO `meta` is a full box. + let body = if p.len() >= 8 && &p[4..8] == b"hdlr" { p } else { p.get(4..).unwrap_or(&[]) }; + let mut keys: Vec = Vec::new(); + if let Some(k) = find(body, b"keys") { + let mut c = Cur::labeled(k, "keys"); + if c.full_header().is_ok() + && let Ok(n) = c.count(8) + { + for _ in 0..n { + let Ok(sz) = c.u32() else { break }; + let Ok(_ns) = c.u32() else { break }; + let Ok(name) = c.bytes((sz as usize).saturating_sub(8)) else { break }; + keys.push(String::from_utf8_lossy(name).into_owned()); + } + } + } + let Some(ilst) = find(body, b"ilst") else { return }; + for item in boxes(ilst).map_while(|b| b.ok()) { + let idx = item.kind.as_u32() as usize; + let named = if idx >= 1 { keys.get(idx - 1) } else { None }; + if let Some(d) = find(item.payload, b"data") + && d.len() >= 8 + { + let ty = u32::from_be_bytes([d[0], d[1], d[2], d[3]]) & 0xFF_FFFF; + // Charged before the key is copied (every item naming one long key is another copy) + // and before the value is converted, at the lengths they will be stored at. + if ty == 1 || ty == 0 { + let fallback = if named.is_none() { Some(item.kind.to_string_lossy()) } else { None }; + let key_len = named.or(fallback.as_ref()).map_or(0, String::len); + if charge_metadata(left, key_len, lossy_len(&d[8..])) { + let key = named.cloned().or(fallback).unwrap_or_default(); + md.entries.push((key, String::from_utf8_lossy(&d[8..]).into_owned())); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn language_codes() { + // "und" = 0x55C4 + assert_eq!(parse_language(0x55C4), "und"); + assert_eq!(parse_language(0), "eng"); + assert_eq!(parse_language(0x15C7), "eng"); + } + + #[test] + fn stts_cursor() { + let runs = [(2, 10), (0, 99), (3, 5)]; + let mut c = SttsCursor { runs: &runs, run: 0, used: 0 }; + assert_eq!(c.next_value(), 10); + assert_eq!(c.take(3), 10 + 5 + 5); + assert_eq!(c.next_value(), 5); + assert_eq!(c.next_value(), 0); + } + + #[test] + fn rejects_no_moov_and_cmov() { + let mut b = crate::isobmff::bytes::BoxBuf::new(); + b.leaf(b"free", &[0; 4]); + assert!(matches!(open(b.buf.clone()), Err(Error::NoMoov))); + let m = b.start(b"moov"); + b.leaf(b"cmov", &[]); + b.end(m); + assert!(matches!(open(b.buf), Err(Error::Unsupported(_)))); + } + + #[test] + fn metadata_qt_and_ilst() { + let mut b = crate::isobmff::bytes::BoxBuf::new(); + let m = b.start(&[0xA9, b'n', b'a', b'm']); + b.u16(2); + b.u16(0); + b.bytes(b"hi"); + b.end(m); + let meta = b.start_full(b"meta", 0, 0); + b.leaf(b"hdlr", &[0; 24]); + let il = b.start(b"ilst"); + let it = b.start(&[0xA9, b'A', b'R', b'T']); + let d = b.start(b"data"); + b.u32(1); + b.u32(0); + b.bytes(b"me"); + b.end(d); + b.end(it); + b.end(il); + b.end(meta); + let mut md = Metadata::default(); + parse_udta(&b.buf, &mut md, &mut { MAX_METADATA_BYTES }); + assert_eq!(md.title(), Some("hi")); + assert_eq!(md.get("©ART"), Some("me")); + } + + use crate::isobmff::bytes::BoxBuf; + + fn full(b: &mut BoxBuf, kind: &[u8; 4], v: u8, f: impl FnOnce(&mut BoxBuf)) { + let m = b.start_full(kind, v, 0); + f(b); + b.end(m); + } + + /// Hand-built file: uuid/wide/skip boxes, stz2 sizes, co64, ctts v1 with negative offsets, + /// stss, sdtp, sbgp/sgpd, and an edit list with a leading empty edit. + fn handmade(stsz_override: Option<(u32, u32)>) -> Vec { + let mut b = BoxBuf::new(); + let m = b.start(b"ftyp"); + b.bytes(b"isom"); + b.u32(0); + b.bytes(b"isom"); + b.end(m); + let m = b.start(b"uuid"); + b.bytes(&[0xAB; 16]); + b.bytes(b"payload"); + b.end(m); + b.leaf(b"wide", &[]); + b.leaf(b"skip", &[1, 2, 3]); + // mdat with 64-bit size: 4 samples of 3,1,2,4 bytes. + let data_start = b.len() as u64 + 16; + b.u32(1); + b.bytes(b"mdat"); + b.u64(16 + 10); + b.bytes(&[1, 1, 1, 2, 3, 3, 4, 4, 4, 4]); + let moov = b.start(b"moov"); + full(&mut b, b"mvhd", 0, |b| { + b.u32(0); + b.u32(0); + b.u32(1000); + b.u32(500); + b.zeros(80); + }); + let trak = b.start(b"trak"); + full(&mut b, b"tkhd", 0, |b| { + b.u32(0); + b.u32(0); + b.u32(7); + b.u32(0); + b.u32(500); + b.zeros(52); + b.u32(320 << 16); + b.u32(240 << 16); + }); + let edts = b.start(b"edts"); + full(&mut b, b"elst", 1, |b| { + b.u32(2); + b.u64(100); + b.i64(-1); + b.i32(0x10000); + b.u64(400); + b.i64(20); + b.i32(0x10000); + }); + b.end(edts); + let mdia = b.start(b"mdia"); + full(&mut b, b"mdhd", 0, |b| { + b.u32(0); + b.u32(0); + b.u32(100); + b.u32(40); + b.u16(0x15C7); + b.u16(0); + }); + full(&mut b, b"hdlr", 0, |b| { + b.u32(0); + b.bytes(b"vide"); + b.zeros(12); + b.bytes(b"Video\0"); + }); + let minf = b.start(b"minf"); + let stbl = b.start(b"stbl"); + full(&mut b, b"stsd", 0, |b| { + b.u32(1); + crate::isobmff::codec::SampleEntry::jpeg(320, 240).write(b, false).unwrap(); + }); + full(&mut b, b"stts", 0, |b| { + b.u32(1); + b.u32(4); + b.u32(10); + }); + full(&mut b, b"ctts", 1, |b| { + b.u32(2); + b.u32(2); + b.i32(-5); + b.u32(2); + b.i32(5); + }); + full(&mut b, b"stss", 0, |b| { + b.u32(2); + b.u32(3); + b.u32(1); + }); + full(&mut b, b"stsc", 0, |b| { + b.u32(2); + b.u32(1); + b.u32(3); + b.u32(1); + b.u32(2); + b.u32(1); + b.u32(1); + }); + match stsz_override { + Some((size, count)) => full(&mut b, b"stsz", 0, |b| { + b.u32(size); + b.u32(count); + }), + None => full(&mut b, b"stz2", 0, |b| { + b.u32(4); + b.u32(4); + b.u8(0x31); + b.u8(0x24); + }), + } + full(&mut b, b"co64", 0, |b| { + b.u32(2); + b.u64(data_start); + b.u64(data_start + 6); + }); + full(&mut b, b"sdtp", 0, |b| b.bytes(&[0x20, 0x10, 0x10, 0x10])); + full(&mut b, b"sbgp", 0, |b| { + b.bytes(b"roll"); + b.u32(1); + b.u32(4); + b.u32(1); + }); + full(&mut b, b"sgpd", 1, |b| { + b.bytes(b"roll"); + b.u32(2); + b.u32(1); + b.i16(-1); + }); + b.end(stbl); + b.end(minf); + b.end(mdia); + b.end(trak); + b.end(moov); + // Trailing box extending to EOF (size 0). + b.u32(0); + b.bytes(b"free"); + b.bytes(&[9; 5]); + b.buf + } + + #[test] + fn handmade_sample_table() { + let d = handmade(None); + let f = open(d.as_slice()).unwrap(); + assert_eq!(f.major_brand, *b"isom"); + let t = &f.tracks[0]; + assert_eq!((t.id, t.kind, t.timescale, t.language.as_str()), (7, TrackKind::Video, 100, "eng")); + assert_eq!((t.width, t.height), (320, 240)); + assert_eq!(t.handler_name, "Video"); + let sizes: Vec = t.samples.iter().map(|s| s.size).collect(); + assert_eq!(sizes, [3, 1, 2, 4]); + let offs: Vec = t.samples.iter().map(|s| s.offset - t.samples[0].offset).collect(); + assert_eq!(offs, [0, 3, 4, 6]); + let pts: Vec = t.samples.iter().map(|s| s.pts).collect(); + assert_eq!(pts, [-5, 5, 25, 35]); + let sync: Vec = t.samples.iter().map(|s| s.is_sync).collect(); + assert_eq!(sync, [true, false, true, false]); + for (i, want) in [vec![1u8, 1, 1], vec![2], vec![3, 3], vec![4; 4]].iter().enumerate() { + assert_eq!(&f.read_sample(d.as_slice(), 0, i).unwrap(), want); + } + // Empty edit of 100 movie ticks = 10 media ticks, then media starts at 20. + assert_eq!(t.edits.len(), 2); + assert_eq!(t.edit_offset, 10 - 20); + assert_eq!(t.presentation_pts(2), Some(15)); + assert_eq!(t.sdtp.len(), 4); + assert_eq!(t.sample_groups[0].grouping_type, *b"roll"); + assert_eq!(t.sample_groups[0].descriptions, vec![vec![0xFF, 0xFF]]); + assert!(f.read_sample(d.as_slice(), 0, 4).is_err()); + assert!(f.read_sample(d.as_slice(), 1, 0).is_err()); + } + + #[test] + fn constant_size_samples_share_one_file_budget() { + // One chunk of u32::MAX constant-size samples makes a track build one sample per file + // byte. Repeating the track must not repeat that allocation. + let mut d = handmade(Some((1, u32::MAX))); + let p = d.windows(4).position(|w| w == b"stsc").unwrap(); + d[p + 16..p + 20].copy_from_slice(&u32::MAX.to_be_bytes()); + let at = d.windows(4).position(|w| w == b"trak").unwrap() - 4; + let size = u32::from_be_bytes(d[at..at + 4].try_into().unwrap()) as usize; + let trak = d[at..at + size].to_vec(); + for _ in 0..3 { + d.splice(at..at, trak.iter().copied()); + } + let moov = d.windows(4).position(|w| w == b"moov").unwrap() - 4; + let moov_size = u32::from_be_bytes(d[moov..moov + 4].try_into().unwrap()) + 3 * size as u32; + d[moov..moov + 4].copy_from_slice(&moov_size.to_be_bytes()); + let f = open(d.as_slice()).unwrap(); + assert_eq!(f.tracks.len(), 4); + assert!(f.tracks[0].samples.len() > d.len() / 2); + assert!(f.tracks.iter().map(|t| t.samples.len()).sum::() <= d.len()); + } + + #[test] + fn oversized_trailing_box_ends_the_scan() { + let mut d = handmade(None); + d.truncate(d.len() - 13); + d.extend_from_slice(&1u32.to_be_bytes()); + d.extend_from_slice(b"free"); + d.extend_from_slice(&u64::MAX.to_be_bytes()); + d.extend_from_slice(&[0; 16]); + assert_eq!(open(d.as_slice()).unwrap().tracks[0].samples.len(), 4); + } + + #[test] + fn one_long_key_named_by_many_items_stays_within_the_metadata_budget() { + let key = vec![b'k'; 64 * 1024]; + let mut b = BoxBuf::new(); + b.leaf(b"hdlr", &[0; 24]); + let keys = b.start_full(b"keys", 0, 0); + b.u32(1); + b.u32(8 + key.len() as u32); + b.bytes(b"mdta"); + b.bytes(&key); + b.end(keys); + let il = b.start(b"ilst"); + for _ in 0..1000 { + let it = b.start(&1u32.to_be_bytes()); + let d = b.start(b"data"); + b.u32(1); + b.u32(0); + b.bytes(b"v"); + b.end(d); + b.end(it); + } + b.end(il); + let mut payload = vec![0; 4]; + payload.extend_from_slice(&b.buf); + let mut md = Metadata::default(); + parse_meta(&payload, &mut md, &mut { MAX_METADATA_BYTES }); + assert!(!md.entries.is_empty() && md.entries.len() < 1000, "{}", md.entries.len()); + assert!(md.entries.iter().map(|(k, v)| k.len() + v.len()).sum::() <= MAX_METADATA_BYTES); + assert_eq!(md.entries[0].0.len(), key.len()); + } + + #[test] + fn metadata_is_charged_at_its_stored_length() { + assert_eq!(lossy_len(b"plain"), 5); + for bytes in [&b"a\xFFb"[..], b"\xFF\xFE\xFD", b"\xE2\x82", "\u{a9}nam".as_bytes()] { + assert_eq!(lossy_len(bytes), String::from_utf8_lossy(bytes).len(), "{bytes:?}"); + } + // Invalid UTF-8 triples in size when converted; the budget sees the converted size. + let mut b = BoxBuf::new(); + let m = b.start(&[0xA9, b'n', b'a', b'm']); + b.u16(1000); + b.u16(0); + b.bytes(&[0xFF; 1000]); + b.end(m); + let mut md = Metadata::default(); + let mut left = 3000 + METADATA_ENTRY_COST + 5; + parse_udta(&b.buf, &mut md, &mut left); + assert_eq!(md.entries.len(), 1); + assert_eq!(md.entries[0].0.len() + md.entries[0].1.len(), 3000 + 5 - left); + } + + #[test] + fn a_declared_sample_count_past_the_chunk_map_reserves_only_what_it_maps() { + // stsz claims u32::MAX samples; the two chunks place four. + let d = handmade(Some((1, u32::MAX))); + let f = open(d.as_slice()).unwrap(); + assert_eq!(f.tracks[0].samples.len(), 4); + assert!(f.tracks[0].samples.capacity() < 64, "{}", f.tracks[0].samples.capacity()); + } + + #[test] + fn absurd_counts_are_bounded() { + // Constant-size stsz claiming 4 billion samples is clamped to what fits in the file. + let d = handmade(Some((1, u32::MAX))); + let f = open(d.as_slice()).unwrap(); + assert!(f.tracks[0].samples.len() <= d.len()); + // A table claiming more entries than its box holds fails cleanly. + let mut d = handmade(None); + let p = d.windows(4).position(|w| w == b"stts").unwrap(); + d[p + 8..p + 12].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(matches!(open(d.as_slice()), Err(Error::Truncated(_)))); + // Box larger than its parent. + let mut d = handmade(None); + let p = d.windows(4).position(|w| w == b"stsc").unwrap(); + d[p - 4..p].copy_from_slice(&0x7FFF_FFFFu32.to_be_bytes()); + assert!(open(d.as_slice()).is_err()); + } +} diff --git a/crates/media/src/isobmff/error.rs b/crates/media/src/isobmff/error.rs new file mode 100644 index 0000000000..b5dfd752fe --- /dev/null +++ b/crates/media/src/isobmff/error.rs @@ -0,0 +1,38 @@ +use std::io; + +/// Errors produced by the demuxer and muxer. +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("I/O error: {0}")] + Io(#[from] io::Error), + /// A box or structure ended before all required fields were read. + #[error("truncated data while reading {0}")] + Truncated(&'static str), + /// Structurally invalid data. + #[error("invalid data: {0}")] + Invalid(String), + /// Valid but unsupported feature (e.g. compressed `cmov` movie header). + #[error("unsupported: {0}")] + Unsupported(String), + /// A count or size exceeds sanity limits relative to the file size. + #[error("size limit exceeded: {0}")] + TooLarge(&'static str), + /// No `moov` box was found. + #[error("no moov box found")] + NoMoov, + /// A track index was out of range. + #[error("track index {0} out of range")] + NoSuchTrack(usize), + /// A sample index was out of range. + #[error("sample index {0} out of range")] + NoSuchSample(usize), + /// Muxer usage error (e.g. invalid track config, bad sample). + #[error("muxer: {0}")] + Mux(String), +} + +pub type Result = std::result::Result; + +pub(crate) fn invalid(msg: impl Into) -> Result { + Err(Error::Invalid(msg.into())) +} diff --git a/crates/media/src/isobmff/mod.rs b/crates/media/src/isobmff/mod.rs new file mode 100644 index 0000000000..b962787850 --- /dev/null +++ b/crates/media/src/isobmff/mod.rs @@ -0,0 +1,29 @@ +//! Clean-room ISO Base Media File Format (MP4, ISO/IEC 14496-12/14/15) and QuickTime (MOV) support. +//! +//! - **Demux:** [`open`] parses box headers plus `moov` (and `moof` for fragmented files) from a +//! [`ByteSource`] and builds per-track [`Sample`] tables; media data is read on demand with +//! [`Mp4File::read_sample`]. +//! - **Mux:** [`Mp4Writer`] writes progressive MP4/MOV (optionally faststart); +//! [`FragmentedWriter`] writes fragmented MP4. +//! - **Boxes:** [`boxes`] iterates the boxes in a byte slice and reads their payloads, for box +//! formats and boxes the demuxer does not model (`uuid` boxes, HEIF items, JPEG 2000, CR3). +//! +//! See the crate README for supported boxes and limitations. + +pub mod boxes; +mod bytes; +mod codec; +mod demux; +mod error; +mod mux; +mod source; + +pub use bytes::FourCc; +pub use codec::{ + AacConfig, ApvConfig, AudioParams, Av1Config, AvcConfig, BitRate, CleanAperture, CodecConfig, ColorInfo, FieldInfo, FlacConfig, HevcConfig, + HevcNalArray, MasteringDisplay, OpusConfig, PcmConfig, SampleEntry, TimecodeConfig, VideoParams, VpcConfig, parse_asc, +}; +pub use demux::{Edit, Metadata, Mp4File, Sample, SampleGroup, Track, TrackKind, open}; +pub use error::{Error, Result}; +pub use mux::{Brand, FragmentedWriter, Mp4Writer, TrackConfig, WriteSample, WriterOptions}; +pub use source::ByteSource; diff --git a/crates/media/src/isobmff/mux.rs b/crates/media/src/isobmff/mux.rs new file mode 100644 index 0000000000..737747912a --- /dev/null +++ b/crates/media/src/isobmff/mux.rs @@ -0,0 +1,992 @@ +//! Muxers: progressive MP4/MOV ([`Mp4Writer`], optional faststart) and fragmented MP4 ([`FragmentedWriter`]). + +use crate::isobmff::bytes::BoxBuf; +use crate::isobmff::codec::{CodecConfig, SampleEntry, TimecodeConfig}; +use crate::isobmff::demux::Edit; +use crate::isobmff::error::{Error, Result}; +use std::io::{Read, Seek, SeekFrom, Write}; + +/// Output flavor: determines brands and some sample-entry encodings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Brand { + /// ISO MP4: `isom` major brand, compatible `isom iso2 avc1 mp41 mp42`. + Mp4, + /// QuickTime MOV: `qt ` major brand. + Mov, +} + +/// Movie-level writer options. +#[derive(Clone, Debug)] +pub struct WriterOptions { + pub brand: Brand, + /// Movie timescale (`mvhd`); default 1000. + pub movie_timescale: u32, + /// Text metadata written to `moov/udta` (keys like `©nam`, `©ART`, `©cmt`, `©too`). + pub metadata: Vec<(String, String)>, +} + +impl WriterOptions { + pub fn new(brand: Brand) -> Self { + WriterOptions { brand, movie_timescale: 1000, metadata: Vec::new() } + } +} + +/// Per-track configuration. +#[derive(Clone, Debug)] +pub struct TrackConfig { + pub entry: SampleEntry, + /// Media timescale. For PCM it must equal the sample rate (one tick per audio frame). + pub timescale: u32, + /// ISO 639-2/T language (`und` by default). + pub language: String, + /// Explicit edit list (segment durations in the movie timescale). Takes precedence over `media_start`. + pub edits: Vec, + /// Convenience: create one edit starting at this media time (e.g. AAC encoder delay / priming, + /// or the first pts of a B-frame stream) spanning the rest of the media. + pub media_start: Option, + /// `hdlr` name; a sensible default is used when `None`. + pub handler_name: Option, +} + +impl TrackConfig { + pub fn new(entry: SampleEntry, timescale: u32) -> Self { + TrackConfig { entry, timescale, language: "und".into(), edits: Vec::new(), media_start: None, handler_name: None } + } +} + +/// A sample handed to the muxers. +#[derive(Clone, Copy, Debug)] +pub struct WriteSample<'a> { + pub data: &'a [u8], + /// Duration in the media timescale. Ignored for PCM (each frame lasts one tick). + pub duration: u32, + /// pts − dts in the media timescale. + pub composition_offset: i32, + pub is_sync: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Handler { + Video, + Audio, + Timecode, + Other, +} + +fn handler_of(e: &SampleEntry) -> Handler { + if matches!(e.codec, CodecConfig::Timecode(_)) { + Handler::Timecode + } else if e.video.is_some() { + Handler::Video + } else if e.audio.is_some() { + Handler::Audio + } else { + Handler::Other + } +} + +/// Accumulated sample tables for one track. +#[derive(Clone, Debug, Default)] +struct Tables { + stts: Vec<(u32, u32)>, + ctts: Vec<(u32, i32)>, + sizes: Vec, + /// Constant sample size (PCM) — then `sizes` is unused. + const_size: Option, + sample_count: u64, + /// 1-based sync sample numbers. + sync: Vec, + all_sync: bool, + /// (offset relative to file start before shifting, sample count) + chunks: Vec<(u64, u32)>, + media_duration: u64, + /// End of the last sample on the composition timeline (decode time + composition offset + + /// duration, maximum over samples). + comp_end: u64, +} + +impl Tables { + fn new() -> Self { + Tables { all_sync: true, ..Default::default() } + } + fn push_run(runs: &mut Vec<(u32, T)>, count: u32, v: T) { + if let Some(last) = runs.last_mut() + && last.1 == v + && last.0.checked_add(count).is_some() + { + last.0 += count; + return; + } + runs.push((count, v)); + } +} + +struct WTrack { + cfg: TrackConfig, + id: u32, + handler: Handler, + pcm_frame_bytes: Option, + t: Tables, + /// Track id of a linked timecode track (`tref/tmcd`). + tmcd_ref: Option, + /// For timecode tracks: (video track index, start frame). + tmcd_source: Option<(usize, u32)>, +} + +fn pack_language(lang: &str) -> u16 { + let b = lang.as_bytes(); + if b.len() == 3 && b.iter().all(|c| c.is_ascii_lowercase()) { + (((b[0] - 0x60) as u16) << 10) | (((b[1] - 0x60) as u16) << 5) | ((b[2] - 0x60) as u16) + } else { + 0x55C4 // "und" + } +} + +fn rescale(v: u64, from: u32, to: u32) -> u64 { + if from == 0 { + return 0; + } + (v as u128 * to as u128 / from as u128).min(u64::MAX as u128) as u64 +} + +const MATRIX: [i32; 9] = [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x4000_0000]; + +fn write_ftyp(b: &mut BoxBuf, brand: Brand) { + let m = b.start(b"ftyp"); + match brand { + Brand::Mp4 => { + b.bytes(b"isom"); + b.u32(0x200); + for c in [b"isom", b"iso2", b"avc1", b"mp41", b"mp42"] { + b.bytes(c); + } + } + Brand::Mov => { + b.bytes(b"qt "); + b.u32(0x200); + b.bytes(b"qt "); + } + } + b.end(m); +} + +fn movie_duration(tracks: &[WTrack], movie_ts: u32) -> u64 { + tracks.iter().map(|t| presentation_duration(t, movie_ts)).max().unwrap_or(0) +} + +fn effective_edits(t: &WTrack, movie_ts: u32) -> Vec { + if !t.cfg.edits.is_empty() { + return t.cfg.edits.clone(); + } + if let Some(start) = t.cfg.media_start { + // presentation runs from `start` to the end of the last sample in composition order (with + // B-frame reordering that is past the end of the decode timeline) + let rest = t.t.comp_end.max(t.t.media_duration).saturating_sub(start.max(0) as u64); + return vec![Edit { segment_duration: rescale(rest, t.cfg.timescale, movie_ts), media_time: start, media_rate: 0x10000 }]; + } + Vec::new() +} + +fn presentation_duration(t: &WTrack, movie_ts: u32) -> u64 { + let e = effective_edits(t, movie_ts); + if e.is_empty() { rescale(t.t.media_duration, t.cfg.timescale, movie_ts) } else { e.iter().map(|e| e.segment_duration).sum() } +} + +fn write_mvhd(b: &mut BoxBuf, timescale: u32, duration: u64, next_id: u32) { + let v1 = duration > u32::MAX as u64; + let m = b.start_full(b"mvhd", v1 as u8, 0); + if v1 { + b.u64(0); + b.u64(0); + b.u32(timescale); + b.u64(duration); + } else { + b.u32(0); + b.u32(0); + b.u32(timescale); + b.u32(duration as u32); + } + b.u32(0x10000); + b.u16(0x100); + b.zeros(10); + for v in MATRIX { + b.i32(v); + } + b.zeros(24); + b.u32(next_id); + b.end(m); +} + +fn write_trak(b: &mut BoxBuf, t: &WTrack, movie_ts: u32, qt: bool, shift: u64, force_co64: bool) -> Result<()> { + let trak = b.start(b"trak"); + let dur = presentation_duration(t, movie_ts); + let v1 = dur > u32::MAX as u64; + let m = b.start_full(b"tkhd", v1 as u8, 3); + if v1 { + b.u64(0); + b.u64(0); + b.u32(t.id); + b.u32(0); + b.u64(dur); + } else { + b.u32(0); + b.u32(0); + b.u32(t.id); + b.u32(0); + b.u32(dur as u32); + } + b.zeros(8); + b.i16(0); + b.u16(0); + b.i16(if t.handler == Handler::Audio { 0x100 } else { 0 }); + b.u16(0); + for v in MATRIX { + b.i32(v); + } + let (w, h) = match &t.cfg.entry.video { + Some(v) => { + let w = match v.pixel_aspect { + Some((hs, vs)) if hs > 0 && vs > 0 => (v.width as u64 * hs as u64 / vs as u64) as u32, + _ => v.width as u32, + }; + (w, v.height as u32) + } + None => (0, 0), + }; + b.u32(w << 16); + b.u32(h << 16); + b.end(m); + let edits = effective_edits(t, movie_ts); + if !edits.is_empty() { + let e = b.start(b"edts"); + let v1 = edits.iter().any(|e| e.segment_duration > u32::MAX as u64 || e.media_time > i32::MAX as i64 || e.media_time < i32::MIN as i64); + let l = b.start_full(b"elst", v1 as u8, 0); + b.u32(edits.len() as u32); + for ed in &edits { + if v1 { + b.u64(ed.segment_duration); + b.i64(ed.media_time); + } else { + b.u32(ed.segment_duration as u32); + b.i32(ed.media_time as i32); + } + b.i32(ed.media_rate); + } + b.end(l); + b.end(e); + } + if let Some(id) = t.tmcd_ref { + let r = b.start(b"tref"); + let m = b.start(b"tmcd"); + b.u32(id); + b.end(m); + b.end(r); + } + let mdia = b.start(b"mdia"); + let mv1 = t.t.media_duration > u32::MAX as u64; + let m = b.start_full(b"mdhd", mv1 as u8, 0); + if mv1 { + b.u64(0); + b.u64(0); + b.u32(t.cfg.timescale); + b.u64(t.t.media_duration); + } else { + b.u32(0); + b.u32(0); + b.u32(t.cfg.timescale); + b.u32(t.t.media_duration as u32); + } + b.u16(pack_language(&t.cfg.language)); + b.u16(0); + b.end(m); + let (htype, default_name) = match t.handler { + Handler::Video => (b"vide", "VideoHandler"), + Handler::Audio => (b"soun", "SoundHandler"), + Handler::Timecode => (b"tmcd", "TimeCodeHandler"), + Handler::Other => (b"meta", "MetaHandler"), + }; + let name = t.cfg.handler_name.clone().unwrap_or_else(|| default_name.into()); + let m = b.start_full(b"hdlr", 0, 0); + b.bytes(if qt { b"mhlr" } else { &[0, 0, 0, 0] }); + b.bytes(htype); + b.zeros(12); + if qt { + let n = name.len().min(255); + b.u8(n as u8); + b.bytes(&name.as_bytes()[..n]); + } else { + b.bytes(name.as_bytes()); + b.u8(0); + } + b.end(m); + let minf = b.start(b"minf"); + match t.handler { + Handler::Video => { + let m = b.start_full(b"vmhd", 0, 1); + b.zeros(8); + b.end(m); + } + Handler::Audio => { + let m = b.start_full(b"smhd", 0, 0); + b.zeros(4); + b.end(m); + } + Handler::Timecode => { + let g = b.start(b"gmhd"); + let m = b.start_full(b"gmin", 0, 0); + b.u16(0x40); + b.u16(0x8000); + b.u16(0x8000); + b.u16(0x8000); + b.i16(0); + b.u16(0); + b.end(m); + let tm = b.start(b"tmcd"); + let m = b.start_full(b"tcmi", 0, 0); + b.u16(0); + b.u16(0); + b.u16(12); + b.u16(0); + b.bytes(&[0xFF; 6]); + b.zeros(6); + b.u8(0); + b.end(m); + b.end(tm); + b.end(g); + } + Handler::Other => { + let m = b.start_full(b"nmhd", 0, 0); + b.end(m); + } + } + if qt { + // QuickTime data handler reference. + let m = b.start_full(b"hdlr", 0, 0); + b.bytes(b"dhlr"); + b.bytes(b"url "); + b.zeros(12); + b.u8(0); + b.end(m); + } + let d = b.start(b"dinf"); + let r = b.start_full(b"dref", 0, 0); + b.u32(1); + let u = b.start_full(b"url ", 0, 1); + b.end(u); + b.end(r); + b.end(d); + let stbl = b.start(b"stbl"); + let m = b.start_full(b"stsd", 0, 0); + b.u32(1); + t.cfg.entry.write(b, qt)?; + b.end(m); + let tb = &t.t; + let m = b.start_full(b"stts", 0, 0); + b.u32(tb.stts.len() as u32); + for &(c, d) in &tb.stts { + b.u32(c); + b.u32(d); + } + b.end(m); + if tb.ctts.iter().any(|&(_, o)| o != 0) { + let neg = tb.ctts.iter().any(|&(_, o)| o < 0); + let m = b.start_full(b"ctts", neg as u8, 0); + b.u32(tb.ctts.len() as u32); + for &(c, o) in &tb.ctts { + b.u32(c); + b.i32(o); + } + b.end(m); + } + if !tb.all_sync { + let m = b.start_full(b"stss", 0, 0); + b.u32(tb.sync.len() as u32); + for &s in &tb.sync { + b.u32(s); + } + b.end(m); + } + let m = b.start_full(b"stsc", 0, 0); + let mut runs: Vec<(u32, u32)> = Vec::new(); + for (i, &(_, n)) in tb.chunks.iter().enumerate() { + if runs.last().is_none_or(|r| r.1 != n) { + runs.push((i as u32 + 1, n)); + } + } + b.u32(runs.len() as u32); + for (first, n) in runs { + b.u32(first); + b.u32(n); + b.u32(1); + } + b.end(m); + let m = b.start_full(b"stsz", 0, 0); + match tb.const_size { + Some(s) => { + b.u32(s); + b.u32(tb.sample_count.min(u32::MAX as u64) as u32); + } + None => { + let first = tb.sizes.first().copied().unwrap_or(0); + // A uniform size of 0 would mean "table follows" (ISO/IEC 14496-12 §8.7.3), so + // all-empty samples must still be written as a table. + if first != 0 && !tb.sizes.is_empty() && tb.sizes.iter().all(|&s| s == first) { + b.u32(first); + b.u32(tb.sizes.len() as u32); + } else { + b.u32(0); + b.u32(tb.sizes.len() as u32); + for &s in &tb.sizes { + b.u32(s); + } + } + } + } + b.end(m); + let co64 = force_co64 || tb.chunks.iter().any(|&(o, _)| o + shift > u32::MAX as u64); + let m = b.start_full(if co64 { b"co64" } else { b"stco" }, 0, 0); + b.u32(tb.chunks.len() as u32); + for &(o, _) in &tb.chunks { + if co64 { + b.u64(o + shift); + } else { + b.u32((o + shift) as u32); + } + } + b.end(m); + b.end(stbl); + b.end(minf); + b.end(mdia); + b.end(trak); + Ok(()) +} + +fn write_udta(b: &mut BoxBuf, md: &[(String, String)]) { + let items: Vec<([u8; 4], &str)> = md + .iter() + .filter_map(|(k, v)| { + let mut chars = k.chars(); + if chars.next()? != '©' { + return None; + } + let rest: Vec = chars.map(|c| c as u32 as u8).collect(); + (rest.len() == 3).then(|| ([0xA9, rest[0], rest[1], rest[2]], v.as_str())) + }) + .collect(); + if items.is_empty() { + return; + } + let u = b.start(b"udta"); + for (k, v) in items { + let m = b.start(&k); + b.u16(v.len() as u16); + b.u16(0x55C4); + b.bytes(v.as_bytes()); + b.end(m); + } + b.end(u); +} + +fn validate_track(entry: &SampleEntry, timescale: u32) -> Result> { + if timescale == 0 { + return Err(Error::Mux("timescale must be non-zero".into())); + } + if let CodecConfig::Pcm(p) = &entry.codec { + if p.bits == 0 || p.channels == 0 { + return Err(Error::Mux("PCM needs bits and channels".into())); + } + if (p.sample_rate - timescale as f64).abs() > 0.5 { + return Err(Error::Mux("PCM track timescale must equal the sample rate".into())); + } + return Ok(Some(p.bytes_per_frame())); + } + Ok(None) +} + +/// Progressive MP4/MOV writer: `ftyp`, then one `mdat` streamed to `W`, then `moov` at [`finish`](Self::finish) +/// (or moved in front of `mdat` by [`finish_faststart`](Self::finish_faststart)). +pub struct Mp4Writer { + w: W, + opts: WriterOptions, + tracks: Vec, + /// Offset of the placeholder box (8 bytes) preceding the mdat header. + pad_pos: u64, + mdat_pos: u64, + pos: u64, + last_track: Option, +} + +impl Mp4Writer { + /// Start a file: writes `ftyp`, a placeholder box and the `mdat` header. + pub fn new(mut w: W, opts: WriterOptions) -> Result { + let start = w.stream_position()?; + let mut b = BoxBuf::new(); + write_ftyp(&mut b, opts.brand); + let pad_pos = start + b.len() as u64; + b.leaf(if opts.brand == Brand::Mov { b"wide" } else { b"free" }, &[]); + let mdat_pos = start + b.len() as u64; + b.leaf(b"mdat", &[]); + w.write_all(&b.buf)?; + let pos = start + b.len() as u64; + Ok(Mp4Writer { w, opts, tracks: Vec::new(), pad_pos, mdat_pos, pos, last_track: None }) + } + + /// Add a track; returns its index (track ids are index + 1). + pub fn add_track(&mut self, cfg: TrackConfig) -> Result { + let pcm = validate_track(&cfg.entry, cfg.timescale)?; + let handler = handler_of(&cfg.entry); + let mut t = Tables::new(); + t.const_size = pcm; + self.tracks.push(WTrack { id: self.tracks.len() as u32 + 1, handler, pcm_frame_bytes: pcm, t, cfg, tmcd_ref: None, tmcd_source: None }); + Ok(self.tracks.len() - 1) + } + + /// Replace a track's sample entry before the file is finished (the `moov` is written last), for + /// codecs whose configuration is only complete at the end, like the FLAC STREAMINFO in `dfLa`. + /// The new entry must keep the media type and, for PCM, the frame size. + pub fn set_sample_entry(&mut self, track: usize, entry: SampleEntry) -> Result<()> { + let t = self.tracks.get_mut(track).ok_or(Error::NoSuchTrack(track))?; + if handler_of(&entry) != t.handler || validate_track(&entry, t.cfg.timescale)? != t.pcm_frame_bytes { + return Err(Error::Mux("replacement sample entry changes the track's media type or PCM layout".into())); + } + t.cfg.entry = entry; + Ok(()) + } + + /// Add a QuickTime timecode track referenced by `video_track`. Its single sample (the start + /// frame number) is written at finish, spanning the video track's duration. + pub fn add_timecode_track(&mut self, video_track: usize, tc: TimecodeConfig, start_frame: u32) -> Result { + if video_track >= self.tracks.len() { + return Err(Error::NoSuchTrack(video_track)); + } + if tc.timescale == 0 || tc.frame_duration == 0 || tc.frames_per_second == 0 { + return Err(Error::Mux("timecode needs timescale, frame duration and fps".into())); + } + let entry = SampleEntry { + format: crate::isobmff::bytes::FourCc(*b"tmcd"), + data_reference_index: 1, + codec: CodecConfig::Timecode(tc.clone()), + video: None, + audio: None, + bitrate: None, + }; + let idx = self.add_track(TrackConfig::new(entry, tc.timescale))?; + self.tracks[idx].tmcd_source = Some((video_track, start_frame)); + let id = self.tracks[idx].id; + self.tracks[video_track].tmcd_ref = Some(id); + Ok(idx) + } + + /// Append one sample to track `track` (decode order). For PCM tracks `data` may hold any whole + /// number of audio frames. + pub fn write_sample(&mut self, track: usize, s: WriteSample) -> Result<()> { + let tr = self.tracks.get(track).ok_or(Error::NoSuchTrack(track))?; + if tr.tmcd_source.is_some() { + return Err(Error::Mux("timecode track samples are written automatically".into())); + } + let (count, dur) = match tr.pcm_frame_bytes { + Some(fb) => { + if !s.data.len().is_multiple_of(fb as usize) { + return Err(Error::Mux("PCM data is not a whole number of frames".into())); + } + ((s.data.len() / fb as usize) as u32, 1u32) + } + None => { + if s.data.len() > u32::MAX as usize { + return Err(Error::Mux("sample larger than 4 GiB".into())); + } + (1, s.duration) + } + }; + if count == 0 { + return Ok(()); + } + self.w.write_all(s.data)?; + let offset = self.pos; + self.pos += s.data.len() as u64; + let contiguous = self.last_track == Some(track); + self.last_track = Some(track); + let tr = &mut self.tracks[track]; + let t = &mut tr.t; + Tables::push_run(&mut t.stts, count, dur); + Tables::push_run(&mut t.ctts, count, if tr.pcm_frame_bytes.is_some() { 0 } else { s.composition_offset }); + if tr.pcm_frame_bytes.is_none() { + t.sizes.push(s.data.len() as u32); + if s.is_sync { + t.sync.push(t.sample_count as u32 + 1); + } else { + t.all_sync = false; + } + } + t.sample_count += count as u64; + let ct = if tr.pcm_frame_bytes.is_some() { 0 } else { s.composition_offset as i64 }; + t.comp_end = t.comp_end.max((t.media_duration as i64 + ct + count as i64 * dur as i64).max(0) as u64); + t.media_duration += count as u64 * dur as u64; + match t.chunks.last_mut() { + Some(c) if contiguous => c.1 += count, + _ => t.chunks.push((offset, count)), + } + Ok(()) + } + + fn finish_mdat(&mut self) -> Result<()> { + // Timecode samples. + for i in 0..self.tracks.len() { + let Some((vi, start)) = self.tracks[i].tmcd_source else { continue }; + let v = &self.tracks[vi]; + let vd = v.t.media_duration; + let vts = v.cfg.timescale; + let tts = self.tracks[i].cfg.timescale; + let tc_dur = match &self.tracks[i].cfg.entry.codec { + CodecConfig::Timecode(tc) => tc.frame_duration, + _ => 1, + }; + let d = rescale(vd, vts, tts).max(tc_dur as u64).min(u32::MAX as u64) as u32; + self.w.write_all(&start.to_be_bytes())?; + let off = self.pos; + self.pos += 4; + self.last_track = None; + let t = &mut self.tracks[i].t; + t.stts.push((1, d)); + t.sizes.push(4); + t.sync.push(1); + t.sample_count = 1; + t.media_duration = d as u64; + t.chunks.push((off, 1)); + } + let size = self.pos - self.mdat_pos; + if size <= u32::MAX as u64 { + self.w.seek(SeekFrom::Start(self.mdat_pos))?; + self.w.write_all(&(size as u32).to_be_bytes())?; + } else { + // Merge the placeholder into a 16-byte large-size mdat header. + let mut h = [0u8; 16]; + h[..4].copy_from_slice(&1u32.to_be_bytes()); + h[4..8].copy_from_slice(b"mdat"); + h[8..].copy_from_slice(&(self.pos - self.pad_pos).to_be_bytes()); + self.w.seek(SeekFrom::Start(self.pad_pos))?; + self.w.write_all(&h)?; + } + self.w.seek(SeekFrom::Start(self.pos))?; + Ok(()) + } + + fn build_moov(&self, shift: u64, force_co64: bool) -> Result> { + let qt = self.opts.brand == Brand::Mov; + let ts = self.opts.movie_timescale.max(1); + let mut b = BoxBuf::new(); + let m = b.start(b"moov"); + write_mvhd(&mut b, ts, movie_duration(&self.tracks, ts), self.tracks.len() as u32 + 1); + for t in &self.tracks { + write_trak(&mut b, t, ts, qt, shift, force_co64)?; + } + write_udta(&mut b, &self.opts.metadata); + b.end(m); + Ok(b.buf) + } + + /// Finish the file with `moov` after `mdat`. Returns the underlying writer. + pub fn finish(mut self) -> Result { + self.finish_mdat()?; + let moov = self.build_moov(0, false)?; + self.w.write_all(&moov)?; + self.w.flush()?; + Ok(self.w) + } +} + +impl Mp4Writer { + /// Finish with `moov` in front of `mdat` ("fast start"): media data is shifted forward in place. + pub fn finish_faststart(mut self) -> Result { + self.finish_mdat()?; + let mut moov = self.build_moov(0, false)?; + let mut force = false; + loop { + let shift = moov.len() as u64; + let next = self.build_moov(shift, force)?; + if next.len() == moov.len() { + moov = next; + break; + } + // Offsets crossed the 32-bit boundary: switch to co64 (size only grows, so this converges). + force = true; + moov = next; + } + let shift = moov.len() as u64; + let start = self.pad_pos; + let end = self.pos; + let mut buf = vec![0u8; 1 << 20]; + let mut cur = end; + while cur > start { + let n = (cur - start).min(buf.len() as u64) as usize; + cur -= n as u64; + self.w.seek(SeekFrom::Start(cur))?; + self.w.read_exact(&mut buf[..n])?; + self.w.seek(SeekFrom::Start(cur + shift))?; + self.w.write_all(&buf[..n])?; + } + self.w.seek(SeekFrom::Start(start))?; + self.w.write_all(&moov)?; + self.w.seek(SeekFrom::Start(end + shift))?; + self.w.flush()?; + Ok(self.w) + } +} + +/// Buffered fragment sample: (data, duration, composition offset, sync). +type PendingSample = (Vec, u32, i32, bool); + +/// Fragmented MP4 writer: an init segment (`ftyp` + `moov` with `mvex`) followed by +/// `moof`+`mdat` fragments. Samples are buffered until [`flush_fragment`](Self::flush_fragment). +pub struct FragmentedWriter { + w: W, + opts: WriterOptions, + tracks: Vec, + pending: Vec>, + next_dts: Vec, + seq: u32, + init_written: bool, +} + +impl FragmentedWriter { + pub fn new(w: W, opts: WriterOptions) -> Self { + FragmentedWriter { w, opts, tracks: Vec::new(), pending: Vec::new(), next_dts: Vec::new(), seq: 0, init_written: false } + } + + /// Add a track (before the first fragment). PCM is not supported in fragments. + pub fn add_track(&mut self, cfg: TrackConfig) -> Result { + if self.init_written { + return Err(Error::Mux("tracks must be added before the first fragment".into())); + } + if validate_track(&cfg.entry, cfg.timescale)?.is_some() { + return Err(Error::Mux("PCM is not supported by the fragmented writer".into())); + } + let handler = handler_of(&cfg.entry); + self.tracks.push(WTrack { + id: self.tracks.len() as u32 + 1, + handler, + pcm_frame_bytes: None, + t: Tables::new(), + cfg, + tmcd_ref: None, + tmcd_source: None, + }); + self.pending.push(Vec::new()); + self.next_dts.push(0); + Ok(self.tracks.len() - 1) + } + + fn write_init(&mut self) -> Result<()> { + let qt = self.opts.brand == Brand::Mov; + let ts = self.opts.movie_timescale.max(1); + let mut b = BoxBuf::new(); + write_ftyp(&mut b, self.opts.brand); + let m = b.start(b"moov"); + write_mvhd(&mut b, ts, 0, self.tracks.len() as u32 + 1); + for t in &self.tracks { + write_trak(&mut b, t, ts, qt, 0, false)?; + } + let mv = b.start(b"mvex"); + for t in &self.tracks { + let x = b.start_full(b"trex", 0, 0); + b.u32(t.id); + b.u32(1); + b.u32(0); + b.u32(0); + b.u32(0); + b.end(x); + } + b.end(mv); + write_udta(&mut b, &self.opts.metadata); + b.end(m); + self.w.write_all(&b.buf)?; + self.init_written = true; + Ok(()) + } + + /// Buffer a sample for the next fragment. + pub fn write_sample(&mut self, track: usize, s: WriteSample) -> Result<()> { + let p = self.pending.get_mut(track).ok_or(Error::NoSuchTrack(track))?; + if s.data.len() > u32::MAX as usize { + return Err(Error::Mux("sample larger than 4 GiB".into())); + } + p.push((s.data.to_vec(), s.duration, s.composition_offset, s.is_sync)); + Ok(()) + } + + fn build_moof(&self, data_offsets: &[i32]) -> Vec { + let mut b = BoxBuf::new(); + let m = b.start(b"moof"); + let h = b.start_full(b"mfhd", 0, 0); + b.u32(self.seq); + b.end(h); + for (i, t) in self.tracks.iter().enumerate() { + let p = &self.pending[i]; + if p.is_empty() { + continue; + } + let tf = b.start(b"traf"); + let h = b.start_full(b"tfhd", 0, 0x20000); + b.u32(t.id); + b.end(h); + let h = b.start_full(b"tfdt", 1, 0); + b.u64(self.next_dts[i]); + b.end(h); + let neg = p.iter().any(|s| s.2 < 0); + let h = b.start_full(b"trun", neg as u8, 0x1 | 0x100 | 0x200 | 0x400 | 0x800); + b.u32(p.len() as u32); + b.i32(data_offsets[i]); + for (d, dur, cto, sync) in p { + b.u32(*dur); + b.u32(d.len() as u32); + b.u32(if *sync { 0x0200_0000 } else { 0x0101_0000 }); + b.i32(*cto); + } + b.end(h); + b.end(tf); + } + b.end(m); + b.buf + } + + /// Write all buffered samples as one `moof` + `mdat` fragment (no-op if nothing is buffered). + pub fn flush_fragment(&mut self) -> Result<()> { + if !self.init_written { + self.write_init()?; + } + if self.pending.iter().all(|p| p.is_empty()) { + return Ok(()); + } + self.seq += 1; + let probe = self.build_moof(&vec![0; self.tracks.len()]); + let data_len: u64 = self.pending.iter().flatten().map(|s| s.0.len() as u64).sum(); + let large = data_len + 8 > u32::MAX as u64; + let hdr = if large { 16 } else { 8 }; + let mut offs = Vec::with_capacity(self.tracks.len()); + let mut acc = probe.len() as u64 + hdr; + for p in &self.pending { + offs.push(i32::try_from(acc).map_err(|_| Error::Mux("fragment too large".into()))?); + acc += p.iter().map(|s| s.0.len() as u64).sum::(); + } + let moof = self.build_moof(&offs); + self.w.write_all(&moof)?; + if large { + self.w.write_all(&1u32.to_be_bytes())?; + self.w.write_all(b"mdat")?; + self.w.write_all(&(data_len + 16).to_be_bytes())?; + } else { + self.w.write_all(&((data_len + 8) as u32).to_be_bytes())?; + self.w.write_all(b"mdat")?; + } + for (i, p) in self.pending.iter_mut().enumerate() { + for (d, dur, _, _) in p.drain(..) { + self.w.write_all(&d)?; + self.next_dts[i] += dur as u64; + } + } + Ok(()) + } + + /// Flush remaining samples and return the writer. + pub fn finish(mut self) -> Result { + self.flush_fragment()?; + self.w.flush()?; + Ok(self.w) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::isobmff::codec::{AvcConfig, PcmConfig}; + use std::io::Cursor; + + fn avc_entry() -> SampleEntry { + SampleEntry::avc(AvcConfig::new(vec![vec![0x67, 0x42, 0, 0x1E]], vec![vec![0x68, 0xCE]], 4), 64, 48) + } + + #[test] + fn language_pack() { + assert_eq!(pack_language("und"), 0x55C4); + assert_eq!(pack_language("eng"), 0x15C7); + assert_eq!(pack_language("EN"), 0x55C4); + } + + #[test] + fn simple_roundtrip_and_faststart() { + for fast in [false, true] { + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap(); + let v = w.add_track(TrackConfig::new(avc_entry(), 12800)).unwrap(); + let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 2, sample_rate: 48000.0 }; + let a = w.add_track(TrackConfig::new(SampleEntry::pcm(pcm), 48000)).unwrap(); + for i in 0..10u8 { + let data = vec![i; 100 + i as usize]; + w.write_sample( + v, + WriteSample { data: &data, duration: 512, composition_offset: if i % 2 == 0 { 1024 } else { 0 }, is_sync: i % 5 == 0 }, + ) + .unwrap(); + w.write_sample(a, WriteSample { data: &[i; 400], duration: 0, composition_offset: 0, is_sync: true }).unwrap(); + } + let out = if fast { w.finish_faststart() } else { w.finish() }.unwrap().into_inner(); + let f = crate::isobmff::open(out.as_slice()).unwrap(); + assert_eq!(f.tracks.len(), 2); + let t = &f.tracks[0]; + assert_eq!(t.samples.len(), 10); + for (i, s) in t.samples.iter().enumerate() { + assert_eq!(s.size as usize, 100 + i); + assert_eq!(s.dts, 512 * i as i64); + assert_eq!(s.is_sync, i % 5 == 0); + assert_eq!(f.read_sample(out.as_slice(), 0, i).unwrap(), vec![i as u8; 100 + i]); + } + let at = &f.tracks[1]; + assert!(at.pcm_chunked); + assert_eq!(at.samples.len(), 10); + assert_eq!(at.samples[3].size, 400); + assert_eq!(at.samples[3].duration, 100); + assert_eq!(f.read_sample(out.as_slice(), 1, 3).unwrap(), vec![3u8; 400]); + if fast { + assert!(f.moov_offset < t.samples[0].offset); + } + } + } + + #[test] + fn set_sample_entry_keeps_track_layout() { + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap(); + let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 2, sample_rate: 48000.0 }; + let a = w.add_track(TrackConfig::new(SampleEntry::pcm(pcm), 48000)).unwrap(); + let f = w.add_track(TrackConfig::new(SampleEntry::flac(&[0; 34]), 48000)).unwrap(); + assert!(w.set_sample_entry(a, SampleEntry::pcm(PcmConfig { big_endian: true, ..pcm })).is_ok()); + assert!(w.set_sample_entry(a, SampleEntry::pcm(PcmConfig { bits: 24, ..pcm })).is_err()); + assert!(w.set_sample_entry(a, avc_entry()).is_err()); + assert!(w.set_sample_entry(f, SampleEntry::flac(&[1; 34])).is_ok()); + assert!(w.set_sample_entry(f, SampleEntry::pcm(pcm)).is_err()); + assert!(matches!(w.set_sample_entry(5, avc_entry()), Err(Error::NoSuchTrack(5)))); + } + + #[test] + fn fragmented_roundtrip() { + let mut w = FragmentedWriter::new(Vec::new(), WriterOptions::new(Brand::Mp4)); + let v = w.add_track(TrackConfig::new(avc_entry(), 1000)).unwrap(); + for i in 0..6u8 { + w.write_sample(v, WriteSample { data: &[i; 10], duration: 40, composition_offset: -(i as i32 % 2), is_sync: i % 3 == 0 }).unwrap(); + if i % 3 == 2 { + w.flush_fragment().unwrap(); + } + } + let out = w.finish().unwrap(); + let f = crate::isobmff::open(out.as_slice()).unwrap(); + assert!(f.fragmented); + assert_eq!(f.fragment_count, 2); + let t = &f.tracks[0]; + assert_eq!(t.samples.len(), 6); + for (i, s) in t.samples.iter().enumerate() { + assert_eq!(s.dts, 40 * i as i64); + assert_eq!(s.pts, s.dts - (i as i64 % 2)); + assert_eq!(s.is_sync, i % 3 == 0); + assert_eq!(f.read_sample(out.as_slice(), 0, i).unwrap(), vec![i as u8; 10]); + } + assert_eq!(t.sync_sample_before(5), 3); + } +} diff --git a/crates/media/src/isobmff/source.rs b/crates/media/src/isobmff/source.rs new file mode 100644 index 0000000000..0dad82b20d --- /dev/null +++ b/crates/media/src/isobmff/source.rs @@ -0,0 +1,123 @@ +//! Random-access byte sources for the demuxer. + +use std::io; +use std::sync::Arc; + +/// Random-access, read-only byte source (file, in-memory buffer, web Blob…). +/// +/// Implementations must be able to serve reads at arbitrary offsets through `&self`. +pub trait ByteSource { + /// Total length in bytes. + fn len(&self) -> u64; + /// Fill `buf` entirely with bytes starting at `offset`; fail with `UnexpectedEof` if past the end. + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()>; + /// True if the source holds no bytes. + fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +fn eof() -> io::Error { + io::Error::new(io::ErrorKind::UnexpectedEof, "read past end of byte source") +} + +impl ByteSource for [u8] { + fn len(&self) -> u64 { + <[u8]>::len(self) as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + let start = usize::try_from(offset).map_err(|_| eof())?; + let end = start.checked_add(buf.len()).ok_or_else(eof)?; + let src = self.get(start..end).ok_or_else(eof)?; + buf.copy_from_slice(src); + Ok(()) + } +} + +impl ByteSource for Vec { + fn len(&self) -> u64 { + self.as_slice().len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + self.as_slice().read_at(offset, buf) + } +} + +impl ByteSource for &T { + fn len(&self) -> u64 { + (**self).len() + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + (**self).read_at(offset, buf) + } +} + +impl ByteSource for Arc { + fn len(&self) -> u64 { + (**self).len() + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + (**self).read_at(offset, buf) + } +} + +impl ByteSource for Box { + fn len(&self) -> u64 { + (**self).len() + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + (**self).read_at(offset, buf) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl ByteSource for std::fs::File { + fn len(&self) -> u64 { + self.metadata().map(|m| m.len()).unwrap_or(0) + } + #[cfg(unix)] + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + std::os::unix::fs::FileExt::read_exact_at(self, buf, offset) + } + #[cfg(windows)] + fn read_at(&self, mut offset: u64, mut buf: &mut [u8]) -> io::Result<()> { + use std::os::windows::fs::FileExt; + while !buf.is_empty() { + let n = self.seek_read(buf, offset)?; + if n == 0 { + return Err(eof()); + } + offset += n as u64; + buf = &mut buf[n..]; + } + Ok(()) + } + #[cfg(not(any(unix, windows)))] + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + use std::io::{Read, Seek, SeekFrom}; + let mut f = self; + f.seek(SeekFrom::Start(offset))?; + f.read_exact(buf) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slice_reads() { + let v = vec![1u8, 2, 3, 4]; + let mut b = [0u8; 2]; + v.read_at(1, &mut b).unwrap(); + assert_eq!(b, [2, 3]); + assert!(v.read_at(3, &mut b).is_err()); + assert!(v.read_at(u64::MAX, &mut b).is_err()); + let a: Arc<[u8]> = Arc::from(v.clone()); + a.read_at(2, &mut b).unwrap(); + assert_eq!(b, [3, 4]); + assert_eq!(ByteSource::len(&a), 4); + let s: &[u8] = &v; + assert_eq!(ByteSource::len(&s), 4); + } +} diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs new file mode 100644 index 0000000000..86cf06b610 --- /dev/null +++ b/crates/media/src/lib.rs @@ -0,0 +1,18 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! Media containers and bit-level I/O for the Craft apps. +//! +//! - `bitstream` (feature `bitstream`): MSB-first bit reader and writer, Exp-Golomb codes, +//! emulation-prevention escaping and NAL unit splitting. +//! - `isobmff` (feature `isobmff`, enables `bitstream`): a clean-room ISO BMFF (MP4) and +//! QuickTime (MOV) demuxer and muxer, and a box reader for other ISO BMFF formats. +//! - `matroska` (feature `matroska`): a clean-room Matroska (MKV) and WebM demuxer and muxer. +//! +//! `bitstream` and `isobmff` are on by default; `matroska` is opt-in. A crate that needs only bit +//! I/O uses `default-features = false, features = ["bitstream"]`. Codecs stay in the apps. + +#[cfg(feature = "bitstream")] +pub mod bitstream; +#[cfg(feature = "isobmff")] +pub mod isobmff; +#[cfg(feature = "matroska")] +pub mod matroska; diff --git a/crates/media/src/matroska/codec.rs b/crates/media/src/matroska/codec.rs new file mode 100644 index 0000000000..1991459642 --- /dev/null +++ b/crates/media/src/matroska/codec.rs @@ -0,0 +1,236 @@ +//! Matroska CodecID → codec mapping (Matroska codec specifications, RFC 9559 §5.1.4.1.21 and the +//! codec mappings registry). + +/// Codec of a track, derived from `CodecID` and `CodecPrivate`. +/// +/// Configuration records are passed through as the raw bytes found in `CodecPrivate`, which for +/// the ISO codecs are exactly the ISOBMFF configuration boxes' payloads (avcC, hvcC, av1C, ASC…). +#[derive(Clone, Debug, PartialEq)] +pub enum Codec { + /// `V_MPEG4/ISO/AVC`; payload is an `AVCDecoderConfigurationRecord` (avcC). + Avc { avcc: Vec }, + /// `V_MPEGH/ISO/HEVC`; payload is an `HEVCDecoderConfigurationRecord` (hvcC). + Hevc { hvcc: Vec }, + /// `V_VP8`. + Vp8, + /// `V_VP9`; `CodecPrivate` (optional) holds VP9 codec feature metadata. + Vp9 { private: Vec }, + /// `V_AV1`; payload is an `AV1CodecConfigurationRecord` (av1C). + Av1 { av1c: Vec }, + /// `V_APV`; payload is an `APVDecoderConfigurationRecord` (apvC), if present. + Apv { apvc: Vec }, + /// `V_PRORES`; `fourcc` from `CodecPrivate` (e.g. `apcn`), if present. + ProRes { fourcc: Option<[u8; 4]> }, + /// `V_MJPEG`, or `V_MS/VFW/FOURCC` with an `MJPG` compression FourCC. + Mjpeg, + /// `V_MS/VFW/FOURCC` with any other FourCC; `bitmap_info_header` is the whole `CodecPrivate`. + VfwFourcc { fourcc: [u8; 4], bitmap_info_header: Vec }, + /// `A_AAC` (and the legacy `A_AAC/MPEG{2,4}/` IDs); `asc` is the + /// `AudioSpecificConfig` (synthesized for legacy IDs without `CodecPrivate`). + Aac { asc: Vec }, + /// `A_OPUS`; `head` is the `OpusHead` identification header. + Opus { head: Vec }, + /// `A_VORBIS`; the three Vorbis headers (identification, comment, setup), split from the + /// Xiph-laced `CodecPrivate`. + Vorbis { headers: Vec> }, + /// `A_FLAC`; `private` is `fLaC` + metadata blocks (STREAMINFO first). + Flac { private: Vec }, + /// `A_PCM/INT/LIT`, `A_PCM/INT/BIG`, `A_PCM/FLOAT/IEEE`. Bit depth comes from the Audio element. + Pcm { float: bool, big_endian: bool, bits: u16 }, + /// `A_AC3`. + Ac3, + /// `A_EAC3`. + Eac3, + /// `A_MPEG/L3`. + Mp3, + /// `A_MPEG/L2`. + Mp2, + /// `A_MPEG/L1`. + Mp1, + /// `S_TEXT/UTF8` (SubRip-style plain text). + SubRip, + /// `S_TEXT/WEBVTT`, or WebM's `D_WEBVTT/{SUBTITLES,CAPTIONS,DESCRIPTIONS,METADATA}`. + WebVtt, + /// `S_TEXT/ASS` / `S_TEXT/SSA`; `header` is the script header from `CodecPrivate`. + Ass { header: Vec, ssa: bool }, + /// Any other CodecID (kept verbatim along with `Track::codec_private`). + Other(String), +} + +impl Codec { + /// Short codec name, matching FFmpeg's `codec_name` where one exists (useful for logs/UI). + pub fn name(&self) -> String { + match self { + Codec::Avc { .. } => "h264".into(), + Codec::Hevc { .. } => "hevc".into(), + Codec::Vp8 => "vp8".into(), + Codec::Vp9 { .. } => "vp9".into(), + Codec::Av1 { .. } => "av1".into(), + Codec::Apv { .. } => "apv".into(), + Codec::ProRes { .. } => "prores".into(), + Codec::Mjpeg => "mjpeg".into(), + Codec::VfwFourcc { fourcc, .. } => String::from_utf8_lossy(fourcc).trim().to_ascii_lowercase(), + Codec::Aac { .. } => "aac".into(), + Codec::Opus { .. } => "opus".into(), + Codec::Vorbis { .. } => "vorbis".into(), + Codec::Flac { .. } => "flac".into(), + Codec::Pcm { float, big_endian, bits } => { + let k = if *float { + 'f' + } else if *bits == 8 { + 'u' + } else { + 's' + }; + if *bits == 8 { format!("pcm_{k}8") } else { format!("pcm_{k}{bits}{}", if *big_endian { "be" } else { "le" }) } + } + Codec::Ac3 => "ac3".into(), + Codec::Eac3 => "eac3".into(), + Codec::Mp3 => "mp3".into(), + Codec::Mp2 => "mp2".into(), + Codec::Mp1 => "mp1".into(), + Codec::SubRip => "subrip".into(), + Codec::WebVtt => "webvtt".into(), + Codec::Ass { ssa, .. } => if *ssa { "ssa" } else { "ass" }.into(), + Codec::Other(id) => id.clone(), + } + } +} + +const AAC_RATES: [u32; 13] = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; + +/// Build a 2-byte (or 5-byte with SBR extension) AudioSpecificConfig for legacy `A_AAC/...` IDs. +fn synth_asc(object_type: u8, rate: f64, out_rate: Option, channels: u64, sbr: bool) -> Vec { + let rate_index = |r: f64| AAC_RATES.iter().position(|&x| x as f64 == r).unwrap_or(4) as u8; + let ri = rate_index(rate); + let ch = channels.min(7) as u8; + let mut v = vec![(object_type << 3) | (ri >> 1), ((ri & 1) << 7) | (ch << 3)]; + if sbr { + // backward-compatible explicit signaling: sync 0x2b7, SBR object type 5, flag, ext rate index + let ext = rate_index(out_rate.unwrap_or(rate * 2.0)); + v.push(0x56); + v.push(0xE5); + v.push(0x80 | (ext << 3)); + } + v +} + +/// Split a Xiph-laced `CodecPrivate` (Vorbis/Theora headers). +fn split_xiph(p: &[u8]) -> Vec> { + let Some(&n) = p.first() else { return Vec::new() }; + let mut pos = 1; + let mut sizes = Vec::new(); + for _ in 0..n { + let mut s = 0usize; + loop { + let Some(&b) = p.get(pos) else { return Vec::new() }; + pos += 1; + s += b as usize; + if b != 255 { + break; + } + } + sizes.push(s); + } + let mut out = Vec::new(); + for s in sizes { + let Some(h) = p.get(pos..pos + s) else { return Vec::new() }; + out.push(h.to_vec()); + pos += s; + } + out.push(p[pos.min(p.len())..].to_vec()); + out +} + +/// Map a CodecID + CodecPrivate (+ audio params for legacy AAC / PCM) to a [`Codec`]. +pub(crate) fn map_codec(id: &str, private: &[u8], audio: Option<&crate::matroska::AudioInfo>) -> Codec { + let p = private.to_vec(); + match id { + "V_MPEG4/ISO/AVC" => Codec::Avc { avcc: p }, + "V_MPEGH/ISO/HEVC" => Codec::Hevc { hvcc: p }, + "V_VP8" => Codec::Vp8, + "V_VP9" => Codec::Vp9 { private: p }, + "V_AV1" => Codec::Av1 { av1c: p }, + "V_APV" => Codec::Apv { apvc: p }, + "V_PRORES" => Codec::ProRes { fourcc: private.get(..4).and_then(|f| f.try_into().ok()) }, + "V_MJPEG" => Codec::Mjpeg, + "V_MS/VFW/FOURCC" => { + let fourcc: [u8; 4] = private.get(16..20).and_then(|f| f.try_into().ok()).unwrap_or(*b" "); + match &fourcc { + b"MJPG" | b"mjpg" | b"AVRn" | b"AVDJ" => Codec::Mjpeg, + b"H264" | b"h264" | b"avc1" | b"X264" | b"x264" => Codec::Avc { avcc: Vec::new() }, + b"apch" | b"apcn" | b"apcs" | b"apco" | b"ap4h" | b"ap4x" => Codec::ProRes { fourcc: Some(fourcc) }, + b"apv1" | b"APV1" => Codec::Apv { apvc: Vec::new() }, + _ => Codec::VfwFourcc { fourcc, bitmap_info_header: p }, + } + } + "A_AAC" => Codec::Aac { asc: p }, + "A_OPUS" => Codec::Opus { head: p }, + "A_VORBIS" => Codec::Vorbis { headers: split_xiph(private) }, + "A_FLAC" => Codec::Flac { private: p }, + "A_PCM/INT/LIT" | "A_PCM/INT/BIG" | "A_PCM/FLOAT/IEEE" => { + let bits = audio.and_then(|a| a.bit_depth).unwrap_or(if id == "A_PCM/FLOAT/IEEE" { 32 } else { 16 }) as u16; + Codec::Pcm { float: id == "A_PCM/FLOAT/IEEE", big_endian: id == "A_PCM/INT/BIG", bits } + } + "A_AC3" | "A_AC3/BSID9" | "A_AC3/BSID10" => Codec::Ac3, + "A_EAC3" => Codec::Eac3, + "A_MPEG/L3" => Codec::Mp3, + "A_MPEG/L2" => Codec::Mp2, + "A_MPEG/L1" => Codec::Mp1, + "S_TEXT/UTF8" => Codec::SubRip, + "S_TEXT/WEBVTT" | "D_WEBVTT/SUBTITLES" | "D_WEBVTT/CAPTIONS" | "D_WEBVTT/DESCRIPTIONS" | "D_WEBVTT/METADATA" => Codec::WebVtt, + "S_TEXT/ASS" | "S_ASS" => Codec::Ass { header: p, ssa: false }, + "S_TEXT/SSA" | "S_SSA" => Codec::Ass { header: p, ssa: true }, + _ if id.starts_with("A_AAC/") => { + if !private.is_empty() { + return Codec::Aac { asc: p }; + } + let (rate, out_rate, ch) = audio.map_or((48000.0, None, 2), |a| (a.sampling_frequency, a.output_sampling_frequency, a.channels)); + let object_type = if id.ends_with("/MAIN") { + 1 + } else if id.ends_with("/SSR") { + 3 + } else if id.ends_with("/LTP") { + 4 + } else { + 2 + }; + let sbr = id.ends_with("/SBR"); + Codec::Aac { asc: synth_asc(object_type, rate, out_rate, ch, sbr) } + } + _ => Codec::Other(id.to_string()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mapping() { + assert_eq!(map_codec("V_MPEG4/ISO/AVC", &[1, 2], None), Codec::Avc { avcc: vec![1, 2] }); + assert_eq!(map_codec("V_APV", &[1, 2, 3], None), Codec::Apv { apvc: vec![1, 2, 3] }); + assert_eq!(map_codec("V_APV", &[], None).name(), "apv"); + assert_eq!(map_codec("V_PRORES", b"apcn", None), Codec::ProRes { fourcc: Some(*b"apcn") }); + let mut bih = vec![0u8; 40]; + bih[16..20].copy_from_slice(b"MJPG"); + assert_eq!(map_codec("V_MS/VFW/FOURCC", &bih, None), Codec::Mjpeg); + bih[16..20].copy_from_slice(b"FFV1"); + assert!(matches!(map_codec("V_MS/VFW/FOURCC", &bih, None), Codec::VfwFourcc { fourcc, .. } if &fourcc == b"FFV1")); + let a = crate::matroska::AudioInfo { sampling_frequency: 44100.0, channels: 2, bit_depth: Some(24), output_sampling_frequency: None }; + assert_eq!(map_codec("A_PCM/INT/LIT", &[], Some(&a)).name(), "pcm_s24le"); + assert_eq!(map_codec("A_PCM/FLOAT/IEEE", &[], Some(&a)), Codec::Pcm { float: true, big_endian: false, bits: 24 }); + // legacy AAC LC 44.1k stereo → 0x12 0x10 + assert_eq!(map_codec("A_AAC/MPEG4/LC", &[], Some(&a)), Codec::Aac { asc: vec![0x12, 0x10] }); + assert_eq!(map_codec("S_TEXT/UTF8", &[], None).name(), "subrip"); + assert_eq!(map_codec("X_WHATEVER", &[], None), Codec::Other("X_WHATEVER".into())); + } + + #[test] + fn xiph_split() { + let mut p = vec![2u8, 3, 2]; + p.extend_from_slice(&[1, 1, 1, 2, 2, 3, 3, 3, 3]); + let h = split_xiph(&p); + assert_eq!(h, vec![vec![1, 1, 1], vec![2, 2], vec![3, 3, 3, 3]]); + } +} diff --git a/crates/media/src/matroska/demux.rs b/crates/media/src/matroska/demux.rs new file mode 100644 index 0000000000..2c95288f89 --- /dev/null +++ b/crates/media/src/matroska/demux.rs @@ -0,0 +1,1238 @@ +//! Matroska / WebM demuxer: EBML header, Segment walk, cluster scanning, packet reading, seeking. + +use std::collections::{HashSet, VecDeque}; + +use crate::matroska::ebml::{self, Children, Lacing, Size, parse_lacing, read_id, read_size}; +use crate::matroska::error::{Error, Result}; +use crate::matroska::ids::*; +use crate::matroska::meta::*; +use crate::matroska::source::{ByteSource, ReadSeekSource}; +use crate::matroska::track::{Sample, Track, TrackKind, gcd}; + +const WIN: usize = 64 * 1024; +/// Upper bound for level-1 metadata elements read into memory (Info, Tracks, Cues, Tags…). +const MAX_META: u64 = 256 << 20; + +/// Options for [`open_with`] / [`Demuxer::with_options`]. +#[derive(Clone, Debug)] +pub struct OpenOptions { + /// Scan every cluster at open to build per-track sample tables and keyframe indices + /// (reads only element and block headers, never frame payloads). Default `true`. + /// + /// With `false`, open stops at the first Cluster and uses the SeekHead to find Cues, Tags, + /// Chapters… placed after the clusters; [`Demuxer::seek`] then uses Cues (or builds the index + /// on first use if there are none). + pub index: bool, + /// Verify CRC-32 elements of level-1 elements (and clusters while indexing). Mismatches are + /// recorded in [`MkvFile::crc_errors`]; parsing continues. Default `false`. + pub verify_crc: bool, +} + +impl Default for OpenOptions { + fn default() -> Self { + Self { index: true, verify_crc: false } + } +} + +/// A parsed Matroska / WebM file (first Segment). +#[derive(Clone, Debug)] +pub struct MkvFile { + /// EBML `DocType`: `matroska` or `webm`. + pub doc_type: String, + pub doc_type_version: u64, + pub doc_type_read_version: u64, + /// Absolute offset of the Segment's data (base for SeekHead and Cues positions). + pub segment_data_start: u64, + /// Absolute end of the Segment (file end for unknown-size / live segments). + pub segment_end: u64, + /// Segment size field was "unknown" (live / streamed output). + pub live: bool, + pub info: SegmentInfo, + pub tracks: Vec, + pub seek_head: Vec, + /// Cue points, sorted by time. + pub cues: Vec, + /// Clusters in file order (complete only when [`MkvFile::indexed`]). + pub clusters: Vec, + pub chapters: Vec, + pub tags: Vec, + pub attachments: Vec, + /// Absolute offset of the first Cluster. + pub first_cluster: Option, + /// Sample tables have been built by scanning all clusters. + pub indexed: bool, + /// Number of CRC-32 elements verified (with `verify_crc`). + pub crc_checked: u32, + /// Absolute offsets of elements whose CRC-32 did not match. + pub crc_errors: Vec, + /// Non-fatal problems met while parsing (damage, resyncs, truncation). + pub warnings: Vec, +} + +/// One demuxed frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Packet { + /// Index into [`MkvFile::tracks`]. + pub track: usize, + /// Matroska `TrackNumber`. + pub track_number: u64, + /// Presentation timestamp in timestamp ticks (the track timebase, [`Track::timebase`]). + pub pts: i64, + /// Presentation timestamp in nanoseconds. + pub pts_ns: i64, + /// Duration in ticks (0 if unknown). + pub duration: u64, + /// Duration in nanoseconds (0 if unknown). + pub duration_ns: u64, + pub keyframe: bool, + pub discardable: bool, + pub invisible: bool, + /// `DiscardPadding` (ns) from the enclosing BlockGroup. + pub discard_padding_ns: Option, + /// Absolute offset of the stored frame data. + pub offset: u64, + /// Index of the frame within a laced block (0 when not laced). Laced frames after the first + /// only have exact timestamps when the block or track carries a duration; otherwise they + /// repeat the block timestamp and `duration` is 0. + pub lace: u16, + /// Frame bytes with header stripping undone. Frames of tracks with other content encodings + /// (zlib, encryption) are returned as stored; see [`Track::frames_readable`]. + pub data: Vec, +} + +/// Result of [`Demuxer::seek`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SeekPoint { + pub track: usize, + /// Keyframe timestamp in ticks and ns. + pub pts: i64, + pub pts_ns: i64, + /// Sample index of the keyframe when the file is indexed. + pub sample: Option, + pub cluster_offset: u64, + pub block_offset: u64, +} + +/// A keyframe index entry ([`Demuxer::keyframe_index`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Keyframe { + pub sample: usize, + pub pts: i64, + pub pts_ns: i64, + pub block_offset: u64, +} + +// --------------------------------------------------------------------------------------------- +// I/O with a small read window +// --------------------------------------------------------------------------------------------- + +#[derive(Default, Clone, Debug)] +struct Cache { + buf: Vec, + start: u64, +} + +struct Io<'a, S: ByteSource + ?Sized> { + src: &'a S, + len: u64, + cache: &'a mut Cache, +} + +#[derive(Clone, Copy, Debug)] +struct Hdr { + id: u32, + pos: u64, + size: Size, + hlen: usize, +} + +impl Hdr { + fn data_start(&self) -> u64 { + self.pos + self.hlen as u64 + } + /// End offset, clamped to `limit`; unknown sizes run to `limit`. + fn end(&self, limit: u64) -> u64 { + match self.size { + Size::Known(n) => self.data_start().saturating_add(n).min(limit), + Size::Unknown => limit, + } + } + fn overruns(&self, limit: u64) -> bool { + matches!(self.size, Size::Known(n) if self.data_start().saturating_add(n) > limit) + } +} + +impl<'a, S: ByteSource + ?Sized> Io<'a, S> { + fn new(src: &'a S, cache: &'a mut Cache) -> Self { + let len = src.len(); + Self { src, len, cache } + } + + /// Up to `n` (≤ WIN) bytes at `pos` (fewer at EOF). + fn peek(&mut self, pos: u64, n: usize) -> Result<&[u8]> { + let n = n.min(WIN); + if pos >= self.len { + return Ok(&[]); + } + let want_end = (pos + n as u64).min(self.len); + let c = &*self.cache; + if !(pos >= c.start && want_end <= c.start + c.buf.len() as u64) { + let fill = ((self.len - pos) as usize).min(WIN); + let mut buf = std::mem::take(&mut self.cache.buf); + buf.resize(fill, 0); + self.src.read_at(pos, &mut buf)?; + self.cache.buf = buf; + self.cache.start = pos; + } + let o = (pos - self.cache.start) as usize; + Ok(&self.cache.buf[o..o + (want_end - pos) as usize]) + } + + /// Exactly `n` bytes at `pos`. + fn read_vec(&mut self, pos: u64, n: u64) -> Result> { + if pos.checked_add(n).is_none_or(|e| e > self.len) { + return Err(Error::Io(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "read past end of file"))); + } + if n as usize <= WIN / 2 { + return Ok(self.peek(pos, n as usize)?.to_vec()); + } + let mut v = vec![0u8; n as usize]; + self.src.read_at(pos, &mut v)?; + Ok(v) + } + + /// Element header at `pos` (`None` if undecodable or past `limit`). + fn header(&mut self, pos: u64, limit: u64) -> Result> { + if pos >= limit { + return Ok(None); + } + let b = self.peek(pos, 12)?; + let Some((id, il)) = read_id(b) else { return Ok(None) }; + let Some((size, sl)) = read_size(&b[il..]) else { return Ok(None) }; + let hlen = il + sl; + if pos + hlen as u64 > limit { + return Ok(None); + } + Ok(Some(Hdr { id, pos, size, hlen })) + } + + /// Scan forward from `from` for a plausible level-1 element (Cluster preferred), up to `limit`. + fn resync(&mut self, from: u64, limit: u64) -> Result> { + let mut pos = from; + while pos + 4 <= limit { + let chunk = self.peek(pos, WIN)?.to_vec(); + if chunk.len() < 4 { + return Ok(None); + } + for i in 0..chunk.len() - 3 { + if chunk[i] & 0xF0 != 0x10 { + continue; + } + let id = u32::from_be_bytes([chunk[i], chunk[i + 1], chunk[i + 2], chunk[i + 3]]); + if !is_top_level(id) || id == EBML || id == SEGMENT { + continue; + } + let p = pos + i as u64; + if self.plausible(p, id, limit)? { + return Ok(Some(p)); + } + } + pos += (chunk.len() - 3) as u64; + } + Ok(None) + } + + fn plausible(&mut self, p: u64, id: u32, limit: u64) -> Result { + let Some(h) = self.header(p, limit)? else { return Ok(false) }; + if h.id != id || h.overruns(limit) { + return Ok(false); + } + if h.size == Size::Unknown && id != CLUSTER { + return Ok(false); + } + // first child must decode and fit; clusters must start with Timestamp (after CRC-32/Void) + let mut cp = h.data_start(); + let end = h.end(limit); + for _ in 0..3 { + let Some(c) = self.header(cp, end)? else { return Ok(false) }; + if c.overruns(end) { + return Ok(false); + } + if id != CLUSTER { + return Ok(true); + } + match c.id { + TIMESTAMP => return Ok(true), + CRC32 | VOID => cp = c.end(end), + _ => return Ok(false), + } + } + Ok(false) + } + + /// End of an unknown-size master element: the first child that is a top-level ID or undecodable. + fn unknown_end(&mut self, data_start: u64, limit: u64) -> Result { + let mut pos = data_start; + while pos < limit { + let Some(h) = self.header(pos, limit)? else { return Ok(pos) }; + if is_top_level(h.id) || h.size == Size::Unknown { + return Ok(pos); + } + pos = h.end(limit); + } + Ok(limit) + } +} + +// --------------------------------------------------------------------------------------------- +// Blocks +// --------------------------------------------------------------------------------------------- + +#[derive(Clone, Debug)] +struct BlockRef { + track: usize, + block_offset: u64, + /// Timestamp in ticks (cluster + relative). + ts: i64, + /// Absolute (offset, size) of each frame. + frames: Vec<(u64, u32)>, + block_duration: Option, + keyframe: bool, + discardable: bool, + invisible: bool, + discard_padding: Option, + /// (offset, size) of the `BlockAdditional` with `BlockAddID` 1 (WebM: the VP8/VP9 alpha + /// layer), kept for unlaced blocks only. + addition: Option<(u64, u32)>, +} + +#[derive(Clone, Copy, Debug)] +struct FrameRef { + track: usize, + offset: u64, + size: u32, + pts: i64, + pts_ns: i64, + duration: u64, + duration_ns: u64, + keyframe: bool, + discardable: bool, + invisible: bool, + discard_padding: Option, + block_offset: u64, + lace: u16, + addition: Option<(u64, u32)>, +} + +fn track_lookup(tracks: &[Track]) -> impl Fn(u64) -> Option + '_ { + move |n| tracks.iter().position(|t| t.number == n) +} + +/// A parsed block header: (track index, relative ts, flags, frames as (offset, size)). +type BlockHeader = (usize, i16, u8, Vec<(u64, u32)>); + +/// Parse the Block/SimpleBlock header at `data_start` (`len` bytes). +/// Returns `None` for unknown tracks / damage. +fn parse_block( + io: &mut Io<'_, S>, + data_start: u64, + len: u64, + lookup: &dyn Fn(u64) -> Option, +) -> Result> { + let head = io.peek(data_start, 16.min(len as usize))?; + let Some((tn, tl, _)) = ebml::read_vint(head) else { return Ok(None) }; + if head.len() < tl + 3 { + return Ok(None); + } + let rel = i16::from_be_bytes([head[tl], head[tl + 1]]); + let flags = head[tl + 2]; + let Some(track) = lookup(tn) else { return Ok(None) }; + let hdr = (tl + 3) as u64; + let lacing = Lacing::from_flags(flags); + let frames = if lacing == Lacing::None { + vec![(data_start + hdr, (len - hdr) as u32)] + } else { + let body = io.read_vec(data_start + hdr, len - hdr)?; + match parse_lacing(lacing, &body) { + Ok(f) => f.into_iter().map(|(o, l)| (data_start + hdr + o as u64, l as u32)).collect(), + Err(_) => return Ok(None), + } + }; + Ok(Some((track, rel, flags, frames))) +} + +/// The `BlockAdditional` with `BlockAddID` 1 (the default ID) in a `BlockAdditions` element: +/// (offset, size) of its data. Other IDs, empty additions and damaged children are skipped. +fn block_addition(io: &mut Io<'_, S>, start: u64, end: u64) -> Result> { + let mut pos = start; + while pos < end { + let Some(more) = io.header(pos, end)? else { break }; + let me = more.end(end); + if more.id == BLOCK_MORE { + let (mut id, mut data) = (1u64, None); + let mut p = more.data_start(); + while p < me { + let Some(c) = io.header(p, me)? else { break }; + let ce = c.end(me); + let len = ce.saturating_sub(c.data_start()); + match c.id { + BLOCK_ADD_ID => id = ebml::uint(io.peek(c.data_start(), len.min(8) as usize)?), + BLOCK_ADDITIONAL => data = u32::try_from(len).ok().filter(|&n| n > 0).map(|n| (c.data_start(), n)), + _ => {} + } + p = ce; + } + if id == 1 && data.is_some() { + return Ok(data); + } + } + pos = me; + } + Ok(None) +} + +/// Cluster timestamps are unsigned; a hostile value beyond `i64::MAX` saturates, so adding a +/// block's relative timestamp cannot overflow. +fn sat_i64(v: i128) -> i64 { + v.clamp(i64::MIN as i128, i64::MAX as i128) as i64 +} + +fn cluster_timestamp(raw: u64) -> i64 { + i64::try_from(raw).unwrap_or(i64::MAX) +} + +/// Parse one SimpleBlock or BlockGroup element. +fn parse_block_elem( + io: &mut Io<'_, S>, + h: &Hdr, + end: u64, + cluster_ts: i64, + lookup: &dyn Fn(u64) -> Option, +) -> Result> { + let ds = h.data_start(); + match h.id { + SIMPLE_BLOCK => { + let Some((track, rel, flags, frames)) = parse_block(io, ds, end - ds, lookup)? else { return Ok(None) }; + Ok(Some(BlockRef { + track, + block_offset: h.pos, + ts: cluster_ts.saturating_add(i64::from(rel)), + frames, + block_duration: None, + keyframe: flags & 0x80 != 0, + discardable: flags & 0x01 != 0, + invisible: flags & 0x08 != 0, + discard_padding: None, + addition: None, + })) + } + BLOCK_GROUP => { + let mut pos = ds; + let mut block = None; + let (mut dur, mut has_ref, mut pad, mut addition) = (None, false, None, None); + while pos < end { + let Some(c) = io.header(pos, end)? else { break }; + let ce = c.end(end); + match c.id { + BLOCK => block = parse_block(io, c.data_start(), ce - c.data_start(), lookup)?, + BLOCK_ADDITIONS => addition = block_addition(io, c.data_start(), ce)?, + BLOCK_DURATION => dur = Some(ebml::uint(io.peek(c.data_start(), (ce - c.data_start()) as usize)?)), + REFERENCE_BLOCK => has_ref = true, + DISCARD_PADDING => pad = Some(ebml::int(io.peek(c.data_start(), (ce - c.data_start()) as usize)?)), + _ => {} + } + pos = ce; + } + let Some((track, rel, flags, frames)) = block else { return Ok(None) }; + // with lacing, an addition belongs to the block, not to one of its frames + let addition = addition.filter(|_| frames.len() == 1); + Ok(Some(BlockRef { + track, + block_offset: h.pos, + ts: cluster_ts.saturating_add(i64::from(rel)), + frames, + block_duration: dur, + keyframe: !has_ref, + discardable: false, + invisible: flags & 0x08 != 0, + discard_padding: pad, + addition, + })) + } + _ => Ok(None), + } +} + +/// Expand a block into frames with per-lace timestamps. +fn expand(b: &BlockRef, t: &Track, scale: u64, skip: u16, out: &mut impl Extend) { + let n = b.frames.len() as u64; + // total block duration in ns + let block_ns: Option = match (b.block_duration, t.default_duration_ns) { + (Some(d), _) => Some(d as u128 * scale as u128), + (None, Some(dd)) => Some(dd as u128 * n as u128), + _ => None, + }; + let scale_i = scale as i128; + // round half away from zero + let to_ticks = |ns: i128| -> i64 { sat_i64(if ns >= 0 { (ns + scale_i / 2) / scale_i } else { (ns - scale_i / 2) / scale_i }) }; + // CodecDelay is subtracted from every timestamp (RFC 9559 §5.1.4.1.25); in ticks it is rounded + // once, so tick timestamps stay on the block grid. + let delay_ns = t.codec_delay_ns as i128; + let delay_ticks = to_ticks(delay_ns); + // `parse_info` caps the scale at 2^32, which keeps these products within i128; results + // outside i64 saturate. + let base_ns = b.ts as i128 * scale_i; + out.extend(b.frames.iter().enumerate().skip(skip as usize).map(|(i, &(offset, size))| { + let (start, end) = match block_ns { + Some(total) => ((total * i as u128 / n as u128) as i128, Some((total * (i as u128 + 1) / n as u128) as i128)), + None => (0, None), + }; + let pts_ns = base_ns + start - delay_ns; + let pts = to_ticks(base_ns + start).saturating_sub(delay_ticks); + let duration = end.map_or(0, |e| to_ticks(e).saturating_sub(to_ticks(start)).max(0) as u64); + FrameRef { + track: b.track, + offset, + size, + pts, + pts_ns: sat_i64(pts_ns), + duration, + duration_ns: end.map_or(0, |e| u64::try_from((e - start).max(0)).unwrap_or(u64::MAX)), + keyframe: b.keyframe, + discardable: b.discardable, + invisible: b.invisible, + discard_padding: b.discard_padding, + block_offset: b.block_offset, + lace: i as u16, + addition: b.addition, + } + })); +} + +/// Scan a whole cluster (headers only), returning its info and blocks. +fn scan_cluster( + io: &mut Io<'_, S>, + h: &Hdr, + limit: u64, + tracks: &[Track], + warnings: &mut Vec, +) -> Result<(ClusterInfo, Vec)> { + let lookup = track_lookup(tracks); + let ds = h.data_start(); + let known_end = match h.size { + Size::Known(_) => Some(h.end(limit)), + Size::Unknown => None, + }; + let lim = known_end.unwrap_or(limit); + let mut ts: i64 = 0; + let mut blocks = Vec::new(); + let mut pos = ds; + let end = loop { + if pos >= lim { + break lim; + } + let Some(c) = io.header(pos, lim)? else { + warnings.push(format!("damaged cluster at {}: undecodable element at {pos}", h.pos)); + break io.resync(pos + 1, limit)?.unwrap_or(limit); + }; + if known_end.is_none() && is_top_level(c.id) { + break pos; + } + if c.size == Size::Unknown || c.overruns(lim) { + warnings.push(format!("damaged cluster at {}: element 0x{:X} at {pos} overruns", h.pos, c.id)); + if c.overruns(lim) && matches!(c.id, SIMPLE_BLOCK | BLOCK_GROUP) && io.len <= c.data_start() + c.size.known().unwrap_or(0) { + break lim; // truncated file: drop the partial block + } + break io.resync(pos + 1, limit)?.unwrap_or(limit); + } + let ce = c.end(lim); + match c.id { + TIMESTAMP => ts = cluster_timestamp(ebml::uint(io.peek(c.data_start(), (ce - c.data_start()) as usize)?)), + SIMPLE_BLOCK | BLOCK_GROUP => { + if let Some(b) = parse_block_elem(io, &c, ce, ts, &lookup)? { + blocks.push(b); + } + } + _ => {} + } + pos = ce; + }; + Ok((ClusterInfo { offset: h.pos, data_start: ds, end, timestamp: ts.max(0) as u64 }, blocks)) +} + +// --------------------------------------------------------------------------------------------- +// Open +// --------------------------------------------------------------------------------------------- + +/// Open a Matroska/WebM file with default options (full sample index). +pub fn open(src: S) -> Result { + open_with(src, &OpenOptions::default()) +} + +/// Open with explicit options. +pub fn open_with(src: S, opts: &OpenOptions) -> Result { + let mut cache = Cache::default(); + open_impl(&src, opts, &mut cache) +} + +fn open_impl(src: &S, opts: &OpenOptions, cache: &mut Cache) -> Result { + let mut io = Io::new(src, cache); + let len = io.len; + // EBML header (tolerate leading junk in the first 64 KiB) + let start = { + let b = io.peek(0, WIN)?; + let magic = [0x1A, 0x45, 0xDF, 0xA3]; + b.windows(4).position(|w| w == magic).ok_or_else(|| Error::NotMatroska("no EBML header".into()))? as u64 + }; + let eh = io.header(start, len)?.ok_or_else(|| Error::NotMatroska("bad EBML header".into()))?; + let hdr_end = eh.end(len); + let hdr = io.read_vec(eh.data_start(), hdr_end - eh.data_start())?; + let (mut doc_type, mut dtv, mut dtrv) = ("matroska".to_string(), 1, 1); + for e in Children::new(&hdr) { + match e.id { + DOC_TYPE => doc_type = ebml::string(e.data), + DOC_TYPE_VERSION => dtv = ebml::uint(e.data), + DOC_TYPE_READ_VERSION => dtrv = ebml::uint(e.data), + EBML_MAX_ID_LENGTH if ebml::uint(e.data) > 4 => return Err(Error::Unsupported("EBMLMaxIDLength > 4".into())), + EBML_MAX_SIZE_LENGTH if ebml::uint(e.data) > 8 => return Err(Error::Unsupported("EBMLMaxSizeLength > 8".into())), + _ => {} + } + } + if doc_type != "matroska" && doc_type != "webm" { + return Err(Error::NotMatroska(format!("DocType {doc_type:?}"))); + } + // Segment + let mut pos = hdr_end; + let seg = loop { + let h = io.header(pos, len)?.ok_or_else(|| Error::Invalid("no Segment".into()))?; + if h.id == SEGMENT { + break h; + } + if h.size == Size::Unknown { + return Err(Error::Invalid("unknown-size element before Segment".into())); + } + pos = h.end(len); + }; + let mut file = MkvFile { + doc_type, + doc_type_version: dtv, + doc_type_read_version: dtrv, + segment_data_start: seg.data_start(), + segment_end: seg.end(len), + live: seg.size == Size::Unknown, + info: SegmentInfo::default(), + tracks: Vec::new(), + seek_head: Vec::new(), + cues: Vec::new(), + clusters: Vec::new(), + chapters: Vec::new(), + tags: Vec::new(), + attachments: Vec::new(), + first_cluster: None, + indexed: false, + crc_checked: 0, + crc_errors: Vec::new(), + warnings: Vec::new(), + }; + if seg.overruns(len) { + file.warnings.push("Segment extends past end of file (truncated)".into()); + } + let mut w = Walker { opts, parsed: HashSet::new(), blocks_seen: false }; + w.walk(&mut io, &mut file)?; + finish_tracks(&mut file); + Ok(file) +} + +struct Walker<'o> { + opts: &'o OpenOptions, + parsed: HashSet, + blocks_seen: bool, +} + +impl Walker<'_> { + fn walk(&mut self, io: &mut Io<'_, S>, file: &mut MkvFile) -> Result<()> { + let seg_end = file.segment_end; + let mut pos = file.segment_data_start; + while pos < seg_end { + let Some(h) = io.header(pos, seg_end)? else { + match io.resync(pos + 1, seg_end)? { + Some(p) => { + file.warnings.push(format!("undecodable element at {pos}; resynced at {p}")); + pos = p; + continue; + } + None => break, + } + }; + match h.id { + CLUSTER => { + if file.first_cluster.is_none() { + file.first_cluster = Some(h.pos); + // make sure Info/Tracks are known before interpreting blocks + self.follow_seek_head(io, file, &[INFO, TRACKS])?; + if !self.opts.index { + break; + } + } + let (ci, blocks) = scan_cluster(io, &h, seg_end, &file.tracks, &mut file.warnings)?; + if self.opts.verify_crc && h.size != Size::Unknown { + let data = io.read_vec(h.data_start(), ci.end - h.data_start())?; + self.check_crc(file, h.pos, &data); + } + add_blocks(file, file.clusters.len() as u32, &blocks); + self.blocks_seen = true; + file.clusters.push(ci); + pos = ci.end.max(h.data_start()); + } + SEEK_HEAD | INFO | TRACKS | CUES | CHAPTERS | TAGS | ATTACHMENTS => { + pos = self.level1(io, file, &h, seg_end)?; + } + EBML | SEGMENT => break, // chained segment: only the first one is read + _ => { + if h.size == Size::Unknown { + pos = io.unknown_end(h.data_start(), seg_end)?; + } else if h.overruns(seg_end) && h.id != VOID { + match io.resync(pos + 1, seg_end)? { + Some(p) => { + file.warnings.push(format!("oversized element 0x{:X} at {pos}; resynced at {p}", h.id)); + pos = p; + } + None => break, + } + } else { + pos = h.end(seg_end); + } + } + } + } + self.follow_seek_head(io, file, &[INFO, TRACKS, CUES, CHAPTERS, TAGS, ATTACHMENTS, SEEK_HEAD])?; + // follow a second-level SeekHead reached through the first one + self.follow_seek_head(io, file, &[CUES, CHAPTERS, TAGS, ATTACHMENTS])?; + file.cues.sort_by_key(|c| c.time); + file.indexed = self.opts.index; + Ok(()) + } + + fn follow_seek_head(&mut self, io: &mut Io<'_, S>, file: &mut MkvFile, ids: &[u32]) -> Result<()> { + let entries = file.seek_head.clone(); + for e in entries { + if !ids.contains(&e.id) { + continue; + } + let Some(abs) = file.segment_data_start.checked_add(e.position) else { continue }; + if self.parsed.contains(&abs) || abs >= file.segment_end { + continue; + } + match io.header(abs, file.segment_end)? { + Some(h) if h.id == e.id => { + self.level1(io, file, &h, file.segment_end)?; + } + _ => file.warnings.push(format!("SeekHead entry 0x{:X} -> {abs} does not point at that element", e.id)), + } + } + Ok(()) + } + + fn check_crc(&self, file: &mut MkvFile, pos: u64, data: &[u8]) { + if let Some(ok) = ebml::verify_crc(data) { + file.crc_checked += 1; + if !ok { + file.crc_errors.push(pos); + file.warnings.push(format!("CRC-32 mismatch in element at {pos}")); + } + } + } + + /// Parse a level-1 metadata element; returns its end. + fn level1(&mut self, io: &mut Io<'_, S>, file: &mut MkvFile, h: &Hdr, limit: u64) -> Result { + let end = if h.size == Size::Unknown { io.unknown_end(h.data_start(), limit)? } else { h.end(limit) }; + if h.overruns(limit) { + file.warnings.push(format!("element 0x{:X} at {} truncated", h.id, h.pos)); + } + if !self.parsed.insert(h.pos) { + return Ok(end); + } + if h.id == ATTACHMENTS { + self.attachments(io, file, h.data_start(), end)?; + return Ok(end); + } + let n = end - h.data_start(); + if n > MAX_META { + file.warnings.push(format!("element 0x{:X} at {} too large ({n} bytes); skipped", h.id, h.pos)); + return Ok(end); + } + let data = io.read_vec(h.data_start(), n)?; + if self.opts.verify_crc { + self.check_crc(file, h.pos, &data); + } + match h.id { + SEEK_HEAD => file.seek_head.extend(parse_seekhead(&data)), + INFO => file.info = parse_info(&data), + TRACKS if file.tracks.is_empty() => { + file.tracks = parse_tracks(&data, file.info.timestamp_scale); + } + CUES => parse_cues(&data, &mut file.cues), + CHAPTERS => parse_chapters(&data, &mut file.chapters), + TAGS => parse_tags(&data, &mut file.tags), + _ => {} + } + Ok(end) + } + + fn attachments(&mut self, io: &mut Io<'_, S>, file: &mut MkvFile, start: u64, end: u64) -> Result<()> { + let mut pos = start; + while pos < end { + let Some(h) = io.header(pos, end)? else { break }; + let he = h.end(end); + if h.id == ATTACHED_FILE { + let mut a = Attachment::default(); + let mut p = h.data_start(); + while p < he { + let Some(c) = io.header(p, he)? else { break }; + let ce = c.end(he); + let n = ce - c.data_start(); + if c.id == FILE_DATA { + a.data_offset = c.data_start(); + a.data_size = n; + } else if n <= 4096 { + let d = io.peek(c.data_start(), n as usize)?; + match c.id { + FILE_NAME => a.name = ebml::string(d), + FILE_MEDIA_TYPE => a.media_type = ebml::string(d), + FILE_DESCRIPTION => a.description = Some(ebml::string(d)), + FILE_UID => a.uid = ebml::uint(d), + _ => {} + } + } + p = ce; + } + file.attachments.push(a); + } + pos = he; + } + Ok(()) + } +} + +fn add_blocks(file: &mut MkvFile, cluster: u32, blocks: &[BlockRef]) { + let scale = file.info.timestamp_scale; + let mut frames: Vec = Vec::new(); + for b in blocks { + frames.clear(); + let t = &file.tracks[b.track]; + expand(b, t, scale, 0, &mut frames); + let t = &mut file.tracks[b.track]; + for f in &frames { + if f.keyframe { + t.sync.push(t.samples.len() as u32); + } + t.samples.push(Sample { + offset: f.offset, + size: f.size, + pts: f.pts, + duration: f.duration, + keyframe: f.keyframe, + cluster, + block_offset: f.block_offset, + lace: f.lace, + addition: f.addition, + }); + } + } +} + +fn finish_tracks(file: &mut MkvFile) { + let scale = file.info.timestamp_scale; + let g = gcd(scale, 1_000_000_000); + for t in &mut file.tracks { + t.timebase = (scale / g, 1_000_000_000 / g); + } +} + +// --------------------------------------------------------------------------------------------- +// MkvFile helpers +// --------------------------------------------------------------------------------------------- + +impl MkvFile { + /// True for WebM (`DocType` = `webm`). + pub fn is_webm(&self) -> bool { + self.doc_type == "webm" + } + + /// Segment duration in ns: `Info/Duration` if present, else the end of the last indexed sample. + pub fn duration_ns(&self) -> Option { + if let Some(d) = self.info.duration { + return Some((d * self.info.timestamp_scale as f64).round() as u64); + } + let end = self.tracks.iter().flat_map(|t| t.samples.iter().map(|s| s.pts.saturating_add(s.duration.min(i64::MAX as u64) as i64))).max()?; + Some((end.max(0) as u64).saturating_mul(self.info.timestamp_scale)) + } + + /// Index of the track with this `TrackNumber`. + pub fn track_by_number(&self, number: u64) -> Option { + self.tracks.iter().position(|t| t.number == number) + } + + /// Index of the first track of the given kind (preferring the default flag). + pub fn track_of_kind(&self, kind: TrackKind) -> Option { + let mut it = self.tracks.iter().enumerate().filter(|(_, t)| t.kind == kind); + let first = it.clone().next().map(|x| x.0); + it.find(|(_, t)| t.default).map(|x| x.0).or(first) + } + + /// Read sample `index` of `track` (header stripping undone). + pub fn read_sample(&self, src: &S, track: usize, index: usize) -> Result> { + let t = self.tracks.get(track).ok_or(Error::NoSuchTrack(track))?; + let s = t.samples.get(index).ok_or(Error::NoSuchSample(index))?; + if !t.frames_readable() { + return Err(Error::Unsupported(format!("content encoding of track {} (compression/encryption)", t.number))); + } + let mut data = t.frame_prefix(s.size as u64); + let at = data.len(); + data.resize(at + s.size as usize, 0); + src.read_at(s.offset, &mut data[at..])?; + Ok(data) + } + + /// The `BlockAdditional` (ID 1) of sample `index` of `track`, `None` when the block has none + /// (see [`Sample::addition`]). Stored as is: header stripping applies to frames only. + pub fn read_sample_addition(&self, src: &S, track: usize, index: usize) -> Result>> { + let t = self.tracks.get(track).ok_or(Error::NoSuchTrack(track))?; + let s = t.samples.get(index).ok_or(Error::NoSuchSample(index))?; + let Some((offset, size)) = s.addition else { return Ok(None) }; + if offset.checked_add(size as u64).is_none_or(|end| end > src.len()) { + return Err(Error::Invalid("block addition past end of file".into())); + } + let mut data = vec![0; size as usize]; + src.read_at(offset, &mut data)?; + Ok(Some(data)) + } + + /// Keyframe sample of `track` with the greatest pts ≤ `time_ns` (indexed files only). + pub fn keyframe_before(&self, track: usize, time_ns: i64) -> Option { + let t = self.tracks.get(track)?; + t.keyframe_before_pts(t.ns_to_ticks(time_ns)) + } +} + +// --------------------------------------------------------------------------------------------- +// Demuxer (streaming packets + seeking) +// --------------------------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug)] +struct InCluster { + ts: i64, + end: Option, +} + +/// Packet reader over a [`ByteSource`]: iterates frames in file order and seeks to keyframes. +pub struct Demuxer { + src: S, + file: MkvFile, + opts: OpenOptions, + cache: Cache, + pos: u64, + cluster: Option, + pending: VecDeque, + skip_laces: Option<(u64, u16)>, + done: bool, +} + +impl Demuxer> { + /// Open from any `Read + Seek` stream. + pub fn from_reader(r: R) -> Result { + Self::new(ReadSeekSource::new(r)?) + } +} + +impl<'a> Demuxer<&'a [u8]> { + /// Open from an in-memory byte slice. + pub fn from_slice(data: &'a [u8]) -> Result { + Self::new(data) + } +} + +impl Demuxer { + /// Open with default options (full index). + pub fn new(src: S) -> Result { + Self::with_options(src, OpenOptions::default()) + } + + pub fn with_options(src: S, opts: OpenOptions) -> Result { + let mut cache = Cache::default(); + let file = open_impl(&src, &opts, &mut cache)?; + let pos = file.first_cluster.unwrap_or(file.segment_end); + Ok(Self { src, file, opts, cache, pos, cluster: None, pending: VecDeque::new(), skip_laces: None, done: false }) + } + + pub fn file(&self) -> &MkvFile { + &self.file + } + pub fn tracks(&self) -> &[Track] { + &self.file.tracks + } + pub fn source(&self) -> &S { + &self.src + } + pub fn into_parts(self) -> (S, MkvFile) { + (self.src, self.file) + } + /// Segment duration in ns. + pub fn duration_ns(&self) -> Option { + self.file.duration_ns() + } + + /// Scan all clusters and build sample tables (no-op if already indexed). + pub fn build_index(&mut self) -> Result<()> { + if self.file.indexed { + return Ok(()); + } + let opts = OpenOptions { index: true, verify_crc: self.opts.verify_crc }; + self.file = open_impl(&self.src, &opts, &mut self.cache)?; + Ok(()) + } + + /// Keyframes of `track` (builds the index if needed). + pub fn keyframe_index(&mut self, track: usize) -> Result> { + self.build_index()?; + let t = self.file.tracks.get(track).ok_or(Error::NoSuchTrack(track))?; + Ok(t.keyframes() + .iter() + .map(|&k| { + let s = &t.samples[k as usize]; + Keyframe { sample: k as usize, pts: s.pts, pts_ns: t.ticks_to_ns(s.pts), block_offset: s.block_offset } + }) + .collect()) + } + + /// Rewind to the first cluster. + pub fn rewind(&mut self) { + self.pos = self.file.first_cluster.unwrap_or(self.file.segment_end); + self.cluster = None; + self.pending.clear(); + self.skip_laces = None; + self.done = false; + } + + /// Read sample `index` of `track` (requires an index). + pub fn read_sample(&self, track: usize, index: usize) -> Result> { + self.file.read_sample(&self.src, track, index) + } + + /// Position the packet stream at the keyframe of `track` with the greatest pts ≤ `time_ns` + /// (or the track's first keyframe if none precedes it). The next [`Demuxer::next_packet`] + /// call returns packets starting at that keyframe's block (all tracks). + /// + /// Uses the sample index when present, else Cues (refined by scanning the cued cluster), else + /// builds the index first. + pub fn seek(&mut self, track: usize, time_ns: i64) -> Result { + let t = self.file.tracks.get(track).ok_or(Error::NoSuchTrack(track))?; + let ticks = t.ns_to_ticks(time_ns); + if !self.file.indexed { + let tn = t.number; + let cue = self + .file + .cues + .iter() + .filter(|c| c.time as i64 <= ticks) + .filter_map(|c| c.positions.iter().find(|p| p.track == tn).map(|p| (c.time, *p))) + .next_back() + .or_else(|| self.file.cues.iter().find_map(|c| c.positions.iter().find(|p| p.track == tn).map(|p| (c.time, *p)))); + if let Some((_, cp)) = cue + && let Some(sp) = self.seek_via_cue(track, ticks, cp.cluster_position)? + { + return Ok(sp); + } + self.build_index()?; + } + let t = &self.file.tracks[track]; + let k = t.keyframe_before_pts(ticks).ok_or_else(|| Error::Invalid(format!("track {} has no keyframes", t.number)))?; + let s = t.samples[k]; + let c = self.file.clusters[s.cluster as usize]; + let sp = + SeekPoint { track, pts: s.pts, pts_ns: t.ticks_to_ns(s.pts), sample: Some(k), cluster_offset: c.offset, block_offset: s.block_offset }; + self.position_at(c, s.block_offset, s.lace); + Ok(sp) + } + + fn position_at(&mut self, c: ClusterInfo, block_offset: u64, lace: u16) { + self.pending.clear(); + self.done = false; + self.pos = block_offset; + let known = c.end; + self.cluster = Some(InCluster { ts: cluster_timestamp(c.timestamp), end: Some(known) }); + self.skip_laces = (lace > 0).then_some((block_offset, lace)); + } + + fn seek_via_cue(&mut self, track: usize, ticks: i64, cluster_position: u64) -> Result> { + let Some(abs) = self.file.segment_data_start.checked_add(cluster_position) else { + self.file.warnings.push(format!("cue position {cluster_position} is past the segment end")); + return Ok(None); + }; + let mut io = Io::new(&self.src, &mut self.cache); + let Some(h) = io.header(abs, self.file.segment_end)? else { return Ok(None) }; + if h.id != CLUSTER { + self.file.warnings.push(format!("cue points at {abs}, which is not a Cluster")); + return Ok(None); + } + let mut warnings = Vec::new(); + let (ci, blocks) = scan_cluster(&mut io, &h, self.file.segment_end, &self.file.tracks, &mut warnings)?; + let t = &self.file.tracks[track]; + let mut frames = Vec::new(); + for b in blocks.iter().filter(|b| b.track == track && b.keyframe) { + expand(b, t, self.file.info.timestamp_scale, 0, &mut frames); + } + let best = frames.iter().filter(|f| f.pts <= ticks).max_by_key(|f| f.pts).or_else(|| frames.iter().min_by_key(|f| f.pts)).copied(); + let Some(f) = best else { return Ok(None) }; + let sp = SeekPoint { track, pts: f.pts, pts_ns: f.pts_ns, sample: None, cluster_offset: ci.offset, block_offset: f.block_offset }; + self.position_at(ci, f.block_offset, f.lace); + Ok(Some(sp)) + } + + /// Next frame in file order, or `None` at the end of the Segment. + pub fn next_packet(&mut self) -> Result> { + loop { + if let Some(f) = self.pending.pop_front() { + return self.materialize(f).map(Some); + } + if self.done || !self.fill()? { + self.done = true; + return Ok(None); + } + } + } + + fn materialize(&mut self, f: FrameRef) -> Result { + let t = &self.file.tracks[f.track]; + let mut data = if t.frames_readable() { t.frame_prefix(f.size as u64) } else { Vec::new() }; + let at = data.len(); + data.resize(at + f.size as usize, 0); + let mut io = Io::new(&self.src, &mut self.cache); + if (f.size as usize) <= WIN / 2 { + let b = io.peek(f.offset, f.size as usize)?; + if b.len() != f.size as usize { + return Err(Error::Invalid("frame data past end of file".into())); + } + data[at..].copy_from_slice(b); + } else { + self.src.read_at(f.offset, &mut data[at..])?; + } + Ok(Packet { + track: f.track, + track_number: t.number, + pts: f.pts, + pts_ns: f.pts_ns, + duration: f.duration, + duration_ns: f.duration_ns, + keyframe: f.keyframe, + discardable: f.discardable, + invisible: f.invisible, + discard_padding_ns: f.discard_padding, + offset: f.offset, + lace: f.lace, + data, + }) + } + + /// Advance over elements until at least one frame is pending. Returns false at the end. + fn fill(&mut self) -> Result { + let seg_end = self.file.segment_end; + let scale = self.file.info.timestamp_scale; + let mut io = Io::new(&self.src, &mut self.cache); + let lookup = track_lookup(&self.file.tracks); + loop { + if let Some(c) = self.cluster { + let lim = c.end.unwrap_or(seg_end); + if self.pos >= lim { + self.cluster = None; + continue; + } + let Some(h) = io.header(self.pos, lim)? else { + self.cluster = None; + match io.resync(self.pos + 1, seg_end)? { + Some(p) => { + self.pos = p; + continue; + } + None => return Ok(false), + } + }; + if c.end.is_none() && is_top_level(h.id) { + self.cluster = None; + continue; + } + if h.size == Size::Unknown || h.overruns(lim) { + self.cluster = None; + match io.resync(self.pos + 1, seg_end)? { + Some(p) => { + self.pos = p; + continue; + } + None => return Ok(false), + } + } + let he = h.end(lim); + self.pos = he; + match h.id { + TIMESTAMP => { + let v = cluster_timestamp(ebml::uint(io.peek(h.data_start(), (he - h.data_start()) as usize)?)); + self.cluster = Some(InCluster { ts: v, end: c.end }); + } + SIMPLE_BLOCK | BLOCK_GROUP => { + if let Some(b) = parse_block_elem(&mut io, &h, he, c.ts, &lookup)? { + let skip = match self.skip_laces.take() { + Some((off, n)) if off == h.pos => n, + _ => 0, + }; + expand(&b, &self.file.tracks[b.track], scale, skip, &mut self.pending); + if !self.pending.is_empty() { + return Ok(true); + } + } + } + _ => {} + } + continue; + } + if self.pos >= seg_end { + return Ok(false); + } + let Some(h) = io.header(self.pos, seg_end)? else { + match io.resync(self.pos + 1, seg_end)? { + Some(p) => { + self.pos = p; + continue; + } + None => return Ok(false), + } + }; + match h.id { + CLUSTER => { + self.cluster = Some(InCluster { ts: 0, end: h.size.known().map(|_| h.end(seg_end)) }); + self.pos = h.data_start(); + } + EBML | SEGMENT => return Ok(false), + _ => { + self.pos = if h.size == Size::Unknown { io.unknown_end(h.data_start(), seg_end)? } else { h.end(seg_end) }; + if self.pos <= h.pos { + return Ok(false); + } + } + } + } + } +} + +impl Iterator for Demuxer { + type Item = Result; + fn next(&mut self) -> Option> { + match self.next_packet() { + Ok(Some(p)) => Some(Ok(p)), + Ok(None) => None, + Err(e) => { + self.done = true; + Some(Err(e)) + } + } + } +} diff --git a/crates/media/src/matroska/ebml.rs b/crates/media/src/matroska/ebml.rs new file mode 100644 index 0000000000..95a680e75e --- /dev/null +++ b/crates/media/src/matroska/ebml.rs @@ -0,0 +1,476 @@ +//! EBML primitives (RFC 8794): variable-length integers, element headers, typed values, CRC-32, +//! and Matroska block lacing (RFC 9559 §10.3). + +use crate::matroska::error::{Result, invalid}; + +/// Length in bytes of a VINT whose first byte is `b` (1..=8), or `None` for a zero first byte. +#[inline] +pub fn vint_len(b: u8) -> Option { + if b == 0 { None } else { Some(b.leading_zeros() as usize + 1) } +} + +/// Element data size: known, or "unknown" (all value bits set). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Size { + Known(u64), + Unknown, +} + +impl Size { + pub fn known(self) -> Option { + match self { + Size::Known(n) => Some(n), + Size::Unknown => None, + } + } +} + +/// Decode an unsigned VINT (marker bit stripped). Returns `(value, length, all_ones)`. +pub fn read_vint(data: &[u8]) -> Option<(u64, usize, bool)> { + let first = *data.first()?; + let len = vint_len(first)?; + if data.len() < len { + return None; + } + let mask = if len == 8 { 0 } else { 0xFFu8 >> len }; + let mut v = (first & mask) as u64; + for &b in &data[1..len] { + v = (v << 8) | b as u64; + } + let all_ones = v == (1u64 << (7 * len)) - 1; + Some((v, len, all_ones)) +} + +/// Decode an element data size. All-ones is the reserved "unknown size". +pub fn read_size(data: &[u8]) -> Option<(Size, usize)> { + let (v, len, ones) = read_vint(data)?; + Some((if ones { Size::Unknown } else { Size::Known(v) }, len)) +} + +/// Decode an element ID (marker bits kept, 1..=4 bytes). Rejects all-ones value bits (reserved). +/// All-zero value bits are accepted, because Matroska's `ChapterDisplay` uses ID `0x80`. +pub fn read_id(data: &[u8]) -> Option<(u32, usize)> { + let first = *data.first()?; + let len = vint_len(first)?; + if len > 4 || data.len() < len { + return None; + } + let (v, _, ones) = read_vint(&data[..len])?; + if ones || (v == 0 && len > 1) { + return None; + } + let mut id = 0u32; + for &b in &data[..len] { + id = (id << 8) | b as u32; + } + Some((id, len)) +} + +/// Decode a signed VINT as used by EBML lacing (value − (2^(7·len−1) − 1)). +pub fn read_svint(data: &[u8]) -> Option<(i64, usize)> { + let (v, len, _) = read_vint(data)?; + let bias = (1i64 << (7 * len - 1)) - 1; + Some((v as i64 - bias, len)) +} + +/// Encode an element ID (already carrying its marker bits). +pub fn write_id(out: &mut Vec, id: u32) { + let n = if id >= 0x100_0000 { + 4 + } else if id >= 0x1_0000 { + 3 + } else if id >= 0x100 { + 2 + } else { + 1 + }; + out.extend_from_slice(&id.to_be_bytes()[4 - n..]); +} + +/// Encode a data size as a VINT using the shortest length (or `min_len` if larger). +pub fn write_size(out: &mut Vec, size: u64, min_len: usize) { + let mut len = 1; + while len < 8 && size >= (1u64 << (7 * len)) - 1 { + len += 1; + } + let len = len.max(min_len).min(8); + let v = size | (1u64 << (7 * len)); + out.extend_from_slice(&v.to_be_bytes()[8 - len..]); +} + +/// Encode the "unknown size" marker of the given length. +pub fn write_unknown_size(out: &mut Vec, len: usize) { + out.push(0xFFu8 >> (len - 1)); + out.extend(std::iter::repeat_n(0xFF, len - 1)); +} + +/// Big-endian unsigned integer of 0..=8 bytes. +pub fn uint(data: &[u8]) -> u64 { + data.iter().take(8).fold(0u64, |a, &b| (a << 8) | b as u64) +} + +/// Big-endian two's-complement signed integer of 0..=8 bytes. +pub fn int(data: &[u8]) -> i64 { + let n = data.len().min(8); + if n == 0 { + return 0; + } + let v = uint(&data[..n]); + let shift = 64 - 8 * n as u32; + ((v << shift) as i64) >> shift +} + +/// IEEE float of 0, 4 or 8 bytes. +pub fn float(data: &[u8]) -> f64 { + match data.len() { + 4 => f32::from_be_bytes(data.try_into().unwrap_or([0; 4])) as f64, + 8 => f64::from_be_bytes(data.try_into().unwrap_or([0; 8])), + _ => 0.0, + } +} + +/// String / UTF-8 value: bytes up to the first NUL, lossily decoded. +pub fn string(data: &[u8]) -> String { + let end = data.iter().position(|&b| b == 0).unwrap_or(data.len()); + String::from_utf8_lossy(&data[..end]).into_owned() +} + +/// One element inside an in-memory master element. +#[derive(Clone, Copy, Debug)] +pub struct Elem<'a> { + pub id: u32, + /// Offset of the element header, relative to the start of the parent's data. + pub offset: usize, + pub header_len: usize, + pub data: &'a [u8], + /// The size field was "unknown" (data runs to the end of the parent). + pub unknown_size: bool, + /// The declared size overran the parent and was truncated. + pub truncated: bool, +} + +/// Iterator over the children of an in-memory master element. +/// +/// Damaged data ends the iteration (see [`Children::damaged`]); oversize elements are truncated to +/// the parent's end. +pub struct Children<'a> { + data: &'a [u8], + pos: usize, + damaged: bool, +} + +impl<'a> Children<'a> { + pub fn new(data: &'a [u8]) -> Self { + Self { data, pos: 0, damaged: false } + } + /// True if iteration stopped on an undecodable header. + pub fn damaged(&self) -> bool { + self.damaged + } +} + +impl<'a> Iterator for Children<'a> { + type Item = Elem<'a>; + fn next(&mut self) -> Option> { + let rest = self.data.get(self.pos..)?; + if rest.is_empty() { + return None; + } + let Some((id, il)) = read_id(rest) else { + self.damaged = true; + self.pos = self.data.len(); + return None; + }; + let Some((size, sl)) = read_size(&rest[il..]) else { + self.damaged = true; + self.pos = self.data.len(); + return None; + }; + let hl = il + sl; + let avail = (rest.len() - hl) as u64; + let (len, unknown, truncated) = match size { + Size::Known(n) if n <= avail => (n as usize, false, false), + Size::Known(_) => (avail as usize, false, true), + Size::Unknown => (avail as usize, true, false), + }; + let e = Elem { id, offset: self.pos, header_len: hl, data: &rest[hl..hl + len], unknown_size: unknown, truncated }; + self.pos += hl + len; + Some(e) + } +} + +/// CRC-32 (ISO 3309 / IEEE 802.3, reflected polynomial 0xEDB88320), as used by EBML CRC-32 elements. +pub fn crc32(data: &[u8]) -> u32 { + crc32_update(0xFFFF_FFFF, data) ^ 0xFFFF_FFFF +} + +/// Incremental form: start with `0xFFFF_FFFF`, finish with `^ 0xFFFF_FFFF`. +pub fn crc32_update(mut crc: u32, data: &[u8]) -> u32 { + static TABLE: std::sync::OnceLock<[u32; 256]> = std::sync::OnceLock::new(); + let t = TABLE.get_or_init(|| { + let mut t = [0u32; 256]; + for (i, e) in t.iter_mut().enumerate() { + let mut c = i as u32; + for _ in 0..8 { + c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + } + *e = c; + } + t + }); + for &b in data { + crc = t[((crc ^ b as u32) & 0xFF) as usize] ^ (crc >> 8); + } + crc +} + +/// Check a master element's leading CRC-32 child, if present. `Some(true/false)` if there is one. +pub fn verify_crc(master_data: &[u8]) -> Option { + let mut it = Children::new(master_data); + let first = it.next()?; + if first.id != crate::matroska::ids::CRC32 || first.data.len() != 4 { + return None; + } + let stored = u32::from_le_bytes(first.data.try_into().ok()?); + let rest = &master_data[first.offset + first.header_len + 4..]; + Some(crc32(rest) == stored) +} + +/// Block lacing mode (flags bits 1–2). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Lacing { + None, + Xiph, + FixedSize, + Ebml, +} + +impl Lacing { + pub fn from_flags(flags: u8) -> Lacing { + match (flags >> 1) & 3 { + 0 => Lacing::None, + 1 => Lacing::Xiph, + 2 => Lacing::FixedSize, + _ => Lacing::Ebml, + } + } +} + +/// Split laced block payload. `data` starts right after the block's flags byte and runs to the end +/// of the block. Returns `(offset, len)` of each frame relative to `data`. +pub fn parse_lacing(lacing: Lacing, data: &[u8]) -> Result> { + if lacing == Lacing::None { + return Ok(vec![(0, data.len())]); + } + let Some(&n1) = data.first() else { return invalid("laced block without frame count") }; + let count = n1 as usize + 1; + let mut pos = 1usize; + let mut sizes = Vec::with_capacity(count); + match lacing { + Lacing::None => return Ok(vec![(0, data.len())]), + Lacing::Xiph => { + for _ in 0..count - 1 { + let mut s = 0usize; + loop { + let Some(&b) = data.get(pos) else { return invalid("truncated Xiph lace header") }; + pos += 1; + s += b as usize; + if b != 255 { + break; + } + } + sizes.push(s); + } + } + Lacing::Ebml => { + if count > 1 { + let Some((first, l, _)) = read_vint(&data[pos..]) else { return invalid("bad EBML lace size") }; + pos += l; + let mut prev = first as i64; + sizes.push(first as usize); + for _ in 1..count - 1 { + let Some((d, l)) = read_svint(&data[pos..]) else { return invalid("bad EBML lace delta") }; + pos += l; + prev += d; + if prev < 0 { + return invalid("negative EBML lace size"); + } + sizes.push(prev as usize); + } + } + } + Lacing::FixedSize => { + let rest = data.len() - pos; + if !rest.is_multiple_of(count) { + return invalid("fixed-size lacing does not divide block"); + } + sizes.extend(std::iter::repeat_n(rest / count, count - 1)); + } + } + let used: usize = sizes.iter().try_fold(0usize, |a, &s| a.checked_add(s)).unwrap_or(usize::MAX); + if pos > data.len() || used > data.len() - pos { + return invalid("lace sizes exceed block"); + } + sizes.push(data.len() - pos - used); + let mut out = Vec::with_capacity(count); + for s in sizes { + out.push((pos, s)); + pos += s; + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vint_roundtrip() { + for &v in &[0u64, 1, 126, 127, 128, 16382, 16383, 16384, 1 << 20, (1 << 56) - 2] { + let mut b = Vec::new(); + write_size(&mut b, v, 1); + let (s, l) = read_size(&b).unwrap(); + assert_eq!(s, Size::Known(v), "value {v}"); + assert_eq!(l, b.len()); + } + // 127 needs 2 bytes because 0xFF is "unknown" + let mut b = Vec::new(); + write_size(&mut b, 127, 1); + assert_eq!(b, [0x40, 0x7F]); + // padded length + let mut b = Vec::new(); + write_size(&mut b, 5, 8); + assert_eq!(b, [1, 0, 0, 0, 0, 0, 0, 5]); + assert_eq!(read_size(&b).unwrap(), (Size::Known(5), 8)); + } + + #[test] + fn vint_unknown_and_invalid() { + assert_eq!(read_size(&[0xFF]).unwrap(), (Size::Unknown, 1)); + assert_eq!(read_size(&[0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).unwrap(), (Size::Unknown, 8)); + for l in 1..=8 { + let mut b = Vec::new(); + write_unknown_size(&mut b, l); + assert_eq!(read_size(&b).unwrap(), (Size::Unknown, l)); + } + assert!(read_size(&[0x00, 1, 2]).is_none()); + assert!(read_size(&[0x40]).is_none()); // truncated + assert_eq!(read_vint(&[0x81]).unwrap(), (1, 1, false)); + assert_eq!(read_vint(&[0x10, 0x00, 0x00, 0x01]).unwrap(), (1, 4, false)); + } + + #[test] + fn ids() { + assert_eq!(read_id(&[0x1A, 0x45, 0xDF, 0xA3, 0x99]).unwrap(), (crate::matroska::ids::EBML, 4)); + assert_eq!(read_id(&[0xA3]).unwrap(), (0xA3, 1)); + assert_eq!(read_id(&[0x42, 0x86]).unwrap(), (0x4286, 2)); + assert!(read_id(&[0xFF]).is_none()); // reserved + assert_eq!(read_id(&[0x80]).unwrap(), (0x80, 1)); // ChapterDisplay + assert!(read_id(&[0x40, 0x00]).is_none()); // zero value + assert!(read_id(&[0x08, 0, 0, 0, 1]).is_none()); // 5-byte ID + for id in [0xA3u32, 0x4286, 0x2AD7B1, 0x1F43B675] { + let mut b = Vec::new(); + write_id(&mut b, id); + assert_eq!(read_id(&b).unwrap(), (id, b.len())); + } + } + + #[test] + fn signed_vint() { + assert_eq!(read_svint(&[0xBF]).unwrap(), (0, 1)); // 63 - 63 + assert_eq!(read_svint(&[0x80]).unwrap(), (-63, 1)); + assert_eq!(read_svint(&[0xC0]).unwrap(), (1, 1)); + assert_eq!(read_svint(&[0x5F, 0xFF]).unwrap(), (0, 2)); + assert_eq!(read_svint(&[0x60, 0x00]).unwrap(), (1, 2)); + } + + #[test] + fn values() { + assert_eq!(uint(&[]), 0); + assert_eq!(uint(&[1, 0]), 256); + assert_eq!(int(&[0xFF]), -1); + assert_eq!(int(&[0xFF, 0xFE]), -2); + assert_eq!(int(&[0x7F]), 127); + assert_eq!(float(&1.5f32.to_be_bytes()), 1.5); + assert_eq!(float(&2.25f64.to_be_bytes()), 2.25); + assert_eq!(string(b"abc\0\0"), "abc"); + } + + #[test] + fn crc() { + assert_eq!(crc32(b"123456789"), 0xCBF4_3926); + let payload = [0x42u8, 0x86, 0x81, 0x01]; + let mut m = vec![0xBF, 0x84]; + m.extend_from_slice(&crc32(&payload).to_le_bytes()); + m.extend_from_slice(&payload); + assert_eq!(verify_crc(&m), Some(true)); + m[7] ^= 1; + assert_eq!(verify_crc(&m), Some(false)); + assert_eq!(verify_crc(&payload), None); + } + + #[test] + fn children_iter() { + // two elements, then one whose size overruns + let d = [0x42, 0x86, 0x81, 0x01, 0xEC, 0x82, 0, 0, 0xA3, 0x85, 1, 2]; + let v: Vec<_> = Children::new(&d).collect(); + assert_eq!(v.len(), 3); + assert_eq!(v[0].id, 0x4286); + assert_eq!(v[0].data, &[1]); + assert_eq!(v[1].id, 0xEC); + assert_eq!(v[2].data, &[1, 2]); + assert!(v[2].truncated); + let mut it = Children::new(&[0x00, 0x01]); + assert!(it.next().is_none()); + assert!(it.damaged()); + } + + fn frames<'a>(d: &'a [u8], f: &[(usize, usize)]) -> Vec<&'a [u8]> { + f.iter().map(|&(o, l)| &d[o..o + l]).collect() + } + + #[test] + fn lacing_xiph() { + // 3 frames: 300, 2, rest(3) + let mut d = vec![2u8, 255, 45, 2]; + d.extend(std::iter::repeat_n(7u8, 300)); + d.extend_from_slice(&[1, 2]); + d.extend_from_slice(&[3, 4, 5]); + let f = parse_lacing(Lacing::Xiph, &d).unwrap(); + assert_eq!(f.iter().map(|x| x.1).collect::>(), [300, 2, 3]); + assert_eq!(frames(&d, &f)[2], &[3, 4, 5]); + // exact multiple of 255 needs a terminating 0 + let mut d = vec![1u8, 255, 0]; + d.extend(std::iter::repeat_n(1u8, 255)); + d.push(9); + let f = parse_lacing(Lacing::Xiph, &d).unwrap(); + assert_eq!(f.iter().map(|x| x.1).collect::>(), [255, 1]); + assert!(parse_lacing(Lacing::Xiph, &[1, 200, 1]).is_err()); + } + + #[test] + fn lacing_ebml() { + // 4 frames: 5, 3 (delta -2), 4 (delta +1), rest 2 + let mut d = vec![3u8, 0x85, 0xBF - 2, 0xBF + 1]; + d.extend_from_slice(&[1; 5]); + d.extend_from_slice(&[2; 3]); + d.extend_from_slice(&[3; 4]); + d.extend_from_slice(&[4; 2]); + let f = parse_lacing(Lacing::Ebml, &d).unwrap(); + assert_eq!(f.iter().map(|x| x.1).collect::>(), [5, 3, 4, 2]); + assert_eq!(frames(&d, &f), [&[1u8; 5][..], &[2; 3], &[3; 4], &[4; 2]]); + assert!(parse_lacing(Lacing::Ebml, &[1, 0x90]).is_err()); + } + + #[test] + fn lacing_fixed_and_none() { + let d = [2u8, 1, 1, 2, 2, 3, 3]; + let f = parse_lacing(Lacing::FixedSize, &d).unwrap(); + assert_eq!(frames(&d, &f), [&[1u8, 1][..], &[2, 2], &[3, 3]]); + assert!(parse_lacing(Lacing::FixedSize, &[2, 1, 1]).is_err()); + assert_eq!(parse_lacing(Lacing::None, &[9, 9]).unwrap(), [(0, 2)]); + assert_eq!(Lacing::from_flags(0x80 | 0x06), Lacing::Ebml); + assert_eq!(Lacing::from_flags(0x02), Lacing::Xiph); + assert_eq!(Lacing::from_flags(0x04), Lacing::FixedSize); + } +} diff --git a/crates/media/src/matroska/error.rs b/crates/media/src/matroska/error.rs new file mode 100644 index 0000000000..718c5c505f --- /dev/null +++ b/crates/media/src/matroska/error.rs @@ -0,0 +1,53 @@ +use std::fmt; +use std::io; + +/// Errors produced by the demuxer. +#[derive(Debug)] +pub enum Error { + /// Underlying I/O failure. + Io(io::Error), + /// Structurally invalid data that could not be recovered from. + Invalid(String), + /// Valid but unsupported feature (e.g. zlib-compressed or encrypted tracks when reading data). + Unsupported(String), + /// Not an EBML file, or an EBML file whose DocType is not `matroska`/`webm`. + NotMatroska(String), + /// A track index was out of range. + NoSuchTrack(usize), + /// A sample index was out of range. + NoSuchSample(usize), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Io(e) => write!(f, "I/O error: {e}"), + Error::Invalid(s) => write!(f, "invalid data: {s}"), + Error::Unsupported(s) => write!(f, "unsupported: {s}"), + Error::NotMatroska(s) => write!(f, "not a Matroska/WebM file: {s}"), + Error::NoSuchTrack(i) => write!(f, "track index {i} out of range"), + Error::NoSuchSample(i) => write!(f, "sample index {i} out of range"), + } + } +} + +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) + } +} + +pub type Result = std::result::Result; + +pub(crate) fn invalid(msg: impl Into) -> Result { + Err(Error::Invalid(msg.into())) +} diff --git a/crates/media/src/matroska/ids.rs b/crates/media/src/matroska/ids.rs new file mode 100644 index 0000000000..3c7eefd3f6 --- /dev/null +++ b/crates/media/src/matroska/ids.rs @@ -0,0 +1,216 @@ +//! EBML / Matroska element IDs (RFC 8794, RFC 9559). IDs keep their VINT marker bits. +#![allow(dead_code)] + +// EBML header + global elements +pub const EBML: u32 = 0x1A45_DFA3; +pub const EBML_VERSION: u32 = 0x4286; +pub const EBML_READ_VERSION: u32 = 0x42F7; +pub const EBML_MAX_ID_LENGTH: u32 = 0x42F2; +pub const EBML_MAX_SIZE_LENGTH: u32 = 0x42F3; +pub const DOC_TYPE: u32 = 0x4282; +pub const DOC_TYPE_VERSION: u32 = 0x4287; +pub const DOC_TYPE_READ_VERSION: u32 = 0x4285; +pub const CRC32: u32 = 0xBF; +pub const VOID: u32 = 0xEC; + +// Segment and level-1 elements +pub const SEGMENT: u32 = 0x1853_8067; +pub const SEEK_HEAD: u32 = 0x114D_9B74; +pub const INFO: u32 = 0x1549_A966; +pub const TRACKS: u32 = 0x1654_AE6B; +pub const CLUSTER: u32 = 0x1F43_B675; +pub const CUES: u32 = 0x1C53_BB6B; +pub const ATTACHMENTS: u32 = 0x1941_A469; +pub const CHAPTERS: u32 = 0x1043_A770; +pub const TAGS: u32 = 0x1254_C367; + +/// True for IDs that can only appear directly inside a Segment (or are the EBML/Segment headers): +/// used to find the end of unknown-size elements. +pub fn is_top_level(id: u32) -> bool { + matches!(id, EBML | SEGMENT | SEEK_HEAD | INFO | TRACKS | CLUSTER | CUES | ATTACHMENTS | CHAPTERS | TAGS) +} + +// SeekHead +pub const SEEK: u32 = 0x4DBB; +pub const SEEK_ID: u32 = 0x53AB; +pub const SEEK_POSITION: u32 = 0x53AC; + +// Info +pub const SEGMENT_UUID: u32 = 0x73A4; +pub const SEGMENT_FILENAME: u32 = 0x7384; +pub const TIMESTAMP_SCALE: u32 = 0x2A_D7B1; +pub const DURATION: u32 = 0x4489; +pub const DATE_UTC: u32 = 0x4461; +pub const TITLE: u32 = 0x7BA9; +pub const MUXING_APP: u32 = 0x4D80; +pub const WRITING_APP: u32 = 0x5741; + +// Cluster +pub const TIMESTAMP: u32 = 0xE7; +pub const POSITION: u32 = 0xA7; +pub const PREV_SIZE: u32 = 0xAB; +pub const SIMPLE_BLOCK: u32 = 0xA3; +pub const BLOCK_GROUP: u32 = 0xA0; +pub const ENCRYPTED_BLOCK: u32 = 0xAF; +pub const SILENT_TRACKS: u32 = 0x5854; +pub const BLOCK: u32 = 0xA1; +pub const BLOCK_ADDITIONS: u32 = 0x75A1; +pub const BLOCK_MORE: u32 = 0xA6; +pub const BLOCK_ADD_ID: u32 = 0xEE; +pub const BLOCK_ADDITIONAL: u32 = 0xA5; +pub const BLOCK_DURATION: u32 = 0x9B; +pub const REFERENCE_PRIORITY: u32 = 0xFA; +pub const REFERENCE_BLOCK: u32 = 0xFB; +pub const CODEC_STATE: u32 = 0xA4; +pub const DISCARD_PADDING: u32 = 0x75A2; + +pub fn is_cluster_child(id: u32) -> bool { + matches!(id, TIMESTAMP | POSITION | PREV_SIZE | SIMPLE_BLOCK | BLOCK_GROUP | ENCRYPTED_BLOCK | SILENT_TRACKS | CRC32 | VOID) +} + +// Tracks +pub const TRACK_ENTRY: u32 = 0xAE; +pub const TRACK_NUMBER: u32 = 0xD7; +pub const TRACK_UID: u32 = 0x73C5; +pub const TRACK_TYPE: u32 = 0x83; +pub const FLAG_ENABLED: u32 = 0xB9; +pub const FLAG_DEFAULT: u32 = 0x88; +pub const FLAG_FORCED: u32 = 0x55AA; +pub const FLAG_HEARING_IMPAIRED: u32 = 0x55AB; +pub const FLAG_VISUAL_IMPAIRED: u32 = 0x55AC; +pub const FLAG_ORIGINAL: u32 = 0x55AE; +pub const FLAG_COMMENTARY: u32 = 0x55AF; +pub const FLAG_LACING: u32 = 0x9C; +pub const DEFAULT_DURATION: u32 = 0x23_E383; +pub const TRACK_TIMESTAMP_SCALE: u32 = 0x23_314F; +pub const NAME: u32 = 0x536E; +pub const LANGUAGE: u32 = 0x22_B59C; +pub const LANGUAGE_BCP47: u32 = 0x22_B59D; +pub const CODEC_ID: u32 = 0x86; +pub const CODEC_PRIVATE: u32 = 0x63A2; +pub const CODEC_NAME: u32 = 0x25_8688; +pub const CODEC_DELAY: u32 = 0x56AA; +pub const SEEK_PRE_ROLL: u32 = 0x56BB; + +// Video +pub const VIDEO: u32 = 0xE0; +pub const FLAG_INTERLACED: u32 = 0x9A; +pub const FIELD_ORDER: u32 = 0x9D; +pub const STEREO_MODE: u32 = 0x53B8; +pub const ALPHA_MODE: u32 = 0x53C0; +pub const PIXEL_WIDTH: u32 = 0xB0; +pub const PIXEL_HEIGHT: u32 = 0xBA; +pub const PIXEL_CROP_BOTTOM: u32 = 0x54AA; +pub const PIXEL_CROP_TOP: u32 = 0x54BB; +pub const PIXEL_CROP_LEFT: u32 = 0x54CC; +pub const PIXEL_CROP_RIGHT: u32 = 0x54DD; +pub const DISPLAY_WIDTH: u32 = 0x54B0; +pub const DISPLAY_HEIGHT: u32 = 0x54BA; +pub const DISPLAY_UNIT: u32 = 0x54B2; +/// Matroska `ColourSpace`. +pub const COLOR_SPACE: u32 = 0x2E_B524; +/// Matroska `Colour`. +pub const COLOR: u32 = 0x55B0; +pub const PROJECTION: u32 = 0x7670; +pub const PROJECTION_TYPE: u32 = 0x7671; +pub const PROJECTION_POSE_YAW: u32 = 0x7673; +pub const PROJECTION_POSE_PITCH: u32 = 0x7674; +pub const PROJECTION_POSE_ROLL: u32 = 0x7675; + +// Colour +pub const MATRIX_COEFFICIENTS: u32 = 0x55B1; +pub const BITS_PER_CHANNEL: u32 = 0x55B2; +pub const CHROMA_SUBSAMPLING_HORZ: u32 = 0x55B3; +pub const CHROMA_SUBSAMPLING_VERT: u32 = 0x55B4; +pub const CB_SUBSAMPLING_HORZ: u32 = 0x55B5; +pub const CB_SUBSAMPLING_VERT: u32 = 0x55B6; +pub const CHROMA_SITING_HORZ: u32 = 0x55B7; +pub const CHROMA_SITING_VERT: u32 = 0x55B8; +pub const RANGE: u32 = 0x55B9; +pub const TRANSFER_CHARACTERISTICS: u32 = 0x55BA; +pub const PRIMARIES: u32 = 0x55BB; +pub const MAX_CLL: u32 = 0x55BC; +pub const MAX_FALL: u32 = 0x55BD; +pub const MASTERING_METADATA: u32 = 0x55D0; +pub const PRIMARY_R_X: u32 = 0x55D1; +pub const PRIMARY_R_Y: u32 = 0x55D2; +pub const PRIMARY_G_X: u32 = 0x55D3; +pub const PRIMARY_G_Y: u32 = 0x55D4; +pub const PRIMARY_B_X: u32 = 0x55D5; +pub const PRIMARY_B_Y: u32 = 0x55D6; +pub const WHITE_POINT_X: u32 = 0x55D7; +pub const WHITE_POINT_Y: u32 = 0x55D8; +pub const LUMINANCE_MAX: u32 = 0x55D9; +pub const LUMINANCE_MIN: u32 = 0x55DA; + +// Audio +pub const AUDIO: u32 = 0xE1; +pub const SAMPLING_FREQUENCY: u32 = 0xB5; +pub const OUTPUT_SAMPLING_FREQUENCY: u32 = 0x78B5; +pub const CHANNELS: u32 = 0x9F; +pub const BIT_DEPTH: u32 = 0x6264; + +// ContentEncodings +pub const CONTENT_ENCODINGS: u32 = 0x6D80; +pub const CONTENT_ENCODING: u32 = 0x6240; +pub const CONTENT_ENCODING_ORDER: u32 = 0x5031; +pub const CONTENT_ENCODING_SCOPE: u32 = 0x5032; +pub const CONTENT_ENCODING_TYPE: u32 = 0x5033; +pub const CONTENT_COMPRESSION: u32 = 0x5034; +pub const CONTENT_COMP_ALGO: u32 = 0x4254; +pub const CONTENT_COMP_SETTINGS: u32 = 0x4255; +pub const CONTENT_ENCRYPTION: u32 = 0x5035; + +// Cues +pub const CUE_POINT: u32 = 0xBB; +pub const CUE_TIME: u32 = 0xB3; +pub const CUE_TRACK_POSITIONS: u32 = 0xB7; +pub const CUE_TRACK: u32 = 0xF7; +pub const CUE_CLUSTER_POSITION: u32 = 0xF1; +pub const CUE_RELATIVE_POSITION: u32 = 0xF0; +pub const CUE_DURATION: u32 = 0xB2; +pub const CUE_BLOCK_NUMBER: u32 = 0x5378; + +// Attachments +pub const ATTACHED_FILE: u32 = 0x61A7; +pub const FILE_DESCRIPTION: u32 = 0x467E; +pub const FILE_NAME: u32 = 0x466E; +pub const FILE_MEDIA_TYPE: u32 = 0x4660; +pub const FILE_DATA: u32 = 0x465C; +pub const FILE_UID: u32 = 0x46AE; + +// Chapters +pub const EDITION_ENTRY: u32 = 0x45B9; +pub const EDITION_UID: u32 = 0x45BC; +pub const EDITION_FLAG_HIDDEN: u32 = 0x45BD; +pub const EDITION_FLAG_DEFAULT: u32 = 0x45DB; +pub const EDITION_FLAG_ORDERED: u32 = 0x45DD; +pub const CHAPTER_ATOM: u32 = 0xB6; +pub const CHAPTER_UID: u32 = 0x73C4; +pub const CHAPTER_STRING_UID: u32 = 0x5654; +pub const CHAPTER_TIME_START: u32 = 0x91; +pub const CHAPTER_TIME_END: u32 = 0x92; +pub const CHAPTER_FLAG_HIDDEN: u32 = 0x98; +pub const CHAPTER_FLAG_ENABLED: u32 = 0x4598; +pub const CHAPTER_DISPLAY: u32 = 0x80; +pub const CHAP_STRING: u32 = 0x85; +pub const CHAP_LANGUAGE: u32 = 0x437C; +pub const CHAP_LANGUAGE_BCP47: u32 = 0x437D; +pub const CHAP_COUNTRY: u32 = 0x437E; + +// Tags +pub const TAG: u32 = 0x7373; +pub const TARGETS: u32 = 0x63C0; +pub const TARGET_TYPE_VALUE: u32 = 0x68CA; +pub const TARGET_TYPE: u32 = 0x63CA; +pub const TAG_TRACK_UID: u32 = 0x63C5; +pub const TAG_EDITION_UID: u32 = 0x63C9; +pub const TAG_CHAPTER_UID: u32 = 0x63C4; +pub const TAG_ATTACHMENT_UID: u32 = 0x63C6; +pub const SIMPLE_TAG: u32 = 0x67C8; +pub const TAG_NAME: u32 = 0x45A3; +pub const TAG_LANGUAGE: u32 = 0x447A; +pub const TAG_LANGUAGE_BCP47: u32 = 0x447B; +pub const TAG_DEFAULT: u32 = 0x4484; +pub const TAG_STRING: u32 = 0x4487; +pub const TAG_BINARY: u32 = 0x4485; diff --git a/crates/media/src/matroska/meta.rs b/crates/media/src/matroska/meta.rs new file mode 100644 index 0000000000..1b559bca9c --- /dev/null +++ b/crates/media/src/matroska/meta.rs @@ -0,0 +1,613 @@ +//! Segment-level metadata: Info, SeekHead, Cues, Chapters, Tags, Attachments — types and parsers +//! for their in-memory element data. + +use crate::matroska::codec::map_codec; +use crate::matroska::ebml::{Children, float, int, string, uint}; +use crate::matroska::ids::*; +use crate::matroska::track::{AudioInfo, Color, ContentEncoding, MasteringMetadata, Projection, Track, TrackKind, VideoInfo, gcd}; + +// A malformed Matroska file may contain arbitrarily deep ChapterAtom and SimpleTag chains. +const MAX_META_DEPTH: usize = 64; +/// Longest header-stripping prefix accepted. It is copied in front of every frame, laced +/// zero-length frames included, so its length multiplies what a small file can make a reader +/// produce. Real files strip a few bytes of codec header; a longer one is treated as an +/// unsupported compression and its frames are not reconstructed. +const MAX_STRIPPED_HEADER: usize = 256; +/// Largest accepted `TimestampScale` (about 4.3 s per tick). It keeps tick to nanosecond +/// arithmetic on 64-bit timestamps within `i128`. +const MAX_TIMESTAMP_SCALE: u64 = 1 << 32; + +/// `Info` element. +#[derive(Clone, Debug, PartialEq)] +pub struct SegmentInfo { + /// Nanoseconds per timestamp tick (default 1 000 000 = 1 ms). A file's value above 2^32 is + /// ignored. + pub timestamp_scale: u64, + /// `Duration` in timestamp ticks (float), if present. + pub duration: Option, + pub title: Option, + pub muxing_app: String, + pub writing_app: String, + /// `DateUTC`: nanoseconds since 2001-01-01T00:00:00 UTC. + pub date_utc: Option, + pub segment_uuid: Option<[u8; 16]>, +} + +impl Default for SegmentInfo { + fn default() -> Self { + Self { + timestamp_scale: 1_000_000, + duration: None, + title: None, + muxing_app: String::new(), + writing_app: String::new(), + date_utc: None, + segment_uuid: None, + } + } +} + +/// One `SeekHead` entry: level-1 element ID and its position relative to the Segment data start. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SeekEntry { + pub id: u32, + pub position: u64, +} + +/// One `CueTrackPositions` of a `CuePoint`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CuePosition { + pub track: u64, + /// Cluster position relative to the Segment data start. + pub cluster_position: u64, + /// Block position relative to the Cluster data start. + pub relative_position: Option, + pub block_number: Option, + pub duration: Option, +} + +/// One `CuePoint`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CuePoint { + /// In timestamp ticks. + pub time: u64, + pub positions: Vec, +} + +/// A cluster found while scanning. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ClusterInfo { + /// Absolute offset of the Cluster element header. + pub offset: u64, + /// Absolute offset of the first child. + pub data_start: u64, + /// Absolute end offset (for unknown-size clusters, where the next top-level element starts). + pub end: u64, + /// Cluster `Timestamp` in ticks. + pub timestamp: u64, +} + +/// One `ChapterDisplay`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ChapterDisplay { + pub string: String, + pub languages: Vec, + pub languages_bcp47: Vec, + pub countries: Vec, +} + +/// `ChapterAtom` (possibly nested). +#[derive(Clone, Debug, PartialEq)] +pub struct Chapter { + pub uid: u64, + pub string_uid: Option, + pub start_ns: u64, + pub end_ns: Option, + pub hidden: bool, + pub enabled: bool, + pub displays: Vec, + pub children: Vec, +} + +impl Chapter { + /// First display string, if any. + pub fn title(&self) -> Option<&str> { + self.displays.first().map(|d| d.string.as_str()) + } +} + +/// `EditionEntry`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Edition { + pub uid: Option, + pub hidden: bool, + pub default: bool, + pub ordered: bool, + pub chapters: Vec, +} + +/// `Targets` of a `Tag`. Empty UID lists mean "the whole segment". +#[derive(Clone, Debug, PartialEq)] +pub struct TagTargets { + pub type_value: u64, + pub type_name: Option, + pub track_uids: Vec, + pub edition_uids: Vec, + pub chapter_uids: Vec, + pub attachment_uids: Vec, +} + +impl Default for TagTargets { + fn default() -> Self { + Self { + type_value: 50, + type_name: None, + track_uids: Vec::new(), + edition_uids: Vec::new(), + chapter_uids: Vec::new(), + attachment_uids: Vec::new(), + } + } +} + +/// `SimpleTag` (possibly nested). +#[derive(Clone, Debug, PartialEq)] +pub struct SimpleTag { + pub name: String, + pub language: String, + pub default: bool, + pub string: Option, + pub binary: Option>, + pub children: Vec, +} + +/// `Tag`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Tag { + pub targets: TagTargets, + pub simple: Vec, +} + +/// `AttachedFile` (listed only; the payload is located by `data_offset`/`data_size`). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Attachment { + pub uid: u64, + pub name: String, + pub media_type: String, + pub description: Option, + pub data_offset: u64, + pub data_size: u64, +} + +pub(crate) fn parse_info(d: &[u8]) -> SegmentInfo { + let mut info = SegmentInfo::default(); + for e in Children::new(d) { + match e.id { + TIMESTAMP_SCALE => { + let v = uint(e.data); + if v > 0 && v <= MAX_TIMESTAMP_SCALE { + info.timestamp_scale = v; + } + } + DURATION => info.duration = Some(float(e.data)).filter(|v| v.is_finite() && *v >= 0.0), + TITLE => info.title = Some(string(e.data)), + MUXING_APP => info.muxing_app = string(e.data), + WRITING_APP => info.writing_app = string(e.data), + DATE_UTC => info.date_utc = Some(int(e.data)), + SEGMENT_UUID => info.segment_uuid = e.data.try_into().ok(), + _ => {} + } + } + info +} + +pub(crate) fn parse_seekhead(d: &[u8]) -> Vec { + let mut out = Vec::new(); + for s in Children::new(d).filter(|e| e.id == SEEK) { + let (mut id, mut pos) = (None, None); + for e in Children::new(s.data) { + match e.id { + SEEK_ID => id = Some(uint(e.data) as u32), + SEEK_POSITION => pos = Some(uint(e.data)), + _ => {} + } + } + if let (Some(id), Some(position)) = (id, pos) { + out.push(SeekEntry { id, position }); + } + } + out +} + +pub(crate) fn parse_cues(d: &[u8], out: &mut Vec) { + for cp in Children::new(d).filter(|e| e.id == CUE_POINT) { + let mut time = None; + let mut positions = Vec::new(); + for e in Children::new(cp.data) { + match e.id { + CUE_TIME => time = Some(uint(e.data)), + CUE_TRACK_POSITIONS => { + let mut p = CuePosition { track: 0, cluster_position: u64::MAX, relative_position: None, block_number: None, duration: None }; + for c in Children::new(e.data) { + match c.id { + CUE_TRACK => p.track = uint(c.data), + CUE_CLUSTER_POSITION => p.cluster_position = uint(c.data), + CUE_RELATIVE_POSITION => p.relative_position = Some(uint(c.data)), + CUE_BLOCK_NUMBER => p.block_number = Some(uint(c.data)), + CUE_DURATION => p.duration = Some(uint(c.data)), + _ => {} + } + } + if p.track != 0 && p.cluster_position != u64::MAX { + positions.push(p); + } + } + _ => {} + } + } + if let Some(time) = time + && !positions.is_empty() + { + out.push(CuePoint { time, positions }); + } + } +} + +fn parse_chapter(d: &[u8], depth: usize) -> Chapter { + let mut c = + Chapter { uid: 0, string_uid: None, start_ns: 0, end_ns: None, hidden: false, enabled: true, displays: Vec::new(), children: Vec::new() }; + for e in Children::new(d) { + match e.id { + CHAPTER_UID => c.uid = uint(e.data), + CHAPTER_STRING_UID => c.string_uid = Some(string(e.data)), + CHAPTER_TIME_START => c.start_ns = uint(e.data), + CHAPTER_TIME_END => c.end_ns = Some(uint(e.data)), + CHAPTER_FLAG_HIDDEN => c.hidden = uint(e.data) != 0, + CHAPTER_FLAG_ENABLED => c.enabled = uint(e.data) != 0, + CHAPTER_DISPLAY => { + let mut disp = ChapterDisplay::default(); + for x in Children::new(e.data) { + match x.id { + CHAP_STRING => disp.string = string(x.data), + CHAP_LANGUAGE => disp.languages.push(string(x.data)), + CHAP_LANGUAGE_BCP47 => disp.languages_bcp47.push(string(x.data)), + CHAP_COUNTRY => disp.countries.push(string(x.data)), + _ => {} + } + } + if disp.languages.is_empty() { + disp.languages.push("eng".into()); + } + c.displays.push(disp); + } + CHAPTER_ATOM if depth < MAX_META_DEPTH => c.children.push(parse_chapter(e.data, depth + 1)), + _ => {} + } + } + c +} + +pub(crate) fn parse_chapters(d: &[u8], out: &mut Vec) { + for ed in Children::new(d).filter(|e| e.id == EDITION_ENTRY) { + let mut edition = Edition::default(); + for e in Children::new(ed.data) { + match e.id { + EDITION_UID => edition.uid = Some(uint(e.data)), + EDITION_FLAG_HIDDEN => edition.hidden = uint(e.data) != 0, + EDITION_FLAG_DEFAULT => edition.default = uint(e.data) != 0, + EDITION_FLAG_ORDERED => edition.ordered = uint(e.data) != 0, + CHAPTER_ATOM => edition.chapters.push(parse_chapter(e.data, 0)), + _ => {} + } + } + out.push(edition); + } +} + +fn parse_simple_tag(d: &[u8], depth: usize) -> SimpleTag { + let mut t = SimpleTag { name: String::new(), language: "und".into(), default: true, string: None, binary: None, children: Vec::new() }; + for e in Children::new(d) { + match e.id { + TAG_NAME => t.name = string(e.data), + TAG_LANGUAGE => t.language = string(e.data), + TAG_DEFAULT => t.default = uint(e.data) != 0, + TAG_STRING => t.string = Some(string(e.data)), + TAG_BINARY => t.binary = Some(e.data.to_vec()), + SIMPLE_TAG if depth < MAX_META_DEPTH => t.children.push(parse_simple_tag(e.data, depth + 1)), + _ => {} + } + } + t +} + +pub(crate) fn parse_tags(d: &[u8], out: &mut Vec) { + for tg in Children::new(d).filter(|e| e.id == TAG) { + let mut tag = Tag::default(); + for e in Children::new(tg.data) { + match e.id { + TARGETS => { + for x in Children::new(e.data) { + match x.id { + TARGET_TYPE_VALUE => tag.targets.type_value = uint(x.data), + TARGET_TYPE => tag.targets.type_name = Some(string(x.data)), + TAG_TRACK_UID => tag.targets.track_uids.push(uint(x.data)), + TAG_EDITION_UID => tag.targets.edition_uids.push(uint(x.data)), + TAG_CHAPTER_UID => tag.targets.chapter_uids.push(uint(x.data)), + TAG_ATTACHMENT_UID => tag.targets.attachment_uids.push(uint(x.data)), + _ => {} + } + } + } + SIMPLE_TAG => tag.simple.push(parse_simple_tag(e.data, 0)), + _ => {} + } + } + out.push(tag); + } +} + +fn parse_color(d: &[u8]) -> Color { + let mut c = Color::default(); + for e in Children::new(d) { + let v = || Some(uint(e.data)); + match e.id { + MATRIX_COEFFICIENTS => c.matrix_coefficients = v(), + BITS_PER_CHANNEL => c.bits_per_channel = v(), + CHROMA_SUBSAMPLING_HORZ => c.chroma_subsampling_horz = v(), + CHROMA_SUBSAMPLING_VERT => c.chroma_subsampling_vert = v(), + CB_SUBSAMPLING_HORZ => c.cb_subsampling_horz = v(), + CB_SUBSAMPLING_VERT => c.cb_subsampling_vert = v(), + CHROMA_SITING_HORZ => c.chroma_siting_horz = v(), + CHROMA_SITING_VERT => c.chroma_siting_vert = v(), + RANGE => c.range = v(), + TRANSFER_CHARACTERISTICS => c.transfer_characteristics = v(), + PRIMARIES => c.primaries = v(), + MAX_CLL => c.max_cll = v(), + MAX_FALL => c.max_fall = v(), + MASTERING_METADATA => { + let mut m = MasteringMetadata::default(); + for x in Children::new(e.data) { + let f = float(x.data); + match x.id { + PRIMARY_R_X => m.primaries[0].0 = f, + PRIMARY_R_Y => m.primaries[0].1 = f, + PRIMARY_G_X => m.primaries[1].0 = f, + PRIMARY_G_Y => m.primaries[1].1 = f, + PRIMARY_B_X => m.primaries[2].0 = f, + PRIMARY_B_Y => m.primaries[2].1 = f, + WHITE_POINT_X => m.white_point.0 = f, + WHITE_POINT_Y => m.white_point.1 = f, + LUMINANCE_MAX => m.luminance_max = f, + LUMINANCE_MIN => m.luminance_min = f, + _ => {} + } + } + c.mastering = Some(m); + } + _ => {} + } + } + c +} + +fn parse_video(d: &[u8]) -> VideoInfo { + let mut v = VideoInfo::default(); + for e in Children::new(d) { + let u = uint(e.data); + match e.id { + PIXEL_WIDTH => v.pixel_width = u as u32, + PIXEL_HEIGHT => v.pixel_height = u as u32, + DISPLAY_WIDTH => v.display_width = Some(u as u32), + DISPLAY_HEIGHT => v.display_height = Some(u as u32), + DISPLAY_UNIT => v.display_unit = u, + PIXEL_CROP_TOP => v.crop.0 = u as u32, + PIXEL_CROP_BOTTOM => v.crop.1 = u as u32, + PIXEL_CROP_LEFT => v.crop.2 = u as u32, + PIXEL_CROP_RIGHT => v.crop.3 = u as u32, + FLAG_INTERLACED => v.flag_interlaced = u, + FIELD_ORDER => v.field_order = Some(u), + STEREO_MODE => v.stereo_mode = Some(u), + ALPHA_MODE => v.alpha_mode = u, + COLOR_SPACE => v.color_space = e.data.try_into().ok(), + COLOR => v.color = Some(parse_color(e.data)), + PROJECTION => { + let mut p = Projection::default(); + for x in Children::new(e.data) { + match x.id { + PROJECTION_TYPE => p.projection_type = uint(x.data), + PROJECTION_POSE_YAW => p.yaw = float(x.data), + PROJECTION_POSE_PITCH => p.pitch = float(x.data), + PROJECTION_POSE_ROLL => p.roll = float(x.data), + _ => {} + } + } + v.projection = Some(p); + } + _ => {} + } + } + v +} + +fn parse_audio(d: &[u8]) -> AudioInfo { + let mut a = AudioInfo::default(); + for e in Children::new(d) { + match e.id { + SAMPLING_FREQUENCY => a.sampling_frequency = float(e.data), + OUTPUT_SAMPLING_FREQUENCY => a.output_sampling_frequency = Some(float(e.data)), + CHANNELS => a.channels = uint(e.data), + BIT_DEPTH => a.bit_depth = Some(uint(e.data)), + _ => {} + } + } + a +} + +fn parse_encodings(d: &[u8]) -> Vec { + let mut list: Vec<(u64, ContentEncoding)> = Vec::new(); + for ce in Children::new(d).filter(|e| e.id == CONTENT_ENCODING) { + let (mut order, mut scope, mut ty) = (0u64, 1u64, 0u64); + let mut comp: Option<(u64, Vec)> = None; + for e in Children::new(ce.data) { + match e.id { + CONTENT_ENCODING_ORDER => order = uint(e.data), + CONTENT_ENCODING_SCOPE => scope = uint(e.data), + CONTENT_ENCODING_TYPE => ty = uint(e.data), + CONTENT_COMPRESSION => { + let (mut algo, mut settings) = (0u64, Vec::new()); + for x in Children::new(e.data) { + match x.id { + CONTENT_COMP_ALGO => algo = uint(x.data), + CONTENT_COMP_SETTINGS => settings = x.data.to_vec(), + _ => {} + } + } + comp = Some((algo, settings)); + } + _ => {} + } + } + let enc = if ty == 1 { + ContentEncoding::Encryption { scope } + } else { + let (algo, settings) = comp.unwrap_or((0, Vec::new())); + if algo == 3 && settings.len() <= MAX_STRIPPED_HEADER { + ContentEncoding::HeaderStripping { bytes: settings, scope } + } else { + ContentEncoding::Compression { algo, settings, scope } + } + }; + list.push((order, enc)); + } + // highest order is applied last on muxing → first to undo; keep decode order + list.sort_by_key(|e| std::cmp::Reverse(e.0)); + list.into_iter().map(|e| e.1).collect() +} + +pub(crate) fn parse_tracks(d: &[u8], timestamp_scale: u64) -> Vec { + let g = gcd(timestamp_scale, 1_000_000_000); + let timebase = (timestamp_scale / g, 1_000_000_000 / g); + let mut out = Vec::new(); + for te in Children::new(d).filter(|e| e.id == TRACK_ENTRY) { + let mut t = Track { + number: 0, + uid: 0, + kind: TrackKind::Other(0), + enabled: true, + default: true, + forced: false, + hearing_impaired: false, + lacing: true, + default_duration_ns: None, + name: String::new(), + language: "eng".into(), + language_bcp47: None, + codec_id: String::new(), + codec_private: Vec::new(), + codec_name: String::new(), + codec: crate::matroska::Codec::Other(String::new()), + codec_delay_ns: 0, + seek_pre_roll_ns: 0, + video: None, + audio: None, + encodings: Vec::new(), + timebase, + samples: Vec::new(), + sync: Vec::new(), + }; + for e in Children::new(te.data) { + match e.id { + TRACK_NUMBER => t.number = uint(e.data), + TRACK_UID => t.uid = uint(e.data), + TRACK_TYPE => t.kind = TrackKind::from_type(uint(e.data)), + FLAG_ENABLED => t.enabled = uint(e.data) != 0, + FLAG_DEFAULT => t.default = uint(e.data) != 0, + FLAG_FORCED => t.forced = uint(e.data) != 0, + FLAG_HEARING_IMPAIRED => t.hearing_impaired = uint(e.data) != 0, + FLAG_LACING => t.lacing = uint(e.data) != 0, + DEFAULT_DURATION => t.default_duration_ns = Some(uint(e.data)).filter(|&v| v > 0), + NAME => t.name = string(e.data), + LANGUAGE => t.language = string(e.data), + LANGUAGE_BCP47 => t.language_bcp47 = Some(string(e.data)), + CODEC_ID => t.codec_id = string(e.data), + CODEC_PRIVATE => t.codec_private = e.data.to_vec(), + CODEC_NAME => t.codec_name = string(e.data), + CODEC_DELAY => t.codec_delay_ns = uint(e.data), + SEEK_PRE_ROLL => t.seek_pre_roll_ns = uint(e.data), + VIDEO => t.video = Some(parse_video(e.data)), + AUDIO => t.audio = Some(parse_audio(e.data)), + CONTENT_ENCODINGS => t.encodings = parse_encodings(e.data), + _ => {} + } + } + if t.number == 0 { + continue; + } + if t.kind == TrackKind::Audio && t.audio.is_none() { + t.audio = Some(AudioInfo::default()); + } + // CodecPrivate may itself be header-stripped (scope bit 2 = private data) + for enc in &t.encodings { + if let ContentEncoding::HeaderStripping { bytes, scope } = enc + && scope & 2 != 0 + { + let mut p = bytes.clone(); + p.extend_from_slice(&t.codec_private); + t.codec_private = p; + } + } + t.codec = map_codec(&t.codec_id, &t.codec_private, t.audio.as_ref()); + out.push(t); + } + out +} + +#[cfg(test)] +mod metadata_depth_tests { + use super::*; + use crate::matroska::mux::{el, el_uint}; + + fn header_stripping(bytes: &[u8]) -> Vec { + let mut comp = Vec::new(); + el_uint(&mut comp, CONTENT_COMP_ALGO, 3); + el(&mut comp, CONTENT_COMP_SETTINGS, bytes); + let mut enc = Vec::new(); + el(&mut enc, CONTENT_COMPRESSION, &comp); + let mut encs = Vec::new(); + el(&mut encs, CONTENT_ENCODING, &enc); + parse_encodings(&encs) + } + + #[test] + fn a_long_stripped_header_is_not_put_in_front_of_frames() { + let kept = header_stripping(&[7; MAX_STRIPPED_HEADER]); + assert!(matches!(&kept[..], [ContentEncoding::HeaderStripping { bytes, .. }] if bytes.len() == MAX_STRIPPED_HEADER)); + let refused = header_stripping(&[7; MAX_STRIPPED_HEADER + 1]); + assert!(matches!(&refused[..], [ContentEncoding::Compression { algo: 3, .. }]), "{refused:?}"); + } + + #[test] + fn deeply_nested_chapters_stop_at_depth_limit() { + // Unknown-size elements make every pair the sole child of the previous ChapterAtom. + let data = [0xB6, 0xFF].repeat(100_000); + let chapter = parse_chapter(&data, 0); + let mut current = &chapter; + for _ in 0..MAX_META_DEPTH { + assert_eq!(current.children.len(), 1); + current = ¤t.children[0]; + } + assert!(current.children.is_empty()); + } + + #[test] + fn deeply_nested_simple_tags_stop_at_depth_limit() { + let data = [0x67, 0xC8, 0xFF].repeat(100_000); + let tag = parse_simple_tag(&data, 0); + let mut current = &tag; + for _ in 0..MAX_META_DEPTH { + assert_eq!(current.children.len(), 1); + current = ¤t.children[0]; + } + assert!(current.children.is_empty()); + } +} diff --git a/crates/media/src/matroska/mod.rs b/crates/media/src/matroska/mod.rs new file mode 100644 index 0000000000..515e99e37d --- /dev/null +++ b/crates/media/src/matroska/mod.rs @@ -0,0 +1,38 @@ +//! Clean-room Matroska (MKV) and WebM demuxer, written from RFC 8794 (EBML), RFC 9559 (Matroska) +//! and the WebM container guidelines. +//! +//! - [`open`] / [`open_with`] parse the EBML header and the first Segment (Info, Tracks, SeekHead, +//! Cues, Chapters, Tags, Attachments) and, by default, scan every Cluster's block headers to build +//! per-track [`Sample`] tables — the same shape as [`isobmff`](crate::isobmff), so callers can treat both +//! containers alike. Frame data is read on demand with [`MkvFile::read_sample`]. +//! - [`Demuxer`] iterates [`Packet`]s in file order (from any [`ByteSource`], `Read + Seek`, or a +//! byte slice) and seeks to the keyframe preceding a time, via the index, Cues, or a cluster scan. +//! +//! No dependencies beyond `std`, no `unsafe`, builds for `wasm32-unknown-unknown`. + +mod codec; +mod demux; +pub mod ebml; +mod error; +mod ids; +mod meta; +mod mux; +mod source; +#[cfg(test)] +mod synthetic_tests; +mod track; + +pub use codec::Codec; +pub use demux::{Demuxer, Keyframe, MkvFile, OpenOptions, Packet, SeekPoint, open, open_with}; +pub use error::{Error, Result}; +pub use meta::{ + Attachment, Chapter, ChapterDisplay, ClusterInfo, CuePoint, CuePosition, Edition, SeekEntry, SegmentInfo, SimpleTag, Tag, TagTargets, +}; +pub use mux::{LacingMode, MkvWriter, MuxOptions, TrackSpec}; +pub use source::{ByteSource, ReadSeekSource}; +pub use track::{AudioInfo, Color, ContentEncoding, MasteringMetadata, Projection, Sample, Track, TrackKind, VideoInfo}; + +/// Element IDs used by the demuxer (marker bits included), for callers inspecting raw elements. +pub mod element_ids { + pub use crate::matroska::ids::*; +} diff --git a/crates/media/src/matroska/mux.rs b/crates/media/src/matroska/mux.rs new file mode 100644 index 0000000000..8f90ed4e79 --- /dev/null +++ b/crates/media/src/matroska/mux.rs @@ -0,0 +1,594 @@ +//! Minimal Matroska / WebM muxer: SimpleBlocks (optionally laced), BlockGroups for explicit +//! durations, Cues, SeekHead, Info with Duration. Output must be `Write + Seek` (sizes and the +//! SeekHead are back-patched on [`MkvWriter::finish`]). + +use std::io::{Seek, SeekFrom, Write}; + +use crate::matroska::ebml::{write_id, write_size, write_unknown_size}; +use crate::matroska::error::{Error, Result}; +use crate::matroska::ids::*; +use crate::matroska::track::TrackKind; + +/// Lacing used for audio tracks. Only frames of a track with a DefaultDuration lace, and a lace +/// ends where the timestamps stop advancing by that duration. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LacingMode { + None, + Xiph, + Ebml, + /// Fixed-size lacing when consecutive frames have equal sizes, otherwise EBML lacing. + FixedOrEbml, +} + +/// Track description for [`MkvWriter`]. +#[derive(Clone, Debug)] +pub struct TrackSpec { + pub kind: TrackKind, + pub codec_id: String, + pub codec_private: Vec, + pub default_duration_ns: Option, + pub language: Option, + pub name: Option, + /// Pixel width/height for video tracks. + pub video_size: Option<(u32, u32)>, + /// (sampling frequency, channels, bit depth) for audio tracks. + pub audio: Option<(f64, u64, Option)>, + pub codec_delay_ns: u64, + pub seek_pre_roll_ns: u64, +} + +impl TrackSpec { + pub fn new(kind: TrackKind, codec_id: impl Into) -> Self { + Self { + kind, + codec_id: codec_id.into(), + codec_private: Vec::new(), + default_duration_ns: None, + language: None, + name: None, + video_size: None, + audio: None, + codec_delay_ns: 0, + seek_pre_roll_ns: 0, + } + } +} + +/// Muxer options. +#[derive(Clone, Debug)] +pub struct MuxOptions { + /// `webm` or `matroska`. + pub doc_type: String, + /// Nanoseconds per tick (default 1 000 000). + pub timestamp_scale: u64, + /// Start a new cluster at the next video keyframe (or any frame without video) after this long. + pub cluster_duration_ns: u64, + pub lacing: LacingMode, + /// Maximum frames per laced block. + pub max_lace_frames: usize, + pub title: Option, + pub writing_app: String, +} + +impl Default for MuxOptions { + fn default() -> Self { + Self { + doc_type: "matroska".into(), + timestamp_scale: 1_000_000, + cluster_duration_ns: 1_000_000_000, + lacing: LacingMode::None, + max_lace_frames: 8, + title: None, + writing_app: "craft-media".into(), + } + } +} + +pub(crate) fn el(out: &mut Vec, id: u32, data: &[u8]) { + write_id(out, id); + write_size(out, data.len() as u64, 1); + out.extend_from_slice(data); +} + +pub(crate) fn el_uint(out: &mut Vec, id: u32, v: u64) { + let n = (8 - v.leading_zeros() as usize / 8).max(1); + el(out, id, &v.to_be_bytes()[8 - n..]); +} + +pub(crate) fn el_float(out: &mut Vec, id: u32, v: f64) { + el(out, id, &v.to_be_bytes()); +} + +pub(crate) fn el_str(out: &mut Vec, id: u32, s: &str) { + el(out, id, s.as_bytes()); +} + +fn void(out: &mut Vec, total: usize) { + debug_assert!(total >= 2); + let sl = if total - 2 <= 126 { 1 } else { 8 }; + write_id(out, VOID); + write_size(out, (total - 1 - sl) as u64, sl); + out.resize(out.len() + total - 1 - sl, 0); +} + +#[derive(Clone, Debug)] +struct Pending { + track: usize, + ts: i64, + frames: Vec>, +} + +const SEEK_HEAD_SPACE: usize = 128; + +/// Streaming Matroska/WebM writer. +pub struct MkvWriter { + w: W, + opts: MuxOptions, + tracks: Vec, + segment_size_pos: u64, + segment_data_start: u64, + seek_head_pos: u64, + duration_pos: u64, + info_pos: u64, + tracks_pos: u64, + cluster: Vec, + cluster_ts: Option, + cluster_start_ns: i64, + pending: Option, + cues: Vec<(u64, u64, u64)>, // (time ticks, track number, cluster position) + /// The cluster number in which each track last had a cue. Starting a cluster bumps + /// `cluster_number` instead of clearing an entry for every declared track. + track_cued_in: Vec, + cluster_number: u64, + end_ns: i64, + has_video: bool, +} + +impl MkvWriter { + pub fn new(mut w: W, tracks: Vec, opts: MuxOptions) -> Result { + if tracks.is_empty() || opts.timestamp_scale == 0 { + return Err(Error::Invalid("muxer needs at least one track and a non-zero timestamp scale".into())); + } + let mut out = Vec::new(); + let mut h = Vec::new(); + el_uint(&mut h, EBML_VERSION, 1); + el_uint(&mut h, EBML_READ_VERSION, 1); + el_uint(&mut h, EBML_MAX_ID_LENGTH, 4); + el_uint(&mut h, EBML_MAX_SIZE_LENGTH, 8); + el_str(&mut h, DOC_TYPE, &opts.doc_type); + el_uint(&mut h, DOC_TYPE_VERSION, 4); + el_uint(&mut h, DOC_TYPE_READ_VERSION, 2); + el(&mut out, EBML, &h); + write_id(&mut out, SEGMENT); + let base = w.stream_position()?; + let segment_size_pos = base + out.len() as u64; + write_unknown_size(&mut out, 8); + let segment_data_start = base + out.len() as u64; + let seek_head_pos = segment_data_start; + void(&mut out, SEEK_HEAD_SPACE); + // Info + let info_pos = base + out.len() as u64; + let mut info = Vec::new(); + el_uint(&mut info, TIMESTAMP_SCALE, opts.timestamp_scale); + el_str(&mut info, MUXING_APP, "craft-media"); + el_str(&mut info, WRITING_APP, &opts.writing_app); + if let Some(t) = &opts.title { + el_str(&mut info, TITLE, t); + } + let dur_off_in_info = info.len() + 2 + 1; // ID (2) + size (1) + el_float(&mut info, DURATION, 0.0); + write_id(&mut out, INFO); + write_size(&mut out, info.len() as u64, 1); + let duration_pos = base + out.len() as u64 + dur_off_in_info as u64; + out.extend_from_slice(&info); + // Tracks + let tracks_pos = base + out.len() as u64; + let mut tr = Vec::new(); + for (i, t) in tracks.iter().enumerate() { + let mut e = Vec::new(); + el_uint(&mut e, TRACK_NUMBER, i as u64 + 1); + el_uint(&mut e, TRACK_UID, 0x1000 + i as u64 + 1); + let ty = match t.kind { + TrackKind::Video => 1, + TrackKind::Audio => 2, + TrackKind::Subtitle => 0x11, + TrackKind::Complex => 3, + TrackKind::Logo => 0x10, + TrackKind::Buttons => 0x12, + TrackKind::Control => 0x20, + TrackKind::Metadata => 0x21, + TrackKind::Other(n) => n as u64, + }; + el_uint(&mut e, TRACK_TYPE, ty); + el_uint(&mut e, FLAG_LACING, (t.kind == TrackKind::Audio && opts.lacing != LacingMode::None) as u64); + if let Some(l) = &t.language { + el_str(&mut e, LANGUAGE, l); + } + if let Some(n) = &t.name { + el_str(&mut e, NAME, n); + } + el_str(&mut e, CODEC_ID, &t.codec_id); + if !t.codec_private.is_empty() { + el(&mut e, CODEC_PRIVATE, &t.codec_private); + } + if let Some(d) = t.default_duration_ns { + el_uint(&mut e, DEFAULT_DURATION, d); + } + if t.codec_delay_ns > 0 { + el_uint(&mut e, CODEC_DELAY, t.codec_delay_ns); + } + if t.seek_pre_roll_ns > 0 { + el_uint(&mut e, SEEK_PRE_ROLL, t.seek_pre_roll_ns); + } + if let Some((pw, ph)) = t.video_size { + let mut v = Vec::new(); + el_uint(&mut v, PIXEL_WIDTH, pw as u64); + el_uint(&mut v, PIXEL_HEIGHT, ph as u64); + el(&mut e, VIDEO, &v); + } + if let Some((rate, ch, bits)) = t.audio { + let mut a = Vec::new(); + el_float(&mut a, SAMPLING_FREQUENCY, rate); + el_uint(&mut a, CHANNELS, ch); + if let Some(b) = bits { + el_uint(&mut a, BIT_DEPTH, b); + } + el(&mut e, AUDIO, &a); + } + el(&mut tr, TRACK_ENTRY, &e); + } + el(&mut out, TRACKS, &tr); + w.write_all(&out)?; + let has_video = tracks.iter().any(|t| t.kind == TrackKind::Video); + let n = tracks.len(); + Ok(Self { + w, + opts, + tracks, + segment_size_pos, + segment_data_start, + seek_head_pos, + duration_pos, + info_pos, + tracks_pos, + cluster: Vec::new(), + cluster_ts: None, + cluster_start_ns: 0, + pending: None, + cues: Vec::new(), + track_cued_in: vec![u64::MAX; n], + cluster_number: 0, + end_ns: 0, + has_video, + }) + } + + /// Add one frame. `pts_ns` is the presentation time (codec delay is added back for storage); + /// frames must be supplied in the desired file order. `duration_ns` forces a BlockGroup with a + /// BlockDuration when it differs from the track's DefaultDuration. + pub fn write_frame(&mut self, track: usize, pts_ns: i64, keyframe: bool, data: &[u8], duration_ns: Option) -> Result<()> { + let spec = self.tracks.get(track).ok_or(Error::NoSuchTrack(track))?; + // the Matroska ProRes mapping stores frames without the 8-byte `size`+`icpf` header + let data = if spec.codec_id == "V_PRORES" && data.get(4..8) == Some(b"icpf") { &data[8..] } else { data }; + let scale = self.opts.timestamp_scale as i64; + let stored_ns = pts_ns + spec.codec_delay_ns as i64; + if stored_ns < 0 { + return Err(Error::Invalid("negative timestamp".into())); + } + let ts = (stored_ns + scale / 2) / scale; + let dur_end = pts_ns + duration_ns.or(spec.default_duration_ns).unwrap_or(0) as i64; + self.end_ns = self.end_ns.max(dur_end).max(pts_ns); + let is_video = spec.kind == TrackKind::Video; + let lacing = spec.kind == TrackKind::Audio && self.opts.lacing != LacingMode::None; + let explicit_dur = duration_ns.filter(|&d| Some(d) != spec.default_duration_ns); + let lace_duration = spec.default_duration_ns.filter(|_| lacing && explicit_dur.is_none()); + // new cluster? + let start_new = match self.cluster_ts { + None => true, + Some(cts) => { + let long = stored_ns - self.cluster_start_ns >= self.opts.cluster_duration_ns as i64; + (long && (!self.has_video || (is_video && keyframe))) || ts - cts > 30_000 || ts < cts + } + }; + if start_new { + self.flush_cluster()?; + self.cluster_ts = Some(ts); + self.cluster_start_ns = stored_ns; + el_uint(&mut self.cluster, TIMESTAMP, ts as u64); + } + let cts = self.cluster_ts.unwrap_or(0); + // cue: video keyframes, or the first frame of each track per cluster when there is no video + if (is_video && keyframe) || (!self.has_video && self.track_cued_in[track] != self.cluster_number) { + self.track_cued_in[track] = self.cluster_number; + let pos = self.w.stream_position()? - self.segment_data_start; + if self.cues.last().is_none_or(|c| c.2 != pos || c.1 != track as u64 + 1) { + self.cues.push((ts as u64, track as u64 + 1, pos)); + } + } + // A laced frame has no timestamp of its own: readers space the frames of a block by + // DefaultDuration. So only frames with that duration lace, and a frame joins the pending + // lace only when the tick it would get there is the tick it has. + if let Some(dd) = lace_duration { + let max = self.opts.max_lace_frames; + let joins = self.pending.as_ref().is_some_and(|p| { + let n = p.frames.len(); + let implied = ((cts + p.ts) as i128 * scale as i128 + n as i128 * dd as i128 + scale as i128 / 2) / scale as i128; + p.track == track && n < max && implied == ts as i128 + }); + if !joins { + self.flush_pending(); + } + match &mut self.pending { + Some(p) => p.frames.push(data.to_vec()), + None => self.pending = Some(Pending { track, ts: ts - cts, frames: vec![data.to_vec()] }), + } + return Ok(()); + } + self.flush_pending(); + let mut block = Vec::new(); + write_size(&mut block, track as u64 + 1, 1); + block.extend_from_slice(&((ts - cts) as i16).to_be_bytes()); + if let Some(d) = explicit_dur { + block.push(0); + block.extend_from_slice(data); + let mut g = Vec::new(); + el(&mut g, BLOCK, &block); + el_uint(&mut g, BLOCK_DURATION, (d as i64 / scale) as u64); + if !keyframe { + el(&mut g, REFERENCE_BLOCK, &[0xFF]); + } + el(&mut self.cluster, BLOCK_GROUP, &g); + } else { + block.push(if keyframe { 0x80 } else { 0 }); + block.extend_from_slice(data); + el(&mut self.cluster, SIMPLE_BLOCK, &block); + } + Ok(()) + } + + fn flush_pending(&mut self) { + let Some(p) = self.pending.take() else { return }; + let mut block = Vec::new(); + write_size(&mut block, p.track as u64 + 1, 1); + block.extend_from_slice(&(p.ts as i16).to_be_bytes()); + let n = p.frames.len(); + let mode = if n == 1 { LacingMode::None } else { self.opts.lacing }; + let fixed = p.frames.iter().all(|f| f.len() == p.frames[0].len()); + match mode { + LacingMode::None => block.push(0x80), + LacingMode::Xiph => { + block.push(0x80 | 0x02); + block.push((n - 1) as u8); + for f in &p.frames[..n - 1] { + let mut s = f.len(); + while s >= 255 { + block.push(255); + s -= 255; + } + block.push(s as u8); + } + } + LacingMode::FixedOrEbml if fixed => { + block.push(0x80 | 0x04); + block.push((n - 1) as u8); + } + LacingMode::Ebml | LacingMode::FixedOrEbml => { + block.push(0x80 | 0x06); + block.push((n - 1) as u8); + write_size(&mut block, p.frames[0].len() as u64, 1); + for i in 1..n - 1 { + let d = p.frames[i].len() as i64 - p.frames[i - 1].len() as i64; + // signed VINT: smallest length whose range holds d + let mut len = 1; + while len < 8 && d.unsigned_abs() >= (1u64 << (7 * len - 1)) - 1 { + len += 1; + } + let v = (d + (1i64 << (7 * len - 1)) - 1) as u64 | (1u64 << (7 * len)); + block.extend_from_slice(&v.to_be_bytes()[8 - len..]); + } + } + } + for f in &p.frames { + block.extend_from_slice(f); + } + el(&mut self.cluster, SIMPLE_BLOCK, &block); + } + + fn flush_cluster(&mut self) -> Result<()> { + self.flush_pending(); + if self.cluster_ts.is_some() { + let mut out = Vec::new(); + el(&mut out, CLUSTER, &self.cluster); + self.w.write_all(&out)?; + } + self.cluster.clear(); + self.cluster_ts = None; + self.cluster_number = self.cluster_number.wrapping_add(1); + Ok(()) + } + + /// Write Cues, back-patch SeekHead / Segment size / Duration, and return the writer. + pub fn finish(mut self) -> Result { + self.flush_cluster()?; + let cues_pos = self.w.stream_position()?; + let mut cues = Vec::new(); + for &(time, track, pos) in &self.cues { + let mut ctp = Vec::new(); + el_uint(&mut ctp, CUE_TRACK, track); + el_uint(&mut ctp, CUE_CLUSTER_POSITION, pos); + let mut cp = Vec::new(); + el_uint(&mut cp, CUE_TIME, time); + el(&mut cp, CUE_TRACK_POSITIONS, &ctp); + el(&mut cues, CUE_POINT, &cp); + } + let has_cues = !cues.is_empty(); + if has_cues { + let mut out = Vec::new(); + el(&mut out, CUES, &cues); + self.w.write_all(&out)?; + } + let end = self.w.stream_position()?; + // SeekHead + let mut sh = Vec::new(); + let mut entries = vec![(INFO, self.info_pos), (TRACKS, self.tracks_pos)]; + if has_cues { + entries.push((CUES, cues_pos)); + } + for (id, pos) in entries { + let mut s = Vec::new(); + let mut idb = Vec::new(); + write_id(&mut idb, id); + el(&mut s, SEEK_ID, &idb); + el_uint(&mut s, SEEK_POSITION, pos - self.segment_data_start); + el(&mut sh, SEEK, &s); + } + let mut out = Vec::new(); + el(&mut out, SEEK_HEAD, &sh); + if out.len() + 2 > SEEK_HEAD_SPACE { + return Err(Error::Invalid("SeekHead does not fit its reserved space".into())); + } + let rest = SEEK_HEAD_SPACE - out.len(); + void(&mut out, rest); + self.w.seek(SeekFrom::Start(self.seek_head_pos))?; + self.w.write_all(&out)?; + // Duration + let dur = self.end_ns as f64 / self.opts.timestamp_scale as f64; + self.w.seek(SeekFrom::Start(self.duration_pos))?; + self.w.write_all(&dur.to_be_bytes())?; + // Segment size + let mut sz = Vec::new(); + write_size(&mut sz, end - self.segment_data_start, 8); + self.w.seek(SeekFrom::Start(self.segment_size_pos))?; + self.w.write_all(&sz)?; + self.w.seek(SeekFrom::Start(end))?; + self.w.flush()?; + Ok(self.w) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::matroska::{Demuxer, TrackKind}; + use std::io::Cursor; + + fn roundtrip(lacing: LacingMode) { + let mut v = TrackSpec::new(TrackKind::Video, "V_MJPEG"); + v.video_size = Some((16, 16)); + v.default_duration_ns = Some(40_000_000); + let mut a = TrackSpec::new(TrackKind::Audio, "A_PCM/INT/LIT"); + a.audio = Some((48000.0, 1, Some(16))); + a.default_duration_ns = Some(10_000_000); + let mut s = TrackSpec::new(TrackKind::Subtitle, "S_TEXT/UTF8"); + s.language = Some("fre".into()); + let opts = MuxOptions { lacing, ..Default::default() }; + let mut m = MkvWriter::new(Cursor::new(Vec::new()), vec![v, a, s], opts).unwrap(); + let mut expect = Vec::new(); + for i in 0..50i64 { + let vf = vec![i as u8; 100 + i as usize]; + m.write_frame(0, i * 40_000_000, i % 10 == 0, &vf, None).unwrap(); + expect.push((0usize, i * 40, vf, i % 10 == 0)); + for k in 0..4 { + let n = if lacing == LacingMode::FixedOrEbml { 960 } else { 900 + (i as usize * 7 + k * 13) % 300 }; + let af = vec![(i * 4 + k as i64) as u8; n]; + let t = i * 40 + k as i64 * 10; + m.write_frame(1, t * 1_000_000, true, &af, None).unwrap(); + expect.push((1, t, af, true)); + } + if i % 20 == 5 { + m.write_frame(2, i * 40_000_000, true, b"hello", Some(500_000_000)).unwrap(); + expect.push((2, i * 40, b"hello".to_vec(), true)); + } + } + let bytes = m.finish().unwrap().into_inner(); + let mut d = Demuxer::from_slice(&bytes).unwrap(); + assert!(d.file().warnings.is_empty(), "{:?}", d.file().warnings); + assert_eq!(d.tracks()[2].language, "fre"); + assert!(!d.file().cues.is_empty()); + assert_eq!(d.duration_ns(), Some(2_300_000_000)); + let got: Vec<_> = d.by_ref().map(|p| p.unwrap()).collect(); + assert_eq!(got.len(), expect.len()); + for (g, e) in got.iter().zip(&expect) { + assert_eq!((g.track, g.pts, &g.data, g.keyframe), (e.0, e.1, &e.2, e.3)); + } + let sub = got.iter().find(|p| p.track == 2).unwrap(); + assert_eq!(sub.duration, 500); + // the index agrees with the packet stream + let f = d.file(); + for (ti, t) in f.tracks.iter().enumerate() { + let pk: Vec<_> = got.iter().filter(|p| p.track == ti).collect(); + assert_eq!(t.samples.len(), pk.len()); + for (i, p) in pk.iter().enumerate() { + assert_eq!(f.read_sample(&bytes[..], ti, i).unwrap(), p.data); + assert_eq!(t.samples[i].pts, p.pts); + } + } + // seeking + let sp = d.seek(0, 1_230_000_000).unwrap(); + assert_eq!(sp.pts, 1200); + let p = d.next_packet().unwrap().unwrap(); + assert_eq!((p.track, p.pts, p.keyframe), (0, 1200, true)); + let sp = d.seek(1, 1_235_000_000).unwrap(); + assert_eq!(sp.pts, 1230); + let p = d.next_packet().unwrap().unwrap(); + assert_eq!((p.track, p.pts), (1, 1230)); + } + + #[test] + fn roundtrip_unlaced() { + roundtrip(LacingMode::None); + } + #[test] + fn roundtrip_xiph() { + roundtrip(LacingMode::Xiph); + } + #[test] + fn roundtrip_ebml() { + roundtrip(LacingMode::Ebml); + } + #[test] + fn roundtrip_fixed() { + roundtrip(LacingMode::FixedOrEbml); + } + + /// Laced frames get their timestamps from the block's and DefaultDuration, so a gap in the + /// input must end the lace, and a track without DefaultDuration must not lace at all. + #[test] + fn lacing_keeps_timestamp_gaps() { + let mut a = TrackSpec::new(TrackKind::Audio, "A_PCM/INT/LIT"); + a.audio = Some((48000.0, 1, Some(16))); + a.default_duration_ns = Some(10_000_000); + let mut b = TrackSpec::new(TrackKind::Audio, "A_PCM/INT/LIT"); + b.audio = Some((48000.0, 1, Some(16))); + let opts = MuxOptions { lacing: LacingMode::Xiph, ..Default::default() }; + let mut m = MkvWriter::new(Cursor::new(Vec::new()), vec![a, b], opts).unwrap(); + for ms in [0i64, 100, 110, 120, 200] { + m.write_frame(0, ms * 1_000_000, true, &[ms as u8; 64], None).unwrap(); + } + for ms in [300i64, 310] { + m.write_frame(1, ms * 1_000_000, true, &[ms as u8; 64], None).unwrap(); + } + let bytes = m.finish().unwrap().into_inner(); + let got: Vec<_> = Demuxer::from_slice(&bytes).unwrap().map(|p| p.unwrap()).map(|p| (p.track, p.pts, p.lace)).collect(); + assert_eq!(got, [(0, 0, 0), (0, 100, 0), (0, 110, 1), (0, 120, 2), (0, 200, 0), (1, 300, 0), (1, 310, 0)]); + } + + #[test] + fn audio_only_files_cue_each_track_once_per_cluster() { + let mut a = TrackSpec::new(TrackKind::Audio, "A_PCM/INT/LIT"); + a.audio = Some((48000.0, 1, Some(16))); + let opts = MuxOptions { cluster_duration_ns: 1, lacing: LacingMode::None, ..Default::default() }; + let mut m = MkvWriter::new(Cursor::new(Vec::new()), vec![a.clone(), a], opts).unwrap(); + for i in 0..4i64 { + m.write_frame(0, i * 10, true, &[1; 4], None).unwrap(); + m.write_frame(1, i * 10, true, &[2; 4], None).unwrap(); + m.write_frame(0, i * 10 + 1, true, &[3; 4], None).unwrap(); + } + // Clusters hold [t0, t1] then [t0] at each step: one cue per track per cluster. + let mut seen: Vec<(u64, u64)> = m.cues.iter().map(|c| (c.1, c.2)).collect(); + assert_eq!(seen.len(), 12, "{:?}", m.cues); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), 12, "{:?}", m.cues); + } +} diff --git a/crates/media/src/matroska/source.rs b/crates/media/src/matroska/source.rs new file mode 100644 index 0000000000..267c427101 --- /dev/null +++ b/crates/media/src/matroska/source.rs @@ -0,0 +1,174 @@ +//! Random-access byte sources for the demuxer. + +use std::cell::RefCell; +use std::io::{self, Read, Seek, SeekFrom}; +use std::sync::Arc; + +/// Random-access, read-only byte source (file, in-memory buffer, web Blob…). +/// +/// Same shape as `craft_media::isobmff::ByteSource`, so one adapter type can implement both. They +/// are separate traits so that a type can implement both without conflicting impls. +pub trait ByteSource { + /// Total length in bytes. + fn len(&self) -> u64; + /// Fill `buf` entirely with bytes starting at `offset`; fail with `UnexpectedEof` if past the end. + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()>; + /// True if the source holds no bytes. + fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +fn eof() -> io::Error { + io::Error::new(io::ErrorKind::UnexpectedEof, "read past end of byte source") +} + +impl ByteSource for [u8] { + fn len(&self) -> u64 { + <[u8]>::len(self) as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + let start = usize::try_from(offset).map_err(|_| eof())?; + let end = start.checked_add(buf.len()).ok_or_else(eof)?; + let src = self.get(start..end).ok_or_else(eof)?; + buf.copy_from_slice(src); + Ok(()) + } +} + +impl ByteSource for Vec { + fn len(&self) -> u64 { + self.as_slice().len() as u64 + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + self.as_slice().read_at(offset, buf) + } +} + +impl ByteSource for &T { + fn len(&self) -> u64 { + (**self).len() + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + (**self).read_at(offset, buf) + } +} + +impl ByteSource for Arc { + fn len(&self) -> u64 { + (**self).len() + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + (**self).read_at(offset, buf) + } +} + +impl ByteSource for Box { + fn len(&self) -> u64 { + (**self).len() + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + (**self).read_at(offset, buf) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl ByteSource for std::fs::File { + fn len(&self) -> u64 { + self.metadata().map(|m| m.len()).unwrap_or(0) + } + #[cfg(unix)] + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + std::os::unix::fs::FileExt::read_exact_at(self, buf, offset) + } + #[cfg(windows)] + fn read_at(&self, mut offset: u64, mut buf: &mut [u8]) -> io::Result<()> { + use std::os::windows::fs::FileExt; + while !buf.is_empty() { + let n = self.seek_read(buf, offset)?; + if n == 0 { + return Err(eof()); + } + offset += n as u64; + buf = &mut buf[n..]; + } + Ok(()) + } + #[cfg(not(any(unix, windows)))] + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + let mut f = self; + f.seek(SeekFrom::Start(offset))?; + f.read_exact(buf) + } +} + +/// Adapts any `Read + Seek` (e.g. `BufReader`, `Cursor>`) into a [`ByteSource`]. +/// +/// The length is taken once at construction; the stream position is tracked so sequential reads +/// do not issue redundant seeks. +pub struct ReadSeekSource { + inner: RefCell<(R, u64)>, + len: u64, +} + +impl ReadSeekSource { + /// Wrap a reader; seeks to the end once to learn the length. + pub fn new(mut r: R) -> io::Result { + let len = r.seek(SeekFrom::End(0))?; + Ok(Self { inner: RefCell::new((r, len)), len }) + } + /// Unwrap the reader. + pub fn into_inner(self) -> R { + self.inner.into_inner().0 + } +} + +impl ByteSource for ReadSeekSource { + fn len(&self) -> u64 { + self.len + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + if offset.checked_add(buf.len() as u64).is_none_or(|e| e > self.len) { + return Err(eof()); + } + let mut g = self.inner.borrow_mut(); + let (r, pos) = &mut *g; + if *pos != offset { + r.seek(SeekFrom::Start(offset))?; + *pos = offset; + } + let res = r.read_exact(buf); + match res { + Ok(()) => { + *pos = offset + buf.len() as u64; + Ok(()) + } + Err(e) => { + *pos = u64::MAX; // unknown; force a seek next time + Err(e) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slice_and_reader_sources() { + let v = vec![1u8, 2, 3, 4]; + let mut b = [0u8; 2]; + v.read_at(1, &mut b).unwrap(); + assert_eq!(b, [2, 3]); + assert!(v.read_at(3, &mut b).is_err()); + assert!(v.read_at(u64::MAX, &mut b).is_err()); + let r = ReadSeekSource::new(io::Cursor::new(v.clone())).unwrap(); + assert_eq!(r.len(), 4); + r.read_at(2, &mut b).unwrap(); + assert_eq!(b, [3, 4]); + r.read_at(0, &mut b).unwrap(); + assert_eq!(b, [1, 2]); + assert!(r.read_at(3, &mut b).is_err()); + } +} diff --git a/crates/media/src/matroska/synthetic_tests.rs b/crates/media/src/matroska/synthetic_tests.rs new file mode 100644 index 0000000000..65fa4dde17 --- /dev/null +++ b/crates/media/src/matroska/synthetic_tests.rs @@ -0,0 +1,351 @@ +//! Hand-built files exercising features FFmpeg does not write: unknown-size Segment/Clusters, +//! header stripping, BlockGroups, Colour + mastering metadata, Chapters, Tags, Attachments, CRC-32. + +use crate::matroska::codec::Codec; +use crate::matroska::ebml::{self, write_id, write_unknown_size}; +use crate::matroska::ids::*; +use crate::matroska::mux::{el, el_float, el_str, el_uint}; +use crate::matroska::track::ContentEncoding; +use crate::matroska::{Demuxer, OpenOptions, Packet, open_with}; + +fn block(track: u8, rel: i16, flags: u8, data: &[u8]) -> Vec { + let mut b = vec![0x80 | track]; + b.extend_from_slice(&rel.to_be_bytes()); + b.push(flags); + b.extend_from_slice(data); + b +} + +fn synthetic() -> Vec { + let mut f = Vec::new(); + let mut h = Vec::new(); + el_str(&mut h, DOC_TYPE, "matroska"); + el_uint(&mut h, DOC_TYPE_VERSION, 4); + el(&mut f, EBML, &h); + write_id(&mut f, SEGMENT); + write_unknown_size(&mut f, 8); + // Info with a correct CRC-32 and a Void + let mut info = Vec::new(); + el_uint(&mut info, TIMESTAMP_SCALE, 1_000_000); + el_str(&mut info, TITLE, "Synthetic"); + el(&mut info, VOID, &[0; 3]); + let mut crc_info = Vec::new(); + el(&mut crc_info, CRC32, &ebml::crc32(&info).to_le_bytes()); + crc_info.extend_from_slice(&info); + el(&mut f, INFO, &crc_info); + // Tracks + let mut v = Vec::new(); + el_uint(&mut v, TRACK_NUMBER, 1); + el_uint(&mut v, TRACK_UID, 11); + el_uint(&mut v, TRACK_TYPE, 1); + el_str(&mut v, CODEC_ID, "V_MPEG4/ISO/AVC"); + el(&mut v, CODEC_PRIVATE, &[1, 0x64, 0, 0x1F]); + el_uint(&mut v, DEFAULT_DURATION, 40_000_000); + let mut mm = Vec::new(); + for (id, val) in + [(PRIMARY_R_X, 0.708), (PRIMARY_R_Y, 0.292), (PRIMARY_G_X, 0.17), (PRIMARY_G_Y, 0.797), (PRIMARY_B_X, 0.131), (PRIMARY_B_Y, 0.046)] + { + el_float(&mut mm, id, val); + } + el_float(&mut mm, WHITE_POINT_X, 0.3127); + el_float(&mut mm, WHITE_POINT_Y, 0.329); + el_float(&mut mm, LUMINANCE_MAX, 1000.0); + el_float(&mut mm, LUMINANCE_MIN, 0.0001); + let mut col = Vec::new(); + el_uint(&mut col, MATRIX_COEFFICIENTS, 9); + el_uint(&mut col, RANGE, 2); + el_uint(&mut col, TRANSFER_CHARACTERISTICS, 16); + el_uint(&mut col, PRIMARIES, 9); + el_uint(&mut col, MAX_CLL, 1000); + el_uint(&mut col, MAX_FALL, 400); + el(&mut col, MASTERING_METADATA, &mm); + let mut vid = Vec::new(); + el_uint(&mut vid, PIXEL_WIDTH, 1440); + el_uint(&mut vid, PIXEL_HEIGHT, 1080); + el_uint(&mut vid, DISPLAY_WIDTH, 1920); + el_uint(&mut vid, DISPLAY_HEIGHT, 1080); + el(&mut vid, COLOR, &col); + // rectangular, a quarter turn clockwise (portrait phone video) + let mut proj = Vec::new(); + el_uint(&mut proj, PROJECTION_TYPE, 0); + el_float(&mut proj, PROJECTION_POSE_ROLL, -90.0); + el(&mut vid, PROJECTION, &proj); + el(&mut v, VIDEO, &vid); + // header stripping: every frame starts with 00 00 00 01 + let mut comp = Vec::new(); + el_uint(&mut comp, CONTENT_COMP_ALGO, 3); + el(&mut comp, CONTENT_COMP_SETTINGS, &[0, 0, 0, 1]); + let mut enc = Vec::new(); + el(&mut enc, CONTENT_COMPRESSION, &comp); + let mut encs = Vec::new(); + el(&mut encs, CONTENT_ENCODING, &enc); + el(&mut v, CONTENT_ENCODINGS, &encs); + let mut a = Vec::new(); + el_uint(&mut a, TRACK_NUMBER, 2); + el_uint(&mut a, TRACK_TYPE, 2); + el_str(&mut a, CODEC_ID, "A_AAC/MPEG4/LC/SBR"); + el_str(&mut a, LANGUAGE, "ger"); + let mut au = Vec::new(); + el_float(&mut au, SAMPLING_FREQUENCY, 24000.0); + el_float(&mut au, OUTPUT_SAMPLING_FREQUENCY, 48000.0); + el_uint(&mut au, CHANNELS, 2); + el(&mut a, AUDIO, &au); + let mut tr = Vec::new(); + el(&mut tr, TRACK_ENTRY, &v); + el(&mut tr, TRACK_ENTRY, &a); + el(&mut f, TRACKS, &tr); + // Chapters + let mut disp = Vec::new(); + el_str(&mut disp, CHAP_STRING, "Intro"); + let mut atom = Vec::new(); + el_uint(&mut atom, CHAPTER_UID, 5); + el_uint(&mut atom, CHAPTER_TIME_START, 0); + el_uint(&mut atom, CHAPTER_TIME_END, 40_000_000); + el(&mut atom, CHAPTER_DISPLAY, &disp); + let mut ed = Vec::new(); + el(&mut ed, CHAPTER_ATOM, &atom); + let mut ch = Vec::new(); + el(&mut ch, EDITION_ENTRY, &ed); + el(&mut f, CHAPTERS, &ch); + // Attachments + let mut af = Vec::new(); + el_str(&mut af, FILE_NAME, "font.ttf"); + el_str(&mut af, FILE_MEDIA_TYPE, "font/ttf"); + el_uint(&mut af, FILE_UID, 77); + el(&mut af, FILE_DATA, &[9; 100]); + let mut att = Vec::new(); + el(&mut att, ATTACHED_FILE, &af); + el(&mut f, ATTACHMENTS, &att); + // Cluster 1 (unknown size): keyframe SimpleBlock, BlockGroup with ReferenceBlock + duration + write_id(&mut f, CLUSTER); + write_unknown_size(&mut f, 1); + el_uint(&mut f, TIMESTAMP, 1000); + el(&mut f, SIMPLE_BLOCK, &block(1, 0, 0x80, &[0x65, 1, 2])); + el(&mut f, SIMPLE_BLOCK, &block(2, 5, 0x80, &[0xAA; 10])); + let mut g = Vec::new(); + el(&mut g, BLOCK, &block(1, 40, 0, &[0x41, 3])); + el(&mut g, REFERENCE_BLOCK, &[0xD8]); + el_uint(&mut g, BLOCK_DURATION, 80); + el(&mut f, BLOCK_GROUP, &g); + el(&mut f, SIMPLE_BLOCK, &block(9, 0, 0x80, &[1])); // unknown track: ignored + // Cluster 2 (unknown size), ended by Tags + write_id(&mut f, CLUSTER); + write_unknown_size(&mut f, 8); + el_uint(&mut f, TIMESTAMP, 1120); + el(&mut f, SIMPLE_BLOCK, &block(1, 0, 0x80, &[0x65, 4])); + let mut st = Vec::new(); + el_str(&mut st, TAG_NAME, "ARTIST"); + el_str(&mut st, TAG_STRING, "Nobody"); + let mut tg = Vec::new(); + let mut tgt = Vec::new(); + el_uint(&mut tgt, TAG_TRACK_UID, 11); + el(&mut tg, TARGETS, &tgt); + el(&mut tg, SIMPLE_TAG, &st); + let mut tags = Vec::new(); + el(&mut tags, TAG, &tg); + el(&mut f, TAGS, &tags); + f +} + +#[test] +fn synthetic_file() { + let bytes = synthetic(); + let f = open_with(&bytes[..], &OpenOptions { index: true, verify_crc: true }).unwrap(); + assert!(f.live); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + assert_eq!((f.crc_checked, f.crc_errors.len()), (1, 0)); + assert_eq!(f.info.title.as_deref(), Some("Synthetic")); + let v = &f.tracks[0]; + assert!(matches!(&v.codec, Codec::Avc { avcc } if avcc[1] == 0x64)); + let vi = v.video.as_ref().unwrap(); + assert_eq!(vi.pixel_aspect(), (4, 3)); + assert_eq!(vi.projection.as_ref().map(|p| p.roll), Some(-90.0)); + assert_eq!(vi.display_rotation(), Some(1)); + let c = vi.color.as_ref().unwrap(); + assert!(c.full_range()); + assert_eq!( + (c.matrix_coefficients, c.transfer_characteristics, c.primaries, c.max_cll, c.max_fall), + (Some(9), Some(16), Some(9), Some(1000), Some(400)) + ); + let m = c.mastering.as_ref().unwrap(); + assert_eq!(m.primaries[1], (0.17, 0.797)); + assert_eq!(m.white_point, (0.3127, 0.329)); + assert_eq!((m.luminance_max, m.luminance_min), (1000.0, 0.0001)); + assert_eq!(v.encodings, vec![ContentEncoding::HeaderStripping { bytes: vec![0, 0, 0, 1], scope: 1 }]); + // legacy AAC ID: ASC synthesized with explicit SBR signaling (LC, 24 kHz, stereo → 48 kHz) + assert_eq!(f.tracks[1].codec, Codec::Aac { asc: vec![0x13, 0x10, 0x56, 0xE5, 0x98] }); + assert_eq!(f.tracks[1].language, "ger"); + assert_eq!(f.chapters[0].chapters[0].title(), Some("Intro")); + assert_eq!(f.chapters[0].chapters[0].end_ns, Some(40_000_000)); + assert_eq!(f.attachments.len(), 1); + let at = &f.attachments[0]; + assert_eq!((at.name.as_str(), at.media_type.as_str(), at.uid), ("font.ttf", "font/ttf", 77)); + assert_eq!(&bytes[at.data_offset as usize..][..100], &[9; 100]); + assert_eq!(f.tags[0].targets.track_uids, vec![11]); + assert_eq!(f.tags[0].simple[0].string.as_deref(), Some("Nobody")); + assert_eq!(f.clusters.len(), 2); + assert_eq!(v.samples.len(), 3); + assert_eq!(v.keyframes(), &[0, 2]); + + let d = Demuxer::from_slice(&bytes).unwrap(); + let p: Vec = d.map(|p| p.unwrap()).collect(); + assert_eq!(p.len(), 4); + assert_eq!((p[0].track, p[0].pts, p[0].keyframe, p[0].duration), (0, 1000, true, 40)); + assert_eq!(p[0].data, [0, 0, 0, 1, 0x65, 1, 2]); + assert_eq!((p[1].track, p[1].pts, p[1].data.len()), (1, 1005, 10)); + assert_eq!((p[2].pts, p[2].keyframe, p[2].duration), (1040, false, 80)); + assert_eq!(p[2].data, [0, 0, 0, 1, 0x41, 3]); + assert_eq!((p[3].pts, p[3].pts_ns), (1120, 1_120_000_000)); + assert_eq!(f.read_sample(&bytes[..], 0, 1).unwrap(), p[2].data); + + // CRC mismatch is reported, not fatal + let mut bad = bytes.clone(); + let title = bad.windows(9).position(|w| w == b"Synthetic").unwrap(); + bad[title] = b's'; + let f = open_with(&bad[..], &OpenOptions { index: true, verify_crc: true }).unwrap(); + assert_eq!(f.crc_errors.len(), 1); + + // seeking without index or cues builds the index + let mut d = Demuxer::with_options(&bytes[..], OpenOptions { index: false, verify_crc: false }).unwrap(); + assert_eq!(d.file().tracks.len(), 2); + assert_eq!(d.seek(0, 1_100_000_000).unwrap().pts, 1000); + assert_eq!(d.seek(0, 1_130_000_000).unwrap().pts, 1120); + assert_eq!(d.next_packet().unwrap().unwrap().pts, 1120); + assert!(d.file().indexed); +} + +/// One video track and one cluster at timestamp `ts` holding `content`. +fn one_cluster(ts: u64, content: &[u8]) -> Vec { + one_cluster_scaled(1_000_000, ts, content) +} + +fn one_cluster_scaled(scale: u64, ts: u64, content: &[u8]) -> Vec { + let mut f = Vec::new(); + let mut h = Vec::new(); + el_str(&mut h, DOC_TYPE, "matroska"); + el(&mut f, EBML, &h); + write_id(&mut f, SEGMENT); + write_unknown_size(&mut f, 8); + let mut info = Vec::new(); + el_uint(&mut info, TIMESTAMP_SCALE, scale); + el(&mut f, INFO, &info); + let mut v = Vec::new(); + el_uint(&mut v, TRACK_NUMBER, 1); + el_uint(&mut v, TRACK_UID, 1); + el_uint(&mut v, TRACK_TYPE, 1); + el_str(&mut v, CODEC_ID, "V_VP9"); + let mut tr = Vec::new(); + el(&mut tr, TRACK_ENTRY, &v); + el(&mut f, TRACKS, &tr); + write_id(&mut f, CLUSTER); + write_unknown_size(&mut f, 8); + el_uint(&mut f, TIMESTAMP, ts); + f.extend_from_slice(content); + f +} + +fn one_block(ts: u64, rel: i16) -> Vec { + let mut b = Vec::new(); + el(&mut b, SIMPLE_BLOCK, &block(1, rel, 0x80, &[0])); + one_cluster(ts, &b) +} + +/// A BlockGroup whose BlockAdditions hold `(BlockAddID, data)` pairs. +fn group_with_additions(block_data: &[u8], additions: &[(Option, &[u8])]) -> Vec { + let mut adds = Vec::new(); + for (id, data) in additions { + let mut more = Vec::new(); + if let Some(id) = id { + el_uint(&mut more, BLOCK_ADD_ID, *id); + } + el(&mut more, BLOCK_ADDITIONAL, data); + el(&mut adds, BLOCK_MORE, &more); + } + let mut g = Vec::new(); + el(&mut g, BLOCK, block_data); + el(&mut g, BLOCK_ADDITIONS, &adds); + let mut out = Vec::new(); + el(&mut out, BLOCK_GROUP, &g); + out +} + +#[test] +fn block_additional_id_1_is_located() { + let mut c = group_with_additions(&block(1, 0, 0, b"frame"), &[(Some(2), b"other"), (None, b"alpha")]); + c.extend(group_with_additions(&block(1, 40, 0, b"next"), &[(Some(2), b"other")])); + // Xiph lacing with two frames: an addition belongs to the block, not to one frame. + c.extend(group_with_additions(&block(1, 80, 0x02, &[1, 2, b'a', b'b', b'c']), &[(Some(1), b"laced")])); + let bytes = one_cluster(0, &c); + let f = open_with(&bytes[..], &OpenOptions::default()).unwrap(); + let t = &f.tracks[0]; + assert_eq!(t.samples.len(), 4); + let adds: Vec<_> = (0..4).map(|i| f.read_sample_addition(&bytes[..], 0, i).unwrap()).collect(); + assert_eq!(adds, [Some(b"alpha".to_vec()), None, None, None]); + assert_eq!(f.read_sample(&bytes[..], 0, 0).unwrap(), b"frame"); + assert!(f.read_sample_addition(&bytes[..], 0, 9).is_err()); +} + +#[test] +fn hostile_cluster_timestamps_saturate() { + let pts = |bytes: &[u8]| { + let first = Demuxer::from_slice(bytes).unwrap().next_packet().unwrap().unwrap().pts; + let indexed = open_with(bytes, &OpenOptions::default()).unwrap().tracks[0].samples[0].pts; + assert_eq!(first, indexed); + first + }; + assert_eq!(pts(&one_block(1000, 5)), 1005); + assert_eq!(pts(&one_block(i64::MAX as u64, 0)), i64::MAX); + assert_eq!(pts(&one_block(i64::MAX as u64, 1)), i64::MAX); + assert_eq!(pts(&one_block(u64::MAX, -3)), i64::MAX - 3); +} + +#[test] +fn cue_position_past_the_file_falls_back_to_the_index() { + for pos in [1 << 40, u64::MAX - 1] { + let mut ctp = Vec::new(); + el_uint(&mut ctp, CUE_TRACK, 1); + el_uint(&mut ctp, CUE_CLUSTER_POSITION, pos); + let mut cp = Vec::new(); + el_uint(&mut cp, CUE_TIME, 0); + el(&mut cp, CUE_TRACK_POSITIONS, &ctp); + let mut cues = Vec::new(); + el(&mut cues, CUE_POINT, &cp); + let mut bytes = one_block(1000, 0); + let at = bytes.windows(4).position(|w| w == CLUSTER.to_be_bytes()).unwrap(); + let mut el_cues = Vec::new(); + el(&mut el_cues, CUES, &cues); + bytes.splice(at..at, el_cues); + let mut d = Demuxer::with_options(&bytes[..], OpenOptions { index: false, verify_crc: false }).unwrap(); + assert_eq!(d.file().cues.len(), 1); + assert_eq!(d.seek(0, 0).unwrap().pts, 1000); + } +} + +#[test] +fn huge_timestamp_scale_is_ignored() { + // Three laced frames sharing the largest BlockDuration: with TimestampScale near 2^64 the + // per-lace split overflowed u128 and i128. + let mut g = Vec::new(); + el(&mut g, BLOCK, &block(1, 0, 0x02, &[2, 1, 1, b'a', b'b', b'c'])); + el_uint(&mut g, BLOCK_DURATION, u64::MAX); + let mut c = Vec::new(); + el(&mut c, BLOCK_GROUP, &g); + let f = open_with(&one_cluster_scaled(u64::MAX, i64::MAX as u64, &c)[..], &OpenOptions::default()).unwrap(); + assert_eq!(f.info.timestamp_scale, 1_000_000); + assert_eq!(f.tracks[0].samples.len(), 3); + let f = open_with(&one_cluster_scaled(1 << 32, 0, &c)[..], &OpenOptions::default()).unwrap(); + assert_eq!(f.info.timestamp_scale, 1 << 32); +} + +#[test] +fn duration_of_a_block_at_the_largest_timestamp_saturates() { + for d in [80, u64::MAX] { + let mut g = Vec::new(); + el(&mut g, BLOCK, &block(1, 0, 0, &[0])); + el_uint(&mut g, BLOCK_DURATION, d); + let mut c = Vec::new(); + el(&mut c, BLOCK_GROUP, &g); + let f = open_with(&one_cluster(i64::MAX as u64, &c)[..], &OpenOptions::default()).unwrap(); + assert_eq!(f.duration_ns(), Some(u64::MAX)); + } +} diff --git a/crates/media/src/matroska/track.rs b/crates/media/src/matroska/track.rs new file mode 100644 index 0000000000..9a5dfd7a13 --- /dev/null +++ b/crates/media/src/matroska/track.rs @@ -0,0 +1,383 @@ +//! Track descriptions (RFC 9559 §5.1.4). + +use crate::matroska::codec::Codec; + +/// Track type (`TrackType`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TrackKind { + Video, + Audio, + Complex, + Logo, + Subtitle, + Buttons, + Control, + Metadata, + Other(u8), +} + +impl TrackKind { + pub(crate) fn from_type(t: u64) -> TrackKind { + match t { + 1 => TrackKind::Video, + 2 => TrackKind::Audio, + 3 => TrackKind::Complex, + 0x10 => TrackKind::Logo, + 0x11 => TrackKind::Subtitle, + 0x12 => TrackKind::Buttons, + 0x20 => TrackKind::Control, + 0x21 => TrackKind::Metadata, + n => TrackKind::Other(n as u8), + } + } +} + +/// SMPTE ST 2086 mastering display metadata (`MasteringMetadata`). Chromaticities are CIE 1931 xy, +/// luminance in cd/m². +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MasteringMetadata { + /// Red, green, blue primaries as (x, y). + pub primaries: [(f64, f64); 3], + pub white_point: (f64, f64), + pub luminance_max: f64, + pub luminance_min: f64, +} + +/// `Colour` element. Code points use ITU-T H.273 values (as Matroska does). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Color { + /// `MatrixCoefficients` (H.273; 2 = unspecified). + pub matrix_coefficients: Option, + pub bits_per_channel: Option, + pub chroma_subsampling_horz: Option, + pub chroma_subsampling_vert: Option, + pub cb_subsampling_horz: Option, + pub cb_subsampling_vert: Option, + pub chroma_siting_horz: Option, + pub chroma_siting_vert: Option, + /// `Range`: 0 unspecified, 1 broadcast (limited), 2 full, 3 defined by matrix/transfer. + pub range: Option, + /// `TransferCharacteristics` (H.273). + pub transfer_characteristics: Option, + /// `Primaries` (H.273). + pub primaries: Option, + /// Maximum content light level (cd/m²). + pub max_cll: Option, + /// Maximum frame-average light level (cd/m²). + pub max_fall: Option, + pub mastering: Option, +} + +impl Color { + /// True if `Range` says full range. + pub fn full_range(&self) -> bool { + self.range == Some(2) + } +} + +/// `Video` element. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct VideoInfo { + pub pixel_width: u32, + pub pixel_height: u32, + /// `DisplayWidth`/`DisplayHeight`, in `display_unit` (0 = pixels, 3 = display aspect ratio). + pub display_width: Option, + pub display_height: Option, + pub display_unit: u64, + /// Crop (top, bottom, left, right) in pixels. + pub crop: (u32, u32, u32, u32), + /// `FlagInterlaced`: 0 undetermined, 1 interlaced, 2 progressive. + pub flag_interlaced: u64, + /// `FieldOrder` (0 progressive, 1 tff, 2 undetermined, 6 bff, 9/14 interleaved). + pub field_order: Option, + pub stereo_mode: Option, + /// `AlphaMode`: 1 if BlockAdditions carry alpha. + pub alpha_mode: u64, + /// `ColourSpace` FourCC (uncompressed video). + pub color_space: Option<[u8; 4]>, + pub color: Option, + pub projection: Option, +} + +/// `Projection` element (RFC 9559 §5.1.4.1.28.41): pose angles in degrees. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Projection { + /// 0 rectangular, 1 equirectangular, 2 cubemap, 3 mesh. + pub projection_type: u64, + /// Clockwise around the up vector. + pub yaw: f64, + /// Counter-clockwise around the right vector. + pub pitch: f64, + /// Counter-clockwise around the forward vector. + pub roll: f64, +} + +impl VideoInfo { + /// Clockwise quarter turns (0–3) to display a rectangular video, from `ProjectionPoseRoll` + /// (a counter-clockwise angle, so −90 is a quarter turn clockwise). None for other + /// projections, flips (non-zero yaw / pitch) or angles that are not a multiple of 90°. + pub fn display_rotation(&self) -> Option { + let Some(p) = &self.projection else { return Some(0) }; + if p.projection_type != 0 || p.yaw != 0.0 || p.pitch != 0.0 || p.roll % 90.0 != 0.0 { + return None; + } + Some((-(p.roll / 90.0) as i64).rem_euclid(4) as u8) + } + + /// Pixel aspect ratio derived from the display size (pixels or aspect-ratio units), reduced. + pub fn pixel_aspect(&self) -> (u32, u32) { + let pw = self.pixel_width.saturating_sub(self.crop.2.saturating_add(self.crop.3)) as u64; + let ph = self.pixel_height.saturating_sub(self.crop.0.saturating_add(self.crop.1)) as u64; + let (Some(dw), Some(dh)) = (self.display_width, self.display_height) else { return (1, 1) }; + if pw == 0 || ph == 0 || dw == 0 || dh == 0 || !matches!(self.display_unit, 0 | 3) { + return (1, 1); + } + // PAR = (dw/dh) / (pw/ph) + let (n, d) = (dw as u64 * ph, dh as u64 * pw); + let g = gcd(n, d); + ((n / g) as u32, (d / g) as u32) + } +} + +pub(crate) fn gcd(mut a: u64, mut b: u64) -> u64 { + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +/// `Audio` element. +#[derive(Clone, Debug, PartialEq)] +pub struct AudioInfo { + /// `SamplingFrequency` (Hz). + pub sampling_frequency: f64, + /// `OutputSamplingFrequency` (e.g. SBR output rate). + pub output_sampling_frequency: Option, + pub channels: u64, + pub bit_depth: Option, +} + +impl Default for AudioInfo { + fn default() -> Self { + Self { sampling_frequency: 8000.0, output_sampling_frequency: None, channels: 1, bit_depth: None } + } +} + +/// One `ContentEncoding`. +#[derive(Clone, Debug, PartialEq)] +pub enum ContentEncoding { + /// `ContentCompAlgo` 3: the given bytes were stripped from the start of every frame. + HeaderStripping { bytes: Vec, scope: u64 }, + /// Other compression (0 zlib, 1 bzlib, 2 lzo1x): not supported for reading frame data. + Compression { algo: u64, settings: Vec, scope: u64 }, + /// Encryption (not supported for reading frame data). + Encryption { scope: u64 }, +} + +/// One entry of a track's sample (frame) table. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Sample { + /// Byte offset of the (stored) frame data in the file. + pub offset: u64, + /// Stored size (excluding header-stripped bytes; see [`Track::sample_size`]). + pub size: u32, + /// Presentation timestamp in the track timebase (`TimestampScale` ticks). + pub pts: i64, + /// Duration in timebase ticks (from `BlockDuration` or `DefaultDuration`), 0 if unknown. + pub duration: u64, + pub keyframe: bool, + /// Index of the owning cluster in [`crate::matroska::MkvFile::clusters`]. + pub cluster: u32, + /// Offset of the block element (SimpleBlock / BlockGroup) header. + pub block_offset: u64, + /// Index of this frame within a laced block. + pub lace: u16, + /// (offset, size) of the block's `BlockAdditional` with `BlockAddID` 1, when it has one and + /// is not laced. In WebM this is the alpha layer of a VP8/VP9 track with `AlphaMode` 1: a + /// second, independently coded stream whose luma plane is the frame's alpha. + pub addition: Option<(u64, u32)>, +} + +/// A Matroska track (`TrackEntry`) plus, once indexed, its sample table. +#[derive(Clone, Debug)] +pub struct Track { + pub number: u64, + pub uid: u64, + pub kind: TrackKind, + pub enabled: bool, + pub default: bool, + pub forced: bool, + pub hearing_impaired: bool, + pub lacing: bool, + /// `DefaultDuration` in nanoseconds. + pub default_duration_ns: Option, + pub name: String, + /// `Language` (ISO 639-2, default `eng`). + pub language: String, + pub language_bcp47: Option, + pub codec_id: String, + pub codec_private: Vec, + pub codec_name: String, + pub codec: Codec, + /// `CodecDelay` in nanoseconds. + pub codec_delay_ns: u64, + /// `SeekPreRoll` in nanoseconds. + pub seek_pre_roll_ns: u64, + pub video: Option, + pub audio: Option, + pub encodings: Vec, + /// Timebase numerator/denominator in seconds: `TimestampScale / 1e9`, reduced. + pub timebase: (u64, u64), + /// Frame table (empty unless the file was opened with indexing). + pub samples: Vec, + pub(crate) sync: Vec, +} + +impl Track { + /// Bytes prepended to every frame by header-stripping compression, if any. + pub fn stripped_header(&self) -> Option<&[u8]> { + self.encodings.iter().find_map(|e| match e { + ContentEncoding::HeaderStripping { bytes, scope } if scope & 1 != 0 => Some(bytes.as_slice()), + _ => None, + }) + } + + /// True if frames can be returned verbatim or with header stripping undone. + pub fn frames_readable(&self) -> bool { + self.encodings.iter().all(|e| match e { + ContentEncoding::HeaderStripping { .. } => true, + ContentEncoding::Compression { scope, .. } | ContentEncoding::Encryption { scope } => scope & 1 == 0, + }) + } + + /// Bytes to put in front of a stored frame of `stored_size` bytes to get the codec frame: + /// header-stripped bytes, or for `V_PRORES` the 8-byte frame header (`size` + `icpf`) that the + /// Matroska ProRes mapping omits. + pub fn frame_prefix(&self, stored_size: u64) -> Vec { + let mut p = self.stripped_header().map(<[u8]>::to_vec).unwrap_or_default(); + if matches!(self.codec, Codec::ProRes { .. }) { + let total = stored_size + p.len() as u64 + 8; + let mut h = (total as u32).to_be_bytes().to_vec(); + h.extend_from_slice(b"icpf"); + h.extend_from_slice(&p); + p = h; + } + p + } + + /// Length of [`frame_prefix`](Self::frame_prefix), without building it. + pub fn frame_prefix_len(&self) -> u64 { + let stripped = self.stripped_header().map_or(0, <[u8]>::len) as u64; + if matches!(self.codec, Codec::ProRes { .. }) { stripped + 8 } else { stripped } + } + + /// Frame size of sample `i` as returned by `read_sample` / packets (stored size plus prefix). + pub fn sample_size(&self, i: usize) -> Option { + let s = self.samples.get(i)?; + Some(s.size as u64 + self.frame_prefix_len()) + } + + /// Indices of keyframe samples, ascending by file order. + pub fn keyframes(&self) -> &[u32] { + &self.sync + } + + /// Timebase ticks → nanoseconds. + pub fn ticks_to_ns(&self, t: i64) -> i64 { + let ns = t as i128 * self.timebase.0 as i128 * 1_000_000_000 / self.timebase.1 as i128; + ns.clamp(i64::MIN as i128, i64::MAX as i128) as i64 + } + + /// Nanoseconds → timebase ticks (floor). + pub fn ns_to_ticks(&self, ns: i64) -> i64 { + let n = ns as i128 * self.timebase.1 as i128; + let d = self.timebase.0 as i128 * 1_000_000_000; + n.div_euclid(d) as i64 + } + + /// Index of the last sample with `pts <= t` (in file order), or the first sample. + pub fn sample_at_pts(&self, t: i64) -> Option { + if self.samples.is_empty() { + return None; + } + let mut best: Option = None; + for (i, s) in self.samples.iter().enumerate() { + if s.pts <= t && best.is_none_or(|b| s.pts >= self.samples[b].pts) { + best = Some(i); + } + } + Some(best.unwrap_or(0)) + } + + /// Index of the keyframe with the greatest `pts <= t` (the first keyframe if none precedes `t`). + pub fn keyframe_before_pts(&self, t: i64) -> Option { + let mut best: Option = None; + for &k in &self.sync { + let s = &self.samples[k as usize]; + if s.pts <= t && best.is_none_or(|b| s.pts >= self.samples[b].pts) { + best = Some(k as usize); + } + } + best.or_else(|| self.sync.first().map(|&k| k as usize)) + } + + /// Index of the nearest keyframe at or before sample `index` in file order. + pub fn sync_sample_before(&self, index: usize) -> usize { + match self.sync.binary_search(&(index as u32)) { + Ok(i) => self.sync[i] as usize, + Err(0) => 0, + Err(i) => self.sync[i - 1] as usize, + } + } +} + +#[cfg(test)] +mod rotation_tests { + use super::{Projection, VideoInfo}; + + fn with_roll(projection_type: u64, yaw: f64, pitch: f64, roll: f64) -> VideoInfo { + VideoInfo { projection: Some(Projection { projection_type, yaw, pitch, roll }), ..Default::default() } + } + + #[test] + fn display_rotation_maps_rectangular_roll_to_clockwise_quarter_turns() { + assert_eq!(VideoInfo::default().display_rotation(), Some(0), "no Projection: as stored"); + // ProjectionPoseRoll is counter-clockwise: -90 is a quarter turn clockwise + for (roll, turns) in [(0.0, 0), (-90.0, 1), (180.0, 2), (-180.0, 2), (90.0, 3), (-270.0, 3), (270.0, 1), (360.0, 0)] { + assert_eq!(with_roll(0, 0.0, 0.0, roll).display_rotation(), Some(turns), "roll {roll}"); + } + } + + #[test] + fn display_rotation_leaves_non_rectangular_flipped_and_odd_angles_alone() { + assert_eq!(with_roll(1, 0.0, 0.0, -90.0).display_rotation(), None, "equirectangular"); + assert_eq!(with_roll(0, 180.0, 0.0, 0.0).display_rotation(), None, "yaw flip"); + assert_eq!(with_roll(0, 0.0, 180.0, 0.0).display_rotation(), None, "pitch flip"); + assert_eq!(with_roll(0, 0.0, 0.0, 45.0).display_rotation(), None, "not a quarter turn"); + assert_eq!(with_roll(0, 0.0, 0.0, f64::NAN).display_rotation(), None, "malformed angle"); + } +} + +#[cfg(test)] +mod aspect_overflow_tests { + use super::VideoInfo; + + #[test] + fn hostile_crop_sums_do_not_overflow() { + let video = VideoInfo { + pixel_width: 640, + pixel_height: 480, + display_width: Some(640), + display_height: Some(480), + crop: (u32::MAX, 1, u32::MAX, 1), + ..Default::default() + }; + assert_eq!(video.pixel_aspect(), (1, 1)); + } + + #[test] + fn ordinary_pixel_aspect_is_unchanged() { + let video = VideoInfo { pixel_width: 1920, pixel_height: 1080, display_width: Some(1440), display_height: Some(1080), ..Default::default() }; + assert_eq!(video.pixel_aspect(), (3, 4)); + } +} diff --git a/crates/media/tests/common/matroska.rs b/crates/media/tests/common/matroska.rs new file mode 100644 index 0000000000..fb301622a8 --- /dev/null +++ b/crates/media/tests/common/matroska.rs @@ -0,0 +1,137 @@ +//! Matroska fixtures and ffprobe helpers for `oracle_matroska.rs`. Tool discovery and the +//! fixture directory come from `common`. +#![allow(dead_code)] + +use serde_json::Value; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +/// (ffmpeg, ffprobe), or `None` after printing `SKIPPED`. +pub fn tools() -> Option<(PathBuf, PathBuf)> { + Some((crate::common::ffmpeg()?, crate::common::ffprobe()?)) +} + +pub fn fixture_dir() -> PathBuf { + crate::common::fixture_subdir("matroska") +} + +const V: &[&str] = &["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25"]; +const A: &[&str] = &["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000"]; + +/// Subtitle inputs shared by fixture generators on other threads, so an existing file is never +/// truncated: it is left alone when current, else replaced by a rename. +fn write_subs(dir: &Path) { + let srt = "1\n00:00:00,200 --> 00:00:00,900\nHello\n\n2\n00:00:01,000 --> 00:00:01,500\nWorld two\n\n"; + let vtt = "WEBVTT\n\n00:00:00.200 --> 00:00:00.900\nHello\n\n00:00:01.000 --> 00:00:01.500\nWorld\n\n"; + for (name, text) in [("in.srt", srt), ("in.vtt", vtt)] { + let path = dir.join(name); + if std::fs::read(&path).is_ok_and(|d| d == text.as_bytes()) { + continue; + } + let tmp = crate::common::temp_path(&path); + std::fs::write(&tmp, text).unwrap(); + std::fs::rename(&tmp, &path).unwrap(); + } +} + +/// Every fixture `spec`/`fixture` knows (for `generate_fixtures`). +pub const ALL_FIXTURES: &[&str] = &[ + "h264_aac.mkv", + "vp9_opus.webm", + "flac.mkv", + "vorbis.mkv", + "subs.mkv", + "webvtt.webm", + "cues_front.mkv", + "hevc_hdr.mkv", + "prores_pcm.mkv", + "mjpeg_ac3.mkv", + "av1.mkv", + "live.mkv", +]; + +/// Fixture name → ffmpeg arguments (after `-y -v error`, before the output path). +/// `None` for fixtures written through a pipe (no Cues, unknown sizes). +pub fn spec(name: &str) -> Option> { + let cat = |parts: &[&[&str]]| parts.concat().into_iter().map(String::from).collect::>(); + let x264: &[&str] = &["-c:v", "libx264", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p"]; + Some(match name { + "h264_aac.mkv" => cat(&[V, A, &["-t", "2"], x264, &["-c:a", "aac"]]), + "vp9_opus.webm" => cat(&[V, A, &["-t", "2", "-c:v", "libvpx-vp9", "-deadline", "realtime", "-g", "10", "-c:a", "libopus"]]), + "flac.mkv" => cat(&[A, &["-t", "2", "-c:a", "flac"]]), + "vorbis.mkv" => cat(&[A, &["-t", "2", "-ac", "2", "-c:a", "vorbis", "-strict", "-2"]]), + "subs.mkv" => cat(&[ + V, + &["-i", "in.srt", "-i", "in.srt", "-t", "2", "-map", "0:v", "-map", "1:s", "-map", "2:s"], + x264, + &["-c:s:0", "srt", "-c:s:1", "ass", "-metadata:s:s:0", "language=fre", "-metadata:s:s:1", "title=Styled"], + ]), + "webvtt.webm" => { + cat(&[V, &["-i", "in.vtt", "-t", "2", "-map", "0:v", "-map", "1:s", "-c:v", "libvpx", "-deadline", "realtime", "-c:s", "webvtt"]]) + } + "cues_front.mkv" => cat(&[V, A, &["-t", "3"], x264, &["-c:a", "aac", "-cues_to_front", "1", "-cluster_time_limit", "500"]]), + "hevc_hdr.mkv" => cat(&[ + V, + &[ + "-t", + "1", + "-c:v", + "libx265", + "-pix_fmt", + "yuv420p10le", + "-x265-params", + "log-level=error:bframes=3:keyint=10:hdr10=1:master-display=G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(10000000,1):max-cll=1000,400", + "-vf", + "setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc:range=tv", + ], + ]), + "prores_pcm.mkv" => cat(&[V, A, &["-t", "1", "-c:v", "prores_ks", "-profile:v", "2", "-c:a", "pcm_s24le"]]), + "mjpeg_ac3.mkv" => cat(&[V, A, &["-t", "1", "-c:v", "mjpeg", "-q:v", "5", "-c:a", "ac3", "-metadata", "title=craft-media test"]]), + "av1.mkv" => cat(&[V, &["-t", "1", "-c:v", "libsvtav1", "-preset", "12", "-g", "10"]]), + "live.mkv" => return None, + _ => panic!("unknown fixture {name}"), + }) +} + +/// Generate (once) and return the path of a fixture; `None` after printing `SKIPPED` if +/// generation failed (a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). +pub fn fixture(ffmpeg: &Path, name: &str) -> Option { + let dir = fixture_dir(); + let out = dir.join(name); + if out.exists() && std::fs::metadata(&out).map(|m| m.len() > 0).unwrap_or(false) { + return Some(out); + } + write_subs(&dir); + let tmp = crate::common::temp_path(&out); + let mut c = Command::new(ffmpeg); + c.current_dir(&dir).args(["-y", "-v", "error"]); + match spec(name) { + Some(args) => { + let fmt = if name.ends_with(".webm") { "webm" } else { "matroska" }; + c.args(&args).args(["-f", fmt]).arg(&tmp); + } + None => { + // streamed to a pipe: unknown-size Segment, no Cues, no Duration + let f = std::fs::File::create(&tmp).unwrap(); + c.args(V).args(A); + c.args(["-t", "2", "-c:v", "libx264", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p", "-c:a", "aac", "-f", "matroska", "pipe:1"]); + c.stdout(Stdio::from(f)); + } + } + // the rename is atomic: concurrent generators race harmlessly + crate::common::run_generator(&mut c, &tmp, &out, crate::common::oracles_required()) +} + +pub fn ffprobe_json(ffprobe: &Path, path: &Path) -> Value { + let out = Command::new(ffprobe) + .args(["-v", "error", "-show_packets", "-show_streams", "-show_format", "-show_chapters", "-of", "json"]) + .arg(path) + .output() + .expect("run ffprobe"); + assert!(out.status.success(), "ffprobe failed on {}: {}", path.display(), String::from_utf8_lossy(&out.stderr)); + serde_json::from_slice(&out.stdout).expect("ffprobe json") +} + +pub fn int(v: &Value) -> Option { + v.as_i64().or_else(|| v.as_str().and_then(|s| s.parse().ok())) +} diff --git a/crates/media/tests/common/mod.rs b/crates/media/tests/common/mod.rs new file mode 100644 index 0000000000..e0a2a3c726 --- /dev/null +++ b/crates/media/tests/common/mod.rs @@ -0,0 +1,374 @@ +//! Shared helpers for oracle tests: ffmpeg/ffprobe discovery and fixture generation. +//! ffmpeg is used only as an external fixture generator and oracle (never linked). +//! +//! Tool search order: `CRAFT_MEDIA_FFMPEG` / `CRAFT_MEDIA_FFPROBE` (an explicit path; a wrong +//! path fails the test), then `PATH`, then well-known install directories. A missing tool, a +//! failed fixture generator or a failed ffprobe run prints `SKIPPED` and the test passes, unless +//! `CRAFT_MEDIA_REQUIRE_ORACLES=1` is set: then each of these fails the test. +//! Fixtures are generated into `$CRAFT_MEDIA_FIXTURES_DIR` or `/target/fixtures`, one +//! directory per container (`isobmff`, `matroska`), and never committed. +#![allow(dead_code)] + +use serde_json::Value; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const REQUIRE_ENV: &str = "CRAFT_MEDIA_REQUIRE_ORACLES"; + +const KNOWN_DIRS: &[&str] = &[ + "/opt/homebrew/bin", + "/usr/local/bin", + "/usr/bin", + "/opt/local/bin", + "/snap/bin", + r"C:\ffmpeg\bin", + r"C:\Program Files\ffmpeg\bin", + r"C:\ProgramData\chocolatey\bin", +]; + +fn env_var(name: &str) -> String { + format!("CRAFT_MEDIA_{}", name.to_ascii_uppercase()) +} + +fn find_tool(name: &str) -> Option { + if let Some(e) = std::env::var_os(env_var(name)).filter(|e| !e.is_empty()) { + let p = PathBuf::from(e); + assert!(p.is_file(), "{} is set but `{}` is not a file", env_var(name), p.display()); + return Some(p); + } + let names = if cfg!(windows) { [format!("{name}.exe"), name.to_string()] } else { [name.to_string(), format!("{name}.exe")] }; + let path_dirs = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect::>()).unwrap_or_default(); + let dirs = path_dirs.into_iter().chain(KNOWN_DIRS.iter().map(PathBuf::from)); + for dir in dirs { + for n in &names { + let p = dir.join(n); + if p.is_file() { + return Some(p); + } + } + } + None +} + +/// Find a tool silently (cached for the process for ffmpeg and ffprobe). +pub fn tool(name: &str) -> Option { + static FFMPEG: OnceLock> = OnceLock::new(); + static FFPROBE: OnceLock> = OnceLock::new(); + match name { + "ffmpeg" => FFMPEG.get_or_init(|| find_tool("ffmpeg")).clone(), + "ffprobe" => FFPROBE.get_or_init(|| find_tool("ffprobe")).clone(), + _ => find_tool(name), + } +} + +pub fn oracles_required() -> bool { + std::env::var(REQUIRE_ENV).is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")) +} + +/// Give up on an oracle check: print `SKIPPED` and return `None`, or fail when oracles are +/// required. +pub fn skip(reason: &str) -> Option { + skip_with(oracles_required(), reason) +} + +fn skip_with(required: bool, reason: &str) -> Option { + assert!(!required, "craft-media oracle: {reason}, and {REQUIRE_ENV}=1 forbids skipping oracle tests"); + eprintln!("SKIPPED (craft-media oracle): {reason}"); + None +} + +/// Run a fixture generator writing `tmp`, then rename it to `out`. A generator that cannot start +/// or fails skips (see [`skip`]); `required` is explicit so tests can set it without touching +/// the process environment. +pub fn run_generator(cmd: &mut Command, tmp: &Path, out: &Path, required: bool) -> Option { + let reason = match cmd.output() { + Ok(o) if o.status.success() => match std::fs::rename(tmp, out) { + Ok(()) => return Some(out.to_path_buf()), + Err(e) => format!("could not move {} into place: {e}", tmp.display()), + }, + Ok(o) => format!("generator failed for {} ({}): {}", out.display(), o.status, String::from_utf8_lossy(&o.stderr).trim()), + Err(e) => format!("could not start generator for {}: {e}", out.display()), + }; + let _ = std::fs::remove_file(tmp); + skip_with(required, &format!("{reason} (encoder unavailable?)")) +} + +fn tool_or_skip(name: &str) -> Option { + tool(name).or_else(|| skip(&format!("{name} not found (set {} or put {name} on PATH)", env_var(name)))) +} + +/// ffmpeg, or `None` after printing `SKIPPED` (a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). +pub fn ffmpeg() -> Option { + tool_or_skip("ffmpeg") +} + +/// ffprobe, or `None` after printing `SKIPPED` (a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). +pub fn ffprobe() -> Option { + tool_or_skip("ffprobe") +} + +/// Fixtures of the `isobmff` tests. +pub fn fixture_dir() -> PathBuf { + fixture_subdir("isobmff") +} + +/// `$CRAFT_MEDIA_FIXTURES_DIR/` or `/target/fixtures/`, created if missing. +pub fn fixture_subdir(name: &str) -> PathBuf { + let d = match std::env::var_os("CRAFT_MEDIA_FIXTURES_DIR").filter(|v| !v.is_empty()) { + Some(d) => PathBuf::from(d), + None => { + let here = Path::new(env!("CARGO_MANIFEST_DIR")); + let root = here.parent().and_then(Path::parent).unwrap_or(here); + root.join("target").join("fixtures") + } + } + .join(name); + std::fs::create_dir_all(&d).unwrap(); + d +} + +pub fn out_dir() -> PathBuf { + let d = fixture_dir().join("out"); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A temporary sibling of `out` that no other thread or process will pick; the extension is kept +/// because ffmpeg chooses the muxer from it. +pub fn temp_path(out: &Path) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let tid = format!("{:?}", std::thread::current().id()).replace(|c: char| !c.is_ascii_alphanumeric(), ""); + let n = N.fetch_add(1, Ordering::Relaxed); + let stem = out.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + let name = match out.extension() { + Some(ext) => format!("{stem}.tmp-{}-{tid}-{n}.{}", std::process::id(), ext.to_string_lossy()), + None => format!("{stem}.tmp-{}-{tid}-{n}", std::process::id()), + }; + out.with_file_name(name) +} + +/// Run a fixture generator and print `FIXTURE `. +pub fn generate_and_report(name: &str, outputs: &[PathBuf], generate: impl FnOnce() -> Option) -> Option { + let existed = !outputs.is_empty() && outputs.iter().all(|p| std::fs::metadata(p).is_ok_and(|m| m.len() > 0)); + let r = generate(); + let status = match (&r, existed) { + (None, _) => "skipped", + (Some(_), true) => "cached", + (Some(_), false) => "made", + }; + println!("FIXTURE {status} {name}"); + r +} + +const V: &[&str] = &["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25"]; +const A: &[&str] = &["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000"]; + +/// (fixture name, ffmpeg arguments after the global options, output file name derived from the name). +pub fn fixture_specs() -> Vec<(&'static str, Vec<&'static str>)> { + let cat = |parts: &[&[&'static str]]| parts.concat(); + vec![ + ("h264_bframes.mp4", cat(&[V, A, &["-t", "2", "-c:v", "libx264", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p", "-c:a", "aac"]])), + ("h264.mov", cat(&[V, A, &["-t", "2", "-c:v", "libx264", "-bf", "3", "-g", "25", "-pix_fmt", "yuv420p", "-c:a", "pcm_s16le"]])), + ( + "hevc.mp4", + cat(&[V, &["-t", "2", "-c:v", "libx265", "-tag:v", "hvc1", "-x265-params", "log-level=error:bframes=3", "-pix_fmt", "yuv420p"]]), + ), + ("prores.mov", cat(&[V, A, &["-t", "1", "-c:v", "prores_ks", "-profile:v", "3", "-c:a", "pcm_s24le"]])), + ("prores4444.mov", cat(&[V, &["-t", "0.5", "-c:v", "prores_ks", "-profile:v", "4", "-pix_fmt", "yuva444p10le"]])), + ("mjpeg.mov", cat(&[V, &["-t", "1", "-c:v", "mjpeg", "-q:v", "5"]])), + ( + "dnxhd.mov", + vec![ + "-f", + "lavfi", + "-i", + "testsrc2=size=1280x720:rate=25", + "-t", + "0.2", + "-c:v", + "dnxhd", + "-profile:v", + "dnxhr_lb", + "-pix_fmt", + "yuv422p", + ], + ), + ("pcm_f32.mov", cat(&[A, &["-t", "1", "-c:a", "pcm_f32le"]])), + ("pcm_s16be.mov", cat(&[A, &["-t", "1", "-c:a", "pcm_s16be"]])), + ("aac.mp4", cat(&[A, &["-t", "2", "-c:a", "aac", "-b:a", "96k"]])), + ("aac_stereo44.m4a", vec!["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", "-t", "1.5", "-ac", "2", "-c:a", "aac"]), + ( + "frag.mp4", + cat(&[ + V, + A, + &[ + "-t", + "3", + "-c:v", + "libx264", + "-bf", + "2", + "-g", + "25", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-movflags", + "frag_keyframe+empty_moov", + ], + ]), + ), + ( + "frag_dash.mp4", + cat(&[ + V, + &[ + "-t", + "3", + "-c:v", + "libx264", + "-bf", + "2", + "-g", + "25", + "-pix_fmt", + "yuv420p", + "-movflags", + "frag_keyframe+empty_moov+default_base_moof", + ], + ]), + ), + ("faststart.mp4", cat(&[V, A, &["-t", "2", "-c:v", "libx264", "-bf", "2", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "+faststart"]])), + ( + "tmcd_2997df.mov", + vec!["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=30000/1001", "-t", "1", "-c:v", "mjpeg", "-timecode", "01:00:00;00"], + ), + ( + "tmcd_23976.mov", + vec![ + "-f", + "lavfi", + "-i", + "testsrc2=size=160x120:rate=24000/1001", + "-t", + "1", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-timecode", + "01:00:00:00", + ], + ), + ( + "h264_2997.mp4", + vec!["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=30000/1001", "-t", "2", "-c:v", "libx264", "-bf", "2", "-pix_fmt", "yuv420p"], + ), + ("flac.mp4", cat(&[A, &["-t", "1", "-c:a", "flac"]])), + ("alac.m4a", cat(&[A, &["-t", "1", "-c:a", "alac"]])), + ("opus.mp4", cat(&[A, &["-t", "1", "-c:a", "libopus"]])), + ("ac3.mp4", cat(&[A, &["-t", "1", "-c:a", "ac3"]])), + ("vp9.mp4", cat(&[V, &["-t", "1", "-c:v", "libvpx-vp9", "-deadline", "realtime", "-cpu-used", "8"]])), + ("av1.mp4", cat(&[V, &["-t", "1", "-c:v", "libsvtav1", "-preset", "12"]])), + ( + "colr_pasp.mov", + cat(&[ + V, + &[ + "-t", + "0.5", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-color_primaries", + "bt709", + "-color_trc", + "bt709", + "-colorspace", + "bt709", + "-aspect", + "16:9", + ], + ]), + ), + ] +} + +fn run_ffmpeg(ff: &Path, args: &[&str], out: &Path) -> Option { + let tmp = temp_path(out); + let mut cmd = Command::new(ff); + cmd.args(["-v", "error", "-y", "-nostdin"]).args(args).arg(&tmp); + run_generator(&mut cmd, &tmp, out, oracles_required()) +} + +/// Path to a fixture, generating it with ffmpeg if needed. `None` after printing `SKIPPED` if +/// ffmpeg is missing or the encoder isn't available (a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). +pub fn fixture(name: &str) -> Option { + let ff = ffmpeg()?; + let path = fixture_dir().join(name); + if path.exists() { + return Some(path); + } + if name == "editlist_cut.mp4" { + let src = fixture("h264_bframes.mp4")?; + let s = src.to_str().expect("fixture path is UTF-8").to_string(); + return run_ffmpeg(&ff, &["-ss", "0.5", "-i", &s, "-c", "copy"], &path); + } + let (_, args) = fixture_specs().into_iter().find(|(n, _)| *n == name).unwrap_or_else(|| panic!("unknown fixture {name}")); + run_ffmpeg(&ff, &args, &path) +} + +pub fn all_fixture_names() -> Vec<&'static str> { + let mut v: Vec<&str> = fixture_specs().iter().map(|(n, _)| *n).collect(); + v.push("editlist_cut.mp4"); + v +} + +/// ffprobe's JSON for `path`, or `None` after printing `SKIPPED` (a failure with +/// `CRAFT_MEDIA_REQUIRE_ORACLES=1`). +pub fn probe_json(path: &Path, what: &[&str]) -> Option { + let fp = ffprobe()?; + let o = match Command::new(fp).args(["-v", "error", "-of", "json"]).args(what).arg(path).output() { + Ok(o) if o.status.success() => o, + Ok(o) => return skip(&format!("ffprobe failed on {}: {}", path.display(), String::from_utf8_lossy(&o.stderr).trim())), + Err(e) => return skip(&format!("could not run ffprobe: {e}")), + }; + match serde_json::from_slice(&o.stdout) { + Ok(v) => Some(v), + Err(e) => skip(&format!("ffprobe output for {} is not JSON: {e}", path.display())), + } +} + +/// ffprobe's packets for `path`, or `None` after a skipped probe (see [`probe_json`]). +pub fn packets(path: &Path) -> Option> { + probe_json(path, &["-show_packets"]).map(|v| v["packets"].as_array().cloned().unwrap_or_default()) +} + +/// ffprobe's streams for `path`, or `None` after a skipped probe (see [`probe_json`]). +pub fn streams(path: &Path) -> Option> { + probe_json(path, &["-show_streams"]).map(|v| v["streams"].as_array().cloned().unwrap_or_default()) +} + +pub fn int(v: &Value) -> Option { + match v { + Value::Number(n) => n.as_i64(), + Value::String(s) => s.parse().ok(), + _ => None, + } +} + +/// Decode a file with ffmpeg to the null muxer; returns stderr (empty on success). +pub fn ffmpeg_decode_errors(path: &Path) -> Option { + let ff = ffmpeg()?; + let o = Command::new(ff).args(["-v", "error", "-nostdin", "-i"]).arg(path).args(["-f", "null", "-"]).output().ok()?; + let mut s = String::from_utf8_lossy(&o.stderr).into_owned(); + if !o.status.success() { + s.push_str("\n(ffmpeg exited with failure)"); + } + Some(s) +} diff --git a/crates/media/tests/fuzz.rs b/crates/media/tests/fuzz.rs new file mode 100644 index 0000000000..3c302ac6b5 --- /dev/null +++ b/crates/media/tests/fuzz.rs @@ -0,0 +1,185 @@ +//! Deterministic mutation fuzzing: the demuxer must never panic on corrupted input. + +mod common; + +use craft_media::isobmff::*; +use std::io::Cursor; + +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } +} + +fn synthetic_files() -> Vec> { + let mut out = Vec::new(); + for brand in [Brand::Mp4, Brand::Mov] { + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(brand)).unwrap(); + let v = w + .add_track(TrackConfig::new(SampleEntry::avc(AvcConfig::new(vec![vec![0x67, 0x64, 0, 0x1F]], vec![vec![0x68]], 4), 64, 64), 25)) + .unwrap(); + let mut cfg = TrackConfig::new(SampleEntry::aac(vec![0x11, 0x90], 2, 48000), 48000); + cfg.media_start = Some(1024); + let a = w.add_track(cfg).unwrap(); + let p = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 1, sample_rate: 8000.0 }; + let pc = w.add_track(TrackConfig::new(SampleEntry::pcm(p), 8000)).unwrap(); + w.add_timecode_track( + v, + TimecodeConfig { flags: 1, timescale: 30000, frame_duration: 1001, frames_per_second: 30, ..Default::default() }, + 1000, + ) + .unwrap(); + for i in 0..20u8 { + w.write_sample(v, WriteSample { data: &[i; 20], duration: 1, composition_offset: (i % 3) as i32, is_sync: i % 10 == 0 }).unwrap(); + w.write_sample(a, WriteSample { data: &[i; 7], duration: 1024, composition_offset: 0, is_sync: true }).unwrap(); + w.write_sample(pc, WriteSample { data: &[i; 16], duration: 0, composition_offset: 0, is_sync: true }).unwrap(); + } + out.push(w.finish().unwrap().into_inner()); + } + let mut w = FragmentedWriter::new(Vec::new(), WriterOptions::new(Brand::Mp4)); + let v = w.add_track(TrackConfig::new(SampleEntry::jpeg(16, 16), 1000)).unwrap(); + for i in 0..12u8 { + w.write_sample(v, WriteSample { data: &[i; 9], duration: 40, composition_offset: -1, is_sync: i % 4 == 0 }).unwrap(); + if i % 4 == 3 { + w.flush_fragment().unwrap(); + } + } + out.push(w.finish().unwrap()); + out +} + +/// Walk every box as if it were a container, checking the iterator's offsets against `data`. +fn walk_boxes(data: &[u8], range: std::ops::Range, depth: usize, budget: &mut usize, lenient: bool) { + let mut it = boxes::BoxIter::within(data, range.clone()); + if lenient { + it = it.allow_truncated(); + } + let mut next = range.start; + for b in it.by_ref() { + let Ok(b) = b else { break }; + assert!(b.offset == next && b.end() <= range.end && b.payload_range().start >= b.offset + 8); + assert_eq!(data.get(b.payload_range()), Some(b.payload)); + next = b.end(); + if depth < 8 && *budget > 0 { + *budget -= 1; + walk_boxes(data, b.payload_range(), depth + 1, budget, lenient); + } + } + assert!(it.next().is_none() && it.offset() <= range.end); +} + +fn exercise(data: &[u8]) -> bool { + walk_boxes(data, 0..data.len(), 0, &mut 2000, false); + walk_boxes(data, 0..data.len(), 0, &mut 200, true); + let r = open(data); + let ok = r.is_ok(); + if let Ok(f) = r { + for (ti, t) in f.tracks.iter().enumerate() { + let n = t.samples.len(); + for i in [0, n / 2, n.saturating_sub(1)] { + let _ = f.read_sample(data, ti, i); + let _ = t.sync_sample_before(i); + let _ = t.presentation_pts(i); + } + let _ = t.sample_at_pts(i64::MIN); + let _ = t.sample_at_pts(i64::MAX); + let _ = t.sample_at_presentation_time(0); + if let Some(CodecConfig::Timecode(tc)) = t.codec() { + let _ = tc.format_frame(tc.start_frame.unwrap_or(u32::MAX)); + } + } + } + ok +} + +fn mutate_all(base: &[u8], seed: u64, iterations: usize) { + let mut rng = Rng(seed | 1); + // Focus mutations on the moov/moof boxes (where parsing happens). + let hot: Vec<(usize, usize)> = { + let mut v = Vec::new(); + for name in [b"moov", b"moof"] { + let mut from = 0; + while let Some(p) = base[from..].windows(4).position(|w| w == name) { + let at = from + p; + let start = at.saturating_sub(4); + let size = u32::from_be_bytes(base[start..start + 4].try_into().unwrap()) as usize; + v.push((start, (start + size.max(8)).min(base.len()))); + from = at + 4; + } + } + if v.is_empty() { + v.push((0, base.len())); + } + v + }; + let mut parsed = 0usize; + for _ in 0..iterations { + let mut d = base.to_vec(); + let (lo, hi) = hot[rng.below(hot.len())]; + let edits = 1 + rng.below(4); + for _ in 0..edits { + let pos = if rng.below(10) < 8 { lo + rng.below(hi - lo) } else { rng.below(d.len()) }; + let pos = pos.min(d.len() - 1); + match rng.below(6) { + 0 => d[pos] ^= 1 << rng.below(8), + 1 => d[pos] = rng.next() as u8, + 2 | 3 => { + // Overwrite a 32-bit field with an extreme value. + let v: u32 = match rng.below(5) { + 0 => 0, + 1 => 1, + 2 => u32::MAX, + 3 => 0x8000_0000, + _ => rng.next() as u32, + }; + let end = (pos + 4).min(d.len()); + d[pos..end].copy_from_slice(&v.to_be_bytes()[..end - pos]); + } + 4 => d.truncate(pos.max(8)), + _ => { + let n = rng.below(16).min(d.len() - pos); + d.drain(pos..pos + n); + } + } + if d.is_empty() { + break; + } + } + parsed += exercise(&d) as usize; + } + eprintln!("seed {seed:#x}: {parsed}/{iterations} mutated files still parsed"); +} + +#[test] +fn mutated_synthetic_files_never_panic() { + for (i, f) in synthetic_files().iter().enumerate() { + exercise(f); + mutate_all(f, 0x5EED_0000 + i as u64, 20_000); + } +} + +#[test] +fn mutated_ffmpeg_fixtures_never_panic() { + for (i, name) in ["h264_bframes.mp4", "frag.mp4", "tmcd_2997df.mov", "prores.mov", "hevc.mp4", "aac.mp4"].iter().enumerate() { + let Some(p) = common::fixture(name) else { continue }; + let data = std::fs::read(p).unwrap(); + mutate_all(&data, 0xF00D + i as u64, 5000); + } +} + +#[test] +fn truncations_never_panic() { + for f in synthetic_files() { + for n in 0..f.len().min(4096) { + exercise(&f[..n]); + } + } +} diff --git a/crates/media/tests/fuzz_matroska.rs b/crates/media/tests/fuzz_matroska.rs new file mode 100644 index 0000000000..73a433616b --- /dev/null +++ b/crates/media/tests/fuzz_matroska.rs @@ -0,0 +1,137 @@ +//! Deterministic mutation fuzzing of the Matroska demuxer: it must never panic on corrupted input. + +use craft_media::matroska::*; +use std::io::Cursor; + +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } +} + +fn synthetic_files() -> Vec> { + let mut out = Vec::new(); + for lacing in [LacingMode::None, LacingMode::Xiph, LacingMode::Ebml, LacingMode::FixedOrEbml] { + let mut v = TrackSpec::new(TrackKind::Video, "V_MJPEG"); + v.video_size = Some((16, 16)); + v.default_duration_ns = Some(40_000_000); + let mut a = TrackSpec::new(TrackKind::Audio, "A_PCM/INT/LIT"); + a.audio = Some((48000.0, 2, Some(16))); + a.default_duration_ns = Some(10_000_000); + let mut s = TrackSpec::new(TrackKind::Subtitle, "S_TEXT/UTF8"); + s.language = Some("ger".into()); + let opts = MuxOptions { lacing, cluster_duration_ns: 200_000_000, title: Some("fuzz".into()), ..Default::default() }; + let mut w = MkvWriter::new(Cursor::new(Vec::new()), vec![v, a, s], opts).unwrap(); + for i in 0..20i64 { + w.write_frame(0, i * 40_000_000, i % 5 == 0, &[i as u8; 24], None).unwrap(); + for k in 0..4 { + let size = if k == 3 { 7 } else { 40 }; + w.write_frame(1, i * 40_000_000 + k * 10_000_000, true, &vec![k as u8; size], None).unwrap(); + } + if i % 7 == 0 { + w.write_frame(2, i * 40_000_000, true, b"text", Some(120_000_000)).unwrap(); + } + } + out.push(w.finish().unwrap().into_inner()); + } + out +} + +fn exercise(data: &[u8]) -> bool { + let mut parsed = false; + for opts in [OpenOptions { index: true, verify_crc: true }, OpenOptions { index: false, verify_crc: false }] { + let Ok(f) = open_with(data, &opts) else { continue }; + parsed = true; + let _ = f.duration_ns(); + for (ti, t) in f.tracks.iter().enumerate() { + let _ = t.video.as_ref().map(|v| (v.pixel_aspect(), v.display_rotation())); + let n = t.samples.len(); + for i in [0, n / 2, n.saturating_sub(1)] { + let _ = f.read_sample(data, ti, i); + let _ = f.read_sample_addition(data, ti, i); + let _ = t.sync_sample_before(i); + } + for time in [i64::MIN, -1, 0, 500_000_000, i64::MAX] { + let _ = f.keyframe_before(ti, time); + let _ = t.sample_at_pts(t.ns_to_ticks(time)); + } + } + let Ok(mut d) = Demuxer::with_options(data, opts) else { continue }; + for p in d.by_ref().take(10_000) { + if p.is_err() { + break; + } + } + for track in 0..d.tracks().len() { + for time in [i64::MIN, 0, 300_000_000, i64::MAX] { + if d.seek(track, time).is_ok() { + let _ = d.next_packet(); + } + } + let _ = d.keyframe_index(track); + } + } + parsed +} + +fn mutate_all(base: &[u8], seed: u64, iterations: usize) { + let mut rng = Rng(seed | 1); + let mut parsed = 0usize; + for _ in 0..iterations { + let mut d = base.to_vec(); + for _ in 0..1 + rng.below(4) { + let pos = rng.below(d.len()); + match rng.below(6) { + 0 => d[pos] ^= 1 << rng.below(8), + 1 => d[pos] = rng.next() as u8, + 2 | 3 => { + // An extreme value, often landing on an EBML size or a timestamp. + let v: u64 = match rng.below(5) { + 0 => 0, + 1 => 0x01FF_FFFF_FFFF_FFFF, + 2 => u64::MAX, + 3 => 0x0100_0000_0000_0000 | (rng.next() >> 8), + _ => rng.next(), + }; + let end = (pos + 8).min(d.len()); + d[pos..end].copy_from_slice(&v.to_be_bytes()[..end - pos]); + } + 4 => d.truncate(pos.max(4)), + _ => { + let n = rng.below(16).min(d.len() - pos); + d.drain(pos..pos + n); + } + } + if d.is_empty() { + break; + } + } + parsed += exercise(&d) as usize; + } + eprintln!("seed {seed:#x}: {parsed}/{iterations} mutated files still parsed"); +} + +#[test] +fn mutated_matroska_files_never_panic() { + for (i, f) in synthetic_files().iter().enumerate() { + assert!(exercise(f)); + mutate_all(f, 0x4D4B_0000 + i as u64, 2000); + } +} + +#[test] +fn matroska_truncations_never_panic() { + for f in synthetic_files().iter().take(1) { + for n in 0..f.len() { + exercise(&f[..n]); + } + } +} diff --git a/crates/media/tests/oracle_demux.rs b/crates/media/tests/oracle_demux.rs new file mode 100644 index 0000000000..0a23b4fb3f --- /dev/null +++ b/crates/media/tests/oracle_demux.rs @@ -0,0 +1,319 @@ +//! Oracle tests: compare our demuxer's sample tables and codec parameters with ffprobe. + +mod common; + +use common::*; +use craft_media::isobmff::{CodecConfig, Mp4File, TrackKind, open}; +use serde_json::Value; + +fn pcm_name_matches(ff: &str, c: &CodecConfig) -> bool { + let CodecConfig::Pcm(p) = c else { return false }; + let Some(rest) = ff.strip_prefix("pcm_") else { return false }; + let kind = rest.as_bytes()[0]; + let digits: String = rest[1..].chars().take_while(|c| c.is_ascii_digit()).collect(); + let bits: u16 = digits.parse().unwrap_or(0); + let endian = &rest[1 + digits.len()..]; + let kind_ok = match kind { + b'f' => p.float, + b's' => p.signed && !p.float, + b'u' => !p.signed && !p.float, + _ => false, + }; + let endian_ok = match endian { + "le" => !p.big_endian, + "be" => p.big_endian, + _ => true, // 8-bit has no endianness + }; + kind_ok && endian_ok && bits == p.bits +} + +fn check_stream(file: &Mp4File, idx: usize, st: &Value) -> Result<(), String> { + let t = &file.tracks[idx]; + let codec = t.codec().ok_or("no sample entry")?; + let ffname = st["codec_name"].as_str().unwrap_or(""); + let tag = st["codec_tag_string"].as_str().unwrap_or(""); + let entry = &t.entries[0]; + if tag != entry.format.to_string() { + return Err(format!("tag {tag} vs {}", entry.format)); + } + let name_ok = match codec { + CodecConfig::Pcm(_) => pcm_name_matches(ffname, codec), + CodecConfig::Timecode(_) => st["codec_type"] == "data", + c => c.name() == ffname, + }; + if !name_ok { + return Err(format!("codec {ffname} vs {codec:?}")); + } + let tb = format!("1/{}", t.timescale); + if st["time_base"].as_str() != Some(tb.as_str()) { + return Err(format!("time_base {} vs {tb}", st["time_base"])); + } + match t.kind { + TrackKind::Video => { + let v = t.video().ok_or("no video params")?; + if int(&st["width"]) != Some(v.width as i64) || int(&st["height"]) != Some(v.height as i64) { + return Err(format!("size {}x{} vs {}x{}", st["width"], st["height"], v.width, v.height)); + } + if let Some(n) = int(&st["nb_frames"]) + && n != t.samples.len() as i64 + { + return Err(format!("nb_frames {n} vs {}", t.samples.len())); + } + if let CodecConfig::Avc(a) = codec { + if int(&st["level"]) != Some(a.level as i64) { + return Err(format!("level {} vs {}", st["level"], a.level)); + } + if st["nal_length_size"].as_str() != Some(&a.length_size.to_string()) { + return Err("nal_length_size".into()); + } + } + if let Some(cp) = st["color_primaries"].as_str() + && cp == "bt709" + { + match &v.color { + Some(craft_media::isobmff::ColorInfo::Nclx { primaries: 1, .. }) + | Some(craft_media::isobmff::ColorInfo::Nclc { primaries: 1, .. }) => {} + other => return Err(format!("colr {other:?}")), + } + } + if let Some(sar) = st["sample_aspect_ratio"].as_str() + && sar != "1:1" + && sar != "0:1" + { + let (h, vv) = v.pixel_aspect.ok_or("no pasp")?; + let want = format!("{}:{}", h / gcd(h, vv), vv / gcd(h, vv)); + if sar != want { + return Err(format!("sar {sar} vs {want}")); + } + } + } + TrackKind::Audio => { + let a = t.audio().ok_or("no audio params")?; + let sr = int(&st["sample_rate"]).unwrap_or(0); + let ch = int(&st["channels"]).unwrap_or(0); + let (our_sr, our_ch) = match codec { + CodecConfig::Pcm(p) => (p.sample_rate, p.channels), + CodecConfig::Flac(f) => (f.sample_rate as f64, f.channels as u32), + CodecConfig::Opus(o) => (48000.0, o.output_channels as u32), + _ => (a.sample_rate, a.channels), + }; + if sr != our_sr.round() as i64 || ch != our_ch as i64 { + return Err(format!("audio {sr}/{ch} vs {our_sr}/{our_ch}")); + } + if let CodecConfig::Aac(c) = codec + && c.object_type != 2 + { + return Err(format!("aac object type {}", c.object_type)); + } + } + TrackKind::Timecode => { + let CodecConfig::Timecode(tc) = codec else { return Err("tmcd codec".into()) }; + let want = st["tags"]["timecode"].as_str().ok_or("no timecode tag")?; + let got = tc.format_frame(tc.start_frame.ok_or("no start frame")?); + if got != want { + return Err(format!("timecode {got} vs {want}")); + } + } + _ => {} + } + Ok(()) +} + +fn gcd(a: u32, b: u32) -> u32 { + if b == 0 { a.max(1) } else { gcd(b, a % b) } +} + +/// `strict`: ffprobe timestamps must equal ours + edit offset. Otherwise (edit starting mid-frame, +/// which ffmpeg snaps to a frame boundary) only a constant shift within one frame is required. +fn check_packets(file: &Mp4File, idx: usize, pk: &[&Value], strict: bool) -> Result<(), String> { + let t = &file.tracks[idx]; + if t.pcm_chunked { + // ffmpeg re-packetizes raw PCM; compare totals. + let ours: u64 = t.samples.iter().map(|s| s.size as u64).sum(); + let theirs: i64 = pk.iter().filter_map(|p| int(&p["size"])).sum(); + let od: u64 = t.samples.iter().map(|s| s.duration as u64).sum(); + let td: i64 = pk.iter().filter_map(|p| int(&p["duration"])).sum(); + if ours as i64 != theirs || od as i64 != td { + return Err(format!("pcm totals: bytes {ours} vs {theirs}, dur {od} vs {td}")); + } + return Ok(()); + } + if pk.len() != t.samples.len() { + return Err(format!("packet count {} vs {}", pk.len(), t.samples.len())); + } + let e = if strict || pk.is_empty() { + t.edit_offset + } else { + let e = int(&pk[0]["pts"]).unwrap_or(0) - t.samples[0].pts; + let max_dur = t.samples.iter().map(|s| s.duration as i64).max().unwrap_or(0); + if (e - t.edit_offset).abs() >= max_dur { + return Err(format!("shift {e} vs edit offset {}", t.edit_offset)); + } + e + }; + let last = pk.len() - 1; + for (i, (p, s)) in pk.iter().zip(&t.samples).enumerate() { + let size = int(&p["size"]); + let pos = int(&p["pos"]); + let pts = int(&p["pts"]); + let dts = int(&p["dts"]); + let key = p["flags"].as_str().unwrap_or("").starts_with('K'); + // ffmpeg extends the last packet's duration when it carries discard padding. + let ok = size == Some(s.size as i64) + && pos == Some(s.offset as i64) + && pts == Some(s.pts + e) + && dts == Some(s.dts + e) + && key == s.is_sync + && (i == last || int(&p["duration"]).is_none_or(|d| d == s.duration as i64)); + if !ok { + return Err(format!("packet {i}: ffprobe {p} vs ours {s:?} (edit_offset {e})")); + } + } + Ok(()) +} + +fn check_fixture(name: &str) { + let Some(path) = fixture(name) else { return }; + check_file(name, &path); +} + +fn check_file(name: &str, path: &std::path::Path) { + let (Some(streams), Some(packets)) = (streams(path), packets(path)) else { return }; + let f = std::fs::File::open(path).unwrap(); + let file = open(&f).unwrap_or_else(|e| panic!("{name}: open failed: {e}")); + assert_eq!(streams.len(), file.tracks.len(), "{name}: stream count"); + let mut errors = Vec::new(); + for (i, st) in streams.iter().enumerate() { + if let Err(e) = check_stream(&file, i, st) { + errors.push(format!("stream {i}: {e}")); + } + if matches!(file.tracks[i].kind, TrackKind::Video | TrackKind::Audio) { + let pk: Vec<&Value> = packets.iter().filter(|p| int(&p["stream_index"]) == Some(i as i64)).collect(); + if let Err(e) = check_packets(&file, i, &pk, name != "editlist_cut.mp4") { + errors.push(format!("stream {i}: {e}")); + } + } + } + // Every sample must be readable. + for (ti, t) in file.tracks.iter().enumerate() { + for si in [0, t.samples.len() / 2, t.samples.len().saturating_sub(1)] { + if si < t.samples.len() { + let d = file.read_sample(&f, ti, si).unwrap(); + assert_eq!(d.len(), t.samples[si].size as usize); + } + } + } + assert!(errors.is_empty(), "{name}:\n{}", errors.join("\n")); + eprintln!("{name}: ok ({} tracks)", file.tracks.len()); +} + +macro_rules! fixture_tests { + ($($fn:ident => $name:expr),* $(,)?) => { + $(#[test] fn $fn() { check_fixture($name); })* + }; +} + +fixture_tests! { + h264_bframes_mp4 => "h264_bframes.mp4", + h264_mov => "h264.mov", + hevc_mp4 => "hevc.mp4", + prores_mov => "prores.mov", + prores4444_mov => "prores4444.mov", + mjpeg_mov => "mjpeg.mov", + dnxhd_mov => "dnxhd.mov", + pcm_f32_mov => "pcm_f32.mov", + pcm_s16be_mov => "pcm_s16be.mov", + aac_mp4 => "aac.mp4", + aac_m4a => "aac_stereo44.m4a", + frag_mp4 => "frag.mp4", + frag_dash_mp4 => "frag_dash.mp4", + faststart_mp4 => "faststart.mp4", + tmcd_2997df_mov => "tmcd_2997df.mov", + tmcd_23976_mov => "tmcd_23976.mov", + h264_2997_mp4 => "h264_2997.mp4", + flac_mp4 => "flac.mp4", + alac_m4a => "alac.m4a", + opus_mp4 => "opus.mp4", + ac3_mp4 => "ac3.mp4", + vp9_mp4 => "vp9.mp4", + av1_mp4 => "av1.mp4", + colr_pasp_mov => "colr_pasp.mov", + editlist_cut_mp4 => "editlist_cut.mp4", +} + +#[test] +fn specific_properties() { + let Some(p) = fixture("h264_bframes.mp4") else { return }; + let data = std::fs::read(&p).unwrap(); + let f = open(data.as_slice()).unwrap(); + assert!(!f.is_quicktime); + let v = &f.tracks[f.track_of_kind(TrackKind::Video).unwrap()]; + // B-frames → non-trivial composition offsets. + assert!(v.samples.iter().any(|s| s.pts != s.dts)); + assert!(v.samples.iter().filter(|s| s.is_sync).count() >= 4); + let i = v.sample_at_pts(v.samples[7].pts).unwrap(); + assert_eq!(i, 7); + assert_eq!(v.sync_sample_before(13), 12); + let a = &f.tracks[f.track_of_kind(TrackKind::Audio).unwrap()]; + assert_eq!(a.edits.len(), 1); + assert_eq!(a.edit_offset, -1024); + + let Some(p) = fixture("tmcd_2997df.mov") else { return }; + let f = open(std::fs::read(&p).unwrap()).unwrap(); + assert!(f.is_quicktime); + let t = &f.tracks[f.track_of_kind(TrackKind::Timecode).unwrap()]; + let CodecConfig::Timecode(tc) = t.codec().unwrap() else { panic!() }; + assert!(tc.drop_frame()); + assert_eq!(tc.frames_per_second, 30); + assert_eq!(tc.start_frame, Some(107892)); + let v = &f.tracks[f.track_of_kind(TrackKind::Video).unwrap()]; + assert!(v.references.iter().any(|(k, ids)| k.to_string() == "tmcd" && ids == &vec![t.id])); +} + +/// Pre-generate every fixture (`cargo test -p craft-media --all-features -- --ignored generate_fixtures`). +#[test] +#[ignore] +fn generate_fixtures() { + for name in all_fixture_names() { + let out = [fixture_dir().join(name)]; + common::generate_and_report(&format!("isobmff/{name}"), &out, || fixture(name)); + } +} + +/// A generator that exits with failure: this test binary given an option libtest rejects. +fn failing_generator() -> std::process::Command { + let mut c = std::process::Command::new(std::env::current_exe().unwrap()); + c.arg("--craft-media-no-such-option"); + c +} + +#[test] +#[should_panic(expected = "forbids skipping")] +fn required_oracles_fail_on_generator_failure() { + let out = fixture_dir().join("generator_failure_required.mp4"); + let _ = run_generator(&mut failing_generator(), &temp_path(&out), &out, true); +} + +#[test] +fn optional_oracles_skip_on_generator_failure() { + let out = fixture_dir().join("generator_failure_optional.mp4"); + assert_eq!(run_generator(&mut failing_generator(), &temp_path(&out), &out, false), None); + let mut missing = std::process::Command::new("craft-media-no-such-generator"); + assert_eq!(run_generator(&mut missing, &temp_path(&out), &out, false), None); + assert!(!out.exists()); +} + +#[test] +fn a_failed_ffprobe_probe_skips_the_optional_check() { + let path = out_dir().join("ffprobe_failure.mp4"); + std::fs::write(&path, b"not a media file").unwrap(); + let result = std::panic::catch_unwind(|| check_file("ffprobe_failure.mp4", &path)); + let _ = std::fs::remove_file(&path); + match result { + Ok(()) => assert!(!oracles_required()), + Err(e) => { + let msg = e.downcast_ref::().cloned().unwrap_or_default(); + assert!(oracles_required() && msg.contains("forbids skipping"), "{msg}"); + } + } +} diff --git a/crates/media/tests/oracle_matroska.rs b/crates/media/tests/oracle_matroska.rs new file mode 100644 index 0000000000..d46198034e --- /dev/null +++ b/crates/media/tests/oracle_matroska.rs @@ -0,0 +1,383 @@ +//! Oracle tests: compare our demuxer's packets, timestamps, keyframes and track parameters with +//! ffprobe on ffmpeg-generated fixtures (skipped when ffmpeg/ffprobe are not installed). + +mod common; +#[path = "common/matroska.rs"] +mod mkv; + +use craft_media::matroska::*; +use mkv::*; +use serde_json::Value; +use std::path::Path; + +/// Compare every packet (file order) and stream parameter against ffprobe. +fn compare(ffprobe: &Path, path: &Path) -> (MkvFile, Vec) { + let json = ffprobe_json(ffprobe, path); + let bytes = std::fs::read(path).unwrap(); + let mut d = Demuxer::from_slice(&bytes).unwrap(); + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let file = d.file().clone(); + let streams = json["streams"].as_array().unwrap(); + assert_eq!(streams.len(), file.tracks.len(), "{name}: stream count"); + for (i, st) in streams.iter().enumerate() { + let t = &file.tracks[i]; + assert_eq!(st["codec_name"].as_str().unwrap_or(""), t.codec.name(), "{name}: track {i} codec ({})", t.codec_id); + assert_eq!(st["time_base"].as_str(), Some(format!("{}/{}", t.timebase.0, t.timebase.1).as_str()), "{name}: time_base"); + match t.kind { + TrackKind::Video => { + let v = t.video.as_ref().unwrap(); + assert_eq!(int(&st["width"]), Some(v.pixel_width as i64), "{name}: width"); + assert_eq!(int(&st["height"]), Some(v.pixel_height as i64), "{name}: height"); + } + TrackKind::Audio => { + let a = t.audio.as_ref().unwrap(); + assert_eq!(int(&st["sample_rate"]), Some(a.sampling_frequency as i64), "{name}: sample_rate"); + assert_eq!(int(&st["channels"]), Some(a.channels as i64), "{name}: channels"); + } + _ => {} + } + } + let packets: Vec = d.by_ref().collect::>().unwrap(); + let ff = json["packets"].as_array().unwrap(); + assert_eq!(packets.len(), ff.len(), "{name}: packet count"); + let (mut pts_checked, mut dur_checked) = (0, 0); + for (i, (p, f)) in packets.iter().zip(ff).enumerate() { + let ctx = format!("{name}: packet {i} (track {})", p.track); + assert_eq!(int(&f["stream_index"]), Some(p.track as i64), "{ctx}: stream"); + if file.tracks[p.track].codec_id.starts_with("D_WEBVTT") { + // WebM WebVTT blocks carry "id\nsettings\npayload"; FFmpeg moves id/settings to side data + assert!(p.data.len() as i64 >= int(&f["size"]).unwrap(), "{ctx}: size"); + } else { + assert_eq!(int(&f["size"]), Some(p.data.len() as i64), "{ctx}: size"); + } + let key = f["flags"].as_str().unwrap_or("").starts_with('K'); + assert_eq!(key, p.keyframe, "{ctx}: keyframe"); + if let Some(pts) = int(&f["pts"]) + && !(p.lace > 0 && p.duration == 0) + { + // FFmpeg truncates the per-lace duration to whole ticks; we place laces exactly + // (rounded once), so later laces may differ by up to one tick per lace. + assert!((pts - p.pts).abs() <= p.lace as i64, "{ctx}: pts ffprobe {pts} vs {}", p.pts); + pts_checked += 1; + } + // The last audio or video frame of a track cut by `-t` is shorter than a codec frame. + // ffmpeg 8 writes a shortened BlockDuration there and reports the codec frame duration; a + // remux by our writer stores DefaultDuration and ffprobe reports the shortened one. So + // that frame's duration is not compared. A subtitle's duration is its cue's, and is. + let last_of_track = packets[i + 1..].iter().all(|q| q.track != p.track); + if let Some(dur) = int(&f["duration"]) + && p.duration != 0 + && (!last_of_track || file.tracks[p.track].kind == TrackKind::Subtitle) + { + assert!((dur - p.duration as i64).abs() <= 1, "{ctx}: duration ffprobe {dur} vs {}", p.duration); + dur_checked += 1; + } + } + assert!(pts_checked > 0, "{name}: no pts compared"); + eprintln!("{name}: {} packets, {pts_checked} pts and {dur_checked} durations compared", packets.len()); + // the sample index agrees with the packet stream + for (ti, t) in file.tracks.iter().enumerate() { + let pk: Vec<&Packet> = packets.iter().filter(|p| p.track == ti).collect(); + assert_eq!(t.samples.len(), pk.len(), "{name}: index size track {ti}"); + for (i, p) in pk.iter().enumerate() { + assert_eq!(t.samples[i].pts, p.pts); + assert_eq!(t.samples[i].keyframe, p.keyframe); + assert_eq!(t.sample_size(i), Some(p.data.len() as u64)); + } + if let Some(i) = pk.len().checked_sub(1) { + assert_eq!(file.read_sample(&bytes[..], ti, i).unwrap(), pk[i].data); + } + } + // duration + if let Some(fd) = json["format"]["duration"].as_str().and_then(|s| s.parse::().ok()) + && let Some(ours) = file.duration_ns() + { + assert!((fd - ours as f64 / 1e9).abs() < 0.05, "{name}: duration {fd} vs {ours}"); + } + (file, packets) +} + +/// Seek to a range of times on `track` and check we land on the latest keyframe ≤ target. +fn check_seeks(bytes: &[u8], opts: OpenOptions, track: usize, packets: &[Packet]) { + let mut d = Demuxer::with_options(bytes, opts).unwrap(); + let keys: Vec<(i64, i64)> = packets.iter().filter(|p| p.track == track && p.keyframe).map(|p| (p.pts, p.pts_ns)).collect(); + let last = packets.iter().filter(|p| p.track == track).map(|p| p.pts_ns).max().unwrap(); + let mut t = 0i64; + while t <= last + 100_000_000 { + let sp = d.seek(track, t).unwrap(); + let expect = keys.iter().filter(|k| k.1 <= t).map(|k| k.0).max().unwrap_or(keys[0].0); + assert_eq!(sp.pts, expect, "seek to {t}ns"); + assert!(sp.pts_ns <= t || sp.pts == keys[0].0); + // the first packet of that track after seeking is the keyframe + let p = loop { + let p = d.next_packet().unwrap().expect("packet after seek"); + if p.track == track { + break p; + } + }; + assert!(p.keyframe); + assert_eq!(p.pts, sp.pts); + t += 137_000_000; + } +} + +fn run(name: &str) -> Option<(Vec, MkvFile, Vec)> { + let (ffmpeg, ffprobe) = tools()?; + let path = fixture(&ffmpeg, name)?; + let (file, packets) = compare(&ffprobe, &path); + let bytes = std::fs::read(&path).unwrap(); + Some((bytes, file, packets)) +} + +#[test] +fn h264_aac() { + let Some((bytes, f, packets)) = run("h264_aac.mkv") else { return }; + assert_eq!(f.doc_type, "matroska"); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + let v = f.track_of_kind(TrackKind::Video).unwrap(); + let Codec::Avc { avcc } = &f.tracks[v].codec else { panic!("not avc") }; + assert_eq!(avcc[0], 1, "avcC version"); + let a = f.track_of_kind(TrackKind::Audio).unwrap(); + assert!(matches!(&f.tracks[a].codec, Codec::Aac { asc } if asc.len() >= 2)); + assert!(!f.cues.is_empty()); + assert!(!f.seek_head.is_empty()); + check_seeks(&bytes, OpenOptions::default(), v, &packets); + check_seeks(&bytes, OpenOptions { index: false, verify_crc: false }, v, &packets); + check_seeks(&bytes, OpenOptions::default(), a, &packets); + // Read + Seek entry point and CRC verification (ffmpeg writes CRC-32 in level-1 elements) + let d = Demuxer::from_reader(std::io::Cursor::new(bytes.clone())).unwrap(); + assert_eq!(d.file().tracks.len(), 2); + let crc = open_with(&bytes[..], &OpenOptions { index: true, verify_crc: true }).unwrap(); + assert!(crc.crc_checked > 0); + assert!(crc.crc_errors.is_empty()); + let kf = Demuxer::from_slice(&bytes).unwrap().keyframe_index(v).unwrap(); + assert_eq!(kf.len(), packets.iter().filter(|p| p.track == v && p.keyframe).count()); +} + +#[test] +fn vp9_opus_webm() { + let Some((bytes, f, packets)) = run("vp9_opus.webm") else { return }; + assert!(f.is_webm()); + let a = f.track_of_kind(TrackKind::Audio).unwrap(); + let t = &f.tracks[a]; + assert!(matches!(&t.codec, Codec::Opus { head } if head.starts_with(b"OpusHead"))); + assert!(t.codec_delay_ns > 0 && t.seek_pre_roll_ns > 0); + assert!(packets.iter().any(|p| p.track == a && p.pts < 0), "codec delay applied"); + let v = f.track_of_kind(TrackKind::Video).unwrap(); + assert!(matches!(f.tracks[v].codec, Codec::Vp9 { .. })); + check_seeks(&bytes, OpenOptions::default(), v, &packets); + check_seeks(&bytes, OpenOptions { index: false, verify_crc: false }, v, &packets); +} + +#[test] +fn flac() { + let Some((_, f, _)) = run("flac.mkv") else { return }; + assert!(matches!(&f.tracks[0].codec, Codec::Flac { private } if private.starts_with(b"fLaC"))); +} + +#[test] +fn vorbis() { + let Some((_, f, _)) = run("vorbis.mkv") else { return }; + let Codec::Vorbis { headers } = &f.tracks[0].codec else { panic!("not vorbis") }; + assert_eq!(headers.len(), 3); + assert_eq!(&headers[0][..7], b"\x01vorbis"); + assert_eq!(&headers[1][..7], b"\x03vorbis"); + assert_eq!(&headers[2][..7], b"\x05vorbis"); +} + +#[test] +fn subtitles() { + let Some((_, f, packets)) = run("subs.mkv") else { return }; + let subs: Vec = (0..f.tracks.len()).filter(|&i| f.tracks[i].kind == TrackKind::Subtitle).collect(); + assert_eq!(subs.len(), 2); + assert_eq!(f.tracks[subs[0]].codec, Codec::SubRip); + assert_eq!(f.tracks[subs[0]].language, "fre"); + assert!(matches!(&f.tracks[subs[1]].codec, Codec::Ass { header, ssa: false } if !header.is_empty())); + assert_eq!(f.tracks[subs[1]].name, "Styled"); + let first = packets.iter().find(|p| p.track == subs[0]).unwrap(); + assert_eq!(first.data, b"Hello"); + assert_eq!((first.pts, first.duration), (200, 700)); +} + +#[test] +fn webvtt_webm() { + let Some((_, f, packets)) = run("webvtt.webm") else { return }; + let s = f.track_of_kind(TrackKind::Subtitle).unwrap(); + assert_eq!(f.tracks[s].codec, Codec::WebVtt); + let cues: Vec<&Packet> = packets.iter().filter(|p| p.track == s).collect(); + assert_eq!(cues.len(), 2); + assert!(cues[0].data.ends_with(b"Hello")); +} + +#[test] +fn cues_at_front() { + let Some((bytes, f, packets)) = run("cues_front.mkv") else { return }; + assert!(!f.cues.is_empty()); + assert!(f.clusters.len() >= 5); + let v = f.track_of_kind(TrackKind::Video).unwrap(); + check_seeks(&bytes, OpenOptions { index: false, verify_crc: false }, v, &packets); +} + +#[test] +fn live_stream_without_cues() { + let Some((bytes, f, packets)) = run("live.mkv") else { return }; + assert!(f.cues.is_empty(), "streamed output has no Cues"); + assert!(f.live || f.info.duration.is_none()); + assert!(f.duration_ns().unwrap() > 1_900_000_000); + let v = f.track_of_kind(TrackKind::Video).unwrap(); + // no cues: seeking builds the index by scanning clusters + check_seeks(&bytes, OpenOptions { index: false, verify_crc: false }, v, &packets); + let mut d = Demuxer::with_options(&bytes[..], OpenOptions { index: false, verify_crc: false }).unwrap(); + assert!(!d.file().indexed); + assert!(!d.keyframe_index(v).unwrap().is_empty()); + assert!(d.file().indexed); +} + +#[test] +fn hevc_hdr_color() { + let Some((_, f, _)) = run("hevc_hdr.mkv") else { return }; + let t = &f.tracks[0]; + assert!(matches!(&t.codec, Codec::Hevc { hvcc } if hvcc.first() == Some(&1))); + let c = t.video.as_ref().unwrap().color.as_ref().expect("Colour element"); + assert_eq!(c.primaries, Some(9)); + assert_eq!(c.transfer_characteristics, Some(16)); + assert_eq!(c.matrix_coefficients, Some(9)); + assert_eq!(c.range, Some(1)); + // mastering metadata / CLL are written by ffmpeg from stream side data when available + if let Some(m) = &c.mastering { + assert!((m.primaries[1].0 - 0.265).abs() < 1e-3, "{m:?}"); + assert!((m.luminance_max - 1000.0).abs() < 1e-3); + } + if let Some(cll) = c.max_cll { + assert_eq!(cll, 1000); + } +} + +#[test] +fn prores_pcm() { + let Some((_, f, _)) = run("prores_pcm.mkv") else { return }; + let a = f.track_of_kind(TrackKind::Audio).unwrap(); + assert_eq!(f.tracks[a].codec, Codec::Pcm { float: false, big_endian: false, bits: 24 }); +} + +#[test] +fn mjpeg_ac3() { + let Some((_, f, _)) = run("mjpeg_ac3.mkv") else { return }; + assert_eq!(f.info.title.as_deref(), Some("craft-media test")); + assert!(f.info.muxing_app.starts_with("Lavf")); + assert!(f.tags.iter().flat_map(|t| &t.simple).any(|s| s.name == "ENCODER")); +} + +#[test] +fn av1() { + let Some((_, f, _)) = run("av1.mkv") else { return }; + assert!(matches!(&f.tracks[0].codec, Codec::Av1 { av1c } if av1c.first() == Some(&0x81))); +} + +/// Re-mux a fixture with our writer using each lacing mode; ffprobe must read the result identically +/// to our demuxer (and to the source packets). +#[test] +fn laced_remux() { + let Some((ffmpeg, ffprobe)) = tools() else { return }; + for (src, modes) in [ + ("vorbis.mkv", &[LacingMode::Xiph, LacingMode::Ebml][..]), + ("h264_aac.mkv", &[LacingMode::Ebml, LacingMode::Xiph][..]), + ("prores_pcm.mkv", &[LacingMode::FixedOrEbml][..]), + ("flac.mkv", &[LacingMode::Ebml][..]), + ] { + let Some(path) = fixture(&ffmpeg, src) else { continue }; + let bytes = std::fs::read(&path).unwrap(); + let d = Demuxer::from_slice(&bytes).unwrap(); + let file = d.file().clone(); + let packets: Vec = d.collect::>().unwrap(); + for &mode in modes { + let specs: Vec = file + .tracks + .iter() + .enumerate() + .map(|(ti, t)| { + let mut s = TrackSpec::new(t.kind, t.codec_id.clone()); + s.codec_private = t.codec_private.clone(); + // audio without a DefaultDuration gets its mean packet spacing, so it can lace + s.default_duration_ns = t.default_duration_ns.or_else(|| { + let pts: Vec = packets.iter().filter(|p| p.track == ti).map(|p| p.pts_ns).collect(); + (t.kind == TrackKind::Audio && pts.len() > 1).then(|| ((pts[pts.len() - 1] - pts[0]) / (pts.len() as i64 - 1)) as u64) + }); + s.video_size = t.video.as_ref().map(|v| (v.pixel_width, v.pixel_height)); + s.audio = t.audio.as_ref().map(|a| (a.sampling_frequency, a.channels, a.bit_depth)); + s.codec_delay_ns = t.codec_delay_ns; + s + }) + .collect(); + let opts = MuxOptions { lacing: mode, ..Default::default() }; + let mut w = MkvWriter::new(std::io::Cursor::new(Vec::new()), specs, opts).unwrap(); + for p in &packets { + w.write_frame(p.track, p.pts_ns, p.keyframe, &p.data, None).unwrap(); + } + let out = w.finish().unwrap().into_inner(); + let laced = { + let f = open(&out[..]).unwrap(); + f.tracks.iter().any(|t| t.samples.iter().any(|s| s.lace > 0)) + }; + assert!(laced, "{src} {mode:?}: nothing was laced"); + let outp = fixture_dir().join(format!("remux_{mode:?}_{src}")); + std::fs::write(&outp, &out).unwrap(); + let (_, got) = compare(&ffprobe, &outp); + assert_eq!(got.len(), packets.len()); + for (a, b) in got.iter().zip(&packets) { + assert_eq!(a.data, b.data, "{src} {mode:?}: payload"); + assert_eq!((a.track, a.pts), (b.track, b.pts), "{src} {mode:?}: timestamp"); + } + std::fs::remove_file(&outp).unwrap(); + } + } +} + +/// Damaged file: overwrite bytes in the middle of the clusters; the demuxer must not fail and must +/// resync on a later cluster. +#[test] +fn damaged_resync() { + let Some((mut bytes, f, packets)) = run("h264_aac.mkv") else { return }; + let mid = f.clusters[f.clusters.len() / 2]; + let at = mid.data_start as usize + 40; + for b in &mut bytes[at..at + 200] { + *b = 0x00; + } + let d = Demuxer::from_slice(&bytes).unwrap(); + assert!(!d.file().warnings.is_empty()); + let got: Vec = d.collect::>().unwrap(); + assert!(got.len() < packets.len()); + assert!(got.len() > packets.len() / 2); + // packets after the damaged cluster are intact + let last = packets.last().unwrap(); + assert_eq!(got.last().unwrap(), last); + // truncated file + let cut = &bytes[..bytes.len() * 2 / 3]; + let d = Demuxer::from_slice(cut).unwrap(); + let got: Vec = d.collect::>().unwrap(); + assert!(!got.is_empty()); + // garbage never panics + for n in [0usize, 10, 100, 1000] { + let _ = Demuxer::from_slice(&bytes[..n.min(bytes.len())]).map(|d| d.count()); + } +} + +#[test] +fn not_matroska() { + assert!(matches!(open(&b"hello world"[..]), Err(Error::NotMatroska(_)))); + let mut ebml = vec![0x1A, 0x45, 0xDF, 0xA3, 0x84, 0x42, 0x82, 0x81, b'x']; + ebml.extend_from_slice(&[0; 8]); + assert!(matches!(open(&ebml[..]), Err(Error::NotMatroska(_)))); + let _ = Value::Null; +} + +/// Pre-generate every fixture (`cargo test -p craft-media --all-features -- --ignored generate_fixtures`). +#[test] +#[ignore] +fn generate_fixtures() { + let Some((ffmpeg, _)) = tools() else { return }; + for name in ALL_FIXTURES { + let out = [fixture_dir().join(name)]; + common::generate_and_report(&format!("matroska/{name}"), &out, || fixture(&ffmpeg, name)); + } +} diff --git a/crates/media/tests/oracle_mux.rs b/crates/media/tests/oracle_mux.rs new file mode 100644 index 0000000000..9a235884d4 --- /dev/null +++ b/crates/media/tests/oracle_mux.rs @@ -0,0 +1,268 @@ +//! Muxer oracle tests: remux ffmpeg-made files with our writers and validate with ffmpeg/ffprobe. + +mod common; + +use common::*; +use craft_media::isobmff::*; +use serde_json::Value; +use std::io::Cursor; +use std::path::{Path, PathBuf}; + +/// All samples of all tracks in decode order interleaved by decode time: (track, sample index). +fn interleave(f: &Mp4File, tracks: &[usize]) -> Vec<(usize, usize)> { + let mut v: Vec<(usize, usize)> = tracks.iter().flat_map(|&t| (0..f.tracks[t].samples.len()).map(move |i| (t, i))).collect(); + v.sort_by(|a, b| { + let ta = &f.tracks[a.0]; + let tb = &f.tracks[b.0]; + let x = ta.samples[a.1].dts as i128 * tb.timescale as i128; + let y = tb.samples[b.1].dts as i128 * ta.timescale as i128; + x.cmp(&y).then(a.0.cmp(&b.0)).then(a.1.cmp(&b.1)) + }); + v +} + +fn track_config(f: &Mp4File, t: &Track, copy_edits: bool) -> TrackConfig { + let mut cfg = TrackConfig::new(t.entries[0].clone(), t.timescale); + cfg.language = t.language.clone(); + if copy_edits { + cfg.edits = t.edits.clone(); + } + let _ = f; + cfg +} + +enum Finish { + Normal, + Faststart, +} + +fn remux(input: &Path, out_name: &str, brand: Brand, finish: Finish, timecode: Option<(TimecodeConfig, u32)>) -> Option<(Mp4File, PathBuf)> { + let data = std::fs::read(input).ok()?; + let f = open(data.as_slice()).unwrap(); + let mut opts = WriterOptions::new(brand); + opts.movie_timescale = f.timescale; + opts.metadata.push(("©nam".into(), "FilmCraft test".into())); + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), opts).unwrap(); + let av: Vec = (0..f.tracks.len()).filter(|&i| matches!(f.tracks[i].kind, TrackKind::Video | TrackKind::Audio)).collect(); + let mut map = vec![usize::MAX; f.tracks.len()]; + for &i in &av { + map[i] = w.add_track(track_config(&f, &f.tracks[i], true)).unwrap(); + } + if let Some((tc, start)) = timecode { + let v = av.iter().copied().find(|&i| f.tracks[i].kind == TrackKind::Video).unwrap(); + w.add_timecode_track(map[v], tc, start).unwrap(); + } + for (t, i) in interleave(&f, &av) { + let s = f.tracks[t].samples[i]; + let bytes = f.read_sample(data.as_slice(), t, i).unwrap(); + w.write_sample(map[t], WriteSample { data: &bytes, duration: s.duration, composition_offset: (s.pts - s.dts) as i32, is_sync: s.is_sync }) + .unwrap(); + } + let out = match finish { + Finish::Normal => w.finish(), + Finish::Faststart => w.finish_faststart(), + } + .unwrap() + .into_inner(); + let path = out_dir().join(out_name); + std::fs::write(&path, &out).unwrap(); + // Our own reader must see identical sample tables and bytes. + let g = open(out.as_slice()).unwrap(); + for (k, &i) in av.iter().enumerate() { + let (a, b) = (&f.tracks[i], &g.tracks[k]); + assert_eq!(a.samples.len(), b.samples.len(), "{out_name}: sample count"); + assert_eq!(a.edit_offset, b.edit_offset, "{out_name}: edit offset"); + assert_eq!(a.codec(), b.codec(), "{out_name}: codec"); + for (j, (x, y)) in a.samples.iter().zip(&b.samples).enumerate() { + assert_eq!((x.size, x.dts, x.pts, x.duration, x.is_sync), (y.size, y.dts, y.pts, y.duration, y.is_sync), "{out_name}: sample {j}"); + } + for j in 0..a.samples.len() { + assert_eq!(f.read_sample(data.as_slice(), i, j).unwrap(), g.read_sample(out.as_slice(), k, j).unwrap()); + } + } + assert_eq!(g.metadata.title(), Some("FilmCraft test")); + Some((f, path)) +} + +fn stream_packets(path: &Path) -> Option>> { + let pk = packets(path)?; + let n = pk.iter().filter_map(|p| int(&p["stream_index"])).max().map(|m| m + 1).unwrap_or(0); + Some((0..n).map(|i| pk.iter().filter(|p| int(&p["stream_index"]) == Some(i)).cloned().collect()).collect()) +} + +/// Compare ffprobe's view of two files (per-stream packets: pts, dts, size, key flag). +fn assert_same_packets(a: &Path, b: &Path) { + let (Some(pa), Some(pb)) = (stream_packets(a), stream_packets(b)) else { return }; + for (i, (x, y)) in pa.iter().zip(&pb).enumerate() { + let key = |p: &Value| (int(&p["pts"]), int(&p["dts"]), int(&p["size"]), p["flags"].as_str().map(|f| f.starts_with('K'))); + let kx: Vec<_> = x.iter().map(key).collect(); + let ky: Vec<_> = y.iter().map(key).collect(); + assert_eq!(kx.len(), ky.len(), "stream {i}: packet count {} vs {}", a.display(), b.display()); + for (j, (p, q)) in kx.iter().zip(&ky).enumerate() { + assert_eq!(p, q, "stream {i} packet {j}"); + } + } +} + +fn assert_same_streams(a: &Path, b: &Path) { + let (Some(sa), Some(sb)) = (streams(a), streams(b)) else { return }; + for (x, y) in sa.iter().zip(&sb) { + if x["codec_type"] == "data" { + continue; + } + for k in ["codec_name", "width", "height", "sample_rate", "channels", "nb_frames", "duration_ts", "time_base", "profile", "pix_fmt"] { + assert_eq!(x[k], y[k], "stream field {k}"); + } + } +} + +fn decode_clean(path: &Path) { + let err = ffmpeg_decode_errors(path).unwrap(); + assert!(err.trim().is_empty(), "ffmpeg reported errors for {}: {err}", path.display()); +} + +#[test] +fn remux_h264_aac_mp4_variants() { + let (Some(src), Some(_)) = (fixture("h264_bframes.mp4"), ffprobe()) else { return }; + for (name, brand, finish) in [ + ("remux_h264_aac.mp4", Brand::Mp4, Finish::Normal), + ("remux_h264_aac_fast.mp4", Brand::Mp4, Finish::Faststart), + ("remux_h264_aac.mov", Brand::Mov, Finish::Normal), + ] { + let (_, out) = remux(&src, name, brand, finish, None).unwrap(); + decode_clean(&out); + assert_same_packets(&src, &out); + assert_same_streams(&src, &out); + eprintln!("{name}: ok"); + } + // Faststart layout: moov before mdat. + let d = std::fs::read(out_dir().join("remux_h264_aac_fast.mp4")).unwrap(); + let moov = d.windows(4).position(|w| w == b"moov").unwrap(); + let mdat = d.windows(4).position(|w| w == b"mdat").unwrap(); + assert!(moov < mdat); +} + +#[test] +fn remux_other_codecs() { + if ffprobe().is_none() { + return; + } + for (src, name, brand) in [ + ("hevc.mp4", "remux_hevc.mp4", Brand::Mp4), + ("h264.mov", "remux_h264_pcm.mov", Brand::Mov), + ("mjpeg.mov", "remux_mjpeg.mov", Brand::Mov), + ("pcm_f32.mov", "remux_pcm_f32.mov", Brand::Mov), + ("pcm_s16be.mov", "remux_pcm_s16be.mov", Brand::Mov), + ("aac_stereo44.m4a", "remux_aac.m4a", Brand::Mp4), + ("colr_pasp.mov", "remux_colr_pasp.mov", Brand::Mov), + ("editlist_cut.mp4", "remux_editlist.mp4", Brand::Mp4), + ("alac.m4a", "remux_alac.m4a", Brand::Mp4), + ("flac.mp4", "remux_flac.mp4", Brand::Mp4), + ("opus.mp4", "remux_opus.mp4", Brand::Mp4), + ("av1.mp4", "remux_av1.mp4", Brand::Mp4), + ("vp9.mp4", "remux_vp9.mp4", Brand::Mp4), + ("ac3.mp4", "remux_ac3.mp4", Brand::Mp4), + ("dnxhd.mov", "remux_dnxhd.mov", Brand::Mov), + ] { + let Some(p) = fixture(src) else { continue }; + let (f, out) = remux(&p, name, brand, Finish::Faststart, None).unwrap(); + decode_clean(&out); + let pcm = f.tracks.iter().any(|t| t.pcm_chunked); + if !pcm { + assert_same_packets(&p, &out); + } + assert_same_streams(&p, &out); + eprintln!("{name}: ok"); + } +} + +#[test] +fn remux_prores_pcm24_with_timecode() { + let (Some(src), Some(_)) = (fixture("prores.mov"), ffprobe()) else { return }; + let tc = TimecodeConfig { flags: 0, timescale: 25, frame_duration: 1, frames_per_second: 25, start_frame: None, name: None }; + let (f, out) = remux(&src, "remux_prores_tc.mov", Brand::Mov, Finish::Normal, Some((tc, 25 * 3600))).unwrap(); + decode_clean(&out); + assert_same_streams(&src, &out); + let Some(st) = streams(&out) else { return }; + assert!(st.iter().any(|s| s["tags"]["timecode"] == "01:00:00:00"), "timecode missing: {st:?}"); + // PCM byte totals survive ffmpeg's repacketization. + let g = open(std::fs::read(&out).unwrap()).unwrap(); + let a = f.track_of_kind(TrackKind::Audio).unwrap(); + let sum = |m: &Mp4File, i: usize| m.tracks[i].samples.iter().map(|s| s.size as u64).sum::(); + assert_eq!(sum(&f, a), sum(&g, g.track_of_kind(TrackKind::Audio).unwrap())); + let t = &g.tracks[g.track_of_kind(TrackKind::Timecode).unwrap()]; + let CodecConfig::Timecode(tc) = t.codec().unwrap() else { panic!() }; + assert_eq!(tc.start_frame, Some(90000)); +} + +#[test] +fn pcm_in_mp4_ipcm() { + let (Some(src), Some(_)) = (fixture("pcm_s16be.mov"), ffprobe()) else { return }; + let (_, out) = remux(&src, "remux_ipcm.mp4", Brand::Mp4, Finish::Normal, None).unwrap(); + let Some(st) = streams(&out) else { return }; + assert_eq!(st[0]["codec_tag_string"], "ipcm"); + assert_eq!(st[0]["codec_name"], "pcm_s16be"); + decode_clean(&out); +} + +#[test] +fn aac_priming_edit() { + let (Some(src), Some(_)) = (fixture("aac.mp4"), ffprobe()) else { return }; + let data = std::fs::read(&src).unwrap(); + let f = open(data.as_slice()).unwrap(); + let t = &f.tracks[0]; + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap(); + let mut cfg = TrackConfig::new(t.entries[0].clone(), t.timescale); + cfg.media_start = Some(1024); + let k = w.add_track(cfg).unwrap(); + for (i, s) in t.samples.iter().enumerate() { + let d = f.read_sample(data.as_slice(), 0, i).unwrap(); + w.write_sample(k, WriteSample { data: &d, duration: s.duration, composition_offset: 0, is_sync: true }).unwrap(); + } + let out = out_dir().join("aac_priming.mp4"); + std::fs::write(&out, w.finish().unwrap().into_inner()).unwrap(); + decode_clean(&out); + let (Some(pk), Some(so), Some(ss)) = (packets(&out), streams(&out), streams(&src)) else { return }; + assert_eq!(int(&pk[0]["pts"]), Some(-1024)); + assert_eq!(int(&so[0]["duration_ts"]), int(&ss[0]["duration_ts"])); +} + +#[test] +fn fragmented_writer_ffmpeg() { + let (Some(src), Some(_)) = (fixture("h264_bframes.mp4"), ffprobe()) else { return }; + let data = std::fs::read(&src).unwrap(); + let f = open(data.as_slice()).unwrap(); + let mut w = FragmentedWriter::new(Vec::new(), WriterOptions::new(Brand::Mp4)); + let tracks: Vec = (0..f.tracks.len()).collect(); + for t in &f.tracks { + w.add_track(TrackConfig::new(t.entries[0].clone(), t.timescale)).unwrap(); + } + let v = f.track_of_kind(TrackKind::Video).unwrap(); + for (t, i) in interleave(&f, &tracks) { + let s = f.tracks[t].samples[i]; + if t == v && s.is_sync && i > 0 { + w.flush_fragment().unwrap(); + } + let d = f.read_sample(data.as_slice(), t, i).unwrap(); + w.write_sample(t, WriteSample { data: &d, duration: s.duration, composition_offset: (s.pts - s.dts) as i32, is_sync: s.is_sync }).unwrap(); + } + let bytes = w.finish().unwrap(); + let out = out_dir().join("our_frag.mp4"); + std::fs::write(&out, &bytes).unwrap(); + decode_clean(&out); + let g = open(bytes.as_slice()).unwrap(); + assert!(g.fragmented && g.fragment_count >= 4); + // ffprobe sees raw timestamps (no edit list in our init segment). + let Some(ours) = stream_packets(&out) else { return }; + for (ti, t) in f.tracks.iter().enumerate() { + assert_eq!(ours[ti].len(), t.samples.len()); + for (p, s) in ours[ti].iter().zip(&t.samples) { + assert_eq!(int(&p["pts"]), Some(s.pts)); + assert_eq!(int(&p["dts"]), Some(s.dts)); + assert_eq!(int(&p["size"]), Some(s.size as i64)); + } + for i in 0..t.samples.len() { + assert_eq!(f.read_sample(data.as_slice(), ti, i).unwrap(), g.read_sample(bytes.as_slice(), ti, i).unwrap()); + } + } +} diff --git a/crates/media/tests/roundtrip.proptest-regressions b/crates/media/tests/roundtrip.proptest-regressions new file mode 100644 index 0000000000..645fba0771 --- /dev/null +++ b/crates/media/tests/roundtrip.proptest-regressions @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 2f1e39c31dcb71e2f413c6f8046cb8976a8d51bab762a3d6cecce91feeda3a96 # shrinks to tracks = [(0, [S { size: 0, duration: 1, cto: 0, sync: false }])], order = [], mov = false, fast = false, with_pcm = false, start = None diff --git a/crates/media/tests/roundtrip.rs b/crates/media/tests/roundtrip.rs new file mode 100644 index 0000000000..95fc88e346 --- /dev/null +++ b/crates/media/tests/roundtrip.rs @@ -0,0 +1,223 @@ +//! Property tests: write with our muxers, read back, compare sample tables and bytes. + +use craft_media::isobmff::*; +use proptest::prelude::*; +use std::io::Cursor; + +#[derive(Clone, Debug)] +struct S { + size: usize, + duration: u32, + cto: i32, + sync: bool, +} + +fn sample_strategy() -> impl Strategy { + (0usize..300, 1u32..3000, -200i32..2000, any::()).prop_map(|(size, duration, cto, sync)| S { size, duration, cto, sync }) +} + +fn payload(track: usize, i: usize, n: usize) -> Vec { + (0..n).map(|k| (track * 31 + i * 7 + k) as u8).collect() +} + +fn entry(kind: u8) -> SampleEntry { + match kind { + 0 => SampleEntry::avc(AvcConfig::new(vec![vec![0x67, 0x64, 0, 0x28, 1, 2]], vec![vec![0x68, 3]], 4), 320, 240), + 1 => SampleEntry::prores(FourCc(*b"apcn"), 1920, 1080), + 2 => SampleEntry::aac(vec![0x11, 0x90], 2, 48000), + _ => SampleEntry::jpeg(64, 64), + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + #[test] + fn progressive_roundtrip( + tracks in prop::collection::vec((0u8..4, prop::collection::vec(sample_strategy(), 0..40)), 1..4), + order in prop::collection::vec(0usize..4, 0..200), + mov in any::(), + fast in any::(), + with_pcm in any::(), + start in prop::option::of(0i64..500), + ) { + let brand = if mov { Brand::Mov } else { Brand::Mp4 }; + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(brand)).unwrap(); + for (k, (kind, _)) in tracks.iter().enumerate() { + let mut cfg = TrackConfig::new(entry(*kind), 1000 + k as u32 * 11); + cfg.media_start = start; + w.add_track(cfg).unwrap(); + } + let pcm_track = if with_pcm { + let p = PcmConfig { bits: 24, float: false, big_endian: false, signed: true, channels: 2, sample_rate: 48000.0 }; + Some(w.add_track(TrackConfig::new(SampleEntry::pcm(p), 48000)).unwrap()) + } else { None }; + // Interleave: follow `order`, then flush the rest. + let mut next = vec![0usize; tracks.len()]; + let mut pcm_chunks = Vec::new(); + let emit = |w: &mut Mp4Writer>>, t: usize, next: &mut Vec| { + let i = next[t]; + let s = &tracks[t].1[i]; + let d = payload(t, i, s.size); + w.write_sample(t, WriteSample { data: &d, duration: s.duration, composition_offset: s.cto, is_sync: s.sync }).unwrap(); + next[t] += 1; + }; + for (step, &o) in order.iter().enumerate() { + if let Some(p) = pcm_track && step % 5 == 0 { + let d = payload(9, step, 6 * (1 + step % 7)); + w.write_sample(p, WriteSample { data: &d, duration: 0, composition_offset: 0, is_sync: true }).unwrap(); + pcm_chunks.push(d); + } + let t = o % tracks.len(); + if next[t] < tracks[t].1.len() { + emit(&mut w, t, &mut next); + } + } + for t in 0..tracks.len() { + while next[t] < tracks[t].1.len() { + emit(&mut w, t, &mut next); + } + } + let out = if fast { w.finish_faststart() } else { w.finish() }.unwrap().into_inner(); + let f = open(out.as_slice()).unwrap(); + prop_assert_eq!(f.is_quicktime, mov); + prop_assert_eq!(f.tracks.len(), tracks.len() + pcm_track.is_some() as usize); + for (k, (kind, samples)) in tracks.iter().enumerate() { + let t = &f.tracks[k]; + prop_assert_eq!(t.codec(), Some(&entry(*kind).codec)); + prop_assert_eq!(t.samples.len(), samples.len()); + let mut dts = 0i64; + for (i, (s, r)) in samples.iter().zip(&t.samples).enumerate() { + prop_assert_eq!(r.size as usize, s.size); + prop_assert_eq!(r.duration, s.duration); + prop_assert_eq!(r.dts, dts); + prop_assert_eq!(r.pts, dts + s.cto as i64); + prop_assert_eq!(r.is_sync, s.sync); + prop_assert_eq!(f.read_sample(out.as_slice(), k, i).unwrap(), payload(k, i, s.size)); + dts += s.duration as i64; + } + prop_assert_eq!(t.duration, dts as u64); + match start { + Some(st) if !samples.is_empty() || st == 0 => prop_assert_eq!(t.edit_offset, -st), + _ => {} + } + } + if let Some(p) = pcm_track { + let t = &f.tracks[p]; + let got: Vec = (0..t.samples.len()).flat_map(|i| f.read_sample(out.as_slice(), p, i).unwrap()).collect(); + prop_assert_eq!(got, pcm_chunks.concat()); + let frames: u64 = t.samples.iter().map(|s| s.duration as u64).sum(); + prop_assert_eq!(frames, pcm_chunks.iter().map(|c| c.len() as u64 / 6).sum::()); + } + } + + #[test] + fn fragmented_roundtrip( + samples in prop::collection::vec(sample_strategy(), 1..60), + cuts in prop::collection::vec(any::(), 60), + ) { + let mut w = FragmentedWriter::new(Vec::new(), WriterOptions::new(Brand::Mp4)); + let v = w.add_track(TrackConfig::new(entry(0), 90000)).unwrap(); + let a = w.add_track(TrackConfig::new(entry(2), 48000)).unwrap(); + for (i, s) in samples.iter().enumerate() { + w.write_sample(v, WriteSample { data: &payload(0, i, s.size), duration: s.duration, composition_offset: s.cto, is_sync: s.sync }).unwrap(); + w.write_sample(a, WriteSample { data: &payload(1, i, s.size / 2), duration: 1024, composition_offset: 0, is_sync: true }).unwrap(); + if cuts[i] { w.flush_fragment().unwrap(); } + } + let out = w.finish().unwrap(); + let f = open(out.as_slice()).unwrap(); + prop_assert!(f.fragmented); + let mut dts = 0i64; + for (i, s) in samples.iter().enumerate() { + let r = f.tracks[0].samples[i]; + prop_assert_eq!((r.size as usize, r.dts, r.pts, r.is_sync), (s.size, dts, dts + s.cto as i64, s.sync)); + prop_assert_eq!(f.read_sample(out.as_slice(), 0, i).unwrap(), payload(0, i, s.size)); + prop_assert_eq!(f.read_sample(out.as_slice(), 1, i).unwrap(), payload(1, i, s.size / 2)); + prop_assert_eq!(f.tracks[1].samples[i].dts, 1024 * i as i64); + dts += s.duration as i64; + } + } +} + +#[test] +fn sample_lookup() { + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap(); + let t = w.add_track(TrackConfig::new(entry(0), 25)).unwrap(); + // I P B B pattern: decode order I0 P3 B1 B2 | I4 P7 B5 B6 + let cto = [1, 3, 0, 0, 1, 3, 0, 0]; + for (i, c) in cto.iter().enumerate() { + w.write_sample(t, WriteSample { data: &[i as u8], duration: 1, composition_offset: *c, is_sync: i % 4 == 0 }).unwrap(); + } + let out = w.finish().unwrap().into_inner(); + let f = open(out.as_slice()).unwrap(); + let tr = &f.tracks[0]; + // pts: 1,4,2,3,5,8,6,7 + assert_eq!(tr.sample_at_pts(0), Some(0)); + assert_eq!(tr.sample_at_pts(2), Some(2)); + assert_eq!(tr.sample_at_pts(4), Some(1)); + assert_eq!(tr.sample_at_pts(7), Some(7)); + assert_eq!(tr.sample_at_pts(100), Some(5)); + assert_eq!(tr.sync_sample_before(3), 0); + assert_eq!(tr.sync_sample_before(4), 4); + assert_eq!(tr.sync_sample_before(7), 4); + assert_eq!(tr.sync_samples(), &[0, 4]); +} + +#[test] +fn large_offsets_use_co64_and_largesize_mdat() { + // Files > 4 GiB are impractical in tests, so patch a small file into the same layout the + // writer produces for them: co64 chunk offsets and a 16-byte large-size mdat header. + let mut moov = Vec::new(); + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap(); + let t = w.add_track(TrackConfig::new(entry(3), 30)).unwrap(); + w.write_sample(t, WriteSample { data: b"abc", duration: 1, composition_offset: 0, is_sync: true }).unwrap(); + let out = w.finish().unwrap().into_inner(); + // Replace stco with co64 (same entry count, 64-bit offsets) and rebuild. + let f = open(out.as_slice()).unwrap(); + let off = f.tracks[0].samples[0].offset; + let stco = out.windows(4).position(|w| w == b"stco").unwrap() - 4; + let moov_at = out.windows(4).position(|w| w == b"moov").unwrap() - 4; + moov.extend_from_slice(&out[moov_at..stco]); + moov.extend_from_slice(&24u32.to_be_bytes()); + moov.extend_from_slice(b"co64"); + moov.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 1]); + moov.extend_from_slice(&off.to_be_bytes()); + // Fix up sizes of moov/trak/mdia/minf/stbl (+4 bytes each). + for name in [b"moov", b"trak", b"mdia", b"minf", b"stbl"] { + let p = moov.windows(4).position(|w| w == name).unwrap() - 4; + let s = u32::from_be_bytes(moov[p..p + 4].try_into().unwrap()) + 4; + moov[p..p + 4].copy_from_slice(&s.to_be_bytes()); + } + let mut file = out[..moov_at].to_vec(); + file.extend_from_slice(&moov); + // ftyp is 32 bytes for MP4; then `free` (8) + `mdat` (8) → one large-size mdat header. + let ftyp_len = u32::from_be_bytes(file[0..4].try_into().unwrap()) as usize; + assert_eq!(&file[ftyp_len + 4..ftyp_len + 8], b"free"); + let mdat_len = (moov_at - ftyp_len) as u64; + file[ftyp_len..ftyp_len + 4].copy_from_slice(&1u32.to_be_bytes()); + file[ftyp_len + 4..ftyp_len + 8].copy_from_slice(b"mdat"); + file[ftyp_len + 8..ftyp_len + 16].copy_from_slice(&mdat_len.to_be_bytes()); + let g = open(file.as_slice()).unwrap(); + assert_eq!(g.read_sample(file.as_slice(), 0, 0).unwrap(), b"abc"); + // size == 0 ("extends to end of file") on a trailing box. + let mut z = file.clone(); + z.extend_from_slice(&[0, 0, 0, 0, b'f', b'r', b'e', b'e', 1, 2, 3]); + assert!(open(z.as_slice()).is_ok()); +} + +/// Found by `progressive_roundtrip`: only zero-byte samples must not be written as uniform +/// `stsz` size 0, which readers take to mean "a size table follows". +#[test] +fn all_empty_samples_roundtrip() { + for n in [1usize, 3] { + let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap(); + w.add_track(TrackConfig::new(entry(0), 1000)).unwrap(); + for _ in 0..n { + w.write_sample(0, WriteSample { data: &[], duration: 1, composition_offset: 0, is_sync: false }).unwrap(); + } + let out = w.finish().unwrap().into_inner(); + let f = open(out.as_slice()).unwrap(); + assert_eq!(f.tracks[0].samples.len(), n); + assert!(f.tracks[0].samples.iter().all(|s| s.size == 0)); + } +} diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.toml new file mode 100644 index 0000000000..c71d6dbd83 --- /dev/null +++ b/crates/platform/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "craft-platform" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +description = "Small platform lifecycle services for the Craft suite" + +[lints] +workspace = true + +[features] +default = [] +dialogs = [] +appearance = ["dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process"] +browser = ["dep:wasm-bindgen", "dep:js-sys", "dep:web-sys"] +egui = ["dep:egui"] + +[dependencies] +egui = { workspace = true, optional = true } + +[target.'cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))'.dependencies] +zbus = { version = "5", default-features = false, features = ["async-io"], optional = true } +futures-lite = { version = "2", optional = true } +async-channel = { version = "2", optional = true } +async-io = { version = "2", optional = true } +async-process = { version = "2", optional = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen = { version = "0.2", optional = true } +js-sys = { version = "0.3", optional = true } +web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Node", "Element"], optional = true } + +[target.'cfg(target_arch = "wasm32")'.dev-dependencies] +wasm-bindgen-test = "0.3" +wasm-bindgen-futures = "0.4" diff --git a/crates/platform/LICENSE-APACHE b/crates/platform/LICENSE-APACHE new file mode 100644 index 0000000000..f433b1a53f --- /dev/null +++ b/crates/platform/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/crates/platform/LICENSE-MIT b/crates/platform/LICENSE-MIT new file mode 100644 index 0000000000..e1450bdf57 --- /dev/null +++ b/crates/platform/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ArtCraft Team and the craft-libs contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/platform/NOTICE b/crates/platform/NOTICE new file mode 100644 index 0000000000..c369e0095f --- /dev/null +++ b/crates/platform/NOTICE @@ -0,0 +1,16 @@ +Platform lifecycle source provenance + +The optional crates/platform services adapt the preserved local platform candidate +9b135779a1e7136438a217c18afe1693ea23f1ab (dialog outcomes and browser resource ownership), +and current application implementations: +- PdfCraft crates/platform/src/desktop_theme.rs, a8cd797a917b1007544575c7280c9a0ce6a17e8f. +- CADCraft apps/cadcraft/src/desktop_theme.rs, 0cc66ad3066e71f2c3d4cacb7de905e79ba1c95b. +- ArtCraft Launcher apps/artcraft-launcher/src/system_theme.rs, f1676dfb41c226b5be490721f486ee6427419d80. +- Earlier PhotoCraft, FilmCraft and EffectCraft appearance services at revisions + 0c72d95425dece90ef9a1cceb49e3315c96e22d5, 794a25fc9ed2e3f6fab51a254625bc9b99a88015 + and 1b4d47f34f2b1c1b4a89f4b7348889def8fd648b respectively. +Sources: https://github.com/storytold/pdfcraft, https://github.com/storytold/cadcraft, +https://github.com/storytold/craft-launcher, https://github.com/storytold/photocraft, +https://github.com/storytold/filmcraft, https://github.com/storytold/effectcraft. +Copyright (c) 2026 ArtCraft Team and the respective application and craft-libs contributors. +All adapted source is licensed MIT OR Apache-2.0. diff --git a/crates/platform/README.md b/crates/platform/README.md new file mode 100644 index 0000000000..14494d613a --- /dev/null +++ b/crates/platform/README.md @@ -0,0 +1,81 @@ +# craft-platform + +Small platform lifecycle services for Craft applications. Application state, settings, palettes, +document policy and native command routing remain in their current owners. Defaults add no +third-party dependencies. Enable only the services a host uses. + +| Feature | Shared responsibility | +| --- | --- | +| default | Typed dialog outcomes; no backend or toolkit. | +| `dialogs` | Reserve waiting workers before eager UI-thread native picker creation; serial requests, failure delivery and completion wakeups. The backend factory belongs to the app. | +| `egui` | Combine with `dialogs` for the deferred-close guard or with `appearance` for native theme mapping. | +| `appearance` | Linux/BSD XDG desktop preference observation, owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. | +| `browser` | Wasm download link/object URL ownership, cleanup on setup failure or abandonment, and cleanup timer registration before clicking. | + + +## Native dialogs + +`dialogs::wait_prepared(create, deliver)` reserves the worker first. Call it on the native UI thread. +`create` must call `pick_file`, `save_file`, or the equivalent backend method **before returning its +future**. Putting that call inside an async block delays native sheet creation until the worker +polls it. Worker reservation failure never opens the sheet. No live picker has a timeout. + +`NativeDialogs` provides an optional serial queue. Pump it on the event-loop +thread before consuming answers and after code that can request a picker. Replies become visible +only after the pump releases transport ownership, so a continuation can enqueue the next picker. +Dropping a stale reply does not release the actual picker. A host-specific preflight is optional; +it runs off-thread and must be bounded. Unknown capability permits a picker. Proven absence may +request an application-owned fallback. Custom save-format sheets and portal choices remain intact. + +`Outcome::Selected`, explicit `Cancelled`, `Failed` and `Indeterminate` have different evidence. +An rfd `None` is `Indeterminate`; it cannot prove user cancellation rather than backend failure. +Disconnected workers are failures. Apps own localization, document identity/revision checks, filters, +actual save receipts, chained continuations and the decision to close. + +Retain the actual parent window through queued requests, preflight, the native picker AND any +unconsumed application continuation. `DeferredClose::update` cancels close during pending work and +returns a request to retry the application's normal close policy afterward. It never grants +permission to discard work. Run those guards before `craft_quit::on_close_request` in `App::logic`. + +## Desktop appearance + +`appearance::Watcher` caches the desktop preference and wakes only on changes. Subscription precedes +the first read. ReadOne/legacy Read, the standard namespace and GNOME fallback are handled together; +malformed values retain the last valid answer, and explicit no-preference clears it. Disconnection +retains the last valid value until a fresh answer. A later service owner triggers a reread; session +reconnection has bounded backoff. Dropping cancels asynchronous work and waits at most 100 ms +for acknowledgement, joining only an already-finished worker. A synchronously blocked OS call or caller wake callback can outlive +the watcher: that exceptional worker is detached and retains its resources until it returns, +possibly until process exit. Wake callbacks must be nonblocking. No per-helper reader threads +are created. + +App-selected Light/Dark/System, custom palettes, window decorations and unknown-theme fallback remain +application policy. `set_active(false)` suppresses wake notifications while continuing to cache. +Four existing custom-palette service hooks retain their current signatures and receive change-only +notifications even in manual mode; they do not change the chosen palette. Never infer Auto from the +egui theme preference when an app implements Auto by explicitly applying a Light/Dark palette. + +`sync_native_window_theme(ctx, observed)` forwards the cached Linux/BSD desktop answer to native +decorations when egui's window policy is System, falling back to the current toolkit answer. +Its output hook runs after egui's automatic +window synchronization, including child-window output. Concrete Light/Dark preferences retain +precedence, absence of both answers releases the native pin, and `sync_window_theme = false` opts out. +It does not change styles or theme preference. Hosts whose custom palette is manual but whose +native window follows System keep observation active for the native window. Native decoration +rendering still depends on the window manager and requires visible acceptance testing. + +## Browser downloads + +`PreparedDownload::{bytes,blob}` owns a detached anchor and URL until click or drop. Call `click` +with the application's positive URL lifetime; setup/attachment/timer failure releases resources +without clicking. A successful return means a click was issued, not that the browser saved a file. +Applications own names, MIME types, pacing, capture hooks and user activation. File System Access +and print iframe lifetimes remain separate. This service has no native filesystem semantics. + +## Integration + +Enable only the services a host uses. Applications retain palettes, settings, document identity, +close policy, filters, names, MIME types and native command routing. Existing craft-settings, +craft-atomic, craft-print, craft-docpath and craft-quit remain canonical. `craft-window` owns +decoration selection and window-button layout; appearance observation and native color hints here +do not choose a frame or draw an application header. diff --git a/crates/platform/src/appearance.rs b/crates/platform/src/appearance.rs new file mode 100644 index 0000000000..c696510d3d --- /dev/null +++ b/crates/platform/src/appearance.rs @@ -0,0 +1,635 @@ +//! Desktop colour preference through the XDG Settings portal. +//! +//! Derived from PdfCraft's activation-safe subscription and GNOME schema fallback, +//! CADCraft's BSD support, and ArtCraft Launcher's ReadOne/Read compatibility. +//! Palettes, manual choices and the fallback when no preference exists belong to the host. +use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicU8, Ordering}, +}; + +/// Desktop color preference observed independently of the application palette. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Theme { + /// The desktop requests a dark appearance. + Dark, + /// The desktop requests a light appearance. + Light, +} + +struct Shared { + value: AtomicU8, + active: AtomicBool, + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + wake: Box, +} +impl Shared { + fn get(&self) -> Option { + match self.value.load(Ordering::Acquire) { + 1 => Some(Theme::Dark), + 2 => Some(Theme::Light), + _ => None, + } + } + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + fn publish(&self, theme: Option) { + let code = match theme { + Some(Theme::Dark) => 1, + Some(Theme::Light) => 2, + None => 0, + }; + if self.value.swap(code, Ordering::AcqRel) != code && self.active.load(Ordering::Acquire) { + (self.wake)(); + } + } +} +/// An owned subscription. Dropping cancels connection setup, reads, backoff and helper capture, +/// and waits at most 100 ms for acknowledgement. Only a finished worker is joined: an OS call +/// or caller wake callback can block synchronously, so an exceptional unfinished worker is +/// detached and retains its resources until it returns (possibly until process exit). +/// Cache reads never block the UI; callers should keep wake callbacks nonblocking. +pub struct Watcher { + shared: Arc, + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + stop: async_channel::Sender<()>, + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + worker: Option>, + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + finished: std::sync::mpsc::Receiver<()>, +} +impl Watcher { + /// Start an active subscription, or return `None` on unsupported targets or worker failure. + /// `wake` runs on the worker and must not block. + pub fn start(wake: impl Fn() + Send + Sync + 'static) -> Option { + Self::start_active(true, wake) + } + /// Start observing with explicit control over wake notifications. + /// An inactive subscription still updates its cache. Unsupported targets and worker + /// startup failure return `None`; browser targets never start a desktop watcher. + pub fn start_active(active: bool, wake: impl Fn() + Send + Sync + 'static) -> Option { + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + { + Self::spawn(active, wake, portal::watch) + } + #[cfg(not(all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))] + { + let _ = (active, wake); + None + } + } + /// Read the cached preference without blocking; `None` means no known preference. + pub fn current(&self) -> Option { + self.shared.get() + } + /// Enable or suppress future change notifications without stopping observation. + /// Changing this flag does not itself wake the host or clear the cached preference. + pub fn set_active(&self, active: bool) { + self.shared.active.store(active, Ordering::Release); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + fn spawn + 'static>( + active: bool, + wake: impl Fn() + Send + Sync + 'static, + source: impl FnOnce(Arc) -> F + Send + 'static, + ) -> Option { + let shared = Arc::new(Shared { value: AtomicU8::new(0), active: AtomicBool::new(active), wake: Box::new(wake) }); + let worker_shared = Arc::clone(&shared); + let (stop, stopped) = async_channel::bounded::<()>(1); + let (done, finished) = std::sync::mpsc::channel(); + let worker = std::thread::Builder::new() + .name("desktop-appearance".into()) + .spawn(move || { + futures_lite::future::block_on(futures_lite::future::race( + async { + let _ = stopped.recv().await; + }, + source(worker_shared), + )); + let _ = done.send(()); + }) + .ok()?; + Some(Self { shared, stop, worker: Some(worker), finished }) + } +} +impl Drop for Watcher { + fn drop(&mut self) { + self.set_active(false); + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + { + self.stop.close(); + if let Some(worker) = self.worker.take() { + let _ = self.finished.recv_timeout(std::time::Duration::from_millis(100)); + // Acknowledgement precedes thread-local destructors. They can block too, so + // never join solely on the acknowledgement (or channel disconnection). + if worker.is_finished() { + let _ = worker.join(); + } + } + } + } +} + +#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +mod portal { + use super::{Shared, Theme}; + use futures_lite::StreamExt; + use std::{sync::Arc, time::Duration}; + use zbus::zvariant::{OwnedValue, Value}; + const DEST: &str = "org.freedesktop.portal.Desktop"; + const PATH: &str = "/org/freedesktop/portal/desktop"; + const IFACE: &str = "org.freedesktop.portal.Settings"; + const STANDARD: &str = "org.freedesktop.appearance"; + const GNOME: &str = "org.gnome.desktop.interface"; + const KEY: &str = "color-scheme"; + const TIMEOUT: Duration = Duration::from_secs(2); + + // Outer None means unknown/malformed; Some(None) is an explicit no-preference answer. + fn decode(namespace: &str, value: &Value<'_>) -> Option> { + match (namespace, value) { + (STANDARD, Value::U32(n)) => Some(match n { + 1 => Some(Theme::Dark), + 2 => Some(Theme::Light), + _ => None, + }), + (GNOME, Value::Str(s)) => Some(match s.as_str() { + "prefer-dark" => Some(Theme::Dark), + "prefer-light" => Some(Theme::Light), + _ => None, + }), + _ => None, + } + } + fn reply(namespace: &str, value: &Value<'_>, legacy: bool) -> Option> { + if legacy { + let Value::Value(inner) = value else { return None }; + decode(namespace, inner) + } else { + decode(namespace, value) + } + } + fn combined(standard: Option>, gnome: Option>) -> Option> { + if standard.is_none() && gnome.is_none() { None } else { Some(standard.flatten().or(gnome.flatten())) } + } + async fn bounded(future: impl std::future::Future) -> Option { + futures_lite::future::race(async { Some(future.await) }, async { + async_io::Timer::after(TIMEOUT).await; + None + }) + .await + } + async fn read(connection: &zbus::Connection, namespace: &str) -> Option> { + for (method, legacy) in [("ReadOne", false), ("Read", true)] { + if let Some(Ok(message)) = bounded(connection.call_method(Some(DEST), PATH, Some(IFACE), method, &(namespace, KEY))).await + && let Ok(value) = message.body().deserialize::() + && let Some(answer) = reply(namespace, &value, legacy) + { + return Some(answer); + } + } + None + } + fn rule() -> zbus::Result> { + Ok(zbus::MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .sender(DEST)? + .path(PATH)? + .interface(IFACE)? + .member("SettingChanged")? + .arg(1, KEY)? + .build()) + } + fn owner_rule() -> zbus::Result> { + Ok(zbus::MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .sender("org.freedesktop.DBus")? + .interface("org.freedesktop.DBus")? + .member("NameOwnerChanged")? + .arg(0, DEST)? + .build()) + } + pub(super) async fn watch(shared: Arc) { + let mut retry = Duration::from_secs(5); + let mut fallback_used = false; + loop { + let mut connected = false; + let _ = session(&shared, &mut fallback_used, &mut connected).await; + if connected { + retry = Duration::from_secs(5); + } + // Keep the last valid answer during disconnect; a new explicit no-preference clears it. + async_io::Timer::after(retry).await; + retry = (retry * 2).min(Duration::from_secs(300)); + } + } + // Keep Nix/profile PATH entries, but never execute a helper from a relative search folder. + fn gsettings_exe(path: Option<&std::ffi::OsStr>) -> Option { + let dirs = path.map(std::env::split_paths).into_iter().flatten().filter(|p| p.is_absolute()); + dirs.chain(["/usr/bin", "/bin", "/usr/local/bin"].map(std::path::PathBuf::from)).map(|p| p.join("gsettings")).find(|p| p.is_file()) + } + async fn fallback(shared: &Shared, used: &mut bool) { + if *used { + return; + } + *used = true; + if let Some(exe) = gsettings_exe(std::env::var_os("PATH").as_deref()) + && let Some(text) = crate::process::capture(&exe, &["get", GNOME, KEY], TIMEOUT).await + { + let text = text.trim().trim_matches('\''); + if let Some(answer) = decode(GNOME, &Value::from(text)) { + shared.publish(answer); + } + } + } + async fn session(shared: &Shared, fallback_used: &mut bool, connected: &mut bool) -> Option<()> { + let connection = match zbus::connection::Builder::session() { + Ok(builder) => bounded(builder.method_timeout(TIMEOUT).build()).await.and_then(Result::ok), + Err(_) => None, + }; + let Some(connection) = connection else { + fallback(shared, fallback_used).await; + return None; + }; + watch_connection(shared, fallback_used, connected, connection).await + } + async fn watch_connection(shared: &Shared, fallback_used: &mut bool, connected: &mut bool, connection: zbus::Connection) -> Option<()> { + // MatchRule installs before activation: unlike a proxy subscription it needs no current owner. + let mut changes = bounded(zbus::MessageStream::for_match_rule(rule().ok()?, &connection, Some(64))).await?.ok()?; + let mut owners = bounded(zbus::MessageStream::for_match_rule(owner_rule().ok()?, &connection, Some(8))).await?.ok()?; + let mut standard = read(&connection, STANDARD).await; + let mut gnome = read(&connection, GNOME).await; + match combined(standard, gnome) { + Some(answer) => { + *connected = true; + shared.publish(answer); + } + None => { + fallback(shared, fallback_used).await; + return None; + } + } + loop { + let message = + futures_lite::future::race(async { changes.next().await.map(|m| (false, m)) }, async { owners.next().await.map(|m| (true, m)) }) + .await?; + let (owner, message) = message; + let message = message.ok()?; + if owner { + // Activation is already covered by the initial read. Loss/replacement reconnects. + if let Ok((_, old, _)) = message.body().deserialize::<(String, String, String)>() + && !old.is_empty() + { + return None; + } + continue; + } + let Ok((namespace, key, value)) = message.body().deserialize::<(String, String, OwnedValue)>() else { continue }; + if key != KEY { + continue; + } + let Some(answer) = decode(&namespace, &value) else { continue }; + match namespace.as_str() { + STANDARD => standard = Some(answer), + GNOME => gnome = Some(answer), + _ => continue, + } + if let Some(answer) = combined(standard, gnome) { + shared.publish(answer); + } + } + } + #[cfg(test)] + #[path = "appearance_bus_tests.rs"] + mod bus_tests; + #[cfg(test)] + mod tests { + #[test] + fn gsettings_respects_absolute_nix_style_path_without_using_relative_folders() -> Result<(), Box> { + struct Fixture(std::path::PathBuf); + impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_nanos(); + let directory = std::env::temp_dir().join(format!("craft-platform-gsettings-{}-{nonce}", std::process::id())); + std::fs::create_dir(&directory)?; + let fixture = Fixture(directory); + let helper = fixture.0.join("gsettings"); + std::fs::write(&helper, b"fixture")?; + let path = std::env::join_paths([std::path::Path::new("relative-untrusted"), fixture.0.as_path()])?; + assert_eq!(super::gsettings_exe(Some(path.as_os_str())), Some(helper)); + assert!(super::gsettings_exe(Some(std::ffi::OsStr::new("relative-untrusted"))).is_none_or(|p| p.is_absolute())); + Ok(()) + } + + use super::{GNOME, STANDARD, combined, decode, reply}; + use crate::appearance::{Theme, Watcher}; + use std::{ + sync::{Arc, atomic::Ordering}, + time::Duration, + }; + use zbus::zvariant::Value; + #[test] + fn no_preference_is_an_answer_and_gnome_only_fills_missing_preference() { + assert_eq!(combined(None, None), None); + assert_eq!(combined(Some(None), None), Some(None)); + assert_eq!(combined(Some(None), Some(Some(Theme::Dark))), Some(Some(Theme::Dark))); + assert_eq!(combined(Some(Some(Theme::Light)), Some(Some(Theme::Dark))), Some(Some(Theme::Light))); + assert_eq!(combined(None, Some(None)), Some(None)); + } + #[test] + fn malformed_is_distinct_from_no_preference_and_legacy_is_exact() { + assert_eq!(decode(STANDARD, &Value::U32(0)), Some(None)); + assert_eq!(decode(STANDARD, &Value::U32(77)), Some(None)); + assert_eq!(decode(STANDARD, &Value::from("dark")), None); + assert_eq!(reply(STANDARD, &Value::Value(Box::new(Value::U32(1))), true), Some(Some(Theme::Dark))); + assert_eq!(reply(STANDARD, &Value::U32(1), true), None); + assert_eq!(reply(STANDARD, &Value::Value(Box::new(Value::Value(Box::new(Value::U32(1))))), true), None); + assert_eq!(decode(STANDARD, &Value::Value(Box::new(Value::U32(1)))), None); + assert_eq!(decode(STANDARD, &Value::I32(1)), None); + assert_eq!(decode(GNOME, &Value::from("default")), Some(None)); + assert_eq!(decode(GNOME, &Value::U32(1)), None); + + assert_eq!(reply(GNOME, &Value::from("prefer-light"), false), Some(Some(Theme::Light))); + } + #[test] + fn manual_cache_changes_do_not_wake_and_drop_cancels_pending_source() -> Result<(), Box> { + let (tx, rx) = std::sync::mpsc::channel(); + let (cancelled, cancellation) = std::sync::mpsc::channel(); + struct Cancelled(std::sync::mpsc::Sender<()>); + impl Drop for Cancelled { + fn drop(&mut self) { + let _ = self.0.send(()); + } + } + let wakes = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let observed = Arc::clone(&wakes); + let watcher = Watcher::spawn( + false, + move || { + observed.fetch_add(1, Ordering::Relaxed); + }, + move |shared| async move { + let _cancelled = Cancelled(cancelled); + shared.publish(Some(Theme::Dark)); + let _ = tx.send(()); + futures_lite::future::pending::<()>().await; + }, + ) + .ok_or("worker creation failed")?; + rx.recv_timeout(Duration::from_secs(2))?; + assert_eq!(watcher.current(), Some(Theme::Dark)); + assert_eq!(wakes.load(Ordering::Relaxed), 0); + watcher.set_active(true); + watcher.shared.publish(Some(Theme::Dark)); + assert_eq!(wakes.load(Ordering::Relaxed), 0); + watcher.shared.publish(Some(Theme::Light)); + assert_eq!(watcher.current(), Some(Theme::Light)); + watcher.shared.publish(Some(Theme::Dark)); + assert_eq!(watcher.current(), Some(Theme::Dark)); + watcher.shared.publish(None); + assert_eq!(watcher.current(), None); + assert_eq!(wakes.load(Ordering::Relaxed), 3); + drop(watcher); + cancellation.recv_timeout(Duration::from_secs(2))?; + Ok(()) + } + #[test] + fn drop_does_not_wait_for_a_synchronously_blocked_source() -> Result<(), Box> { + let (started, ready) = std::sync::mpsc::channel(); + let (release, blocked) = std::sync::mpsc::channel(); + let (exited, exit) = std::sync::mpsc::channel(); + struct Release(Option>); + impl Drop for Release { + fn drop(&mut self) { + if let Some(release) = self.0.take() { + let _ = release.send(()); + } + } + } + // Declared before the watcher: every error/unwind releases the synchronous poll. + let release = Release(Some(release)); + let watcher = Watcher::spawn( + false, + || {}, + move |_| async move { + let _ = started.send(()); + let _ = blocked.recv(); + let _ = exited.send(()); + }, + ) + .ok_or("worker creation failed")?; + ready.recv_timeout(Duration::from_secs(2))?; + let (dropped, drop_result) = std::sync::mpsc::channel(); + let dropper = std::thread::spawn(move || { + drop(watcher); + let _ = dropped.send(()); + }); + let bounded = drop_result.recv_timeout(Duration::from_secs(1)).is_ok(); + // Release before asserting, including when an unbounded implementation regresses. + drop(release); + exit.recv_timeout(Duration::from_secs(2))?; + assert!(dropper.join().is_ok(), "watcher drop panicked"); + assert!(bounded, "watcher drop waited for a blocked synchronous poll"); + Ok(()) + } + } +} +/// Owned callback that supplies an observed theme and updates egui native-window hints. +#[cfg(feature = "egui")] +pub type SystemThemeFn = Box Option>; +/// Create an egui theme callback that owns the subscription and wakes its first context. +/// Return `None` when no desktop watcher can start; the host retains its fallback policy. +#[cfg(feature = "egui")] +pub fn egui_service() -> Option { + let context = Arc::new(std::sync::OnceLock::::new()); + let worker_context = Arc::clone(&context); + let watcher = Watcher::start(move || { + if let Some(ctx) = worker_context.get() { + ctx.request_repaint(); + } + })?; + Some(Box::new(move |ctx| { + let _ = context.set(ctx.clone()); + sync_native_window_theme(ctx, watcher.current()); + watcher.current().map(|t| match t { + Theme::Dark => egui::Theme::Dark, + Theme::Light => egui::Theme::Light, + }) + })) +} + +/// Supply the portal answer for native window decorations without changing egui's theme choice +/// or either palette. A missing portal answer falls back to the current toolkit system theme; +/// when both are absent the native pin is released. Linux/BSD window backends cannot reliably +/// resolve `SystemDefault` themselves. +/// The output hook runs after egui's own window-theme synchronization, so it cannot be overwritten +/// by a later automatic `SetTheme(SystemDefault)` in the same pass. +#[cfg(feature = "egui")] +pub fn sync_native_window_theme(ctx: &egui::Context, observed: Option) { + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + { + ctx.add_plugin(NativeWindowTheme::default()); + ctx.with_plugin(|plugin: &mut NativeWindowTheme| plugin.observed = observed); + } + #[cfg(not(all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))] + let _ = (ctx, observed); +} + +#[cfg(all(feature = "egui", unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +#[derive(Default)] +struct NativeWindowTheme { + observed: Option, + sent: std::collections::HashMap, +} +#[cfg(all(feature = "egui", unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +impl egui::Plugin for NativeWindowTheme { + fn debug_name(&self) -> &'static str { + "desktop window appearance" + } + fn output_hook(&mut self, ctx: &egui::Context, output: &mut egui::FullOutput) { + if !ctx.options(|o| o.sync_window_theme) { + // Another owner may alter the native theme while synchronization is disabled. + self.sent.clear(); + return; + } + let desired = match ctx.options(|o| o.theme_preference) { + egui::ThemePreference::Dark => egui::SystemTheme::Dark, + egui::ThemePreference::Light => egui::SystemTheme::Light, + egui::ThemePreference::System => match self.observed.or_else(|| { + ctx.system_theme().map(|theme| match theme { + egui::Theme::Dark => Theme::Dark, + egui::Theme::Light => Theme::Light, + }) + }) { + Some(Theme::Dark) => egui::SystemTheme::Dark, + Some(Theme::Light) => egui::SystemTheme::Light, + None => egui::SystemTheme::SystemDefault, + }, + }; + // FullOutput can carry child-window commands too. Rewrite every viewport so a deferred + // or immediate child cannot reintroduce egui's inherited hint after its own UI pass. + for (id, viewport) in &mut output.viewport_output { + let had_sync = viewport.commands.iter().any(|command| matches!(command, egui::ViewportCommand::SetTheme(_))); + viewport.commands.retain(|command| !matches!(command, egui::ViewportCommand::SetTheme(_))); + if had_sync || self.sent.get(id) != Some(&desired) { + viewport.commands.push(egui::ViewportCommand::SetTheme(desired)); + self.sent.insert(*id, desired); + } + } + // Forget destroyed native windows: a reused viewport identifier must receive its hint. + self.sent.retain(|id, _| output.viewport_output.contains_key(id)); + } +} + +#[cfg(all(test, feature = "egui", unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +mod native_window_tests { + use super::{Theme, sync_native_window_theme}; + fn pass(ctx: &egui::Context, observed: Option, preference: egui::ThemePreference) -> Vec { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + sync_native_window_theme(ui.ctx(), observed); + // Deliberately apply the host's choice AFTER the observer, as real palette adapters do. + ui.ctx().set_theme(preference); + }); + output.textures_delta.clear(); // Headless policy test; no renderer consumes uploads. + output + .viewport_output + .values() + .flat_map(|v| &v.commands) + .filter_map(|command| match command { + egui::ViewportCommand::SetTheme(theme) => Some(*theme), + _ => None, + }) + .collect() + } + #[test] + fn actual_end_pass_maps_system_manual_and_reset_without_overwriting_palettes() { + use egui::{SystemTheme as Native, ThemePreference as Choice}; + let ctx = egui::Context::default(); + let marker = egui::Color32::from_rgb(12, 34, 56); + ctx.all_styles_mut(|s| s.visuals.panel_fill = marker); + assert_eq!(pass(&ctx, Some(Theme::Light), Choice::System), vec![Native::Light]); + assert_eq!(ctx.options(|o| o.theme_preference), Choice::System); + assert!(pass(&ctx, Some(Theme::Light), Choice::System).is_empty()); + assert_eq!(pass(&ctx, Some(Theme::Dark), Choice::System), vec![Native::Dark]); + // A portal change cannot override a concrete manual native preference. + assert_eq!(pass(&ctx, Some(Theme::Light), Choice::Dark), vec![Native::Dark]); + assert_eq!(pass(&ctx, Some(Theme::Dark), Choice::Light), vec![Native::Light]); + assert_eq!(pass(&ctx, Some(Theme::Dark), Choice::System), vec![Native::Dark]); + assert_eq!(pass(&ctx, None, Choice::System), vec![Native::SystemDefault]); + assert!(pass(&ctx, None, Choice::System).is_empty()); + assert_eq!(ctx.style_of(egui::Theme::Dark).visuals.panel_fill, marker); + assert_eq!(ctx.style_of(egui::Theme::Light).visuals.panel_fill, marker); + } + #[test] + fn native_system_hint_uses_current_toolkit_fallback_without_retaining_stale_input() { + let ctx = egui::Context::default(); + for (raw_theme, observed, expected) in [ + (Some(egui::Theme::Light), None, egui::SystemTheme::Light), + (Some(egui::Theme::Dark), None, egui::SystemTheme::Dark), + (Some(egui::Theme::Dark), Some(Theme::Light), egui::SystemTheme::Light), + (None, None, egui::SystemTheme::SystemDefault), + ] { + let mut output = ctx.run_ui(egui::RawInput { system_theme: raw_theme, ..Default::default() }, |ui| { + sync_native_window_theme(ui.ctx(), observed); + ui.ctx().set_theme(egui::ThemePreference::System); + }); + let hints: Vec<_> = output + .viewport_output + .values() + .flat_map(|v| &v.commands) + .filter_map(|command| match command { + egui::ViewportCommand::SetTheme(theme) => Some(*theme), + _ => None, + }) + .collect(); + output.textures_delta.clear(); + assert_eq!(hints, vec![expected]); + } + } + #[test] + fn deferred_windows_receive_the_same_hint_and_reset() { + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let child = egui::ViewportId::from_hash_of("appearance-child"); + for observed in [Some(Theme::Light), Some(Theme::Dark), None] { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + sync_native_window_theme(ui.ctx(), observed); + ui.ctx().set_theme(egui::ThemePreference::System); + ui.ctx().show_viewport_deferred(child, egui::ViewportBuilder::default(), |_, _| {}); + }); + output.textures_delta.clear(); + let expected = match observed { + Some(Theme::Light) => egui::SystemTheme::Light, + Some(Theme::Dark) => egui::SystemTheme::Dark, + None => egui::SystemTheme::SystemDefault, + }; + for id in [egui::ViewportId::ROOT, child] { + let commands: Vec<_> = output + .viewport_output + .get(&id) + .into_iter() + .flat_map(|v| &v.commands) + .filter_map(|c| match c { + egui::ViewportCommand::SetTheme(t) => Some(*t), + _ => None, + }) + .collect(); + assert_eq!(commands, vec![expected]); + } + } + } + #[test] + fn custom_palette_system_policy_and_explicit_sync_opt_out_are_preserved() { + use egui::{SystemTheme as Native, ThemePreference as Choice}; + let ctx = egui::Context::default(); + // Photo/PDF/Sound keep System native policy even when their custom palette is manual. + ctx.all_styles_mut(|s| s.visuals = egui::Visuals::dark()); + assert_eq!(pass(&ctx, Some(Theme::Light), Choice::System), vec![Native::Light]); + assert!(ctx.style_of(egui::Theme::Light).visuals.dark_mode); + ctx.options_mut(|o| o.sync_window_theme = false); + assert!(pass(&ctx, Some(Theme::Dark), Choice::System).is_empty()); + ctx.options_mut(|o| o.sync_window_theme = true); + assert_eq!(pass(&ctx, Some(Theme::Dark), Choice::System), vec![Native::Dark]); + } +} diff --git a/crates/platform/src/appearance/portal/appearance_bus_tests.rs b/crates/platform/src/appearance/portal/appearance_bus_tests.rs new file mode 100644 index 0000000000..d5923bc274 --- /dev/null +++ b/crates/platform/src/appearance/portal/appearance_bus_tests.rs @@ -0,0 +1,147 @@ +//! Private-bus regression based on PdfCraft's queued-update test (storytold/pdfcraft#881). +use super::{DEST, GNOME, IFACE, KEY, PATH, STANDARD, watch_connection}; +use crate::appearance::{Theme, Watcher}; +use std::time::Duration; +use zbus::zvariant::{OwnedValue, Value}; + +#[test] +#[ignore = "requires dbus-daemon; private session bus only"] +fn legacy_read_keeps_queued_signals_and_drop_cancels_idle_subscription() -> Result<(), Box> { + use std::io::BufRead; + use std::process::{Command, Stdio}; + struct Daemon(std::process::Child); + impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + struct Settings { + captured: std::sync::mpsc::Sender<()>, + released: async_channel::Receiver<()>, + } + #[zbus::interface(name = "org.freedesktop.portal.Settings")] + impl Settings { + async fn read(&self, namespace: &str, _key: &str) -> zbus::fdo::Result { + if namespace != STANDARD { + return Err(zbus::fdo::Error::InvalidArgs("unknown namespace".into())); + } + self.captured.send(()).map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?; + self.released.recv().await.map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?; + OwnedValue::try_from(Value::Value(Box::new(Value::U32(2)))).map_err(|e| zbus::fdo::Error::Failed(e.to_string())) + } + } + let mut daemon = Daemon( + Command::new("dbus-daemon") + .args(["--session", "--nofork", "--print-address=1"]) + .arg(format!("--address=unix:abstract=craft-appearance-test-{}", std::process::id())) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn()?, + ); + let mut address = String::new(); + std::io::BufReader::new(daemon.0.stdout.take().ok_or("no daemon stdout")?).read_line(&mut address)?; + let (captured, seen) = std::sync::mpsc::channel(); + let (release, released) = async_channel::bounded(1); + let server = futures_lite::future::block_on( + zbus::connection::Builder::address(address.trim())?.name(DEST)?.serve_at(PATH, Settings { captured, released })?.build(), + )?; + let client = futures_lite::future::block_on(zbus::connection::Builder::address(address.trim())?.build())?; + let (woke, wakes) = std::sync::mpsc::channel(); + let tracker = Watcher::spawn( + true, + move || { + let _ = woke.send(()); + }, + move |shared| async move { + let _ = watch_connection(&shared, &mut true, &mut false, client).await; + }, + ) + .ok_or("could not start observer")?; + seen.recv_timeout(Duration::from_secs(2))?; + futures_lite::future::block_on(server.emit_signal(None::<&str>, PATH, IFACE, "SettingChanged", &(STANDARD, KEY, OwnedValue::from(1u32))))?; + release.send_blocking(())?; + wakes.recv_timeout(Duration::from_secs(2))?; + wakes.recv_timeout(Duration::from_secs(2))?; + assert_eq!(tracker.current(), Some(Theme::Dark)); + // A malformed update must not clear the valid value or cause a wake. + futures_lite::future::block_on(server.emit_signal(None::<&str>, PATH, IFACE, "SettingChanged", &(STANDARD, KEY, OwnedValue::from(true))))?; + assert!(wakes.recv_timeout(Duration::from_millis(50)).is_err()); + assert_eq!(tracker.current(), Some(Theme::Dark)); + let before = std::time::Instant::now(); + drop(tracker); + assert!(before.elapsed() < Duration::from_secs(1)); + // Drop also cancels a backend that has entered Read and never replies. + let client = futures_lite::future::block_on(zbus::connection::Builder::address(address.trim())?.build())?; + let pending = Watcher::spawn( + true, + || {}, + move |shared| async move { + let _ = watch_connection(&shared, &mut true, &mut false, client).await; + }, + ) + .ok_or("could not start pending-read observer")?; + seen.recv_timeout(Duration::from_secs(2))?; + let before = std::time::Instant::now(); + drop(pending); + assert!(before.elapsed() < Duration::from_secs(1)); + // A newly available portal uses ReadOne, and a replacement owner must trigger a reread. + futures_lite::future::block_on(server.release_name(DEST))?; + struct ModernSettings(u32); + #[zbus::interface(name = "org.freedesktop.portal.Settings")] + impl ModernSettings { + fn read_one(&self, namespace: &str, _key: &str) -> zbus::fdo::Result { + if namespace == STANDARD { Ok(OwnedValue::from(self.0)) } else { Err(zbus::fdo::Error::InvalidArgs("unknown namespace".into())) } + } + } + let client = futures_lite::future::block_on(zbus::connection::Builder::address(address.trim())?.build())?; + let (woke, wakes) = std::sync::mpsc::channel(); + let (attempted, attempts) = std::sync::mpsc::channel(); + let tracker = Watcher::spawn( + true, + move || { + let _ = woke.send(()); + }, + move |shared| async move { + // The production observer repeats this session after its bounded reconnect backoff. + loop { + let _ = watch_connection(&shared, &mut true, &mut false, client.clone()).await; + let _ = attempted.send(()); + async_io::Timer::after(Duration::from_millis(10)).await; + } + }, + ) + .ok_or("could not start modern observer")?; + attempts.recv_timeout(Duration::from_secs(2))?; + let modern = + futures_lite::future::block_on(zbus::connection::Builder::address(address.trim())?.name(DEST)?.serve_at(PATH, ModernSettings(2))?.build())?; + + wakes.recv_timeout(Duration::from_secs(2))?; + assert_eq!(tracker.current(), Some(Theme::Light)); + futures_lite::future::block_on(modern.release_name(DEST))?; + let replacement = + futures_lite::future::block_on(zbus::connection::Builder::address(address.trim())?.name(DEST)?.serve_at(PATH, ModernSettings(1))?.build())?; + wakes.recv_timeout(Duration::from_secs(2))?; + assert_eq!(tracker.current(), Some(Theme::Dark)); + futures_lite::future::block_on(replacement.emit_signal(None::<&str>, PATH, IFACE, "SettingChanged", &(STANDARD, KEY, OwnedValue::from(0u32))))?; + wakes.recv_timeout(Duration::from_secs(2))?; + assert_eq!(tracker.current(), None); + // GNOME's string schema fills the empty standard preference. Manual mode still caches it, + // and opting back into System sees that latest cache without a redundant wake. + tracker.set_active(false); + futures_lite::future::block_on(replacement.emit_signal(None::<&str>, PATH, IFACE, "SettingChanged", &(GNOME, KEY, Value::from("prefer-dark"))))?; + let deadline = std::time::Instant::now() + Duration::from_secs(2); + while tracker.current() != Some(Theme::Dark) { + assert!(std::time::Instant::now() < deadline, "GNOME change was not cached"); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(matches!(wakes.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty))); + tracker.set_active(true); + assert_eq!(tracker.current(), Some(Theme::Dark)); + assert!(matches!(wakes.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty))); + futures_lite::future::block_on(replacement.emit_signal(None::<&str>, PATH, IFACE, "SettingChanged", &(GNOME, KEY, Value::from("default"))))?; + wakes.recv_timeout(Duration::from_secs(2))?; + assert_eq!(tracker.current(), None); + drop(tracker); + Ok(()) +} diff --git a/crates/platform/src/browser.rs b/crates/platform/src/browser.rs new file mode 100644 index 0000000000..965eb925c9 --- /dev/null +++ b/crates/platform/src/browser.rs @@ -0,0 +1,89 @@ +//! Browser downloads. Caller owns MIME/name decisions and pacing; this module owns resource cleanup. +use wasm_bindgen::{JsCast, JsValue, closure::Closure}; +use web_sys::{Blob, BlobPropertyBag, HtmlAnchorElement, Url, Window}; + +/// Object-URL lifetime for a requested download; the default is 60 seconds. +#[derive(Clone, Copy, Debug)] +pub struct DownloadOptions { + /// Positive delay in milliseconds before cleanup; nonpositive values reject the click. + pub revoke_after_ms: i32, +} +impl Default for DownloadOptions { + fn default() -> Self { + Self { revoke_after_ms: 60_000 } + } +} + +/// Prepared DOM link and object URL. Dropping without clicking cleans both up. +/// Preparation can occur before an app's download pacer yields. +pub struct PreparedDownload { + window: Window, + anchor: HtmlAnchorElement, + url: Option, +} +impl PreparedDownload { + /// Prepare an owned Blob and hidden link using the caller's bytes, MIME and filename. + /// No download is requested until [`Self::click`]; browser setup failures return an error. + pub fn bytes(name: &str, mime: &str, bytes: &[u8]) -> Result { + let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes)); + let options = BlobPropertyBag::new(); + options.set_type(mime); + Self::blob(name, &Blob::new_with_u8_array_sequence_and_options(&parts, &options)?) + } + /// Prepare a hidden link and owned object URL for an existing Blob. + /// Blank filenames, missing browser DOM and setup failures return an error. + pub fn blob(name: &str, blob: &Blob) -> Result { + if name.trim().is_empty() { + return Err(JsValue::from_str("a file name is required")); + } + let window = web_sys::window().ok_or_else(|| JsValue::from_str("no browser window"))?; + let document = window.document().ok_or_else(|| JsValue::from_str("no browser document"))?; + document.body().ok_or_else(|| JsValue::from_str("the page has no body"))?; + let anchor = document.create_element("a")?.dyn_into::()?; + anchor.set_download(name); + anchor.set_attribute("style", "display:none")?; + let download = Self { window, anchor, url: Some(Url::create_object_url_with_blob(blob)?) }; + if let Some(url) = &download.url { + download.anchor.set_href(url); + } + Ok(download) + } + /// Register cleanup before clicking: a timer failure returns an error without triggering + /// a partial download. Success only means a click was issued; browser acceptance is unobservable. + pub fn click(mut self, options: DownloadOptions) -> Result<(), JsValue> { + if options.revoke_after_ms <= 0 { + return Err(JsValue::from_str("download lifetime must be positive")); + } + let Some(url) = self.url.as_ref().cloned() else { + return Err(JsValue::from_str("download has no object URL")); + }; + let body = self.window.document().and_then(|d| d.body()).ok_or_else(|| JsValue::from_str("the page has no body"))?; + body.append_child(&self.anchor)?; + let revoke = Closure::once(move || { + let _ = Url::revoke_object_url(&url); + }); + self.window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.as_ref().unchecked_ref(), options.revoke_after_ms)?; + revoke.forget(); // Ownership transfers only after successful timer registration. + self.url = None; + self.anchor.click(); + Ok(()) + } +} +impl Drop for PreparedDownload { + fn drop(&mut self) { + self.anchor.remove(); + if let Some(url) = self.url.take() { + let _ = Url::revoke_object_url(&url); + } + } +} +/// Prepare bytes and request a download with the specified URL lifetime. +/// Success means the click was issued, not that the browser accepted or saved the file. +pub fn download_bytes(name: &str, mime: &str, bytes: &[u8], options: DownloadOptions) -> Result<(), JsValue> { + PreparedDownload::bytes(name, mime, bytes)?.click(options) +} +/// Prepare a Blob and request a download with the specified URL lifetime. +/// Setup or scheduling failures clean up owned resources and return an error. +pub fn download_blob(name: &str, blob: &Blob, options: DownloadOptions) -> Result<(), JsValue> { + PreparedDownload::blob(name, blob)?.click(options) +} diff --git a/crates/platform/src/dialog_outcome.rs b/crates/platform/src/dialog_outcome.rs new file mode 100644 index 0000000000..7f6750023a --- /dev/null +++ b/crates/platform/src/dialog_outcome.rs @@ -0,0 +1,97 @@ +//! Dialog results with evidence: an empty rfd answer does not establish user cancellation. +/// Host assessment of whether a native backend is available; unknown is not proven absence. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Capability { + /// The host has confirmed that a backend is available. + Available, + /// Proven backend absence, with a diagnostic suitable for the host. + Unavailable(String), + /// Inconclusive capability evidence; the host should still permit a picker attempt. + Unknown(String), +} +/// The layer that prevented a dialog request from completing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ErrorKind { + /// The host proved that no backend is available. + Unavailable, + /// Request transport or background execution failed. + Worker, + /// The picker backend reported or encountered a failure. + Backend, +} +/// A classified dialog failure with a host-facing diagnostic. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DialogError { + /// The failing layer. + pub kind: ErrorKind, + /// Diagnostic text for the host to present or log. + pub message: String, +} +impl DialogError { + /// Construct a failure without inferring cancellation from the diagnostic. + pub fn new(kind: ErrorKind, message: impl Into) -> Self { + Self { kind, message: message.into() } + } +} +impl std::fmt::Display for DialogError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} +impl std::error::Error for DialogError {} +/// Selection, explicit cancellation, failure, or an answer whose cause is unknown. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + /// A value returned by the picker. + Selected(T), + /// Explicit app/backend cancellation; never inferred from rfd's empty answer. + Cancelled, + /// A transport, capability or backend failure. + Failed(DialogError), + /// No selection; rfd cannot say whether the user cancelled or its backend failed. + Indeterminate, +} +impl Outcome { + /// Preserve a selection; an empty rfd answer is indeterminate, never proven cancellation. + pub fn from_rfd(value: Option) -> Self { + value.map_or(Self::Indeterminate, Self::Selected) + } + /// Transform only a selected value, preserving all other outcomes unchanged. + pub fn map(self, map: impl FnOnce(T) -> U) -> Outcome { + match self { + Self::Selected(value) => Outcome::Selected(map(value)), + Self::Cancelled => Outcome::Cancelled, + Self::Failed(error) => Outcome::Failed(error), + Self::Indeterminate => Outcome::Indeterminate, + } + } + /// Construct a backend failure with the supplied diagnostic. + pub fn failed(message: impl Into) -> Self { + Self::Failed(DialogError::new(ErrorKind::Backend, message)) + } +} +impl Outcome> { + /// Treat missing and empty multi-selection answers as indeterminate. + pub fn from_rfd_files(value: Option>) -> Self { + Self::from_rfd(value.filter(|paths| !paths.is_empty())) + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn missing_and_empty_rfd_answers_never_establish_cancellation() { + assert_eq!(Outcome::::from_rfd(None), Outcome::Indeterminate); + assert_eq!(Outcome::>::from_rfd_files(Some(Vec::new())), Outcome::Indeterminate); + assert_eq!(Outcome::from_rfd_files(Some(vec!["a"])), Outcome::Selected(vec!["a"])); + for _capability in [Capability::Available, Capability::Unavailable("missing".into()), Capability::Unknown("timeout".into())] { + assert_eq!(Outcome::::from_rfd(None), Outcome::Indeterminate); + } + } + #[test] + fn mapping_preserves_explicit_cancellation_and_failure() { + assert_eq!(Outcome::::Cancelled.map(u32::from), Outcome::Cancelled); + assert_eq!(Outcome::::failed("worker stopped").map(u32::from), Outcome::failed("worker stopped")); + assert_eq!(Outcome::Selected(7_u8).map(u32::from), Outcome::Selected(7)); + } +} diff --git a/crates/platform/src/dialogs.rs b/crates/platform/src/dialogs.rs new file mode 100644 index 0000000000..b09c66be44 --- /dev/null +++ b/crates/platform/src/dialogs.rs @@ -0,0 +1,258 @@ +//! UI-thread picker creation with reserved waiting workers. No backend or application policy. +//! +//! `create` must call the native picker method eagerly on the event-loop thread, returning its +//! already-created future. Hosts retain the parent through transport AND their continuation. +//! A missing backend answer is indeterminate; only explicit backend evidence proves cancellation. +use crate::dialog_outcome::{DialogError, ErrorKind, Outcome}; +use std::{ + future::Future, + pin::Pin, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc::{self, Receiver, Sender, SyncSender, TryRecvError}, + }, + thread::JoinHandle, +}; +/// An already-created native picker future that a reserved worker can wait on. +pub type DialogFuture = Pin> + Send>>; + +/// Wait for a future without polling an idle native dialog. +pub fn block_on(future: impl Future) -> T { + struct Unpark(std::thread::Thread); + impl std::task::Wake for Unpark { + fn wake(self: Arc) { + self.0.unpark(); + } + } + let waker = std::task::Waker::from(Arc::new(Unpark(std::thread::current()))); + let mut context = std::task::Context::from_waker(&waker); + let mut future = std::pin::pin!(future); + loop { + if let std::task::Poll::Ready(value) = future.as_mut().poll(&mut context) { + return value; + } + std::thread::park(); + } +} +// Notification callbacks must not unwind a reserved worker after the UI observes readiness. +fn notify(wake: &dyn Fn()) { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(wake)); +} +fn worker_error(message: impl Into) -> DialogError { + DialogError::new(ErrorKind::Worker, message) +} +fn guarded(f: impl FnOnce() -> Outcome) -> Outcome { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Outcome::Failed(worker_error("The file-dialog backend failed"))) +} +/// Reserve the worker before opening a native sheet. A failed reservation never calls `create`. +/// No timeout is imposed on a live picker. Backend constructor/poll panics become explicit failures. +pub fn wait_prepared> + Send + 'static>( + create: impl FnOnce() -> F, + deliver: impl FnOnce(Outcome) + Send + 'static, +) -> std::io::Result> { + let (send, receive) = mpsc::channel::(); + let worker = std::thread::Builder::new().name("file-dialog".into()).spawn(move || { + deliver(guarded(|| match receive.recv() { + Ok(future) => block_on(future), + Err(_) => Outcome::Failed(worker_error("The file-dialog factory failed")), + })); + })?; + if let Ok(future) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(create)) { + send.send(future).map_err(|_| std::io::Error::other("The reserved file-dialog worker stopped"))?; + } + Ok(worker) +} + +type Job = (R, Sender>); +/// Clonable request endpoint. At most one queued, preparing or live request is accepted. +pub struct DialogClient { + sender: SyncSender>, + busy: Arc, + wake: Arc, +} +impl Clone for DialogClient { + fn clone(&self) -> Self { + Self { sender: self.sender.clone(), busy: self.busy.clone(), wake: self.wake.clone() } + } +} +impl DialogClient { + /// Queue a request without blocking and wake the host to pump it. + /// A busy or unavailable host answers with a worker failure; no second picker is opened. + pub fn request(&self, request: R) -> Receiver> { + let (answer, receive) = mpsc::channel(); + if self.busy.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err() { + let _ = answer.send(Outcome::Failed(worker_error("A file dialog is already pending"))); + } else if let Err(error) = self.sender.try_send((request, answer)) { + self.busy.store(false, Ordering::SeqCst); + let (_, answer) = match error { + mpsc::TrySendError::Full(job) | mpsc::TrySendError::Disconnected(job) => job, + }; + let _ = answer.send(Outcome::Failed(worker_error("The file-dialog host is unavailable"))); + } + notify(self.wake.as_ref()); + receive + } +} +struct Preparing { + request: R, + ready: Receiver<()>, + send: Sender>, + completion: Completion, +} +struct Completion { + done: Receiver>, + answer: Sender>, +} +impl Completion { + fn poll(&self) -> Option> { + match self.done.try_recv() { + Ok(outcome) => Some(outcome), + Err(TryRecvError::Empty) => None, + Err(TryRecvError::Disconnected) => Some(Outcome::Failed(worker_error("The file-dialog worker stopped without an answer"))), + } + } +} +enum State { + Preparing(Preparing), + Waiting(Completion), +} +/// Event-loop-owned transport. Dropping a reply does not release a live picker or its parent. +/// `pump` must run before consuming replies, and after app code that may enqueue a request. +/// The host must retain this service/window while `pending()` or its own continuation is pending. +pub struct NativeDialogs { + queue: Receiver>, + busy: Arc, + state: Option>, + wake: Arc, + check: Arc Result<(), DialogError> + Send + Sync>, +} +impl NativeDialogs { + /// Create a client and its event-loop-owned service without a backend preflight check. + pub fn new(wake: impl Fn() + Send + Sync + 'static) -> (DialogClient, Self) { + Self::with_preflight(wake, || Ok(())) + } + /// Optional host-owned advisory check, run on the reserved worker before any picker exists. + /// Hosts must bound this check. Unknown capability must permit the actual picker; return an + /// Unavailable error only when absence is proven. This service performs no filesystem probes. + pub fn with_preflight( + wake: impl Fn() + Send + Sync + 'static, + check: impl Fn() -> Result<(), DialogError> + Send + Sync + 'static, + ) -> (DialogClient, Self) { + let (sender, queue) = mpsc::sync_channel(1); + let busy = Arc::new(AtomicBool::new(false)); + let wake: Arc = Arc::new(wake); + (DialogClient { sender, busy: busy.clone(), wake: wake.clone() }, Self { queue, busy, state: None, wake, check: Arc::new(check) }) + } + /// Whether a queued, preparing or live picker still owns the transport reservation. + pub fn pending(&self) -> bool { + self.busy.load(Ordering::SeqCst) + } + /// Advance requests on the event-loop thread and publish completed replies. + /// Call before consuming replies and after enqueuing work. `create` must eagerly open + /// the native picker on this thread and return its already-created future. + pub fn pump(&mut self, mut create: impl FnMut(R) -> DialogFuture) { + if let Some(state) = self.state.take() { + match state { + State::Waiting(completion) => { + if let Some(outcome) = completion.poll() { + // Only the UI pump publishes replies, after releasing the transport. + // A continuation can therefore immediately request its next picker. + self.busy.store(false, Ordering::SeqCst); + let _ = completion.answer.send(outcome); + } else { + self.state = Some(State::Waiting(completion)); + } + } + State::Preparing(preparing) => { + if let Some(outcome) = preparing.completion.poll() { + self.busy.store(false, Ordering::SeqCst); + let _ = preparing.completion.answer.send(outcome); + } else if preparing.ready.try_recv().is_ok() { + let future = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| create(preparing.request))) + .unwrap_or_else(|_| Box::pin(async { Outcome::Failed(worker_error("The file-dialog factory failed")) })); + let _ = preparing.send.send(future); + self.state = Some(State::Waiting(preparing.completion)); + } else { + self.state = Some(State::Preparing(preparing)); + } + } + } + } + if self.state.is_none() + && let Ok((request, answer)) = self.queue.try_recv() + { + let (ready_send, ready) = mpsc::channel(); + let (send, receive) = mpsc::channel::>(); + let (done_send, done) = mpsc::channel(); + let check = self.check.clone(); + let wake = self.wake.clone(); + let started = std::thread::Builder::new().name("file-dialog".into()).spawn(move || { + let output = guarded(|| { + if let Err(error) = check() { + return Outcome::Failed(error); + } + if ready_send.send(()).is_err() { + return Outcome::Failed(worker_error("The file-dialog host stopped")); + } + notify(wake.as_ref()); + match receive.recv() { + Ok(future) => block_on(future), + Err(_) => Outcome::Failed(worker_error("The file-dialog host stopped")), + } + }); + let _ = done_send.send(output); + notify(wake.as_ref()); + }); + match started { + Ok(_) => self.state = Some(State::Preparing(Preparing { request, ready, send, completion: Completion { done, answer } })), + Err(error) => { + self.busy.store(false, Ordering::SeqCst); + let _ = answer.send(Outcome::Failed(worker_error(error.to_string()))); + notify(self.wake.as_ref()); + } + } + } + } +} +/// Holds close intent while a picker/continuation owns the parent. A retry never authorizes +/// discarding documents: the caller must run its ordinary unsaved-work policy again. +#[cfg(feature = "egui")] +#[derive(Default, Debug)] +pub struct DeferredClose { + held: bool, +} +#[cfg(feature = "egui")] +impl DeferredClose { + /// Hold actual close requests while a picker or app continuation is pending. + /// Return `true` once after settlement so the host retries its unsaved-work policy; + /// this never grants permission to discard changes or closes the viewport itself. + pub fn update(&mut self, ctx: &egui::Context, pending: bool) -> bool { + let outgoing = ctx.viewport(|v| { + v.commands + .iter() + .rev() + .find_map(|c| match c { + egui::ViewportCommand::Close => Some(true), + egui::ViewportCommand::CancelClose => Some(false), + _ => None, + }) + .unwrap_or(false) + }); + if pending { + let requested = outgoing || ctx.input(|i| i.viewport().close_requested()); + self.held |= requested; + // Every viewport command requests a repaint. An idle native picker must sleep. + if requested { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + } + false + } else if std::mem::take(&mut self.held) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + ctx.request_repaint(); + true + } else { + false + } + } +} diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs new file mode 100644 index 0000000000..b3fa54e077 --- /dev/null +++ b/crates/platform/src/lib.rs @@ -0,0 +1,11 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! Shared lifecycle mechanics; application state, theme choices and file policy stay in hosts. +#[cfg(feature = "appearance")] +pub mod appearance; +#[cfg(all(feature = "browser", target_arch = "wasm32"))] +pub mod browser; +pub mod dialog_outcome; +#[cfg(all(feature = "dialogs", not(target_arch = "wasm32")))] +pub mod dialogs; +#[cfg(all(feature = "appearance", unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +mod process; diff --git a/crates/platform/src/process.rs b/crates/platform/src/process.rs new file mode 100644 index 0000000000..24c4f7f4bd --- /dev/null +++ b/crates/platform/src/process.rs @@ -0,0 +1,53 @@ +//! Bounded, cancellable output capture for the desktop's one-shot settings fallback. + +/// Reads at most 8193 bytes from a pipe, without a detached reader or disk spool. +/// Cancellation/timeout drops the reader and kills the owned child; async-process reaps it. +pub(crate) async fn capture(program: &std::path::Path, args: &[&str], timeout: std::time::Duration) -> Option { + use futures_lite::io::AsyncReadExt; + use std::process::Stdio; + let mut child = async_process::Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .reap_on_drop(true) + .spawn() + .ok()?; + let stdout = child.stdout.take()?; + futures_lite::future::race( + async { + let mut bytes = Vec::new(); + stdout.take(8193).read_to_end(&mut bytes).await.ok()?; + if bytes.len() > 8192 { + return None; + } + if !child.status().await.ok()?.success() { + return None; + } + String::from_utf8(bytes).ok() + }, + async { + async_io::Timer::after(timeout).await; + None + }, + ) + .await +} +#[cfg(all(test, feature = "appearance", unix, not(target_os = "macos")))] +mod tests { + use super::capture; + #[test] + fn capture_checks_exit_status_size_and_deadline() { + use std::time::{Duration, Instant}; + futures_lite::future::block_on(async { + let shell = std::path::Path::new("/bin/sh"); + assert_eq!(capture(shell, &["-c", "printf hello"], Duration::from_secs(1)).await.as_deref(), Some("hello")); + assert_eq!(capture(shell, &["-c", "printf failure; exit 7"], Duration::from_secs(1)).await, None); + let before = Instant::now(); + assert_eq!(capture(shell, &["-c", "exec sleep 5"], Duration::from_millis(30)).await, None); + assert!(before.elapsed() < Duration::from_secs(1)); + assert_eq!(capture(shell, &["-c", "head -c 10000 /dev/zero"], Duration::from_secs(1)).await, None); + }); + } +} diff --git a/crates/platform/tests/browser_downloads.rs b/crates/platform/tests/browser_downloads.rs new file mode 100644 index 0000000000..a9dd94ae9b --- /dev/null +++ b/crates/platform/tests/browser_downloads.rs @@ -0,0 +1,98 @@ +#![cfg(all(target_arch = "wasm32", feature = "browser"))] +use craft_platform::browser::{DownloadOptions, PreparedDownload, download_bytes}; +use wasm_bindgen::{JsValue, prelude::wasm_bindgen}; +use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure}; +wasm_bindgen_test_configure!(run_in_browser); + +#[wasm_bindgen(module = "/tests/browser_harness.js")] +extern "C" { + fn setup(mode: &str); + fn restore(); + fn created_count() -> u32; + fn revoked_count() -> u32; + fn clicked_count() -> u32; + fn anchor_count() -> u32; + fn last_name() -> String; + fn last_mime() -> String; + fn timer_before_click() -> bool; + fn wait_for_cleanup() -> js_sys::Promise; +} +struct Restore; +impl Drop for Restore { + fn drop(&mut self) { + restore(); + } +} + +#[wasm_bindgen_test] +fn abandoning_a_prepared_download_releases_its_url() -> Result<(), JsValue> { + setup(""); + let _restore = Restore; + let prepared = PreparedDownload::bytes("export.txt", "text/plain", b"content")?; + assert_eq!(created_count(), 1); + drop(prepared); + assert_eq!(revoked_count(), 1); + assert_eq!(clicked_count(), 0); + assert_eq!(anchor_count(), 0); + Ok(()) +} + +#[wasm_bindgen_test] +fn failed_attachment_and_timer_do_not_click_or_leak() { + for mode in ["attach-error", "timer-error"] { + setup(mode); + let _restore = Restore; + assert!(download_bytes("export.txt", "text/plain", b"content", Default::default()).is_err()); + assert_eq!(created_count(), 1); + assert_eq!(revoked_count(), 1); + assert_eq!(clicked_count(), 0); + assert_eq!(anchor_count(), 0); + } +} + +#[wasm_bindgen_test] +async fn successful_download_releases_its_url_after_the_click() -> Result<(), JsValue> { + setup(""); + let _restore = Restore; + download_bytes("export.txt", "text/plain", b"content", DownloadOptions { revoke_after_ms: 5 })?; + assert_eq!(clicked_count(), 1); + assert_eq!(last_name(), "export.txt"); + assert_eq!(last_mime(), "text/plain"); + assert!(timer_before_click()); + assert_eq!(revoked_count(), 0); + assert_eq!(anchor_count(), 0); + wasm_bindgen_futures::JsFuture::from(wait_for_cleanup()).await?; + assert_eq!(revoked_count(), 1); + Ok(()) +} + +#[wasm_bindgen_test] +fn invalid_lifetime_cleans_a_prepared_download() { + setup(""); + let _restore = Restore; + assert!(download_bytes("export.txt", "text/plain", b"content", DownloadOptions { revoke_after_ms: 0 }).is_err()); + assert_eq!(revoked_count(), 1); + assert_eq!(clicked_count(), 0); +} + +#[wasm_bindgen_test] +fn failed_setup_does_not_allocate_a_url_or_click() { + for mode in ["element-error", "style-error"] { + setup(mode); + let _restore = Restore; + assert!(download_bytes("export.txt", "text/plain", b"content", Default::default()).is_err()); + assert_eq!(created_count(), 0); + assert_eq!(revoked_count(), 0); + assert_eq!(clicked_count(), 0); + assert_eq!(anchor_count(), 0); + } +} + +#[wasm_bindgen_test] +fn empty_name_is_rejected_before_allocating_resources() { + setup(""); + let _restore = Restore; + assert!(download_bytes(" ", "text/plain", b"content", Default::default()).is_err()); + assert_eq!(created_count(), 0); + assert_eq!(clicked_count(), 0); +} diff --git a/crates/platform/tests/browser_harness.js b/crates/platform/tests/browser_harness.js new file mode 100644 index 0000000000..fc652c31bd --- /dev/null +++ b/crates/platform/tests/browser_harness.js @@ -0,0 +1,42 @@ +// Test-only browser fault injection; no app runtime depends on this module. +let originals; +let created, revoked, clicked, scheduled, lastName, lastMime, timerBeforeClick; +export function setup(mode) { + created = 0; revoked = 0; clicked = 0; scheduled = 0; + lastName = ''; lastMime = ''; timerBeforeClick = false; + originals = { + create: URL.createObjectURL, revoke: URL.revokeObjectURL, + click: HTMLAnchorElement.prototype.click, + append: Node.prototype.appendChild, timer: window.setTimeout, + element: Document.prototype.createElement, + attribute: Element.prototype.setAttribute, + }; + URL.createObjectURL = function(blob) { created++; lastMime = blob.type; return originals.create.call(URL, blob); }; + URL.revokeObjectURL = function(url) { revoked++; return originals.revoke.call(URL, url); }; + HTMLAnchorElement.prototype.click = function() { + clicked++; lastName = this.download; timerBeforeClick = scheduled > 0; + }; + window.setTimeout = function(...args) { + if (mode === 'timer-error') throw new Error('timer failed'); + scheduled++; + return originals.timer.apply(window, args); + }; + if (mode === 'attach-error') Node.prototype.appendChild = function() { throw new Error('attachment failed'); }; + if (mode === 'element-error') Document.prototype.createElement = function() { throw new Error('element failed'); }; + if (mode === 'style-error') Element.prototype.setAttribute = function() { throw new Error('style failed'); }; +} +export function restore() { + URL.createObjectURL = originals.create; URL.revokeObjectURL = originals.revoke; + HTMLAnchorElement.prototype.click = originals.click; + Node.prototype.appendChild = originals.append; window.setTimeout = originals.timer; + Document.prototype.createElement = originals.element; + Element.prototype.setAttribute = originals.attribute; +} +export function created_count() { return created; } +export function revoked_count() { return revoked; } +export function clicked_count() { return clicked; } +export function anchor_count() { return document.querySelectorAll('a[download]').length; } +export function last_name() { return lastName; } +export function last_mime() { return lastMime; } +export function timer_before_click() { return timerBeforeClick; } +export function wait_for_cleanup() { return new Promise(resolve => originals.timer.call(window, resolve, 50)); } diff --git a/crates/platform/tests/dialog_lifecycle.rs b/crates/platform/tests/dialog_lifecycle.rs new file mode 100644 index 0000000000..1b78d03192 --- /dev/null +++ b/crates/platform/tests/dialog_lifecycle.rs @@ -0,0 +1,248 @@ +#![cfg(all(feature = "dialogs", not(target_arch = "wasm32")))] +use craft_platform::{ + dialog_outcome::{DialogError, ErrorKind, Outcome}, + dialogs::{NativeDialogs, wait_prepared}, +}; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + mpsc, +}; +use std::time::{Duration, Instant}; +fn pump_until( + service: &mut NativeDialogs, + mut create: impl FnMut(R) -> craft_platform::dialogs::DialogFuture, + until: impl Fn() -> bool, +) { + let deadline = Instant::now() + Duration::from_secs(3); + while !until() { + assert!(Instant::now() < deadline, "worker did not settle"); + service.pump(&mut create); + std::thread::yield_now(); + } +} +#[test] +fn factory_is_eager_on_caller_and_completion_on_worker() -> Result<(), Box> { + let caller = std::thread::current().id(); + let (tx, rx) = mpsc::channel(); + let worker = wait_prepared( + || { + assert_eq!(caller, std::thread::current().id()); + async { Outcome::Selected(42) } + }, + move |outcome| { + let _ = tx.send((outcome, std::thread::current().id())); + }, + )?; + let (outcome, thread) = rx.recv_timeout(Duration::from_secs(3))?; + assert_eq!(outcome, Outcome::Selected(42)); + assert_ne!(caller, thread); + assert!(worker.join().is_ok()); + Ok(()) +} +#[test] +fn constructor_and_poll_failures_are_not_cancellation() -> Result<(), Box> { + for construct in [false, true] { + let (tx, rx) = mpsc::channel(); + let worker = wait_prepared( + || { + if construct { + std::panic::resume_unwind(Box::new("constructor")); + } + async { + std::panic::resume_unwind(Box::new("poll")); + #[allow(unreachable_code)] + Outcome::::Cancelled + } + }, + move |outcome| { + let _ = tx.send(outcome); + }, + )?; + assert!(matches!(rx.recv_timeout(Duration::from_secs(3))?, Outcome::Failed(DialogError { kind: ErrorKind::Worker, .. }))); + assert!(worker.join().is_ok()); + } + Ok(()) +} +#[test] +fn queued_and_dropped_replies_keep_live_picker_busy() -> Result<(), Box> { + let (c, mut service) = NativeDialogs::<(), u8>::new(|| {}); + let reply = c.request(()); + assert!(service.pending()); + drop(reply); + let (release, wait) = mpsc::channel(); + let mut wait = Some(wait); + let created = Arc::new(AtomicUsize::new(0)); + let count = created.clone(); + pump_until( + &mut service, + move |()| { + count.fetch_add(1, Ordering::SeqCst); + let wait = wait.take(); + Box::pin(async move { + let _ = wait.map(|w| w.recv()); + Outcome::Selected(1) + }) + }, + || created.load(Ordering::SeqCst) == 1, + ); + assert!(service.pending()); + assert!(matches!(c.request(()).recv_timeout(Duration::from_secs(3))?, Outcome::Failed(_))); + release.send(())?; + let deadline = Instant::now() + Duration::from_secs(3); + while service.pending() { + assert!(Instant::now() < deadline); + service.pump(|()| Box::pin(async { Outcome::Indeterminate })); + std::thread::yield_now(); + } + Ok(()) +} +#[test] +fn proven_absence_skips_native_factory() -> Result<(), Box> { + let (c, mut service) = NativeDialogs::<(), u8>::with_preflight(|| {}, || Err(DialogError::new(ErrorKind::Unavailable, "test backend missing"))); + let reply = c.request(()); + let called = Arc::new(AtomicUsize::new(0)); + let count = called.clone(); + let mut result = None; + let deadline = Instant::now() + Duration::from_secs(3); + while result.is_none() { + assert!(Instant::now() < deadline); + service.pump(|()| { + count.fetch_add(1, Ordering::SeqCst); + Box::pin(async { Outcome::Selected(1) }) + }); + result = reply.try_recv().ok(); + std::thread::yield_now(); + } + assert_eq!(called.load(Ordering::SeqCst), 0); + assert!(matches!(result, Some(Outcome::Failed(DialogError { kind: ErrorKind::Unavailable, .. })))); + Ok(()) +} +#[test] +fn missing_backend_answer_is_ambiguous() { + assert_eq!(Outcome::::from_rfd(None), Outcome::Indeterminate); +} +#[cfg(feature = "egui")] +#[test] +fn held_close_retries_policy_without_granting_discard() { + let ctx = egui::Context::default(); + let mut close = craft_platform::dialogs::DeferredClose::default(); + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + let mut output = ctx.run_ui(input, |ui| assert!(!close.update(ui.ctx(), true))); + assert!(output.viewport_output[&egui::ViewportId::ROOT].commands.contains(&egui::ViewportCommand::CancelClose)); + output.textures_delta.clear(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| assert!(close.update(ui.ctx(), false))); + assert!(!output.viewport_output[&egui::ViewportId::ROOT].commands.contains(&egui::ViewportCommand::Close)); + output.textures_delta.clear(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| assert!(!close.update(ui.ctx(), false))); + output.textures_delta.clear(); +} +#[test] +fn notification_panic_cannot_kill_reserved_picker_worker() -> Result<(), Box> { + let (c, mut service) = NativeDialogs::<(), u8>::new(|| std::panic::resume_unwind(Box::new("wake failure"))); + let reply = c.request(()); + let mut result = None; + let deadline = Instant::now() + Duration::from_secs(3); + while result.is_none() { + assert!(Instant::now() < deadline); + service.pump(|()| Box::pin(async { Outcome::Selected(7) })); + result = reply.try_recv().ok(); + std::thread::yield_now(); + } + assert_eq!(result, Some(Outcome::Selected(7))); + Ok(()) +} + +#[test] +fn completion_between_pumps_cannot_reject_a_chained_request() -> Result<(), Box> { + let wakes = Arc::new(AtomicUsize::new(0)); + let count = wakes.clone(); + let (client, mut service) = NativeDialogs::::new(move || { + count.fetch_add(1, Ordering::SeqCst); + }); + let first = client.request(1); + let (release, wait) = mpsc::channel(); + let mut wait = Some(wait); + let created = Arc::new(AtomicUsize::new(0)); + let count = created.clone(); + pump_until( + &mut service, + move |value| { + count.fetch_add(1, Ordering::SeqCst); + let wait = wait.take(); + Box::pin(async move { + let _ = wait.map(|wait| wait.recv()); + Outcome::Selected(value) + }) + }, + || created.load(Ordering::SeqCst) == 1, + ); + // Finish after the host's pump, before its app continuation polls the reply. + release.send(())?; + let deadline = Instant::now() + Duration::from_secs(3); + while wakes.load(Ordering::SeqCst) < 3 { + assert!(Instant::now() < deadline, "worker did not publish completion"); + std::thread::yield_now(); + } + assert!(matches!(first.try_recv(), Err(mpsc::TryRecvError::Empty))); + assert!(service.pending(), "an unpublished completion still retains the parent"); + service.pump(|value| Box::pin(async move { Outcome::Selected(value) })); + assert_eq!(first.try_recv()?, Outcome::Selected(1)); + assert!(!service.pending()); + // The app can chain the next dialog immediately upon observing the first answer. + let second = client.request(2); + assert!(matches!(second.try_recv(), Err(mpsc::TryRecvError::Empty))); + let mut result = None; + while result.is_none() { + assert!(Instant::now() < deadline, "chained picker did not settle"); + service.pump(|value| Box::pin(async move { Outcome::Selected(value) })); + result = second.try_recv().ok(); + std::thread::yield_now(); + } + assert_eq!(result, Some(Outcome::Selected(2))); + assert!(!service.pending()); + Ok(()) +} + +#[cfg(feature = "egui")] +#[test] +fn pending_dialog_without_close_intent_does_not_schedule_viewport_work() { + let ctx = egui::Context::default(); + let mut close = craft_platform::dialogs::DeferredClose::default(); + // Let egui settle its own initial font/style passes before testing the idle host. + for _ in 0..4 { + let mut output = ctx.run_ui(egui::RawInput::default(), |_| {}); + output.textures_delta.clear(); + } + for _ in 0..3 { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(!close.update(ui.ctx(), true)); + }); + output.textures_delta.clear(); + let viewport = output.viewport_output.get(&egui::ViewportId::ROOT).unwrap(); + assert!(viewport.commands.is_empty(), "an idle picker must not enqueue commands: {:?}", viewport.commands); + assert_ne!(viewport.repaint_delay, std::time::Duration::ZERO, "an idle picker must not request another frame"); + } + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| assert!(!close.update(ui.ctx(), false))); + output.textures_delta.clear(); +} + +#[cfg(feature = "egui")] +#[test] +fn programmatic_close_is_held_until_the_pending_dialog_settles() { + let ctx = egui::Context::default(); + let mut close = craft_platform::dialogs::DeferredClose::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close); + assert!(!close.update(ui.ctx(), true)); + }); + output.textures_delta.clear(); + let commands = &output.viewport_output.get(&egui::ViewportId::ROOT).unwrap().commands; + let last_close = commands.iter().rev().find(|command| matches!(command, egui::ViewportCommand::Close | egui::ViewportCommand::CancelClose)); + assert_eq!(last_close, Some(&egui::ViewportCommand::CancelClose)); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| assert!(close.update(ui.ctx(), false))); + output.textures_delta.clear(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| assert!(!close.update(ui.ctx(), false))); + output.textures_delta.clear(); +} diff --git a/crates/print/src/lib.rs b/crates/print/src/lib.rs index 8fbea52b37..3c26974a56 100644 --- a/crates/print/src/lib.rs +++ b/crates/print/src/lib.rs @@ -42,7 +42,12 @@ impl std::error::Error for Error {} #[derive(Clone, Debug, PartialEq, Eq)] pub struct Printer { + /// The destination `lp -d` and the spooler know the printer by. pub name: String, + /// The printer's human name (CUPS `printer-info`), empty when the spooler gives none. A CUPS + /// queue name can't hold dots or spaces, so a printer added as `192.0.2.15` is the queue + /// `_192_0_2_15` described as `192.0.2.15`. Windows names are already human: empty there. + pub description: String, pub default: bool, /// Whether the Windows driver reports duplex support; None when unknown (CUPS). pub two_sided: Option, @@ -103,14 +108,30 @@ fn default_destination(out: &str) -> Option<&str> { out.lines().find_map(|l| l.strip_prefix("system default destination:")).map(str::trim) } -/// Parse `lpstat -p -d` output. +/// The longest description kept, in characters: a dialog shows a name, not a paragraph. +const MAX_DESCRIPTION: usize = 256; + +/// Parse `lpstat -p -d` output, or `lpstat -l -p -d`, whose indented `Description:` line under a +/// queue becomes its [`Printer::description`]. pub fn parse_lpstat(out: &str) -> Vec { let default = default_destination(out); - out.lines() - .filter_map(|l| l.strip_prefix("printer ")) - .filter_map(|l| l.split_whitespace().next()) - .map(|n| Printer { name: n.to_string(), default: default == Some(n), two_sided: None }) - .collect() + let mut printers: Vec = Vec::new(); + // Whether the last queue has had its Description line, even an empty one. + let mut described = false; + for line in out.lines() { + if let Some(name) = line.strip_prefix("printer ").and_then(|l| l.split_whitespace().next()) { + printers.push(Printer { name: name.to_string(), description: String::new(), default: default == Some(name), two_sided: None }); + described = false; + } else if line.starts_with(char::is_whitespace) && !described { + // Only a queue's own detail lines are indented; the first description wins. + let Some(description) = line.trim_start().strip_prefix("Description:") else { continue }; + if let Some(printer) = printers.last_mut() { + printer.description = description.trim().chars().take(MAX_DESCRIPTION).collect(); + described = true; + } + } + } + printers } /// Parse `lpstat -e` output: destination names, one per line. @@ -174,6 +195,13 @@ pub const HANDLED_OPTIONS: &[&str] = &["PageSize", "PageRegion", "Duplex", "Coll /// Caps on what a PPD may make the dialog hold (PPDs are text files from the printer vendor). const MAX_OPTIONS: usize = 400; const MAX_CHOICES: usize = 400; +/// Longest group, option or choice label kept, in characters; every option copies its group's. +const MAX_PPD_LABEL: usize = 256; + +/// `label`, cut to [`MAX_PPD_LABEL`] characters. +fn ppd_label(label: &str) -> String { + label.chars().take(MAX_PPD_LABEL).collect() +} /// A PPD keyword: printable ASCII without spaces, `/`, `:` or `=`. fn is_ppd_keyword(s: &str) -> bool { @@ -199,7 +227,7 @@ pub fn parse_ppd(ppd: &str) -> Vec { let line = line.trim_end_matches('\r'); if let Some(rest) = line.strip_prefix("*OpenGroup:") { let (k, l) = name_label(rest); - (group_key, group) = (k.to_string(), l.to_string()); + (group_key, group) = (k.to_string(), ppd_label(l)); } else if line.starts_with("*CloseGroup") { (group_key, group) = (String::new(), String::new()); } else if let Some(rest) = line.strip_prefix("*OpenUI") { @@ -207,7 +235,7 @@ pub fn parse_ppd(ppd: &str) -> Vec { let (key, label) = name_label(head.trim().trim_start_matches('*')); open = is_ppd_keyword(key).then(|| PrinterOption { key: key.to_string(), - label: label.to_string(), + label: ppd_label(label), group: group.clone(), choices: Vec::new(), default: String::new(), @@ -230,7 +258,7 @@ pub fn parse_ppd(ppd: &str) -> Vec { let head = rest.split_once(':').map_or(rest, |(h, _)| h); let (choice, label) = name_label(head); if is_ppd_keyword(choice) && o.choices.len() < MAX_CHOICES && o.choices.iter().all(|(c, _)| c != choice) { - o.choices.push((choice.to_string(), label.to_string())); + o.choices.push((choice.to_string(), ppd_label(label))); } } } @@ -345,9 +373,9 @@ fn lpstat_with(args: &[&str]) -> std::process::Command { c } -/// `lpstat -p -d`: the spooler's queues and the default destination. +/// `lpstat -l -p -d`: the spooler's queues with their descriptions, and the default destination. pub fn lpstat_command() -> std::process::Command { - lpstat_with(&["-p", "-d"]) + lpstat_with(&["-l", "-p", "-d"]) } /// `lpstat -e`: every destination CUPS can print to, including driverless network printers no @@ -392,9 +420,10 @@ pub fn printers_parsed(queues: &str, available: Option<&str>) -> Vec { let mut printers = parse_lpstat(queues); let default = default_destination(queues); if let Some(names) = available { + let mut seen: std::collections::HashSet = printers.iter().map(|p| p.name.clone()).collect(); for name in parse_lpstat_e(names) { - if !printers.iter().any(|p| p.name == name) { - printers.push(Printer { default: default == Some(name.as_str()), name, two_sided: None }); + if seen.insert(name.clone()) { + printers.push(Printer { default: default == Some(name.as_str()), name, description: String::new(), two_sided: None }); } } } @@ -409,7 +438,10 @@ pub(crate) fn printer_list(queues: impl IntoIterator)> = queues.into_iter().filter(|(n, _)| !n.trim().is_empty()).collect(); queues.sort_by(|a, b| a.0.cmp(&b.0)); queues.dedup_by(|a, b| a.0 == b.0); - queues.into_iter().map(|(name, two_sided)| Printer { default: default == Some(name.as_str()), name, two_sided }).collect() + queues + .into_iter() + .map(|(name, two_sided)| Printer { default: default == Some(name.as_str()), name, description: String::new(), two_sided }) + .collect() } /// A printer list in the text form craft-print's former PowerShell backend printed: one per line, @@ -428,8 +460,8 @@ pub fn parse_windows_printers(out: &str) -> Vec { _ => (l, None), }; match l.strip_prefix('*') { - Some(name) => Printer { name: name.to_string(), default: true, two_sided }, - None => Printer { name: l.to_string(), default: false, two_sided }, + Some(name) => Printer { name: name.to_string(), description: String::new(), default: true, two_sided }, + None => Printer { name: l.to_string(), description: String::new(), default: false, two_sided }, } }) .collect(); diff --git a/crates/print/src/sheets.rs b/crates/print/src/sheets.rs index d3c989cd80..bbb4c7c790 100644 --- a/crates/print/src/sheets.rs +++ b/crates/print/src/sheets.rs @@ -11,6 +11,7 @@ //! Every length, count and depth is bounded, and anything unreadable is an [`Error`], never a //! panic: the caller's PDF is input like any other. +use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -781,16 +782,27 @@ impl Reader<'_> { None } - fn rect(&mut self, obj: Option<&Obj>) -> Option<[f64; 4]> { - let obj = self.resolve(obj?)?; - let items = obj.array()?; - let mut v = [0.0; 4]; - for (slot, item) in v.iter_mut().zip(items) { - *slot = self.resolve(item)?.num()?; + /// Like [`resolve`](Self::resolve), but a direct object is borrowed, not copied. Inherited + /// page attributes are read once per page, so copying a large inline value would repeat that + /// work for every page outside the budget. + fn resolve_borrowed<'o>(&mut self, obj: &'o Obj) -> Option> { + match obj { + Obj::Ref(..) => self.resolve(obj).map(Cow::Owned), + direct => Some(Cow::Borrowed(direct)), } + } + + fn rect(&mut self, obj: Option<&Obj>) -> Option<[f64; 4]> { + let obj = self.resolve_borrowed(obj?)?; + let items = obj.array()?; + // The shape is checked before reading any element. if items.len() != 4 { return None; } + let mut v = [0.0; 4]; + for (slot, item) in v.iter_mut().zip(items) { + *slot = self.resolve_borrowed(item)?.num()?; + } let [x0, y0, x1, y1] = v; Some([x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)]) } @@ -938,7 +950,7 @@ pub(crate) fn read(data: &[u8]) -> Result, Error> { .map(|c| [c[0].max(media[0]), c[1].max(media[1]), c[2].min(media[2]), c[3].min(media[3])]) .filter(|c| c[2] > c[0] && c[3] > c[1]) .unwrap_or(media); - let rotate = here.rotate.as_ref().and_then(|r| reader.resolve(r)).and_then(|r| r.int()).unwrap_or(0).rem_euclid(360); + let rotate = here.rotate.as_ref().and_then(|r| reader.resolve_borrowed(r).and_then(|r| r.int())).unwrap_or(0).rem_euclid(360); // Not a multiple of 90 is invalid; such a page is shown unrotated. let rotate = if rotate % 90 == 0 { u32::try_from(rotate).unwrap_or(0) } else { 0 }; // Windows renders viewer visibility, not annotation print visibility. Only a plain diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs index fd5499e97f..db03fb8ac1 100644 --- a/crates/print/src/tests.rs +++ b/crates/print/src/tests.rs @@ -9,8 +9,8 @@ fn spooler_arguments_and_printer_list() { assert_eq!( parse_lpstat(out), [ - spool::Printer { name: "Office_Laser".into(), default: true, two_sided: None }, - spool::Printer { name: "Label_Writer".into(), default: false, two_sided: None } + spool::Printer { name: "Office_Laser".into(), description: String::new(), default: true, two_sided: None }, + spool::Printer { name: "Label_Writer".into(), description: String::new(), default: false, two_sided: None } ] ); assert!(parse_lpstat("lpstat: No destinations added.\nno system default destination\n").is_empty()); @@ -44,6 +44,32 @@ fn lpstat_output_is_untranslated() { assert!(envs.iter().any(|(k, v)| k == "SOFTWARE" && v.as_deref().is_some_and(|v| !v.is_empty())), "SOFTWARE missing: {envs:?}"); } +#[test] +fn a_queue_keeps_its_human_name() { + // A CUPS queue name can't hold dots, so macOS adds the printer at 192.0.2.15 as the queue + // `_192_0_2_15`. The dialog showed that underscored name; `lpstat -l` also gives the name the + // user knows, as the queue's Description. + let out = "printer _192_0_2_15 is idle. enabled since Thu Oct 1 09:00:00 2026\n\tForm mounted:\n\tDescription: 192.0.2.15\n\tAlerts: none\n\tLocation: Description: not this one\nprinter Label_Writer disabled since Thu Oct 1 09:00:00 2026 -\n\treason unknown\n\tDescription:\nprinter Office_Laser is idle.\r\n\tDescription: Office Laser, 2nd floor\r\n\tDescription: a second one is ignored\nDescription: not indented, not a detail\nsystem default destination: _192_0_2_15\n"; + assert_eq!( + parse_lpstat(out), + [ + spool::Printer { name: "_192_0_2_15".into(), description: "192.0.2.15".into(), default: true, two_sided: None }, + spool::Printer { name: "Label_Writer".into(), description: String::new(), default: false, two_sided: None }, + spool::Printer { name: "Office_Laser".into(), description: "Office Laser, 2nd floor".into(), default: false, two_sided: None }, + ], + "each queue takes its own first Description; an empty one stays empty" + ); + // A description before any queue belongs to none, and a huge one is cut to a name's length. + assert!(parse_lpstat("\tDescription: orphan\n").is_empty()); + // An empty first description is still the first: a later one doesn't replace it. + assert_eq!(parse_lpstat("printer Q is idle.\n\tDescription:\n\tDescription: Office\n")[0].description, ""); + let long = format!("printer Q is idle.\n\tDescription: {}\n", "é".repeat(10_000)); + assert_eq!(parse_lpstat(&long)[0].description.chars().count(), 256); + // The queues come from `lpstat -l`, so the descriptions are there to read. + let args: Vec<_> = spool::lpstat_command().get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + assert_eq!(args, ["-l", "-p", "-d"]); +} + #[test] fn driverless_printers_join_the_list_without_a_queue() { // A driverless network printer (IPP, discovered on the LAN) has no queue, so `lpstat -p` @@ -53,18 +79,21 @@ fn driverless_printers_join_the_list_without_a_queue() { assert_eq!( spool::printers_parsed(queues, Some("Basement_Color\nOffice_Laser\n")), [ - spool::Printer { name: "Office_Laser".into(), default: true, two_sided: None }, - spool::Printer { name: "Basement_Color".into(), default: false, two_sided: None }, + spool::Printer { name: "Office_Laser".into(), description: String::new(), default: true, two_sided: None }, + spool::Printer { name: "Basement_Color".into(), description: String::new(), default: false, two_sided: None }, ], "queues first, then the driverless destination; the queue listed twice is not doubled" ); // An old spooler without `-e` (CUPS < 1.7) keeps its queues; only the driverless names are lost. - assert_eq!(spool::printers_parsed(queues, None), [spool::Printer { name: "Office_Laser".into(), default: true, two_sided: None }]); + assert_eq!( + spool::printers_parsed(queues, None), + [spool::Printer { name: "Office_Laser".into(), description: String::new(), default: true, two_sided: None }] + ); // The default can itself be driverless (`lpoptions -d` names a destination no queue exists // for): it keeps its marker, so the dialog preselects the user's default, not the first queue. assert_eq!( spool::printers_parsed("system default destination: Basement_Color\n", Some("Basement_Color\n")), - [spool::Printer { name: "Basement_Color".into(), default: true, two_sided: None }], + [spool::Printer { name: "Basement_Color".into(), description: String::new(), default: true, two_sided: None }], "a default destination without a queue is still the default" ); assert!(spool::parse_lpstat_e("\n \n").is_empty(), "no destinations is empty, not [\"\"]"); @@ -156,16 +185,16 @@ fn windows_printers_carry_one_default_and_keep_their_names() { // Windows marks the system default with a `*` no queue name may contain; names hold spaces, // parentheses and non-ASCII letters, and the lines end with CRLF. let printers = parse_windows_printers("*Microsoft Print to PDF\r\nHP LaserJet 400 (Copy 2)\r\nКопир Canon iR\r\n\r\n*XPS via USB\r\n"); - assert_eq!(printers[0], Printer { name: "Microsoft Print to PDF".into(), default: true, two_sided: None }); - assert_eq!(printers[1], Printer { name: "HP LaserJet 400 (Copy 2)".into(), default: false, two_sided: None }); - assert_eq!(printers[2], Printer { name: "Копир Canon iR".into(), default: false, two_sided: None }); + assert_eq!(printers[0], Printer { name: "Microsoft Print to PDF".into(), description: String::new(), default: true, two_sided: None }); + assert_eq!(printers[1], Printer { name: "HP LaserJet 400 (Copy 2)".into(), description: String::new(), default: false, two_sided: None }); + assert_eq!(printers[2], Printer { name: "Копир Canon iR".into(), description: String::new(), default: false, two_sided: None }); // A spooler marking two defaults: the first still wins, so the dialog has one to preselect. - assert_eq!(printers[3], Printer { name: "XPS via USB".into(), default: false, two_sided: None }); + assert_eq!(printers[3], Printer { name: "XPS via USB".into(), description: String::new(), default: false, two_sided: None }); assert_eq!(parse_windows_printers("\r\n"), Vec::new()); let sided = parse_windows_printers("*Office PCL\t2\r\nOffice PS\t1\r\nTab\tName\t2\r\n"); - assert_eq!(sided[0], Printer { name: "Office PCL".into(), default: true, two_sided: Some(true) }); - assert_eq!(sided[1], Printer { name: "Office PS".into(), default: false, two_sided: Some(false) }); - assert_eq!(sided[2], Printer { name: "Tab\tName".into(), default: false, two_sided: Some(true) }); + assert_eq!(sided[0], Printer { name: "Office PCL".into(), description: String::new(), default: true, two_sided: Some(true) }); + assert_eq!(sided[1], Printer { name: "Office PS".into(), description: String::new(), default: false, two_sided: Some(false) }); + assert_eq!(sided[2], Printer { name: "Tab\tName".into(), description: String::new(), default: false, two_sided: Some(true) }); } /// A PPD shaped like a Fiery's: installable options, multi-line PostScript in the choices, Latin-1 @@ -227,6 +256,29 @@ fn printer_options_come_from_the_ppd() { assert!(spool::parse_ppd("*OpenUI *Broken\n*Broken A/B\n").is_empty(), "unclosed or malformed blocks are skipped"); } +#[test] +fn ppd_labels_are_capped_before_every_option_copies_its_group() { + let long = "G".repeat(100_000); + let mut ppd = format!("*OpenGroup: Big/{long}\n"); + for i in 0..300 { + ppd += &format!("*OpenUI *Opt{i}/{long}: PickOne\n*Opt{i} A/{long}: \"\"\n*CloseUI: *Opt{i}\n"); + } + let options = spool::parse_ppd(&ppd); + assert_eq!(options.len(), 300); + assert!(options.iter().all(|o| o.group.len() <= 256 && o.label.len() <= 256 && o.choices[0].1.len() <= 256)); + assert_eq!(options[0].group, "G".repeat(256)); +} + +#[test] +fn many_driverless_destinations_merge_in_linear_time() { + let names: String = (0..200_000).map(|i| format!("dest_{i}\n")).collect(); + let started = std::time::Instant::now(); + let printers = spool::printers_parsed("printer Office is idle.\n", Some(&format!("Office\n{names}dest_7\n"))); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed()); + assert_eq!(printers.len(), 200_001, "each destination once, queues first"); + assert_eq!(printers[0].name, "Office"); +} + #[test] fn printer_option_defaults_and_job_arguments() { let current = diff --git a/crates/print/src/tests/pdf_bounds.rs b/crates/print/src/tests/pdf_bounds.rs index a1729273ac..76b1409a47 100644 --- a/crates/print/src/tests/pdf_bounds.rs +++ b/crates/print/src/tests/pdf_bounds.rs @@ -254,3 +254,32 @@ fn an_inflate_limit_stops_later_stream_and_object_work() { assert_eq!(reader.budget.nodes, 0); assert_eq!(reader.budget.tokens, 0); } + +#[test] +fn an_oversized_inherited_media_box_is_not_copied_for_every_page() { + // One inline MediaBox far longer than four numbers, inherited by many small pages. + let pages = 4_000; + let media = vec!["0"; 25_000].join(" "); + let kids: Vec = (0..pages).map(|i| format!("{} 0 R", i + 3)).collect(); + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R >>".to_string(), + format!("<< /Type /Pages /Kids [{}] /Count {pages} /MediaBox [{media}] >>", kids.join(" ")), + ]; + objects.extend((0..pages).map(|_| "<< /Type /Page /Parent 2 0 R >>".to_string())); + let mut pdf = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, object) in objects.iter().enumerate() { + offsets.push(pdf.len()); + pdf.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes()); + } + let xref = pdf.len(); + pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f\r\n", objects.len() + 1).as_bytes()); + for offset in offsets { + pdf.extend_from_slice(format!("{offset:010} 00000 n\r\n").as_bytes()); + } + pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes()); + let started = std::time::Instant::now(); + let sheets = read(&pdf).unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed()); + assert_eq!(sheets.sheets.len(), pages); +} diff --git a/crates/print/src/tests/windows_native.rs b/crates/print/src/tests/windows_native.rs index 157fe68b9f..c42bccc917 100644 --- a/crates/print/src/tests/windows_native.rs +++ b/crates/print/src/tests/windows_native.rs @@ -21,10 +21,10 @@ fn windows_printers_are_sorted_once_with_their_default() { assert_eq!( printers, [ - Printer { name: "HP LaserJet 400 (Copy 2)".into(), default: false, two_sided: Some(true) }, - Printer { name: "Zebra Label".into(), default: false, two_sided: Some(false) }, - Printer { name: r"\\print01\Office, 2nd floor".into(), default: true, two_sided: Some(true) }, - Printer { name: "Копир Canon iR".into(), default: false, two_sided: None }, + Printer { name: "HP LaserJet 400 (Copy 2)".into(), description: String::new(), default: false, two_sided: Some(true) }, + Printer { name: "Zebra Label".into(), description: String::new(), default: false, two_sided: Some(false) }, + Printer { name: r"\\print01\Office, 2nd floor".into(), description: String::new(), default: true, two_sided: Some(true) }, + Printer { name: "Копир Canon iR".into(), description: String::new(), default: false, two_sided: None }, ] ); assert!(spool::printer_list([("Office".to_string(), None)], Some("Office 2")).iter().all(|p| !p.default)); diff --git a/crates/settings/src/document.rs b/crates/settings/src/document.rs index d5c80025f6..4e0a16f620 100644 --- a/crates/settings/src/document.rs +++ b/crates/settings/src/document.rs @@ -36,18 +36,22 @@ pub fn new_document(version: u32) -> DocumentMut { /// is kept. This is what keeps a renamed enum variant from resetting the whole file. pub fn deserialize_sections(doc: &DocumentMut) -> (T, Vec) { let defaults = T::default(); - let Ok(mut merged) = toml_edit::ser::to_document(&defaults) else { + let Ok(base) = toml_edit::ser::to_document(&defaults) else { return (defaults, Vec::new()); }; + let mut merged = base.clone(); let mut errors = Vec::new(); for (key, item) in doc.iter() { if key == SCHEMA_VERSION_KEY { continue; } - let mut candidate = merged.clone(); + // Each section is tried against the defaults alone, never against the sections accepted + // before it, so a file of many keys costs the defaults plus that key per key instead of + // the whole document so far. + let mut candidate = base.clone(); candidate[key] = item.clone(); - match toml_edit::de::from_document::(candidate.clone()) { - Ok(_) => merged = candidate, + match toml_edit::de::from_document::(candidate) { + Ok(_) => merged[key] = item.clone(), Err(e) => errors.push(SectionError { section: key.to_owned(), message: e.to_string() }), } } diff --git a/crates/settings/tests/recovery.rs b/crates/settings/tests/recovery.rs index 4af90bb4d6..437d18cfe2 100644 --- a/crates/settings/tests/recovery.rs +++ b/crates/settings/tests/recovery.rs @@ -47,6 +47,23 @@ fn bad_value_only_resets_its_section() { assert!(config_path(tmp.path()).exists(), "the file is not moved aside"); } +#[test] +fn many_unknown_keys_load_in_linear_time() { + // Each key was once tried against every key accepted before it. + let tmp = tempfile::tempdir().unwrap(); + let mut text = String::from("schema_version = 2\n"); + for i in 0..20_000 { + text.push_str(&format!("unknown_{i} = \"{}\"\n", "x".repeat(64))); + } + text.push_str("[general]\nlanguage = \"de\"\n"); + write_config(tmp.path(), &text); + let started = std::time::Instant::now(); + let (store, report) = open_in(tmp.path()); + assert!(report.section_errors.is_empty(), "{report:?}"); + assert_eq!(store.get().general.language, "de"); + assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed()); +} + #[test] fn newer_schema_opens_read_only_and_never_overwrites() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index babb3e2fd8..36c3bdbc94 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -389,7 +389,13 @@ impl Layout

{ } Action::Float { panel, .. } if !permissions(panel).floatable || !permissions(panel).movable => return Err(DockError::NotAllowed), Action::Close { panel } if !permissions(panel).closable => return Err(DockError::NotAllowed), - Action::MoveFloating { panel, .. } if !permissions(panel).movable => return Err(DockError::NotAllowed), + // The rectangle belongs to the whole floating group, so every member must allow it. + Action::MoveFloating { panel, .. } + if !permissions(panel).movable + || self.floating.iter().find(|g| g.panels.contains(panel)).is_some_and(|g| g.panels.iter().any(|p| !permissions(p).movable)) => + { + return Err(DockError::NotAllowed); + } Action::Open { anchor: Some(anchor), .. } if !permissions(anchor).accepts_tabs => return Err(DockError::NotAllowed), _ => {} } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index b0e5badd22..76d920893c 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -793,7 +793,9 @@ impl Renderer<'_, P> { } }); } - if response.enabled() && delta != Vec2::ZERO { + // Resizing changes the group's shared rectangle, which the model allows only when + // every member is movable. + if response.enabled() && delta != Vec2::ZERO && group.panels.iter().all(|p| (self.permissions)(p).movable) { let size = (rect.size() + delta).max(limits.min.max(vec2(40.0, self.style.tab_height + 20.0))).min(limits.max).min(screen.size()); self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [rect.left(), rect.top(), size.x, size.y] }); } diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 54d37df6cb..dfd3d8b0f1 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -129,6 +129,21 @@ fn protected_canvas_remains_present_and_cannot_be_grouped_with_panels() { assert!(next.contains(&1) && next.contains(&7)); } +#[test] +fn moving_a_floating_group_needs_every_member_movable() { + // sample() floats 5 and 6 together; 6 may not move, so naming 5 cannot move it either. + let permissions = |panel: &u32| Permissions { movable: *panel != 6, ..Permissions::default() }; + let layout = sample(); + let mut next = layout.clone(); + assert_eq!( + next.apply_with_permissions(Action::MoveFloating { panel: 5, rect: [0.0, 0.0, 300.0, 220.0] }, permissions), + Err(DockError::NotAllowed) + ); + assert_eq!(next, layout); + next.apply_with_permissions(Action::MoveFloating { panel: 5, rect: [0.0, 0.0, 300.0, 220.0] }, |_: &u32| Permissions::default()).unwrap(); + assert_eq!(next.floating[0].rect, [0.0, 0.0, 300.0, 220.0]); +} + #[test] fn close_and_restore_preserve_fixed_side_and_floating_geometry() { let mut layout = Layout { @@ -852,6 +867,48 @@ fn protected_group_member_blocks_whole_group_gesture_and_host_drop() { } } +/// Drags the floating group's resize grip in `sample()` and returns every action emitted. +fn resize_floating_group(permissions: impl Fn(&u32) -> Permissions + Copy) -> Vec> { + let ctx = Context::default(); + let layout = sample(); + // sample() floats 5 and 6 at [80, 70, 300, 220]; the grip is its bottom-right corner. + let (start, end) = (pos2(374.0, 284.0), pos2(398.0, 308.0)); + let mut actions = Vec::new(); + for events in [ + vec![], + vec![], + vec![Event::PointerMoved(start), pointer_button(start, true)], + vec![Event::PointerMoved(end)], + vec![pointer_button(end, false)], + ] { + let mut out = DockOutput::default(); + ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), events, ..Default::default() }, |ui| { + let style = DockStyle::from_ui(ui); + out = DockArea::new(Id::new("resize-area")).show( + ui, + &layout, + &style, + |p| format!("Panel {p}"), + permissions, + |ui, _| { + ui.label("Body"); + }, + ); + }) + .textures_delta + .clear(); + actions.extend(out.actions); + } + actions +} + +#[test] +fn protected_group_member_blocks_floating_group_resize() { + let moved = |actions: &[Action]| actions.iter().any(|a| matches!(a, Action::MoveFloating { .. })); + assert!(moved(&resize_floating_group(|_| Permissions::default())), "the grip resizes a movable group"); + assert!(!moved(&resize_floating_group(|p| if *p == 6 { Permissions::PROTECTED } else { Permissions::default() }))); +} + #[test] fn chrome_focus_classifies_rendered_tab_but_excludes_body_text_field_and_invalid_layout() { let ctx = Context::default(); diff --git a/crates/ui/src/printing.rs b/crates/ui/src/printing.rs index 523ecfa554..bdcf55277e 100644 --- a/crates/ui/src/printing.rs +++ b/crates/ui/src/printing.rs @@ -1,14 +1,65 @@ //! Printer selection and asynchronous job feedback, independent of any spooler or document. //! Hosts provide workers; applications own PDF generation, commands and translated wording. +use std::collections::HashMap; use std::sync::mpsc::{Receiver, TryRecvError}; #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Printer { + /// The spooler's destination: what [`Settings::printer`] and jobs name. pub name: String, + /// What the dialog shows; empty shows `name`. CUPS, for one, describes the queue + /// `_192_0_2_15` as `192.0.2.15`, the name the user gave the printer. + pub label: String, pub default: bool, } +/// The text the dialog shows for each of `printers`, in order: its label, or its name when it has +/// none. Text two printers would share is followed by the name in brackets, so neither hides the +/// other; when even that text is shared (another printer's label is `Office (Office_1)`), those +/// printers show their names, which the spooler keeps distinct. +pub fn shown_names(printers: &[Printer]) -> Vec { + let base: Vec<&str> = printers.iter().map(|p| if p.label.trim().is_empty() { p.name.as_str() } else { p.label.as_str() }).collect(); + let mut base_count: HashMap<&str, usize> = HashMap::with_capacity(base.len()); + for text in &base { + *base_count.entry(text).or_default() += 1; + } + let mut shown: Vec = printers + .iter() + .zip(&base) + .map(|(printer, text)| { + let shared = base_count.get(text).is_some_and(|n| *n > 1); + if shared && *text != printer.name { format!("{text} ({})", printer.name) } else { (*text).to_owned() } + }) + .collect(); + // Which printers show each text. A shared text turns every printer showing it into its name; + // a printer that shows its name never changes again, so each moves at most once and the + // whole cascade stays linear in the number of printers. + let mut by_text: HashMap> = HashMap::with_capacity(shown.len()); + for (i, text) in shown.iter().enumerate() { + by_text.entry(text.clone()).or_default().push(i); + } + let mut pending: Vec = by_text.iter().filter(|(_, ids)| ids.len() > 1).map(|(text, _)| text.clone()).collect(); + while let Some(text) = pending.pop() { + let Some(ids) = by_text.get_mut(&text) else { continue }; + if ids.len() < 2 { + continue; + } + let (stay, moving): (Vec, Vec) = ids.iter().partition(|&&i| printers.get(i).is_some_and(|p| p.name == text)); + *ids = stay; + for i in moving { + let (Some(printer), Some(slot)) = (printers.get(i), shown.get_mut(i)) else { continue }; + slot.clone_from(&printer.name); + let ids = by_text.entry(printer.name.clone()).or_default(); + ids.push(i); + if ids.len() == 2 { + pending.push(printer.name.clone()); + } + } + } + shown +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Duplex { Off, @@ -160,13 +211,15 @@ impl State { ui.add_enabled_ui(!self.busy(), |ui| { let width = ui.available_width().clamp(32.0, 230.0); let printer_label = ui.label(labels.printer); + let shown = shown_names(&self.printers); + let selected = self.printers.iter().zip(&shown).find(|(p, _)| p.name == self.settings.printer).map(|(_, text)| text.as_str()); egui::ComboBox::from_id_salt("printer") .width(width) .wrap_mode(egui::TextWrapMode::Truncate) - .selected_text(if self.settings.printer.is_empty() { labels.select_printer } else { &self.settings.printer }) + .selected_text(if self.settings.printer.is_empty() { labels.select_printer } else { selected.unwrap_or(&self.settings.printer) }) .show_ui(ui, |ui| { - for printer in &self.printers { - ui.selectable_value(&mut self.settings.printer, printer.name.clone(), &printer.name); + for (printer, text) in self.printers.iter().zip(&shown) { + ui.selectable_value(&mut self.settings.printer, printer.name.clone(), text); } }) .response diff --git a/crates/ui/src/printing/tests.rs b/crates/ui/src/printing/tests.rs index 1fb84a8c3e..caddd58a4f 100644 --- a/crates/ui/src/printing/tests.rs +++ b/crates/ui/src/printing/tests.rs @@ -1,7 +1,103 @@ use super::*; fn queue(name: &str, default: bool) -> Printer { - Printer { name: name.into(), default } + Printer { name: name.into(), label: String::new(), default } +} + +fn labelled(name: &str, label: &str) -> Printer { + Printer { name: name.into(), label: label.into(), default: false } +} + +/// The pass-by-pass resolution `shown_names` replaced, to check they agree. +fn shown_names_by_passes(printers: &[Printer]) -> Vec { + let base: Vec<&str> = printers.iter().map(|p| if p.label.trim().is_empty() { p.name.as_str() } else { p.label.as_str() }).collect(); + let mut shown: Vec = printers + .iter() + .zip(&base) + .map(|(printer, text)| { + let shared = base.iter().filter(|other| *other == text).count() > 1; + if shared && *text != printer.name { format!("{text} ({})", printer.name) } else { (*text).to_owned() } + }) + .collect(); + loop { + let shared: Vec = shown.iter().map(|text| shown.iter().filter(|other| *other == text).count() > 1).collect(); + let mut changed = false; + for ((text, printer), shared) in shown.iter_mut().zip(printers).zip(shared) { + if shared && *text != printer.name { + text.clone_from(&printer.name); + changed = true; + } + } + if !changed { + return shown; + } + } +} + +/// Each printer's label is the name the one before it falls back to, so every pass of the +/// old resolution freed exactly one more printer. +fn cascade(n: usize) -> Vec { + let mut printers = vec![labelled("n0", "x"), labelled("n1", "x"), labelled("n2", "x (n0)")]; + printers.extend((3..n).map(|i| labelled(&format!("n{i}"), &format!("n{}", i - 1)))); + printers +} + +#[test] +fn collisions_resolve_like_the_pass_by_pass_rule() { + let names = ["a", "b", "c", "Office", "Office_1", "x"]; + let labels = ["", "a", "b", "Office", "Office (Office_1)", "x (a)", "a (b)", "c"]; + let mut seed = 7u32; + for _ in 0..2000 { + let printers: Vec = (0..5) + .map(|_| { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + labelled(names[(seed >> 8) as usize % names.len()], labels[(seed >> 16) as usize % labels.len()]) + }) + .collect(); + assert_eq!(shown_names(&printers), shown_names_by_passes(&printers), "{printers:?}"); + } + assert_eq!(shown_names(&cascade(40)), shown_names_by_passes(&cascade(40))); +} + +#[test] +fn a_long_collision_cascade_stays_fast() { + let printers = cascade(20_000); + let started = std::time::Instant::now(); + let shown = shown_names(&printers); + assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + assert_eq!(shown[0], "n0"); + assert_eq!(shown[1], "x (n1)"); + assert!(shown[2..].iter().zip(&printers[2..]).all(|(s, p)| *s == p.name)); +} + +#[test] +fn the_dialog_shows_a_printers_label_and_keeps_its_queue_name() { + // CUPS can't put dots in a queue name: the printer added as 192.0.2.15 is `_192_0_2_15`. + let printers = [labelled("_192_0_2_15", "192.0.2.15"), queue("Plain_Queue", false), labelled("Blank", " ")]; + assert_eq!(shown_names(&printers), ["192.0.2.15", "Plain_Queue", "Blank"], "the label, else the name"); + // Two printers described alike stay apart by their queue names; a unique label stays bare. + let printers = [labelled("Office_1", "Office"), labelled("Office_2", "Office"), labelled("Lab", "Lab printer")]; + assert_eq!(shown_names(&printers), ["Office (Office_1)", "Office (Office_2)", "Lab printer"]); + // A label that is another queue's name doesn't pass for that queue. + assert_eq!(shown_names(&[queue("Office", false), labelled("Office_2", "Office")]), ["Office", "Office (Office_2)"]); + // A label that is another printer's bracketed text doesn't make two entries read alike: the + // printers whose text is still shared show their queue names. + let printers = [labelled("Office_1", "Office"), labelled("Office_2", "Office"), labelled("Office_3", "Office (Office_1)")]; + assert_eq!(shown_names(&printers), ["Office_1", "Office (Office_2)", "Office_3"]); + assert!(shown_names(&[]).is_empty()); + + // Choosing still selects the queue: jobs go to the name, not the label. + let ctx = egui::Context::default(); + let mut state = State::default(); + let discover: Discover = Box::new(|| { + let (sender, receiver) = std::sync::mpsc::channel(); + sender.send(vec![Printer { name: "_192_0_2_15".into(), label: "192.0.2.15".into(), default: true }]).unwrap(); + receiver + }); + assert!(state.refresh(&discover)); + state.poll(&ctx); + assert_eq!(state.settings.printer, "_192_0_2_15"); + assert!(state.ready()); } #[test] diff --git a/crates/window/Cargo.toml b/crates/window/Cargo.toml new file mode 100644 index 0000000000..54db833d8d --- /dev/null +++ b/crates/window/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "craft-window" +description = "Decide who draws the window frame on Linux (the compositor or the app) and apply it, so every Craft app gets the same native titlebar and borders per desktop." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[features] +# `apply`/`decorations`: decide decorations and set them on an `egui::ViewportBuilder`. +egui = ["dep:egui"] + +[dependencies] +egui = { workspace = true, optional = true } + +# Only Linux and the BSDs probe a Wayland compositor; everywhere else the frame is the OS's. +[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies] +wayland-client = "0.31" + +[lints] +workspace = true diff --git a/crates/window/README.md b/crates/window/README.md new file mode 100644 index 0000000000..75b4c6818a --- /dev/null +++ b/crates/window/README.md @@ -0,0 +1,70 @@ +craft-window +============ + +Decide who draws the window frame — the desktop or the app — so every Craft app shows the same +titlebar and borders on a given desktop. + +## Why + +egui apps either keep the desktop's window frame (titlebar, borders, window buttons) or turn it off +and draw their own. Across the suite this had drifted: + +- some apps always drew their own frame on Linux (so KDE's titlebar was replaced by the app's), +- some always kept the desktop's, +- some probed the compositor and only drew their own on GNOME. + +So two Craft apps open side by side on KDE could wear different titlebars. This crate makes the +decision in one place, matching each desktop. + +## The rule + +| Platform | Frame | +| --- | --- | +| macOS, Windows | desktop (the OS) | +| Linux/BSD on X11 | desktop (the window manager) | +| Linux/BSD on Wayland **with** `zxdg_decoration_manager_v1` (KDE, Sway, Hyprland, COSMIC) | desktop (the compositor) | +| Linux/BSD on Wayland **without** it (GNOME's Mutter) | the app | + +When the app draws the frame, the decision carries the window-button `Layout` the desktop names +(GNOME's `button-layout`), so the app's header bar puts minimize/maximize/close where that desktop +puts them. This crate decides *whether* and *where*; drawing the buttons stays in each app, whose +title bars differ. + +### Override + +`_TITLEBAR` forces the choice. With the default prefix `CRAFT`: `CRAFT_TITLEBAR=app` forces +the app frame, `=system` (or `=desktop`) forces the desktop frame. Apps pass their own prefix +(`Prefix::new("PDFCRAFT")` → `PDFCRAFT_TITLEBAR`) so each keeps its own variable name. + +## Use + +```rust,ignore +use craft_window::{Choice, Prefix, decorate}; + +// Once at startup, before the window is created: +let choice = Choice::probe(Prefix::new("PHOTOCRAFT")); +let viewport = decorate(egui::ViewportBuilder::default().with_title("PhotoCraft"), choice.frame()); + +// If the app draws the frame, lay the header-bar buttons out by the desktop's order: +if let Some(layout) = choice.frame().layout() { + // layout.left / layout.right -> draw Minimize/Maximize/Close there +} +``` + +An app that offers a "System title bar" preference checks `choice.overridden()` and its own setting, +and can override the probe by setting the frame to `Frame::Desktop`. + +The `egui` feature adds [`decorate`]. Without it, the crate is pure decision logic (`Choice`, +`Frame`, `Layout`) with no egui dependency. + +## Notes + +- The Wayland probe opens a short-lived connection and reads the global registry once, on its own + thread with a 500 ms timeout; on failure or timeout it keeps the desktop's frame. Call it once at + startup. +- It never touches the connection winit inherits: when `WAYLAND_SOCKET` is set (a compositor handed + the app an open descriptor), the probe skips connecting and keeps the desktop frame, so it can't + consume the socket winit needs. +- The GNOME `button-layout` lookup (`gsettings`) runs behind the same bounded worker, so a stalled + `gsettings` can't block startup either. +- `#![forbid(unsafe_code)]`, and the never-crash lints the workspace requires. diff --git a/crates/window/src/lib.rs b/crates/window/src/lib.rs new file mode 100644 index 0000000000..42f936c58a --- /dev/null +++ b/crates/window/src/lib.rs @@ -0,0 +1,439 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Decide who draws the window frame, so every Craft app shows the same titlebar and borders on a +//! given desktop. +//! +//! egui apps either let the desktop draw the window frame (the title bar, borders and window +//! buttons) or turn it off and draw their own. Across the suite this decision had drifted: some +//! apps always drew their own frame on Linux, some always kept the desktop's, and some probed the +//! compositor — so on KDE, say, one app wore KWin's title bar while another wore its own. This +//! crate makes the decision one place. +//! +//! The rule, by platform: +//! +//! - **macOS and Windows:** the OS always draws the frame ([`Frame::Desktop`]). (An app that insets +//! its content under the traffic lights, or draws its own caption buttons on Windows, still asks +//! the OS for a decorated window and overdraws it; that is the app's choice and not this crate's.) +//! - **Linux and the BSDs, X11:** the window manager draws the frame ([`Frame::Desktop`]). +//! - **Linux and the BSDs, Wayland:** a compositor that offers server-side decorations +//! (`zxdg_decoration_manager_v1` — KDE, Sway, Hyprland, COSMIC) draws the frame +//! ([`Frame::Desktop`]). One that does not (GNOME's Mutter) leaves the frame to the app +//! ([`Frame::App`]): without this, winit draws an imitation frame that matches no desktop. +//! +//! An environment variable overrides the choice, for users whose compositor the probe can't read +//! or who simply prefer the other frame. With the default prefix `CRAFT`, `CRAFT_TITLEBAR=app` +//! forces [`Frame::App`] and `=system` (or `=desktop`) forces [`Frame::Desktop`]; apps may pass +//! their own prefix (`PDFCRAFT`, `FIGCRAFT`, …) so each keeps its own variable name. +//! +//! When the app draws the frame, [`Frame::App`] carries the [`Layout`] of window buttons the +//! desktop names (GNOME's `button-layout`), so the app's header bar puts minimize, maximize and +//! close where that desktop puts them. This crate decides *whether* and *where*; drawing the +//! buttons stays with each app (their title bars differ). +//! +//! # With egui +//! +//! The `egui` feature adds [`decorate`], which applies the decision to an +//! [`egui::ViewportBuilder`] before the window is created: +//! +//! ```ignore +//! let viewport = egui::ViewportBuilder::default().with_title("PhotoCraft"); +//! // The app may still prefer its own frame when the user asked for it in preferences: +//! let choice = craft_window::Choice::probe(craft_window::Prefix::default()); +//! let viewport = craft_window::decorate(viewport, choice.frame()); +//! ``` +//! +//! The probe opens a short-lived Wayland connection and reads the global registry once; it never +//! touches the connection winit inherits. Call it once at startup. + +/// The environment-variable prefix an app overrides the frame with: `_TITLEBAR`. +/// +/// `Prefix::default()` is `CRAFT`, so `CRAFT_TITLEBAR`. An app that wants its own name passes +/// [`Prefix::new`] (`Prefix::new("PDFCRAFT")` reads `PDFCRAFT_TITLEBAR`). The name is used as +/// given; it should be ASCII letters, digits and underscores, as environment names are. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Prefix(&'static str); + +impl Default for Prefix { + fn default() -> Self { + Self("CRAFT") + } +} + +impl Prefix { + /// An app-specific prefix, so the override variable is `_TITLEBAR`. + pub const fn new(prefix: &'static str) -> Self { + Self(prefix) + } + + /// The environment variable this prefix reads, e.g. `CRAFT_TITLEBAR`. + pub fn var_name(self) -> String { + format!("{}_TITLEBAR", self.0) + } +} + +/// Who draws the window frame. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Frame { + /// The desktop draws it: the OS on macOS and Windows, the window manager on X11, the + /// compositor on a Wayland session with server-side decorations. The app leaves decorations on. + Desktop, + /// The app draws it (GNOME's Wayland session, or an override). The app turns decorations off + /// and draws a header bar with the window buttons in this [`Layout`]. + App(Layout), +} + +impl Frame { + /// Whether the app should keep the OS/compositor decorations on (`true` for [`Frame::Desktop`]). + /// This is the value to pass to `egui::ViewportBuilder::with_decorations`. + pub fn decorations(&self) -> bool { + matches!(self, Frame::Desktop) + } + + /// The window-button layout when the app draws the frame, else `None`. + pub fn layout(&self) -> Option<&Layout> { + match self { + Frame::App(layout) => Some(layout), + Frame::Desktop => None, + } + } +} + +/// How the frame was decided, so an app can log it or offer a "System title bar" preference that +/// knows the current state. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Choice { + frame: Frame, + /// `Some(true)` when `_TITLEBAR` forced the app frame, `Some(false)` when it forced the + /// desktop frame, `None` when the platform decided. + overridden: Option, +} + +impl Choice { + /// Probe the running platform and desktop and decide who draws the frame. + /// + /// `prefix` names the override variable (`_TITLEBAR`). On macOS, Windows and X11 this + /// does no I/O; on a Wayland session it opens a short-lived connection to read the registry. + pub fn probe(prefix: Prefix) -> Self { + match override_frame(&prefix.var_name()) { + Some(true) => Self { frame: Frame::App(Layout::from_desktop()), overridden: Some(true) }, + Some(false) => Self { frame: Frame::Desktop, overridden: Some(false) }, + None if app_draws_frame() => Self { frame: Frame::App(Layout::from_desktop()), overridden: None }, + None => Self { frame: Frame::Desktop, overridden: None }, + } + } + + /// The decided frame. + pub fn frame(&self) -> &Frame { + &self.frame + } + + /// The decided frame, consumed. + pub fn into_frame(self) -> Frame { + self.frame + } + + /// Whether `_TITLEBAR` set the frame: `Some(true)` it forced the app's, `Some(false)` + /// the desktop's, `None` the platform decided. + pub fn overridden(&self) -> Option { + self.overridden + } +} + +/// Read ``: `app` → force the app frame, `system`/`desktop` → force the desktop frame, +/// anything else (or unset) → let the platform decide. +fn override_frame(var: &str) -> Option { + parse_override(std::env::var(var).ok().as_deref()) +} + +/// The override a `_TITLEBAR` value asks for: `Some(true)` the app frame, `Some(false)` the +/// desktop frame, `None` to let the platform decide. Pure, so it is tested without the environment. +fn parse_override(value: Option<&str>) -> Option { + match value.map(str::trim) { + Some("app") => Some(true), + Some("system" | "desktop") => Some(false), + _ => None, + } +} + +/// A window button. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Button { + Minimize, + Maximize, + Close, +} + +/// Which window buttons go on which end of the app-drawn header bar, outermost last. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Layout { + pub left: Vec