Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M10.5: Text-based editing / transcripts

Brandon Thomasfc18a6962ef8
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index 9ec856fce..3fc73c92e 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -94,3 +94,14 @@ openly licensed and are not covered by the project licence; forks must remove or
| `docs/brand/artcraft-mark-black.svg` | ArtCraft team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), black) | ArtCraft trademark, all rights reserved; used with permission (not MIT/Apache) |
| `docs/brand/artcraft-mark.png` | ArtCraft team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft trademark, all rights reserved; used with permission (not MIT/Apache) |
| `docs/brand/artcraft-mark.svg` | ArtCraft team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft trademark, all rights reserved; used with permission (not MIT/Apache) |
+
+## Downloaded at runtime
+
+These files are never in the repository or the app bundle. FilmCraft downloads them into the
+per-user data directory (`<data dir>/models/<id>/`) only after the user confirms a dialog that shows
+the size, the source URL and the licence. Every file is pinned to a revision and checked against its
+SHA-256 (`crates/speech/src/models.rs`, `docs/transcripts.md`).
+
+| Asset | Author | Source | Licence |
+|---|---|---|---|
+| Whisper tiny / base / small speech-recognition weights (`model.safetensors`, `config.json`, `generation_config.json`, `tokenizer.json`) | OpenAI | `https://huggingface.co/openai/whisper-{tiny,base,small}` (revisions `169d4a43…`, `e37978b9…`, `973afd24…`); weights released with `https://github.com/openai/whisper` | MIT (weights and code, github.com/openai/whisper); the Hugging Face conversion is labelled Apache-2.0 |
diff --git a/Cargo.lock b/Cargo.lock
index 5caa45174..4a31195ce 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -121,6 +121,41 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common",
+ "generic-array",
+]
+
+[[package]]
+name = "aes"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+]
+
+[[package]]
+name = "aes-gcm"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
+dependencies = [
+ "aead",
+ "aes",
+ "cipher",
+ "ctr",
+ "ghash",
+ "subtle",
+]
+
[[package]]
name = "ahash"
version = "0.8.12"
@@ -440,12 +475,30 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+[[package]]
+name = "base16ct"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
+
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
[[package]]
name = "bit-set"
version = "0.8.0"
@@ -488,6 +541,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "block2"
version = "0.5.1"
@@ -545,6 +607,12 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "byteorder"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+
[[package]]
name = "byteorder-lite"
version = "0.1.0"
@@ -633,6 +701,45 @@ dependencies = [
"wayland-client",
]
+[[package]]
+name = "candle-core"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c15b675b80d994b2eadb20a4bbe434eabeb454eac3ee5e2b4cf6f147ee9be091"
+dependencies = [
+ "byteorder",
+ "float8",
+ "gemm",
+ "half",
+ "libm",
+ "memmap2",
+ "num-traits",
+ "num_cpus",
+ "rand 0.9.5",
+ "rand_distr",
+ "rayon",
+ "safetensors",
+ "thiserror 2.0.21",
+ "yoke",
+ "zip",
+]
+
+[[package]]
+name = "candle-nn"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3045fa9e7aef8567d209a27d56b692f60b96f4d0569f4c3011f8ca6715c65e03"
+dependencies = [
+ "candle-core",
+ "half",
+ "libc",
+ "num-traits",
+ "rayon",
+ "safetensors",
+ "serde",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "cc"
version = "1.5.1"
@@ -682,6 +789,30 @@ dependencies = [
"libc",
]
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+]
+
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead",
+ "chacha20",
+ "cipher",
+ "poly1305",
+ "zeroize",
+]
+
[[package]]
name = "chrono"
version = "0.4.45"
@@ -694,6 +825,17 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common",
+ "inout",
+ "zeroize",
+]
+
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -748,6 +890,12 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "const-oid"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
+
[[package]]
name = "core-foundation"
version = "0.9.4"
@@ -758,6 +906,16 @@ dependencies = [
"libc",
]
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
@@ -771,7 +929,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
dependencies = [
"bitflags 1.3.2",
- "core-foundation",
+ "core-foundation 0.9.4",
"core-graphics-types",
"foreign-types",
"libc",
@@ -784,7 +942,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
dependencies = [
"bitflags 1.3.2",
- "core-foundation",
+ "core-foundation 0.9.4",
"libc",
]
@@ -834,6 +992,15 @@ dependencies = [
"windows 0.54.0",
]
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -883,12 +1050,70 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+[[package]]
+name = "crypto-bigint"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
+dependencies = [
+ "generic-array",
+ "rand_core 0.6.4",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "ctr"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "cursor-icon"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "curve25519-dalek-derive",
+ "digest",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "darling"
version = "0.24.1"
@@ -929,6 +1154,29 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
+[[package]]
+name = "der"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
+dependencies = [
+ "const-oid",
+ "pem-rfc7468",
+ "zeroize",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "const-oid",
+ "crypto-common",
+ "subtle",
+]
+
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -983,6 +1231,36 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+[[package]]
+name = "dyn-stack"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c4713e43e2886ba72b8271aa66c93d722116acf7a75555cce11dcde84388fe8"
+dependencies = [
+ "bytemuck",
+ "dyn-stack-macros",
+]
+
+[[package]]
+name = "dyn-stack-macros"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9"
+
+[[package]]
+name = "ecdsa"
+version = "0.16.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
+dependencies = [
+ "der",
+ "digest",
+ "elliptic-curve",
+ "rfc6979",
+ "signature",
+ "spki",
+]
+
[[package]]
name = "ecolor"
version = "0.36.2"
@@ -993,6 +1271,30 @@ dependencies = [
"emath",
]
+[[package]]
+name = "ed25519"
+version = "2.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
+dependencies = [
+ "pkcs8",
+ "signature",
+]
+
+[[package]]
+name = "ed25519-dalek"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
+dependencies = [
+ "curve25519-dalek",
+ "ed25519",
+ "serde",
+ "sha2",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "eframe"
version = "0.36.2"
@@ -1127,6 +1429,27 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
+[[package]]
+name = "elliptic-curve"
+version = "0.13.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
+dependencies = [
+ "base16ct",
+ "crypto-bigint",
+ "digest",
+ "ff",
+ "generic-array",
+ "group",
+ "hkdf",
+ "pem-rfc7468",
+ "pkcs8",
+ "rand_core 0.6.4",
+ "sec1",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "emath"
version = "0.36.2"
@@ -1156,6 +1479,18 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
+[[package]]
+name = "enum-as-inner"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
+dependencies = [
+ "heck 0.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "enumflags2"
version = "0.7.12"
@@ -1292,6 +1627,22 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
+[[package]]
+name = "ff"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
+dependencies = [
+ "rand_core 0.6.4",
+ "subtle",
+]
+
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "field-offset"
version = "0.3.6"
@@ -1343,7 +1694,7 @@ dependencies = [
name = "filmcraft-automation"
version = "0.1.0"
dependencies = [
- "base64",
+ "base64 0.22.1",
"filmcraft-engine",
"filmcraft-time",
"image",
@@ -1448,6 +1799,7 @@ dependencies = [
"filmcraft-project",
"filmcraft-time",
"proptest",
+ "serde_json",
"thiserror 2.0.21",
]
@@ -1468,6 +1820,7 @@ dependencies = [
"filmcraft-media",
"filmcraft-project",
"filmcraft-render",
+ "filmcraft-speech",
"filmcraft-testkit",
"filmcraft-text",
"filmcraft-time",
@@ -1697,6 +2050,24 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "filmcraft-speech"
+version = "0.1.0"
+dependencies = [
+ "candle-core",
+ "candle-nn",
+ "filmcraft-project",
+ "filmcraft-time",
+ "rayon",
+ "rustls",
+ "rustls-rustcrypto",
+ "serde",
+ "serde_json",
+ "sha2",
+ "thiserror 2.0.21",
+ "ureq",
+]
+
[[package]]
name = "filmcraft-testkit"
version = "0.1.0"
@@ -1803,6 +2174,18 @@ dependencies = [
"zlib-rs",
]
+[[package]]
+name = "float8"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "719a903cc23e4a89e87962c2a80fdb45cdaad0983a89bd150bb57b4c8571a7d5"
+dependencies = [
+ "half",
+ "num-traits",
+ "rand 0.9.5",
+ "rand_distr",
+]
+
[[package]]
name = "fnv"
version = "1.0.7"
@@ -2010,6 +2393,136 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "gemm"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa0673db364b12263d103b68337a68fbecc541d6f6b61ba72fe438654709eacb"
+dependencies = [
+ "dyn-stack",
+ "gemm-c32",
+ "gemm-c64",
+ "gemm-common",
+ "gemm-f16",
+ "gemm-f32",
+ "gemm-f64",
+ "num-complex",
+ "num-traits",
+ "paste",
+ "raw-cpuid",
+ "seq-macro",
+]
+
+[[package]]
+name = "gemm-c32"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "086936dbdcb99e37aad81d320f98f670e53c1e55a98bee70573e83f95beb128c"
+dependencies = [
+ "dyn-stack",
+ "gemm-common",
+ "num-complex",
+ "num-traits",
+ "paste",
+ "raw-cpuid",
+ "seq-macro",
+]
+
+[[package]]
+name = "gemm-c64"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20c8aeeeec425959bda4d9827664029ba1501a90a0d1e6228e48bef741db3a3f"
+dependencies = [
+ "dyn-stack",
+ "gemm-common",
+ "num-complex",
+ "num-traits",
+ "paste",
+ "raw-cpuid",
+ "seq-macro",
+]
+
+[[package]]
+name = "gemm-common"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88027625910cc9b1085aaaa1c4bc46bb3a36aad323452b33c25b5e4e7c8e2a3e"
+dependencies = [
+ "bytemuck",
+ "dyn-stack",
+ "half",
+ "libm",
+ "num-complex",
+ "num-traits",
+ "once_cell",
+ "paste",
+ "pulp",
+ "raw-cpuid",
+ "rayon",
+ "seq-macro",
+ "sysctl",
+]
+
+[[package]]
+name = "gemm-f16"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3df7a55202e6cd6739d82ae3399c8e0c7e1402859b30e4cb780e61525d9486e"
+dependencies = [
+ "dyn-stack",
+ "gemm-common",
+ "gemm-f32",
+ "half",
+ "num-complex",
+ "num-traits",
+ "paste",
+ "raw-cpuid",
+ "rayon",
+ "seq-macro",
+]
+
+[[package]]
+name = "gemm-f32"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02e0b8c9da1fbec6e3e3ab2ce6bc259ef18eb5f6f0d3e4edf54b75f9fd41a81c"
+dependencies = [
+ "dyn-stack",
+ "gemm-common",
+ "num-complex",
+ "num-traits",
+ "paste",
+ "raw-cpuid",
+ "seq-macro",
+]
+
+[[package]]
+name = "gemm-f64"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "056131e8f2a521bfab322f804ccd652520c79700d81209e9d9275bbdecaadc6a"
+dependencies = [
+ "dyn-stack",
+ "gemm-common",
+ "num-complex",
+ "num-traits",
+ "paste",
+ "raw-cpuid",
+ "seq-macro",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+ "zeroize",
+]
+
[[package]]
name = "gethostname"
version = "1.1.0"
@@ -2020,6 +2533,17 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
[[package]]
name = "getrandom"
version = "0.3.4"
@@ -2043,6 +2567,16 @@ dependencies = [
"r-efi 6.0.0",
]
+[[package]]
+name = "ghash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
+dependencies = [
+ "opaque-debug",
+ "polyval",
+]
+
[[package]]
name = "gif"
version = "0.14.2"
@@ -2262,6 +2796,17 @@ dependencies = [
"windows 0.62.2",
]
+[[package]]
+name = "group"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
+dependencies = [
+ "ff",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
[[package]]
name = "gtk"
version = "0.18.2"
@@ -2329,9 +2874,12 @@ version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
+ "bytemuck",
"cfg-if",
"crunchy",
"num-traits",
+ "rand 0.9.5",
+ "rand_distr",
"zerocopy",
]
@@ -2356,6 +2904,8 @@ dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
+ "serde",
+ "serde_core",
]
[[package]]
@@ -2391,6 +2941,40 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hkdf"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
+dependencies = [
+ "hmac",
+]
+
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest",
+]
+
+[[package]]
+name = "http"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
[[package]]
name = "iana-time-zone"
version = "0.1.65"
@@ -2462,6 +3046,15 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "itertools"
version = "0.15.0"
@@ -2626,6 +3219,9 @@ name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+dependencies = [
+ "spin",
+]
[[package]]
name = "libc"
@@ -2722,6 +3318,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
dependencies = [
"libc",
+ "stable_deref_trait",
]
[[package]]
@@ -2875,6 +3472,32 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
+[[package]]
+name = "num-bigint-dig"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
+dependencies = [
+ "lazy_static",
+ "libm",
+ "num-integer",
+ "num-iter",
+ "num-traits",
+ "rand 0.8.8",
+ "smallvec",
+ "zeroize",
+]
+
+[[package]]
+name = "num-complex"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
+dependencies = [
+ "bytemuck",
+ "num-traits",
+]
+
[[package]]
name = "num-derive"
version = "0.4.2"
@@ -2886,6 +3509,25 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-iter"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2896,6 +3538,16 @@ dependencies = [
"libm",
]
+[[package]]
+name = "num_cpus"
+version = "1.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
+dependencies = [
+ "hermit-abi",
+ "libc",
+]
+
[[package]]
name = "num_enum"
version = "0.7.6"
@@ -3272,6 +3924,18 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
[[package]]
name = "orbclient"
version = "0.3.55"
@@ -3301,6 +3965,30 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "p256"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
+dependencies = [
+ "ecdsa",
+ "elliptic-curve",
+ "primeorder",
+ "sha2",
+]
+
+[[package]]
+name = "p384"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"
+dependencies = [
+ "ecdsa",
+ "elliptic-curve",
+ "primeorder",
+ "sha2",
+]
+
[[package]]
name = "pango"
version = "0.18.3"
@@ -3355,12 +4043,27 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
[[package]]
name = "pastey"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
+[[package]]
+name = "pem-rfc7468"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
+dependencies = [
+ "base64ct",
+]
+
[[package]]
name = "peniko"
version = "0.6.1"
@@ -3460,6 +4163,38 @@ dependencies = [
"futures-io",
]
+[[package]]
+name = "pkcs1"
+version = "0.7.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
+dependencies = [
+ "der",
+ "pkcs8",
+ "spki",
+]
+
+[[package]]
+name = "pkcs5"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6"
+dependencies = [
+ "der",
+ "spki",
+]
+
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der",
+ "pkcs5",
+ "spki",
+]
+
[[package]]
name = "pkg-config"
version = "0.3.34"
@@ -3511,6 +4246,17 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336"
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures",
+ "opaque-debug",
+ "universal-hash",
+]
+
[[package]]
name = "polycool"
version = "0.4.0"
@@ -3520,6 +4266,18 @@ dependencies = [
"arrayvec",
]
+[[package]]
+name = "polyval"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "opaque-debug",
+ "universal-hash",
+]
+
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -3550,6 +4308,15 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
+[[package]]
+name = "primeorder"
+version = "0.13.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
+dependencies = [
+ "elliptic-curve",
+]
+
[[package]]
name = "proc-macro-crate"
version = "1.3.1"
@@ -3628,8 +4395,8 @@ dependencies = [
"bit-vec 0.8.0",
"bitflags 2.13.2",
"num-traits",
- "rand",
- "rand_chacha",
+ "rand 0.9.5",
+ "rand_chacha 0.9.0",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
@@ -3637,6 +4404,29 @@ dependencies = [
"unarray",
]
+[[package]]
+name = "pulp"
+version = "0.22.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a"
+dependencies = [
+ "bytemuck",
+ "cfg-if",
+ "libm",
+ "num-complex",
+ "paste",
+ "pulp-wasm-simd-flag",
+ "raw-cpuid",
+ "reborrow",
+ "version_check",
+]
+
+[[package]]
+name = "pulp-wasm-simd-flag"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740"
+
[[package]]
name = "pxfm"
version = "0.1.30"
@@ -3685,14 +4475,34 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+[[package]]
+name = "rand"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
+dependencies = [
+ "rand_chacha 0.3.1",
+ "rand_core 0.6.4",
+]
+
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
- "rand_chacha",
- "rand_core",
+ "rand_chacha 0.9.0",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.6.4",
]
[[package]]
@@ -3702,7 +4512,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
- "rand_core",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
]
[[package]]
@@ -3714,13 +4533,23 @@ dependencies = [
"getrandom 0.3.4",
]
+[[package]]
+name = "rand_distr"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463"
+dependencies = [
+ "num-traits",
+ "rand 0.9.5",
+]
+
[[package]]
name = "rand_xorshift"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
dependencies = [
- "rand_core",
+ "rand_core 0.9.5",
]
[[package]]
@@ -3729,6 +4558,15 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
+[[package]]
+name = "raw-cpuid"
+version = "11.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -3778,6 +4616,12 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "reborrow"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"
+
[[package]]
name = "redox_syscall"
version = "0.4.1"
@@ -3837,6 +4681,16 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+[[package]]
+name = "rfc6979"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
+dependencies = [
+ "hmac",
+ "subtle",
+]
+
[[package]]
name = "rfd"
version = "0.17.2"
@@ -3864,6 +4718,20 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "rmcp"
version = "3.5.0"
@@ -3908,6 +4776,27 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "rsa"
+version = "0.9.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
+dependencies = [
+ "const-oid",
+ "digest",
+ "num-bigint-dig",
+ "num-integer",
+ "num-traits",
+ "pkcs1",
+ "pkcs8",
+ "rand_core 0.6.4",
+ "sha2",
+ "signature",
+ "spki",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -3955,6 +4844,120 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "rustls"
+version = "0.23.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
+dependencies = [
+ "log",
+ "once_cell",
+ "rustls-pki-types",
+ "rustls-webpki 0.103.15",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-platform-verifier"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
+dependencies = [
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "jni 0.22.4",
+ "log",
+ "once_cell",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-platform-verifier-android",
+ "rustls-webpki 0.103.15",
+ "security-framework",
+ "security-framework-sys",
+ "webpki-root-certs",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls-platform-verifier-android"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
+
+[[package]]
+name = "rustls-rustcrypto"
+version = "0.0.2-alpha"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f12052947763ab8515f753315357599e9b0b4dab3b8ba15f30f725fe6d025557"
+dependencies = [
+ "aead",
+ "aes-gcm",
+ "chacha20poly1305",
+ "crypto-common",
+ "der",
+ "digest",
+ "ecdsa",
+ "ed25519-dalek",
+ "hmac",
+ "p256",
+ "p384",
+ "paste",
+ "pkcs8",
+ "rand_core 0.6.4",
+ "rsa",
+ "rustls",
+ "rustls-pki-types",
+ "rustls-webpki 0.102.8",
+ "sec1",
+ "sha2",
+ "signature",
+ "x25519-dalek",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.102.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
[[package]]
name = "rustversion"
version = "1.0.23"
@@ -3973,6 +4976,17 @@ dependencies = [
"wait-timeout",
]
+[[package]]
+name = "safetensors"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "675656c1eabb620b921efea4f9199f97fc86e36dd6ffd1fbbe48d0f59a4987f5"
+dependencies = [
+ "hashbrown 0.16.1",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "same-file"
version = "1.0.6"
@@ -3982,6 +4996,15 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "schemars"
version = "1.2.2"
@@ -4020,6 +5043,43 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "sec1"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
+dependencies = [
+ "base16ct",
+ "der",
+ "generic-array",
+ "pkcs8",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags 2.13.2",
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "self_cell"
version = "1.3.0"
@@ -4032,6 +5092,12 @@ version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+[[package]]
+name = "seq-macro"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
+
[[package]]
name = "serde"
version = "1.0.229"
@@ -4115,6 +5181,17 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
[[package]]
name = "shlex"
version = "2.0.1"
@@ -4131,6 +5208,16 @@ dependencies = [
"libc",
]
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "digest",
+ "rand_core 0.6.4",
+]
+
[[package]]
name = "simd-adler32"
version = "0.3.10"
@@ -4272,6 +5359,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "spin"
+version = "0.9.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
+
[[package]]
name = "spirv"
version = "0.4.0+sdk-1.4.341.0"
@@ -4281,6 +5374,22 @@ dependencies = [
"bitflags 2.13.2",
]
+[[package]]
+name = "spki"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
[[package]]
name = "static_assertions"
version = "1.1.0"
@@ -4293,6 +5402,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
[[package]]
name = "symphonia"
version = "0.5.5"
@@ -4483,6 +5598,31 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "synstructure"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "sysctl"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc"
+dependencies = [
+ "bitflags 2.13.2",
+ "byteorder",
+ "enum-as-inner",
+ "libc",
+ "thiserror 1.0.69",
+ "walkdir",
+]
+
[[package]]
name = "system-deps"
version = "6.2.2"
@@ -4747,6 +5887,18 @@ dependencies = [
"rustc-hash 2.1.3",
]
+[[package]]
+name = "typed-path"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
[[package]]
name = "uds_windows"
version = "1.2.1"
@@ -4800,6 +5952,56 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common",
+ "subtle",
+]
+
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "ureq"
+version = "3.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"
+dependencies = [
+ "base64 0.23.1",
+ "log",
+ "percent-encoding",
+ "rustls",
+ "rustls-pki-types",
+ "rustls-platform-verifier",
+ "ureq-proto",
+ "utf8-zero",
+]
+
+[[package]]
+name = "ureq-proto"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be"
+dependencies = [
+ "base64 0.23.1",
+ "http",
+ "httparse",
+ "log",
+]
+
+[[package]]
+name = "utf8-zero"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
+
[[package]]
name = "uuid"
version = "1.26.1"
@@ -5096,6 +6298,15 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "webpki-root-certs"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "weezl"
version = "0.1.12"
@@ -5701,7 +6912,7 @@ dependencies = [
"calloop 0.13.0",
"cfg_aliases",
"concurrent-queue",
- "core-foundation",
+ "core-foundation 0.9.4",
"core-graphics",
"cursor-icon",
"dpi",
@@ -5793,6 +7004,17 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek",
+ "rand_core 0.6.4",
+ "zeroize",
+]
+
[[package]]
name = "xcursor"
version = "0.3.11"
@@ -5832,6 +7054,29 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
[[package]]
name = "zbus"
version = "5.19.0"
@@ -5958,6 +7203,59 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+dependencies = [
+ "zeroize_derive",
+]
+
+[[package]]
+name = "zeroize_derive"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zip"
+version = "7.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c42e33efc22a0650c311c2ef19115ce232583abbe80850bc8b66509ebef02de0"
+dependencies = [
+ "crc32fast",
+ "indexmap",
+ "memchr",
+ "typed-path",
+]
+
[[package]]
name = "zlib-rs"
version = "0.6.8"
diff --git a/Cargo.toml b/Cargo.toml
index 71799d381..fa73ed112 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -36,6 +36,7 @@ filmcraft-edit = { path = "crates/edit" }
filmcraft-interchange = { path = "crates/interchange" }
filmcraft-text = { path = "crates/text" }
filmcraft-captions = { path = "crates/captions" }
+filmcraft-speech = { path = "crates/speech" }
filmcraft-render = { path = "crates/render" }
filmcraft-gpu = { path = "crates/gpu" }
filmcraft-export = { path = "crates/export" }
diff --git a/apps/filmcraft-cli/Cargo.toml b/apps/filmcraft-cli/Cargo.toml
index 3fd8641b8..7d530e79b 100644
--- a/apps/filmcraft-cli/Cargo.toml
+++ b/apps/filmcraft-cli/Cargo.toml
@@ -12,6 +12,11 @@ workspace = true
name = "filmcraft-cli"
path = "src/main.rs"
+[features]
+default = []
+# Speech-to-text (Text panel ▸ Transcribe) with Whisper on the CPU, and model downloads.
+whisper = ["filmcraft-engine/whisper", "filmcraft-engine/speech-download"]
+
[dependencies]
filmcraft-engine = { workspace = true }
filmcraft-media = { workspace = true }
diff --git a/apps/filmcraft/Cargo.toml b/apps/filmcraft/Cargo.toml
index f99a57f95..bbf8b96f7 100644
--- a/apps/filmcraft/Cargo.toml
+++ b/apps/filmcraft/Cargo.toml
@@ -9,6 +9,11 @@ default-run = "filmcraft"
[lints]
workspace = true
+[features]
+default = []
+# Speech-to-text (Text panel ▸ Transcribe) with Whisper on the CPU, and model downloads.
+whisper = ["filmcraft-engine/whisper", "filmcraft-engine/speech-download"]
+
[dependencies]
filmcraft-engine = { workspace = true }
filmcraft-ui-egui = { workspace = true }
diff --git a/crates/edit/Cargo.toml b/crates/edit/Cargo.toml
index 558316110..fcecc05a3 100644
--- a/crates/edit/Cargo.toml
+++ b/crates/edit/Cargo.toml
@@ -17,3 +17,4 @@ thiserror = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
filmcraft-media = { workspace = true }
+serde_json = { workspace = true }
diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs
index bf6de640d..8407c4080 100644
--- a/crates/edit/src/lib.rs
+++ b/crates/edit/src/lib.rs
@@ -17,6 +17,7 @@
pub mod captions;
pub mod multicam;
+pub mod transcript;
use std::collections::HashMap;
diff --git a/crates/edit/src/transcript.rs b/crates/edit/src/transcript.rs
new file mode 100644
index 000000000..ff7c4634c
--- /dev/null
+++ b/crates/edit/src/transcript.rs
@@ -0,0 +1,425 @@
+//! Text-based editing: the sequence transcript and the edits made through it.
+//!
+//! Clip transcripts (`filmcraft_project::Transcript`) hold words in **media time**. The sequence
+//! transcript ([`sequence_words`]) maps them through the audio track items that play them:
+//!
+//! - audio tracks are read top first (A1, A2…); a word is taken from the first track whose
+//! transcribed clip covers the word's midpoint, so a dialogue clip duplicated on two tracks (or a
+//! stereo pair split over two mono tracks) reads once;
+//! - a word belongs to a clip when its midpoint, mapped through the clip's speed, falls inside the
+//! clip; its timeline bounds are clamped to the clip, so a word cut by an edit is shown cut;
+//! - disabled clips, reversed clips and frame holds contribute no words (they don't play speech).
+//!
+//! Text edits turn word ranges into timeline ranges ([`word_range`]) snapped outward to frames, then
+//! reuse the ordinary [`crate::extract`] / [`crate::lift`] edits. Pause and filler-word removal
+//! ([`find_pauses`], [`find_fillers`]) produce many ranges that [`ripple_delete_ranges`] removes in
+//! one pass, right to left. Captions come from [`caption_blocks`].
+
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+use filmcraft_project::{Caption, ClipId, ItemId, Sequence, TrackId, Transcript};
+use filmcraft_time::{FrameRate, TICKS_PER_SECOND, Tick, TimeRange};
+
+use crate::EditCtx;
+
+/// A word of the sequence transcript.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SeqWord {
+ pub text: String,
+ /// Sequence time.
+ pub start: Tick,
+ pub end: Tick,
+ /// The track item it is heard through and that item's media.
+ pub clip: ClipId,
+ pub item: ItemId,
+ /// Index of the word in the media item's transcript.
+ pub index: usize,
+ /// Audio track index (0 = A1).
+ pub track: usize,
+ pub speaker: Option<String>,
+ pub confidence: f32,
+}
+
+impl SeqWord {
+ pub fn normalized(&self) -> String {
+ filmcraft_project::transcript::normalize_word(&self.text)
+ }
+ pub fn range(&self) -> TimeRange {
+ TimeRange::from_bounds(self.start, self.end.max(self.start))
+ }
+}
+
+/// Transcripts by media item (as in `Project::transcripts`).
+pub type Transcripts = BTreeMap<ItemId, Arc<Transcript>>;
+
+fn ticks(t: f64) -> Tick {
+ Tick(t.round() as i64)
+}
+
+/// The sequence transcript: words of every transcribed clip on the audio tracks, in sequence
+/// time order (see the module docs for the rules).
+pub fn sequence_words(seq: &Sequence, transcripts: &Transcripts) -> Vec<SeqWord> {
+ let mut out: Vec<SeqWord> = Vec::new();
+ // timeline ranges already served by a higher track's transcribed clips
+ let mut claimed: Vec<TimeRange> = Vec::new();
+ for (ti, track) in seq.audio_tracks.iter().enumerate() {
+ let mut mine = Vec::new();
+ for it in &track.items {
+ if !it.enabled || it.reverse || it.frame_hold.is_some() || it.speed <= 0.0 {
+ continue;
+ }
+ let Some(tr) = transcripts.get(&it.item) else { continue };
+ mine.push(it.range());
+ let speed = it.speed;
+ let media_end = it.source_in + ticks(it.duration.0 as f64 * speed);
+ let to_tl = |m: Tick| it.start + ticks((m - it.source_in).0 as f64 / speed);
+ for wi in tr.words_in(TimeRange::from_bounds(it.source_in, media_end.max(it.source_in))) {
+ let w = &tr.words[wi];
+ let (a, b) = (to_tl(w.start), to_tl(w.end.max(w.start)));
+ let mid = Tick(a.0 + (b.0 - a.0) / 2);
+ if mid < it.start || mid >= it.end() || claimed.iter().any(|r| r.contains(mid)) {
+ continue;
+ }
+ out.push(SeqWord {
+ text: w.text.clone(),
+ start: a.max(it.start),
+ end: b.min(it.end()).max(a.max(it.start)),
+ clip: it.id,
+ item: it.item,
+ index: wi,
+ track: ti,
+ speaker: tr.speaker_name(w),
+ confidence: w.confidence,
+ });
+ }
+ }
+ claimed.extend(mine);
+ }
+ out.sort_by_key(|w| (w.start, w.track));
+ out
+}
+
+/// Index of the word being spoken at `t` (the last word starting at or before `t` whose end is
+/// after `t`).
+pub fn word_at(words: &[SeqWord], t: Tick) -> Option<usize> {
+ let i = words.partition_point(|w| w.start <= t).checked_sub(1)?;
+ (t < words[i].end).then_some(i)
+}
+
+/// Paragraphs (Text panel segments): runs of words split where the speaker changes or at a pause
+/// of at least `gap`.
+pub fn paragraphs(words: &[SeqWord], gap: Tick) -> Vec<std::ops::Range<usize>> {
+ let mut out = Vec::new();
+ let mut a = 0;
+ for i in 1..=words.len() {
+ if i == words.len() || words[i].speaker != words[i - 1].speaker || words[i].start - words[i - 1].end >= gap {
+ if a < i {
+ out.push(a..i);
+ }
+ a = i;
+ }
+ }
+ out
+}
+
+/// Matches of `query` (one or more words, case and punctuation ignored; the last query word may be
+/// a prefix) as word index ranges.
+pub fn search(words: &[SeqWord], query: &str) -> Vec<std::ops::Range<usize>> {
+ let q: Vec<String> = query.split_whitespace().map(filmcraft_project::transcript::normalize_word).filter(|s| !s.is_empty()).collect();
+ if q.is_empty() {
+ return Vec::new();
+ }
+ let norm: Vec<String> = words.iter().map(SeqWord::normalized).collect();
+ let mut out = Vec::new();
+ for i in 0..norm.len().saturating_sub(q.len() - 1) {
+ let ok = q.iter().enumerate().all(|(k, qw)| if k + 1 == q.len() { norm[i + k].starts_with(qw.as_str()) } else { norm[i + k] == *qw });
+ if ok {
+ out.push(i..i + q.len());
+ }
+ }
+ out
+}
+
+/// Timeline range of words `a..=b`, snapped outward to frames.
+pub fn word_range(words: &[SeqWord], a: usize, b: usize, rate: FrameRate) -> Option<TimeRange> {
+ let (a, b) = (a.min(b), a.max(b));
+ let (s, e) = (words.get(a)?.start, words.get(b)?.end);
+ let s = rate.snap(s);
+ let mut e2 = rate.snap(e);
+ if e2 < e || e2 <= s {
+ e2 += rate.frame_duration();
+ }
+ Some(TimeRange::from_bounds(s, e2))
+}
+
+/// Media range of words `a..=b` of a clip transcript, snapped outward to the media's frames (for
+/// Source-monitor In/Out from a text selection).
+pub fn media_word_range(t: &Transcript, a: usize, b: usize, rate: FrameRate) -> Option<TimeRange> {
+ let (a, b) = (a.min(b), a.max(b));
+ let (s, e) = (t.words.get(a)?.start, t.words.get(b)?.end);
+ let s = rate.snap(s);
+ let mut e2 = rate.snap(e);
+ if e2 < e || e2 <= s {
+ e2 += rate.frame_duration();
+ }
+ Some(TimeRange::from_bounds(s, e2))
+}
+
+/// Pauses between consecutive words of at least `min`, as the ranges to remove: each keeps `keep`
+/// of silence next to both words and is snapped inward to frames (pauses shorter than one frame
+/// after that are skipped).
+pub fn find_pauses(words: &[SeqWord], min: Tick, keep: Tick, rate: FrameRate) -> Vec<TimeRange> {
+ let mut out = Vec::new();
+ for p in words.windows(2) {
+ let (a, b) = (p[0].end, p[1].start);
+ if b - a < min || b <= a {
+ continue;
+ }
+ let s = a + keep;
+ let e = b - keep;
+ let mut s2 = rate.snap(s);
+ if s2 < s {
+ s2 += rate.frame_duration();
+ }
+ let e2 = rate.snap(e);
+ if e2 > s2 {
+ out.push(TimeRange::from_bounds(s2, e2));
+ }
+ }
+ out
+}
+
+/// The default filler words and phrases (configurable in preferences and per command).
+pub const DEFAULT_FILLERS: &[&str] = &["um", "uh", "umm", "uhm", "erm", "er", "ah", "hmm", "mm", "mhm"];
+
+/// Filler words: word index ranges matching one of `fillers` (each a word or a phrase such as
+/// "you know"; case and punctuation ignored).
+pub fn find_fillers(words: &[SeqWord], fillers: &[String]) -> Vec<std::ops::Range<usize>> {
+ let norm: Vec<String> = words.iter().map(SeqWord::normalized).collect();
+ let mut phrases: Vec<Vec<String>> = fillers
+ .iter()
+ .map(|f| f.split_whitespace().map(filmcraft_project::transcript::normalize_word).filter(|s| !s.is_empty()).collect::<Vec<_>>())
+ .filter(|p| !p.is_empty())
+ .collect();
+ // longest phrases first, so "you know" wins over a lone "you"
+ phrases.sort_by_key(|p| std::cmp::Reverse(p.len()));
+ let mut out = Vec::new();
+ let mut i = 0;
+ while i < norm.len() {
+ let hit = phrases.iter().find(|p| i + p.len() <= norm.len() && p.iter().enumerate().all(|(k, w)| norm[i + k] == *w));
+ match hit {
+ Some(p) => {
+ out.push(i..i + p.len());
+ i += p.len();
+ }
+ None => i += 1,
+ }
+ }
+ out
+}
+
+/// Timeline ranges removing the filler words `hits`: each word range snapped to the nearest frames
+/// (never into the neighbouring words' frames).
+pub fn filler_ranges(words: &[SeqWord], hits: &[std::ops::Range<usize>], rate: FrameRate) -> Vec<TimeRange> {
+ let mut out = Vec::new();
+ for h in hits {
+ let (a, b) = (h.start, h.end - 1);
+ let mut s = rate.snap_nearest(words[a].start);
+ let mut e = rate.snap_nearest(words[b].end);
+ if a > 0 && s < words[a - 1].end {
+ s = rate.snap(words[a - 1].end) + rate.frame_duration();
+ }
+ if let Some(n) = words.get(b + 1)
+ && e > n.start
+ {
+ e = rate.snap(n.start);
+ }
+ if e > s {
+ out.push(TimeRange::from_bounds(s, e));
+ }
+ }
+ out
+}
+
+/// Sort and merge ranges (overlapping or touching).
+pub fn merge_ranges(mut r: Vec<TimeRange>) -> Vec<TimeRange> {
+ r.sort_by_key(|x| x.start);
+ let mut out: Vec<TimeRange> = Vec::new();
+ for x in r {
+ match out.last_mut() {
+ Some(l) if x.start <= l.end() => *l = TimeRange::from_bounds(l.start, l.end().max(x.end())),
+ _ => out.push(x),
+ }
+ }
+ out
+}
+
+/// Ripple-delete every range on every unlocked track (and sync-locked caption tracks), right to
+/// left so earlier ranges keep their positions. Returns the total time removed.
+pub fn ripple_delete_ranges(seq: &mut Sequence, ranges: Vec<TimeRange>, ctx: &mut EditCtx) -> Tick {
+ let tracks: Vec<TrackId> = seq.all_tracks().filter(|t| !t.locked).map(|t| t.id).collect();
+ let mut total = Tick::ZERO;
+ for r in merge_ranges(ranges).into_iter().rev() {
+ if r.duration <= Tick::ZERO {
+ continue;
+ }
+ crate::extract(seq, &tracks, r, ctx);
+ total += r.duration;
+ }
+ total
+}
+
+/// Rules for Create Captions from a transcript (Premiere's dialog defaults).
+#[derive(Clone, Debug, PartialEq)]
+pub struct CaptionRules {
+ /// Maximum characters per line.
+ pub max_chars: usize,
+ /// Lines per caption (1 = single, 2 = double).
+ pub lines: usize,
+ /// Minimum caption duration; a short caption is extended into the silence after it, never
+ /// over the next one.
+ pub min_duration: Tick,
+ /// Longest caption.
+ pub max_duration: Tick,
+ /// Frames left empty between consecutive captions.
+ pub gap_frames: i64,
+ /// A pause at least this long starts a new caption.
+ pub break_pause: Tick,
+}
+
+impl Default for CaptionRules {
+ fn default() -> Self {
+ Self {
+ max_chars: 42,
+ lines: 2,
+ min_duration: Tick(TICKS_PER_SECOND),
+ max_duration: Tick(7 * TICKS_PER_SECOND),
+ gap_frames: 0,
+ break_pause: Tick(TICKS_PER_SECOND),
+ }
+ }
+}
+
+/// A caption block made from words.
+#[derive(Clone, Debug, PartialEq)]
+pub struct CaptionBlock {
+ pub start: Tick,
+ pub end: Tick,
+ /// Lines joined by `\n`.
+ pub text: String,
+ pub speaker: Option<String>,
+ /// The word index range it shows.
+ pub words: std::ops::Range<usize>,
+}
+
+/// Lay words out as caption blocks: words fill lines of at most `max_chars` (a longer single word
+/// gets a line of its own) and blocks of `lines` lines; a new block starts at a speaker change,
+/// at a pause of `break_pause`, after `max_duration`, or after sentence-ending punctuation once the
+/// block is past half full. Times are snapped to frames, blocks never overlap and keep
+/// `gap_frames` between them.
+pub fn caption_blocks(words: &[SeqWord], rules: &CaptionRules, rate: FrameRate) -> Vec<CaptionBlock> {
+ let max_chars = rules.max_chars.max(1);
+ let max_lines = rules.lines.max(1);
+ let cap_chars = max_chars * max_lines;
+ let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
+ let mut a = 0;
+ let mut lines: Vec<usize> = vec![0];
+ for i in 0..words.len() {
+ let w = &words[i];
+ let len = w.text.chars().count();
+ if i > a {
+ let prev = &words[i - 1];
+ let cur = *lines.last().unwrap_or(&0);
+ let fits_line = cur + 1 + len <= max_chars;
+ let fits = fits_line || lines.len() < max_lines;
+ let used: usize = lines.iter().sum::<usize>() + lines.len() - 1;
+ let sentence_end = prev.text.ends_with(['.', '?', '!']) && used * 2 >= cap_chars;
+ let brk =
+ !fits || w.speaker != prev.speaker || w.start - prev.end >= rules.break_pause || w.end - words[a].start > rules.max_duration || sentence_end;
+ if brk {
+ groups.push(a..i);
+ a = i;
+ lines = vec![len];
+ continue;
+ }
+ if fits_line {
+ *lines.last_mut().expect("non-empty") += 1 + len;
+ } else {
+ lines.push(len);
+ }
+ } else {
+ lines = vec![len];
+ }
+ }
+ if a < words.len() {
+ groups.push(a..words.len());
+ }
+ // text, frame-snapped times
+ let fd = rate.frame_duration();
+ let gap = Tick(fd.0 * rules.gap_frames.max(0));
+ let mut out: Vec<CaptionBlock> = Vec::new();
+ for g in groups {
+ let mut text_lines: Vec<String> = vec![String::new()];
+ for w in &words[g.clone()] {
+ let l = text_lines.last_mut().expect("non-empty");
+ if l.is_empty() {
+ l.push_str(&w.text);
+ } else if l.chars().count() + 1 + w.text.chars().count() <= max_chars {
+ l.push(' ');
+ l.push_str(&w.text);
+ } else {
+ text_lines.push(w.text.clone());
+ }
+ }
+ let start = rate.snap(words[g.start].start);
+ let mut end = rate.snap(words[g.end - 1].end);
+ if end < words[g.end - 1].end {
+ end += fd;
+ }
+ out.push(CaptionBlock { start, end: end.max(start + fd), text: text_lines.join("\n"), speaker: words[g.start].speaker.clone(), words: g });
+ }
+ // no overlaps, minimum duration (into the silence after a block, never over the next one)
+ for i in 0..out.len() {
+ if i > 0 {
+ let min_start = out[i - 1].end + gap;
+ if out[i].start < min_start {
+ out[i].start = min_start;
+ out[i].end = out[i].end.max(min_start + fd);
+ }
+ }
+ let next = out.get(i + 1).map(|n| n.start);
+ let b = &mut out[i];
+ if b.end - b.start < rules.min_duration {
+ let want = b.start + rules.min_duration;
+ let mut e = rate.snap(want);
+ if e < want {
+ e += fd;
+ }
+ b.end = e;
+ }
+ if let Some(n) = next {
+ b.end = b.end.min(n - gap).max(b.start + fd);
+ }
+ }
+ out
+}
+
+/// Caption blocks as captions (ids from `ctx`).
+pub fn blocks_to_captions(blocks: &[CaptionBlock], ctx: &mut EditCtx) -> Vec<Caption> {
+ blocks
+ .iter()
+ .map(|b| Caption {
+ id: ClipId(ctx.alloc()),
+ start: b.start,
+ duration: b.end - b.start,
+ text: b.text.clone(),
+ speaker: b.speaker.clone(),
+ cue_id: None,
+ settings: String::new(),
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/edit/src/transcript/tests.rs b/crates/edit/src/transcript/tests.rs
new file mode 100644
index 000000000..b44e139e8
--- /dev/null
+++ b/crates/edit/src/transcript/tests.rs
@@ -0,0 +1,292 @@
+//! Deterministic tests of the transcript → sequence mapping and the text-based edits, on the
+//! hand-made interview transcript (`tests/fixtures/interview.transcript.json`, 10 s, two speakers,
+//! a 2 s pause after "show.", fillers "Um," and "uh", phrase "you know.").
+
+use super::*;
+use filmcraft_project::{Label, Project, SequenceSettings, TrackItem};
+use filmcraft_time::FrameRate;
+
+const R: FrameRate = FrameRate { num: 25, den: 1 };
+const MEDIA: ItemId = ItemId(1);
+
+fn s(x: f64) -> Tick {
+ Tick((x * TICKS_PER_SECOND as f64).round() as i64)
+}
+
+fn fixture() -> Transcript {
+ let mut t: Transcript = serde_json::from_str(include_str!("../../tests/fixtures/interview.transcript.json")).unwrap();
+ t.normalize();
+ t.check().unwrap();
+ t
+}
+
+fn transcripts() -> Transcripts {
+ let mut m = Transcripts::new();
+ m.insert(MEDIA, Arc::new(fixture()));
+ m
+}
+
+fn seq() -> Sequence {
+ let mut p = Project::new("t");
+ let id = p.new_sequence("s", SequenceSettings { frame_rate: R, ..Default::default() }, 1, 2, None);
+ p.sequence(id).unwrap().clone()
+}
+
+fn clip(id: u64, start: f64, dur: f64, src_in: f64) -> TrackItem {
+ TrackItem {
+ id: ClipId(id),
+ item: MEDIA,
+ name: "interview".into(),
+ label: Label::Iris,
+ start: s(start),
+ duration: s(dur),
+ source_in: s(src_in),
+ speed: 1.0,
+ reverse: false,
+ enabled: true,
+ link: None,
+ group: None,
+ effects: vec![],
+ markers: vec![],
+ gain_db: 0.0,
+ frame_hold: None,
+ scale_to_frame: false,
+ essential: None,
+ multicam: None,
+ }
+}
+
+fn texts(w: &[SeqWord]) -> Vec<&str> {
+ w.iter().map(|w| w.text.as_str()).collect()
+}
+
+fn media_dur(_: ItemId) -> Option<Tick> {
+ Some(s(10.0))
+}
+
+fn whole() -> Sequence {
+ let mut q = seq();
+ q.audio_tracks[0].items.push(clip(100, 0.0, 10.0, 0.0));
+ q
+}
+
+#[test]
+fn words_map_through_the_clip() {
+ let mut q = seq();
+ // media 3.5 s – 6.5 s at timeline 2 s
+ q.audio_tracks[0].items.push(clip(100, 2.0, 3.0, 3.5));
+ let w = sequence_words(&q, &transcripts());
+ assert_eq!(texts(&w), ["Um,", "today", "we", "talk", "about", "rivers."]);
+ assert_eq!(w[0].start, s(2.2));
+ assert_eq!(w[0].end, s(2.5));
+ assert_eq!(w[5].end, s(4.4));
+ assert!(w.iter().all(|x| x.clip == ClipId(100) && x.item == MEDIA && x.track == 0));
+ assert_eq!(w[0].index, 4);
+ assert_eq!(w[0].speaker.as_deref(), Some("Speaker 1"));
+}
+
+#[test]
+fn a_cut_word_is_kept_by_its_midpoint_and_clamped() {
+ let mut q = seq();
+ // cut inside "show." (1.20–1.70, midpoint 1.45): the clip starts at media 1.4
+ q.audio_tracks[0].items.push(clip(100, 0.0, 1.0, 1.4));
+ let w = sequence_words(&q, &transcripts());
+ assert_eq!(texts(&w), ["show."]);
+ assert_eq!(w[0].start, Tick::ZERO);
+ assert_eq!(w[0].end, s(0.3));
+}
+
+#[test]
+fn speed_scales_word_times() {
+ let mut q = seq();
+ let mut c = clip(100, 0.0, 5.0, 0.0);
+ c.speed = 2.0;
+ q.audio_tracks[0].items.push(c);
+ let w = sequence_words(&q, &transcripts());
+ assert_eq!(w.len(), 20);
+ assert_eq!((w[3].start, w[3].end), (s(0.6), s(0.85)));
+}
+
+#[test]
+fn duplicate_tracks_read_once_and_disabled_or_reversed_clips_are_silent() {
+ let mut q = whole();
+ q.audio_tracks[1].items.push(clip(101, 0.0, 10.0, 0.0));
+ let w = sequence_words(&q, &transcripts());
+ assert_eq!(w.len(), 20);
+ assert!(w.iter().all(|x| x.track == 0));
+ q.audio_tracks[0].items[0].enabled = false;
+ let w = sequence_words(&q, &transcripts());
+ assert_eq!(w.len(), 20);
+ assert!(w.iter().all(|x| x.track == 1));
+ q.audio_tracks[1].items[0].reverse = true;
+ assert!(sequence_words(&q, &transcripts()).is_empty());
+}
+
+#[test]
+fn two_clips_of_the_same_media_repeat_words_in_edit_order() {
+ let mut q = seq();
+ // "rivers." twice: media 5.3–5.9 at 0 s and again at 1 s
+ q.audio_tracks[0].items.push(clip(100, 0.0, 1.0, 5.2));
+ q.audio_tracks[0].items.push(clip(101, 1.0, 1.0, 5.2));
+ let w = sequence_words(&q, &transcripts());
+ assert_eq!(texts(&w), ["rivers.", "rivers."]);
+ assert_eq!(w[1].start, s(1.1));
+ assert_eq!(w[1].clip, ClipId(101));
+}
+
+#[test]
+fn search_word_at_and_paragraphs() {
+ let w = sequence_words(&whole(), &transcripts());
+ assert_eq!(search(&w, "rivers"), vec![9..10, 17..18]);
+ assert_eq!(search(&w, "YOU kn"), vec![18..20]);
+ assert_eq!(search(&w, "talk about"), vec![7..9]);
+ assert!(search(&w, " ").is_empty());
+ assert_eq!(word_at(&w, s(4.2)), Some(5));
+ assert_eq!(word_at(&w, s(2.5)), None); // in the pause
+ assert_eq!(word_at(&w, s(0.1)), None);
+ // pause ≥ 1.5 s after "show.", speaker change before "Thanks"
+ assert_eq!(paragraphs(&w, s(1.5)), vec![0..4, 4..10, 10..20]);
+}
+
+#[test]
+fn word_ranges_snap_outward() {
+ let w = sequence_words(&whole(), &transcripts());
+ // "Welcome to the show." 0.50–1.70 → frames 12..43 (0.48–1.72)
+ let r = word_range(&w, 3, 0, R).unwrap();
+ assert_eq!((r.start, r.end()), (s(0.48), s(1.72)));
+ let m = media_word_range(&fixture(), 4, 9, R).unwrap();
+ assert_eq!((m.start, m.end()), (s(3.68), s(5.92)));
+ assert!(word_range(&w, 0, 99, R).is_none());
+}
+
+#[test]
+fn extract_text_closes_the_gap() {
+ let mut q = whole();
+ let w = sequence_words(&q, &transcripts());
+ let r = word_range(&w, 0, 3, R).unwrap();
+ let mut next = 1000;
+ let mut ctx = EditCtx { next_id: &mut next, media_duration: &media_dur, min_duration: R.frame_duration() };
+ let tracks: Vec<TrackId> = q.all_tracks().map(|t| t.id).collect();
+ crate::extract(&mut q, &tracks, r, &mut ctx);
+ q.check().unwrap();
+ let w2 = sequence_words(&q, &transcripts());
+ assert_eq!(w2.len(), 16);
+ assert_eq!(w2[0].text, "Um,");
+ assert_eq!(w2[0].start, s(3.70) - r.duration);
+}
+
+#[test]
+fn pauses_are_found_and_removed_in_one_pass() {
+ let mut q = whole();
+ let w = sequence_words(&q, &transcripts());
+ // only the 2 s pause after "show." is ≥ 1 s; 0.1 s is kept on each side
+ let p = find_pauses(&w, s(1.0), s(0.1), R);
+ assert_eq!(p.len(), 1);
+ assert_eq!((p[0].start, p[0].end()), (s(1.80), s(3.60)));
+ // 0.4 s threshold also finds 5.90→6.40 and 7.60→8.00
+ let p2 = find_pauses(&w, s(0.4), s(0.1), R);
+ assert_eq!(p2.len(), 3);
+ let mut next = 1000;
+ let mut ctx = EditCtx { next_id: &mut next, media_duration: &media_dur, min_duration: R.frame_duration() };
+ let removed = ripple_delete_ranges(&mut q, p2.clone(), &mut ctx);
+ q.check().unwrap();
+ assert_eq!(removed, p2.iter().map(|r| r.duration).fold(Tick::ZERO, |a, b| a + b));
+ let w2 = sequence_words(&q, &transcripts());
+ assert_eq!(texts(&w2), texts(&w));
+ // the long pause is now 0.2 s
+ assert_eq!(w2[4].start - w2[3].end, s(0.2));
+ assert_eq!(w2.last().unwrap().end, s(10.0) - removed);
+ assert!(find_pauses(&w2, s(0.4), s(0.1), R).is_empty());
+}
+
+#[test]
+fn fillers_are_found_with_phrases_and_removed() {
+ let mut q = whole();
+ let w = sequence_words(&q, &transcripts());
+ let defaults: Vec<String> = DEFAULT_FILLERS.iter().map(|x| x.to_string()).collect();
+ let hits = find_fillers(&w, &defaults);
+ assert_eq!(hits, vec![4..5, 15..16]);
+ let mut more = defaults.clone();
+ more.push("You know".into());
+ more.push("you".into());
+ assert_eq!(find_fillers(&w, &more), vec![4..5, 15..16, 18..20]);
+ let ranges = filler_ranges(&w, &hits, R);
+ // "Um," 3.70–4.00 → nearest frames 3.68–4.00; "uh" 8.20–8.50 → 8.20–8.48
+ assert_eq!(ranges.iter().map(|r| (r.start, r.end())).collect::<Vec<_>>(), vec![(s(3.68), s(4.00)), (s(8.20), s(8.48))]);
+ let mut next = 1000;
+ let mut ctx = EditCtx { next_id: &mut next, media_duration: &media_dur, min_duration: R.frame_duration() };
+ ripple_delete_ranges(&mut q, ranges, &mut ctx);
+ q.check().unwrap();
+ let w2 = sequence_words(&q, &transcripts());
+ assert_eq!(w2.len(), 18);
+ assert!(find_fillers(&w2, &defaults).is_empty());
+ assert_eq!(q.audio_tracks[0].items.len(), 3);
+}
+
+#[test]
+fn merge_ranges_joins_overlaps() {
+ let r = |a: f64, b: f64| TimeRange::from_bounds(s(a), s(b));
+ let m = merge_ranges(vec![r(5.0, 6.0), r(1.0, 2.0), r(1.5, 3.0), r(3.0, 4.0)]);
+ assert_eq!(m, vec![r(1.0, 4.0), r(5.0, 6.0)]);
+}
+
+fn check_blocks(b: &[CaptionBlock], rules: &CaptionRules) {
+ for (i, x) in b.iter().enumerate() {
+ assert!(x.end > x.start, "{x:?}");
+ assert_eq!(R.snap(x.start), x.start);
+ assert_eq!(R.snap(x.end), x.end);
+ let lines: Vec<&str> = x.text.lines().collect();
+ assert!(lines.len() <= rules.lines, "{x:?}");
+ assert!(lines.iter().all(|l| l.chars().count() <= rules.max_chars), "{x:?}");
+ if i > 0 {
+ assert!(x.start >= b[i - 1].end + Tick(R.frame_duration().0 * rules.gap_frames), "{:?} overlaps {:?}", b[i - 1], x);
+ }
+ }
+}
+
+#[test]
+fn captions_follow_line_length_speaker_and_pause_rules() {
+ let w = sequence_words(&whole(), &transcripts());
+ let rules = CaptionRules::default();
+ let b = caption_blocks(&w, &rules, R);
+ check_blocks(&b, &rules);
+ assert_eq!(
+ b.iter().map(|x| x.text.as_str()).collect::<Vec<_>>(),
+ ["Welcome to the show.", "Um, today we talk about rivers.", "Thanks for having me. I uh love rivers,\nyou know."]
+ );
+ assert_eq!((b[0].start, b[0].end), (s(0.48), s(1.72)));
+ assert_eq!(b[2].speaker.as_deref(), Some("Speaker 2"));
+ assert_eq!(b[2].words, 10..20);
+
+ // single 20-character lines, two-frame gaps, 3 s minimum
+ let tight = CaptionRules { max_chars: 20, lines: 1, gap_frames: 2, min_duration: s(3.0), ..Default::default() };
+ let b = caption_blocks(&w, &tight, R);
+ check_blocks(&b, &tight);
+ assert!(b.len() >= 5);
+ // the first block is extended to 3 s (room before "Um,")
+ assert_eq!(b[0].end - b[0].start, s(3.0));
+ // every word is shown exactly once, in order
+ let all: Vec<usize> = b.iter().flat_map(|x| x.words.clone()).collect();
+ assert_eq!(all, (0..20).collect::<Vec<_>>());
+}
+
+#[test]
+fn captions_never_overlap_with_dense_words() {
+ // 30 one-frame words back to back
+ let words: Vec<SeqWord> = (0..30)
+ .map(|i| SeqWord {
+ text: format!("w{i}."),
+ start: R.tick_of(i),
+ end: R.tick_of(i + 1),
+ clip: ClipId(1),
+ item: MEDIA,
+ index: i as usize,
+ track: 0,
+ speaker: if i % 3 == 0 { Some("A".into()) } else { Some("B".into()) },
+ confidence: 1.0,
+ })
+ .collect();
+ let rules = CaptionRules { gap_frames: 1, ..Default::default() };
+ let b = caption_blocks(&words, &rules, R);
+ check_blocks(&b, &rules);
+}
diff --git a/crates/edit/tests/fixtures/interview.transcript.json b/crates/edit/tests/fixtures/interview.transcript.json
new file mode 100644
index 000000000..6eaec9027
--- /dev/null
+++ b/crates/edit/tests/fixtures/interview.transcript.json
@@ -0,0 +1,27 @@
+{
+ "language": "en",
+ "source": "manual",
+ "speakers": [{"name": "Speaker 1"}, {"name": "Speaker 2"}],
+ "words": [
+ {"text": "Welcome", "start": 127008000000, "end": 228614400000, "speaker": 0},
+ {"text": "to", "start": 228614400000, "end": 266716800000, "speaker": 0},
+ {"text": "the", "start": 266716800000, "end": 304819200000, "speaker": 0},
+ {"text": "show.", "start": 304819200000, "end": 431827200000, "speaker": 0},
+ {"text": "Um,", "start": 939859200000, "end": 1016064000000, "speaker": 0},
+ {"text": "today", "start": 1041465600000, "end": 1143072000000, "speaker": 0},
+ {"text": "we", "start": 1143072000000, "end": 1181174400000, "speaker": 0},
+ {"text": "talk", "start": 1181174400000, "end": 1257379200000, "speaker": 0},
+ {"text": "about", "start": 1257379200000, "end": 1346284800000, "speaker": 0},
+ {"text": "rivers.", "start": 1346284800000, "end": 1498694400000, "speaker": 0},
+ {"text": "Thanks", "start": 1625702400000, "end": 1727308800000, "speaker": 1},
+ {"text": "for", "start": 1727308800000, "end": 1765411200000, "speaker": 1},
+ {"text": "having", "start": 1765411200000, "end": 1854316800000, "speaker": 1},
+ {"text": "me.", "start": 1854316800000, "end": 1930521600000, "speaker": 1},
+ {"text": "I", "start": 2032128000000, "end": 2057529600000, "speaker": 1},
+ {"text": "uh", "start": 2082931200000, "end": 2159136000000, "speaker": 1},
+ {"text": "love", "start": 2184537600000, "end": 2260742400000, "speaker": 1},
+ {"text": "rivers,", "start": 2260742400000, "end": 2387750400000, "speaker": 1},
+ {"text": "you", "start": 2413152000000, "end": 2451254400000, "speaker": 1},
+ {"text": "know.", "start": 2451254400000, "end": 2540160000000, "speaker": 1}
+ ]
+}
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index d38870dfd..c86cfb7f0 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -9,6 +9,13 @@ rust-version.workspace = true
[lints]
workspace = true
+[features]
+default = []
+# Speech-to-text with Whisper (candle, CPU). Off by default and in wasm builds.
+whisper = ["filmcraft-speech/whisper"]
+# Speech-model downloads over HTTPS.
+speech-download = ["filmcraft-speech/download"]
+
[dependencies]
filmcraft-time = { workspace = true }
filmcraft-geom = { workspace = true }
@@ -25,6 +32,7 @@ filmcraft-export = { workspace = true }
filmcraft-format = { workspace = true }
filmcraft-interchange = { workspace = true }
filmcraft-captions = { workspace = true }
+filmcraft-speech = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index ef5978117..e3ce3634c 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -1926,6 +1926,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::project_manager::commands());
v.extend(crate::masks::commands());
v.extend(crate::presets::commands());
+ v.extend(crate::transcript::commands());
// Labels as individual commands (Edit ▸ Label ▸ <name>)
for l in Label::ALL {
let _ = l;
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index aa29c872a..b38f92825 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -28,6 +28,7 @@ pub mod relink;
pub mod shortcut_presets;
pub mod shortcuts;
pub mod sync;
+pub mod transcript;
pub mod trim;
use std::sync::Arc;
@@ -243,6 +244,9 @@ pub struct Session {
pub presets: presets::PresetLibrary,
/// Exports run a batch at a time by [`Session::pump_jobs`] (hosts without threads: web).
pub stepped: Vec<SteppedJob>,
+ /// Speech recogniser for `transcript.generate` (None = the Whisper model named by the command,
+ /// feature `whisper`). Hosts and tests install one here.
+ pub transcriber: Option<Arc<dyn filmcraft_speech::Transcriber>>,
/// Nesting depth of [`Session::execute`] (commands that run other commands).
exec_depth: u32,
}
@@ -322,6 +326,7 @@ impl Session {
mask_jobs: Vec::new(),
presets: Default::default(),
stepped: Vec::new(),
+ transcriber: None,
exec_depth: 0,
}
}
@@ -722,4 +727,6 @@ mod shortcuts_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
+mod transcript_tests;
+#[cfg(test)]
mod trim_tests;
diff --git a/crates/engine/src/transcript.rs b/crates/engine/src/transcript.rs
new file mode 100644
index 000000000..0dfab5ecc
--- /dev/null
+++ b/crates/engine/src/transcript.rs
@@ -0,0 +1,473 @@
+//! Text-based editing commands (`transcript.*`): the Text panel ▸ Transcript tab.
+//!
+//! Transcripts belong to media items (`Project::transcripts`, media time); the sequence transcript
+//! is derived from them ([`filmcraft_edit::transcript::sequence_words`]). Words of the sequence
+//! transcript are addressed by index (`from`, `to`, inclusive), as `transcript.inspect` lists them.
+//!
+//! Speech recognition goes through a [`Transcriber`]: [`Session::transcriber`] when a host or a
+//! test installed one, else the Whisper model named by `model` from `<data dir>/models` (needs the
+//! engine feature `whisper`; without it `transcript.generate` fails with a clear error, and agents
+//! can still bring their own transcript with `transcript.set`).
+
+use std::sync::Arc;
+
+use serde_json::{Value, json};
+
+use filmcraft_edit as edit;
+use filmcraft_edit::transcript::{self as tx, CaptionRules, SeqWord};
+use filmcraft_project::{CaptionFormat, CaptionTrack, ItemId, ItemKind, TrackId, Transcript};
+use filmcraft_speech::{Options, SpeechError, Transcriber};
+use filmcraft_time::{TICKS_PER_SECOND, Tick, TimeRange};
+
+use crate::commands::{CommandSpec, always, bad, bool_p, f64_p, has_seq, str_p, u64_p};
+use crate::{EngineError, Result, Session};
+
+type Run = fn(&mut Session, &Value) -> Result<Value>;
+type Enabled = fn(&Session) -> std::result::Result<(), String>;
+
+fn spec(id: &'static str, label: &'static str, menu: &'static [&'static str], params: &'static str, enabled: Enabled, run: Run, journal: bool) -> CommandSpec {
+ CommandSpec { id, label, menu, shortcut: None, params, enabled, run, journal }
+}
+
+/// Where downloaded speech models live (`<data dir>/models`).
+pub fn models_dir() -> Option<std::path::PathBuf> {
+ crate::autosave::default_data_dir().map(|d| d.join("models"))
+}
+
+/// Whether this build can transcribe with Whisper (feature `whisper`).
+pub fn speech_available() -> bool {
+ filmcraft_speech::available()
+}
+
+/// The words of the active sequence's transcript.
+pub fn sequence_words(s: &Session) -> Vec<SeqWord> {
+ match s.active_sequence() {
+ Some(q) => tx::sequence_words(q, &s.project.transcripts),
+ None => Vec::new(),
+ }
+}
+
+fn has_transcript(s: &Session) -> std::result::Result<(), String> {
+ has_seq(s)?;
+ if sequence_words(s).is_empty() { Err("the sequence has no transcript (Transcribe first)".into()) } else { Ok(()) }
+}
+
+fn has_transcripts(s: &Session) -> std::result::Result<(), String> {
+ if s.project.transcripts.is_empty() { Err("there are no transcripts".into()) } else { Ok(()) }
+}
+
+/// The media item behind a project item (subclips resolve to their parent).
+fn media_item(s: &Session, item: ItemId) -> Option<ItemId> {
+ match &s.project.item(item)?.kind {
+ ItemKind::Media(_) => Some(item),
+ ItemKind::Subclip { parent, .. } => media_item(s, *parent),
+ _ => None,
+ }
+}
+
+fn ids_p(p: &Value, k: &str) -> Option<Vec<ItemId>> {
+ p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(ItemId).collect())
+}
+
+/// Items to transcribe: `items` / `item`, else the Project panel selection, else the media of the
+/// active sequence's enabled audio clips. Subclips resolve to their media; duplicates are removed.
+fn targets(s: &Session, p: &Value) -> Vec<ItemId> {
+ let mut raw = ids_p(p, "items").or_else(|| u64_p(p, "item").map(|i| vec![ItemId(i)])).unwrap_or_default();
+ if raw.is_empty() {
+ raw = s.state.project_selection.clone();
+ }
+ if raw.is_empty()
+ && let Some(q) = s.active_sequence()
+ {
+ raw = q.audio_tracks.iter().flat_map(|t| t.items.iter()).filter(|it| it.enabled).map(|it| it.item).collect();
+ }
+ let mut out = Vec::new();
+ for i in raw {
+ if let Some(m) = media_item(s, i)
+ && !out.contains(&m)
+ {
+ out.push(m);
+ }
+ }
+ out
+}
+
+/// Mono 16 kHz audio of a media item (None: no audio).
+fn item_audio(s: &Session, item: ItemId) -> Option<Vec<f32>> {
+ let dur = match &s.project.item(item)?.kind {
+ ItemKind::Media(m) => m.duration(),
+ _ => return None,
+ };
+ let src = s.source(item)?;
+ if !src.info().has_audio() {
+ return None;
+ }
+ let sr = filmcraft_speech::SAMPLE_RATE;
+ let len = dur.to_units_floor(sr as i64).max(0) as usize;
+ let buf = src.audio(0, len, sr).ok()?;
+ Some(filmcraft_speech::downmix(&buf.channels))
+}
+
+fn speech_err(e: SpeechError) -> EngineError {
+ EngineError::Other(e.to_string())
+}
+
+/// The transcriber to use: the installed one, else the named catalogue model.
+fn transcriber(s: &Session, p: &Value) -> Result<Arc<dyn Transcriber>> {
+ if let Some(t) = &s.transcriber {
+ return Ok(t.clone());
+ }
+ let model = str_p(p, "model").unwrap_or(filmcraft_speech::models::DEFAULT_MODEL);
+ if filmcraft_speech::models::find(model).is_none() {
+ return Err(speech_err(SpeechError::UnknownModel(model.into())));
+ }
+ if !filmcraft_speech::available() {
+ return Err(EngineError::Other(
+ "speech-to-text is not available in this build (built without the `whisper` feature); import a transcript with transcript.set instead".into(),
+ ));
+ }
+ let dir = models_dir().ok_or_else(|| EngineError::Other("no data directory for speech models".into()))?;
+ filmcraft_speech::load(&dir, model).map_err(speech_err)
+}
+
+fn generate(s: &mut Session, p: &Value) -> Result<Value> {
+ let items = targets(s, p);
+ if items.is_empty() {
+ return Err(bad("transcript.generate", "nothing to transcribe (pass `items`, select clips, or open a sequence with audio)"));
+ }
+ let t = transcriber(s, p)?;
+ let opts = Options {
+ language: str_p(p, "language").filter(|l| !l.is_empty() && *l != "auto").map(str::to_string),
+ diarize: bool_p(p, "diarize").unwrap_or(true),
+ max_speakers: u64_p(p, "maxSpeakers").map(|n| n.clamp(1, 32) as usize).unwrap_or(Options::default().max_speakers),
+ };
+ let mut done: Vec<(ItemId, Transcript)> = Vec::new();
+ let mut skipped = Vec::new();
+ for item in items {
+ let Some(audio) = item_audio(s, item) else {
+ skipped.push(item.0);
+ continue;
+ };
+ let mut tr = t.transcribe(&audio, &opts, &mut |_, _| true).map_err(speech_err)?;
+ tr.normalize();
+ done.push((item, tr));
+ }
+ if done.is_empty() {
+ return Err(EngineError::Other("none of the clips has audio to transcribe".into()));
+ }
+ let report: Vec<Value> = done
+ .iter()
+ .map(|(i, t)| json!({"item": i.0, "words": t.words.len(), "speakers": t.speakers.len(), "language": t.language, "source": t.source}))
+ .collect();
+ s.edit("Transcribe", move |pr, _| {
+ for (i, t) in done {
+ pr.transcripts.insert(i, Arc::new(t));
+ }
+ Ok(())
+ })?;
+ Ok(json!({"items": report, "skipped": skipped}))
+}
+
+fn set(s: &mut Session, p: &Value) -> Result<Value> {
+ let item = u64_p(p, "item").map(ItemId).ok_or_else(|| bad("transcript.set", "`item` is required"))?;
+ let item = media_item(s, item).ok_or_else(|| bad("transcript.set", "no such media item"))?;
+ let v = p.get("transcript").cloned().ok_or_else(|| bad("transcript.set", "`transcript` is required"))?;
+ let mut t: Transcript = serde_json::from_value(v).map_err(|e| bad("transcript.set", e.to_string()))?;
+ if t.source.is_empty() {
+ t.source = "imported".into();
+ }
+ t.normalize();
+ t.check().map_err(|e| bad("transcript.set", e))?;
+ let n = t.words.len();
+ s.edit("Set Transcript", move |pr, _| {
+ pr.transcripts.insert(item, Arc::new(t));
+ Ok(())
+ })?;
+ Ok(json!({"item": item.0, "words": n}))
+}
+
+fn delete(s: &mut Session, p: &Value) -> Result<Value> {
+ let items: Vec<ItemId> = match ids_p(p, "items").or_else(|| u64_p(p, "item").map(|i| vec![ItemId(i)])) {
+ Some(v) => v.into_iter().filter_map(|i| media_item(s, i)).collect(),
+ None => s.project.transcripts.keys().copied().collect(),
+ };
+ let n = items.iter().filter(|i| s.project.transcripts.contains_key(i)).count();
+ if n == 0 {
+ return Err(EngineError::Other("no transcript to delete".into()));
+ }
+ s.edit("Delete Transcript", move |pr, _| {
+ for i in items {
+ pr.transcripts.remove(&i);
+ }
+ Ok(())
+ })?;
+ Ok(json!({"deleted": n}))
+}
+
+fn word_json(i: usize, w: &SeqWord) -> Value {
+ json!({"i": i, "text": w.text, "start": w.start.0, "end": w.end.0, "speaker": w.speaker, "clip": w.clip.0, "item": w.item.0, "confidence": w.confidence})
+}
+
+fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
+ let words = sequence_words(s);
+ let gap = Tick::from_seconds_f64(f64_p(p, "paragraphGapSeconds").unwrap_or(1.5));
+ let paras: Vec<Value> = tx::paragraphs(&words, gap)
+ .into_iter()
+ .map(|r| {
+ let text = words[r.clone()].iter().map(|w| w.text.as_str()).collect::<Vec<_>>().join(" ");
+ json!({"from": r.start, "to": r.end - 1, "speaker": words[r.start].speaker, "start": words[r.start].start.0, "end": words[r.end - 1].end.0, "text": text})
+ })
+ .collect();
+ let speakers: Vec<String> = {
+ let mut v: Vec<String> = Vec::new();
+ for w in &words {
+ if let Some(n) = &w.speaker
+ && !v.contains(n)
+ {
+ v.push(n.clone());
+ }
+ }
+ v
+ };
+ let current = tx::word_at(&words, s.playhead());
+ Ok(json!({
+ "words": words.iter().enumerate().map(|(i, w)| word_json(i, w)).collect::<Vec<_>>(),
+ "paragraphs": paras,
+ "speakers": speakers,
+ "current": current,
+ "items": s.project.transcripts.iter().map(|(i, t)| json!({"item": i.0, "words": t.words.len(), "language": t.language, "source": t.source, "speakers": t.speakers.iter().map(|k| &k.name).collect::<Vec<_>>()})).collect::<Vec<_>>(),
+ }))
+}
+
+fn search(s: &mut Session, p: &Value) -> Result<Value> {
+ let q = str_p(p, "query").ok_or_else(|| bad("transcript.search", "`query` is required"))?;
+ let words = sequence_words(s);
+ let hits: Vec<Value> = tx::search(&words, q)
+ .into_iter()
+ .map(|r| json!({"from": r.start, "to": r.end - 1, "start": words[r.start].start.0, "end": words[r.end - 1].end.0}))
+ .collect();
+ Ok(json!({"matches": hits}))
+}
+
+/// Timeline range of the words `from..=to` (frame-snapped outward).
+fn range_p(s: &Session, p: &Value, cmd: &str) -> Result<TimeRange> {
+ let words = sequence_words(s);
+ let from = u64_p(p, "from").ok_or_else(|| bad(cmd, "`from` (word index) is required"))? as usize;
+ let to = u64_p(p, "to").map(|n| n as usize).unwrap_or(from);
+ tx::word_range(&words, from, to, s.sequence_rate()).ok_or_else(|| bad(cmd, format!("word index out of range (the transcript has {} words)", words.len())))
+}
+
+fn range_json(r: TimeRange) -> Value {
+ json!({"start": r.start.0, "end": r.end().0})
+}
+
+fn select(s: &mut Session, p: &Value) -> Result<Value> {
+ let r = range_p(s, p, "transcript.select")?;
+ let fd = s.sequence_rate().frame_duration();
+ s.edit_sequence("Mark Transcript Selection", |q, _, _| {
+ q.mark_in = Some(r.start);
+ q.mark_out = Some(r.end() - fd);
+ Ok(())
+ })?;
+ s.set_playhead(r.start);
+ Ok(range_json(r))
+}
+
+fn extract_or_lift(s: &mut Session, p: &Value, extract: bool) -> Result<Value> {
+ let cmd = if extract { "transcript.extract" } else { "transcript.lift" };
+ let r = range_p(s, p, cmd)?;
+ let tg = s.targeting().targeted;
+ s.edit_sequence(if extract { "Extract Text" } else { "Lift Text" }, |q, ctx, _| {
+ if extract {
+ edit::extract(q, &tg, r, ctx);
+ } else {
+ edit::lift(q, &tg, r, ctx);
+ }
+ q.mark_in = None;
+ q.mark_out = None;
+ Ok(())
+ })?;
+ s.set_playhead(r.start);
+ Ok(range_json(r))
+}
+
+fn rename_speaker(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = str_p(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("transcript.renameSpeaker", "`name` is required"))?.to_string();
+ let item = u64_p(p, "item").map(ItemId).and_then(|i| media_item(s, i));
+ // `speaker`: the current name (every transcript), or an index (needs `item`)
+ let (old_name, index) = match p.get("speaker") {
+ Some(Value::String(n)) => (Some(n.clone()), None),
+ Some(v) if v.is_u64() => (None, v.as_u64().map(|n| n as usize)),
+ _ => return Err(bad("transcript.renameSpeaker", "`speaker` (name, or index with `item`) is required")),
+ };
+ if index.is_some() && item.is_none() {
+ return Err(bad("transcript.renameSpeaker", "a speaker index needs `item`"));
+ }
+ let mut n = 0;
+ let mut next = s.project.transcripts.clone();
+ for (i, t) in next.iter_mut() {
+ if item.is_some_and(|x| x != *i) {
+ continue;
+ }
+ let tt = Arc::make_mut(t);
+ for (k, sp) in tt.speakers.iter_mut().enumerate() {
+ if old_name.as_ref().is_some_and(|o| *o == sp.name) || index == Some(k) {
+ sp.name = name.clone();
+ n += 1;
+ }
+ }
+ }
+ if n == 0 {
+ return Err(EngineError::Other("no such speaker".into()));
+ }
+ s.edit("Rename Speaker", move |pr, _| {
+ pr.transcripts = next;
+ Ok(())
+ })?;
+ Ok(json!({"renamed": n}))
+}
+
+fn remove_ranges(s: &mut Session, label: &str, ranges: Vec<TimeRange>) -> Result<Value> {
+ let n = ranges.len();
+ if n == 0 {
+ return Ok(json!({"removed": 0, "ticks": 0}));
+ }
+ let total = s.edit_sequence(label, |q, ctx, _| Ok(tx::ripple_delete_ranges(q, ranges, ctx)))?;
+ Ok(json!({"removed": n, "ticks": total.0, "seconds": total.0 as f64 / TICKS_PER_SECOND as f64}))
+}
+
+fn remove_pauses(s: &mut Session, p: &Value) -> Result<Value> {
+ let words = sequence_words(s);
+ let min = Tick::from_seconds_f64(f64_p(p, "minSeconds").unwrap_or(1.0));
+ let keep = Tick::from_seconds_f64(f64_p(p, "keepSeconds").unwrap_or(0.15));
+ let ranges = tx::find_pauses(&words, min, keep, s.sequence_rate());
+ remove_ranges(s, "Remove Pauses", ranges)
+}
+
+fn remove_fillers(s: &mut Session, p: &Value) -> Result<Value> {
+ let words = sequence_words(s);
+ let fillers: Vec<String> = match p.get("fillers").and_then(Value::as_array) {
+ Some(a) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
+ None => tx::DEFAULT_FILLERS.iter().map(|f| f.to_string()).collect(),
+ };
+ let hits = tx::find_fillers(&words, &fillers);
+ let ranges = tx::filler_ranges(&words, &hits, s.sequence_rate());
+ remove_ranges(s, "Remove Filler Words", ranges)
+}
+
+fn create_captions(s: &mut Session, p: &Value) -> Result<Value> {
+ let words = sequence_words(s);
+ let d = CaptionRules::default();
+ let rules = CaptionRules {
+ max_chars: u64_p(p, "maxChars").map(|n| n as usize).unwrap_or(d.max_chars),
+ lines: u64_p(p, "lines").map(|n| n as usize).unwrap_or(d.lines),
+ min_duration: f64_p(p, "minSeconds").map(Tick::from_seconds_f64).unwrap_or(d.min_duration),
+ max_duration: f64_p(p, "maxSeconds").map(Tick::from_seconds_f64).unwrap_or(d.max_duration),
+ gap_frames: p.get("gapFrames").and_then(Value::as_i64).unwrap_or(d.gap_frames),
+ break_pause: d.break_pause,
+ };
+ let blocks = tx::caption_blocks(&words, &rules, s.sequence_rate());
+ let format = str_p(p, "format").and_then(CaptionFormat::from_name).unwrap_or_default();
+ let name = str_p(p, "name").unwrap_or("Transcript").to_string();
+ let n = blocks.len();
+ let tid = s.edit_sequence("Create Captions", |q, ctx, st| {
+ let tid = TrackId(ctx.alloc());
+ let mut t = CaptionTrack::new(tid, name, format);
+ t.captions = tx::blocks_to_captions(&blocks, ctx);
+ q.caption_tracks.insert(0, t);
+ st.caption_selection.clear();
+ Ok(tid)
+ })?;
+ Ok(json!({"track": tid.0, "captions": n}))
+}
+
+fn models(_: &mut Session, _: &Value) -> Result<Value> {
+ let dir = models_dir();
+ Ok(json!({
+ "available": filmcraft_speech::available(),
+ "default": filmcraft_speech::models::DEFAULT_MODEL,
+ "dir": dir.as_ref().map(|d| d.to_string_lossy().to_string()),
+ "models": filmcraft_speech::models::catalogue().iter().map(|m| json!({
+ "id": m.id, "name": m.name, "multilingual": m.multilingual, "description": m.description,
+ "license": m.license, "source": m.source, "size": m.size(),
+ "installed": dir.as_ref().is_some_and(|d| filmcraft_speech::models::installed(d, m)),
+ })).collect::<Vec<_>>(),
+ }))
+}
+
+/// Download a catalogue model into `<data dir>/models` (feature `speech-download`). Hosts show
+/// the size, source and licence (`transcript.models`) and ask before running this.
+fn download_model(_: &mut Session, p: &Value) -> Result<Value> {
+ let id = str_p(p, "model").unwrap_or(filmcraft_speech::models::DEFAULT_MODEL);
+ let m = filmcraft_speech::models::find(id).ok_or_else(|| speech_err(SpeechError::UnknownModel(id.into())))?;
+ let dir = models_dir().ok_or_else(|| EngineError::Other("no data directory for speech models".into()))?;
+ #[cfg(feature = "speech-download")]
+ {
+ filmcraft_speech::models::download(&dir, m, &mut |_, _, _| true).map_err(speech_err)?;
+ Ok(json!({"model": m.id, "dir": filmcraft_speech::models::model_dir(&dir, m).to_string_lossy()}))
+ }
+ #[cfg(not(feature = "speech-download"))]
+ {
+ let _ = (m, dir);
+ Err(EngineError::Other("model downloads are not available in this build (built without the `speech-download` feature)".into()))
+ }
+}
+
+pub fn commands() -> Vec<CommandSpec> {
+ vec![
+ spec(
+ "transcript.generate",
+ "Transcribe…",
+ &["Sequence", "Transcript"],
+ r#"{"items":[id]?,"model":"whisper-base"?,"language":"en|auto"?,"diarize":bool?,"maxSpeakers":n?}"#,
+ always,
+ generate,
+ true,
+ ),
+ spec(
+ "transcript.set",
+ "Import Transcript",
+ &[],
+ r#"{"item":id,"transcript":{"language":str,"speakers":[{"name":str}],"words":[{"text":str,"start":tick,"end":tick,"speaker":n?}]}}"#,
+ always,
+ set,
+ true,
+ ),
+ spec("transcript.delete", "Delete Transcript", &["Sequence", "Transcript"], r#"{"items":[id]?}"#, has_transcripts, delete, true),
+ spec("transcript.inspect", "Inspect Transcript", &[], r#"{"paragraphGapSeconds":f?}"#, always, inspect, false),
+ spec("transcript.search", "Search Transcript", &[], r#"{"query":str}"#, always, search, false),
+ spec("transcript.models", "List Speech Models", &[], "{}", always, models, false),
+ spec("transcript.downloadModel", "Download Speech Model", &[], r#"{"model":"whisper-base"?}"#, always, download_model, true),
+ spec("transcript.select", "Mark Selected Text", &[], r#"{"from":word,"to":word?}"#, has_transcript, select, true),
+ spec("transcript.extract", "Extract Selected Text", &[], r#"{"from":word,"to":word?}"#, has_transcript, |s, p| extract_or_lift(s, p, true), true),
+ spec("transcript.lift", "Lift Selected Text", &[], r#"{"from":word,"to":word?}"#, has_transcript, |s, p| extract_or_lift(s, p, false), true),
+ spec(
+ "transcript.renameSpeaker",
+ "Rename Speaker…",
+ &[],
+ r#"{"speaker":"Speaker 1"|index,"name":str,"item":id?}"#,
+ has_transcripts,
+ rename_speaker,
+ true,
+ ),
+ spec(
+ "transcript.removePauses",
+ "Remove Pauses",
+ &["Sequence", "Transcript"],
+ r#"{"minSeconds":f?,"keepSeconds":f?}"#,
+ has_transcript,
+ remove_pauses,
+ true,
+ ),
+ spec("transcript.removeFillers", "Remove Filler Words", &["Sequence", "Transcript"], r#"{"fillers":[str]?}"#, has_transcript, remove_fillers, true),
+ spec(
+ "transcript.createCaptions",
+ "Create Captions from Transcript…",
+ &["Sequence", "Transcript"],
+ r#"{"maxChars":n?,"lines":1|2?,"minSeconds":f?,"maxSeconds":f?,"gapFrames":n?,"format":str?,"name":str?}"#,
+ has_transcript,
+ create_captions,
+ true,
+ ),
+ ]
+}
diff --git a/crates/engine/src/transcript_tests.rs b/crates/engine/src/transcript_tests.rs
new file mode 100644
index 000000000..54fc421d5
--- /dev/null
+++ b/crates/engine/src/transcript_tests.rs
@@ -0,0 +1,177 @@
+use std::sync::Arc;
+
+use serde_json::json;
+
+use crate::Session;
+use filmcraft_project::{ItemId, Transcript, Word};
+use filmcraft_speech::FixedTranscriber;
+use filmcraft_time::Tick;
+
+/// The demo project with a fake transcriber whose transcript fits the first A1 clip's media:
+/// "Hello um world." (Speaker 1), a 1.2 s pause, "Second speaker here." (Speaker 2).
+fn session() -> (Session, ItemId, Tick) {
+ let mut s = Session::default();
+ s.execute("file.openDemoProject", json!({})).unwrap();
+ let q = s.active_sequence().unwrap();
+ let a = &q.audio_tracks[0].items[0];
+ let (item, sin) = (a.item, a.source_in);
+ let sec = |x: f64| sin + Tick::from_seconds_f64(x);
+ let mut t = Transcript { language: "en".into(), ..Default::default() };
+ for (text, a, b, sp) in
+ [("Hello", 0.2, 0.5, 0), ("um", 0.6, 0.9, 0), ("world.", 1.0, 1.4, 0), ("Second", 2.6, 3.0, 1), ("speaker", 3.0, 3.5, 1), ("here.", 3.5, 4.0, 1)]
+ {
+ let mut w = Word::new(text, sec(a), sec(b));
+ w.speaker = Some(sp);
+ t.words.push(w);
+ }
+ t.normalize();
+ s.transcriber = Some(Arc::new(FixedTranscriber { transcript: t, id: "fixed".into() }));
+ let start = a_start(&s);
+ (s, item, start)
+}
+
+fn a_start(s: &Session) -> Tick {
+ s.active_sequence().unwrap().audio_tracks[0].items[0].start
+}
+
+fn words(s: &mut Session) -> Vec<String> {
+ let r = s.execute("transcript.inspect", json!({})).unwrap();
+ r["words"].as_array().unwrap().iter().map(|w| w["text"].as_str().unwrap().to_string()).collect()
+}
+
+#[test]
+fn generate_inspect_search_and_rename() {
+ let (mut s, item, start) = session();
+ assert!(s.execute("transcript.select", json!({"from": 0})).is_err(), "disabled before transcribing");
+ let r = s.execute("transcript.generate", json!({"items": [item.0]})).unwrap();
+ assert_eq!(r["items"][0]["words"], 6, "{r}");
+ assert_eq!(r["items"][0]["source"], "fixed");
+ assert_eq!(s.project.transcripts[&item].words.len(), 6);
+
+ let r = s.execute("transcript.inspect", json!({})).unwrap();
+ assert_eq!(words(&mut s), ["Hello", "um", "world.", "Second", "speaker", "here."]);
+ assert_eq!(r["words"][0]["start"].as_i64().unwrap(), (start + Tick::from_seconds_f64(0.2)).0, "mapped to sequence time");
+ assert_eq!(r["paragraphs"].as_array().unwrap().len(), 2, "speaker change splits paragraphs: {}", r["paragraphs"]);
+ assert_eq!(r["speakers"], json!(["Speaker 1", "Speaker 2"]));
+
+ let r = s.execute("transcript.search", json!({"query": "second spea"})).unwrap();
+ assert_eq!(r["matches"], json!([{"from": 3, "to": 4, "start": r["matches"][0]["start"], "end": r["matches"][0]["end"]}]));
+
+ s.execute("transcript.renameSpeaker", json!({"speaker": "Speaker 2", "name": "Ann"})).unwrap();
+ let r = s.execute("transcript.inspect", json!({})).unwrap();
+ assert_eq!(r["words"][3]["speaker"], "Ann");
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.project.transcripts[&item].speakers[1].name, "Speaker 2");
+ s.execute("transcript.renameSpeaker", json!({"speaker": 0, "item": item.0, "name": "Bo"})).unwrap();
+ assert_eq!(s.project.transcripts[&item].speakers[0].name, "Bo");
+ assert!(s.execute("transcript.renameSpeaker", json!({"speaker": "Nobody", "name": "X"})).is_err());
+
+ // transcribing is one undo step
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(s.project.transcripts.is_empty());
+}
+
+#[test]
+fn select_extract_and_lift_by_words() {
+ let (mut s, item, _) = session();
+ s.execute("transcript.generate", json!({"items": [item.0]})).unwrap();
+ let rate = s.sequence_rate();
+ let before = s.active_sequence().unwrap().duration();
+
+ let r = s.execute("transcript.select", json!({"from": 3, "to": 5})).unwrap();
+ let (a, b) = (Tick(r["start"].as_i64().unwrap()), Tick(r["end"].as_i64().unwrap()));
+ let q = s.active_sequence().unwrap();
+ assert_eq!(q.mark_in, Some(a));
+ assert_eq!(q.mark_out, Some(b - rate.frame_duration()), "Out is the last frame inside");
+ assert_eq!(rate.snap(a), a, "frame aligned");
+ assert_eq!(s.playhead(), a);
+
+ // Extract "um": the sequence gets shorter by the word's frames and the word is gone
+ let r = s.execute("transcript.extract", json!({"from": 1})).unwrap();
+ let cut = Tick(r["end"].as_i64().unwrap()) - Tick(r["start"].as_i64().unwrap());
+ assert!(cut > Tick::ZERO);
+ assert_eq!(s.active_sequence().unwrap().duration(), before - cut);
+ assert!(!words(&mut s).contains(&"um".to_string()), "{:?}", words(&mut s));
+ s.active_sequence().unwrap().check().unwrap();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.active_sequence().unwrap().duration(), before);
+
+ // Lift leaves a gap: same duration, word gone
+ s.execute("transcript.lift", json!({"from": 1, "to": 1})).unwrap();
+ assert_eq!(s.active_sequence().unwrap().duration(), before);
+ assert_eq!(words(&mut s), ["Hello", "world.", "Second", "speaker", "here."]);
+ assert!(s.execute("transcript.extract", json!({"from": 99})).is_err());
+}
+
+#[test]
+fn remove_fillers_pauses_and_create_captions() {
+ let (mut s, item, _) = session();
+ s.execute("transcript.generate", json!({"items": [item.0]})).unwrap();
+ let before = s.active_sequence().unwrap().duration();
+ let r = s.execute("transcript.removeFillers", json!({})).unwrap();
+ assert_eq!(r["removed"], 1, "{r}");
+ assert!(!words(&mut s).contains(&"um".to_string()));
+ let r = s.execute("transcript.removePauses", json!({"minSeconds": 1.0, "keepSeconds": 0.1})).unwrap();
+ assert_eq!(r["removed"], 1, "{r}");
+ let after = s.active_sequence().unwrap().duration();
+ assert!(after < before - Tick::from_seconds_f64(1.0), "the pause and the filler are gone");
+ assert_eq!(words(&mut s).len(), 5);
+ s.active_sequence().unwrap().check().unwrap();
+
+ let r = s.execute("transcript.createCaptions", json!({"maxChars": 32})).unwrap();
+ assert_eq!(r["captions"], 2, "one caption per speaker: {r}");
+ let q = s.active_sequence().unwrap();
+ let tr = &q.caption_tracks[0];
+ assert_eq!(tr.captions[0].text, "Hello world.");
+ assert_eq!(tr.captions[1].speaker.as_deref(), Some("Speaker 2"));
+ q.check().unwrap();
+}
+
+#[test]
+fn set_delete_and_models() {
+ let (mut s, item, _) = session();
+ let t = json!({"language": "en", "words": [
+ {"text": "b", "start": 2000, "end": 3000, "speaker": 1},
+ {"text": "a", "start": 0, "end": 1000},
+ ]});
+ let r = s.execute("transcript.set", json!({"item": item.0, "transcript": t})).unwrap();
+ assert_eq!(r["words"], 2);
+ let tr = &s.project.transcripts[&item];
+ assert_eq!(tr.words[0].text, "a", "normalized: sorted");
+ assert_eq!(tr.speakers.len(), 2, "missing speaker labels added");
+ assert_eq!(tr.source, "imported");
+ assert!(s.execute("transcript.set", json!({"item": 999_999, "transcript": {}})).is_err());
+ assert!(s.execute("transcript.set", json!({"item": item.0, "transcript": {"words": 3}})).is_err());
+
+ // survives save/load
+ let bytes = filmcraft_format::encode(&s.project, true);
+ let back = filmcraft_format::decode(&bytes).unwrap();
+ assert_eq!(back.project.transcripts[&item].words.len(), 2);
+
+ s.execute("transcript.delete", json!({"items": [item.0]})).unwrap();
+ assert!(s.project.transcripts.is_empty());
+ assert!(s.execute("transcript.delete", json!({})).is_err());
+
+ let m = s.execute("transcript.models", json!({})).unwrap();
+ assert_eq!(m["available"], filmcraft_speech::available());
+ assert!(m["models"].as_array().unwrap().iter().any(|x| x["id"] == "whisper-base"));
+}
+
+#[test]
+fn generate_without_a_transcriber() {
+ let (mut s, item, _) = session();
+ s.transcriber = None;
+ let e = s.execute("transcript.generate", json!({"items": [item.0], "model": "nope"})).unwrap_err().to_string();
+ assert!(e.contains("unknown speech model"), "{e}");
+ if !filmcraft_speech::available() {
+ let e = s.execute("transcript.generate", json!({"items": [item.0]})).unwrap_err().to_string();
+ assert!(e.contains("whisper") && e.contains("not available"), "{e}");
+ #[cfg(not(feature = "speech-download"))]
+ assert!(s.execute("transcript.downloadModel", json!({})).unwrap_err().to_string().contains("not available"));
+ }
+ // defaults to the media of the open sequence's audio clips
+ s.transcriber = Some(Arc::new(FixedTranscriber { transcript: Transcript::default(), id: "empty".into() }));
+ let r = s.execute("transcript.generate", json!({})).unwrap();
+ assert!(r["items"].as_array().unwrap().len() >= 2, "{r}");
+}
diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs
index 565b73d23..469a48274 100644
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@ -48,7 +48,7 @@ pub type Migration = fn(Value) -> Result<Value, String>;
/// `MIGRATIONS[i]` upgrades schema `i + 1` to `i + 2`. Append one function per schema bump; never
/// edit a shipped one.
-pub const MIGRATIONS: &[Migration] = &[v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8];
+pub const MIGRATIONS: &[Migration] = &[v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9];
/// The schema version this build writes (and the newest it reads).
pub const SCHEMA_VERSION: u32 = MIGRATIONS.len() as u32 + 1;
@@ -253,13 +253,18 @@ fn v7_to_v8(doc: Value) -> Result<Value, String> {
Ok(doc)
}
+/// v8 → v9: per-media-item transcripts (`project.transcripts`) added; existing data needs no change.
+fn v8_to_v9(doc: Value) -> Result<Value, String> {
+ Ok(doc)
+}
+
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schema_version_matches_table() {
- assert_eq!(SCHEMA_VERSION, 8);
+ assert_eq!(SCHEMA_VERSION, 9);
}
#[test]
diff --git a/crates/format/tests/fixtures.rs b/crates/format/tests/fixtures.rs
index e49d3bcc1..252e6cf88 100644
--- a/crates/format/tests/fixtures.rs
+++ b/crates/format/tests/fixtures.rs
@@ -153,3 +153,21 @@ fn large_project_roundtrip_and_timing() {
compact.len() as f64 / 1024.0
);
}
+
+#[test]
+fn v8_loads_without_transcripts_and_v9_roundtrips_them() {
+ let l = decode(&fixture("v8-minimal.fcproj")).unwrap();
+ assert_eq!(l.schema_version, 8);
+ assert!(l.migrated());
+ assert!(l.project.transcripts.is_empty());
+ let mut p = l.project;
+ let mut t = filmcraft_project::Transcript { language: "en".into(), source: "manual".into(), ..Default::default() };
+ t.words.push(filmcraft_project::Word::new("Hello", Tick(0), Tick(1000)));
+ t.words[0].speaker = Some(0);
+ t.normalize();
+ p.transcripts.insert(ItemId(7), std::sync::Arc::new(t));
+ let again = decode(&encode(&p, true)).unwrap();
+ assert!(!again.migrated());
+ assert_eq!(again.project, p);
+ assert_eq!(again.project.transcripts[&ItemId(7)].speakers[0].name, "Speaker 1");
+}
diff --git a/crates/format/tests/fixtures/v8-minimal.fcproj b/crates/format/tests/fixtures/v8-minimal.fcproj
new file mode 100644
index 000000000..9fdcb3075
--- /dev/null
+++ b/crates/format/tests/fixtures/v8-minimal.fcproj
@@ -0,0 +1 @@
+{"schema_version":8,"generator":"FilmCraft 0.1.0","project":{"name":"Before Transcripts","settings":{"renderer":"FilmCraft GPU Acceleration (wgpu)","video_display":"Timecode","audio_display_samples":true,"default_still_duration":1270080000000,"default_transition_duration_frames":24,"default_audio_transition_duration":254016000000},"root":{"id":0,"name":"Before Transcripts","children":[]},"items":{},"next_id":1}}
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index f8d4d80cc..063edca47 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -15,6 +15,7 @@ pub mod keyframe;
pub mod mask;
pub mod mixer;
pub mod multicam;
+pub mod transcript;
use std::collections::BTreeMap;
@@ -30,6 +31,7 @@ pub use keyframe::{Interpolation, Keyframe, Param, ParamValue};
pub use mask::{Mask, MaskMode, MaskPath, MaskVertex, TrackMethod};
pub use mixer::{AutomationMode, InputMap, MixerStrip, TrackSend};
pub use multicam::{Camera, MergedClip, MulticamAudio, MulticamSel, MulticamSource};
+pub use transcript::{Speaker, Transcript, Word};
macro_rules! id_type {
($name:ident) => {
@@ -879,6 +881,10 @@ pub struct Project {
/// embedded, so projects render without the original files.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub luts: Vec<ProjectLut>,
+ /// Transcripts of media items (Text panel ▸ Transcript), keyed by the media item; word times
+ /// are media time. Shared (`Arc`) so undo snapshots don't copy them.
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub transcripts: BTreeMap<ItemId, std::sync::Arc<Transcript>>,
}
/// A LUT imported into the project (`lut.import`). Lumetri refers to it as `lib:<id>`.
@@ -910,6 +916,7 @@ impl Project {
items: BTreeMap::new(),
next_id: 1,
luts: Vec::new(),
+ transcripts: BTreeMap::new(),
}
}
diff --git a/crates/project/src/transcript.rs b/crates/project/src/transcript.rs
new file mode 100644
index 000000000..5c9d68ab1
--- /dev/null
+++ b/crates/project/src/transcript.rs
@@ -0,0 +1,175 @@
+//! Transcripts of media clips (Text panel ▸ Transcript).
+//!
+//! A [`Transcript`] belongs to one media item (`Project::transcripts`, keyed by the item id) and
+//! lists the spoken [`Word`]s with their **media-time** bounds, so it stays valid however the clip
+//! is trimmed, moved or reused: the sequence transcript is derived from the clip transcripts by
+//! mapping each word through the track items that show it (`filmcraft_edit::transcript`).
+//!
+//! Speakers are numbered per transcript (`Word::speaker` indexes [`Transcript::speakers`]); the
+//! Text panel shows and renames them by name, so two clips whose speakers share a name read as one
+//! speaker in the sequence transcript.
+
+use filmcraft_time::{Tick, TimeRange};
+use serde::{Deserialize, Serialize};
+
+/// One transcribed word.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Word {
+ /// The word as written, with attached punctuation (`"Hello,"`). No surrounding spaces.
+ pub text: String,
+ /// Media time of the word's first sample.
+ pub start: Tick,
+ /// Media time just after the word (exclusive).
+ pub end: Tick,
+ /// Index into [`Transcript::speakers`].
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub speaker: Option<u32>,
+ /// Recogniser confidence 0..1 (1 for hand-made or corrected words).
+ #[serde(default = "one", skip_serializing_if = "is_one")]
+ pub confidence: f32,
+}
+
+fn one() -> f32 {
+ 1.0
+}
+fn is_one(v: &f32) -> bool {
+ *v == 1.0
+}
+
+impl Word {
+ pub fn new(text: impl Into<String>, start: Tick, end: Tick) -> Self {
+ Self { text: text.into(), start, end, speaker: None, confidence: 1.0 }
+ }
+ pub fn range(&self) -> TimeRange {
+ TimeRange::from_bounds(self.start, self.end.max(self.start))
+ }
+ /// Lower-case text without leading/trailing punctuation (`"Um,"` → `"um"`), for search and
+ /// filler-word matching.
+ pub fn normalized(&self) -> String {
+ normalize_word(&self.text)
+ }
+}
+
+/// Lower-case `s` and trim punctuation and symbols from both ends (apostrophes inside a word stay:
+/// `"Don't!"` → `"don't"`).
+pub fn normalize_word(s: &str) -> String {
+ s.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase()
+}
+
+/// A speaker label.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Speaker {
+ pub name: String,
+}
+
+/// The transcript of one media item.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Transcript {
+ /// ISO 639-1 code of the spoken language (`"en"`).
+ pub language: String,
+ /// What produced it: a model id (`"whisper-base"`), `"imported"` or `"manual"`.
+ pub source: String,
+ pub speakers: Vec<Speaker>,
+ /// Words in time order, non-overlapping.
+ pub words: Vec<Word>,
+}
+
+impl Transcript {
+ /// The speaker name of `word` (`"Speaker 2"` when the label list is short; `None` when the word
+ /// has no speaker).
+ pub fn speaker_name(&self, word: &Word) -> Option<String> {
+ let i = word.speaker? as usize;
+ Some(self.speakers.get(i).map(|s| s.name.clone()).unwrap_or_else(|| format!("Speaker {}", i + 1)))
+ }
+
+ /// The text of all words joined by spaces.
+ pub fn text(&self) -> String {
+ self.words.iter().map(|w| w.text.as_str()).collect::<Vec<_>>().join(" ")
+ }
+
+ /// Indices of the words overlapping the media range.
+ pub fn words_in(&self, r: TimeRange) -> std::ops::Range<usize> {
+ let a = self.words.partition_point(|w| w.end <= r.start);
+ let b = self.words.partition_point(|w| w.start < r.end());
+ a..b.max(a)
+ }
+
+ /// Sort words by time and make the transcript well formed: empty words dropped, `end >= start`,
+ /// no overlaps (a word ends at the next one's start at the latest), speaker indices in range
+ /// (missing labels are added as "Speaker N").
+ pub fn normalize(&mut self) {
+ self.words.retain(|w| !w.text.trim().is_empty());
+ for w in &mut self.words {
+ w.text = w.text.trim().to_string();
+ if w.end < w.start {
+ w.end = w.start;
+ }
+ w.confidence = w.confidence.clamp(0.0, 1.0);
+ }
+ self.words.sort_by_key(|w| (w.start, w.end));
+ for i in 1..self.words.len() {
+ let s = self.words[i].start;
+ if self.words[i - 1].end > s {
+ self.words[i - 1].end = s.max(self.words[i - 1].start);
+ }
+ }
+ let max = self.words.iter().filter_map(|w| w.speaker).max();
+ if let Some(m) = max {
+ while self.speakers.len() <= m as usize {
+ let n = self.speakers.len() + 1;
+ self.speakers.push(Speaker { name: format!("Speaker {n}") });
+ }
+ }
+ }
+
+ /// Validate the invariants [`Transcript::normalize`] establishes.
+ pub fn check(&self) -> Result<(), String> {
+ for (i, w) in self.words.iter().enumerate() {
+ if w.end < w.start {
+ return Err(format!("word {i} ({:?}) ends before it starts", w.text));
+ }
+ if i > 0 && self.words[i - 1].end > w.start {
+ return Err(format!("word {i} ({:?}) overlaps the word before it", w.text));
+ }
+ if let Some(s) = w.speaker
+ && s as usize >= self.speakers.len()
+ {
+ return Err(format!("word {i} has speaker {s}, but there are {} speakers", self.speakers.len()));
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn w(t: &str, a: i64, b: i64) -> Word {
+ Word::new(t, Tick(a), Tick(b))
+ }
+
+ #[test]
+ fn normalize_sorts_clamps_and_labels() {
+ let mut t = Transcript { words: vec![w("b", 10, 30), w(" a ", 0, 15), w("", 40, 50), w("c", 35, 20)], ..Default::default() };
+ t.words[0].speaker = Some(1);
+ t.normalize();
+ assert_eq!(t.words.iter().map(|w| w.text.as_str()).collect::<Vec<_>>(), ["a", "b", "c"]);
+ assert_eq!(t.words[0].end, Tick(10));
+ assert_eq!(t.words[2].end, Tick(35));
+ assert_eq!(t.speakers.len(), 2);
+ assert_eq!(t.speaker_name(&t.words[1]).as_deref(), Some("Speaker 2"));
+ t.check().unwrap();
+ }
+
+ #[test]
+ fn words_in_range_and_normalized() {
+ let t = Transcript { words: vec![w("Um,", 0, 10), w("Don't!", 10, 20), w("go", 25, 30)], ..Default::default() };
+ assert_eq!(t.words_in(TimeRange::from_bounds(Tick(5), Tick(24))), 0..2);
+ assert_eq!(t.words_in(TimeRange::from_bounds(Tick(20), Tick(25))), 2..2);
+ assert_eq!(t.words[0].normalized(), "um");
+ assert_eq!(t.words[1].normalized(), "don't");
+ assert_eq!(t.text(), "Um, Don't! go");
+ }
+}
diff --git a/crates/speech/Cargo.toml b/crates/speech/Cargo.toml
new file mode 100644
index 000000000..67f6d8fd6
--- /dev/null
+++ b/crates/speech/Cargo.toml
@@ -0,0 +1,35 @@
+[package]
+name = "filmcraft-speech"
+description = "FilmCraft speech-to-text: the Transcriber trait, the Whisper model catalogue and downloader, pure-Rust Whisper inference (candle) with word timestamps, and speaker labelling"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[features]
+default = []
+# Whisper inference on the CPU via candle (pure Rust). Off by default (and in wasm builds).
+whisper = ["dep:candle-core", "dep:candle-nn"]
+# Model downloads over HTTPS (pure-Rust TLS: rustls + RustCrypto, OS certificate verification).
+download = ["dep:ureq", "dep:rustls", "dep:rustls-rustcrypto", "dep:sha2"]
+
+[dependencies]
+filmcraft-time = { workspace = true }
+filmcraft-project = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+candle-core = { version = "0.9", default-features = false, optional = true }
+candle-nn = { version = "0.9", default-features = false, optional = true }
+rayon = { workspace = true }
+ureq = { version = "3", default-features = false, features = ["rustls-no-provider", "platform-verifier"], optional = true }
+rustls = { version = "0.23", default-features = false, optional = true }
+rustls-rustcrypto = { version = "0.0.2-alpha", optional = true }
+sha2 = { version = "0.10", optional = true }
+
+[[example]]
+name = "transcribe"
+required-features = ["whisper"]
diff --git a/crates/speech/README.md b/crates/speech/README.md
new file mode 100644
index 000000000..a411bda16
--- /dev/null
+++ b/crates/speech/README.md
@@ -0,0 +1,21 @@
+# filmcraft-speech
+
+Speech-to-text for FilmCraft's Text panel ▸ Transcript (L2). User-facing behaviour, commands and
+model handling: [docs/transcripts.md](../../docs/transcripts.md).
+
+- `Transcriber` trait (mono 16 kHz in, word-timed `filmcraft_project::Transcript` out) and
+ `FixedTranscriber` for tests and agents.
+- `models`: Whisper model catalogue (pinned revisions, SHA-256, sizes, licences) and, with feature
+ `download`, the verified downloader (ureq + rustls + RustCrypto). Weights are never bundled.
+- `whisper` (feature `whisper`): Whisper inference on candle (CPU, pure Rust).
+- `mel`, `vad`, `diarize`: log-mel front end, word-bound tightening, MFCC-clustering speaker labels.
+
+Both features are off by default and are never enabled for wasm (`cargo xtask wasm` checks the
+crate without them).
+
+## References
+
+Implemented from the published description of the model: A. Radford et al., "Robust Speech
+Recognition via Large-Scale Weak Supervision" (OpenAI, 2022), the model cards and configuration
+files published with the weights (`config.json`, `generation_config.json`, `tokenizer.json`), and
+the candle tensor library's public API. Weights: OpenAI Whisper, MIT licence.
diff --git a/crates/speech/examples/transcribe.rs b/crates/speech/examples/transcribe.rs
new file mode 100644
index 000000000..8d7beaa67
--- /dev/null
+++ b/crates/speech/examples/transcribe.rs
@@ -0,0 +1,65 @@
+//! Transcribe raw mono 16 kHz f32 files and report the word error rate against `<file>.txt`.
+//!
+//! ```sh
+//! ffmpeg -i speech.flac -ar 16000 -ac 1 -f f32le speech.f32
+//! cargo run --release -p filmcraft-speech --features whisper --example transcribe -- <model dir> [--words] [--diarize] speech.f32…
+//! ```
+
+use filmcraft_speech::{Options, Transcriber, word_error_rate};
+
+fn main() {
+ let mut args = std::env::args().skip(1);
+ let dir = std::path::PathBuf::from(args.next().expect("model dir"));
+ let id = dir.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
+ let t0 = std::time::Instant::now();
+ let w = filmcraft_speech::whisper::Whisper::load(&dir, &id).expect("load");
+ eprintln!("loaded {id} in {:.2}s", t0.elapsed().as_secs_f64());
+ let mut show_words = false;
+ let mut diarize = false;
+ let mut language = None;
+ let (mut errs, mut words, mut audio_s, mut cpu_s) = (0.0, 0usize, 0.0, 0.0);
+ for a in args {
+ match a.as_str() {
+ "--words" => show_words = true,
+ "--diarize" => diarize = true,
+ l if l.starts_with("--lang=") => language = Some(l[7..].to_string()),
+ p => {
+ let audio: Vec<f32> = std::fs::read(p).expect("read").chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
+ let t1 = std::time::Instant::now();
+ let opts = Options { language: language.clone(), diarize, ..Default::default() };
+ let t = w.transcribe(&audio, &opts, &mut |_, _| true).expect("transcribe");
+ let secs = t1.elapsed().as_secs_f64();
+ audio_s += audio.len() as f64 / 16_000.0;
+ cpu_s += secs;
+ let hyp = t.text();
+ print!("{p} [{} {:.1}s]: {hyp}", t.language, secs);
+ if let Ok(r) = std::fs::read_to_string(std::path::Path::new(p).with_extension("txt")) {
+ let n = r.split_whitespace().count();
+ let e = word_error_rate(&r, &hyp);
+ errs += e * n as f64;
+ words += n;
+ print!(" (WER {:.1}%)", e * 100.0);
+ }
+ println!();
+ if show_words {
+ for x in &t.words {
+ println!(
+ " {:7.2} {:7.2} {:>3} {}",
+ x.start.0 as f64 / 254_016_000_000.0,
+ x.end.0 as f64 / 254_016_000_000.0,
+ x.speaker.map(|s| s.to_string()).unwrap_or_default(),
+ x.text
+ );
+ }
+ }
+ }
+ }
+ }
+ if words > 0 {
+ println!(
+ "total WER {:.2}% over {words} words; {audio_s:.1}s of audio in {cpu_s:.1}s ({:.1}× realtime)",
+ errs / words as f64 * 100.0,
+ audio_s / cpu_s.max(1e-9)
+ );
+ }
+}
diff --git a/crates/speech/src/diarize.rs b/crates/speech/src/diarize.rs
new file mode 100644
index 000000000..3271b0257
--- /dev/null
+++ b/crates/speech/src/diarize.rs
@@ -0,0 +1,332 @@
+//! Speaker labelling ("who spoke when") without a model.
+//!
+//! A classical, openly documented method (MFCC statistics + agglomerative clustering, as in the
+//! speaker-clustering literature, e.g. Reynolds & Torres-Carrasquillo 2005; no code or data from
+//! any implementation is used):
+//!
+//! 1. The transcript's words are grouped into **chunks**: a new chunk starts at a pause of at least
+//! [`Params::chunk_gap`] or when the chunk reaches [`Params::max_chunk`]; chunks shorter than
+//! [`Params::min_chunk`] are joined to the previous one.
+//! 2. Each chunk gets a voice vector: 40-band log-mel energies → DCT → MFCC 1–19 over the chunk's
+//! voiced frames (within 30 dB of its loudest), then the mean and standard deviation of each
+//! coefficient (38 values), each scaled by that coefficient's spread over all voiced frames of
+//! the file.
+//! 3. Average-linkage agglomerative clustering with RMS distance merges the closest clusters
+//! until the closest pair is farther apart than [`Params::threshold`] or only
+//! `max_speakers` remain. Clusters holding less than 5 % of the speech are folded into their
+//! nearest neighbour.
+//! 4. Speakers are numbered in order of first appearance ("Speaker 1", "Speaker 2"…).
+//!
+//! It works for interviews and dialogue with distinct voices and clean turns; overlapping speech,
+//! very similar voices or music beds confuse it. Labels are editable in the Text panel (rename a
+//! speaker, or assign words to a speaker by hand), which is the fallback when it gets them wrong.
+
+use filmcraft_project::{Speaker, Transcript};
+use filmcraft_time::Tick;
+
+use crate::{SAMPLE_RATE, TICKS_PER_SAMPLE};
+
+/// Tunables (defaults chosen on LibriSpeech test-clean dialogues; see `docs/transcripts.md`).
+#[derive(Clone, Debug, PartialEq)]
+pub struct Params {
+ pub chunk_gap: Tick,
+ pub min_chunk: Tick,
+ pub max_chunk: Tick,
+ pub threshold: f32,
+ pub max_speakers: usize,
+}
+
+impl Default for Params {
+ fn default() -> Self {
+ let ms = |m: i64| Tick(m * TICKS_PER_SAMPLE * SAMPLE_RATE as i64 / 1000);
+ Self { chunk_gap: ms(250), min_chunk: ms(700), max_chunk: ms(4000), threshold: 0.4, max_speakers: 6 }
+ }
+}
+
+const N_MELS: usize = 40;
+const N_MFCC: usize = 20;
+const FRAME_TICKS: i64 = TICKS_PER_SAMPLE * crate::mel::HOP as i64;
+
+/// Word index ranges of the chunks.
+pub fn chunks(t: &Transcript, p: &Params) -> Vec<std::ops::Range<usize>> {
+ let w = &t.words;
+ let mut out: Vec<std::ops::Range<usize>> = Vec::new();
+ let mut a = 0;
+ for i in 1..=w.len() {
+ if i == w.len() || w[i].start - w[i - 1].end >= p.chunk_gap || w[i].end - w[a].start > p.max_chunk {
+ if a < i {
+ out.push(a..i);
+ }
+ a = i;
+ }
+ }
+ // join short chunks to the previous one
+ let mut merged: Vec<std::ops::Range<usize>> = Vec::new();
+ for c in out {
+ let dur = w[c.end - 1].end - w[c.start].start;
+ match merged.last_mut() {
+ Some(l) if dur < p.min_chunk => l.end = c.end,
+ _ => merged.push(c),
+ }
+ }
+ // a short first chunk joins the next
+ if merged.len() > 1 && w[merged[0].end - 1].end - w[0].start < p.min_chunk {
+ let first = merged.remove(0);
+ merged[0].start = first.start;
+ }
+ merged
+}
+
+fn mfcc_frames(audio: &[f32]) -> (usize, Vec<f32>, Vec<f32>) {
+ let (frames, mel) = crate::mel::mel_energies(audio, N_MELS);
+ // per frame: log energies (dB-ish) and the DCT-II of the log mel
+ let mut energy = vec![0f32; frames];
+ let mut mfcc = vec![0f32; frames * N_MFCC];
+ let dct: Vec<f32> = (0..N_MFCC * N_MELS)
+ .map(|i| {
+ let (k, m) = (i / N_MELS, i % N_MELS);
+ (std::f32::consts::PI * k as f32 * (m as f32 + 0.5) / N_MELS as f32).cos()
+ })
+ .collect();
+ let mut lm = [0f32; N_MELS];
+ for f in 0..frames {
+ let mut e = 0f32;
+ for m in 0..N_MELS {
+ let v = mel[m * frames + f];
+ e += v;
+ lm[m] = (v + 1e-10).ln();
+ }
+ energy[f] = 10.0 * (e + 1e-10).log10();
+ for k in 0..N_MFCC {
+ mfcc[f * N_MFCC + k] = (0..N_MELS).map(|m| dct[k * N_MELS + m] * lm[m]).sum();
+ }
+ }
+ (frames, energy, mfcc)
+}
+
+fn rms_distance(a: &[f32], b: &[f32]) -> f32 {
+ (a.iter().zip(b).map(|(x, y)| (x - y).powi(2)).sum::<f32>() / a.len().max(1) as f32).sqrt()
+}
+
+/// Label the speakers of `t` from `audio` (mono 16 kHz, the transcript's time base). Replaces
+/// `t.speakers` and every word's speaker; returns the number of speakers found.
+pub fn diarize(audio: &[f32], t: &mut Transcript, p: &Params) -> usize {
+ let ch = chunks(t, p);
+ if t.words.is_empty() {
+ return 0;
+ }
+ let one = |t: &mut Transcript| {
+ t.speakers = vec![Speaker { name: "Speaker 1".into() }];
+ for w in &mut t.words {
+ w.speaker = Some(0);
+ }
+ 1
+ };
+ if ch.len() < 2 {
+ return one(t);
+ }
+ let (frames, energy, mfcc) = mfcc_frames(audio);
+ // chunk vectors: mean and std of MFCC 1..N over voiced frames
+ let dim = 2 * (N_MFCC - 1);
+ let mut vecs: Vec<Vec<f32>> = Vec::new();
+ let mut weight: Vec<f32> = Vec::new();
+ for c in &ch {
+ let a = ((t.words[c.start].start.0 / FRAME_TICKS).max(0) as usize).min(frames);
+ let b = ((t.words[c.end - 1].end.0 / FRAME_TICKS).max(0) as usize).min(frames).max(a);
+ let peak = energy[a..b].iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ let voiced: Vec<usize> = (a..b).filter(|&f| energy[f] > peak - 30.0).collect();
+ let mut v = vec![0f32; dim];
+ if !voiced.is_empty() {
+ let n = voiced.len() as f32;
+ for k in 1..N_MFCC {
+ let mean = voiced.iter().map(|&f| mfcc[f * N_MFCC + k]).sum::<f32>() / n;
+ let var = voiced.iter().map(|&f| (mfcc[f * N_MFCC + k] - mean).powi(2)).sum::<f32>() / n;
+ v[k - 1] = mean;
+ v[N_MFCC - 1 + k - 1] = var.sqrt();
+ }
+ }
+ vecs.push(v);
+ weight.push(voiced.len() as f32);
+ }
+ // scale each dimension by its spread over all voiced frames of the file (an absolute yardstick:
+ // one voice stays close to itself however many chunks there are)
+ let all: Vec<usize> = {
+ let peak = energy.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ (0..frames).filter(|&f| energy[f] > peak - 40.0).collect()
+ };
+ let nf = all.len().max(1) as f32;
+ for k in 1..N_MFCC {
+ let mean = all.iter().map(|&f| mfcc[f * N_MFCC + k]).sum::<f32>() / nf;
+ let sd = (all.iter().map(|&f| (mfcc[f * N_MFCC + k] - mean).powi(2)).sum::<f32>() / nf).sqrt().max(1e-6);
+ for v in &mut vecs {
+ v[k - 1] = (v[k - 1] - mean) / sd;
+ v[N_MFCC - 1 + k - 1] /= sd;
+ }
+ }
+ // average-linkage agglomerative clustering
+ let n = vecs.len();
+ let mut dist = vec![0f32; n * n];
+ for i in 0..n {
+ for j in i + 1..n {
+ let d = rms_distance(&vecs[i], &vecs[j]);
+ dist[i * n + j] = d;
+ dist[j * n + i] = d;
+ }
+ }
+ let mut clusters: Vec<Vec<usize>> = (0..n).map(|i| vec![i]).collect();
+ let link = |a: &[usize], b: &[usize]| -> f32 {
+ let mut s = 0f32;
+ for &i in a {
+ for &j in b {
+ s += dist[i * n + j];
+ }
+ }
+ s / (a.len() * b.len()) as f32
+ };
+ let max_speakers = p.max_speakers.max(1);
+ loop {
+ if clusters.len() <= 1 {
+ break;
+ }
+ let mut best = (f32::INFINITY, 0, 0);
+ for i in 0..clusters.len() {
+ for j in i + 1..clusters.len() {
+ let d = link(&clusters[i], &clusters[j]);
+ if d < best.0 {
+ best = (d, i, j);
+ }
+ }
+ }
+ if best.0 > p.threshold && clusters.len() <= max_speakers {
+ break;
+ }
+ let b = clusters.remove(best.2);
+ clusters[best.1].extend(b);
+ }
+ // fold clusters with < 5 % of the voiced frames into their nearest neighbour
+ let total: f32 = weight.iter().sum::<f32>().max(1.0);
+ loop {
+ if clusters.len() <= 1 {
+ break;
+ }
+ let small = clusters.iter().position(|c| c.iter().map(|&i| weight[i]).sum::<f32>() < 0.05 * total);
+ let Some(si) = small else { break };
+ let s = clusters.remove(si);
+ let near = (0..clusters.len()).min_by(|&a, &b| link(&s, &clusters[a]).total_cmp(&link(&s, &clusters[b]))).unwrap_or(0);
+ clusters[near].extend(s);
+ }
+ if clusters.len() == 1 {
+ return one(t);
+ }
+ // number speakers by first appearance
+ let mut label = vec![0usize; n];
+ for (ci, c) in clusters.iter().enumerate() {
+ for &i in c {
+ label[i] = ci;
+ }
+ }
+ let mut order: Vec<usize> = Vec::new();
+ for &l in &label {
+ if !order.contains(&l) {
+ order.push(l);
+ }
+ }
+ for (k, c) in ch.iter().enumerate() {
+ let sp = order.iter().position(|&o| o == label[k]).unwrap_or(0) as u32;
+ for w in &mut t.words[c.clone()] {
+ w.speaker = Some(sp);
+ }
+ }
+ t.speakers = (0..order.len()).map(|i| Speaker { name: format!("Speaker {}", i + 1) }).collect();
+ order.len()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::seconds_tick;
+ use filmcraft_project::Word;
+
+ /// A synthetic "voice": a pulse train at `f0` through two resonances (formants), with a slow
+ /// syllable envelope.
+ fn voice(f0: f32, formants: [(f32, f32); 2], secs: f32, seed: u32) -> Vec<f32> {
+ let n = (secs * 16_000.0) as usize;
+ let mut out = vec![0f32; n];
+ let mut phase = 0f32;
+ let mut st = [[0f32; 2]; 2];
+ let mut rng = seed;
+ for (i, o) in out.iter_mut().enumerate() {
+ let t = i as f32 / 16_000.0;
+ let jitter = 1.0 + 0.03 * (2.0 * std::f32::consts::PI * 5.0 * t).sin();
+ phase += f0 * jitter / 16_000.0;
+ let mut x = if phase >= 1.0 {
+ phase -= 1.0;
+ 1.0
+ } else {
+ 0.0
+ };
+ rng = rng.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
+ x += ((rng >> 8) as f32 / (1u32 << 24) as f32 - 0.5) * 0.02;
+ let mut y = 0f32;
+ for (k, (fc, bw)) in formants.iter().enumerate() {
+ let r = (-std::f32::consts::PI * bw / 16_000.0).exp();
+ let a1 = 2.0 * r * (2.0 * std::f32::consts::PI * fc / 16_000.0).cos();
+ let a2 = -r * r;
+ let v = x + a1 * st[k][0] + a2 * st[k][1];
+ st[k][1] = st[k][0];
+ st[k][0] = v;
+ y += v;
+ }
+ let env = (std::f32::consts::PI * (t * 4.0).fract()).sin().max(0.0);
+ *o = y * env * 0.05;
+ }
+ out
+ }
+
+ #[test]
+ fn two_synthetic_voices_are_told_apart() {
+ let a = |s| voice(110.0, [(600.0, 90.0), (1100.0, 120.0)], 2.0, s);
+ let b = |s| voice(230.0, [(400.0, 80.0), (2600.0, 150.0)], 2.0, s);
+ let silence = vec![0f32; 8000];
+ let turns = [true, false, true, true, false, false, true, false];
+ let mut audio = Vec::new();
+ let mut words = Vec::new();
+ for (k, &is_a) in turns.iter().enumerate() {
+ let t0 = audio.len() as f64 / 16_000.0;
+ audio.extend(if is_a { a(k as u32) } else { b(k as u32) });
+ // four 0.5 s "words" per turn
+ for w in 0..4 {
+ let s = t0 + w as f64 * 0.5;
+ words.push(Word::new(format!("w{k}.{w}"), seconds_tick(s), seconds_tick(s + 0.45)));
+ }
+ audio.extend(&silence);
+ }
+ let mut t = Transcript { words, ..Default::default() };
+ let n = diarize(&audio, &mut t, &Params::default());
+ assert_eq!(n, 2);
+ for (k, &is_a) in turns.iter().enumerate() {
+ let want = if is_a { 0 } else { 1 };
+ for w in &t.words[k * 4..k * 4 + 4] {
+ assert_eq!(w.speaker, Some(want), "turn {k}");
+ }
+ }
+ assert_eq!(t.speakers[1].name, "Speaker 2");
+ t.check().unwrap();
+ }
+
+ #[test]
+ fn one_voice_is_one_speaker() {
+ let audio = voice(140.0, [(500.0, 90.0), (1500.0, 120.0)], 12.0, 1);
+ let words = (0..20).map(|i| Word::new("x", seconds_tick(i as f64 * 0.6), seconds_tick(i as f64 * 0.6 + 0.4))).collect();
+ let mut t = Transcript { words, ..Default::default() };
+ assert_eq!(diarize(&audio, &mut t, &Params::default()), 1);
+ assert!(t.words.iter().all(|w| w.speaker == Some(0)));
+ }
+
+ #[test]
+ fn chunks_split_at_pauses_and_join_short_ones() {
+ let w = |a: f64, b: f64| Word::new("x", seconds_tick(a), seconds_tick(b));
+ let t = Transcript { words: vec![w(0.0, 0.5), w(0.5, 1.0), w(2.0, 2.2), w(3.0, 3.6), w(3.6, 4.4)], ..Default::default() };
+ assert_eq!(chunks(&t, &Params::default()), vec![0..3, 3..5]);
+ }
+}
diff --git a/crates/speech/src/lib.rs b/crates/speech/src/lib.rs
new file mode 100644
index 000000000..68922daeb
--- /dev/null
+++ b/crates/speech/src/lib.rs
@@ -0,0 +1,206 @@
+//! Speech-to-text for FilmCraft's Text panel ▸ Transcript.
+//!
+//! - [`Transcriber`]: the trait every speech recogniser implements. It takes mono 16 kHz samples
+//! and returns a [`Transcript`] whose words carry media-time bounds (`Tick`s; one 16 kHz sample
+//! is exactly 15 876 000 ticks).
+//! - [`models`]: the catalogue of downloadable Whisper models (source URL pinned to a revision,
+//! SHA-256, size, licence), where they live in the per-user data directory, and (feature
+//! `download`) the verified downloader. Weights are **never** bundled or committed.
+//! - [`whisper`] (feature `whisper`): Whisper inference in pure Rust on candle, with timestamp
+//! decoding, language detection and word-level timestamps from cross-attention alignment (DTW).
+//! - [`diarize`]: speaker labelling by clustering per-chunk MFCC statistics (classical, no model).
+//! - [`mel`]: the log-mel front end shared by Whisper and diarization.
+//! - [`vad`]: energy-based tightening of word bounds (keeps pauses out of words).
+//!
+//! See `docs/transcripts.md` for the user-facing behaviour and accuracy numbers.
+
+pub mod diarize;
+pub mod mel;
+pub mod models;
+pub mod vad;
+#[cfg(feature = "whisper")]
+pub mod whisper;
+
+use filmcraft_project::Transcript;
+use filmcraft_time::{TICKS_PER_SECOND, Tick};
+
+/// The sample rate every transcriber takes.
+pub const SAMPLE_RATE: u32 = 16_000;
+
+/// Ticks per 16 kHz sample (exact).
+pub const TICKS_PER_SAMPLE: i64 = TICKS_PER_SECOND / SAMPLE_RATE as i64;
+
+/// Media time of a 16 kHz sample index.
+pub fn sample_tick(n: i64) -> Tick {
+ Tick(n * TICKS_PER_SAMPLE)
+}
+
+/// Media time of `s` seconds (rounded to the nearest 16 kHz sample).
+pub fn seconds_tick(s: f64) -> Tick {
+ sample_tick((s * SAMPLE_RATE as f64).round() as i64)
+}
+
+#[derive(Debug, Clone, PartialEq, thiserror::Error)]
+pub enum SpeechError {
+ #[error("stopped")]
+ Cancelled,
+ #[error("the speech model `{0}` is not downloaded")]
+ NotInstalled(String),
+ #[error("unknown speech model `{0}`")]
+ UnknownModel(String),
+ #[error("speech-to-text is not available in this build ({0})")]
+ Unavailable(String),
+ #[error("model: {0}")]
+ Model(String),
+ #[error("download: {0}")]
+ Download(String),
+ #[error("{0}")]
+ Io(String),
+}
+
+impl From<std::io::Error> for SpeechError {
+ fn from(e: std::io::Error) -> Self {
+ SpeechError::Io(e.to_string())
+ }
+}
+
+/// Transcription options.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Options {
+ /// ISO 639-1 language code; `None` = detect from the first 30 s.
+ pub language: Option<String>,
+ /// Label speakers ([`diarize`]); otherwise every word gets speaker 0.
+ pub diarize: bool,
+ /// Upper bound for the number of speakers found.
+ pub max_speakers: usize,
+}
+
+impl Default for Options {
+ fn default() -> Self {
+ Self { language: None, diarize: true, max_speakers: 6 }
+ }
+}
+
+/// Progress callback: `(fraction 0..1, status)`; return `false` to cancel.
+pub type ProgressFn<'a> = &'a mut dyn FnMut(f32, &str) -> bool;
+
+/// A speech recogniser.
+pub trait Transcriber: Send + Sync {
+ /// Stable id of the model (`"whisper-base"`), stored in the transcript's `source`.
+ fn id(&self) -> String;
+ /// Transcribe mono 16 kHz `audio`. Word times are relative to the first sample.
+ fn transcribe(&self, audio: &[f32], opts: &Options, progress: ProgressFn) -> Result<Transcript, SpeechError>;
+}
+
+/// A transcriber that returns a fixed transcript (tests, demos and agents that bring their own
+/// transcript); words beyond the audio's length are dropped.
+pub struct FixedTranscriber {
+ pub transcript: Transcript,
+ pub id: String,
+}
+
+impl Transcriber for FixedTranscriber {
+ fn id(&self) -> String {
+ self.id.clone()
+ }
+ fn transcribe(&self, audio: &[f32], _: &Options, progress: ProgressFn) -> Result<Transcript, SpeechError> {
+ if !progress(0.5, "Transcribing") {
+ return Err(SpeechError::Cancelled);
+ }
+ let end = sample_tick(audio.len() as i64);
+ let mut t = self.transcript.clone();
+ t.words.retain(|w| w.start < end);
+ t.source = self.id.clone();
+ progress(1.0, "Done");
+ Ok(t)
+ }
+}
+
+/// Load the transcriber for catalogue model `id` from `models_dir` (feature `whisper`).
+pub fn load(models_dir: &std::path::Path, id: &str) -> Result<std::sync::Arc<dyn Transcriber>, SpeechError> {
+ let m = models::find(id).ok_or_else(|| SpeechError::UnknownModel(id.into()))?;
+ if !models::installed(models_dir, m) {
+ return Err(SpeechError::NotInstalled(id.into()));
+ }
+ #[cfg(feature = "whisper")]
+ {
+ Ok(std::sync::Arc::new(whisper::Whisper::load(&models::model_dir(models_dir, m), m.id)?))
+ }
+ #[cfg(not(feature = "whisper"))]
+ {
+ Err(SpeechError::Unavailable("built without the `whisper` feature".into()))
+ }
+}
+
+/// Whether this build can run speech models.
+pub const fn available() -> bool {
+ cfg!(feature = "whisper")
+}
+
+/// Mix a multi-channel buffer down to mono.
+pub fn downmix(channels: &[Vec<f32>]) -> Vec<f32> {
+ let n = channels.iter().map(Vec::len).min().unwrap_or(0);
+ if channels.len() == 1 {
+ return channels[0][..n].to_vec();
+ }
+ let k = 1.0 / channels.len().max(1) as f32;
+ (0..n).map(|i| channels.iter().map(|c| c[i]).sum::<f32>() * k).collect()
+}
+
+/// Word error rate between a reference and a hypothesis (words compared case-insensitively
+/// without punctuation, hyphenated words split): (substitutions + deletions + insertions) / reference words.
+pub fn word_error_rate(reference: &str, hypothesis: &str) -> f64 {
+ let norm = |s: &str| -> Vec<String> {
+ s.split(|c: char| c.is_whitespace() || c == '-').map(filmcraft_project::transcript::normalize_word).filter(|w| !w.is_empty()).collect()
+ };
+ let (r, h) = (norm(reference), norm(hypothesis));
+ if r.is_empty() {
+ return if h.is_empty() { 0.0 } else { 1.0 };
+ }
+ let mut prev: Vec<usize> = (0..=h.len()).collect();
+ for i in 1..=r.len() {
+ let mut cur = vec![i; h.len() + 1];
+ for j in 1..=h.len() {
+ let sub = prev[j - 1] + usize::from(r[i - 1] != h[j - 1]);
+ cur[j] = sub.min(prev[j] + 1).min(cur[j - 1] + 1);
+ }
+ prev = cur;
+ }
+ prev[h.len()] as f64 / r.len() as f64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use filmcraft_project::Word;
+
+ #[test]
+ fn sample_ticks_are_exact() {
+ assert_eq!(TICKS_PER_SAMPLE * SAMPLE_RATE as i64, TICKS_PER_SECOND);
+ assert_eq!(seconds_tick(1.5), Tick(TICKS_PER_SECOND * 3 / 2));
+ }
+
+ #[test]
+ fn wer_counts_edits() {
+ assert_eq!(word_error_rate("the cat sat", "The cat, sat."), 0.0);
+ assert!((word_error_rate("the cat sat on the mat", "the cat sat on mat") - 1.0 / 6.0).abs() < 1e-9);
+ assert!((word_error_rate("a b", "a x b y") - 1.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn fixed_transcriber_trims_and_cancels() {
+ let mut t = Transcript::default();
+ t.words.push(Word::new("hi", seconds_tick(0.1), seconds_tick(0.3)));
+ t.words.push(Word::new("late", seconds_tick(5.0), seconds_tick(5.5)));
+ let f = FixedTranscriber { transcript: t, id: "fixed".into() };
+ let out = f.transcribe(&vec![0.0; 16_000], &Options::default(), &mut |_, _| true).unwrap();
+ assert_eq!(out.words.len(), 1);
+ assert_eq!(out.source, "fixed");
+ assert_eq!(f.transcribe(&[], &Options::default(), &mut |_, _| false), Err(SpeechError::Cancelled));
+ }
+
+ #[test]
+ fn downmix_averages() {
+ assert_eq!(downmix(&[vec![1.0, 0.0], vec![0.0, 0.0, 9.0]]), vec![0.5, 0.0]);
+ }
+}
diff --git a/crates/speech/src/mel.rs b/crates/speech/src/mel.rs
new file mode 100644
index 000000000..db44f9943
--- /dev/null
+++ b/crates/speech/src/mel.rs
@@ -0,0 +1,171 @@
+//! Log-mel spectrogram front end (Whisper's), computed from the published recipe:
+//! 16 kHz audio, 400-sample periodic Hann window, hop 160 (100 frames/s), reflect padding of
+//! 200 samples at both ends (centred frames), power spectrum, Slaney-style mel filterbank with
+//! Slaney area normalisation (0–8 kHz), `log10(max(x, 1e-10))`, floor at `max − 8`, then
+//! `(x + 4) / 4`. The last STFT frame is dropped, so `n` samples give `n / 160` frames.
+//!
+//! The filterbank is computed here, not loaded from a file.
+
+/// FFT size (25 ms).
+pub const N_FFT: usize = 400;
+/// Hop length (10 ms).
+pub const HOP: usize = 160;
+/// Frequency bins of the one-sided spectrum.
+pub const N_BINS: usize = N_FFT / 2 + 1;
+
+fn hz_to_mel(f: f64) -> f64 {
+ // Slaney: linear below 1 kHz, logarithmic above
+ let f_sp = 200.0 / 3.0;
+ let min_log_hz = 1000.0;
+ let min_log_mel = min_log_hz / f_sp;
+ let logstep = (6.4f64).ln() / 27.0;
+ if f >= min_log_hz { min_log_mel + (f / min_log_hz).ln() / logstep } else { f / f_sp }
+}
+
+fn mel_to_hz(m: f64) -> f64 {
+ let f_sp = 200.0 / 3.0;
+ let min_log_hz = 1000.0;
+ let min_log_mel = min_log_hz / f_sp;
+ let logstep = (6.4f64).ln() / 27.0;
+ if m >= min_log_mel { min_log_hz * (logstep * (m - min_log_mel)).exp() } else { f_sp * m }
+}
+
+/// Mel filterbank, `n_mels × N_BINS` row-major, for 16 kHz audio and a 400-point FFT.
+pub fn mel_filters(n_mels: usize) -> Vec<f32> {
+ let sr = 16_000.0;
+ let fftfreqs: Vec<f64> = (0..N_BINS).map(|i| i as f64 * sr / N_FFT as f64).collect();
+ let (lo, hi) = (hz_to_mel(0.0), hz_to_mel(sr / 2.0));
+ let mel_f: Vec<f64> = (0..n_mels + 2).map(|i| mel_to_hz(lo + (hi - lo) * i as f64 / (n_mels + 1) as f64)).collect();
+ let mut w = vec![0f32; n_mels * N_BINS];
+ for m in 0..n_mels {
+ let enorm = 2.0 / (mel_f[m + 2] - mel_f[m]);
+ for (k, &f) in fftfreqs.iter().enumerate() {
+ let lower = (f - mel_f[m]) / (mel_f[m + 1] - mel_f[m]);
+ let upper = (mel_f[m + 2] - f) / (mel_f[m + 2] - mel_f[m + 1]);
+ w[m * N_BINS + k] = (lower.min(upper).max(0.0) * enorm) as f32;
+ }
+ }
+ w
+}
+
+/// Power spectrum frames (`frames × N_BINS`) of `audio`, Whisper framing (see module docs).
+pub fn power_spectrum(audio: &[f32]) -> (usize, Vec<f32>) {
+ let pad = N_FFT / 2;
+ let n = audio.len();
+ // reflect padding (numpy "reflect": the edge sample is not repeated)
+ let at = |i: isize| -> f32 {
+ if n == 0 {
+ return 0.0;
+ }
+ if n == 1 {
+ return audio[0];
+ }
+ let p = 2 * (n as isize - 1);
+ let mut j = i.rem_euclid(p);
+ if j >= n as isize {
+ j = p - j;
+ }
+ audio[j as usize]
+ };
+ let frames = n / HOP; // the last centred frame (n / HOP + 1) is dropped
+ let window: Vec<f32> = (0..N_FFT).map(|i| (0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / N_FFT as f64).cos()) as f32).collect();
+ let (cos, sin) = twiddles();
+ let mut out = vec![0f32; frames * N_BINS];
+ let work = |f: usize, row: &mut [f32]| {
+ let mut x = [0f32; N_FFT];
+ let base = (f * HOP) as isize - pad as isize;
+ for (i, v) in x.iter_mut().enumerate() {
+ *v = at(base + i as isize) * window[i];
+ }
+ for (k, r) in row.iter_mut().enumerate() {
+ let (mut re, mut im) = (0f32, 0f32);
+ let (c, s) = (&cos[k * N_FFT..(k + 1) * N_FFT], &sin[k * N_FFT..(k + 1) * N_FFT]);
+ for i in 0..N_FFT {
+ re += x[i] * c[i];
+ im += x[i] * s[i];
+ }
+ *r = re * re + im * im;
+ }
+ };
+ {
+ use rayon::prelude::*;
+ out.par_chunks_mut(N_BINS).enumerate().for_each(|(f, row)| work(f, row));
+ }
+ (frames, out)
+}
+
+fn twiddles() -> (Vec<f32>, Vec<f32>) {
+ let mut c = vec![0f32; N_BINS * N_FFT];
+ let mut s = vec![0f32; N_BINS * N_FFT];
+ for k in 0..N_BINS {
+ for i in 0..N_FFT {
+ // index the angle table by (k·i mod N) so the f64 argument stays small and exact
+ let a = 2.0 * std::f64::consts::PI * ((k * i) % N_FFT) as f64 / N_FFT as f64;
+ c[k * N_FFT + i] = a.cos() as f32;
+ s[k * N_FFT + i] = -a.sin() as f32;
+ }
+ }
+ (c, s)
+}
+
+/// Mel energies `n_mels × frames` (row-major by mel band, like Whisper's input) before the log.
+pub fn mel_energies(audio: &[f32], n_mels: usize) -> (usize, Vec<f32>) {
+ let (frames, pow) = power_spectrum(audio);
+ let filters = mel_filters(n_mels);
+ let mut out = vec![0f32; n_mels * frames];
+ for f in 0..frames {
+ let p = &pow[f * N_BINS..(f + 1) * N_BINS];
+ for m in 0..n_mels {
+ let w = &filters[m * N_BINS..(m + 1) * N_BINS];
+ out[m * frames + f] = w.iter().zip(p).map(|(a, b)| a * b).sum();
+ }
+ }
+ (frames, out)
+}
+
+/// Whisper's normalised log-mel spectrogram, `n_mels × frames` row-major.
+pub fn log_mel(audio: &[f32], n_mels: usize) -> (usize, Vec<f32>) {
+ let (frames, mut m) = mel_energies(audio, n_mels);
+ for v in &mut m {
+ *v = v.max(1e-10).log10();
+ }
+ let max = m.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ for v in &mut m {
+ *v = (v.max(max - 8.0) + 4.0) / 4.0;
+ }
+ (frames, m)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn filterbank_shape_and_coverage() {
+ let w = mel_filters(80);
+ assert_eq!(w.len(), 80 * N_BINS);
+ // every band has weight, nothing is negative
+ for m in 0..80 {
+ let row = &w[m * N_BINS..(m + 1) * N_BINS];
+ assert!(row.iter().all(|v| *v >= 0.0));
+ assert!(row.iter().sum::<f32>() > 0.0, "band {m}");
+ }
+ // Slaney scale is linear below 1 kHz
+ assert!((hz_to_mel(500.0) - 7.5).abs() < 1e-9);
+ assert!((mel_to_hz(hz_to_mel(3000.0)) - 3000.0).abs() < 1e-6);
+ }
+
+ #[test]
+ fn a_tone_lands_in_its_band() {
+ let audio: Vec<f32> = (0..16_000).map(|i| (2.0 * std::f32::consts::PI * 1000.0 * i as f32 / 16_000.0).sin()).collect();
+ let (frames, m) = log_mel(&audio, 80);
+ assert_eq!(frames, 100);
+ let f = 50;
+ let col: Vec<f32> = (0..80).map(|b| m[b * frames + f]).collect();
+ let peak = col.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)).unwrap().0;
+ let w = mel_filters(80);
+ let k = 1000 * N_FFT / 16_000; // bin 25
+ let best = (0..80).max_by(|a, b| w[a * N_BINS + k].total_cmp(&w[b * N_BINS + k])).unwrap();
+ assert_eq!(peak, best);
+ }
+}
diff --git a/crates/speech/src/models.rs b/crates/speech/src/models.rs
new file mode 100644
index 000000000..74fc646c5
--- /dev/null
+++ b/crates/speech/src/models.rs
@@ -0,0 +1,318 @@
+//! The speech model catalogue and the model store.
+//!
+//! Models are downloaded on first use, after the user confirms (the dialog shows the size, the
+//! source URL and the licence), into `<data dir>/models/<id>/`. They are never bundled with
+//! FilmCraft or committed to the repository. Every file is pinned to a Hugging Face revision of
+//! OpenAI's own repositories and checked against its SHA-256 before it is used.
+//!
+//! Licence: OpenAI released the Whisper code and model weights under the MIT licence
+//! (<https://github.com/openai/whisper/blob/main/LICENSE>); the safetensors conversions OpenAI
+//! publishes at `huggingface.co/openai/whisper-*` are labelled Apache-2.0. Both are permissive.
+
+use std::path::{Path, PathBuf};
+
+use serde::Serialize;
+
+/// One file of a model.
+#[derive(Clone, Copy, Debug, Serialize)]
+pub struct ModelFile {
+ pub name: &'static str,
+ pub url: &'static str,
+ pub sha256: &'static str,
+ pub size: u64,
+}
+
+/// A downloadable speech model.
+#[derive(Clone, Copy, Debug, Serialize)]
+pub struct ModelInfo {
+ pub id: &'static str,
+ pub name: &'static str,
+ /// Recognises languages other than English (and detects the language).
+ pub multilingual: bool,
+ pub description: &'static str,
+ pub license: &'static str,
+ pub license_url: &'static str,
+ pub author: &'static str,
+ /// Human-readable source page.
+ pub source: &'static str,
+ pub files: &'static [ModelFile],
+}
+
+impl ModelInfo {
+ pub fn size(&self) -> u64 {
+ self.files.iter().map(|f| f.size).sum()
+ }
+}
+
+const LICENSE: &str = "MIT (OpenAI Whisper weights); Hugging Face conversion: Apache-2.0";
+const LICENSE_URL: &str = "https://github.com/openai/whisper/blob/main/LICENSE";
+const AUTHOR: &str = "OpenAI";
+
+macro_rules! hf {
+ ($repo:literal, $rev:literal, $name:literal, $sha:literal, $size:expr) => {
+ ModelFile { name: $name, url: concat!("https://huggingface.co/openai/", $repo, "/resolve/", $rev, "/", $name), sha256: $sha, size: $size }
+ };
+}
+
+const TOKENIZER_MULTI: &str = "27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566";
+
+static CATALOGUE: &[ModelInfo] = &[
+ ModelInfo {
+ id: "whisper-tiny",
+ name: "Whisper tiny (multilingual)",
+ multilingual: true,
+ description: "39 M parameters. Fastest; fine for clear speech, rough on noisy audio.",
+ license: LICENSE,
+ license_url: LICENSE_URL,
+ author: AUTHOR,
+ source: "https://huggingface.co/openai/whisper-tiny",
+ files: &[
+ hf!(
+ "whisper-tiny",
+ "169d4a4341b33bc18d8881c4b69c2e104e1cc0af",
+ "config.json",
+ "ffdccec4f3211f4c63310f2b7098f309fe70f3952cedc5e4d11e43f5b2379b98",
+ 1983
+ ),
+ hf!(
+ "whisper-tiny",
+ "169d4a4341b33bc18d8881c4b69c2e104e1cc0af",
+ "generation_config.json",
+ "a5d5325911f16e74001a72fa13d6e208eee51548f994646de1f4b4cc8b35b512",
+ 3747
+ ),
+ hf!(
+ "whisper-tiny",
+ "169d4a4341b33bc18d8881c4b69c2e104e1cc0af",
+ "tokenizer.json",
+ "27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566",
+ 2480466
+ ),
+ hf!(
+ "whisper-tiny",
+ "169d4a4341b33bc18d8881c4b69c2e104e1cc0af",
+ "model.safetensors",
+ "7ebd0e69e78190ffe1438491fa05cc1f5c1aa3a4c4db3bc1723adbb551ea2395",
+ 151061672
+ ),
+ ],
+ },
+ ModelInfo {
+ id: "whisper-base",
+ name: "Whisper base (multilingual)",
+ multilingual: true,
+ description: "74 M parameters. The default: a good balance of speed and accuracy.",
+ license: LICENSE,
+ license_url: LICENSE_URL,
+ author: AUTHOR,
+ source: "https://huggingface.co/openai/whisper-base",
+ files: &[
+ hf!(
+ "whisper-base",
+ "e37978b90ca9030d5170a5c07aadb050351a65bb",
+ "config.json",
+ "a153c53883a6799b6f056b4a8d1a515c9926d03994682ba88a7616618d7da0c1",
+ 1983
+ ),
+ hf!(
+ "whisper-base",
+ "e37978b90ca9030d5170a5c07aadb050351a65bb",
+ "generation_config.json",
+ "444b3f636d2fff89dd9ecf549e2a085b61f7ff0fa0246d4628bac6a3b8cc9ba4",
+ 3807
+ ),
+ hf!(
+ "whisper-base",
+ "e37978b90ca9030d5170a5c07aadb050351a65bb",
+ "tokenizer.json",
+ "27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566",
+ 2480466
+ ),
+ hf!(
+ "whisper-base",
+ "e37978b90ca9030d5170a5c07aadb050351a65bb",
+ "model.safetensors",
+ "07cadb9f25677c8d50df603e66a98fbd842cce45047139baeb16e6219a1e807b",
+ 290403936
+ ),
+ ],
+ },
+ ModelInfo {
+ id: "whisper-small",
+ name: "Whisper small (multilingual)",
+ multilingual: true,
+ description: "244 M parameters. Most accurate here; about 4× slower than base.",
+ license: LICENSE,
+ license_url: LICENSE_URL,
+ author: AUTHOR,
+ source: "https://huggingface.co/openai/whisper-small",
+ files: &[
+ hf!(
+ "whisper-small",
+ "973afd24965f72e36ca33b3055d56a652f456b4d",
+ "config.json",
+ "e6a2b489da1b5aed65a8eb8d1e7466fa867ad5643a8bc138ba708bd56b2875c4",
+ 1967
+ ),
+ hf!(
+ "whisper-small",
+ "973afd24965f72e36ca33b3055d56a652f456b4d",
+ "generation_config.json",
+ "71565b8ef50d0bf7a1193ed4bbed195b94e70c18894d81bba2f1233dcec3ab53",
+ 3868
+ ),
+ hf!(
+ "whisper-small",
+ "973afd24965f72e36ca33b3055d56a652f456b4d",
+ "tokenizer.json",
+ "27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566",
+ 2480466
+ ),
+ hf!(
+ "whisper-small",
+ "973afd24965f72e36ca33b3055d56a652f456b4d",
+ "model.safetensors",
+ "1d7734884874f1a1513ed9aa760a4f8e97aaa02fd6d93a3a85d27b2ae9ca596b",
+ 966995080
+ ),
+ ],
+ },
+];
+
+/// The default model.
+pub const DEFAULT_MODEL: &str = "whisper-base";
+
+pub fn catalogue() -> &'static [ModelInfo] {
+ CATALOGUE
+}
+
+pub fn find(id: &str) -> Option<&'static ModelInfo> {
+ CATALOGUE.iter().find(|m| m.id == id)
+}
+
+/// Where model `m` lives under `models_dir`.
+pub fn model_dir(models_dir: &Path, m: &ModelInfo) -> PathBuf {
+ models_dir.join(m.id)
+}
+
+/// All files present with their catalogue sizes (contents were verified when downloaded).
+pub fn installed(models_dir: &Path, m: &ModelInfo) -> bool {
+ let d = model_dir(models_dir, m);
+ m.files.iter().all(|f| std::fs::metadata(d.join(f.name)).is_ok_and(|md| md.len() == f.size))
+}
+
+/// Bytes still to download for `m` (files already present are skipped).
+pub fn missing_bytes(models_dir: &Path, m: &ModelInfo) -> u64 {
+ let d = model_dir(models_dir, m);
+ m.files.iter().filter(|f| !std::fs::metadata(d.join(f.name)).is_ok_and(|md| md.len() == f.size)).map(|f| f.size).sum()
+}
+
+/// The tokenizer shared by the multilingual models has one checksum.
+pub fn shared_tokenizer_sha() -> &'static str {
+ TOKENIZER_MULTI
+}
+
+/// Download progress: `(bytes done, bytes total, file)`; return false to cancel.
+#[cfg(feature = "download")]
+pub type DownloadProgress<'a> = &'a mut dyn FnMut(u64, u64, &str) -> bool;
+
+/// Download the missing files of `m` into `models_dir/<id>/`: each file streams into `<name>.part`,
+/// its SHA-256 is checked, then it is renamed into place. A wrong checksum deletes the part file
+/// and fails. Pure Rust TLS (rustls + RustCrypto) with the operating system's certificate
+/// verifier.
+#[cfg(feature = "download")]
+pub fn download(models_dir: &Path, m: &ModelInfo, progress: DownloadProgress) -> Result<(), crate::SpeechError> {
+ use crate::SpeechError;
+ use sha2::Digest;
+ use std::io::{Read, Write};
+ let dir = model_dir(models_dir, m);
+ std::fs::create_dir_all(&dir)?;
+ let total = missing_bytes(models_dir, m);
+ let agent = agent();
+ let mut done = 0u64;
+ for f in m.files {
+ let dest = dir.join(f.name);
+ if std::fs::metadata(&dest).is_ok_and(|md| md.len() == f.size) {
+ continue;
+ }
+ let part = dir.join(format!("{}.part", f.name));
+ let resp = agent.get(f.url).call().map_err(|e| SpeechError::Download(format!("{}: {e}", f.url)))?;
+ let mut body = resp.into_body();
+ let mut reader = body.as_reader();
+ let mut out = std::io::BufWriter::new(std::fs::File::create(&part)?);
+ let mut hasher = sha2::Sha256::new();
+ let mut buf = vec![0u8; 1 << 20];
+ let mut got = 0u64;
+ loop {
+ let n = reader.read(&mut buf).map_err(|e| SpeechError::Download(format!("{}: {e}", f.name)))?;
+ if n == 0 {
+ break;
+ }
+ hasher.update(&buf[..n]);
+ out.write_all(&buf[..n])?;
+ got += n as u64;
+ if !progress(done + got, total, f.name) {
+ drop(out);
+ let _ = std::fs::remove_file(&part);
+ return Err(SpeechError::Cancelled);
+ }
+ }
+ out.flush()?;
+ drop(out);
+ let sha: String = hasher.finalize().iter().map(|b| format!("{b:02x}")).collect();
+ if sha != f.sha256 || got != f.size {
+ let _ = std::fs::remove_file(&part);
+ return Err(SpeechError::Download(format!("{}: checksum mismatch (got {sha}, {got} bytes; expected {}, {} bytes)", f.name, f.sha256, f.size)));
+ }
+ std::fs::rename(&part, &dest)?;
+ done += f.size;
+ }
+ Ok(())
+}
+
+#[cfg(feature = "download")]
+fn agent() -> ureq::Agent {
+ let provider = std::sync::Arc::new(rustls_rustcrypto::provider());
+ ureq::Agent::config_builder()
+ .tls_config(
+ ureq::tls::TlsConfig::builder()
+ .provider(ureq::tls::TlsProvider::Rustls)
+ .root_certs(ureq::tls::RootCerts::PlatformVerifier)
+ .unversioned_rustls_crypto_provider(provider)
+ .build(),
+ )
+ .timeout_connect(Some(std::time::Duration::from_secs(30)))
+ .build()
+ .into()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn catalogue_is_pinned_and_checksummed() {
+ assert!(find(DEFAULT_MODEL).is_some());
+ for m in catalogue() {
+ assert!(m.size() > 100_000_000, "{}", m.id);
+ for f in m.files {
+ assert!(f.url.starts_with("https://huggingface.co/openai/whisper-"), "{}", f.url);
+ assert!(f.url.contains("/resolve/") && f.url.ends_with(f.name));
+ assert_eq!(f.sha256.len(), 64);
+ assert!(f.sha256.bytes().all(|b| b.is_ascii_hexdigit()));
+ if f.name == "tokenizer.json" {
+ assert_eq!(f.sha256, shared_tokenizer_sha());
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn installed_checks_sizes() {
+ let dir = std::env::temp_dir().join(format!("filmcraft-speech-models-{}", std::process::id()));
+ let m = find("whisper-tiny").unwrap();
+ assert!(!installed(&dir, m));
+ assert_eq!(missing_bytes(&dir, m), m.size());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/speech/src/vad.rs b/crates/speech/src/vad.rs
new file mode 100644
index 000000000..8557f4824
--- /dev/null
+++ b/crates/speech/src/vad.rs
@@ -0,0 +1,97 @@
+//! Energy-based tightening of word bounds.
+//!
+//! Attention alignment places every word boundary on the next word's start, so silence between
+//! words is absorbed into the word before it (and leading silence into the first word). Pause
+//! detection and text-based editing need the silences, so each word's start and end are moved
+//! inward past 10 ms frames whose level is below a threshold set between the clip's noise floor
+//! (10th percentile of the levels of frames above −100 dBFS) and its speech level (95th percentile): 30 % of the way up,
+//! and at least 6 dB above the floor. A word keeps at least 60 ms.
+
+use filmcraft_project::Word;
+
+use crate::{SAMPLE_RATE, TICKS_PER_SAMPLE};
+
+const FRAME: usize = (SAMPLE_RATE / 100) as usize;
+const MIN_WORD_FRAMES: usize = 6;
+
+/// Frame levels in dBFS (10 ms RMS).
+pub fn frame_db(audio: &[f32]) -> Vec<f32> {
+ audio
+ .chunks(FRAME)
+ .map(|c| {
+ let e = c.iter().map(|v| v * v).sum::<f32>() / c.len().max(1) as f32;
+ 10.0 * (e + 1e-12).log10()
+ })
+ .collect()
+}
+
+/// The speech/silence threshold in dBFS.
+pub fn threshold(db: &[f32]) -> f32 {
+ if db.is_empty() {
+ return -60.0;
+ }
+ // digital silence (< −100 dBFS) would drag the floor far below the recording's own noise
+ let mut s: Vec<f32> = db.iter().copied().filter(|v| *v > -100.0).collect();
+ if s.is_empty() {
+ return -60.0;
+ }
+ s.sort_by(f32::total_cmp);
+ let q = |p: f32| s[((s.len() - 1) as f32 * p) as usize];
+ let (floor, speech) = (q(0.10), q(0.95));
+ (floor + 0.3 * (speech - floor)).max(floor + 6.0)
+}
+
+/// Move word bounds inward past silent frames (see the module docs).
+pub fn tighten_words(audio: &[f32], words: &mut [Word]) {
+ let db = frame_db(audio);
+ if db.is_empty() {
+ return;
+ }
+ let th = threshold(&db);
+ let frame_ticks = TICKS_PER_SAMPLE * FRAME as i64;
+ for w in words {
+ let a = (w.start.0 / frame_ticks).max(0) as usize;
+ let b = (((w.end.0 + frame_ticks - 1) / frame_ticks).max(0) as usize).min(db.len());
+ if b <= a + MIN_WORD_FRAMES {
+ continue;
+ }
+ let mut s = a;
+ while s + MIN_WORD_FRAMES < b && db[s] < th {
+ s += 1;
+ }
+ let mut e = b;
+ while e > s + MIN_WORD_FRAMES && db[e - 1] < th {
+ e -= 1;
+ }
+ // nothing voiced at all: leave the word alone
+ if (s..e).all(|f| db[f] < th) {
+ continue;
+ }
+ if s > a {
+ w.start = filmcraft_time::Tick(s as i64 * frame_ticks);
+ }
+ if e < b {
+ w.end = filmcraft_time::Tick(e as i64 * frame_ticks).max(w.start);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::seconds_tick;
+
+ #[test]
+ fn silence_is_trimmed_from_words() {
+ // 0.0–0.5 silence, 0.5–1.0 tone, 1.0–2.0 silence, 2.0–2.5 tone
+ let mut audio: Vec<f32> = (0..40_000).map(|i| if i % 2 == 0 { 0.0001 } else { 0.0 }).collect();
+ for i in (8_000..16_000).chain(32_000..40_000) {
+ audio[i] = 0.3 * (i as f32 * 0.2).sin();
+ }
+ let mut w = vec![Word::new("a", seconds_tick(0.0), seconds_tick(2.0)), Word::new("b", seconds_tick(2.0), seconds_tick(2.5))];
+ tighten_words(&audio, &mut w);
+ assert_eq!(w[0].start, seconds_tick(0.5));
+ assert_eq!(w[0].end, seconds_tick(1.0));
+ assert_eq!((w[1].start, w[1].end), (seconds_tick(2.0), seconds_tick(2.5)));
+ }
+}
diff --git a/crates/speech/src/whisper/align.rs b/crates/speech/src/whisper/align.rs
new file mode 100644
index 000000000..903de393d
--- /dev/null
+++ b/crates/speech/src/whisper/align.rs
@@ -0,0 +1,165 @@
+//! Word timing from cross-attention: token-to-audio alignment by dynamic time warping over the
+//! averaged, normalised attention of the alignment heads (see the module docs of `whisper`).
+
+use candle_core::{Result, Tensor};
+
+use super::model::Model;
+
+/// Start/end (in mel frames from the window start, 10 ms) of every token of `text`.
+pub fn align(m: &mut Model, xa: &Tensor, prompt: &[u32], text: &[u32], eot: u32, heads: &[(usize, usize)], seg_frames: usize) -> Result<Vec<(usize, usize)>> {
+ let mut tokens = prompt.to_vec();
+ tokens.extend_from_slice(text);
+ tokens.push(eot);
+ m.decoder.reset();
+ let (_, qk) = m.decoder.forward(&tokens, xa, false, Some(heads))?;
+ m.decoder.reset();
+ let Some(qk) = qk else { return Ok(vec![(0, 0); text.len()]) };
+ let (h, t, f_all) = qk.dims3()?;
+ let f = (seg_frames / 2).clamp(1, f_all);
+ let qk = qk.narrow(2, 0, f)?.contiguous()?;
+ let w = candle_nn::ops::softmax_last_dim(&qk)?;
+ let w: Vec<Vec<Vec<f32>>> = w.to_vec3()?;
+ let rows = text.len() + 1;
+ let first = prompt.len() - 1;
+ let mut matrix = vec![0f32; rows * f];
+ for head in w.iter().take(h) {
+ // standardise over tokens for every frame
+ let mut z = vec![0f32; t * f];
+ for j in 0..f {
+ let mean = (0..t).map(|i| head[i][j]).sum::<f32>() / t as f32;
+ let var = (0..t).map(|i| (head[i][j] - mean).powi(2)).sum::<f32>() / t as f32;
+ let sd = var.sqrt().max(1e-8);
+ for i in 0..t {
+ z[i * f + j] = (head[i][j] - mean) / sd;
+ }
+ }
+ for r in 0..rows {
+ let row = median_filter(&z[(first + r) * f..(first + r + 1) * f], 7);
+ for j in 0..f {
+ matrix[r * f + j] += row[j] / h as f32;
+ }
+ }
+ }
+ let neg: Vec<f32> = matrix.iter().map(|v| -v).collect();
+ let path = dtw(&neg, rows, f);
+ // the frame where each row is first reached
+ let mut jump = vec![usize::MAX; rows];
+ for &(i, j) in &path {
+ if jump[i] == usize::MAX {
+ jump[i] = j;
+ }
+ }
+ let mut out = Vec::with_capacity(text.len());
+ for i in 0..text.len() {
+ let s = jump[i].min(f);
+ let e = jump[i + 1].min(f).max(s);
+ out.push((s * 2, e * 2));
+ }
+ Ok(out)
+}
+
+/// Median filter with reflect padding.
+pub fn median_filter(x: &[f32], width: usize) -> Vec<f32> {
+ let n = x.len();
+ if n == 0 || width <= 1 {
+ return x.to_vec();
+ }
+ let half = width / 2;
+ let at = |i: isize| -> f32 {
+ if n == 1 {
+ return x[0];
+ }
+ let p = 2 * (n as isize - 1);
+ let mut j = i.rem_euclid(p);
+ if j >= n as isize {
+ j = p - j;
+ }
+ x[j as usize]
+ };
+ let mut buf = vec![0f32; width];
+ (0..n)
+ .map(|i| {
+ for (k, b) in buf.iter_mut().enumerate() {
+ *b = at(i as isize + k as isize - half as isize);
+ }
+ buf.sort_by(f32::total_cmp);
+ buf[half]
+ })
+ .collect()
+}
+
+/// Dynamic time warping through `cost` (`n × m`, row-major), monotonic steps (diagonal, down,
+/// right). Returns the path from (0, 0) to (n − 1, m − 1).
+pub fn dtw(cost: &[f32], n: usize, m: usize) -> Vec<(usize, usize)> {
+ let inf = f32::INFINITY;
+ let mut acc = vec![inf; (n + 1) * (m + 1)];
+ let mut trace = vec![0u8; (n + 1) * (m + 1)];
+ acc[0] = 0.0;
+ let idx = |i: usize, j: usize| i * (m + 1) + j;
+ for j in 1..=m {
+ for i in 1..=n {
+ let c0 = acc[idx(i - 1, j - 1)];
+ let c1 = acc[idx(i - 1, j)];
+ let c2 = acc[idx(i, j - 1)];
+ let (c, t) = if c0 < c1 && c0 < c2 {
+ (c0, 0)
+ } else if c1 < c0 && c1 < c2 {
+ (c1, 1)
+ } else {
+ (c2, 2)
+ };
+ acc[idx(i, j)] = cost[(i - 1) * m + (j - 1)] + c;
+ trace[idx(i, j)] = t;
+ }
+ }
+ for j in 0..=m {
+ trace[idx(0, j)] = 2;
+ }
+ for i in 0..=n {
+ trace[idx(i, 0)] = 1;
+ }
+ let (mut i, mut j) = (n, m);
+ let mut path = Vec::new();
+ while i > 0 || j > 0 {
+ if i > 0 && j > 0 {
+ path.push((i - 1, j - 1));
+ }
+ match trace[idx(i, j)] {
+ 0 => {
+ i -= 1;
+ j -= 1;
+ }
+ 1 => i -= 1,
+ _ => j -= 1,
+ }
+ }
+ path.reverse();
+ path
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn median_filter_removes_spikes() {
+ assert_eq!(median_filter(&[0.0, 0.0, 9.0, 0.0, 0.0], 3), vec![0.0, 0.0, 0.0, 0.0, 0.0]);
+ assert_eq!(median_filter(&[1.0, 2.0, 3.0], 1), vec![1.0, 2.0, 3.0]);
+ }
+
+ #[test]
+ fn dtw_follows_the_cheap_diagonal_band() {
+ // 3 rows × 6 columns, cheap cells at row 0: cols 0-1, row 1: cols 2-3, row 2: cols 4-5
+ let mut c = vec![1.0f32; 18];
+ for (r, cols) in [(0, [0, 1]), (1, [2, 3]), (2, [4, 5])] {
+ for k in cols {
+ c[r * 6 + k] = 0.0;
+ }
+ }
+ let p = dtw(&c, 3, 6);
+ assert_eq!(p.first(), Some(&(0, 0)));
+ assert_eq!(p.last(), Some(&(2, 5)));
+ let first_col = |row: usize| p.iter().find(|x| x.0 == row).unwrap().1;
+ assert_eq!((first_col(0), first_col(1), first_col(2)), (0, 2, 4));
+ }
+}
diff --git a/crates/speech/src/whisper/mod.rs b/crates/speech/src/whisper/mod.rs
new file mode 100644
index 000000000..6a602bce1
--- /dev/null
+++ b/crates/speech/src/whisper/mod.rs
@@ -0,0 +1,350 @@
+//! Whisper speech recognition in pure Rust (candle, CPU).
+//!
+//! Transcription follows the procedure described with the model (sequential 30-second windows):
+//!
+//! 1. The whole clip's log-mel spectrogram is computed once ([`crate::mel`]), padded with 30 s of
+//! silence. A window of 3000 frames starting at `seek` is encoded.
+//! 2. **Language**: unless given, the first window's decoder logits after `<|startoftranscript|>`
+//! are compared over the language tokens and the most likely language is used.
+//! 3. **Decoding** is greedy with timestamp tokens: the first token must be a timestamp (≤ 1 s),
+//! timestamps come in pairs and never go backwards, timestamps win whenever their summed
+//! probability beats the best text token, and special tokens are suppressed. Windows whose
+//! `<|nospeech|>` probability exceeds 0.6 while the text is improbable are skipped. A loop
+//! guard stops a window that keeps repeating itself.
+//! 4. `seek` advances to the last complete timestamp pair (or the whole window).
+//! 5. **Word timestamps**: the window's text tokens are run once more through the decoder
+//! (`<|notimestamps|>` prompt) and the cross-attention logits of the model's alignment heads
+//! (`generation_config.json`; default: every head of the second half of the decoder) are
+//! softmaxed over the window's audio frames, standardised per token, median-filtered (width 7)
+//! and averaged; dynamic time warping through the negated matrix gives each token's start frame
+//! (20 ms resolution). Tokens are grouped into words at spaces, punctuation joins its word.
+//!
+//! 6. Word bounds are tightened past silent frames ([`crate::vad`]), so pauses stay pauses.
+//!
+//! Optional speaker labelling runs afterwards ([`crate::diarize`]).
+
+mod align;
+mod model;
+pub mod tokenizer;
+
+use std::path::Path;
+use std::sync::Mutex;
+
+use candle_core::Tensor;
+use filmcraft_project::{Transcript, Word};
+
+use crate::{Options, ProgressFn, SpeechError, Transcriber, sample_tick};
+use model::{Config, Model};
+use tokenizer::Tokenizer;
+
+/// Mel frames per window (30 s).
+const N_FRAMES: usize = 3000;
+/// Mel frames per timestamp step (0.02 s).
+const FRAMES_PER_TS: usize = 2;
+const SAMPLES_PER_FRAME: usize = crate::mel::HOP;
+const MAX_TOKENS: usize = 224;
+
+fn merr(e: candle_core::Error) -> SpeechError {
+ SpeechError::Model(e.to_string())
+}
+
+pub struct Whisper {
+ id: String,
+ model: Mutex<Model>,
+ tok: Tokenizer,
+ alignment_heads: Vec<(usize, usize)>,
+ suppress: Vec<u32>,
+ begin_suppress: Vec<u32>,
+}
+
+impl Whisper {
+ /// Load a model directory (`config.json`, `generation_config.json`, `tokenizer.json`,
+ /// `model.safetensors`).
+ pub fn load(dir: &Path, id: &str) -> Result<Self, SpeechError> {
+ let read = |n: &str| std::fs::read(dir.join(n)).map_err(|e| SpeechError::Model(format!("{}: {e}", dir.join(n).display())));
+ let cfg: Config = serde_json::from_slice(&read("config.json")?).map_err(|e| SpeechError::Model(format!("config.json: {e}")))?;
+ let gen_cfg: serde_json::Value = serde_json::from_slice(&read("generation_config.json")?).unwrap_or_default();
+ let tok = Tokenizer::from_json(&String::from_utf8_lossy(&read("tokenizer.json")?))?;
+ let weights = read("model.safetensors")?;
+ let alignment_heads = gen_cfg["alignment_heads"]
+ .as_array()
+ .map(|a| a.iter().filter_map(|p| Some((p[0].as_u64()? as usize, p[1].as_u64()? as usize))).collect::<Vec<_>>())
+ .filter(|v| !v.is_empty())
+ .unwrap_or_else(|| (cfg.decoder_layers / 2..cfg.decoder_layers).flat_map(|l| (0..cfg.decoder_attention_heads).map(move |h| (l, h))).collect());
+ let mut suppress: Vec<u32> =
+ gen_cfg["suppress_tokens"].as_array().map(|a| a.iter().filter_map(|x| x.as_u64().map(|v| v as u32)).collect()).unwrap_or_default();
+ suppress.extend(tok.non_text_specials());
+ suppress.sort_unstable();
+ suppress.dedup();
+ let begin_suppress = gen_cfg["begin_suppress_tokens"]
+ .as_array()
+ .map(|a| a.iter().filter_map(|x| x.as_u64().map(|v| v as u32)).collect())
+ .unwrap_or_else(|| vec![220, tok.eot]);
+ let model = Model::load(cfg, weights).map_err(merr)?;
+ Ok(Self { id: id.to_string(), model: Mutex::new(model), tok, alignment_heads, suppress, begin_suppress })
+ }
+
+ pub fn languages(&self) -> Vec<String> {
+ self.tok.languages.iter().map(|l| l.0.clone()).collect()
+ }
+
+ fn window(mel: &[f32], n_mels: usize, frames: usize, seek: usize) -> Vec<f32> {
+ let mut w = vec![0f32; n_mels * N_FRAMES];
+ for m in 0..n_mels {
+ let end = (seek + N_FRAMES).min(frames);
+ if seek < end {
+ w[m * N_FRAMES..m * N_FRAMES + end - seek].copy_from_slice(&mel[m * frames + seek..m * frames + end]);
+ }
+ }
+ w
+ }
+
+ fn detect_language(&self, m: &mut Model, xa: &Tensor) -> Result<String, SpeechError> {
+ m.decoder.reset();
+ let (logits, _) = m.decoder.forward(&[self.tok.sot], xa, false, None).map_err(merr)?;
+ let l = Model::last_logits(&logits).map_err(merr)?;
+ let best = self.tok.languages.iter().max_by(|a, b| l[a.1 as usize].total_cmp(&l[b.1 as usize])).map(|x| x.0.clone());
+ Ok(best.unwrap_or_else(|| "en".into()))
+ }
+
+ /// Apply the timestamp rules and suppression to `logits` for the next token after `seq`
+ /// (sampled tokens of this window, prompt excluded).
+ fn constrain(&self, logits: &mut [f32], seq: &[u32], max_ts: Option<u32>) {
+ let tb = self.tok.timestamp_begin as usize;
+ let ninf = f32::NEG_INFINITY;
+ for &s in &self.suppress {
+ if let Some(v) = logits.get_mut(s as usize) {
+ *v = ninf;
+ }
+ }
+ if seq.is_empty() {
+ for &s in &self.begin_suppress {
+ if let Some(v) = logits.get_mut(s as usize) {
+ *v = ninf;
+ }
+ }
+ }
+ let last_ts = seq.last().is_some_and(|&t| self.tok.is_timestamp(t));
+ let penult_ts = seq.len() < 2 || self.tok.is_timestamp(seq[seq.len() - 2]);
+ if last_ts {
+ if penult_ts {
+ logits[tb..].iter_mut().for_each(|v| *v = ninf);
+ } else {
+ logits[..self.tok.eot as usize].iter_mut().for_each(|v| *v = ninf);
+ }
+ }
+ if let Some(&last) = seq.iter().rev().find(|&&t| self.tok.is_timestamp(t)) {
+ let lim = (if last_ts && !penult_ts { last } else { last + 1 } as usize).min(logits.len());
+ logits[tb..lim].iter_mut().for_each(|v| *v = ninf);
+ }
+ if seq.is_empty() {
+ logits[..tb].iter_mut().for_each(|v| *v = ninf);
+ if let Some(m) = max_ts {
+ let cut = (tb + m as usize + 1).min(logits.len());
+ logits[cut..].iter_mut().for_each(|v| *v = ninf);
+ }
+ }
+ // timestamps win when their total probability beats every text token
+ let max = logits.iter().copied().fold(ninf, f32::max);
+ if max.is_finite() {
+ let lse = |s: &[f32]| -> f32 {
+ let m = s.iter().copied().fold(ninf, f32::max);
+ if !m.is_finite() {
+ return ninf;
+ }
+ m + s.iter().map(|v| (v - m).exp()).sum::<f32>().ln()
+ };
+ let ts = lse(&logits[tb..]);
+ let best_text = logits[..tb].iter().copied().fold(ninf, f32::max);
+ if ts > best_text {
+ logits[..tb].iter_mut().for_each(|v| *v = ninf);
+ }
+ }
+ }
+
+ /// Greedy decode of one window. Returns sampled tokens (no prompt, no end-of-text), the mean
+ /// log-probability and the no-speech probability.
+ fn decode_window(&self, m: &mut Model, xa: &Tensor, prompt: &[u32]) -> Result<(Vec<u32>, f32, f32), SpeechError> {
+ m.decoder.reset();
+ let mut seq: Vec<u32> = Vec::new();
+ let (logits, _) = m.decoder.forward(prompt, xa, true, None).map_err(merr)?;
+ // no-speech probability from the start-of-transcript position
+ let first = logits.get(0).and_then(|l| l.get(0)).and_then(|l| l.to_vec1::<f32>()).map_err(merr)?;
+ let no_speech = self.tok.no_speech.map(|ns| softmax_at(&first, ns as usize)).unwrap_or(0.0);
+ let mut cur = Model::last_logits(&logits).map_err(merr)?;
+ let mut sum_lp = 0f32;
+ for _ in 0..MAX_TOKENS.min(m.cfg.max_target_positions / 2) {
+ let lp = log_softmax(&cur);
+ self.constrain(&mut cur, &seq, Some(50));
+ let next = argmax(&cur);
+ sum_lp += lp[next as usize];
+ if next == self.tok.eot {
+ break;
+ }
+ seq.push(next);
+ if repeating(&seq, self.tok.timestamp_begin) {
+ break;
+ }
+ let (logits, _) = m.decoder.forward(&[next], xa, true, None).map_err(merr)?;
+ cur = Model::last_logits(&logits).map_err(merr)?;
+ }
+ let avg = sum_lp / (seq.len() + 1) as f32;
+ Ok((seq, avg, no_speech))
+ }
+}
+
+fn softmax_at(x: &[f32], i: usize) -> f32 {
+ let m = x.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ let s: f32 = x.iter().map(|v| (v - m).exp()).sum();
+ x.get(i).map(|v| (v - m).exp() / s).unwrap_or(0.0)
+}
+
+fn log_softmax(x: &[f32]) -> Vec<f32> {
+ let m = x.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ let lse = m + x.iter().map(|v| (v - m).exp()).sum::<f32>().ln();
+ x.iter().map(|v| v - lse).collect()
+}
+
+fn argmax(x: &[f32]) -> u32 {
+ let mut best = 0;
+ for (i, v) in x.iter().enumerate() {
+ if *v > x[best] {
+ best = i;
+ }
+ }
+ best as u32
+}
+
+/// The tail of `seq` (text tokens) repeats a short pattern many times: a decoding loop.
+fn repeating(seq: &[u32], tb: u32) -> bool {
+ let text: Vec<u32> = seq.iter().copied().filter(|&t| t < tb).collect();
+ for n in 1..=8 {
+ let reps = if n == 1 { 12 } else { 5 };
+ if text.len() < n * reps {
+ continue;
+ }
+ let tail = &text[text.len() - n * reps..];
+ if (1..reps).all(|r| tail[r * n..(r + 1) * n] == tail[..n]) {
+ return true;
+ }
+ }
+ false
+}
+
+impl Transcriber for Whisper {
+ fn id(&self) -> String {
+ self.id.clone()
+ }
+
+ fn transcribe(&self, audio: &[f32], opts: &Options, progress: ProgressFn) -> Result<Transcript, SpeechError> {
+ let mut m = self.model.lock().unwrap_or_else(|e| e.into_inner());
+ let n_mels = m.cfg.num_mel_bins;
+ let content_frames = audio.len() / SAMPLES_PER_FRAME;
+ let mut padded = audio.to_vec();
+ padded.extend(std::iter::repeat_n(0.0, N_FRAMES * SAMPLES_PER_FRAME));
+ if !progress(0.0, "Analysing audio") {
+ return Err(SpeechError::Cancelled);
+ }
+ let trace = std::env::var_os("FILMCRAFT_SPEECH_TRACE").is_some();
+ let clock = std::time::Instant::now();
+ let (frames, mel) = crate::mel::log_mel(&padded, n_mels);
+ if trace {
+ eprintln!("mel {:.3}s", clock.elapsed().as_secs_f64());
+ }
+ let mut language = opts.language.clone().filter(|l| !l.is_empty() && l != "auto");
+ if language.as_deref().is_some_and(|l| self.tok.multilingual() && self.tok.language_token(l).is_none()) {
+ return Err(SpeechError::Model(format!("the model does not know the language `{}`", language.unwrap_or_default())));
+ }
+ let mut words: Vec<Word> = Vec::new();
+ let mut seek = 0usize;
+ while seek < content_frames {
+ let frac = seek as f32 / content_frames.max(1) as f32;
+ if !progress(frac * 0.95, &format!("Transcribing {:.0}%", frac * 100.0)) {
+ return Err(SpeechError::Cancelled);
+ }
+ let seg_frames = N_FRAMES.min(content_frames - seek);
+ let win = Self::window(&mel, n_mels, frames, seek);
+ let x = Tensor::from_vec(win, (1, n_mels, N_FRAMES), &m.device).map_err(merr)?;
+ let xa = m.encoder.forward(&x).map_err(merr)?;
+ if trace {
+ eprintln!("encode {:.3}s", clock.elapsed().as_secs_f64());
+ }
+ let mut prompt = vec![self.tok.sot];
+ if self.tok.multilingual() {
+ if language.is_none() {
+ language = Some(self.detect_language(&mut m, &xa)?);
+ }
+ let lang = language.as_deref().unwrap_or("en");
+ prompt.push(self.tok.language_token(lang).unwrap_or(self.tok.sot + 1));
+ prompt.push(self.tok.transcribe);
+ }
+ let (toks, avg_lp, no_speech) = self.decode_window(&mut m, &xa, &prompt)?;
+ if trace {
+ eprintln!("decode {} tokens {:.3}s", toks.len(), clock.elapsed().as_secs_f64());
+ }
+ let skip = no_speech > 0.6 && avg_lp < -1.0;
+ // where the next window starts
+ let is_ts: Vec<bool> = toks.iter().map(|&t| self.tok.is_timestamp(t)).collect();
+ let single_ending = is_ts.len() >= 2 && !is_ts[is_ts.len() - 2] && is_ts[is_ts.len() - 1];
+ let last_pair = (1..is_ts.len()).rev().find(|&i| is_ts[i] && is_ts[i - 1]);
+ let advance = match last_pair {
+ Some(i) if !single_ending => ((toks[i - 1] - self.tok.timestamp_begin) as usize * FRAMES_PER_TS).clamp(1, seg_frames),
+ _ => seg_frames,
+ };
+ let text: Vec<u32> = toks.iter().copied().filter(|&t| t < self.tok.eot).collect();
+ if !skip && !text.is_empty() {
+ // the text up to the last complete segment (what `advance` covers)
+ let upto = match last_pair {
+ Some(i) if !single_ending => i,
+ _ => toks.len(),
+ };
+ let text: Vec<u32> = toks[..upto].iter().copied().filter(|&t| t < self.tok.eot).collect();
+ let mut aprompt = prompt.clone();
+ aprompt.push(self.tok.no_timestamps);
+ let times = align::align(&mut m, &xa, &aprompt, &text, self.tok.eot, &self.alignment_heads, seg_frames).map_err(merr)?;
+ let offset = seek * SAMPLES_PER_FRAME;
+ let limit = (seek + advance) * SAMPLES_PER_FRAME;
+ for (wtext, r) in tokenizer::group_words(&self.tok, &text) {
+ let (s, e) = (times[r.start].0, times[r.end - 1].1);
+ let a = (offset + s * SAMPLES_PER_FRAME).min(limit);
+ let b = (offset + e * SAMPLES_PER_FRAME).min(limit).max(a);
+ words.push(Word::new(wtext, sample_tick(a as i64), sample_tick(b as i64)));
+ }
+ }
+ if trace {
+ eprintln!("align {:.3}s", clock.elapsed().as_secs_f64());
+ }
+ seek += advance;
+ }
+ let mut t = Transcript { language: language.unwrap_or_else(|| "en".into()), source: self.id.clone(), speakers: Vec::new(), words };
+ t.normalize();
+ crate::vad::tighten_words(audio, &mut t.words);
+ if opts.diarize && !t.words.is_empty() {
+ if !progress(0.96, "Labelling speakers") {
+ return Err(SpeechError::Cancelled);
+ }
+ let p = crate::diarize::Params { max_speakers: opts.max_speakers, ..Default::default() };
+ crate::diarize::diarize(audio, &mut t, &p);
+ }
+ progress(1.0, "Done");
+ Ok(t)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn repetition_guard() {
+ let tb = 1000;
+ assert!(repeating(&[5; 12], tb));
+ assert!(!repeating(&[5, 5, 5, 6, 7, 8], tb));
+ let mut s = Vec::new();
+ for _ in 0..5 {
+ s.extend([1, 2, 3]);
+ }
+ assert!(repeating(&s, tb));
+ assert!(!repeating(&[1, 2, 3, 4, 5, 6, 7], tb));
+ }
+}
diff --git a/crates/speech/src/whisper/model.rs b/crates/speech/src/whisper/model.rs
new file mode 100644
index 000000000..0c397d9f3
--- /dev/null
+++ b/crates/speech/src/whisper/model.rs
@@ -0,0 +1,274 @@
+//! The Whisper network (encoder–decoder transformer), written against candle from the published
+//! architecture (Radford et al. 2022, "Robust Speech Recognition via Large-Scale Weak
+//! Supervision", and OpenAI's MIT-licensed model description), reading the tensor names of the
+//! Hugging Face safetensors release.
+//!
+//! Encoder: two 1-D convolutions (k = 3, the second with stride 2) with GELU, learned/sinusoidal
+//! position table, pre-LayerNorm self-attention blocks, final LayerNorm. Decoder: token and
+//! position embeddings, pre-LayerNorm blocks of causal self-attention, cross-attention to the
+//! audio and an MLP, final LayerNorm, logits tied to the token embedding.
+//!
+//! The decoder keeps a key/value cache for incremental decoding and can return the cross-attention
+//! logits of chosen heads (word alignment).
+
+use candle_core::{DType, Device, Module, Result, Tensor};
+use candle_nn::{Conv1d, Conv1dConfig, Embedding, LayerNorm, Linear, VarBuilder};
+
+/// `config.json` fields we use.
+#[derive(Clone, Debug, serde::Deserialize)]
+pub struct Config {
+ pub num_mel_bins: usize,
+ pub d_model: usize,
+ pub encoder_layers: usize,
+ pub encoder_attention_heads: usize,
+ pub decoder_layers: usize,
+ pub decoder_attention_heads: usize,
+ pub max_source_positions: usize,
+ pub max_target_positions: usize,
+ pub vocab_size: usize,
+}
+
+struct Attention {
+ q: Linear,
+ k: Linear,
+ v: Linear,
+ out: Linear,
+ heads: usize,
+ /// cached keys/values (self-attention: grows; cross-attention: the audio's, computed once)
+ cache: Option<(Tensor, Tensor)>,
+}
+
+impl Attention {
+ fn new(d: usize, heads: usize, vb: VarBuilder) -> Result<Self> {
+ Ok(Self {
+ q: candle_nn::linear(d, d, vb.pp("q_proj"))?,
+ k: candle_nn::linear_no_bias(d, d, vb.pp("k_proj"))?,
+ v: candle_nn::linear(d, d, vb.pp("v_proj"))?,
+ out: candle_nn::linear(d, d, vb.pp("out_proj"))?,
+ heads,
+ cache: None,
+ })
+ }
+
+ fn split(&self, x: &Tensor) -> Result<Tensor> {
+ let (b, t, d) = x.dims3()?;
+ x.reshape((b, t, self.heads, d / self.heads))?.transpose(1, 2)?.contiguous()
+ }
+
+ /// `x`: queries (b, t, d). `kv`: None = self-attention on `x` (appending to the cache when
+ /// `cached`), Some(audio) = cross-attention (keys/values cached after the first call when
+ /// `cached`). Returns the output and the attention logits (b, heads, t, tk).
+ fn forward(&mut self, x: &Tensor, kv: Option<&Tensor>, mask: Option<&Tensor>, cached: bool) -> Result<(Tensor, Tensor)> {
+ let (_, t, d) = x.dims3()?;
+ let dh = d / self.heads;
+ let q = (self.split(&self.q.forward(x)?)? * (dh as f64).powf(-0.5))?;
+ let (k, v) = match kv {
+ None => {
+ let k = self.split(&self.k.forward(x)?)?;
+ let v = self.split(&self.v.forward(x)?)?;
+ if cached {
+ let (k, v) = match &self.cache {
+ Some((pk, pv)) => (Tensor::cat(&[pk, &k], 2)?, Tensor::cat(&[pv, &v], 2)?),
+ None => (k, v),
+ };
+ self.cache = Some((k.clone(), v.clone()));
+ (k, v)
+ } else {
+ (k, v)
+ }
+ }
+ Some(xa) => match (&self.cache, cached) {
+ (Some((k, v)), true) => (k.clone(), v.clone()),
+ _ => {
+ let k = self.split(&self.k.forward(xa)?)?;
+ let v = self.split(&self.v.forward(xa)?)?;
+ if cached {
+ self.cache = Some((k.clone(), v.clone()));
+ }
+ (k, v)
+ }
+ },
+ };
+ let mut qk = q.matmul(&k.transpose(2, 3)?.contiguous()?)?;
+ if let Some(m) = mask {
+ qk = qk.broadcast_add(m)?;
+ }
+ let w = candle_nn::ops::softmax_last_dim(&qk)?;
+ let o = w.matmul(&v)?.transpose(1, 2)?.contiguous()?;
+ let (b, _, _, _) = o.dims4()?;
+ Ok((self.out.forward(&o.reshape((b, t, d))?)?, qk))
+ }
+}
+
+struct Block {
+ attn: Attention,
+ attn_ln: LayerNorm,
+ cross: Option<(Attention, LayerNorm)>,
+ fc1: Linear,
+ fc2: Linear,
+ mlp_ln: LayerNorm,
+}
+
+impl Block {
+ fn new(d: usize, heads: usize, cross: bool, vb: VarBuilder) -> Result<Self> {
+ let cross = if cross {
+ Some((Attention::new(d, heads, vb.pp("encoder_attn"))?, candle_nn::layer_norm(d, 1e-5, vb.pp("encoder_attn_layer_norm"))?))
+ } else {
+ None
+ };
+ Ok(Self {
+ attn: Attention::new(d, heads, vb.pp("self_attn"))?,
+ attn_ln: candle_nn::layer_norm(d, 1e-5, vb.pp("self_attn_layer_norm"))?,
+ cross,
+ fc1: candle_nn::linear(d, 4 * d, vb.pp("fc1"))?,
+ fc2: candle_nn::linear(4 * d, d, vb.pp("fc2"))?,
+ mlp_ln: candle_nn::layer_norm(d, 1e-5, vb.pp("final_layer_norm"))?,
+ })
+ }
+
+ fn forward(&mut self, x: &Tensor, xa: Option<&Tensor>, mask: Option<&Tensor>, cached: bool) -> Result<(Tensor, Option<Tensor>)> {
+ let (a, _) = self.attn.forward(&self.attn_ln.forward(x)?, None, mask, cached)?;
+ let mut x = (x + a)?;
+ let mut qk = None;
+ if let (Some((c, ln)), Some(xa)) = (&mut self.cross, xa) {
+ let (a, w) = c.forward(&ln.forward(&x)?, Some(xa), None, cached)?;
+ x = (x + a)?;
+ qk = Some(w);
+ }
+ let h = self.fc2.forward(&self.fc1.forward(&self.mlp_ln.forward(&x)?)?.gelu_erf()?)?;
+ Ok(((x + h)?, qk))
+ }
+
+ fn reset(&mut self) {
+ self.attn.cache = None;
+ if let Some((c, _)) = &mut self.cross {
+ c.cache = None;
+ }
+ }
+}
+
+pub struct Encoder {
+ conv1: Conv1d,
+ conv2: Conv1d,
+ pos: Tensor,
+ blocks: Vec<Block>,
+ ln: LayerNorm,
+}
+
+impl Encoder {
+ fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {
+ let d = cfg.d_model;
+ let c1 = Conv1dConfig { padding: 1, stride: 1, ..Default::default() };
+ let c2 = Conv1dConfig { padding: 1, stride: 2, ..Default::default() };
+ Ok(Self {
+ conv1: candle_nn::conv1d(cfg.num_mel_bins, d, 3, c1, vb.pp("conv1"))?,
+ conv2: candle_nn::conv1d(d, d, 3, c2, vb.pp("conv2"))?,
+ pos: vb.get((cfg.max_source_positions, d), "embed_positions.weight")?,
+ blocks: (0..cfg.encoder_layers).map(|i| Block::new(d, cfg.encoder_attention_heads, false, vb.pp(format!("layers.{i}")))).collect::<Result<_>>()?,
+ ln: candle_nn::layer_norm(d, 1e-5, vb.pp("layer_norm"))?,
+ })
+ }
+
+ /// `mel`: (1, n_mels, 3000) → (1, 1500, d).
+ pub fn forward(&mut self, mel: &Tensor) -> Result<Tensor> {
+ let x = self.conv1.forward(mel)?.gelu_erf()?;
+ let x = self.conv2.forward(&x)?.gelu_erf()?;
+ let x = x.transpose(1, 2)?;
+ let t = x.dim(1)?;
+ let mut x = x.broadcast_add(&self.pos.narrow(0, 0, t)?)?;
+ for b in &mut self.blocks {
+ x = b.forward(&x, None, None, false)?.0;
+ }
+ self.ln.forward(&x)
+ }
+}
+
+pub struct Decoder {
+ tok: Embedding,
+ /// The token embedding transposed (d, vocab), contiguous: the output projection.
+ tok_t: Tensor,
+ pos: Tensor,
+ blocks: Vec<Block>,
+ ln: LayerNorm,
+ /// tokens already in the self-attention cache
+ offset: usize,
+}
+
+impl Decoder {
+ fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {
+ let d = cfg.d_model;
+ let tok = candle_nn::embedding(cfg.vocab_size, d, vb.pp("embed_tokens"))?;
+ Ok(Self {
+ tok_t: tok.embeddings().t()?.contiguous()?,
+ tok,
+ pos: vb.get((cfg.max_target_positions, d), "embed_positions.weight")?,
+ blocks: (0..cfg.decoder_layers).map(|i| Block::new(d, cfg.decoder_attention_heads, true, vb.pp(format!("layers.{i}")))).collect::<Result<_>>()?,
+ ln: candle_nn::layer_norm(d, 1e-5, vb.pp("layer_norm"))?,
+ offset: 0,
+ })
+ }
+
+ /// Forget the cached keys/values (new audio window or new token sequence).
+ pub fn reset(&mut self) {
+ self.offset = 0;
+ for b in &mut self.blocks {
+ b.reset();
+ }
+ }
+
+ fn mask(t: usize, offset: usize, dev: &Device) -> Result<Tensor> {
+ let m: Vec<f32> = (0..t).flat_map(|i| (0..offset + t).map(move |j| if j > offset + i { f32::NEG_INFINITY } else { 0.0 })).collect();
+ Tensor::from_vec(m, (t, offset + t), dev)
+ }
+
+ /// Logits (1, t, vocab) for `tokens` appended to the cache. With `qk_heads`, also returns the
+ /// cross-attention logits of those (layer, head) pairs: (heads, t, audio frames).
+ pub fn forward(&mut self, tokens: &[u32], xa: &Tensor, cached: bool, qk_heads: Option<&[(usize, usize)]>) -> Result<(Tensor, Option<Tensor>)> {
+ let dev = xa.device();
+ let t = tokens.len();
+ let offset = if cached { self.offset } else { 0 };
+ let ids = Tensor::new(tokens, dev)?.unsqueeze(0)?;
+ let mut x = self.tok.forward(&ids)?.broadcast_add(&self.pos.narrow(0, offset, t)?)?;
+ let mask = if t > 1 { Some(Self::mask(t, offset, dev)?) } else { None };
+ let mut picked = Vec::new();
+ for (li, b) in self.blocks.iter_mut().enumerate() {
+ let (y, qk) = b.forward(&x, Some(xa), mask.as_ref(), cached)?;
+ x = y;
+ if let (Some(heads), Some(qk)) = (qk_heads, qk) {
+ for &(l, h) in heads {
+ if l == li {
+ picked.push(qk.get(0)?.get(h)?);
+ }
+ }
+ }
+ }
+ if cached {
+ self.offset += t;
+ }
+ let x = self.ln.forward(&x)?;
+ let logits = x.broadcast_matmul(&self.tok_t)?;
+ let qk = if picked.is_empty() { None } else { Some(Tensor::stack(&picked, 0)?) };
+ Ok((logits, qk))
+ }
+}
+
+pub struct Model {
+ pub cfg: Config,
+ pub encoder: Encoder,
+ pub decoder: Decoder,
+ pub device: Device,
+}
+
+impl Model {
+ pub fn load(cfg: Config, weights: Vec<u8>) -> Result<Self> {
+ let device = Device::Cpu;
+ let vb = VarBuilder::from_buffered_safetensors(weights, DType::F32, &device)?;
+ let vb = vb.pp("model");
+ Ok(Self { encoder: Encoder::new(&cfg, vb.pp("encoder"))?, decoder: Decoder::new(&cfg, vb.pp("decoder"))?, cfg, device })
+ }
+
+ pub fn last_logits(logits: &Tensor) -> Result<Vec<f32>> {
+ let t = logits.dim(1)?;
+ logits.get(0)?.get(t - 1)?.to_dtype(DType::F32)?.to_vec1()
+ }
+}
diff --git a/crates/speech/src/whisper/tokenizer.rs b/crates/speech/src/whisper/tokenizer.rs
new file mode 100644
index 000000000..2fa024b22
--- /dev/null
+++ b/crates/speech/src/whisper/tokenizer.rs
@@ -0,0 +1,166 @@
+//! Decoding Whisper token ids to text from the model's `tokenizer.json` (byte-level BPE: each
+//! vocabulary entry is a string of "printable" stand-in characters, one per byte, using the
+//! GPT-2 byte↔unicode table; special tokens are listed separately as added tokens).
+//!
+//! Only decoding is needed (Whisper produces tokens; we never encode text), so the BPE merges are
+//! not used.
+
+use std::collections::HashMap;
+
+use crate::SpeechError;
+
+pub struct Tokenizer {
+ /// Bytes of each regular token, by id.
+ bytes: Vec<Vec<u8>>,
+ /// Special (added) tokens by content and by id.
+ special: HashMap<String, u32>,
+ special_by_id: HashMap<u32, String>,
+ pub eot: u32,
+ pub sot: u32,
+ pub transcribe: u32,
+ pub translate: Option<u32>,
+ pub no_timestamps: u32,
+ pub no_speech: Option<u32>,
+ /// `<|0.00|>`; every later id is a timestamp in 0.02 s steps.
+ pub timestamp_begin: u32,
+ /// Language tokens (`"en"` → id), multilingual models only.
+ pub languages: Vec<(String, u32)>,
+}
+
+/// GPT-2's byte → printable character table, inverted.
+fn unicode_to_byte() -> HashMap<char, u8> {
+ let mut bs: Vec<u32> = (b'!' as u32..=b'~' as u32).chain(0xA1..=0xAC).chain(0xAE..=0xFF).collect();
+ let mut cs = bs.clone();
+ let mut n = 0;
+ for b in 0..256u32 {
+ if !bs.contains(&b) {
+ bs.push(b);
+ cs.push(256 + n);
+ n += 1;
+ }
+ }
+ bs.iter().zip(&cs).map(|(&b, &c)| (char::from_u32(c).expect("valid"), b as u8)).collect()
+}
+
+impl Tokenizer {
+ pub fn from_json(json: &str) -> Result<Self, SpeechError> {
+ let bad = |m: &str| SpeechError::Model(format!("tokenizer.json: {m}"));
+ let v: serde_json::Value = serde_json::from_str(json).map_err(|e| bad(&e.to_string()))?;
+ let vocab = v["model"]["vocab"].as_object().ok_or_else(|| bad("no model.vocab"))?;
+ let table = unicode_to_byte();
+ let max = vocab.values().filter_map(|x| x.as_u64()).max().unwrap_or(0) as usize;
+ let mut bytes = vec![Vec::new(); max + 1];
+ for (tok, id) in vocab {
+ let id = id.as_u64().ok_or_else(|| bad("vocab id"))? as usize;
+ bytes[id] = tok.chars().filter_map(|c| table.get(&c).copied()).collect();
+ }
+ let mut special = HashMap::new();
+ let mut special_by_id = HashMap::new();
+ for a in v["added_tokens"].as_array().ok_or_else(|| bad("no added_tokens"))? {
+ let (Some(id), Some(c)) = (a["id"].as_u64(), a["content"].as_str()) else { continue };
+ special.insert(c.to_string(), id as u32);
+ special_by_id.insert(id as u32, c.to_string());
+ }
+ let get = |k: &str| special.get(k).copied();
+ let need = |k: &str| get(k).ok_or_else(|| bad(&format!("no {k}")));
+ let sot = need("<|startoftranscript|>")?;
+ let translate = get("<|translate|>");
+ let mut languages: Vec<(String, u32)> = special
+ .iter()
+ .filter(|(k, id)| **id > sot && translate.is_none_or(|t| **id < t) && k.starts_with("<|") && k.ends_with("|>"))
+ .map(|(k, id)| (k[2..k.len() - 2].to_string(), *id))
+ .collect();
+ languages.sort_by_key(|x| x.1);
+ Ok(Self {
+ eot: need("<|endoftext|>")?,
+ sot,
+ transcribe: need("<|transcribe|>")?,
+ translate,
+ no_timestamps: need("<|notimestamps|>")?,
+ no_speech: get("<|nospeech|>").or_else(|| get("<|nocaptions|>")),
+ timestamp_begin: need("<|0.00|>")?,
+ languages,
+ bytes,
+ special,
+ special_by_id,
+ })
+ }
+
+ pub fn multilingual(&self) -> bool {
+ !self.languages.is_empty()
+ }
+
+ pub fn language_token(&self, code: &str) -> Option<u32> {
+ self.languages.iter().find(|(c, _)| c == code).map(|x| x.1)
+ }
+
+ pub fn is_timestamp(&self, id: u32) -> bool {
+ id >= self.timestamp_begin
+ }
+
+ /// Bytes of a regular token (empty for special tokens).
+ pub fn token_bytes(&self, id: u32) -> &[u8] {
+ if self.special_by_id.contains_key(&id) {
+ return &[];
+ }
+ self.bytes.get(id as usize).map(Vec::as_slice).unwrap_or(&[])
+ }
+
+ pub fn decode(&self, ids: &[u32]) -> String {
+ let b: Vec<u8> = ids.iter().flat_map(|&i| self.token_bytes(i).iter().copied()).collect();
+ String::from_utf8_lossy(&b).into_owned()
+ }
+
+ /// Ids of all special tokens that must never be sampled as text (everything special except
+ /// end-of-text and the timestamps).
+ pub fn non_text_specials(&self) -> Vec<u32> {
+ self.special.values().copied().filter(|&id| id != self.eot && id < self.timestamp_begin).collect()
+ }
+}
+
+/// Group text tokens into words: a token whose text starts with a space starts a new word;
+/// punctuation-only tokens join the word before them (opening quotes/brackets the word after).
+/// Returns (word text, token index range).
+pub fn group_words(tok: &Tokenizer, ids: &[u32]) -> Vec<(String, std::ops::Range<usize>)> {
+ let mut groups: Vec<(Vec<u8>, std::ops::Range<usize>)> = Vec::new();
+ let mut pending_open: Option<(Vec<u8>, usize)> = None;
+ for (i, &id) in ids.iter().enumerate() {
+ let b = tok.token_bytes(id);
+ if b.is_empty() {
+ continue;
+ }
+ let text = String::from_utf8_lossy(b);
+ let trimmed = text.trim();
+ let starts_space = b[0] == b' ';
+ let punct = !trimmed.is_empty() && trimmed.chars().all(|c| c.is_ascii_punctuation() || "“”‘’«»¿¡…。,!?:、".contains(c));
+ let opening = punct && trimmed.chars().all(|c| "\"'“‘¿¡([{«-".contains(c)) && starts_space;
+ if opening {
+ let start = pending_open.as_ref().map(|p| p.1).unwrap_or(i);
+ let mut acc = pending_open.take().map(|p| p.0).unwrap_or_default();
+ acc.extend_from_slice(b);
+ pending_open = Some((acc, start));
+ continue;
+ }
+ if let Some((mut pre, start)) = pending_open.take() {
+ pre.extend_from_slice(b);
+ groups.push((pre, start..i + 1));
+ continue;
+ }
+ match groups.last_mut() {
+ Some(g) if !starts_space => {
+ g.0.extend_from_slice(b);
+ g.1.end = i + 1;
+ }
+ Some(g) if punct => {
+ // " ," style punctuation with a space still belongs to the previous word
+ g.0.extend_from_slice(b);
+ g.1.end = i + 1;
+ }
+ _ => groups.push((b.to_vec(), i..i + 1)),
+ }
+ }
+ if let Some((pre, start)) = pending_open {
+ groups.push((pre, start..ids.len()));
+ }
+ groups.into_iter().map(|(b, r)| (String::from_utf8_lossy(&b).trim().to_string(), r)).filter(|(t, _)| !t.is_empty()).collect()
+}
diff --git a/crates/speech/tests/whisper_model.rs b/crates/speech/tests/whisper_model.rs
new file mode 100644
index 000000000..d2fbd8ea8
--- /dev/null
+++ b/crates/speech/tests/whisper_model.rs
@@ -0,0 +1,93 @@
+//! Whisper end-to-end on real speech, when the weights are on this machine.
+//!
+//! Never downloads. Looks for the model in `$FILMCRAFT_MODELS_DIR/<id>/`, then
+//! `<repo>/target/models/<id>/` (put a model there by hand, or let the app download it into the
+//! data directory and point `FILMCRAFT_MODELS_DIR` at `<data dir>/models`). Speech samples are
+//! `<repo>/target/fixtures/speech/**/<name>.f32` (mono 16 kHz little-endian f32) with the
+//! reference text in `<name>.txt`; without either the test prints SKIPPED.
+#![cfg(feature = "whisper")]
+
+use std::path::{Path, PathBuf};
+
+use filmcraft_speech::{Options, Transcriber, models, word_error_rate};
+
+fn repo() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
+}
+
+fn model_dir(id: &str) -> Option<PathBuf> {
+ let m = models::find(id)?;
+ let mut roots: Vec<PathBuf> = std::env::var_os("FILMCRAFT_MODELS_DIR").map(PathBuf::from).into_iter().collect();
+ roots.push(repo().join("target/models"));
+ // worktrees: the main checkout's target
+ if let Ok(main) = std::fs::canonicalize(repo())
+ && let Some(p) = main.ancestors().find(|p| p.join(".git").is_dir())
+ {
+ roots.push(p.join("target/models"));
+ }
+ roots.into_iter().find(|r| models::installed(r, m)).map(|r| models::model_dir(&r, m))
+}
+
+fn samples() -> Vec<(PathBuf, String)> {
+ let mut roots = vec![repo().join("target/fixtures/speech")];
+ if let Ok(main) = std::fs::canonicalize(repo())
+ && let Some(p) = main.ancestors().find(|p| p.join(".git").is_dir())
+ {
+ roots.push(p.join("target/fixtures/speech"));
+ }
+ let mut out = Vec::new();
+ for r in roots {
+ let Ok(dirs) = std::fs::read_dir(&r) else { continue };
+ for d in dirs.flatten() {
+ let Ok(files) = std::fs::read_dir(d.path()) else { continue };
+ for f in files.flatten() {
+ let p = f.path();
+ if p.extension().is_some_and(|e| e == "f32")
+ && let Ok(txt) = std::fs::read_to_string(p.with_extension("txt"))
+ {
+ out.push((p, txt.trim().to_string()));
+ }
+ }
+ }
+ if !out.is_empty() {
+ break;
+ }
+ }
+ out.sort();
+ out
+}
+
+fn read_f32(p: &Path) -> Vec<f32> {
+ std::fs::read(p).unwrap().chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+#[test]
+fn tiny_model_transcribes_public_domain_speech() {
+ let Some(dir) = model_dir("whisper-tiny") else {
+ eprintln!("SKIPPED: whisper-tiny weights not found (see the test's module docs)");
+ return;
+ };
+ let samples = samples();
+ if samples.is_empty() {
+ eprintln!("SKIPPED: no speech samples in target/fixtures/speech");
+ return;
+ }
+ let w = filmcraft_speech::whisper::Whisper::load(&dir, "whisper-tiny").unwrap();
+ let opts = Options { language: Some("en".into()), diarize: false, ..Default::default() };
+ let (mut errs, mut words) = (0.0, 0usize);
+ for (p, reference) in samples.iter().take(8) {
+ let audio = read_f32(p);
+ let t = w.transcribe(&audio, &opts, &mut |_, _| true).unwrap();
+ let hyp = t.text();
+ let n = reference.split_whitespace().count();
+ errs += word_error_rate(reference, &hyp) * n as f64;
+ words += n;
+ // word times: in order, inside the audio
+ let end = filmcraft_speech::sample_tick(audio.len() as i64);
+ t.check().unwrap();
+ assert!(t.words.iter().all(|x| x.end <= end), "{}", p.display());
+ }
+ let wer = errs / words.max(1) as f64;
+ eprintln!("whisper-tiny WER {:.1}% over {words} words", wer * 100.0);
+ assert!(wer < 0.25, "WER {wer}");
+}
diff --git a/crates/ui-egui/src/panels/text.rs b/crates/ui-egui/src/panels/text.rs
index 7189c6508..748354121 100644
--- a/crates/ui-egui/src/panels/text.rs
+++ b/crates/ui-egui/src/panels/text.rs
@@ -1,7 +1,9 @@
//! The Text panel: Transcript / Captions / Graphics tabs. The Captions tab lists the caption
//! segments of a caption track with editable in/out timecodes and text, a toolbar (add, split,
//! merge, delete), track choice and the track style. Every edit dispatches a `captions.*` engine
-//! command; every widget registers an automation id (`text.*`).
+//! command; every widget registers an automation id (`text.*`). The Transcript tab shows the
+//! sequence transcript as speaker paragraphs of clickable words (click, Shift+click to extend);
+//! the selection marks In/Out and can be extracted or lifted (`transcript.*` commands).
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use filmcraft_project::{CaptionAlign, CaptionAnchor, CaptionFormat};
@@ -43,7 +45,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let body = Rect::from_min_max(pos2(rect.min.x, rect.min.y + 34.0), rect.max);
match app.ui.text_tab.as_str() {
"Captions" => captions(app, ui, body),
- "Transcript" => crate::dock::placeholder(ui, body, &t, "Transcript (speech-to-text) arrives in M10.5"),
+ "Transcript" => transcript(app, ui, body),
_ => crate::dock::placeholder(ui, body, &t, "Graphics text search arrives with M10.1–M10.2"),
}
}
@@ -258,6 +260,118 @@ fn captions(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
run(app, ui, actions);
}
+fn transcript(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
+ let t = app.tokens;
+ if app.session.active_sequence().is_none() {
+ crate::dock::placeholder(ui, rect, &t, "Open a sequence to see its transcript");
+ return;
+ }
+ let mut actions: Vec<(String, Value)> = Vec::new();
+ let words = filmcraft_engine::transcript::sequence_words(&app.session);
+ if words.is_empty() {
+ let c = rect.center();
+ icons::paint(ui.painter(), Rect::from_center_size(c - vec2(0.0, 70.0), vec2(40.0, 40.0)), Icon::Captions, t.text_dim);
+ ui.painter().text(c - vec2(0.0, 30.0), Align2::CENTER_CENTER, "Transcribe sequence", Tokens::semibold(16.0), t.text);
+ let note = if filmcraft_speech_available(app) {
+ "Speech-to-text turns the dialogue into editable text."
+ } else {
+ "This build has no speech-to-text; import a transcript with transcript.set."
+ };
+ ui.painter().text(c - vec2(0.0, 8.0), Align2::CENTER_CENTER, note, Tokens::ui(12.0), t.text_dim);
+ let r = Rect::from_center_size(c + vec2(0.0, 26.0), vec2(200.0, 26.0));
+ let resp = ui.interact(r, egui::Id::new("text.transcript.generate"), Sense::click());
+ ui.painter().rect_filled(r, 13.0, if resp.hovered() { t.accent_hover } else { t.accent });
+ ui.painter().text(r.center(), Align2::CENTER_CENTER, "Transcribe", Tokens::semibold(12.0), Color32::WHITE);
+ app.auto.add("text.transcript.generate", r, "Transcribe");
+ if resp.clicked() {
+ actions.push(("transcript.generate".into(), json!({})));
+ }
+ run(app, ui, actions);
+ return;
+ }
+ let sel = app.ui.transcript_sel.filter(|(a, b)| *a < words.len() && *b < words.len());
+ let (sa, sb) = sel.map(|(a, b)| (a.min(b), a.max(b))).unzip();
+
+ // ---- toolbar: search, extract / lift selection, remove fillers / pauses, captions
+ let bar = Rect::from_min_size(rect.min + vec2(10.0, 2.0), vec2(rect.width() - 20.0, 26.0));
+ let sw = 170.0f32.min(bar.width() * 0.4);
+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_min_size(bar.min, vec2(sw, 24.0))));
+ let sresp = crate::widgets::search_field(&mut child, &mut app.ui.transcript_search, "Search", sw, &t);
+ app.auto.add("text.transcript.search", sresp.rect, "Search transcript");
+ let hits: Vec<std::ops::Range<usize>> = filmcraft_edit::transcript::search(&words, &app.ui.transcript_search);
+ let mut x = bar.min.x + sw + 10.0;
+ let range = sel.map(|(a, b)| json!({"from": a.min(b), "to": a.max(b)}));
+ let tools: [(Icon, &str, &str, bool, &str, Value); 4] = [
+ (Icon::Razor, "text.transcript.extract", "Extract selected text", sel.is_some(), "transcript.extract", range.clone().unwrap_or_default()),
+ (Icon::Trash, "text.transcript.lift", "Lift selected text", sel.is_some(), "transcript.lift", range.unwrap_or_default()),
+ (Icon::Link, "text.transcript.removeFillers", "Remove filler words", true, "transcript.removeFillers", json!({})),
+ (Icon::Captions, "text.transcript.createCaptions", "Create captions", true, "transcript.createCaptions", json!({})),
+ ];
+ for (icon, id, label, enabled, cmd, params) in tools {
+ let r = Rect::from_min_size(pos2(x, bar.min.y), vec2(24.0, 24.0));
+ if r.max.x > rect.max.x {
+ break;
+ }
+ if tool_button(app, ui, r, icon, id, label, enabled) {
+ if cmd.ends_with("extract") || cmd.ends_with("lift") {
+ app.ui.transcript_sel = None;
+ }
+ actions.push((cmd.into(), params));
+ }
+ x += 28.0;
+ }
+
+ // ---- paragraphs of words
+ let list = Rect::from_min_max(pos2(rect.min.x + 6.0, bar.max.y + 8.0), pos2(rect.max.x - 6.0, rect.max.y - 4.0));
+ ui.painter().rect_filled(list, 3.0, t.app_bg);
+ let ph = app.session.playhead();
+ let current = filmcraft_edit::transcript::word_at(&words, ph);
+ let paras = filmcraft_edit::transcript::paragraphs(&words, filmcraft_time::Tick::from_seconds_f64(1.5));
+ let rate = app.session.sequence_rate();
+ let df = app.session.active_sequence().is_some_and(|q| q.settings.drop_frame);
+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(list.shrink(6.0)).id_salt("transcript-list"));
+ egui::ScrollArea::vertical().auto_shrink([false, false]).id_salt("transcript-scroll").show(&mut child, |ui| {
+ ui.set_width(list.width() - 16.0);
+ for (pi, pr) in paras.iter().enumerate() {
+ let w0 = &words[pr.start];
+ let head = format!("{} {}", w0.speaker.as_deref().unwrap_or("Speaker"), format_time(w0.start, rate, df, TimeDisplay::Timecode, 48_000));
+ let hr = ui.label(egui::RichText::new(head).size(11.0).color(t.text_dim).strong());
+ app.auto.add(&format!("text.transcript.paragraph.{pi}"), hr.rect, "Paragraph");
+ ui.horizontal_wrapped(|ui| {
+ ui.spacing_mut().item_spacing = vec2(4.0, 3.0);
+ for i in pr.clone() {
+ let w = &words[i];
+ let in_sel = sa.is_some_and(|a| i >= a) && sb.is_some_and(|b| i <= b);
+ let hit = hits.iter().any(|h| h.contains(&i));
+ let mut text = egui::RichText::new(&w.text).size(13.0).color(if Some(i) == current { t.hot_text } else { t.text });
+ if in_sel {
+ text = text.background_color(t.row_selected);
+ } else if hit {
+ text = text.background_color(t.hover);
+ }
+ let resp = ui.add(egui::Label::new(text).sense(Sense::click()));
+ app.auto.add(&format!("text.transcript.word.{i}"), resp.rect, &w.text);
+ if resp.clicked() {
+ let shift = ui.input(|inp| inp.modifiers.shift);
+ app.ui.transcript_sel = Some(match (shift, sel) {
+ (true, Some((a, _))) => (a, i),
+ _ => (i, i),
+ });
+ let (a, b) = app.ui.transcript_sel.unwrap_or((i, i));
+ actions.push(("transcript.select".into(), json!({"from": a.min(b), "to": a.max(b)})));
+ }
+ }
+ });
+ ui.add_space(8.0);
+ }
+ });
+ run(app, ui, actions);
+}
+
+fn filmcraft_speech_available(app: &FilmcraftApp) -> bool {
+ app.session.transcriber.is_some() || filmcraft_engine::transcript::speech_available()
+}
+
fn style_strip(app: &mut FilmcraftApp, ui: &mut egui::Ui, r: Rect, track_idx: usize, actions: &mut Vec<(String, Value)>) {
let Some(tr) = app.session.active_sequence().and_then(|q| q.caption_tracks.get(track_idx)).cloned() else { return };
let st = tr.style.clone();
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 3609f37c0..1e43cb6ec 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -283,6 +283,13 @@ pub struct UiState {
/// Text panel: caption search filter.
#[serde(default)]
pub caption_search: String,
+ /// Text panel ▸ Transcript: selected words of the sequence transcript (anchor, end; indices as
+ /// `transcript.inspect` lists them).
+ #[serde(default)]
+ pub transcript_sel: Option<(usize, usize)>,
+ /// Text panel ▸ Transcript: search text.
+ #[serde(default)]
+ pub transcript_search: String,
/// Preferences ▸ Playback: play the rendered range when a preview render finishes.
#[serde(default = "yes")]
pub play_after_render: bool,
@@ -553,6 +560,8 @@ impl Default for UiState {
export_burn_captions: false,
text_tab: captions_tab(),
caption_search: String::new(),
+ transcript_sel: None,
+ transcript_search: String::new(),
play_after_render: true,
mixer_fx_open: false,
audio_gain: AudioGainDraft::default(),
diff --git a/crates/ui-egui/tests/transcript_ui.rs b/crates/ui-egui/tests/transcript_ui.rs
new file mode 100644
index 000000000..105236cc0
--- /dev/null
+++ b/crates/ui-egui/tests/transcript_ui.rs
@@ -0,0 +1,112 @@
+//! Headless UI test of the Text panel's Transcript tab: the Transcribe button, the word view,
+//! clicking words (In/Out from the selection) and extracting the selected text.
+//!
+//! Set `FILMCRAFT_UI_SNAPSHOT_DIR=<dir>` to also render the window offscreen with wgpu and write
+//! `transcript-*.png` there; without it no GPU is needed.
+
+use std::sync::mpsc::{Sender, channel};
+
+use egui_kittest::Harness;
+use filmcraft_engine::Session;
+use filmcraft_ui_egui::FilmcraftApp;
+use filmcraft_ui_egui::control::ControlRequest;
+use serde_json::{Value, json};
+
+struct Driver {
+ harness: Harness<'static, FilmcraftApp>,
+ tx: Sender<ControlRequest>,
+ snapshots: Option<std::path::PathBuf>,
+}
+
+impl Driver {
+ fn demo() -> Self {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ let (tx, rx) = channel();
+ let app = FilmcraftApp::new(session).with_control(rx);
+ let snapshots = std::env::var_os("FILMCRAFT_UI_SNAPSHOT_DIR").map(std::path::PathBuf::from);
+ let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000);
+ if snapshots.is_some() {
+ b = b.wgpu();
+ }
+ let harness = b.build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, snapshots };
+ d.frames(4);
+ d
+ }
+
+ fn frames(&mut self, n: usize) {
+ for _ in 0..n {
+ let ctx = self.harness.ctx.clone();
+ let mut raw = std::mem::take(self.harness.input_mut());
+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);
+ *self.harness.input_mut() = raw;
+ self.harness.step();
+ }
+ }
+
+ fn ok(&mut self, method: &str, params: Value) -> Value {
+ let (req, reply) = ControlRequest::new(method, params.clone());
+ self.tx.send(req).unwrap();
+ for _ in 0..600 {
+ self.frames(1);
+ if let Ok(v) = reply.try_recv() {
+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");
+ return v["result"].clone();
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+
+ fn ids(&mut self, prefix: &str) -> Vec<String> {
+ let v = self.ok("ui.elements", json!({"prefix": prefix}));
+ v.as_array().unwrap().iter().filter_map(|e| e["id"].as_str().map(str::to_string)).collect()
+ }
+
+ fn snapshot(&mut self, name: &str) {
+ let Some(dir) = self.snapshots.clone() else { return };
+ self.frames(2);
+ match self.harness.render() {
+ Ok(img) => {
+ std::fs::create_dir_all(&dir).unwrap();
+ img.save(dir.join(format!("transcript-{name}.png"))).unwrap();
+ }
+ Err(e) => eprintln!("snapshot {name} skipped: {e}"),
+ }
+ }
+}
+
+#[test]
+fn transcript_tab_selects_and_extracts_words() {
+ let mut d = Driver::demo();
+ d.ok("ui.set", json!({"workspace": "Captions and Graphics"}));
+ d.frames(2);
+ d.ok("ui.click", json!({"id": "text.tab.Transcript"}));
+ d.frames(3);
+ assert_eq!(d.ids("text.transcript.generate"), vec!["text.transcript.generate".to_string()], "empty state offers Transcribe");
+
+ // bring a transcript for the first A1 clip's media (as an agent without a speech model would)
+ let mut probe = Session::default();
+ probe.execute("file.openDemoProject", json!({})).unwrap();
+ let a = probe.active_sequence().unwrap().audio_tracks[0].items[0].clone();
+ let tk = |s: f64| a.source_in.0 + (s * filmcraft_time::TICKS_PER_SECOND as f64) as i64;
+ let words: Vec<Value> = ["Hello", "um", "there", "friend."]
+ .iter()
+ .enumerate()
+ .map(|(i, w)| json!({"text": w, "start": tk(0.5 + i as f64 * 0.5), "end": tk(0.9 + i as f64 * 0.5), "speaker": 0}))
+ .collect();
+ d.ok("engine.execute", json!({"command": "transcript.set", "params": {"item": a.item.0, "transcript": {"language": "en", "words": words}}}));
+ d.frames(3);
+ let ids = d.ids("text.transcript.word.");
+ assert_eq!(ids.len(), 4, "{ids:?}");
+ d.snapshot("words");
+
+ d.ok("ui.click", json!({"id": "text.transcript.word.1"}));
+ d.frames(3);
+ d.ok("ui.click", json!({"id": "text.transcript.extract"}));
+ d.frames(3);
+ let r = d.ok("engine.execute", json!({"command": "transcript.inspect", "params": {}}));
+ let left: Vec<&str> = r["words"].as_array().unwrap().iter().filter_map(|w| w["text"].as_str()).collect();
+ assert_eq!(left, ["Hello", "there", "friend."]);
+ assert_eq!(d.ids("text.transcript.word.").len(), 3);
+}
diff --git a/docs/architecture.md b/docs/architecture.md
index c254f126e..e2e405a1c 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -24,7 +24,7 @@ Design principles:
L5 ui-egui · automation
L4 engine
L3 render · gpu · export · golden (test-only)
- L2 edit · codecs · interchange · captions
+ L2 edit · codecs · interchange · captions · speech
L1 frame · media · project · audio-dsp · text
L0 foundation: time · geom · color · bitstream · testkit (dev-dependency only)
codecs/containers: isobmff · matroska · h264 · h264enc · hevc · vp9 · av1 · prores · dnx · aac · opus
@@ -53,7 +53,8 @@ and `filmcraft-cli`.
| `project` | L1 | document model, effect definitions, keyframes |
| `audio-dsp` | L1 | loudness metering (BS.1770 / R128) and audio effects; no dependencies |
| `text` | L1 | text engine: font database (bundled OFL fonts + system fonts), shaping (harfrust), bidi, line breaking, paragraph layout, glyph/path rasteriser, strokes ([crates/text/README.md](../crates/text/README.md)) |
-| `edit` | L2 | pure edit algebra (insert, overwrite, razor, ripple, roll, slip, slide, rate stretch…) |
+| `edit` | L2 | pure edit algebra (insert, overwrite, razor, ripple, roll, slip, slide, rate stretch…; text-based editing: `edit::transcript`) |
+| `speech` | L2 | speech-to-text: `Transcriber` trait, Whisper model catalogue + verified downloader (feature `download`), pure-Rust Whisper inference on candle with word timestamps (feature `whisper`), speaker labelling ([transcripts.md](transcripts.md)) |
| `codecs` | L2 | container + codec hub: MP4/MOV and MKV sources, GOP-aware seeking, decoder registry, audio decoding |
| `interchange` | L2 | EDL, FCP7 XML, FCPXML and OTIO import/export (no file I/O) |
| `render` | L3 | sequence evaluation, CPU compositor, video effects, transitions, audio mix |
diff --git a/docs/project-files.md b/docs/project-files.md
index cba4230db..56df29e58 100644
--- a/docs/project-files.md
+++ b/docs/project-files.md
@@ -8,7 +8,7 @@ writing them is `crates/format` (`filmcraft-format`); the engine's `file.*` comm
```json
{
"format": "filmcraft.project",
- "schema_version": 8,
+ "schema_version": 9,
"generator": "FilmCraft 0.1.0",
"project": { "name": "…", "settings": { … }, "root": { … }, "items": { … }, "next_id": 48 }
}
@@ -32,6 +32,7 @@ writing them is `crates/format` (`filmcraft-format`); the engine's `file.*` comm
| 6 | M11.7/M11.9 | media identity fingerprints, ingest settings; no-op step |
| 7 | M5.5 | effect masks: `masks` on effect instances with keyframable Bézier `Path` values; no-op step |
| 8 | M12 | multi-camera source sequences and clips, merged clips; no-op step |
+| 9 | M10.5 | transcripts of media items (`project.transcripts`); no-op step |
### Migrations
@@ -59,8 +60,8 @@ on disk is unchanged until you save. The **first save over it** keeps the origin
A file with a `schema_version` newer than the build supports is **refused**, not half-read:
-> this project was saved by a newer version of FilmCraft (project schema v9); this build reads up to
-> v8. Update FilmCraft to open it.
+> this project was saved by a newer version of FilmCraft (project schema v10); this build reads up to
+> v9. Update FilmCraft to open it.
Reading it partially and saving it back would silently drop whatever the newer version added.
diff --git a/docs/transcripts.md b/docs/transcripts.md
new file mode 100644
index 000000000..4aa8a2f33
--- /dev/null
+++ b/docs/transcripts.md
@@ -0,0 +1,83 @@
+# Transcripts and text-based editing
+
+FilmCraft's Text panel ▸ **Transcript** tab shows the dialogue of the open sequence as text. Select
+words to mark In/Out, then extract or lift them; remove filler words and long pauses in one step;
+turn the transcript into captions. Every action is an engine command (`transcript.*`), so the CLI,
+the control channel and MCP agents can do the same.
+
+## Model
+
+- A **transcript** belongs to a media item (`Project::transcripts`, saved in the `.fcproj` since
+ schema v9). It lists **words** with media-time bounds (`Tick`s), an optional speaker index and a
+ confidence, plus the speaker names and the language. Because the times are media time, the
+ transcript stays valid however the clip is trimmed, moved, sped up or reused.
+- The **sequence transcript** is derived, never stored (`filmcraft_edit::transcript::sequence_words`):
+ audio tracks are read top first; a word is heard through the first enabled clip whose range
+ covers the word's midpoint (duplicates of the same dialogue on lower tracks read once); disabled,
+ reversed and frame-hold clips contribute nothing.
+- Speaker names come from the clip transcripts, so renaming "Speaker 1" in every transcript renames
+ it across the sequence.
+
+## Commands
+
+| Command | What it does |
+|---|---|
+| `transcript.generate` | Transcribe media items (`items`, else the Project selection, else the media of the sequence's audio clips). Params: `model` (default `whisper-base`), `language` (`auto` = detect), `diarize`, `maxSpeakers`. One undo step. |
+| `transcript.set` | Store a transcript you bring (JSON: `language`, `speakers`, `words` with `text`/`start`/`end`/`speaker`); it is sorted and made well formed. |
+| `transcript.delete` | Remove transcripts. |
+| `transcript.inspect` | The sequence transcript: words (index, text, sequence times, speaker, clip), paragraphs, speakers, the word at the playhead. |
+| `transcript.search` | Word-index ranges matching a phrase (case and punctuation ignored; the last word may be a prefix). |
+| `transcript.select` | Mark In/Out around words `from..=to` (frame-snapped outward) and move the playhead there. |
+| `transcript.extract` / `transcript.lift` | Extract (ripple) or lift the words' frames on the targeted tracks. |
+| `transcript.renameSpeaker` | Rename a speaker by name (every transcript) or by index in one `item`. |
+| `transcript.removeFillers` | Ripple-delete filler words (`fillers`, default um/uh/erm/…; phrases such as "you know" allowed). |
+| `transcript.removePauses` | Ripple-delete pauses longer than `minSeconds`, keeping `keepSeconds` of air on both sides. |
+| `transcript.createCaptions` | Lay the words out as captions on a new caption track (`maxChars`, `lines`, `minSeconds`, `maxSeconds`, `gapFrames`). |
+| `transcript.models` / `transcript.downloadModel` | List the speech models (size, licence, installed) / download one. |
+
+## Speech recognition
+
+Recognition goes through the `Transcriber` trait (`crates/speech`). The built-in recogniser is
+OpenAI's Whisper, run in pure Rust on [candle](https://github.com/huggingface/candle) on the CPU,
+with timestamp decoding, language detection and word times from cross-attention alignment (see the
+`filmcraft_speech::whisper` module docs). Speakers are labelled by clustering per-chunk MFCC
+statistics (`filmcraft_speech::diarize`); no model is involved.
+
+Both are **optional features**, off by default and never built for the web:
+
+- `whisper` (on `filmcraft-speech`, `filmcraft-engine`, and the `filmcraft` / `filmcraft-cli`
+ apps, where it also enables downloads): candle inference.
+- `download` (`speech-download` on the engine): HTTPS downloads with rustls + RustCrypto and the
+ operating system's certificate verifier.
+
+Without `whisper`, `transcript.generate` fails with "speech-to-text is not available in this build";
+transcripts can still be imported with `transcript.set` and edited with every other command. Hosts
+and tests can install any recogniser in `Session::transcriber`.
+
+### Models
+
+Weights are **never** bundled or committed. They are downloaded on request into
+`<data dir>/models/<id>/` (see `filmcraft_engine::autosave::default_data_dir`), each file pinned to a
+revision of OpenAI's Hugging Face repositories and checked against its SHA-256:
+
+| Id | Languages | Licence |
+|---|---|---|
+| `whisper-tiny` | multilingual | MIT (OpenAI); HF conversion Apache-2.0 |
+| `whisper-base` (default) | multilingual | MIT (OpenAI); HF conversion Apache-2.0 |
+| `whisper-small` | multilingual | MIT (OpenAI); HF conversion Apache-2.0 |
+
+### Testing
+
+Unit and engine tests use a fake `Transcriber` (`FixedTranscriber`), so CI needs no model. The
+end-to-end test `crates/speech/tests/whisper_model.rs` (feature `whisper`) runs only when weights are
+in `target/models/<id>/` (or `$FILMCRAFT_MODELS_DIR`) and speech samples (mono 16 kHz f32 with a
+reference `.txt`) are in `target/fixtures/speech/`; it reports the word error rate and otherwise
+prints SKIPPED. Measured on 2026-10-01: `whisper-tiny`, English, 12.2 % WER over 797 words of
+the local speech samples (LibriSpeech read speech and dialogue clips) (about 9.5 minutes for the run in a release build on an
+Apple-silicon laptop CPU).
+
+## Limits
+
+- Transcription runs synchronously inside the command (no background job or progress bar yet).
+- Track items that refer to a subclip are looked up by the subclip's id, so a transcript made for
+ the parent media is not shown through subclip clips yet.
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index 6d20437f0..be4064d4b 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -48,6 +48,7 @@ const LAYERS: &[(&str, u8)] = &[
("effects", 2),
("audio", 2),
("captions", 2),
+ ("speech", 2),
("interchange", 2),
("render", 3),
("gpu", 3),