diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
index dac20b9d21..6a88886d4e 100644
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -41,6 +41,9 @@ jobs:
packages: mesa-vulkan-drivers libvulkan1
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
+ # Test binaries without debug info or symbols: about a third of the size, and a panic still
+ # names its file and line.
+ dev-strip: true
# No debuginfo on Windows: writing PDBs for every test binary is a large part of its link
# time. A panic still names its file and line; only backtrace frames lose theirs, and the
# Linux and macOS legs keep line tables.
@@ -86,22 +89,28 @@ jobs:
cargo test -p craft-image-codecs -p craft-text --no-run --locked
command: |
# The tests run once, with every feature, in parallel across test binaries; nextest skips
- # doctests, so `cargo test --doc` runs them. The default-feature compile is the lint leg's
+ # doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose
+ # tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's
# first clippy run; the last command runs the crates whose tests check behaviour with a
# feature off, which an all-features build cannot reach.
- cargo nextest run --workspace --all-features --locked --profile ci
+ cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests
+ cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench
cargo test --workspace --doc --all-features --locked
- cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci
+ cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests
windows-command: |
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
- cargo nextest run --workspace --all-features --locked --profile ci
+ cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests
+ cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench
cargo test --workspace --doc --all-features --locked
- cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci
+ cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests
msrv:
name: Rust 1.95
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
+ # Its own dependency-cache entry: the calls in this file share one job id, so without a name
+ # they would write the same key.
+ cache-name: msrv
os: '["ubuntu-latest"]'
toolchain: 1.95.0
targets: ""
@@ -116,6 +125,7 @@ jobs:
name: UI and settings WASM
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
+ cache-name: wasm
os: '["ubuntu-latest"]'
targets: wasm32-unknown-unknown
tools: ""
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index f5a4217d82..085306ffef 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -11,6 +11,7 @@ author, source and license. Library code and original assets are under the repos
| `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files |
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 |
| `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 |
+| `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 |
| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
diff --git a/Cargo.lock b/Cargo.lock
index 2accb3454f..51db3db13f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1809,6 +1809,10 @@ dependencies = [
"craft-gcode",
"craft-geom",
"craft-gif",
+ "craft-gpu",
+ "craft-gpu-null",
+ "craft-gpu-providers",
+ "craft-gpu-wgpu",
"craft-gridcraft-format",
"craft-gzip",
"craft-har",
@@ -1824,6 +1828,7 @@ dependencies = [
"craft-imaging",
"craft-indd",
"craft-ipc",
+ "craft-ipp",
"craft-java-class",
"craft-jmap",
"craft-jpeg",
@@ -1870,6 +1875,7 @@ dependencies = [
"craft-platform",
"craft-plist",
"craft-plotter",
+ "craft-ppt-binary",
"craft-pptx",
"craft-prc",
"craft-prepress",
@@ -1914,6 +1920,7 @@ dependencies = [
"craft-tiff",
"craft-time",
"craft-timeline",
+ "craft-tracked",
"craft-ui",
"craft-update",
"craft-usd",
@@ -2046,10 +2053,8 @@ name = "craft-automation"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
- "craft-ai-agents",
- "craft-atomic",
"craft-behavior",
- "craft-flags",
+ "craft-control",
"craft-host",
"craft-keymap",
"craft-platform",
@@ -2109,6 +2114,7 @@ dependencies = [
name = "craft-captions"
version = "0.1.0"
dependencies = [
+ "craft-media",
"craft-media-testkit",
"craft-timeline",
"craft-xml",
@@ -2314,7 +2320,9 @@ name = "craft-develop"
version = "0.1.0"
dependencies = [
"craft-develop-model",
+ "craft-render-parity",
"proptest",
+ "rayon",
"serde",
]
@@ -2798,6 +2806,40 @@ dependencies = [
"image",
]
+[[package]]
+name = "craft-gpu"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "craft-gpu-null"
+version = "0.1.0"
+dependencies = [
+ "craft-gpu",
+]
+
+[[package]]
+name = "craft-gpu-providers"
+version = "0.1.0"
+dependencies = [
+ "craft-gpu",
+ "craft-gpu-null",
+]
+
+[[package]]
+name = "craft-gpu-wgpu"
+version = "0.1.0"
+dependencies = [
+ "craft-gpu",
+ "craft-gpu-providers",
+ "pollster 0.4.0",
+ "wgpu",
+]
+
[[package]]
name = "craft-gridcraft-format"
version = "0.1.0"
@@ -2988,6 +3030,10 @@ dependencies = [
"widestring",
]
+[[package]]
+name = "craft-ipp"
+version = "0.1.0"
+
[[package]]
name = "craft-java-class"
version = "0.1.0"
@@ -3576,10 +3622,24 @@ dependencies = [
name = "craft-plotter"
version = "0.1.0"
dependencies = [
+ "kurbo",
"serde",
"thiserror 2.0.21",
]
+[[package]]
+name = "craft-ppt-binary"
+version = "0.1.0"
+dependencies = [
+ "craft-cfb",
+ "craft-drawingml",
+ "craft-pptx",
+ "image",
+ "log",
+ "miniz_oxide 0.8.9",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "craft-pptx"
version = "0.1.0"
@@ -4128,6 +4188,13 @@ dependencies = [
"web-time",
]
+[[package]]
+name = "craft-tracked"
+version = "0.1.0"
+dependencies = [
+ "craft-ui-macros",
+]
+
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -4193,6 +4260,7 @@ dependencies = [
"craft-settings",
"craft-svg",
"craft-theme",
+ "craft-tracked",
"craft-ui-contract",
"craft-ui-macros",
"craft-ui-test-kit",
@@ -4210,6 +4278,8 @@ dependencies = [
"proc-macro2",
"scoped-tls",
"serde",
+ "serde_json",
+ "siphasher",
"skrifa 0.44.0",
"smallvec",
"syn 2.0.119",
@@ -5316,7 +5386,7 @@ dependencies = [
[[package]]
name = "ecolor"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
dependencies = [
"bytemuck",
"emath",
@@ -5372,7 +5442,7 @@ dependencies = [
[[package]]
name = "eframe"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
dependencies = [
"ahash",
"bytemuck",
@@ -5407,7 +5477,7 @@ dependencies = [
[[package]]
name = "egui"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
dependencies = [
"accesskit",
"ahash",
@@ -5426,7 +5496,7 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
dependencies = [
"ahash",
"bytemuck",
@@ -5445,7 +5515,7 @@ dependencies = [
[[package]]
name = "egui-winit"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
dependencies = [
"block2 0.6.2",
"bytemuck",
@@ -5465,7 +5535,7 @@ dependencies = [
[[package]]
name = "egui_glow"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
dependencies = [
"bytemuck",
"egui",
@@ -5478,7 +5548,7 @@ dependencies = [
[[package]]
name = "egui_kittest"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
dependencies = [
"eframe",
"egui",
@@ -5555,7 +5625,7 @@ dependencies = [
[[package]]
name = "emath"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
dependencies = [
"bytemuck",
]
@@ -5628,7 +5698,7 @@ dependencies = [
[[package]]
name = "epaint"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
dependencies = [
"ahash",
"bytemuck",
@@ -5654,7 +5724,7 @@ dependencies = [
[[package]]
name = "epaint_default_fonts"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
[[package]]
name = "equator"
@@ -14972,19 +15042,19 @@ dependencies = [
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
[[patch.unused]]
name = "egui_extras"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
-source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1cef1977ff8c16234d#e9711ca9b69772f875ae0d1cef1977ff8c16234d"
+source = "git+https://github.com/storytold/egui.git?rev=7e1c30d142bc7879d043e74b5ceb3ecfe7f51329#7e1c30d142bc7879d043e74b5ceb3ecfe7f51329"
diff --git a/Cargo.toml b/Cargo.toml
index 4dd200442f..75e77e50c9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -123,6 +123,7 @@ craft-gif = { path = "crates/gif" }
craft-hdr = { path = "crates/hdr" }
craft-mesh = { path = "crates/mesh" }
craft-html = { path = "crates/html" }
+craft-ipp = { path = "crates/ipp" }
craft-heif = { path = "crates/heif" }
craft-fig = { path = "crates/fig" }
craft-fonts-build = { path = "crates/fonts-build" }
@@ -130,6 +131,10 @@ craft-font-subset = { path = "crates/font-subset" }
# The HarfBuzz subsetter from storytold's HarfBuzz fork (branch rust-subset-15.0.0: HarfBuzz 15.0.0 plus rust/harfbuzz-subset-sys).
harfbuzz-subset-sys = { git = "https://github.com/storytold/harfbuzz.git", rev = "f32ed1e548eaa8852bff47e49a90629a013a2faa" }
craft-host = { path = "crates/host" }
+craft-gpu = { path = "crates/gpu" }
+craft-gpu-null = { path = "crates/gpu-null" }
+craft-gpu-providers = { path = "crates/gpu-providers" }
+craft-gpu-wgpu = { path = "crates/gpu-wgpu" }
craft-i18n = { path = "crates/i18n" }
craft-ipc = { path = "crates/ipc" }
craft-idml = { path = "crates/idml" }
@@ -172,6 +177,7 @@ craft-opc = { path = "crates/opc" }
craft-openpgp = { path = "crates/openpgp" }
craft-ora = { path = "crates/ora" }
craft-pptx = { path = "crates/pptx" }
+craft-ppt-binary = { path = "crates/ppt-binary" }
craft-penpot = { path = "crates/penpot" }
craft-pcraft-format = { path = "crates/pcraft-format" }
craft-pcraft-bundle = { path = "crates/pcraft-bundle" }
@@ -219,6 +225,7 @@ craft-table = { path = "crates/table" }
craft-theme = { path = "crates/theme" }
craft-theme-editor = { path = "crates/theme-editor" }
craft-theme-store = { path = "crates/theme-store" }
+craft-tracked = { path = "crates/tracked" }
craft-ui = { path = "crates/ui" }
craft-ui-canvas = { path = "crates/ui-canvas" }
craft-ui-contract = { path = "crates/ui-contract" }
@@ -269,6 +276,9 @@ proptest = "1"
encoding_rs = "0.8"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
+# Foundation crates for craft-gpu-wgpu. The versions match the ones the app repos already pin.
+pollster = "0.4"
+wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] }
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -294,20 +304,20 @@ hayro-jbig2 = { path = "vendor/hayro-jbig2" }
hayro-cmap = { path = "vendor/hayro-cmap" }
hayro-postscript = { path = "vendor/hayro-postscript" }
linesweeper = { path = "vendor/linesweeper" }
-ecolor = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-emath = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-epaint = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-egui = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-egui-winit = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-egui_glow = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-egui_extras = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-eframe = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
-egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
+ecolor = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+emath = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+epaint = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+egui = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+egui-winit = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+egui_glow = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+egui_extras = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+eframe = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
+egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
diff --git a/NOTICE b/NOTICE
index ac101996d2..8ca284e8db 100644
--- a/NOTICE
+++ b/NOTICE
@@ -114,6 +114,14 @@ Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. The format imp
clean-room work based on their public specifications; dependency licences and X.Org's `rgb.txt`
attribution are listed in ATTRIBUTION.md.
+crates/develop (craft-develop) is moved from LightCraft, module by module:
+- src/inpaint.rs and src/inpaint/ from crates/inpaint (lightcraft-inpaint), with its tests, revision a75497d6.
+ https://github.com/storytold/lightcraft
+ Copyright (c) 2026 ArtCraft Team and the LightCraft contributors.
+ That crate ports the inpainting (PatchMatch completion) and Poisson membrane fill code of PhotoCraft
+ (https://github.com/storytold/photocraft, crates/algo/src/inpaint.rs and poisson.rs), Copyright the PhotoCraft
+ contributors, MIT OR Apache-2.0; the port was modified by the LightCraft contributors (2026).
+
crates/raw (craft-raw) is moved from LightCraft, with behaviour ported from two other readers:
- LightCraft, crates/raw (src/lib.rs, dng.rs, dngwrite.rs, tiffraw.rs, unpack.rs, ljpeg.rs, jxl.rs,
opcodes.rs, profile.rs, gaintable.rs, semantic.rs, preview.rs, vendor/crw.rs, vendor/hasselblad.rs,
diff --git a/README.md b/README.md
index 659b21db0e..f1ded80ca2 100644
--- a/README.md
+++ b/README.md
@@ -2,6 +2,7 @@ Craft App Libraries
===================
+
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.
@@ -341,6 +342,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-plotter`](crates/plotter/README.md): cutter and pen-plotter command languages: HP-GL,
DMPL and GP-GL (plain and the Silhouette dialect, three generations, registration marks) from a
job in millimetres, plus the Silhouette device queries and reply parsers. No I/O.
+- [`craft-ppt-binary`](crates/ppt-binary/README.md): the PowerPoint 97-2003 binary format (`.ppt`, `.pot`, `.pps`;
+ [MS-PPT], [MS-ODRAW]) read into `craft-pptx`, on `craft-cfb`. Import only. DeckCraft's reader.
- [`craft-pptx`](crates/pptx/README.md): PresentationML, the model of a `.pptx` presentation:
masters, layouts, slides, shapes, placeholders and their inheritance, transitions and animations,
comments, sections, media and kept parts. From DeckCraft. DrawingML comes from `craft-drawingml`.
diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml
index 78c589e49d..7981f3a013 100644
--- a/crates/audio/Cargo.toml
+++ b/crates/audio/Cargo.toml
@@ -71,6 +71,9 @@ ac3-encode = ["craft-media/bitstream"]
eac3-encode = ["craft-media/bitstream"]
# MPEG-1/2 Layer III (MP3) encoder (`mp3`).
mp3-encode = ["craft-media/bitstream"]
+# Direct Stream Digital (DSD) files: DSF and DSDIFF decoders and DSD-to-PCM decimation.
+dsd = []
+
# MPEG-1/2 Layer II (MP2) encoder (`mpa::encoder`). It shares the polyphase analysis filter of the
# MP3 encoder and the tables of the MP1/MP2 decoder.
mpa-encode = ["mpa-decode", "mp3-encode"]
diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs
new file mode 100644
index 0000000000..f9f12d04d3
--- /dev/null
+++ b/crates/audio/src/dsd/dsdiff.rs
@@ -0,0 +1,378 @@
+//! Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`) parser and writer.
+//!
+//! DSDIFF files use an IFF-style big-endian chunk format starting with `FRM8` of type `DSD `:
+//! - `FRM8` container chunk containing:
+//! - `FVER`: format version (typically 1.5.0.0).
+//! - `PROP`: properties chunk with subtype `SND `, containing:
+//! - `FS `: sampling frequency (e.g. 2,822,400 Hz for DSD64).
+//! - `CHNL`: channel count and 4-character channel ID codes (`SLFT`, `SRGT`, etc.).
+//! - `CMPR`: compression type (`DSD ` for uncompressed, `DST ` for compressed).
+//! - `DSD `: audio data chunk containing channel-interleaved 1-bit samples (MSB-first).
+//! - Optional `DIIN`: disc and track information (title, artist).
+
+use super::{BitOrder, Error, Format, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio};
+
+/// Decodes 4-byte ASCII channel identifiers into human-readable channel names.
+fn channel_id_to_name(id: &[u8; 4]) -> String {
+ match id {
+ b"SLFT" => "FrontLeft".to_string(),
+ b"SRGT" => "FrontRight".to_string(),
+ b"MLFT" => "Mono/Left".to_string(),
+ b"MRGT" => "Right".to_string(),
+ b"C " => "Center".to_string(),
+ b"LFE " => "LFE".to_string(),
+ b"LS " => "LeftSurround".to_string(),
+ b"RS " => "RightSurround".to_string(),
+ b"CO " => "CenterOverhead".to_string(),
+ b"LH " => "LeftHeight".to_string(),
+ b"RH " => "RightHeight".to_string(),
+ _ => {
+ if let Ok(s) = std::str::from_utf8(id) {
+ let trimmed = s.trim();
+ if !trimmed.is_empty() {
+ return trimmed.to_string();
+ }
+ }
+ format!("Channel {:02X}{:02X}{:02X}{:02X}", id[0], id[1], id[2], id[3])
+ }
+ }
+}
+
+/// The text of a `DITI` or `DIAR` chunk: a four-byte big-endian character count, then that many
+/// bytes. `None` when the count is missing or longer than the chunk.
+fn diin_text(sub_data: &[u8]) -> Option {
+ let count = usize::try_from(u32::from_be_bytes(sub_data.get(..4)?.try_into().ok()?)).ok()?;
+ let text = sub_data.get(4..)?.get(..count)?;
+ Some(String::from_utf8_lossy(text).trim().to_string())
+}
+
+/// The channel identifiers DSDIFF 1.5 defines for a channel count (stereo, 5 and 5.1 channels);
+/// other counts use the generic `C001`, `C002`, ... identifiers.
+fn channel_ids(num_channels: usize) -> Vec<[u8; 4]> {
+ let named: &[&[u8; 4]] = match num_channels {
+ 1 => &[b"SLFT"],
+ 2 => &[b"SLFT", b"SRGT"],
+ 5 => &[b"MLFT", b"MRGT", b"C ", b"LS ", b"RS "],
+ 6 => &[b"MLFT", b"MRGT", b"C ", b"LFE ", b"LS ", b"RS "],
+ _ => &[],
+ };
+ if !named.is_empty() {
+ return named.iter().map(|id| **id).collect();
+ }
+ (1..=num_channels)
+ .map(|n| {
+ let s = format!("C{n:03}");
+ let mut id = [b' '; 4];
+ id.copy_from_slice(&s.as_bytes()[..4]);
+ id
+ })
+ .collect()
+}
+
+/// Parses the metadata from a DSDIFF file.
+pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Error> {
+ if bytes.len() < 16 {
+ return Err(Error::UnexpectedEof("DSDIFF file is too short"));
+ }
+
+ if &bytes[0..4] != b"FRM8" {
+ return Err(Error::InvalidHeader("missing 'FRM8' magic chunk"));
+ }
+ let form_size = u64::from_be_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("FRM8 size"))?);
+ if &bytes[12..16] != b"DSD " {
+ return Err(Error::InvalidHeader("invalid FRM8 form type (expected 'DSD ')"));
+ }
+
+ let total_file_data = bytes.len().saturating_sub(12);
+ let form_size = usize::try_from(form_size).map_err(|_| Error::MemoryLimitExceeded)?;
+ if form_size > total_file_data {
+ return Err(Error::UnexpectedEof("FRM8 chunk extends beyond file size"));
+ }
+
+ let mut pos = 16;
+ let end = 12 + form_size;
+
+ let mut sample_rate = None;
+ let mut channel_names = Vec::new();
+ let mut num_channels = None;
+ let mut is_compressed_dst = false;
+ let mut dsd_data_offset = None;
+ let mut dsd_data_len = None;
+ let mut title = None;
+ let mut artist = None;
+
+ while pos + 12 <= end {
+ let chunk_id: [u8; 4] = bytes[pos..pos + 4].try_into().map_err(|_| Error::UnexpectedEof("chunk ID"))?;
+ let chunk_size = usize::try_from(u64::from_be_bytes(bytes[pos + 4..pos + 12].try_into().map_err(|_| Error::UnexpectedEof("chunk size"))?))
+ .map_err(|_| Error::MemoryLimitExceeded)?;
+ pos += 12;
+
+ if chunk_size > end.saturating_sub(pos) {
+ return Err(Error::UnexpectedEof("subchunk extends beyond container bounds"));
+ }
+
+ let chunk_data = &bytes[pos..pos + chunk_size];
+ let pad = chunk_size & 1;
+ pos = pos.saturating_add(chunk_size).saturating_add(pad);
+
+ match &chunk_id {
+ b"PROP" => {
+ if chunk_data.len() < 4 {
+ continue;
+ }
+ if &chunk_data[0..4] != b"SND " {
+ continue;
+ }
+ let mut prop_pos = 4;
+ while prop_pos + 12 <= chunk_data.len() {
+ let sub_id: [u8; 4] = chunk_data[prop_pos..prop_pos + 4].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk ID"))?;
+ let sub_size = usize::try_from(u64::from_be_bytes(
+ chunk_data[prop_pos + 4..prop_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk size"))?,
+ ))
+ .map_err(|_| Error::MemoryLimitExceeded)?;
+ prop_pos += 12;
+
+ if sub_size > chunk_data.len().saturating_sub(prop_pos) {
+ return Err(Error::UnexpectedEof("PROP subchunk extends beyond bounds"));
+ }
+
+ let sub_data = &chunk_data[prop_pos..prop_pos + sub_size];
+ let sub_pad = sub_size & 1;
+ prop_pos = prop_pos.saturating_add(sub_size).saturating_add(sub_pad);
+
+ match &sub_id {
+ b"FS " => {
+ if sub_data.len() < 4 {
+ return Err(Error::UnexpectedEof("truncated FS chunk"));
+ }
+ if sample_rate.is_some() {
+ return Err(Error::InvalidHeader("duplicate FS chunk"));
+ }
+ let sr = u32::from_be_bytes([sub_data[0], sub_data[1], sub_data[2], sub_data[3]]);
+ if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sr) {
+ return Err(Error::InvalidHeader("sampling frequency out of range"));
+ }
+ sample_rate = Some(sr);
+ }
+ b"CHNL" => {
+ if sub_data.len() < 2 {
+ return Err(Error::UnexpectedEof("truncated CHNL chunk"));
+ }
+ if num_channels.is_some() {
+ return Err(Error::InvalidHeader("duplicate CHNL chunk"));
+ }
+ let n = u16::from_be_bytes([sub_data[0], sub_data[1]]);
+ if n == 0 || n > MAX_CHANNELS as u16 {
+ return Err(Error::Unsupported("channel count must be between 1 and 8"));
+ }
+ num_channels = Some(n);
+ channel_names.clear();
+ let mut ch_pos = 2;
+ while ch_pos + 4 <= sub_data.len() && channel_names.len() < n as usize {
+ let id: [u8; 4] = [sub_data[ch_pos], sub_data[ch_pos + 1], sub_data[ch_pos + 2], sub_data[ch_pos + 3]];
+ channel_names.push(channel_id_to_name(&id));
+ ch_pos += 4;
+ }
+ }
+ b"CMPR" if sub_data.len() >= 4 => {
+ if &sub_data[0..4] == b"DST " {
+ is_compressed_dst = true;
+ } else if &sub_data[0..4] != b"DSD " {
+ return Err(Error::Unsupported("unknown DSDIFF compression type"));
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ b"DSD " => {
+ dsd_data_offset = Some(pos - chunk_size - pad);
+ dsd_data_len = Some(chunk_size);
+ }
+ b"DST " => {
+ is_compressed_dst = true;
+ }
+ b"DIIN" => {
+ // Parse optional disc info for title and artist.
+ let mut diin_pos = 0;
+ while diin_pos + 12 <= chunk_data.len() {
+ let sub_id = &chunk_data[diin_pos..diin_pos + 4];
+ let sub_size = usize::try_from(u64::from_be_bytes(
+ chunk_data[diin_pos + 4..diin_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("DIIN subchunk size"))?,
+ ))
+ .map_err(|_| Error::MemoryLimitExceeded)?;
+ diin_pos += 12;
+ if sub_size > chunk_data.len().saturating_sub(diin_pos) {
+ break;
+ }
+ let sub_data = &chunk_data[diin_pos..diin_pos + sub_size];
+ let sub_pad = sub_size & 1;
+ diin_pos = diin_pos.saturating_add(sub_size).saturating_add(sub_pad);
+
+ if sub_id == b"DITI" && title.is_none() {
+ title = diin_text(sub_data);
+ } else if sub_id == b"DIAR" && artist.is_none() {
+ artist = diin_text(sub_data);
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+
+ if is_compressed_dst {
+ return Err(Error::Unsupported("DST compression in DSDIFF is not yet supported"));
+ }
+
+ let sample_rate = sample_rate.ok_or(Error::InvalidHeader("missing sample rate ('FS ' chunk)"))?;
+ if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) {
+ return Err(Error::InvalidHeader("sampling frequency out of range"));
+ }
+
+ let channels = num_channels.ok_or(Error::InvalidHeader("missing channel info ('CHNL' chunk)"))?;
+ if channels == 0 || channels > MAX_CHANNELS as u16 {
+ return Err(Error::Unsupported("channel count must be between 1 and 8"));
+ }
+
+ let data_offset = dsd_data_offset.ok_or(Error::InvalidHeader("missing audio data ('DSD ' chunk)"))?;
+ let data_len = dsd_data_len.ok_or(Error::InvalidHeader("missing audio data length"))?;
+
+ let bytes_per_channel = data_len / (channels as usize);
+ let sample_count = (bytes_per_channel as u64).saturating_mul(8);
+
+ if channel_names.len() < channels as usize {
+ for c in channel_names.len()..(channels as usize) {
+ channel_names.push(format!("Channel {}", c + 1));
+ }
+ }
+
+ let metadata = Metadata { format: Format::Dsdiff, sample_rate, channels, sample_count, channel_names, title, artist };
+
+ Ok((metadata, data_offset, data_len))
+}
+
+/// Parses a DSDIFF file into raw 1-bit planar channel streams.
+pub fn parse_dsdiff(bytes: &[u8]) -> Result {
+ let (metadata, data_offset, data_len) = parse_dsdiff_header(bytes)?;
+ let channels = metadata.channels as usize;
+ let bytes_per_channel = data_len / channels;
+
+ if bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES {
+ return Err(Error::MemoryLimitExceeded);
+ }
+
+ let end_offset = data_offset + data_len;
+ if end_offset > bytes.len() {
+ return Err(Error::UnexpectedEof("DSD sound data extends beyond file bounds"));
+ }
+ let data_slice = &bytes[data_offset..end_offset];
+
+ let mut channel_bytes: Vec> = Vec::with_capacity(channels);
+ for _ in 0..channels {
+ let mut ch_vec = Vec::new();
+ ch_vec.try_reserve_exact(bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?;
+ channel_bytes.push(ch_vec);
+ }
+
+ // De-interleave byte-by-byte: Ch0, Ch1, ... Ch(N-1), Ch0, Ch1 ...
+ for chunk in data_slice.chunks_exact(channels) {
+ for (c, &byte) in chunk.iter().enumerate() {
+ if let Some(ch_vec) = channel_bytes.get_mut(c) {
+ ch_vec.push(byte);
+ }
+ }
+ }
+
+ Ok(RawAudio { metadata, bit_order: BitOrder::MsbFirst, channel_bytes })
+}
+
+/// Encodes 1-bit planar audio channels into a valid Philips DSDIFF (`.dff`) file.
+pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result, Error> {
+ if channels.is_empty() || channels.len() > MAX_CHANNELS {
+ return Err(Error::Unsupported("channel count must be between 1 and 8"));
+ }
+ if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) {
+ return Err(Error::InvalidData("sample rate out of bounds"));
+ }
+
+ let num_channels = channels.len();
+ let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?;
+ let data_size = bytes_per_ch.checked_mul(num_channels).ok_or(Error::MemoryLimitExceeded)?;
+ // Fixed headers plus four bytes for each channel identifier.
+ // An odd-sized chunk payload is followed by a pad byte that its size field does not count.
+ let data_pad = data_size & 1;
+ let padded_size = data_size.checked_add(data_pad).ok_or(Error::MemoryLimitExceeded)?;
+ let file_size = super::encoded_size(padded_size, 110 + 4 * num_channels)?;
+
+ // Build PROP subchunks:
+ // 1. 'FS ' (4 bytes + 12 chunk header)
+ let mut fs_chunk = Vec::with_capacity(16);
+ fs_chunk.extend_from_slice(b"FS ");
+ fs_chunk.extend_from_slice(&4u64.to_be_bytes());
+ fs_chunk.extend_from_slice(&sample_rate.to_be_bytes());
+
+ // 2. 'CHNL' (2 + 4 * num_channels + 12 chunk header)
+ let chnl_data_len = 2 + 4 * num_channels;
+ let mut chnl_chunk = Vec::with_capacity(12 + chnl_data_len + 1);
+ chnl_chunk.extend_from_slice(b"CHNL");
+ chnl_chunk.extend_from_slice(&(chnl_data_len as u64).to_be_bytes());
+ chnl_chunk.extend_from_slice(&(num_channels as u16).to_be_bytes());
+ for id in channel_ids(num_channels) {
+ chnl_chunk.extend_from_slice(&id);
+ }
+ if !chnl_data_len.is_multiple_of(2) {
+ chnl_chunk.push(0);
+ }
+
+ // 3. 'CMPR' (4 + 1 + 3 + pad = 8 bytes + 12 chunk header)
+ let mut cmpr_chunk = Vec::with_capacity(20);
+ cmpr_chunk.extend_from_slice(b"CMPR");
+ cmpr_chunk.extend_from_slice(&8u64.to_be_bytes());
+ cmpr_chunk.extend_from_slice(b"DSD ");
+ cmpr_chunk.push(3); // name len
+ cmpr_chunk.extend_from_slice(b"DSD");
+
+ let prop_payload_len = 4 + fs_chunk.len() + chnl_chunk.len() + cmpr_chunk.len();
+ let mut prop_chunk = Vec::with_capacity(12 + prop_payload_len);
+ prop_chunk.extend_from_slice(b"PROP");
+ prop_chunk.extend_from_slice(&(prop_payload_len as u64).to_be_bytes());
+ prop_chunk.extend_from_slice(b"SND ");
+ prop_chunk.extend_from_slice(&fs_chunk);
+ prop_chunk.extend_from_slice(&chnl_chunk);
+ prop_chunk.extend_from_slice(&cmpr_chunk);
+
+ // FVER chunk (4 bytes payload + 12 chunk header)
+ let mut fver_chunk = Vec::with_capacity(16);
+ fver_chunk.extend_from_slice(b"FVER");
+ fver_chunk.extend_from_slice(&4u64.to_be_bytes());
+ fver_chunk.extend_from_slice(&0x01050000u32.to_be_bytes());
+
+ // DSD chunk (data_size payload + 12 chunk header)
+ let mut dsd_chunk_hdr = Vec::with_capacity(12);
+ dsd_chunk_hdr.extend_from_slice(b"DSD ");
+ dsd_chunk_hdr.extend_from_slice(&(data_size as u64).to_be_bytes());
+
+ let frm8_payload_len = file_size - 12;
+ let mut out = Vec::new();
+ out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?;
+
+ out.extend_from_slice(b"FRM8");
+ out.extend_from_slice(&(frm8_payload_len as u64).to_be_bytes());
+ out.extend_from_slice(b"DSD ");
+ out.extend_from_slice(&fver_chunk);
+ out.extend_from_slice(&prop_chunk);
+ out.extend_from_slice(&dsd_chunk_hdr);
+
+ // Interleave channels byte-by-byte.
+ for i in 0..bytes_per_ch {
+ for ch_data in channels {
+ let byte = ch_data.get(i).copied().unwrap_or(super::filter::SILENCE_MSBF);
+ out.push(byte);
+ }
+ }
+ if data_pad == 1 {
+ out.push(0);
+ }
+
+ Ok(out)
+}
diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs
new file mode 100644
index 0000000000..1fb36c18da
--- /dev/null
+++ b/crates/audio/src/dsd/dsf.rs
@@ -0,0 +1,391 @@
+//! Sony DSF (Direct Stream Digital File) parser and writer.
+//!
+//! A DSF file consists of three contiguous little-endian chunks:
+//! - `'DSD '` chunk (28 bytes): file identification, total size, and metadata offset.
+//! - `'fmt '` chunk (52 bytes): sample rate, channel count, sample count, block size.
+//! - `'data'` chunk (12 bytes + data): 1-bit audio organized into channel blocks.
+//! - Optional ID3v2 metadata chunk located at `metadata_offset`.
+
+use super::{BitOrder, Error, Format, MAX_BLOCK_SIZE, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio};
+
+/// Channel configuration names for DSF channel types 1..=7.
+fn dsf_channel_names(channel_type: u32, channel_count: u16) -> Vec {
+ match channel_type {
+ 1 => vec!["Mono".to_string()],
+ 2 => vec!["Left".to_string(), "Right".to_string()],
+ 3 => vec!["Left".to_string(), "Right".to_string(), "Center".to_string()],
+ 4 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "BackLeft".to_string(), "BackRight".to_string()],
+ 5 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "LFE".to_string()],
+ 6 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "BackLeft".to_string(), "BackRight".to_string()],
+ 7 => vec![
+ "FrontLeft".to_string(),
+ "FrontRight".to_string(),
+ "Center".to_string(),
+ "LFE".to_string(),
+ "BackLeft".to_string(),
+ "BackRight".to_string(),
+ ],
+ _ => (0..channel_count).map(|c| format!("Channel {}", c + 1)).collect(),
+ }
+}
+
+/// Attempts to parse basic ID3v2 title and artist tags if present at `offset`.
+fn parse_id3v2(bytes: &[u8], offset: usize) -> (Option, Option) {
+ let Some(id3) = bytes.get(offset..) else {
+ return (None, None);
+ };
+ if id3.len() < 10 || &id3[..3] != b"ID3" {
+ return (None, None);
+ }
+
+ let mut title = None;
+ let mut artist = None;
+
+ // ID3v2 size is 4 synchsafe bytes at offset 6.
+ let tag_size = ((id3[6] as usize & 0x7F) << 21) | ((id3[7] as usize & 0x7F) << 14) | ((id3[8] as usize & 0x7F) << 7) | (id3[9] as usize & 0x7F);
+
+ let end = (10 + tag_size).min(id3.len());
+ let mut pos = 10;
+
+ // Scan ID3v2.3 / ID3v2.4 frames.
+ while pos + 10 <= end {
+ let frame_id = &id3[pos..pos + 4];
+ if frame_id[0] == 0 {
+ break;
+ }
+ let raw = [id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]];
+ // ID3v2.4 frame sizes are synchsafe; v2.3 ones are plain big-endian.
+ let frame_size = if id3[3] >= 4 {
+ if raw.iter().any(|b| b & 0x80 != 0) {
+ break;
+ }
+ ((raw[0] as usize) << 21) | ((raw[1] as usize) << 14) | ((raw[2] as usize) << 7) | raw[3] as usize
+ } else {
+ u32::from_be_bytes(raw) as usize
+ };
+ pos += 10;
+ if frame_size > end.saturating_sub(pos) {
+ break;
+ }
+
+ let frame_data = &id3[pos..pos + frame_size];
+ pos += frame_size;
+
+ if frame_id == b"TIT2" && title.is_none() {
+ title = parse_text_frame(frame_data);
+ } else if frame_id == b"TPE1" && artist.is_none() {
+ artist = parse_text_frame(frame_data);
+ }
+ }
+
+ (title, artist)
+}
+
+fn parse_text_frame(data: &[u8]) -> Option {
+ if data.is_empty() {
+ return None;
+ }
+ let encoding = data[0];
+ let content = &data[1..];
+ let text = match encoding {
+ // ISO-8859-1: every byte is the code point of the same value.
+ 0 => content.iter().map(|&b| char::from(b)).collect::(),
+ 3 => String::from_utf8_lossy(content).into_owned(),
+ // UTF-16 with a byte order mark (which is removed); without one, assume big-endian.
+ 1 => {
+ let (big_endian, body) = match content {
+ [0xFE, 0xFF, rest @ ..] => (true, rest),
+ [0xFF, 0xFE, rest @ ..] => (false, rest),
+ _ => (true, content),
+ };
+ utf16(body, big_endian)
+ }
+ // UTF-16BE without a byte order mark.
+ 2 => utf16(content, true),
+ _ => return None,
+ };
+ let s = text.trim_end_matches('\0').trim().to_string();
+ if s.is_empty() { None } else { Some(s) }
+}
+
+fn utf16(bytes: &[u8], big_endian: bool) -> String {
+ let units: Vec = bytes
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|c| if big_endian { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) })
+ .collect();
+ String::from_utf16_lossy(&units)
+}
+
+/// Parses DSF file metadata, returning the metadata, audio data offset, and block size per channel.
+pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> {
+ let (metadata, offset, _, block_size) = parse_dsf_header_bounded(bytes)?;
+ Ok((metadata, offset, block_size))
+}
+
+fn parse_dsf_header_bounded(bytes: &[u8]) -> Result<(Metadata, usize, usize, u32), Error> {
+ if bytes.len() < 28 + 52 + 12 {
+ return Err(Error::UnexpectedEof("DSF file header is truncated"));
+ }
+
+ // 1. 'DSD ' chunk
+ if &bytes[..4] != b"DSD " {
+ return Err(Error::InvalidHeader("missing 'DSD ' magic header"));
+ }
+ let dsd_chunk_size = u64::from_le_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("DSD chunk size"))?);
+ if dsd_chunk_size != 28 {
+ return Err(Error::InvalidHeader("invalid 'DSD ' chunk size (must be 28)"));
+ }
+ let file_size = u64::from_le_bytes(bytes[12..20].try_into().map_err(|_| Error::UnexpectedEof("file size"))?);
+ let metadata_offset = u64::from_le_bytes(bytes[20..28].try_into().map_err(|_| Error::UnexpectedEof("metadata offset"))?);
+
+ if file_size > bytes.len() as u64 {
+ return Err(Error::UnexpectedEof("declared file size extends beyond buffer"));
+ }
+ let file_len = usize::try_from(file_size).map_err(|_| Error::MemoryLimitExceeded)?;
+ if file_len < 28 + 52 + 12 {
+ return Err(Error::InvalidHeader("declared file size is smaller than required headers"));
+ }
+ let file_bytes = &bytes[..file_len];
+
+ // 2. 'fmt ' chunk
+ let fmt_offset = 28;
+ if &file_bytes[fmt_offset..fmt_offset + 4] != b"fmt " {
+ return Err(Error::InvalidHeader("missing 'fmt ' chunk header"));
+ }
+ let fmt_chunk_size =
+ u64::from_le_bytes(file_bytes[fmt_offset + 4..fmt_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("fmt chunk size"))?);
+ if fmt_chunk_size < 52 {
+ return Err(Error::InvalidHeader("invalid 'fmt ' chunk size (must be at least 52)"));
+ }
+ let fmt_size = usize::try_from(fmt_chunk_size).map_err(|_| Error::MemoryLimitExceeded)?;
+ if fmt_size > file_bytes.len().saturating_sub(fmt_offset) {
+ return Err(Error::UnexpectedEof("fmt chunk extends beyond file bounds"));
+ }
+
+ let format_version =
+ u32::from_le_bytes(file_bytes[fmt_offset + 12..fmt_offset + 16].try_into().map_err(|_| Error::UnexpectedEof("format version"))?);
+ if format_version != 1 {
+ return Err(Error::Unsupported("unsupported DSF format version (only version 1 is supported)"));
+ }
+
+ let format_id = u32::from_le_bytes(file_bytes[fmt_offset + 16..fmt_offset + 20].try_into().map_err(|_| Error::UnexpectedEof("format id"))?);
+ if format_id != 0 {
+ return Err(Error::Unsupported("unsupported DSF format id (only raw DSD id=0 is supported)"));
+ }
+
+ let channel_type = u32::from_le_bytes(file_bytes[fmt_offset + 20..fmt_offset + 24].try_into().map_err(|_| Error::UnexpectedEof("channel type"))?);
+ let channel_count =
+ u32::from_le_bytes(file_bytes[fmt_offset + 24..fmt_offset + 28].try_into().map_err(|_| Error::UnexpectedEof("channel count"))?);
+ if channel_count == 0 || channel_count > MAX_CHANNELS as u32 {
+ return Err(Error::Unsupported("DSF channel count must be between 1 and 8"));
+ }
+ let channels = channel_count as u16;
+
+ let sample_rate =
+ u32::from_le_bytes(file_bytes[fmt_offset + 28..fmt_offset + 32].try_into().map_err(|_| Error::UnexpectedEof("sampling frequency"))?);
+ if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) {
+ return Err(Error::InvalidHeader("DSF sampling frequency out of valid range"));
+ }
+
+ let bits_per_sample =
+ u32::from_le_bytes(file_bytes[fmt_offset + 32..fmt_offset + 36].try_into().map_err(|_| Error::UnexpectedEof("bits per sample"))?);
+ if bits_per_sample != 1 {
+ return Err(Error::Unsupported("DSF bits per sample must be 1"));
+ }
+
+ let sample_count = u64::from_le_bytes(file_bytes[fmt_offset + 36..fmt_offset + 44].try_into().map_err(|_| Error::UnexpectedEof("sample count"))?);
+
+ let block_size_per_channel =
+ u32::from_le_bytes(file_bytes[fmt_offset + 44..fmt_offset + 48].try_into().map_err(|_| Error::UnexpectedEof("block size per channel"))?);
+ if block_size_per_channel == 0 || block_size_per_channel > MAX_BLOCK_SIZE {
+ return Err(Error::InvalidHeader("DSF block size per channel is invalid or too large"));
+ }
+
+ // 3. 'data' chunk
+ let data_offset = fmt_offset.saturating_add(fmt_size);
+ if data_offset.saturating_add(12) > file_bytes.len() {
+ return Err(Error::UnexpectedEof("missing 'data' chunk header"));
+ }
+ if &file_bytes[data_offset..data_offset + 4] != b"data" {
+ return Err(Error::InvalidHeader("missing 'data' chunk header"));
+ }
+ let data_chunk_size =
+ u64::from_le_bytes(file_bytes[data_offset + 4..data_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("data chunk size"))?);
+ if data_chunk_size < 12 {
+ return Err(Error::InvalidHeader("invalid 'data' chunk size (must be at least 12)"));
+ }
+
+ let payload_offset = data_offset + 12;
+ let payload_size = usize::try_from(data_chunk_size - 12).map_err(|_| Error::MemoryLimitExceeded)?;
+ if payload_size > file_bytes.len().saturating_sub(payload_offset) {
+ return Err(Error::UnexpectedEof("data chunk payload extends beyond file bounds"));
+ }
+ let data_end = payload_offset.saturating_add(payload_size);
+
+ // Parse ID3v2 metadata if pointer is valid.
+ let (title, artist) = if metadata_offset == 0 {
+ (None, None)
+ } else {
+ let meta_offset = usize::try_from(metadata_offset).map_err(|_| Error::MemoryLimitExceeded)?;
+ if meta_offset < data_end || meta_offset >= file_len {
+ return Err(Error::InvalidHeader("DSF metadata offset outside declared file bounds"));
+ }
+ parse_id3v2(file_bytes, meta_offset)
+ };
+
+ let channel_names = dsf_channel_names(channel_type, channels);
+
+ let metadata = Metadata { format: Format::Dsf, sample_rate, channels, sample_count, channel_names, title, artist };
+
+ Ok((metadata, payload_offset, payload_size, block_size_per_channel))
+}
+
+/// Parses a DSF file into raw 1-bit planar channel streams.
+pub fn parse_dsf(bytes: &[u8]) -> Result {
+ let (metadata, payload_offset, payload_size, block_size) = parse_dsf_header_bounded(bytes)?;
+ let block_size = block_size as usize;
+ let channels = metadata.channels as usize;
+
+ let target_bytes_per_channel = usize::try_from(metadata.sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?;
+ if target_bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES {
+ return Err(Error::MemoryLimitExceeded);
+ }
+
+ let slice_size = channels.saturating_mul(block_size);
+ if slice_size == 0 {
+ return Err(Error::InvalidHeader("zero slice size"));
+ }
+
+ // The header validated this range. Trailing ID3 or other bytes are not audio,
+ // even if sample_count asks for more samples than the data chunk contains.
+ let payload = &bytes[payload_offset..payload_offset + payload_size];
+ let num_slices = payload.len() / slice_size;
+
+ let mut channel_bytes: Vec> = Vec::with_capacity(channels);
+ for _ in 0..channels {
+ let mut ch_vec = Vec::new();
+ ch_vec.try_reserve_exact(target_bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?;
+ channel_bytes.push(ch_vec);
+ }
+
+ for s in 0..num_slices {
+ let slice_base = s * slice_size;
+ for (c, ch_vec) in channel_bytes.iter_mut().enumerate() {
+ let ch_start = slice_base + c * block_size;
+ let ch_end = ch_start + block_size;
+ if let Some(block) = payload.get(ch_start..ch_end) {
+ let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len());
+ let take = block.len().min(remaining);
+ ch_vec.extend_from_slice(&block[..take]);
+ }
+ }
+ }
+
+ // Handle any trailing partial slice.
+ let remainder = payload.len() % slice_size;
+ if remainder > 0 {
+ let slice_base = num_slices * slice_size;
+ for (c, ch_vec) in channel_bytes.iter_mut().enumerate() {
+ let ch_start = slice_base + c * block_size;
+ if ch_start < payload.len() {
+ let ch_end = (ch_start + block_size).min(payload.len());
+ let block = &payload[ch_start..ch_end];
+ let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len());
+ let take = block.len().min(remaining);
+ ch_vec.extend_from_slice(&block[..take]);
+ }
+ }
+ }
+
+ // Pad with silence (0x69) if the file had fewer bytes than required by sample_count.
+ for ch_vec in &mut channel_bytes {
+ if ch_vec.len() < target_bytes_per_channel {
+ ch_vec.resize(target_bytes_per_channel, super::filter::SILENCE_LSBF);
+ }
+ }
+
+ Ok(RawAudio { metadata, bit_order: BitOrder::LsbFirst, channel_bytes })
+}
+
+fn unsupported_channel_layout() -> Result {
+ Err(Error::Unsupported("DSF has no channel type for this channel count (1 to 6 are supported)"))
+}
+
+/// Encodes 1-bit planar audio channels into a valid Sony DSF file.
+pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> {
+ if channels.is_empty() || channels.len() > MAX_CHANNELS {
+ return Err(Error::Unsupported("channel count must be between 1 and 8"));
+ }
+ if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) {
+ return Err(Error::InvalidData("sample rate out of bounds"));
+ }
+ if block_size > MAX_BLOCK_SIZE {
+ return Err(Error::InvalidData("DSF block size exceeds maximum"));
+ }
+ let block_size = if block_size == 0 { 4096 } else { block_size as usize };
+
+ let num_channels = channels.len();
+ let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?;
+ let num_blocks = bytes_per_ch.div_ceil(block_size);
+ let payload_size = num_blocks.checked_mul(num_channels).and_then(|n| n.checked_mul(block_size)).ok_or(Error::MemoryLimitExceeded)?;
+ let file_size = super::encoded_size(payload_size, 92)?;
+
+ let data_chunk_size = 12u64 + payload_size as u64;
+
+ let mut out = Vec::new();
+ out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?;
+
+ // 1. 'DSD ' chunk (28 bytes)
+ out.extend_from_slice(b"DSD ");
+ out.extend_from_slice(&28u64.to_le_bytes());
+ out.extend_from_slice(&(file_size as u64).to_le_bytes());
+ out.extend_from_slice(&0u64.to_le_bytes()); // metadata offset = 0
+
+ // 2. 'fmt ' chunk (52 bytes)
+ out.extend_from_slice(b"fmt ");
+ out.extend_from_slice(&52u64.to_le_bytes());
+ out.extend_from_slice(&1u32.to_le_bytes()); // format_version = 1
+ out.extend_from_slice(&0u32.to_le_bytes()); // format_id = 0 (raw DSD)
+ // DSF channel types: 1 mono, 2 stereo, 3 L R C, 4 quad, 6 five channels, 7 5.1.
+ let channel_type = match num_channels {
+ 1 => 1u32,
+ 2 => 2,
+ 3 => 3,
+ 4 => 4,
+ 5 => 6,
+ 6 => 7,
+ _ => unsupported_channel_layout()?,
+ };
+ out.extend_from_slice(&channel_type.to_le_bytes());
+ out.extend_from_slice(&(num_channels as u32).to_le_bytes());
+ out.extend_from_slice(&sample_rate.to_le_bytes());
+ out.extend_from_slice(&1u32.to_le_bytes()); // bits_per_sample = 1
+ out.extend_from_slice(&sample_count.to_le_bytes());
+ out.extend_from_slice(&(block_size as u32).to_le_bytes());
+ out.extend_from_slice(&0u32.to_le_bytes()); // reserved
+
+ // 3. 'data' chunk
+ out.extend_from_slice(b"data");
+ out.extend_from_slice(&data_chunk_size.to_le_bytes());
+
+ for b in 0..num_blocks {
+ let blk_start = b * block_size;
+ let blk_end = blk_start + block_size;
+ for ch_data in channels {
+ let available = if blk_start < ch_data.len() {
+ let end = blk_end.min(ch_data.len());
+ &ch_data[blk_start..end]
+ } else {
+ &[]
+ };
+ out.extend_from_slice(available);
+ if available.len() < block_size {
+ out.resize(out.len() + (block_size - available.len()), super::filter::SILENCE_LSBF);
+ }
+ }
+ }
+
+ Ok(out)
+}
diff --git a/crates/audio/src/dsd/filter.rs b/crates/audio/src/dsd/filter.rs
new file mode 100644
index 0000000000..ec815afd1c
--- /dev/null
+++ b/crates/audio/src/dsd/filter.rs
@@ -0,0 +1,288 @@
+//! DSD-to-PCM decimation filter.
+//!
+//! Direct Stream Digital (DSD) uses 1-bit Sigma-Delta modulation sampled at high rates
+//! (2,822,400 Hz for DSD64, 5,644,800 Hz for DSD128, etc.). Decimation to multi-bit PCM
+//! involves low-pass filtering to attenuate high-frequency quantization noise followed
+//! by downsampling.
+//!
+//! This module provides a 96-tap symmetric FIR decimation filter that downsamples 1-bit DSD
+//! to multi-bit PCM at 1/8th of the DSD sampling rate (e.g. 352,800 Hz for DSD64). Further
+//! integer decimation (to 176.4 kHz, 88.2 kHz, or 44.1 kHz) is supported via subsequent
+//! downsampling stages.
+
+use super::{BitOrder, Error, MAX_DECODE_BYTES};
+
+/// 96-tap symmetric FIR decimation filter coefficients for decimation by 8.
+///
+/// Output is normalized so that alternating silence bits (0x69 or 0xAA) decode near 0.0,
+/// and full-scale runs of 1s or 0s decode near +1.0 and -1.0.
+#[allow(clippy::excessive_precision)]
+pub const TAPS_96: [f32; 96] = [
+ 2.9802322388e-08_f32,
+ 1.1920928955e-07_f32,
+ 3.5762786865e-07_f32,
+ 7.4505805969e-07_f32,
+ 1.3113021851e-06_f32,
+ 1.9371509552e-06_f32,
+ 2.1755695343e-06_f32,
+ 1.2516975403e-06_f32,
+ -1.9967556000e-06_f32,
+ -9.1493129730e-06_f32,
+ -2.1725893021e-05_f32,
+ -4.0739774704e-05_f32,
+ -6.5773725510e-05_f32,
+ -9.3966722488e-05_f32,
+ -1.1900067329e-04_f32,
+ -1.3050436974e-04_f32,
+ -1.1405348778e-04_f32,
+ -5.2779912949e-05_f32,
+ 7.0035457611e-05_f32,
+ 2.6643276215e-04_f32,
+ 5.3817033768e-04_f32,
+ 8.7043642998e-04_f32,
+ 1.2266933918e-03_f32,
+ 1.5456080437e-03_f32,
+ 1.7420351505e-03_f32,
+ 1.7137229443e-03_f32,
+ 1.3538300991e-03_f32,
+ 5.7008862495e-04_f32,
+ -6.9221854210e-04_f32,
+ -2.4250447750e-03_f32,
+ -4.5351684093e-03_f32,
+ -6.8288743496e-03_f32,
+ -9.0079009533e-03_f32,
+ -1.0681360960e-02_f32,
+ -1.1394292116e-02_f32,
+ -1.0672420263e-02_f32,
+ -8.0802738667e-03_f32,
+ -3.2847225666e-03_f32,
+ 3.8830339909e-03_f32,
+ 1.3377487659e-02_f32,
+ 2.4909228086e-02_f32,
+ 3.7942945957e-02_f32,
+ 5.1726281643e-02_f32,
+ 6.5348774195e-02_f32,
+ 7.7825516462e-02_f32,
+ 8.8196486235e-02_f32,
+ 9.5628470182e-02_f32,
+ 9.9507331848e-02_f32,
+ 9.9507331848e-02_f32,
+ 9.5628470182e-02_f32,
+ 8.8196486235e-02_f32,
+ 7.7825516462e-02_f32,
+ 6.5348774195e-02_f32,
+ 5.1726281643e-02_f32,
+ 3.7942945957e-02_f32,
+ 2.4909228086e-02_f32,
+ 1.3377487659e-02_f32,
+ 3.8830339909e-03_f32,
+ -3.2847225666e-03_f32,
+ -8.0802738667e-03_f32,
+ -1.0672420263e-02_f32,
+ -1.1394292116e-02_f32,
+ -1.0681360960e-02_f32,
+ -9.0079009533e-03_f32,
+ -6.8288743496e-03_f32,
+ -4.5351684093e-03_f32,
+ -2.4250447750e-03_f32,
+ -6.9221854210e-04_f32,
+ 5.7008862495e-04_f32,
+ 1.3538300991e-03_f32,
+ 1.7137229443e-03_f32,
+ 1.7420351505e-03_f32,
+ 1.5456080437e-03_f32,
+ 1.2266933918e-03_f32,
+ 8.7043642998e-04_f32,
+ 5.3817033768e-04_f32,
+ 2.6643276215e-04_f32,
+ 7.0035457611e-05_f32,
+ -5.2779912949e-05_f32,
+ -1.1405348778e-04_f32,
+ -1.3050436974e-04_f32,
+ -1.1900067329e-04_f32,
+ -9.3966722488e-05_f32,
+ -6.5773725510e-05_f32,
+ -4.0739774704e-05_f32,
+ -2.1725893021e-05_f32,
+ -9.1493129730e-06_f32,
+ -1.9967556000e-06_f32,
+ 1.2516975403e-06_f32,
+ 2.1755695343e-06_f32,
+ 1.9371509552e-06_f32,
+ 1.3113021851e-06_f32,
+ 7.4505805969e-07_f32,
+ 3.5762786865e-07_f32,
+ 1.1920928955e-07_f32,
+ 2.9802322388e-08_f32,
+];
+
+/// The number of filter history bytes (96 taps / 8 bits per byte = 12 bytes).
+pub const FILTER_BYTES: usize = 12;
+
+/// Standard DSD silence pattern byte for LSB-first ordering (Sony DSF).
+pub const SILENCE_LSBF: u8 = 0x69;
+
+/// Standard DSD silence pattern byte for MSB-first ordering (Philips DSDIFF).
+pub const SILENCE_MSBF: u8 = 0xAA;
+
+/// Precomputes lookup table entries for byte position `k` (0..12) and byte value `v` (0..256).
+///
+/// In LSB-first order, bit `b` of input byte `k` corresponds to tap `k * 8 + b`.
+#[inline]
+fn byte_lut(k: usize, byte_val: u8) -> f32 {
+ let mut sum = 0.0_f32;
+ let base_tap = k * 8;
+ for b in 0..8 {
+ if ((byte_val >> b) & 1) != 0
+ && let Some(tap) = TAPS_96.get(base_tap + b)
+ {
+ sum += 2.0 * *tap;
+ }
+ }
+ sum
+}
+
+// Both the first-stage samples and the secondary output coexist during filtering.
+pub(super) fn allocation_sizes(len: usize, factor: u32) -> Result<(usize, usize), Error> {
+ if !matches!(factor, 8 | 16 | 32 | 64) {
+ return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64"));
+ }
+ let stage = len.checked_mul(std::mem::size_of::()).ok_or(Error::MemoryLimitExceeded)?;
+ let output = (len / (factor / 8) as usize).checked_mul(std::mem::size_of::()).ok_or(Error::MemoryLimitExceeded)?;
+ let working = if factor == 8 { stage } else { stage.checked_add(output).ok_or(Error::MemoryLimitExceeded)? };
+ if working > MAX_DECODE_BYTES {
+ return Err(Error::MemoryLimitExceeded);
+ }
+ Ok((working, output))
+}
+
+/// Unity-DC-gain low-pass taps for decimating by `ratio` (cutoff 0.45 / ratio cycles per sample).
+fn decimation_taps(ratio: usize) -> Vec {
+ let n = 24 * ratio + 1;
+ let mid = (n / 2) as f64;
+ let fc = 0.45 / ratio as f64;
+ let mut taps: Vec = (0..n)
+ .map(|k| {
+ let x = k as f64 - mid;
+ let sinc = if x == 0.0 { 2.0 * fc } else { (2.0 * std::f64::consts::PI * fc * x).sin() / (std::f64::consts::PI * x) };
+ let t = k as f64 / (n - 1) as f64;
+ let window = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * t).cos() + 0.08 * (4.0 * std::f64::consts::PI * t).cos();
+ sinc * window
+ })
+ .collect();
+ let sum: f64 = taps.iter().sum();
+ for t in &mut taps {
+ *t /= sum;
+ }
+ taps.into_iter().map(|t| t as f32).collect()
+}
+
+/// Decimates 1-bit DSD audio bytes for a single channel to `f32` PCM.
+///
+/// The default decimation factor is 8 (1 output float per input byte).
+/// When `factor` is 16, 32, or 64, the 1/8 output is further downsampled
+/// by 2, 4, or 8 respectively.
+pub fn decimate_channel(channel_bytes: &[u8], bit_order: BitOrder, factor: u32) -> Result, Error> {
+ allocation_sizes(channel_bytes.len(), factor)?;
+ let num_bytes = channel_bytes.len();
+
+ // Build the 12 x 256 lookup table for fast convolution.
+ // 12 * 256 * 4 bytes = 12 KB, sits comfortably in L1 cache.
+ let mut lut = [[0.0_f32; 256]; FILTER_BYTES];
+ for (k, lut_k) in lut.iter_mut().enumerate() {
+ for (v, cell) in lut_k.iter_mut().enumerate() {
+ *cell = byte_lut(k, v as u8);
+ }
+ }
+
+ let mut stage1 = Vec::new();
+ stage1.try_reserve_exact(num_bytes).map_err(|_| Error::MemoryLimitExceeded)?;
+
+ // History buffer holds the most recent 12 bytes in LSB-first order.
+ // Pre-filled with silence (0x69).
+ let mut history = [SILENCE_LSBF; FILTER_BYTES];
+
+ for &raw_byte in channel_bytes {
+ let byte = match bit_order {
+ BitOrder::LsbFirst => raw_byte,
+ BitOrder::MsbFirst => raw_byte.reverse_bits(),
+ };
+
+ // Shift history left by 1 and push current byte to the end.
+ history.copy_within(1.., 0);
+ if let Some(last) = history.last_mut() {
+ *last = byte;
+ }
+
+ let mut sample = -1.0_f32;
+ for (k, &hist_byte) in history.iter().enumerate() {
+ if let Some(lut_k) = lut.get(k)
+ && let Some(&contrib) = lut_k.get(hist_byte as usize)
+ {
+ sample += contrib;
+ }
+ }
+
+ stage1.push(sample);
+ }
+
+ if factor == 8 {
+ return Ok(stage1);
+ }
+
+ // Secondary decimation by ratio = factor / 8 (2, 4, or 8). A plain average attenuates the band
+ // between the new Nyquist rate and the stage-1 rate too little (about -7.6 dB at 29.4 kHz for
+ // factor 64), so low-pass first: a Blackman-windowed sinc with its cutoff at 90% of the new
+ // Nyquist frequency, evaluated only at the kept samples.
+ let ratio = (factor / 8) as usize;
+ let out_len = stage1.len() / ratio;
+ let mut out = Vec::new();
+ out.try_reserve_exact(out_len).map_err(|_| Error::MemoryLimitExceeded)?;
+
+ let taps = decimation_taps(ratio);
+ let half = (taps.len() / 2) as isize;
+ let last = stage1.len() as isize - 1;
+ for i in 0..out_len {
+ let center = (i * ratio + ratio / 2) as isize;
+ let mut acc = 0.0_f32;
+ for (k, &w) in taps.iter().enumerate() {
+ let idx = (center + k as isize - half).clamp(0, last);
+ if let Some(&x) = stage1.get(idx as usize) {
+ acc += w * x;
+ }
+ }
+ out.push(acc);
+ }
+
+ Ok(out)
+}
+
+#[cfg(test)]
+#[allow(clippy::unwrap_used)]
+mod decimation_tests {
+ use super::*;
+
+ /// A full-scale 29.4 kHz square wave in DSD64 (six bytes of ones, six of zeros) lies between
+ /// the output Nyquist frequency and the sampling rate of a 44.1 kHz result: it must be
+ /// attenuated well, not folded down at 0.42 of its amplitude.
+ #[test]
+ fn factor_64_attenuates_29_4_khz() {
+ let mut bytes = Vec::new();
+ for _ in 0..2000 {
+ bytes.extend_from_slice(&[0xFF; 6]);
+ bytes.extend_from_slice(&[0x00; 6]);
+ }
+ let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap();
+ let mid = &out[out.len() / 4..out.len() * 3 / 4];
+ let peak = mid.iter().fold(0.0_f32, |m, v| m.max(v.abs()));
+ assert!(peak < 0.05, "peak {peak}");
+ }
+
+ #[test]
+ fn decimation_keeps_dc_level() {
+ let bytes = vec![0xFF; 4096];
+ let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap();
+ let mid = out[out.len() / 2];
+ assert!((mid - 1.0).abs() < 0.05, "{mid}");
+ }
+}
diff --git a/crates/audio/src/dsd/mod.rs b/crates/audio/src/dsd/mod.rs
new file mode 100644
index 0000000000..e782b50f05
--- /dev/null
+++ b/crates/audio/src/dsd/mod.rs
@@ -0,0 +1,275 @@
+//! Direct Stream Digital (DSD) audio: Sony DSF and Philips DSDIFF (`.dff`) readers and
+//! DSD-to-PCM decimation.
+//!
+//! DSD stores 1-bit Pulse Density Modulation (PDM) sampled at high rates (e.g. 2,822,400 Hz
+//! for DSD64, 5,644,800 Hz for DSD128, etc.).
+//!
+//! This module provides:
+//! - File parsers for Sony DSF (`.dsf`) and Philips DSDIFF (`.dff`) containers.
+//! - Raw 1-bit audio extraction with preservation of native bit ordering (LSB-first for DSF,
+//! MSB-first for DSDIFF).
+//! - Clean-room 96-tap symmetric FIR decimation filter converting 1-bit PDM to multi-bit PCM
+//! (decimation by 8 to 352,800 Hz for DSD64, or downsampled to 176.4, 88.2, or 44.1 kHz).
+//! - Reference encoders for generating synthetic DSF and DSDIFF files.
+
+pub mod dsdiff;
+pub mod dsf;
+pub mod filter;
+
+use crate::AudioBuffer;
+
+/// Maximum number of audio channels supported (1 to 8).
+pub const MAX_CHANNELS: usize = 8;
+
+/// Minimum allowable DSD sample rate in Hz.
+pub const MIN_SAMPLE_RATE: u32 = 44_100;
+
+/// Maximum allowable DSD sample rate in Hz (e.g. DSD1024 at 45.1584 MHz).
+pub const MAX_SAMPLE_RATE: u32 = 45_158_400;
+
+/// Maximum safe block size for DSF channel blocks (16 MiB).
+pub const MAX_BLOCK_SIZE: u32 = 16 * 1024 * 1024;
+
+/// Maximum audio-buffer allocation budget (256 MiB).
+///
+/// Raw readers limit their channel bytes; PCM conversion separately limits the
+/// simultaneously live PCM output and scratch buffers. Caller-owned raw input,
+/// metadata, and the small filter lookup table are not included.
+pub const MAX_DECODE_BYTES: usize = 256 * 1024 * 1024;
+
+/// Maximum encoded container size, including headers and block padding (256 MiB).
+pub const MAX_ENCODE_BYTES: usize = 256 * 1024 * 1024;
+
+fn encoded_size(payload: usize, header: usize) -> Result {
+ payload.checked_add(header).filter(|&n| n <= MAX_ENCODE_BYTES).ok_or(Error::MemoryLimitExceeded)
+}
+
+// Account for retained channel output plus the current filter's two live buffers.
+fn pcm_budget(lengths: impl Iterator- , factor: u32) -> Result<(), Error> {
+ let mut retained = 0usize;
+ for len in lengths {
+ let (working, output) = filter::allocation_sizes(len, factor)?;
+ if retained.checked_add(working).is_none_or(|n| n > MAX_DECODE_BYTES) {
+ return Err(Error::MemoryLimitExceeded);
+ }
+ retained = retained.checked_add(output).ok_or(Error::MemoryLimitExceeded)?;
+ }
+ Ok(())
+}
+
+/// Supported DSD container formats.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Format {
+ /// Sony DSF (Direct Stream Digital File) format.
+ Dsf,
+ /// Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`).
+ Dsdiff,
+}
+
+/// Bit ordering of 1-bit DSD audio samples within bytes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum BitOrder {
+ /// Least-significant bit first (LSB-first, as used in DSF).
+ /// Bit 0 is the earliest temporal sample; bit 7 is the latest.
+ LsbFirst,
+ /// Most-significant bit first (MSB-first, as used in DSDIFF).
+ /// Bit 7 is the earliest temporal sample; bit 0 is the latest.
+ MsbFirst,
+}
+
+/// Stream properties and metadata parsed from a DSD container header.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Metadata {
+ /// Container format (DSF or DSDIFF).
+ pub format: Format,
+ /// DSD sampling frequency in Hz (e.g. 2,822,400 for DSD64).
+ pub sample_rate: u32,
+ /// Number of audio channels (1 to 8).
+ pub channels: u16,
+ /// Total number of 1-bit audio samples per channel.
+ pub sample_count: u64,
+ /// Channel identification labels (e.g. "SLFT", "SRGT", "Center").
+ pub channel_names: Vec,
+ /// Optional track title if present in container metadata.
+ pub title: Option,
+ /// Optional artist name if present in container metadata.
+ pub artist: Option,
+}
+
+/// Raw 1-bit DSD audio extracted from a file without decimation.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RawAudio {
+ /// Stream metadata from the file header.
+ pub metadata: Metadata,
+ /// Bit ordering of the bytes in `channel_bytes`.
+ pub bit_order: BitOrder,
+ /// Planar 1-bit audio bytes per channel.
+ pub channel_bytes: Vec>,
+}
+
+impl RawAudio {
+ /// Converts all channel byte streams to the requested bit ordering in place.
+ pub fn convert_bit_order(&mut self, target: BitOrder) {
+ if self.bit_order == target {
+ return;
+ }
+ for ch in &mut self.channel_bytes {
+ for b in ch.iter_mut() {
+ *b = b.reverse_bits();
+ }
+ }
+ self.bit_order = target;
+ }
+
+ /// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples.
+ ///
+ /// The default decimation factor is 8 (e.g. 352,800 Hz for DSD64).
+ pub fn to_pcm(&self) -> Result {
+ self.to_pcm_with_factor(8)
+ }
+
+ /// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples with the given factor (8, 16, 32, or 64).
+ pub fn to_pcm_with_factor(&self, factor: u32) -> Result {
+ // Validate before iterating: public RawAudio may contain no channels.
+ if !matches!(factor, 8 | 16 | 32 | 64) {
+ return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64"));
+ }
+ if self.channel_bytes.len() > MAX_CHANNELS {
+ return Err(Error::Unsupported("channel count must be between 1 and 8"));
+ }
+ pcm_budget(self.channel_bytes.iter().map(Vec::len), factor)?;
+ let mut channels = Vec::with_capacity(self.channel_bytes.len());
+ for ch_bytes in &self.channel_bytes {
+ let pcm = filter::decimate_channel(ch_bytes, self.bit_order, factor)?;
+ channels.push(pcm);
+ }
+ let sample_rate = self.metadata.sample_rate / factor;
+ Ok(DecodedAudio { metadata: self.metadata.clone(), sample_rate, channels })
+ }
+}
+
+/// Decoded multi-bit PCM audio produced by DSD-to-PCM decimation.
+#[derive(Debug, Clone, PartialEq)]
+pub struct DecodedAudio {
+ /// Stream metadata from the DSD file header.
+ pub metadata: Metadata,
+ /// PCM sample rate in Hz (e.g. 352,800 Hz for DSD64 decimated by 8).
+ pub sample_rate: u32,
+ /// Planar normalized PCM samples in `[-1.0, 1.0]`, one `Vec` per channel.
+ pub channels: Vec>,
+}
+
+impl DecodedAudio {
+ /// Converts the decoded PCM audio into an [`AudioBuffer`].
+ pub fn to_audio_buffer(&self) -> AudioBuffer {
+ AudioBuffer { sample_rate: self.sample_rate, channels: self.channels.clone() }
+ }
+}
+
+/// Errors returned when parsing or decoding DSD audio.
+#[non_exhaustive]
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum Error {
+ /// Input data ended prematurely while parsing a header or chunk.
+ #[error("unexpected end of file: {0}")]
+ UnexpectedEof(&'static str),
+ /// Invalid magic bytes or malformed chunk header.
+ #[error("invalid DSD header or chunk: {0}")]
+ InvalidHeader(&'static str),
+ /// An unsupported feature, compression, or channel configuration.
+ #[error("unsupported DSD feature: {0}")]
+ Unsupported(&'static str),
+ /// Audio data length or structure does not match the header specification.
+ #[error("invalid audio data: {0}")]
+ InvalidData(&'static str),
+ /// Header or data requested exceeds maximum safe allocation budget.
+ #[error("memory budget exceeded")]
+ MemoryLimitExceeded,
+}
+
+/// Inspects the magic bytes of `bytes` and detects whether it is a DSF or DSDIFF file.
+pub fn probe_format(bytes: &[u8]) -> Result {
+ if bytes.len() < 4 {
+ return Err(Error::UnexpectedEof("input is too short to determine DSD format"));
+ }
+ if &bytes[0..4] == b"DSD " {
+ Ok(Format::Dsf)
+ } else if bytes.len() >= 16 && &bytes[0..4] == b"FRM8" && &bytes[12..16] == b"DSD " {
+ Ok(Format::Dsdiff)
+ } else {
+ Err(Error::InvalidHeader("unknown or unsupported DSD container format"))
+ }
+}
+
+/// Parses the metadata from a DSF or DSDIFF file without decoding audio samples.
+pub fn read_metadata(bytes: &[u8]) -> Result {
+ match probe_format(bytes)? {
+ Format::Dsf => {
+ let (meta, _, _) = dsf::parse_dsf_header(bytes)?;
+ Ok(meta)
+ }
+ Format::Dsdiff => {
+ let (meta, _, _) = dsdiff::parse_dsdiff_header(bytes)?;
+ Ok(meta)
+ }
+ }
+}
+
+/// Reads raw 1-bit planar audio streams from a DSF or DSDIFF file without decimation.
+pub fn read_raw(bytes: &[u8]) -> Result {
+ match probe_format(bytes)? {
+ Format::Dsf => dsf::parse_dsf(bytes),
+ Format::Dsdiff => dsdiff::parse_dsdiff(bytes),
+ }
+}
+
+/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio using decimation by 8.
+///
+/// For DSD64 (2,822,400 Hz), the output sample rate is 352,800 Hz.
+pub fn decode(bytes: &[u8]) -> Result {
+ decode_with_factor(bytes, 8)
+}
+
+/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio with the specified decimation factor.
+///
+/// Supported decimation factors are:
+/// - 8: 1/8th of DSD rate (e.g. 352,800 Hz for DSD64).
+/// - 16: 1/16th of DSD rate (e.g. 176,400 Hz for DSD64).
+/// - 32: 1/32th of DSD rate (e.g. 88,200 Hz for DSD64).
+/// - 64: 1/64th of DSD rate (e.g. 44,100 Hz for DSD64).
+pub fn decode_with_factor(bytes: &[u8], factor: u32) -> Result {
+ let raw = read_raw(bytes)?;
+ raw.to_pcm_with_factor(factor)
+}
+
+/// Encodes planar 1-bit audio channels into a Sony DSF file.
+pub fn encode_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> {
+ dsf::write_dsf(sample_rate, channels, sample_count, block_size)
+}
+
+/// Encodes planar 1-bit audio channels into a Philips DSDIFF file.
+pub fn encode_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result, Error> {
+ dsdiff::write_dsdiff(sample_rate, channels, sample_count)
+}
+
+#[cfg(test)]
+mod budget_tests {
+ use super::*;
+
+ #[test]
+ fn pcm_budget_counts_all_channels_and_live_scratch() {
+ let quarter = MAX_DECODE_BYTES / 4;
+ assert!(pcm_budget([quarter / 2, quarter / 2].into_iter(), 8).is_ok());
+ assert_eq!(pcm_budget([quarter / 2, quarter / 2 + 1].into_iter(), 8), Err(Error::MemoryLimitExceeded));
+ assert!(pcm_budget([quarter / 2].into_iter(), 16).is_ok());
+ assert_eq!(pcm_budget([quarter].into_iter(), 16), Err(Error::MemoryLimitExceeded));
+ assert_eq!(pcm_budget([usize::MAX].into_iter(), 8), Err(Error::MemoryLimitExceeded));
+ }
+
+ #[test]
+ fn encoded_budget_includes_headers_without_large_allocations() {
+ assert_eq!(encoded_size(MAX_ENCODE_BYTES - 92, 92), Ok(MAX_ENCODE_BYTES));
+ assert_eq!(encoded_size(MAX_ENCODE_BYTES - 91, 92), Err(Error::MemoryLimitExceeded));
+ assert_eq!(encoded_size(usize::MAX, 92), Err(Error::MemoryLimitExceeded));
+ }
+}
diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs
index 3ccdcdf3ff..9ca1571cf8 100644
--- a/crates/audio/src/lib.rs
+++ b/crates/audio/src/lib.rs
@@ -2,7 +2,7 @@
#![warn(missing_docs)]
// The docs link items of every feature; built with fewer features, those links have no target.
// CI and docs.rs build the docs with all features, where every link must resolve.
-#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks")), allow(rustdoc::broken_intra_doc_links))]
+#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks", feature = "dsd")), allow(rustdoc::broken_intra_doc_links))]
//! Audio file I/O and codecs for the Craft apps. Input and output are byte slices or a
//! [`craft_media::ByteSource`] (no filesystem access of its own); builds for
//! `wasm32-unknown-unknown`.
@@ -32,7 +32,7 @@
//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`]
//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder;
//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), [`adpcm`]
-//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM),
+//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM),
//! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`:
//! Sierra VMD sound).
//!
@@ -47,6 +47,8 @@ pub mod adpcm;
#[cfg(any(feature = "alac-decode", feature = "alac-encode"))]
pub mod alac;
mod buffer;
+#[cfg(feature = "dsd")]
+pub mod dsd;
#[cfg(feature = "g722")]
pub mod g722;
#[cfg(feature = "g726")]
diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs
new file mode 100644
index 0000000000..5388f2aa45
--- /dev/null
+++ b/crates/audio/tests/dsd_bounds.rs
@@ -0,0 +1,208 @@
+//! Hostile container sizes must return errors, never wrap offsets or panic.
+use craft_audio::dsd::{BitOrder, Error, RawAudio, encode_dsdiff, encode_dsf, read_metadata, read_raw};
+
+#[test]
+fn dsf_untrusted_sizes_are_checked() {
+ let original = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap();
+ for offset in [32, 84] {
+ // fmt and data chunk sizes
+ for size in [u64::MAX, u64::MAX - 31, 1 << 32] {
+ let mut bytes = original.clone();
+ bytes[offset..offset + 8].copy_from_slice(&size.to_le_bytes());
+ assert!(read_metadata(&bytes).is_err());
+ assert!(read_raw(&bytes).is_err());
+ }
+ }
+ let mut bytes = original;
+ bytes[64..72].copy_from_slice(&u64::MAX.to_le_bytes());
+ assert_eq!(read_raw(&bytes), Err(Error::MemoryLimitExceeded));
+}
+
+#[test]
+fn dsdiff_untrusted_top_level_and_property_sizes_are_checked() {
+ let original = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap();
+ let prop = original.windows(4).position(|w| w == b"PROP").unwrap();
+ for offset in [4, 20, prop + 20] {
+ // FRM8, FVER, nested FS
+ for size in [u64::MAX, u64::MAX - 31, 1 << 32] {
+ let mut bytes = original.clone();
+ bytes[offset..offset + 8].copy_from_slice(&size.to_be_bytes());
+ assert!(read_metadata(&bytes).is_err());
+ assert!(read_raw(&bytes).is_err());
+ }
+ }
+}
+
+#[test]
+fn dsdiff_invalid_optional_disc_info_is_ignored_without_overflow() {
+ let mut bytes = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap();
+ let expected = read_metadata(&bytes).unwrap();
+ bytes.extend_from_slice(b"DIIN");
+ bytes.extend_from_slice(&12u64.to_be_bytes());
+ bytes.extend_from_slice(b"DITI");
+ bytes.extend_from_slice(&u64::MAX.to_be_bytes());
+ let size = (bytes.len() - 12) as u64;
+ bytes[4..12].copy_from_slice(&size.to_be_bytes());
+ // Optional malformed text is ignored on 64-bit; unrepresentable sizes may
+ // be rejected on narrower targets, but must never wrap or panic.
+ match read_metadata(&bytes) {
+ Ok(actual) => assert_eq!(actual, expected),
+ Err(Error::MemoryLimitExceeded) => {}
+ other => panic!("unexpected result: {other:?}"),
+ }
+}
+
+#[test]
+fn empty_raw_audio_rejects_invalid_decimation_factors() {
+ let bytes = encode_dsf(2_822_400, &[&[]], 0, 8).unwrap();
+ let raw = RawAudio { metadata: read_metadata(&bytes).unwrap(), bit_order: BitOrder::LsbFirst, channel_bytes: Vec::new() };
+ for factor in [0, 1, 7, 9, u32::MAX] {
+ assert!(matches!(raw.to_pcm_with_factor(factor), Err(Error::Unsupported(_))));
+ }
+ for factor in [8, 16, 32, 64] {
+ assert_eq!(raw.to_pcm_with_factor(factor).unwrap().sample_rate, 2_822_400 / factor);
+ }
+}
+
+#[test]
+fn writers_reject_unbounded_output_before_allocating() {
+ let channels: [&[u8]; 8] = [&[]; 8];
+ for count in [u64::MAX, (craft_audio::dsd::MAX_ENCODE_BYTES as u64 + 1) * 8] {
+ assert_eq!(encode_dsf(2_822_400, &channels, count, 8), Err(Error::MemoryLimitExceeded));
+ assert_eq!(encode_dsdiff(2_822_400, &channels, count), Err(Error::MemoryLimitExceeded));
+ }
+ assert!(matches!(encode_dsf(2_822_400, &[&[]], 0, u32::MAX), Err(Error::InvalidData(_))));
+}
+
+#[test]
+fn encoded_sizes_match_actual_bytes_for_odd_and_even_payloads() {
+ for channels in 1..=8 {
+ for len in 0..=9 {
+ let data = vec![0x69; len];
+ let planes = vec![data.as_slice(); channels];
+ for block in [0, 1, 3, 8] {
+ // DSF has channel types for 1 to 6 channels only.
+ if channels > 6 {
+ assert!(matches!(encode_dsf(2_822_400, &planes, len as u64 * 8, block), Err(Error::Unsupported(_))));
+ continue;
+ }
+ let dsf = encode_dsf(2_822_400, &planes, len as u64 * 8, block).unwrap();
+ assert_eq!(u64::from_le_bytes(dsf[12..20].try_into().unwrap()), dsf.len() as u64);
+ assert_eq!(read_raw(&dsf).unwrap().channel_bytes, vec![data.clone(); channels]);
+ }
+ let dff = encode_dsdiff(2_822_400, &planes, len as u64 * 8).unwrap();
+ assert_eq!(u64::from_be_bytes(dff[4..12].try_into().unwrap()) + 12, dff.len() as u64);
+ assert_eq!(read_raw(&dff).unwrap().channel_bytes, vec![data; channels]);
+ }
+ }
+}
+
+#[test]
+fn dsf_audio_stops_at_the_declared_data_chunk() {
+ for channels in 1..=2 {
+ let input = vec![&[0x33u8; 8][..]; channels];
+ let mut bytes = encode_dsf(2_822_400, &input, 64, 8).unwrap();
+ // Ask for an additional block without extending the data chunk.
+ bytes[64..72].copy_from_slice(&128u64.to_le_bytes());
+ let expected = read_raw(&bytes).unwrap();
+ for c in &expected.channel_bytes {
+ assert_eq!(&c[..8], &[0x33; 8]);
+ assert_eq!(&c[8..], &[0x69; 8]);
+ }
+ let metadata_offset = bytes.len() as u64;
+ bytes[20..28].copy_from_slice(&metadata_offset.to_le_bytes());
+ bytes.extend_from_slice(b"ID3\x04\x00\x00\x00\x00\x00\x00");
+ bytes.extend_from_slice(&[0xff; 32]);
+ let file_size = bytes.len() as u64;
+ bytes[12..20].copy_from_slice(&file_size.to_le_bytes());
+ assert_eq!(read_raw(&bytes).unwrap().channel_bytes, expected.channel_bytes);
+ }
+}
+
+#[test]
+fn dsdiff_odd_payload_receives_pad_byte() {
+ let input = [&[0xaau8; 3][..]];
+ let bytes = encode_dsdiff(2_822_400, &input, 24).unwrap();
+ let raw = read_raw(&bytes).unwrap();
+ assert_eq!(raw.channel_bytes[0].len(), 3);
+}
+
+#[test]
+fn dsf_declared_file_size_and_metadata_pointer_bounds() {
+ let valid = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap();
+
+ // Undersized file size declaration (e.g. 28)
+ let mut undersized = valid.clone();
+ undersized[12..20].copy_from_slice(&28u64.to_le_bytes());
+ assert!(read_metadata(&undersized).is_err());
+ assert!(read_raw(&undersized).is_err());
+
+ // Oversized file size declaration beyond buffer
+ let mut oversized = valid.clone();
+ let big_size = valid.len() as u64 + 100;
+ oversized[12..20].copy_from_slice(&big_size.to_le_bytes());
+ assert!(read_metadata(&oversized).is_err());
+ assert!(read_raw(&oversized).is_err());
+
+ // Metadata pointer outside the declared file bounds
+ let mut outside_meta = valid.clone();
+ let outside_offset = valid.len() as u64 + 10;
+ outside_meta[20..28].copy_from_slice(&outside_offset.to_le_bytes());
+ assert!(read_metadata(&outside_meta).is_err());
+ assert!(read_raw(&outside_meta).is_err());
+
+ // Metadata pointer overlapping data chunk
+ let mut overlap_meta = valid.clone();
+ overlap_meta[20..28].copy_from_slice(&32u64.to_le_bytes());
+ assert!(read_metadata(&overlap_meta).is_err());
+ assert!(read_raw(&overlap_meta).is_err());
+}
+
+#[test]
+fn dsdiff_channel_count_and_duplicate_chunks_are_validated() {
+ let base = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap();
+
+ // Locate PROP chunk payload and CHNL subchunk
+ let prop_idx = base.windows(4).position(|w| w == b"PROP").unwrap();
+ let chnl_idx = base.windows(4).position(|w| w == b"CHNL").unwrap();
+
+ // 1. Oversized channel count (e.g. 65535 or 9)
+ let mut bad_count = base.clone();
+ bad_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&65535u16.to_be_bytes());
+ assert!(matches!(read_metadata(&bad_count), Err(Error::Unsupported(_))));
+ assert!(matches!(read_raw(&bad_count), Err(Error::Unsupported(_))));
+
+ let mut zero_count = base.clone();
+ zero_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&0u16.to_be_bytes());
+ assert!(matches!(read_metadata(&zero_count), Err(Error::Unsupported(_))));
+
+ // 2. Conflicting duplicate CHNL chunk in PROP
+ let mut dup_chnl = base.clone();
+ let chnl_chunk = dup_chnl[chnl_idx..chnl_idx + 18].to_vec();
+ dup_chnl.splice(chnl_idx..chnl_idx, chnl_chunk);
+ // Adjust PROP size and FRM8 size
+ let prop_size = u64::from_be_bytes(dup_chnl[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 18;
+ dup_chnl[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes());
+ let frm8_size = (dup_chnl.len() - 12) as u64;
+ dup_chnl[4..12].copy_from_slice(&frm8_size.to_be_bytes());
+ assert_eq!(read_metadata(&dup_chnl), Err(Error::InvalidHeader("duplicate CHNL chunk")));
+
+ // 3. Duplicate FS chunk in PROP
+ let fs_idx = base.windows(4).position(|w| w == b"FS ").unwrap();
+ let mut dup_fs = base.clone();
+ let fs_chunk = dup_fs[fs_idx..fs_idx + 16].to_vec();
+ dup_fs.splice(fs_idx..fs_idx, fs_chunk);
+ let prop_size = u64::from_be_bytes(dup_fs[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 16;
+ dup_fs[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes());
+ let frm8_size = (dup_fs.len() - 12) as u64;
+ dup_fs[4..12].copy_from_slice(&frm8_size.to_be_bytes());
+ assert_eq!(read_metadata(&dup_fs), Err(Error::InvalidHeader("duplicate FS chunk")));
+}
+
+#[test]
+#[cfg(target_pointer_width = "32")]
+fn dsdiff_32bit_padding_overflow_is_rejected() {
+ let dummy = [&[][..]];
+ let result = encode_dsdiff(2_822_400, &dummy, 34_359_738_360);
+ assert_eq!(result, Err(Error::MemoryLimitExceeded));
+}
diff --git a/crates/audio/tests/dsd_metadata.rs b/crates/audio/tests/dsd_metadata.rs
new file mode 100644
index 0000000000..74fd16f314
--- /dev/null
+++ b/crates/audio/tests/dsd_metadata.rs
@@ -0,0 +1,155 @@
+//! Channel labels, text metadata and padding in the DSF and DSDIFF readers and writers.
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+use craft_audio::dsd::{encode_dsdiff, encode_dsf, read_metadata, read_raw};
+
+const RATE: u32 = 2_822_400;
+
+fn planes(channels: usize, len: usize) -> Vec> {
+ vec![vec![0x69; len]; channels]
+}
+
+fn refs(p: &[Vec]) -> Vec<&[u8]> {
+ p.iter().map(Vec::as_slice).collect()
+}
+
+#[test]
+fn dsdiff_names_surround_channels_by_layout() {
+ for (n, names) in [
+ (5, vec!["Mono/Left", "Right", "Center", "LeftSurround", "RightSurround"]),
+ (6, vec!["Mono/Left", "Right", "Center", "LFE", "LeftSurround", "RightSurround"]),
+ ] {
+ let p = planes(n, 4);
+ let bytes = encode_dsdiff(RATE, &refs(&p), 32).unwrap();
+ assert_eq!(read_metadata(&bytes).unwrap().channel_names, names, "{n} channels");
+ }
+}
+
+#[test]
+fn dsdiff_odd_audio_is_padded_and_counted_in_the_file_size() {
+ let p = planes(1, 1);
+ let bytes = encode_dsdiff(RATE, &refs(&p), 8).unwrap();
+ assert_eq!(bytes.len() % 2, 0);
+ assert_eq!(u64::from_be_bytes(bytes[4..12].try_into().unwrap()) + 12, bytes.len() as u64);
+ assert_eq!(*bytes.last().unwrap(), 0, "pad byte");
+ assert_eq!(read_raw(&bytes).unwrap().channel_bytes, vec![vec![0x69]]);
+}
+
+fn with_diin(mut bytes: Vec, sub: &[u8; 4], payload: &[u8]) -> Vec {
+ let mut sub_chunk = Vec::new();
+ sub_chunk.extend_from_slice(sub);
+ sub_chunk.extend_from_slice(&(payload.len() as u64).to_be_bytes());
+ sub_chunk.extend_from_slice(payload);
+ if payload.len() % 2 == 1 {
+ sub_chunk.push(0);
+ }
+ bytes.extend_from_slice(b"DIIN");
+ bytes.extend_from_slice(&(sub_chunk.len() as u64).to_be_bytes());
+ bytes.extend_from_slice(&sub_chunk);
+ let size = (bytes.len() - 12) as u64;
+ bytes[4..12].copy_from_slice(&size.to_be_bytes());
+ bytes
+}
+
+#[test]
+fn dsdiff_title_and_artist_skip_the_character_count() {
+ let p = planes(2, 4);
+ let base = encode_dsdiff(RATE, &refs(&p), 32).unwrap();
+ let mut payload = 4u32.to_be_bytes().to_vec();
+ payload.extend_from_slice(b"Test");
+ let bytes = with_diin(base.clone(), b"DITI", &payload);
+ assert_eq!(read_metadata(&bytes).unwrap().title.as_deref(), Some("Test"));
+ let bytes = with_diin(base.clone(), b"DIAR", &payload);
+ assert_eq!(read_metadata(&bytes).unwrap().artist.as_deref(), Some("Test"));
+ // A count longer than the chunk is not text.
+ let mut bad = 99u32.to_be_bytes().to_vec();
+ bad.extend_from_slice(b"Test");
+ assert_eq!(read_metadata(&with_diin(base, b"DITI", &bad)).unwrap().title, None);
+}
+
+#[test]
+fn dsf_channel_types_match_the_channel_count() {
+ for (n, expect) in [(1, 1), (2, 2), (3, 3), (4, 4), (5, 6), (6, 7)] {
+ let p = planes(n, 4);
+ let bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap();
+ assert_eq!(u32::from_le_bytes(bytes[48..52].try_into().unwrap()), expect, "{n} channels");
+ assert_eq!(read_metadata(&bytes).unwrap().channel_names.len(), n);
+ }
+ let p = planes(7, 4);
+ assert!(encode_dsf(RATE, &refs(&p), 32, 4096).is_err());
+}
+
+#[test]
+fn dsf_type_5_names_the_fourth_channel_lfe() {
+ let p = planes(4, 4);
+ let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap();
+ bytes[48..52].copy_from_slice(&5u32.to_le_bytes());
+ assert_eq!(read_metadata(&bytes).unwrap().channel_names, ["FrontLeft", "FrontRight", "Center", "LFE"]);
+}
+
+fn id3(version: u8, frames: &[u8]) -> Vec {
+ let n = frames.len();
+ let mut tag = vec![b'I', b'D', b'3', version, 0, 0];
+ tag.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]);
+ tag.extend_from_slice(frames);
+ tag
+}
+
+fn frame(version: u8, id: &[u8; 4], body: &[u8]) -> Vec {
+ let n = body.len();
+ let mut f = id.to_vec();
+ if version >= 4 {
+ f.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]);
+ } else {
+ f.extend_from_slice(&(n as u32).to_be_bytes());
+ }
+ f.extend_from_slice(&[0, 0]);
+ f.extend_from_slice(body);
+ f
+}
+
+fn dsf_with_tag(tag: &[u8]) -> Vec {
+ let p = planes(2, 4);
+ let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap();
+ let offset = bytes.len() as u64;
+ bytes[20..28].copy_from_slice(&offset.to_le_bytes());
+ bytes.extend_from_slice(tag);
+ let file_size = bytes.len() as u64;
+ bytes[12..20].copy_from_slice(&file_size.to_le_bytes());
+ bytes
+}
+
+#[test]
+fn id3v24_frame_sizes_are_synchsafe() {
+ // A 128-byte frame has the synchsafe size 00 00 01 00; read as plain big-endian it is 256.
+ let mut frames = frame(4, b"APIC", &[0u8; 128]);
+ let mut title = vec![3];
+ title.extend_from_slice(b"After art");
+ frames.extend(frame(4, b"TIT2", &title));
+ let m = read_metadata(&dsf_with_tag(&id3(4, &frames))).unwrap();
+ assert_eq!(m.title.as_deref(), Some("After art"));
+}
+
+#[test]
+fn id3v23_frame_sizes_stay_big_endian() {
+ let mut frames = frame(3, b"APIC", &[0u8; 128]);
+ let mut title = vec![3];
+ title.extend_from_slice(b"Three");
+ frames.extend(frame(3, b"TIT2", &title));
+ let m = read_metadata(&dsf_with_tag(&id3(3, &frames))).unwrap();
+ assert_eq!(m.title.as_deref(), Some("Three"));
+}
+
+#[test]
+fn id3_text_encodings() {
+ let cases: [(&[u8], &str); 5] = [
+ (b"\x00Caf\xe9", "Café"),
+ (b"\x03Caf\xc3\xa9", "Café"),
+ (b"\x02\x00A\x00B", "AB"),
+ (b"\x01\xFF\xFEA\x00B\x00", "AB"),
+ (b"\x01\xFE\xFF\x00A\x00B", "AB"),
+ ];
+ for (body, expect) in cases {
+ let m = read_metadata(&dsf_with_tag(&id3(4, &frame(4, b"TIT2", body)))).unwrap();
+ assert_eq!(m.title.as_deref(), Some(expect), "{body:?}");
+ }
+}
diff --git a/crates/audio/tests/dsd_oracle.rs b/crates/audio/tests/dsd_oracle.rs
new file mode 100644
index 0000000000..94334485b9
--- /dev/null
+++ b/crates/audio/tests/dsd_oracle.rs
@@ -0,0 +1,347 @@
+//! DSD (DSF and DSDIFF) decoding and decimation tests, including oracle tests against FFmpeg
+//! (skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`).
+
+use craft_audio::dsd::{BitOrder, Format, decode, decode_with_factor, encode_dsdiff, encode_dsf, filter::SILENCE_LSBF, read_metadata, read_raw};
+use std::process::Command;
+
+/// Generates a test DSD 1-bit stream with various features (silence, alternating tones, noise).
+fn make_test_stream(num_bytes: usize, seed: u8) -> Vec {
+ let mut out = Vec::with_capacity(num_bytes);
+ let mut s = seed as u32;
+ for i in 0..num_bytes {
+ s ^= s << 13;
+ s ^= s >> 17;
+ s ^= s << 5;
+ let byte = match (i / 128) % 4 {
+ 0 => SILENCE_LSBF, // DSD silence
+ 1 => 0x55, // Alternate silence pattern
+ 2 => (s & 0xFF) as u8,
+ _ => {
+ if (i / 16) % 2 == 0 {
+ 0xFF // full positive level
+ } else {
+ 0x00 // full negative level
+ }
+ }
+ };
+ out.push(byte);
+ }
+ out
+}
+
+#[test]
+fn roundtrip_dsf() {
+ let sample_rate = 2_822_400;
+ let block_size = 4096;
+ let ch0 = make_test_stream(8192, 42);
+ let ch1 = make_test_stream(8192, 99);
+ let sample_count = 8192 * 8;
+
+ let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf");
+
+ let meta = read_metadata(&dsf_bytes).expect("read_metadata");
+ assert_eq!(meta.format, Format::Dsf);
+ assert_eq!(meta.sample_rate, sample_rate);
+ assert_eq!(meta.channels, 2);
+ assert_eq!(meta.sample_count, sample_count);
+
+ let raw = read_raw(&dsf_bytes).expect("read_raw");
+ assert_eq!(raw.bit_order, BitOrder::LsbFirst);
+ assert_eq!(raw.channel_bytes.len(), 2);
+ assert_eq!(raw.channel_bytes[0], ch0);
+ assert_eq!(raw.channel_bytes[1], ch1);
+
+ let decoded = decode(&dsf_bytes).expect("decode");
+ assert_eq!(decoded.sample_rate, sample_rate / 8);
+ assert_eq!(decoded.channels.len(), 2);
+ assert_eq!(decoded.channels[0].len(), 8192);
+ assert_eq!(decoded.channels[1].len(), 8192);
+}
+
+#[test]
+fn roundtrip_dsdiff() {
+ let sample_rate = 2_822_400;
+ let ch0 = make_test_stream(4096, 17);
+ let ch1 = make_test_stream(4096, 73);
+ let sample_count = 4096 * 8;
+
+ let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff");
+
+ let meta = read_metadata(&dff_bytes).expect("read_metadata");
+ assert_eq!(meta.format, Format::Dsdiff);
+ assert_eq!(meta.sample_rate, sample_rate);
+ assert_eq!(meta.channels, 2);
+ assert_eq!(meta.sample_count, sample_count);
+
+ let raw = read_raw(&dff_bytes).expect("read_raw");
+ assert_eq!(raw.bit_order, BitOrder::MsbFirst);
+ assert_eq!(raw.channel_bytes.len(), 2);
+ assert_eq!(raw.channel_bytes[0], ch0);
+ assert_eq!(raw.channel_bytes[1], ch1);
+
+ let decoded = decode(&dff_bytes).expect("decode");
+ assert_eq!(decoded.sample_rate, sample_rate / 8);
+ assert_eq!(decoded.channels.len(), 2);
+ assert_eq!(decoded.channels[0].len(), 4096);
+ assert_eq!(decoded.channels[1].len(), 4096);
+}
+
+#[test]
+fn decimation_factors() {
+ let sample_rate = 2_822_400;
+ let ch0 = make_test_stream(2048, 123);
+ let dsf_bytes = encode_dsf(sample_rate, &[&ch0], 2048 * 8, 4096).expect("encode_dsf");
+
+ // Factor 8 -> 352,800 Hz
+ let dec8 = decode_with_factor(&dsf_bytes, 8).expect("factor 8");
+ assert_eq!(dec8.sample_rate, 352_800);
+ assert_eq!(dec8.channels[0].len(), 2048);
+
+ // Factor 16 -> 176,400 Hz
+ let dec16 = decode_with_factor(&dsf_bytes, 16).expect("factor 16");
+ assert_eq!(dec16.sample_rate, 176_400);
+ assert_eq!(dec16.channels[0].len(), 1024);
+
+ // Factor 32 -> 88,200 Hz
+ let dec32 = decode_with_factor(&dsf_bytes, 32).expect("factor 32");
+ assert_eq!(dec32.sample_rate, 88_200);
+ assert_eq!(dec32.channels[0].len(), 512);
+
+ // Factor 64 -> 44,100 Hz
+ let dec64 = decode_with_factor(&dsf_bytes, 64).expect("factor 64");
+ assert_eq!(dec64.sample_rate, 44_100);
+ assert_eq!(dec64.channels[0].len(), 256);
+
+ // Invalid factor
+ assert!(decode_with_factor(&dsf_bytes, 12).is_err());
+}
+
+#[test]
+fn silence_and_dc_levels() {
+ let sample_rate = 2_822_400;
+ // Pure silence
+ let silence = vec![SILENCE_LSBF; 1024];
+ let dsf_bytes = encode_dsf(sample_rate, &[&silence], 1024 * 8, 4096).expect("encode");
+ let dec = decode(&dsf_bytes).expect("decode");
+ for &sample in &dec.channels[0][12..] {
+ assert!(sample.abs() < 1e-4, "silence sample should be ~0.0, got {sample}");
+ }
+
+ // Full positive level
+ let ones = vec![0xFF; 1024];
+ let dsf_ones = encode_dsf(sample_rate, &[&ones], 1024 * 8, 4096).expect("encode");
+ let dec_ones = decode(&dsf_ones).expect("decode");
+ for &sample in &dec_ones.channels[0][12..] {
+ assert!((sample - 1.0).abs() < 1e-4, "ones sample should be ~1.0, got {sample}");
+ }
+
+ // Full negative level
+ let zeros = vec![0x00; 1024];
+ let dsf_zeros = encode_dsf(sample_rate, &[&zeros], 1024 * 8, 4096).expect("encode");
+ let dec_zeros = decode(&dsf_zeros).expect("decode");
+ for &sample in &dec_zeros.channels[0][12..] {
+ assert!((sample - (-1.0)).abs() < 1e-4, "zeros sample should be ~-1.0, got {sample}");
+ }
+}
+
+#[test]
+fn multichannel_dsf_and_dsdiff() {
+ let sample_rate = 2_822_400;
+ // Test 6-channel (5.1 surround)
+ let channels: Vec> = (0..6).map(|c| make_test_stream(1024, (c * 23 + 5) as u8)).collect();
+ let ch_refs: Vec<&[u8]> = channels.iter().map(Vec::as_slice).collect();
+
+ let dsf = encode_dsf(sample_rate, &ch_refs, 1024 * 8, 512).expect("encode 5.1 dsf");
+ let dsf_meta = read_metadata(&dsf).expect("meta 5.1 dsf");
+ assert_eq!(dsf_meta.channels, 6);
+ let dsf_dec = decode(&dsf).expect("decode 5.1 dsf");
+ assert_eq!(dsf_dec.channels.len(), 6);
+ assert_eq!(dsf_dec.channels[0].len(), 1024);
+
+ let dff = encode_dsdiff(sample_rate, &ch_refs, 1024 * 8).expect("encode 5.1 dsdiff");
+ let dff_meta = read_metadata(&dff).expect("meta 5.1 dsdiff");
+ assert_eq!(dff_meta.channels, 6);
+ let dff_dec = decode(&dff).expect("decode 5.1 dsdiff");
+ assert_eq!(dff_dec.channels.len(), 6);
+ assert_eq!(dff_dec.channels[0].len(), 1024);
+}
+
+#[test]
+fn dst_compression_rejected() {
+ // Construct a minimal DSDIFF with CMPR = 'DST '
+ let mut dff = encode_dsdiff(2_822_400, &[&[0xAA; 64]], 512).expect("encode");
+ // Find 'DSD ' in CMPR chunk and replace with 'DST '
+ let mut replaced = false;
+ for i in 0..dff.len().saturating_sub(8) {
+ if &dff[i..i + 4] == b"CMPR" && &dff[i + 12..i + 16] == b"DSD " {
+ dff[i + 12..i + 16].copy_from_slice(b"DST ");
+ replaced = true;
+ break;
+ }
+ }
+ assert!(replaced, "should find CMPR DSD chunk");
+ assert!(read_metadata(&dff).is_err(), "DST compression should be rejected as unsupported");
+ assert!(decode(&dff).is_err(), "DST compression should be rejected as unsupported");
+}
+
+#[test]
+fn id3v2_tag_in_dsf() {
+ let sample_rate = 2_822_400;
+ let mut dsf = encode_dsf(sample_rate, &[&[0x69; 128]], 1024, 512).expect("encode");
+ let metadata_offset = dsf.len() as u64;
+
+ // Append simple ID3v2.3 tag with TIT2="Test Title" and TPE1="Test Artist"
+ let mut id3 = Vec::new();
+ id3.extend_from_slice(b"ID3");
+ id3.push(3); // v2.3
+ id3.push(0); // revision
+ id3.push(0); // flags
+
+ let mut frames = Vec::new();
+ // TIT2 frame
+ frames.extend_from_slice(b"TIT2");
+ let title_bytes = b"\x03DSD Master"; // UTF-8
+ frames.extend_from_slice(&(title_bytes.len() as u32).to_be_bytes());
+ frames.extend_from_slice(&[0, 0]); // flags
+ frames.extend_from_slice(title_bytes);
+
+ // TPE1 frame
+ frames.extend_from_slice(b"TPE1");
+ let artist_bytes = b"\x03The Audiophiles";
+ frames.extend_from_slice(&(artist_bytes.len() as u32).to_be_bytes());
+ frames.extend_from_slice(&[0, 0]); // flags
+ frames.extend_from_slice(artist_bytes);
+
+ // synchsafe size
+ let tag_len = frames.len();
+ id3.push(((tag_len >> 21) & 0x7F) as u8);
+ id3.push(((tag_len >> 14) & 0x7F) as u8);
+ id3.push(((tag_len >> 7) & 0x7F) as u8);
+ id3.push((tag_len & 0x7F) as u8);
+ id3.extend_from_slice(&frames);
+
+ dsf.extend_from_slice(&id3);
+ // Update file size and metadata_offset of 'DSD ' chunk
+ let file_size = dsf.len() as u64;
+ dsf[12..20].copy_from_slice(&file_size.to_le_bytes());
+ dsf[20..28].copy_from_slice(&metadata_offset.to_le_bytes());
+
+ let meta = read_metadata(&dsf).expect("read metadata with ID3");
+ assert_eq!(meta.title.as_deref(), Some("DSD Master"));
+ assert_eq!(meta.artist.as_deref(), Some("The Audiophiles"));
+}
+
+#[test]
+fn raw_audio_bit_order_conversion() {
+ let ch0 = vec![0b00000001, 0b10000000];
+ let dsf = encode_dsf(2_822_400, &[&ch0], 16, 512).expect("encode");
+ let mut raw = read_raw(&dsf).expect("read raw");
+ assert_eq!(raw.bit_order, BitOrder::LsbFirst);
+ assert_eq!(raw.channel_bytes[0], ch0);
+
+ raw.convert_bit_order(BitOrder::MsbFirst);
+ assert_eq!(raw.bit_order, BitOrder::MsbFirst);
+ assert_eq!(raw.channel_bytes[0], vec![0b10000000, 0b00000001]);
+}
+
+#[test]
+fn hostile_inputs() {
+ // Truncated headers
+ assert!(read_metadata(b"").is_err());
+ assert!(read_metadata(b"DSD ").is_err());
+ assert!(read_metadata(b"FRM8").is_err());
+
+ // Bad magic
+ assert!(read_metadata(b"RIFF\x00\x00\x00\x00WAVE").is_err());
+
+ // Truncated DSF chunk
+ let mut bad_dsf = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode");
+ bad_dsf.truncate(50);
+ assert!(decode(&bad_dsf).is_err());
+
+ // Corrupted fmt chunk size
+ let mut bad_fmt = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode");
+ bad_fmt[32] = 0; // bits_per_sample = 0
+ assert!(decode(&bad_fmt).is_err());
+
+ // Absurd channels
+ let mut bad_ch = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode");
+ bad_ch[28 + 24] = 99; // channel_count = 99
+ assert!(decode(&bad_ch).is_err());
+}
+
+#[test]
+fn ffmpeg_dsf_oracle() {
+ let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return };
+ let dir = craft_media_testkit::fixture_subdir("dsd");
+
+ let sample_rate = 2_822_400;
+ let block_size = 4096;
+ let ch0 = make_test_stream(16384, 11);
+ let ch1 = make_test_stream(16384, 88);
+ let sample_count = 16384 * 8;
+
+ let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf");
+ let dsf_path = dir.join("test_oracle.dsf");
+ std::fs::write(&dsf_path, &dsf_bytes).expect("write fixture");
+
+ let raw_out_path = dir.join("ffmpeg_dsf.raw");
+ let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dsf_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg");
+ assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr));
+
+ let raw_bytes = std::fs::read(&raw_out_path).expect("read raw");
+ let ffmpeg_floats: Vec = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
+
+ let decoded = decode(&dsf_bytes).expect("our decode");
+ assert_eq!(decoded.channels.len(), 2);
+ assert_eq!(decoded.channels[0].len(), 16384);
+ assert_eq!(decoded.channels[1].len(), 16384);
+
+ // FFmpeg interleaves L0, R0, L1, R1...
+ // Compare samples after filter startup (sample 12 onwards).
+ for i in 12..16000 {
+ let ff_l = ffmpeg_floats[i * 2];
+ let ff_r = ffmpeg_floats[i * 2 + 1];
+ let our_l = decoded.channels[0][i];
+ let our_r = decoded.channels[1][i];
+
+ assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}");
+ assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}");
+ }
+}
+
+#[test]
+fn ffmpeg_dsdiff_oracle() {
+ let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return };
+ let dir = craft_media_testkit::fixture_subdir("dsd");
+
+ let sample_rate = 2_822_400;
+ let ch0 = make_test_stream(8192, 33);
+ let ch1 = make_test_stream(8192, 77);
+ let sample_count = 8192 * 8;
+
+ let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff");
+ let dff_path = dir.join("test_oracle.dff");
+ std::fs::write(&dff_path, &dff_bytes).expect("write fixture");
+
+ let raw_out_path = dir.join("ffmpeg_dff.raw");
+ let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dff_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg");
+ assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr));
+
+ let raw_bytes = std::fs::read(&raw_out_path).expect("read raw");
+ let ffmpeg_floats: Vec = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
+
+ let decoded = decode(&dff_bytes).expect("our decode");
+ assert_eq!(decoded.channels.len(), 2);
+ assert_eq!(decoded.channels[0].len(), 8192);
+
+ for i in 12..8000 {
+ let ff_l = ffmpeg_floats[i * 2];
+ let ff_r = ffmpeg_floats[i * 2 + 1];
+ let our_l = decoded.channels[0][i];
+ let our_r = decoded.channels[1][i];
+
+ assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}");
+ assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}");
+ }
+}
diff --git a/crates/audio/tests/main.rs b/crates/audio/tests/main.rs
index a1bd3d933b..5470dc5530 100644
--- a/crates/audio/tests/main.rs
+++ b/crates/audio/tests/main.rs
@@ -9,6 +9,15 @@ mod audio;
#[cfg(all(feature = "decode", feature = "encode"))]
#[path = "codecs/main.rs"]
mod codecs;
+#[cfg(feature = "dsd")]
+#[path = "dsd_bounds.rs"]
+mod dsd_bounds;
+#[cfg(feature = "dsd")]
+#[path = "dsd_metadata.rs"]
+mod dsd_metadata;
+#[cfg(feature = "dsd")]
+#[path = "dsd_oracle.rs"]
+mod dsd_oracle;
#[cfg(all(feature = "flac-decode", feature = "flac-encode"))]
#[path = "flac_decode.rs"]
mod flac_decode;
diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml
index f82a4c14fe..9e4e079df3 100644
--- a/crates/automation/Cargo.toml
+++ b/crates/automation/Cargo.toml
@@ -25,12 +25,15 @@ ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"]
# The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`.
screen-testing = ["ui", "agents", "craft-ui/testing"]
# Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an
-# app's `-cli mcp` reads, and with `ui` the link host and the Agents page. The agent settings
-# build on every target without it.
-agents = ["dep:craft-ai-agents", "dep:craft-flags", "dep:craft-atomic", "dep:craft-host"]
+# app's `-cli mcp` reads and that CLI's live client (all `craft-control`'s, re-exported), and
+# with `ui` the link host and the Agents page. The agent settings build on every target without it.
+agents = ["craft-control/agents", "dep:craft-host"]
[dependencies]
craft-behavior = { workspace = true, optional = true }
+# The agents code without a UI toolkit (settings, the launcher's switch, the connection file, the
+# CLI's live client), re-exported by `agents` so every app shares one copy.
+craft-control = { workspace = true }
craft-keymap = { workspace = true, optional = true }
craft-theme = { workspace = true }
craft-ui = { workspace = true, optional = true }
@@ -42,9 +45,6 @@ serde_json = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
base64 = "0.22"
craft-platform = { workspace = true }
-craft-ai-agents = { workspace = true, optional = true }
-craft-atomic = { workspace = true, optional = true }
-craft-flags = { workspace = true, optional = true }
craft-host = { workspace = true, optional = true }
getrandom = "0.3"
hmac = "0.12"
diff --git a/crates/automation/README.md b/crates/automation/README.md
index 1c9ff22d4b..d82a01e5b5 100644
--- a/crates/automation/README.md
+++ b/crates/automation/README.md
@@ -8,7 +8,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch
| --- | --- |
| `actions` | Recorded actions (every target): `ActionList` of `Action`s and `ActionStep`s, `ActionsFile`, playback with `ActionPlayer` and `ActionRunner` under a `PlaybackBudget`, and `Recording`. The app keeps the command table. |
| `ui::actions` | `ActionsPanel` (every target): sets, actions and steps as a tree, include and dialog cells, rename (`start_rename`), drag to move, Button Mode, the footer and the menus (`ActionsPanelCommands`, `ActionsMenuFacts` and `panel_rows`, which leaves out the rows the host has no command for). It runs nothing; it reports `ActionsEvent`s. `ActionsPanelState` holds its view state. `ActionsWords` holds its words. |
-| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `-cli mcp` finds the open window by. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. |
+| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `-cli mcp` finds the open window by; the CLI's live client (`Live`, `LiveConfig`, `Route`). All of these are `craft_control::agents`, re-exported, so apps without the shared UI library use the same code. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. |
| `ui::agents` | `AgentsPage` (desktop, features `agents` and `ui`): the Agents page of Preferences, a custom page over the agent settings in the Preferences draft, with the link's status; the folder rows are `PathSetting`s. `AgentsWords` holds its words. |
| `args` | `ControlOptions`: the `--control `, `--control-token`, `--control-token-file` values and their `_CONTROL_*` environment fallbacks, checked the way the apps' command lines report them (usage errors exit 2). |
| `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. |
diff --git a/crates/automation/src/agents/connection.rs b/crates/automation/src/agents/connection.rs
deleted file mode 100644
index f34ee3c401..0000000000
--- a/crates/automation/src/agents/connection.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-//! The connection file: where an app's control server listens for agents.
-
-use std::net::{SocketAddr, TcpStream};
-use std::path::{Path, PathBuf};
-use std::time::Duration;
-
-use serde::{Deserialize, Serialize};
-
-use crate::AutomationError;
-
-/// The connection file in the app's settings folder, present while the app accepts agents.
-pub const CONNECTION_FILE: &str = "agent-connection.json";
-/// The token file the app keeps in its settings folder for agent connections.
-pub const TOKEN_FILE: &str = "agent-control.token";
-/// How long [`probe`] waits for a connection to be accepted.
-pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
-/// The version of the [`Connection`] file format.
-const CONNECTION_VERSION: u32 = 1;
-/// The largest connection file read; anything bigger is not one.
-const MAX_CONNECTION_BYTES: u64 = 1 << 20;
-
-/// What an app publishes in [`CONNECTION_FILE`]: `{"version", "pid", "port", "tokenFile", "app"}`.
-/// Holds no secret: the token stays in its own owner-only file.
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Connection {
- /// The file format's version (1).
- pub version: u32,
- /// The app's process id: only that process removes the file.
- pub pid: u32,
- /// The loopback port of the control server.
- pub port: u16,
- /// The file holding the token.
- pub token_file: PathBuf,
- /// The app's version, for diagnostics.
- pub app: String,
-}
-
-impl Connection {
- /// This process's connection on `port`, naming `app` (the app's version string).
- pub fn new(port: u16, token_file: PathBuf, app: impl Into) -> Self {
- Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() }
- }
-
- /// `127.0.0.1:`.
- pub fn addr(&self) -> String {
- format!("127.0.0.1:{}", self.port)
- }
-}
-
-fn io_error(path: &Path, e: impl std::fmt::Display) -> AutomationError {
- AutomationError::Io(format!("{}: {e}", path.display()))
-}
-
-/// Publishes `c` in `dir` (made if missing), written atomically so a reader never sees half a
-/// file.
-pub fn write_connection(dir: &Path, c: &Connection) -> Result<(), AutomationError> {
- std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?;
- let path = dir.join(CONNECTION_FILE);
- let text = serde_json::to_string_pretty(c).map_err(|e| io_error(&path, e))?;
- craft_atomic::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e))
-}
-
-/// The connection published in `dir`, if any. A file of another version, with port 0, or one
-/// that does not parse (invalid UTF-8 included) counts as none: the app rewrites it when it next
-/// starts listening. Anything but a regular file (a FIFO would block the read) or a file over
-/// 1 MiB is an error, and left alone.
-pub fn read_connection(dir: &Path) -> Result