Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: implement captions editor integration (#364)

David Anyatonwu09c449c80ba7
diff --git a/Cargo.lock b/Cargo.lock
index 2da95d142..ab4ff109b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -611,7 +611,7 @@ dependencies = [
"regex",
"rustc-hash 1.1.0",
"shlex 0.1.1",
- "which",
+ "which 3.1.1",
]
[[package]]
@@ -627,12 +627,15 @@ dependencies = [
"itertools",
"lazy_static",
"lazycell",
+ "log",
+ "prettyplease",
"proc-macro2",
"quote",
"regex",
"rustc-hash 1.1.0",
"shlex 1.3.0",
"syn 2.0.90",
+ "which 4.4.2",
]
[[package]]
@@ -934,6 +937,7 @@ dependencies = [
"anyhow",
"axum",
"base64 0.22.1",
+ "cap-audio",
"cap-editor",
"cap-export",
"cap-fail",
@@ -959,12 +963,13 @@ dependencies = [
"global-hotkey",
"image 0.25.5",
"keyed_priority_queue",
+ "lazy_static",
+ "log",
"md5",
"mp4",
"nix 0.29.0",
"objc",
"objc2-app-kit 0.3.0",
- "percent-encoding",
"png",
"rand 0.8.5",
"relative-path",
@@ -1006,6 +1011,7 @@ dependencies = [
"tracing-appender",
"tracing-subscriber",
"uuid",
+ "whisper-rs",
"windows 0.58.0",
"windows-sys 0.59.0",
]
@@ -1126,10 +1132,12 @@ name = "cap-project"
version = "0.1.0"
dependencies = [
"either",
+ "log",
"relative-path",
"serde",
"serde_json",
"specta",
+ "tracing",
]
[[package]]
@@ -1181,6 +1189,7 @@ dependencies = [
"ffmpeg-sys-next",
"futures",
"futures-intrusive",
+ "glyphon",
"image 0.25.5",
"log",
"pretty_assertions",
@@ -1256,9 +1265,9 @@ dependencies = [
[[package]]
name = "cc"
-version = "1.1.14"
+version = "1.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50d2eb3cd3d1bf4529e31c215ee6f93ec5a3d536d9f578f93d9d33ee19562932"
+checksum = "16595d3be041c03b09d08d0858631facccee9221e579704070e6e9e4915d3bc7"
dependencies = [
"jobserver",
"libc",
@@ -1470,6 +1479,15 @@ dependencies = [
"windows-win",
]
+[[package]]
+name = "cmake"
+version = "0.1.54"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "cocoa"
version = "0.20.2"
@@ -1946,6 +1964,29 @@ dependencies = [
"bindgen 0.69.4",
]
+[[package]]
+name = "cosmic-text"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59fd57d82eb4bfe7ffa9b1cec0c05e2fd378155b47f255a67983cb4afe0e80c2"
+dependencies = [
+ "bitflags 2.9.0",
+ "fontdb",
+ "log",
+ "rangemap",
+ "rayon",
+ "rustc-hash 1.1.0",
+ "rustybuzz",
+ "self_cell",
+ "swash",
+ "sys-locale",
+ "ttf-parser 0.21.1",
+ "unicode-bidi",
+ "unicode-linebreak",
+ "unicode-script",
+ "unicode-segmentation",
+]
+
[[package]]
name = "cpal"
version = "0.15.3"
@@ -2561,6 +2602,25 @@ version = "3.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9305ccc6942a704f4335694ecd3de2ea531b114ac2d51f5f843750787a92f"
+[[package]]
+name = "etagere"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc89bf99e5dc15954a60f707c1e09d7540e5cd9af85fa75caa0b510bc08c5342"
+dependencies = [
+ "euclid",
+ "svg_fmt",
+]
+
+[[package]]
+name = "euclid"
+version = "0.22.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad9cdb4b747e485a12abb0e6566612956c7a1bafa3bdb8d682c5b6d403589e48"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "event-listener"
version = "5.3.1"
@@ -2720,6 +2780,38 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+[[package]]
+name = "font-types"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b3971f9a5ca983419cdc386941ba3b9e1feba01a0ab888adf78739feb2798492"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "fontconfig-parser"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
+dependencies = [
+ "roxmltree",
+]
+
+[[package]]
+name = "fontdb"
+version = "0.16.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0299020c3ef3f60f526a4f64ab4a3d4ce116b1acbf24cdd22da0068e5d81dc3"
+dependencies = [
+ "fontconfig-parser",
+ "log",
+ "memmap2",
+ "slotmap",
+ "tinyvec",
+ "ttf-parser 0.20.0",
+]
+
[[package]]
name = "foreign-types"
version = "0.3.2"
@@ -2777,6 +2869,12 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c661315fd366b2a1f970df7b7cb1a28d2678d49ef4872f7dcc19b4a83150f20b"
+[[package]]
+name = "fs_extra"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
+
[[package]]
name = "futf"
version = "0.1.5"
@@ -3218,6 +3316,19 @@ dependencies = [
"gl_generator",
]
+[[package]]
+name = "glyphon"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b11b1afb04c1a1be055989042258499473d0a9447f16450b433aba10bc2a46e7"
+dependencies = [
+ "cosmic-text",
+ "etagere",
+ "lru",
+ "rustc-hash 2.1.1",
+ "wgpu",
+]
+
[[package]]
name = "gobject-sys"
version = "0.18.0"
@@ -3444,6 +3555,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"
+[[package]]
+name = "home"
+version = "0.5.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf"
+dependencies = [
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "hostname"
version = "0.4.0"
@@ -4109,6 +4229,12 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "libm"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de"
+
[[package]]
name = "libredox"
version = "0.1.3"
@@ -4185,6 +4311,12 @@ dependencies = [
"imgref",
]
+[[package]]
+name = "lru"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"
+
[[package]]
name = "mac"
version = "0.1.1"
@@ -4288,6 +4420,15 @@ version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
+[[package]]
+name = "memmap2"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3f7eed9d3848f8b98834af67102b720745c4ec028fcd0aa0239277e7de374f"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "memoffset"
version = "0.9.1"
@@ -5664,6 +5805,16 @@ dependencies = [
"yansi",
]
+[[package]]
+name = "prettyplease"
+version = "0.2.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033"
+dependencies = [
+ "proc-macro2",
+ "syn 2.0.90",
+]
+
[[package]]
name = "proc-macro-crate"
version = "1.3.1"
@@ -5818,7 +5969,7 @@ dependencies = [
"pin-project-lite",
"quinn-proto",
"quinn-udp",
- "rustc-hash 2.0.0",
+ "rustc-hash 2.1.1",
"rustls",
"socket2",
"thiserror 1.0.69",
@@ -5835,7 +5986,7 @@ dependencies = [
"bytes",
"rand 0.8.5",
"ring",
- "rustc-hash 2.0.0",
+ "rustc-hash 2.1.1",
"rustls",
"slab",
"thiserror 1.0.69",
@@ -5952,6 +6103,12 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8a99fddc9f0ba0a85884b8d14e3592853e787d581ca1816c91349b10e4eeab"
+[[package]]
+name = "rangemap"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f60fcc7d6849342eff22c4350c8b9a989ee8ceabc4b481253e8946b9fe83d684"
+
[[package]]
name = "rav1e"
version = "0.7.1"
@@ -6040,13 +6197,23 @@ dependencies = [
"guardian",
"or_poisoned",
"pin-project-lite",
- "rustc-hash 2.0.0",
+ "rustc-hash 2.1.1",
"send_wrapper",
"slotmap",
"thiserror 2.0.6",
"web-sys",
]
+[[package]]
+name = "read-fonts"
+version = "0.22.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69aacb76b5c29acfb7f90155d39759a29496aebb49395830e928a9703d2eec2f"
+dependencies = [
+ "bytemuck",
+ "font-types",
+]
+
[[package]]
name = "readkey"
version = "0.2.2"
@@ -6263,6 +6430,12 @@ dependencies = [
"thiserror 1.0.69",
]
+[[package]]
+name = "roxmltree"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+
[[package]]
name = "rust-ini"
version = "0.21.1"
@@ -6288,9 +6461,9 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
[[package]]
name = "rustc-hash"
-version = "2.0.0"
+version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "583034fd73374156e66797ed8e5b0d5690409c9226b22d87cb7f19821c05d152"
+checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
name = "rustc_version"
@@ -6361,6 +6534,23 @@ version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6"
+[[package]]
+name = "rustybuzz"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfb9cf8877777222e4a3bc7eb247e398b56baba500c38c1c46842431adc8b55c"
+dependencies = [
+ "bitflags 2.9.0",
+ "bytemuck",
+ "libm",
+ "smallvec",
+ "ttf-parser 0.21.1",
+ "unicode-bidi-mirroring",
+ "unicode-ccc",
+ "unicode-properties",
+ "unicode-script",
+]
+
[[package]]
name = "ryu"
version = "1.0.18"
@@ -6505,6 +6695,12 @@ dependencies = [
"thin-slice",
]
+[[package]]
+name = "self_cell"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f7d95a54511e0c7be3f51e8867aa8cf35148d7b9445d44de2f943e2b206e749"
+
[[package]]
name = "semver"
version = "1.0.23"
@@ -6905,6 +7101,16 @@ version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
+[[package]]
+name = "skrifa"
+version = "0.22.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e1c44ad1f6c5bdd4eefed8326711b7dbda9ea45dfd36068c427d332aa382cbe"
+dependencies = [
+ "bytemuck",
+ "read-fonts",
+]
+
[[package]]
name = "slab"
version = "0.4.9"
@@ -7108,6 +7314,23 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+[[package]]
+name = "svg_fmt"
+version = "0.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb"
+
+[[package]]
+name = "swash"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cbd59f3f359ddd2c95af4758c18270eddd9c730dde98598023cdabff472c2ca2"
+dependencies = [
+ "skrifa",
+ "yazi",
+ "zeno",
+]
+
[[package]]
name = "swift-rs"
version = "1.0.7"
@@ -8396,6 +8619,18 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "ttf-parser"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4"
+
+[[package]]
+name = "ttf-parser"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8"
+
[[package]]
name = "tungstenite"
version = "0.24.0"
@@ -8502,12 +8737,30 @@ version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75"
+[[package]]
+name = "unicode-bidi-mirroring"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23cb788ffebc92c5948d0e997106233eeb1d8b9512f93f41651f52b6c5f5af86"
+
+[[package]]
+name = "unicode-ccc"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656"
+
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+[[package]]
+name = "unicode-linebreak"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
+
[[package]]
name = "unicode-normalization"
version = "0.1.23"
@@ -8517,6 +8770,18 @@ dependencies = [
"tinyvec",
]
+[[package]]
+name = "unicode-properties"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0"
+
+[[package]]
+name = "unicode-script"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fb421b350c9aff471779e262955939f565ec18b86c15364e6bdf0d662ca7c1f"
+
[[package]]
name = "unicode-segmentation"
version = "1.11.0"
@@ -9076,6 +9341,39 @@ dependencies = [
"libc",
]
+[[package]]
+name = "which"
+version = "4.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"
+dependencies = [
+ "either",
+ "home",
+ "once_cell",
+ "rustix",
+]
+
+[[package]]
+name = "whisper-rs"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed7a191078e189d96d029244ab1dff159775adec71dc89a222e9bb9d21a7d161"
+dependencies = [
+ "whisper-rs-sys",
+]
+
+[[package]]
+name = "whisper-rs-sys"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2834f4ca6472b02748c6c282a60cea538f962428f79e685c3205a08efd711336"
+dependencies = [
+ "bindgen 0.69.4",
+ "cfg-if 1.0.0",
+ "cmake",
+ "fs_extra",
+]
+
[[package]]
name = "widestring"
version = "1.2.0"
@@ -10009,6 +10307,12 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "yazi"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c94451ac9513335b5e23d7a8a2b61a7102398b8cca5160829d313e84c9d98be1"
+
[[package]]
name = "zbus"
version = "4.4.0"
@@ -10135,6 +10439,12 @@ dependencies = [
"zvariant 5.2.0",
]
+[[package]]
+name = "zeno"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd15f8e0dbb966fd9245e7498c7e9e5055d9e5c8b676b95bd67091cd11a1e697"
+
[[package]]
name = "zerocopy"
version = "0.7.35"
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 14f40f18c..c07214fbb 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -76,7 +76,9 @@ cpal.workspace = true
keyed_priority_queue = "0.4.2"
sentry.workspace = true
clipboard-rs = "0.2.2"
-percent-encoding = { workspace = true }
+whisper-rs = "0.11.0"
+lazy_static = "1.4.0"
+log = "0.4.20"
cap-utils = { path = "../../../crates/utils" }
cap-project = { path = "../../../crates/project" }
@@ -86,6 +88,7 @@ cap-media = { path = "../../../crates/media" }
cap-flags = { path = "../../../crates/flags" }
cap-recording = { path = "../../../crates/recording" }
cap-export = { path = "../../../crates/export" }
+cap-audio = { path = "../../../crates/audio" }
flume.workspace = true
tracing-subscriber = "0.3.19"
tracing-appender = "0.2.3"
diff --git a/apps/desktop/src-tauri/src/captions.rs b/apps/desktop/src-tauri/src/captions.rs
new file mode 100644
index 000000000..a7a76b57a
--- /dev/null
+++ b/apps/desktop/src-tauri/src/captions.rs
@@ -0,0 +1,1277 @@
+use anyhow::Result;
+use cap_audio::AudioData;
+use cap_project;
+use ffmpeg::{
+ codec as avcodec,
+ format::{self as avformat},
+ software::resampling,
+ ChannelLayout,
+};
+use reqwest::Client;
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use std::fs::File;
+use std::io::Read;
+use std::path::PathBuf;
+use std::sync::Arc;
+use tauri::{AppHandle, Emitter, Manager, Window};
+use tempfile::tempdir;
+use tokio::io::AsyncWriteExt;
+use tokio::sync::Mutex;
+use whisper_rs::{FullParams, SamplingStrategy, WhisperContext, WhisperContextParameters};
+
+// Re-export caption types from cap_project
+pub use cap_project::{CaptionSegment, CaptionSettings};
+
+// Convert the project type's float precision from f32 to f64 for compatibility
+#[derive(Debug, Serialize, Deserialize, Type, Clone)]
+pub struct CaptionData {
+ pub segments: Vec<CaptionSegment>,
+ pub settings: Option<CaptionSettings>,
+}
+
+impl Default for CaptionData {
+ fn default() -> Self {
+ Self {
+ segments: Vec::new(),
+ settings: Some(CaptionSettings::default()),
+ }
+ }
+}
+
+// Model context is shared and cached
+lazy_static::lazy_static! {
+ static ref WHISPER_CONTEXT: Arc<Mutex<Option<WhisperContext>>> = Arc::new(Mutex::new(None));
+}
+
+// Constants
+const WHISPER_SAMPLE_RATE: u32 = 16000;
+
+/// Function to handle creating directories for the model
+#[tauri::command]
+#[specta::specta]
+pub async fn create_dir(path: String, _recursive: bool) -> Result<(), String> {
+ std::fs::create_dir_all(path).map_err(|e| format!("Failed to create directory: {}", e))
+}
+
+/// Function to save the model file
+#[tauri::command]
+#[specta::specta]
+pub async fn save_model_file(path: String, data: Vec<u8>) -> Result<(), String> {
+ std::fs::write(&path, &data).map_err(|e| format!("Failed to write model file: {}", e))
+}
+
+/// Extract audio from a video file and save it as a temporary WAV file
+async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Result<(), String> {
+ log::info!("Attempting to extract audio from: {}", video_path);
+
+ // Check if this is a .cap directory
+ if video_path.ends_with(".cap") {
+ log::info!("Detected .cap project directory");
+
+ // Read the recording metadata
+ let meta_path = std::path::Path::new(video_path).join("recording-meta.json");
+ let meta_content = std::fs::read_to_string(&meta_path)
+ .map_err(|e| format!("Failed to read recording metadata: {}", e))?;
+
+ let meta: serde_json::Value = serde_json::from_str(&meta_content)
+ .map_err(|e| format!("Failed to parse recording metadata: {}", e))?;
+
+ // Get paths for both audio sources
+ let base_path = std::path::Path::new(video_path);
+ let mut audio_sources = Vec::new();
+
+ if let Some(segments) = meta["segments"].as_array() {
+ for segment in segments {
+ // Add system audio if available
+ if let Some(system_audio) = segment["system_audio"]["path"].as_str() {
+ audio_sources.push(base_path.join(system_audio));
+ }
+
+ // Add microphone audio if available
+ if let Some(audio) = segment["audio"]["path"].as_str() {
+ audio_sources.push(base_path.join(audio));
+ }
+ }
+ }
+
+ if audio_sources.is_empty() {
+ return Err("No audio sources found in the recording metadata".to_string());
+ }
+
+ log::info!("Found {} audio sources", audio_sources.len());
+
+ // Process each audio source using AudioData
+ let mut mixed_samples = Vec::new();
+ let mut channel_count = 0;
+
+ for source in audio_sources {
+ match AudioData::from_file(&source) {
+ Ok(audio) => {
+ log::info!(
+ "Processing audio source {:?}: {} channels, {} samples",
+ source,
+ audio.channels(),
+ audio.sample_count()
+ );
+
+ if mixed_samples.is_empty() {
+ mixed_samples = audio.samples().to_vec();
+ channel_count = audio.channels() as usize;
+ } else {
+ // Handle potential different channel counts by mixing to mono first if needed
+ if audio.channels() as usize != channel_count {
+ log::info!(
+ "Channel count mismatch: {} vs {}, mixing to mono",
+ channel_count,
+ audio.channels()
+ );
+
+ // If we have mixed samples with multiple channels, convert to mono
+ if channel_count > 1 {
+ let mono_samples = convert_to_mono(&mixed_samples, channel_count);
+ mixed_samples = mono_samples;
+ channel_count = 1;
+ }
+
+ // Convert the new audio to mono too if it has multiple channels
+ let samples = if audio.channels() > 1 {
+ convert_to_mono(audio.samples(), audio.channels() as usize)
+ } else {
+ audio.samples().to_vec()
+ };
+
+ // Mix mono samples
+ mix_samples(&mut mixed_samples, &samples);
+ } else {
+ // Same channel count, simple mix
+ mix_samples(&mut mixed_samples, audio.samples());
+ }
+ }
+ }
+ Err(e) => {
+ log::warn!("Failed to process audio source {:?}: {}", source, e);
+ continue;
+ }
+ }
+ }
+
+ // No matter what, ensure we have mono audio for Whisper
+ if channel_count > 1 {
+ log::info!(
+ "Converting final mixed audio from {} channels to mono",
+ channel_count
+ );
+ mixed_samples = convert_to_mono(&mixed_samples, channel_count);
+ channel_count = 1;
+ }
+
+ if mixed_samples.is_empty() {
+ return Err("Failed to process any audio sources".to_string());
+ }
+
+ // Convert to WAV format with desired sample rate
+ let mut output = avformat::output(&output_path)
+ .map_err(|e| format!("Failed to create output file: {}", e))?;
+
+ let codec = avcodec::encoder::find_by_name("pcm_s16le")
+ .ok_or_else(|| "PCM encoder not found".to_string())?;
+
+ let mut encoder = avcodec::Context::new()
+ .encoder()
+ .audio()
+ .map_err(|e| format!("Failed to create encoder: {}", e))?;
+
+ encoder.set_rate(WHISPER_SAMPLE_RATE as i32);
+ let channel_layout = ChannelLayout::MONO;
+ encoder.set_channel_layout(channel_layout);
+ encoder.set_format(avformat::Sample::I16(avformat::sample::Type::Packed));
+
+ let mut encoder = encoder
+ .open_as(codec)
+ .map_err(|e| format!("Failed to open encoder: {}", e))?;
+
+ let mut stream = output
+ .add_stream(codec)
+ .map_err(|e| format!("Failed to add stream: {}", e))?;
+ stream.set_parameters(&encoder);
+
+ output
+ .write_header()
+ .map_err(|e| format!("Failed to write header: {}", e))?;
+
+ // Create resampler for sample rate conversion
+ let mut resampler = resampling::Context::get(
+ avformat::Sample::F32(avformat::sample::Type::Packed),
+ channel_layout,
+ AudioData::SAMPLE_RATE,
+ avformat::Sample::I16(avformat::sample::Type::Packed),
+ channel_layout,
+ WHISPER_SAMPLE_RATE,
+ )
+ .map_err(|e| format!("Failed to create resampler: {}", e))?;
+
+ // Process audio in chunks
+ let frame_size = encoder.frame_size() as usize;
+ // Check if frame_size is zero and use a fallback
+ let frame_size = if frame_size == 0 { 1024 } else { frame_size };
+
+ log::info!(
+ "Using frame size: {}, total samples: {}, channel count: {}",
+ frame_size,
+ mixed_samples.len(),
+ channel_count
+ );
+
+ let mut frame = ffmpeg::frame::Audio::new(
+ avformat::Sample::I16(avformat::sample::Type::Packed),
+ frame_size,
+ ChannelLayout::MONO,
+ );
+ frame.set_rate(WHISPER_SAMPLE_RATE);
+
+ // Make sure we have samples and a valid chunk size
+ if !mixed_samples.is_empty() && frame_size * channel_count > 0 {
+ // Process chunks of audio
+ for (chunk_idx, chunk) in mixed_samples.chunks(frame_size * channel_count).enumerate() {
+ if chunk_idx % 100 == 0 {
+ log::info!("Processing chunk {}, size: {}", chunk_idx, chunk.len());
+ }
+
+ // Create a new input frame with actual data from the chunk
+ let mut input_frame = ffmpeg::frame::Audio::new(
+ avformat::Sample::F32(avformat::sample::Type::Packed),
+ chunk.len() / channel_count,
+ channel_layout,
+ );
+ input_frame.set_rate(AudioData::SAMPLE_RATE);
+
+ // Copy data from chunk to frame
+ let bytes = unsafe {
+ std::slice::from_raw_parts(
+ chunk.as_ptr() as *const u8,
+ chunk.len() * std::mem::size_of::<f32>(),
+ )
+ };
+ input_frame.data_mut(0)[0..bytes.len()].copy_from_slice(bytes);
+
+ // Create output frame for resampled data
+ let mut output_frame = ffmpeg::frame::Audio::new(
+ avformat::Sample::I16(avformat::sample::Type::Packed),
+ frame_size,
+ ChannelLayout::MONO,
+ );
+ output_frame.set_rate(WHISPER_SAMPLE_RATE);
+
+ // Use the input frame with actual data instead of the empty frame
+ match resampler.run(&input_frame, &mut output_frame) {
+ Ok(_) => {
+ if chunk_idx % 100 == 0 {
+ log::info!(
+ "Successfully resampled chunk {}, output samples: {}",
+ chunk_idx,
+ output_frame.samples()
+ );
+ }
+ }
+ Err(e) => {
+ log::error!("Failed to resample chunk {}: {}", chunk_idx, e);
+ continue;
+ }
+ }
+
+ if let Err(e) = encoder.send_frame(&output_frame) {
+ log::error!("Failed to send frame to encoder: {}", e);
+ continue;
+ }
+
+ // Process each encoded packet
+ loop {
+ let mut packet = ffmpeg::Packet::empty();
+ match encoder.receive_packet(&mut packet) {
+ Ok(_) => {
+ if let Err(e) = packet.write_interleaved(&mut output) {
+ log::error!("Failed to write packet: {}", e);
+ }
+ }
+ Err(_) => break,
+ }
+ }
+ }
+ }
+
+ // Flush the encoder
+ encoder
+ .send_eof()
+ .map_err(|e| format!("Failed to send EOF: {}", e))?;
+
+ // Process final packets in a loop with limited borrow scope
+ loop {
+ let mut packet = ffmpeg::Packet::empty();
+ let received = encoder.receive_packet(&mut packet);
+
+ if received.is_err() {
+ break;
+ }
+
+ // Use a block to limit the scope of the output borrow
+ {
+ if let Err(e) = packet.write_interleaved(&mut output) {
+ return Err(format!("Failed to write final packet: {}", e));
+ }
+ }
+ }
+
+ output
+ .write_trailer()
+ .map_err(|e| format!("Failed to write trailer: {}", e))?;
+
+ Ok(())
+ } else {
+ // Handle regular video file
+ let mut input = avformat::input(&video_path)
+ .map_err(|e| format!("Failed to open video file: {}", e))?;
+
+ let stream = input
+ .streams()
+ .best(ffmpeg::media::Type::Audio)
+ .ok_or_else(|| "No audio stream found".to_string())?;
+
+ let codec_params = stream.parameters();
+
+ // Get decoder parameters first
+ let decoder_ctx = avcodec::Context::from_parameters(codec_params.clone())
+ .map_err(|e| format!("Failed to create decoder context: {}", e))?;
+
+ // Create and open the decoder
+ let mut decoder = decoder_ctx
+ .decoder()
+ .audio()
+ .map_err(|e| format!("Failed to create decoder: {}", e))?;
+
+ // Now we can access audio-specific methods
+ let decoder_format = decoder.format();
+ let decoder_channel_layout = decoder.channel_layout();
+ let decoder_rate = decoder.rate();
+
+ // Set up and prepare encoder and output separately to avoid multiple borrows
+ let channel_layout = ChannelLayout::MONO;
+
+ // Create encoder first
+ let mut encoder_ctx = avcodec::Context::new()
+ .encoder()
+ .audio()
+ .map_err(|e| format!("Failed to create encoder: {}", e))?;
+
+ encoder_ctx.set_rate(WHISPER_SAMPLE_RATE as i32);
+ encoder_ctx.set_channel_layout(channel_layout);
+ encoder_ctx.set_format(avformat::Sample::I16(avformat::sample::Type::Packed));
+
+ let codec = avcodec::encoder::find_by_name("pcm_s16le")
+ .ok_or_else(|| "PCM encoder not found".to_string())?;
+
+ let mut encoder = encoder_ctx
+ .open_as(codec)
+ .map_err(|e| format!("Failed to open encoder: {}", e))?;
+
+ // Create output context separately
+ let mut output = avformat::output(&output_path)
+ .map_err(|e| format!("Failed to create output file: {}", e))?;
+
+ // Add stream and get parameters in a block to limit the borrow
+ let stream_params = {
+ let mut output_stream = output
+ .add_stream(codec)
+ .map_err(|e| format!("Failed to add stream: {}", e))?;
+
+ output_stream.set_parameters(&encoder);
+
+ // Store the stream parameters we need for later
+ (output_stream.index(), output_stream.id())
+ };
+
+ // Write header
+ output
+ .write_header()
+ .map_err(|e| format!("Failed to write header: {}", e))?;
+
+ // Create resampler
+ let mut resampler = resampling::Context::get(
+ decoder_format,
+ decoder_channel_layout,
+ decoder_rate,
+ avformat::Sample::I16(avformat::sample::Type::Packed),
+ channel_layout,
+ WHISPER_SAMPLE_RATE,
+ )
+ .map_err(|e| format!("Failed to create resampler: {}", e))?;
+
+ // Create frames
+ let mut decoded_frame = ffmpeg::frame::Audio::empty();
+ let mut resampled_frame = ffmpeg::frame::Audio::new(
+ avformat::Sample::I16(avformat::sample::Type::Packed),
+ encoder.frame_size() as usize,
+ channel_layout,
+ );
+
+ // Save the stream index from the original stream (not the output stream)
+ let input_stream_index = stream.index();
+
+ // Process packets one at a time, cloning what we need from input packets
+ let mut packet_queue = Vec::new();
+
+ // First collect all the packets we need by cloning the data
+ {
+ // Use a separate block to limit the immutable borrow lifetime
+ for (stream_idx, packet) in input.packets() {
+ if stream_idx.index() == input_stream_index {
+ // Clone the packet data to avoid borrowing input
+ if let Some(data) = packet.data() {
+ // Copy the packet data to a new packet
+ let mut cloned_packet = ffmpeg::Packet::copy(data);
+ // Copy timing information
+ if let Some(pts) = packet.pts() {
+ cloned_packet.set_pts(Some(pts));
+ }
+ if let Some(dts) = packet.dts() {
+ cloned_packet.set_dts(Some(dts));
+ }
+ packet_queue.push(cloned_packet);
+ }
+ }
+ }
+ }
+
+ // Then process each cloned packet
+ for packet_res in packet_queue {
+ if let Err(e) = decoder.send_packet(&packet_res) {
+ log::warn!("Failed to send packet to decoder: {}", e);
+ continue;
+ }
+
+ // Process decoded frames
+ while let Ok(_) = decoder.receive_frame(&mut decoded_frame) {
+ if let Err(e) = resampler.run(&decoded_frame, &mut resampled_frame) {
+ log::warn!("Failed to resample audio: {}", e);
+ continue;
+ }
+
+ if let Err(e) = encoder.send_frame(&resampled_frame) {
+ log::warn!("Failed to send frame to encoder: {}", e);
+ continue;
+ }
+
+ // Process encoded packets
+ loop {
+ let mut packet = ffmpeg::Packet::empty();
+ match encoder.receive_packet(&mut packet) {
+ Ok(_) => {
+ // Set the stream for the output packet
+ packet.set_stream(stream_params.0);
+
+ if let Err(e) = packet.write_interleaved(&mut output) {
+ log::error!("Failed to write packet: {}", e);
+ }
+ }
+ Err(_) => break,
+ }
+ }
+ }
+ }
+
+ // Flush the decoder
+ decoder
+ .send_eof()
+ .map_err(|e| format!("Failed to send EOF to decoder: {}", e))?;
+
+ while decoder.receive_frame(&mut decoded_frame).is_ok() {
+ resampler
+ .run(&decoded_frame, &mut resampled_frame)
+ .map_err(|e| format!("Failed to resample final audio: {}", e))?;
+
+ encoder
+ .send_frame(&resampled_frame)
+ .map_err(|e| format!("Failed to send final frame: {}", e))?;
+
+ // Process final encoded packets
+ loop {
+ let mut packet = ffmpeg::Packet::empty();
+ let received = encoder.receive_packet(&mut packet);
+
+ if received.is_err() {
+ break;
+ }
+
+ packet
+ .write_interleaved(&mut output)
+ .map_err(|e| format!("Failed to write final packet: {}", e))?;
+ }
+ }
+
+ // Close the output file with trailer
+ output
+ .write_trailer()
+ .map_err(|e| format!("Failed to write trailer: {}", e))?;
+
+ Ok(())
+ }
+}
+
+/// Load or initialize the WhisperContext
+async fn get_whisper_context(model_path: &str) -> Result<Arc<WhisperContext>, String> {
+ let mut context_guard = WHISPER_CONTEXT.lock().await;
+
+ // Always create a new context to avoid issues with multiple uses
+ log::info!("Initializing Whisper context with model: {}", model_path);
+ let ctx = WhisperContext::new_with_params(model_path, WhisperContextParameters::default())
+ .map_err(|e| format!("Failed to load Whisper model: {}", e))?;
+
+ *context_guard = Some(ctx);
+
+ // Get a reference to the context and wrap it in an Arc
+ let context_ref = context_guard.as_ref().unwrap();
+ let context_arc = unsafe { Arc::new(std::ptr::read(context_ref)) };
+ Ok(context_arc)
+}
+
+/// Process audio file with Whisper for transcription
+fn process_with_whisper(
+ audio_path: &PathBuf,
+ context: Arc<WhisperContext>,
+ language: &str,
+) -> Result<CaptionData, String> {
+ log::info!("Processing audio file: {:?}", audio_path);
+
+ // Set up parameters for Whisper
+ let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 });
+
+ // Configure parameters for better caption quality
+ params.set_translate(false);
+ params.set_print_special(false);
+ params.set_print_progress(false);
+ params.set_print_realtime(false);
+ params.set_token_timestamps(true); // Enable timestamps for captions
+ params.set_language(Some(if language == "auto" { "auto" } else { language })); // Use selected language or auto-detect
+ params.set_max_len(i32::MAX); // No max length for transcription
+
+ // Load audio file
+ let mut audio_file = File::open(audio_path)
+ .map_err(|e| format!("Failed to open audio file: {} at path: {:?}", e, audio_path))?;
+ let mut audio_data = Vec::new();
+ audio_file
+ .read_to_end(&mut audio_data)
+ .map_err(|e| format!("Failed to read audio file: {}", e))?;
+
+ log::info!("Processing audio file of size: {} bytes", audio_data.len());
+
+ // Convert audio data to the required format (16-bit mono PCM)
+ let mut audio_data_f32 = Vec::new();
+ for i in (0..audio_data.len()).step_by(2) {
+ if i + 1 < audio_data.len() {
+ let sample = i16::from_le_bytes([audio_data[i], audio_data[i + 1]]) as f32 / 32768.0;
+ audio_data_f32.push(sample);
+ }
+ }
+
+ log::info!("Converted {} samples to f32 format", audio_data_f32.len());
+
+ // Log sample data statistics for debugging
+ if !audio_data_f32.is_empty() {
+ let min_sample = audio_data_f32.iter().fold(f32::MAX, |a, &b| a.min(b));
+ let max_sample = audio_data_f32.iter().fold(f32::MIN, |a, &b| a.max(b));
+ let avg_sample = audio_data_f32.iter().sum::<f32>() / audio_data_f32.len() as f32;
+ log::info!(
+ "Audio samples - min: {}, max: {}, avg: {}",
+ min_sample,
+ max_sample,
+ avg_sample
+ );
+
+ // Sample a few values
+ let sample_count = audio_data_f32.len().min(10);
+ for i in 0..sample_count {
+ let idx = i * audio_data_f32.len() / sample_count;
+ log::info!("Sample {}: {}", idx, audio_data_f32[idx]);
+ }
+ }
+
+ // Run the transcription
+ let mut state = context
+ .create_state()
+ .map_err(|e| format!("Failed to create Whisper state: {}", e))?;
+
+ state
+ .full(params, &audio_data_f32[..])
+ .map_err(|e| format!("Failed to run Whisper transcription: {}", e))?;
+
+ // Process results: convert Whisper segments to CaptionSegment
+ let num_segments = state
+ .full_n_segments()
+ .map_err(|e| format!("Failed to get number of segments: {}", e))?;
+
+ log::info!("Found {} segments", num_segments);
+
+ let mut segments = Vec::new();
+
+ for i in 0..num_segments {
+ let text = state
+ .full_get_segment_text(i)
+ .map_err(|e| format!("Failed to get segment text: {}", e))?;
+
+ // Properly unwrap the Result first, then convert i64 to f64
+ let start_i64 = state
+ .full_get_segment_t0(i)
+ .map_err(|e| format!("Failed to get segment start time: {}", e))?;
+ let end_i64 = state
+ .full_get_segment_t1(i)
+ .map_err(|e| format!("Failed to get segment end time: {}", e))?;
+
+ // Convert timestamps from centiseconds to seconds (as f32 for CaptionSegment)
+ let start_time = (start_i64 as f32) / 100.0;
+ let end_time = (end_i64 as f32) / 100.0;
+
+ // Add debug logging for timestamps
+ log::info!(
+ "Segment {}: start={}, end={}, text='{}'",
+ i,
+ start_time,
+ end_time,
+ text.trim()
+ );
+
+ if !text.trim().is_empty() {
+ segments.push(CaptionSegment {
+ id: format!("segment-{}", i),
+ start: start_time,
+ end: end_time,
+ text: text.trim().to_string(),
+ });
+ }
+ }
+
+ log::info!("Successfully processed {} segments", segments.len());
+
+ Ok(CaptionData {
+ segments,
+ settings: Some(cap_project::CaptionSettings::default()),
+ })
+}
+
+/// Function to transcribe audio from a video file using Whisper
+#[tauri::command]
+#[specta::specta]
+pub async fn transcribe_audio(
+ video_path: String,
+ model_path: String,
+ language: String,
+) -> Result<CaptionData, String> {
+ // Check if files exist with detailed error messages
+ if !std::path::Path::new(&video_path).exists() {
+ return Err(format!("Video file not found at path: {}", video_path));
+ }
+
+ if !std::path::Path::new(&model_path).exists() {
+ return Err(format!("Model file not found at path: {}", model_path));
+ }
+
+ // Create temp dir with better error handling
+ let temp_dir = tempdir().map_err(|e| format!("Failed to create temporary directory: {}", e))?;
+ let audio_path = temp_dir.path().join("audio.wav");
+
+ // First try the ffmpeg implementation
+ match extract_audio_from_video(&video_path, &audio_path).await {
+ Ok(_) => log::info!("Successfully extracted audio to {:?}", audio_path),
+ Err(e) => {
+ log::error!("Failed to extract audio: {}", e);
+ return Err(format!("Failed to extract audio from video: {}", e));
+ }
+ }
+
+ // Verify the audio file was created
+ if !audio_path.exists() {
+ return Err("Failed to create audio file for transcription".to_string());
+ }
+
+ log::info!("Audio file created at: {:?}", audio_path);
+
+ // Get or initialize Whisper context with detailed error handling
+ let context = match get_whisper_context(&model_path).await {
+ Ok(ctx) => ctx,
+ Err(e) => {
+ log::error!("Failed to initialize Whisper context: {}", e);
+ return Err(format!("Failed to initialize transcription model: {}", e));
+ }
+ };
+
+ // Process with Whisper and handle errors
+ match process_with_whisper(&audio_path, context, &language) {
+ Ok(captions) => {
+ if captions.segments.is_empty() {
+ log::warn!("No caption segments were generated");
+ return Err("No speech detected in the audio".to_string());
+ }
+ Ok(captions)
+ }
+ Err(e) => {
+ log::error!("Failed to process audio with Whisper: {}", e);
+ Err(format!("Failed to transcribe audio: {}", e))
+ }
+ }
+}
+
+/// Function to save caption data to a file
+#[tauri::command]
+#[specta::specta]
+pub async fn save_captions(
+ video_id: String,
+ captions: CaptionData,
+ app: AppHandle,
+) -> Result<(), String> {
+ tracing::info!("Saving captions for video_id: {}", video_id);
+
+ let captions_dir = app_captions_dir(&app, &video_id)?;
+
+ if !captions_dir.exists() {
+ tracing::info!("Creating captions directory: {:?}", captions_dir);
+ std::fs::create_dir_all(&captions_dir).map_err(|e| {
+ tracing::error!("Failed to create captions directory: {}", e);
+ format!("Failed to create captions directory: {}", e)
+ })?;
+ }
+
+ let captions_path = captions_dir.join("captions.json");
+
+ tracing::info!("Writing captions to: {:?}", captions_path);
+
+ // Ensure settings are included with default values if not provided
+ let settings = captions.settings.unwrap_or_default();
+
+ // Create a JSON structure manually to ensure field naming consistency
+ let mut json_obj = serde_json::Map::new();
+
+ // Add segments array
+ let segments_array = serde_json::to_value(
+ captions
+ .segments
+ .iter()
+ .map(|seg| {
+ let mut segment = serde_json::Map::new();
+ segment.insert("id".to_string(), serde_json::Value::String(seg.id.clone()));
+ segment.insert(
+ "start".to_string(),
+ serde_json::Value::Number(
+ serde_json::Number::from_f64(seg.start as f64).unwrap(),
+ ),
+ );
+ segment.insert(
+ "end".to_string(),
+ serde_json::Value::Number(
+ serde_json::Number::from_f64(seg.end as f64).unwrap(),
+ ),
+ );
+ segment.insert(
+ "text".to_string(),
+ serde_json::Value::String(seg.text.clone()),
+ );
+ segment
+ })
+ .collect::<Vec<_>>(),
+ )
+ .map_err(|e| {
+ tracing::error!("Failed to serialize captions segments: {}", e);
+ format!("Failed to serialize captions: {}", e)
+ })?;
+
+ json_obj.insert("segments".to_string(), segments_array);
+
+ // Add settings object with camelCase naming
+ let mut settings_obj = serde_json::Map::new();
+ settings_obj.insert(
+ "enabled".to_string(),
+ serde_json::Value::Bool(settings.enabled),
+ );
+ settings_obj.insert(
+ "font".to_string(),
+ serde_json::Value::String(settings.font.clone()),
+ );
+ settings_obj.insert(
+ "size".to_string(),
+ serde_json::Value::Number(serde_json::Number::from(settings.size)),
+ );
+ settings_obj.insert(
+ "color".to_string(),
+ serde_json::Value::String(settings.color.clone()),
+ );
+ settings_obj.insert(
+ "backgroundColor".to_string(),
+ serde_json::Value::String(settings.background_color.clone()),
+ );
+ settings_obj.insert(
+ "backgroundOpacity".to_string(),
+ serde_json::Value::Number(serde_json::Number::from(settings.background_opacity)),
+ );
+ settings_obj.insert(
+ "position".to_string(),
+ serde_json::Value::String(settings.position.clone()),
+ );
+ settings_obj.insert("bold".to_string(), serde_json::Value::Bool(settings.bold));
+ settings_obj.insert(
+ "italic".to_string(),
+ serde_json::Value::Bool(settings.italic),
+ );
+ settings_obj.insert(
+ "outline".to_string(),
+ serde_json::Value::Bool(settings.outline),
+ );
+ settings_obj.insert(
+ "outlineColor".to_string(),
+ serde_json::Value::String(settings.outline_color.clone()),
+ );
+ settings_obj.insert(
+ "exportWithSubtitles".to_string(),
+ serde_json::Value::Bool(settings.export_with_subtitles),
+ );
+
+ json_obj.insert(
+ "settings".to_string(),
+ serde_json::Value::Object(settings_obj),
+ );
+
+ // Convert to pretty JSON string
+ let json = serde_json::to_string_pretty(&json_obj).map_err(|e| {
+ tracing::error!("Failed to serialize captions: {}", e);
+ format!("Failed to serialize captions: {}", e)
+ })?;
+
+ std::fs::write(captions_path, json).map_err(|e| {
+ tracing::error!("Failed to write captions file: {}", e);
+ format!("Failed to write captions file: {}", e)
+ })?;
+
+ tracing::info!("Successfully saved captions");
+ Ok(())
+}
+
+/// Helper function to parse captions from a JSON string
+/// This can be used by other modules to parse captions without duplicating code
+pub fn parse_captions_json(json: &str) -> Result<cap_project::CaptionsData, String> {
+ // Use a more flexible parsing approach
+ match serde_json::from_str::<serde_json::Value>(json) {
+ Ok(json_value) => {
+ if let Some(segments_array) = json_value.get("segments").and_then(|v| v.as_array()) {
+ let mut segments = Vec::new();
+
+ // Process each segment
+ for segment in segments_array {
+ if let (Some(id), Some(start), Some(end), Some(text)) = (
+ segment.get("id").and_then(|v| v.as_str()),
+ segment.get("start").and_then(|v| v.as_f64()),
+ segment.get("end").and_then(|v| v.as_f64()),
+ segment.get("text").and_then(|v| v.as_str()),
+ ) {
+ segments.push(cap_project::CaptionSegment {
+ id: id.to_string(),
+ start: start as f32,
+ end: end as f32,
+ text: text.to_string(),
+ });
+ }
+ }
+
+ // Get settings or use defaults
+ let settings = if let Some(settings_obj) = json_value.get("settings") {
+ // Extract each field with proper fallbacks
+ let enabled = settings_obj
+ .get("enabled")
+ .and_then(|v| v.as_bool())
+ .unwrap_or_default();
+ let font = settings_obj
+ .get("font")
+ .and_then(|v| v.as_str())
+ .unwrap_or("System Sans-Serif")
+ .to_string();
+ let size = settings_obj
+ .get("size")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(24) as u32;
+ let color = settings_obj
+ .get("color")
+ .and_then(|v| v.as_str())
+ .unwrap_or("#FFFFFF")
+ .to_string();
+
+ // Handle both camelCase and snake_case field names
+ let background_color = settings_obj
+ .get("backgroundColor")
+ .or_else(|| settings_obj.get("background_color"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("#000000")
+ .to_string();
+
+ let background_opacity = settings_obj
+ .get("backgroundOpacity")
+ .or_else(|| settings_obj.get("background_opacity"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(80) as u32;
+
+ let position = settings_obj
+ .get("position")
+ .and_then(|v| v.as_str())
+ .unwrap_or("bottom")
+ .to_string();
+ let bold = settings_obj
+ .get("bold")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(true);
+ let italic = settings_obj
+ .get("italic")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ let outline = settings_obj
+ .get("outline")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(true);
+
+ let outline_color = settings_obj
+ .get("outlineColor")
+ .or_else(|| settings_obj.get("outline_color"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("#000000")
+ .to_string();
+
+ let export_with_subtitles = settings_obj
+ .get("exportWithSubtitles")
+ .or_else(|| settings_obj.get("export_with_subtitles"))
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ cap_project::CaptionSettings {
+ enabled,
+ font,
+ size,
+ color,
+ background_color,
+ background_opacity,
+ position,
+ bold,
+ italic,
+ outline,
+ outline_color,
+ export_with_subtitles,
+ }
+ } else {
+ // Use default settings if none provided
+ cap_project::CaptionSettings::default()
+ };
+
+ Ok(cap_project::CaptionsData { segments, settings })
+ } else {
+ Err("Missing or invalid segments array in captions file".to_string())
+ }
+ }
+ Err(e) => Err(format!("Failed to parse captions JSON: {}", e)),
+ }
+}
+
+/// Function to load caption data from a file
+#[tauri::command]
+#[specta::specta]
+pub async fn load_captions(
+ video_id: String,
+ app: AppHandle,
+) -> Result<Option<CaptionData>, String> {
+ tracing::info!("Loading captions for video_id: {}", video_id);
+ let captions_dir = app_captions_dir(&app, &video_id)?;
+ let captions_path = captions_dir.join("captions.json");
+
+ if !captions_path.exists() {
+ tracing::info!("No captions file found at: {:?}", captions_path);
+ return Ok(None);
+ }
+
+ tracing::info!("Reading captions from: {:?}", captions_path);
+ let json = match std::fs::read_to_string(captions_path.clone()) {
+ Ok(j) => j,
+ Err(e) => {
+ tracing::error!("Failed to read captions file: {}", e);
+ return Err(format!("Failed to read captions file: {}", e));
+ }
+ };
+
+ tracing::info!("Parsing captions JSON");
+ match parse_captions_json(&json) {
+ Ok(project_captions) => {
+ tracing::info!(
+ "Successfully loaded {} caption segments",
+ project_captions.segments.len()
+ );
+
+ // Create the CaptionData structure
+ let tauri_captions = CaptionData {
+ segments: project_captions.segments,
+ settings: Some(project_captions.settings),
+ };
+
+ Ok(Some(tauri_captions))
+ }
+ Err(e) => {
+ tracing::error!("Failed to parse captions: {}", e);
+ Err(format!("Failed to parse captions: {}", e))
+ }
+ }
+}
+
+/// Helper function to get the captions directory for a video
+fn app_captions_dir(app: &AppHandle, video_id: &str) -> Result<PathBuf, String> {
+ tracing::info!("Getting captions directory for video_id: {}", video_id);
+
+ // Get the app data directory
+ let app_dir = app
+ .path()
+ .app_data_dir()
+ .map_err(|_| "Failed to get app data directory".to_string())?;
+
+ // Create a dedicated captions directory
+ // Strip .cap extension if present in video_id
+ let clean_video_id = video_id.trim_end_matches(".cap");
+ let captions_dir = app_dir.join("captions").join(clean_video_id);
+
+ tracing::info!("Captions directory path: {:?}", captions_dir);
+ Ok(captions_dir)
+}
+
+// Add new type for download progress
+#[derive(Debug, Serialize, Type, tauri_specta::Event, Clone)]
+pub struct DownloadProgress {
+ pub progress: f64,
+ pub message: String,
+}
+
+impl DownloadProgress {
+ const EVENT_NAME: &'static str = "download-progress";
+}
+
+/// Helper function to download a Whisper model from Hugging Face Hub
+#[tauri::command]
+#[specta::specta]
+pub async fn download_whisper_model(
+ window: Window,
+ model_name: String,
+ output_path: String,
+) -> Result<(), String> {
+ // Define model URLs based on model names
+ let model_url = match model_name.as_str() {
+ "tiny" => "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.bin",
+ "base" => "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.bin",
+ "small" => "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin",
+ "medium" => "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-medium.bin",
+ "large" => "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-large-v3.bin",
+ "large-v3" => "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-large-v3.bin",
+ _ => "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.bin", // Default to tiny
+ };
+
+ // Create the client and download the model
+ let client = Client::new();
+ let response = client
+ .get(model_url)
+ .send()
+ .await
+ .map_err(|e| format!("Failed to download model: {}", e))?;
+
+ if !response.status().is_success() {
+ return Err(format!(
+ "Failed to download model: HTTP {}",
+ response.status()
+ ));
+ }
+
+ // Get the total size for progress calculation
+ let total_size = response.content_length().unwrap_or(0);
+
+ // Create a file to write to
+ if let Some(parent) = std::path::Path::new(&output_path).parent() {
+ std::fs::create_dir_all(parent)
+ .map_err(|e| format!("Failed to create parent directories: {}", e))?;
+ }
+ let mut file = tokio::fs::File::create(&output_path)
+ .await
+ .map_err(|e| format!("Failed to create file: {}", e))?;
+
+ // Download and write in chunks
+ let mut downloaded = 0;
+ let mut bytes = response
+ .bytes()
+ .await
+ .map_err(|e| format!("Failed to get response bytes: {}", e))?;
+
+ // Write the bytes in chunks to show progress
+ const CHUNK_SIZE: usize = 1024 * 1024; // 1MB chunks
+ while !bytes.is_empty() {
+ let chunk_size = std::cmp::min(CHUNK_SIZE, bytes.len());
+ let chunk = bytes.split_to(chunk_size);
+
+ file.write_all(&chunk)
+ .await
+ .map_err(|e| format!("Error while writing to file: {}", e))?;
+
+ downloaded += chunk_size as u64;
+
+ // Calculate and emit progress
+ let progress = if total_size > 0 {
+ (downloaded as f64 / total_size as f64) * 100.0
+ } else {
+ 0.0
+ };
+
+ window
+ .emit(
+ DownloadProgress::EVENT_NAME,
+ DownloadProgress {
+ message: format!("Downloading model: {:.1}%", progress),
+ progress,
+ },
+ )
+ .map_err(|e| format!("Failed to emit progress: {}", e))?;
+ }
+
+ // Ensure file is properly written
+ file.flush()
+ .await
+ .map_err(|e| format!("Failed to flush file: {}", e))?;
+
+ Ok(())
+}
+
+/// Function to check if a model file exists
+#[tauri::command]
+#[specta::specta]
+pub async fn check_model_exists(model_path: String) -> Result<bool, String> {
+ Ok(std::path::Path::new(&model_path).exists())
+}
+
+/// Function to delete a downloaded model
+#[tauri::command]
+#[specta::specta]
+pub async fn delete_whisper_model(model_path: String) -> Result<(), String> {
+ if !std::path::Path::new(&model_path).exists() {
+ return Err(format!("Model file not found: {}", model_path));
+ }
+
+ tokio::fs::remove_file(&model_path)
+ .await
+ .map_err(|e| format!("Failed to delete model file: {}", e))?;
+
+ Ok(())
+}
+
+/// Convert caption segments to SRT format
+fn captions_to_srt(captions: &CaptionData) -> String {
+ let mut srt = String::new();
+ for (i, segment) in captions.segments.iter().enumerate() {
+ // Convert start and end times from seconds to HH:MM:SS,mmm format
+ let start_time = format_srt_time(f64::from(segment.start));
+ let end_time = format_srt_time(f64::from(segment.end));
+
+ // Write SRT entry
+ srt.push_str(&format!(
+ "{}\n{} --> {}\n{}\n\n",
+ i + 1,
+ start_time,
+ end_time,
+ segment.text.trim()
+ ));
+ }
+ srt
+}
+
+/// Format time in seconds to SRT time format (HH:MM:SS,mmm)
+fn format_srt_time(seconds: f64) -> String {
+ let hours = (seconds / 3600.0) as i32;
+ let minutes = ((seconds % 3600.0) / 60.0) as i32;
+ let secs = (seconds % 60.0) as i32;
+ let millis = ((seconds % 1.0) * 1000.0) as i32;
+ format!("{:02}:{:02}:{:02},{:03}", hours, minutes, secs, millis)
+}
+
+/// Export captions to an SRT file
+#[tauri::command]
+#[specta::specta]
+pub async fn export_captions_srt(
+ video_id: String,
+ app: AppHandle,
+) -> Result<Option<PathBuf>, String> {
+ tracing::info!("Starting SRT export for video_id: {}", video_id);
+
+ // Load captions
+ tracing::info!("Loading captions from storage");
+ let captions = match load_captions(video_id.clone(), app.clone()).await? {
+ Some(c) => {
+ tracing::info!("Found {} caption segments to export", c.segments.len());
+ c
+ }
+ None => {
+ tracing::info!("No captions found for video_id: {}", video_id);
+ return Ok(None);
+ }
+ };
+
+ // Ensure we have settings (this should already be handled by load_captions,
+ // but we add this check for extra safety)
+ let captions_with_settings = CaptionData {
+ segments: captions.segments,
+ settings: captions
+ .settings
+ .or_else(|| Some(CaptionSettings::default())),
+ };
+
+ // Convert to SRT format
+ tracing::info!("Converting captions to SRT format");
+ let srt_content = captions_to_srt(&captions_with_settings);
+
+ // Get path for SRT file
+ let captions_dir = app_captions_dir(&app, &video_id)?;
+ let srt_path = captions_dir.join("captions.srt");
+ tracing::info!("Will write SRT file to: {:?}", srt_path);
+
+ // Write SRT file
+ match std::fs::write(&srt_path, srt_content) {
+ Ok(_) => {
+ tracing::info!("Successfully wrote SRT file to: {:?}", srt_path);
+ Ok(Some(srt_path))
+ }
+ Err(e) => {
+ tracing::error!("Failed to write SRT file: {}", e);
+ Err(format!("Failed to write SRT file: {}", e))
+ }
+ }
+}
+
+// Helper function to convert multi-channel audio to mono
+fn convert_to_mono(samples: &[f32], channels: usize) -> Vec<f32> {
+ if channels == 1 {
+ return samples.to_vec();
+ }
+
+ let sample_count = samples.len() / channels;
+ let mut mono_samples = Vec::with_capacity(sample_count);
+
+ for i in 0..sample_count {
+ let mut sample_sum = 0.0;
+ for c in 0..channels {
+ sample_sum += samples[i * channels + c];
+ }
+ mono_samples.push(sample_sum / channels as f32);
+ }
+
+ mono_samples
+}
+
+// Helper function to mix two sample arrays together
+fn mix_samples(dest: &mut Vec<f32>, source: &[f32]) -> usize {
+ let length = dest.len().min(source.len());
+ for i in 0..length {
+ // Simple mix with equal weight (0.5) to prevent clipping
+ dest[i] = (dest[i] + source[i]) * 0.5;
+ }
+ length
+}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index d199d89d3..8ce67a1fb 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1,6 +1,7 @@
mod audio;
mod auth;
mod camera;
+mod captions;
mod flags;
mod general_settings;
mod hotkeys;
@@ -35,6 +36,7 @@ use cap_project::{ProjectConfiguration, RecordingMeta, SharingMeta, StudioRecord
use cap_recording::RecordingMode;
use cap_recording::RecordingOptions;
use cap_rendering::ProjectRecordings;
+use captions::DownloadProgress;
use clipboard_rs::common::RustImage;
use clipboard_rs::{Clipboard, ClipboardContext};
use editor_window::EditorInstances;
@@ -2008,7 +2010,16 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
update_auth_plan,
set_window_transparent,
get_editor_meta,
- set_server_url
+ set_server_url,
+ captions::create_dir,
+ captions::save_model_file,
+ captions::transcribe_audio,
+ captions::save_captions,
+ captions::load_captions,
+ captions::download_whisper_model,
+ captions::check_model_exists,
+ captions::delete_whisper_model,
+ captions::export_captions_srt
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
@@ -2028,6 +2039,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
AuthenticationInvalid,
audio_meter::AudioInputLevelChange,
UploadProgress,
+ captions::DownloadProgress,
])
.error_handling(tauri_specta::ErrorHandlingMode::Throw)
.typ::<ProjectConfiguration>()
diff --git a/apps/desktop/src/routes/editor/CaptionsTab.tsx b/apps/desktop/src/routes/editor/CaptionsTab.tsx
new file mode 100644
index 000000000..4e502da58
--- /dev/null
+++ b/apps/desktop/src/routes/editor/CaptionsTab.tsx
@@ -0,0 +1,1157 @@
+import { batch, createEffect, createSignal, onMount, Show } from "solid-js";
+import { createStore } from "solid-js/store";
+import { appLocalDataDir, join } from "@tauri-apps/api/path";
+import { exists } from "@tauri-apps/plugin-fs";
+import toast from "solid-toast";
+import { Button } from "@cap/ui-solid";
+import { Select as KSelect } from "@kobalte/core/select";
+import { createWritableMemo } from "@solid-primitives/memo";
+import { createElementSize } from "@solid-primitives/resize-observer";
+
+import { MenuItem, MenuItemList, PopperContent } from "./ui";
+import { topLeftAnimateClasses } from "./ui";
+import { TextInput } from "./TextInput";
+import { Toggle } from "~/components/Toggle";
+import type { CaptionSettings, CaptionSegment } from "~/utils/tauri";
+import { Field, Slider, Subfield, Input } from "./ui";
+import { useEditorContext, FPS, OUTPUT_SIZE } from "./context";
+import { commands, events } from "~/utils/tauri";
+
+// Model information
+interface ModelOption {
+ name: string;
+ label: string;
+}
+
+interface LanguageOption {
+ code: string;
+ label: string;
+}
+
+interface FontOption {
+ value: string;
+ label: string;
+}
+
+const MODEL_OPTIONS: ModelOption[] = [
+ { name: "tiny", label: "Tiny (75MB) - Fastest, less accurate" },
+ { name: "base", label: "Base (142MB) - Fast, decent accuracy" },
+ { name: "small", label: "Small (466MB) - Balanced speed/accuracy" },
+ { name: "medium", label: "Medium (1.5GB) - Slower, more accurate" },
+ { name: "large-v3", label: "Large (3GB) - Slowest, most accurate" },
+];
+
+const LANGUAGE_OPTIONS: LanguageOption[] = [
+ { code: "auto", label: "Auto Detect" },
+ { code: "en", label: "English" },
+ { code: "es", label: "Spanish" },
+ { code: "fr", label: "French" },
+ { code: "de", label: "German" },
+ { code: "it", label: "Italian" },
+ { code: "pt", label: "Portuguese" },
+ { code: "nl", label: "Dutch" },
+ { code: "pl", label: "Polish" },
+ { code: "ru", label: "Russian" },
+ { code: "tr", label: "Turkish" },
+ { code: "ja", label: "Japanese" },
+ { code: "ko", label: "Korean" },
+ { code: "zh", label: "Chinese" },
+];
+
+const DEFAULT_MODEL = "tiny";
+const MODEL_FOLDER = "transcription_models";
+
+// Custom flat button component since we can't import it
+function FlatButton(props: {
+ class?: string;
+ onClick?: () => void;
+ disabled?: boolean;
+ children: any;
+}) {
+ return (
+ <button
+ class={`px-3 py-1.5 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors ${
+ props.class || ""
+ }`}
+ onClick={props.onClick}
+ disabled={props.disabled}
+ >
+ {props.children}
+ </button>
+ );
+}
+
+const fontOptions = [
+ { value: "System Sans-Serif", label: "System Sans-Serif" },
+ { value: "System Serif", label: "System Serif" },
+ { value: "System Monospace", label: "System Monospace" },
+];
+
+// Add type definitions at the top
+interface CaptionsResponse {
+ segments: CaptionSegment[];
+}
+
+// Color conversion types
+type RGB = [number, number, number];
+
+// Helper functions for color conversion
+function hexToRgb(hex: string): RGB {
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+ return result
+ ? [
+ parseInt(result[1], 16),
+ parseInt(result[2], 16),
+ parseInt(result[3], 16),
+ ]
+ : [0, 0, 0];
+}
+
+function rgbToHex(rgb: RGB): string {
+ return `#${rgb.map((x) => x.toString(16).padStart(2, "0")).join("")}`;
+}
+
+// Add RgbInput component at the top level
+function RgbInput(props: { value: string; onChange: (value: string) => void }) {
+ const [text, setText] = createWritableMemo(() => props.value);
+ let prevColor = props.value;
+ let colorInput!: HTMLInputElement;
+
+ return (
+ <div class="flex flex-row items-center gap-[0.75rem] relative">
+ <button
+ type="button"
+ class="size-[3rem] rounded-[0.5rem]"
+ style={{
+ "background-color": text(),
+ }}
+ onClick={() => colorInput.click()}
+ />
+ <input
+ ref={colorInput}
+ type="color"
+ class="absolute left-0 bottom-0 w-[3rem] opacity-0"
+ value={text()}
+ onChange={(e) => {
+ setText(e.target.value);
+ props.onChange(e.target.value);
+ }}
+ />
+ <TextInput
+ class="w-[5rem] p-[0.375rem] border text-gray-400 rounded-[0.5rem] bg-gray-50"
+ value={text()}
+ onFocus={() => {
+ prevColor = props.value;
+ }}
+ onInput={(e) => {
+ setText(e.currentTarget.value);
+ props.onChange(e.currentTarget.value);
+ }}
+ onBlur={(e) => {
+ if (!/^#[0-9A-F]{6}$/i.test(e.target.value)) {
+ setText(prevColor);
+ props.onChange(prevColor);
+ }
+ }}
+ />
+ </div>
+ );
+}
+
+// Add scroll position preservation for the container
+export function CaptionsTab() {
+ const { project, setProject, editorInstance, editorState } =
+ useEditorContext();
+
+ // Scroll management
+ let scrollContainerRef: HTMLDivElement | undefined;
+ const [scrollState, setScrollState] = createStore({
+ lastScrollTop: 0,
+ isScrolling: false,
+ });
+
+ // Track container size changes
+ const size = createElementSize(() => scrollContainerRef);
+
+ // Create a local store for caption settings to avoid direct project mutations
+ const [captionSettings, setCaptionSettings] = createStore(
+ project?.captions?.settings || {
+ enabled: false,
+ font: "Arial",
+ size: 24,
+ color: "#FFFFFF",
+ backgroundColor: "#000000",
+ backgroundOpacity: 80,
+ position: "bottom",
+ bold: true,
+ italic: false,
+ outline: true,
+ outlineColor: "#000000",
+ exportWithSubtitles: false,
+ }
+ );
+
+ // Sync caption settings with project and update player
+ createEffect(() => {
+ if (!project?.captions) return;
+
+ const settings = captionSettings;
+
+ // Only update if there are actual changes
+ if (
+ JSON.stringify(settings) !== JSON.stringify(project.captions.settings)
+ ) {
+ batch(() => {
+ // Update project settings
+ setProject("captions", "settings", settings);
+
+ // Force player refresh
+ events.renderFrameEvent.emit({
+ frame_number: Math.floor(editorState.playbackTime * FPS),
+ fps: FPS,
+ resolution_base: OUTPUT_SIZE,
+ });
+ });
+ }
+ });
+
+ // Sync project settings to local store
+ createEffect(() => {
+ if (project?.captions?.settings) {
+ setCaptionSettings(project.captions.settings);
+ }
+ });
+
+ // Helper function to update caption settings
+ const updateCaptionSetting = (key: keyof CaptionSettings, value: any) => {
+ if (!project?.captions) return;
+
+ // Store scroll position before update
+ if (scrollContainerRef) {
+ setScrollState("lastScrollTop", scrollContainerRef.scrollTop);
+ }
+
+ // Update local store
+ setCaptionSettings({
+ ...captionSettings,
+ [key]: value,
+ });
+
+ // For font changes, force an immediate player update
+ if (key === "font") {
+ events.renderFrameEvent.emit({
+ frame_number: Math.floor(editorState.playbackTime * FPS),
+ fps: FPS,
+ resolution_base: OUTPUT_SIZE,
+ });
+ }
+ };
+
+ // Restore scroll position after any content changes
+ createEffect(() => {
+ // Track any size changes
+ const _ = size.height;
+
+ // Restore scroll position if we have one
+ if (scrollContainerRef && scrollState.lastScrollTop > 0) {
+ requestAnimationFrame(() => {
+ scrollContainerRef!.scrollTop = scrollState.lastScrollTop;
+ });
+ }
+ });
+
+ // Add model selection state
+ const [selectedModel, setSelectedModel] = createSignal(DEFAULT_MODEL);
+ const [selectedLanguage, setSelectedLanguage] = createSignal("auto");
+ const [downloadedModels, setDownloadedModels] = createSignal<string[]>([]);
+
+ // States for captions
+ const [modelExists, setModelExists] = createSignal(false);
+ const [isDownloading, setIsDownloading] = createSignal(false);
+ const [downloadProgress, setDownloadProgress] = createSignal(0);
+ const [downloadingModel, setDownloadingModel] = createSignal<string | null>(
+ null
+ );
+ const [isGenerating, setIsGenerating] = createSignal(false);
+ const [hasAudio, setHasAudio] = createSignal(false);
+ const [modelPath, setModelPath] = createSignal("");
+ const [currentCaption, setCurrentCaption] = createSignal<string | null>(null);
+
+ // Ensure captions object is initialized in project config
+ createEffect(() => {
+ if (!project || !editorInstance) return;
+
+ if (!project.captions) {
+ // Initialize captions with default settings
+ setProject("captions", {
+ segments: [],
+ settings: {
+ enabled: false,
+ font: "Arial",
+ size: 24,
+ color: "#FFFFFF",
+ backgroundColor: "#000000",
+ backgroundOpacity: 80,
+ position: "bottom",
+ bold: true,
+ italic: false,
+ outline: true,
+ outlineColor: "#000000",
+ exportWithSubtitles: false,
+ },
+ });
+ }
+ });
+
+ // Check downloaded models on mount
+ onMount(async () => {
+ try {
+ // Check for downloaded models
+ const appDataDirPath = await appLocalDataDir();
+ const modelsPath = await join(appDataDirPath, MODEL_FOLDER);
+
+ // Create models directory if it doesn't exist
+ if (!(await exists(modelsPath))) {
+ await commands.createDir(modelsPath, true);
+ }
+
+ // Check which models are already downloaded
+ const models = await Promise.all(
+ MODEL_OPTIONS.map(async (model) => {
+ const downloaded = await checkModelExists(model.name);
+ return { name: model.name, downloaded };
+ })
+ );
+
+ // Set available models
+ setDownloadedModels(
+ models.filter((m) => m.downloaded).map((m) => m.name)
+ );
+
+ // Check if current model exists
+ if (selectedModel()) {
+ setModelExists(await checkModelExists(selectedModel()));
+ }
+
+ // Check if the video has audio
+ if (editorInstance && editorInstance.recordings) {
+ const hasAudioTrack = editorInstance.recordings.segments.some(
+ (segment) => segment.mic !== null || segment.system_audio !== null
+ );
+ setHasAudio(hasAudioTrack);
+ }
+
+ // Restore download state if there was an ongoing download
+ const downloadState = localStorage.getItem("modelDownloadState");
+ if (downloadState) {
+ const { model, progress } = JSON.parse(downloadState);
+ if (model && progress < 100) {
+ setDownloadingModel(model);
+ setDownloadProgress(progress);
+ setIsDownloading(true);
+ } else {
+ localStorage.removeItem("modelDownloadState");
+ }
+ }
+ } catch (error) {
+ console.error("Error checking models:", error);
+ }
+ });
+
+ // Save download state when it changes
+ createEffect(() => {
+ if (isDownloading() && downloadingModel()) {
+ localStorage.setItem(
+ "modelDownloadState",
+ JSON.stringify({
+ model: downloadingModel(),
+ progress: downloadProgress(),
+ })
+ );
+ } else {
+ localStorage.removeItem("modelDownloadState");
+ }
+ });
+
+ // Effect to update current caption based on playback time
+ createEffect(() => {
+ if (!project?.captions?.segments || editorState.playbackTime === undefined)
+ return;
+
+ const time = editorState.playbackTime;
+ const segments = project.captions.segments;
+
+ // Binary search for the correct segment
+ const findSegment = (
+ time: number,
+ segments: CaptionSegment[]
+ ): CaptionSegment | undefined => {
+ let left = 0;
+ let right = segments.length - 1;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+ const segment = segments[mid];
+
+ if (time >= segment.start && time < segment.end) {
+ return segment;
+ }
+
+ if (time < segment.start) {
+ right = mid - 1;
+ } else {
+ left = mid + 1;
+ }
+ }
+
+ return undefined;
+ };
+
+ // Find the current segment using binary search
+ const currentSegment = findSegment(time, segments);
+
+ // Only update if the caption has changed
+ if (currentSegment?.text !== currentCaption()) {
+ setCurrentCaption(currentSegment?.text || null);
+ }
+ });
+
+ const checkModelExists = async (modelName: string) => {
+ const appDataDirPath = await appLocalDataDir();
+ const modelsPath = await join(appDataDirPath, MODEL_FOLDER);
+ const modelPath = await join(modelsPath, `${modelName}.bin`);
+ setModelPath(modelPath);
+ return await commands.checkModelExists(modelPath);
+ };
+
+ const downloadModel = async () => {
+ try {
+ const modelToDownload = selectedModel();
+ setIsDownloading(true);
+ setDownloadProgress(0);
+ setDownloadingModel(modelToDownload);
+
+ // Create the directory if it doesn't exist
+ const appDataDirPath = await appLocalDataDir();
+ const modelsPath = await join(appDataDirPath, MODEL_FOLDER);
+ const modelPath = await join(modelsPath, `${modelToDownload}.bin`);
+
+ try {
+ await commands.createDir(modelsPath, true);
+ } catch (err) {
+ console.error("Error creating directory:", err);
+ }
+
+ // Set up progress listener
+ const unlisten = await events.downloadProgress.listen((event) => {
+ setDownloadProgress(event.payload.progress);
+ });
+
+ // Download the model
+ await commands.downloadWhisperModel(modelToDownload, modelPath);
+
+ // Clean up listener
+ unlisten();
+
+ // Update downloaded models list
+ setDownloadedModels((prev) => [...prev, modelToDownload]);
+ setModelExists(true);
+ toast.success("Transcription model downloaded successfully!");
+ } catch (error) {
+ console.error("Error downloading model:", error);
+ toast.error("Failed to download transcription model");
+ } finally {
+ setIsDownloading(false);
+ setDownloadingModel(null);
+ }
+ };
+
+ const generateCaptions = async () => {
+ if (!editorInstance) {
+ toast.error("Editor instance not found");
+ return;
+ }
+
+ setIsGenerating(true);
+
+ try {
+ const videoPath = editorInstance.path;
+ const lang = selectedLanguage();
+ const currentModelPath = await join(
+ await appLocalDataDir(),
+ MODEL_FOLDER,
+ `${selectedModel()}.bin`
+ );
+
+ // Verify file existence before proceeding
+ const result = await commands.transcribeAudio(
+ videoPath,
+ currentModelPath,
+ lang
+ );
+
+ if (result && result.segments.length > 0) {
+ // Update project with the new segments
+ setProject("captions", "segments", result.segments);
+ updateCaptionSetting("enabled", true);
+ toast.success("Captions generated successfully!");
+ } else {
+ toast.error(
+ "No captions were generated. The audio might be too quiet or unclear."
+ );
+ }
+ } catch (error) {
+ console.error("Error generating captions:", error);
+ let errorMessage = "Unknown error occurred";
+
+ if (error instanceof Error) {
+ errorMessage = error.message;
+ } else if (typeof error === "string") {
+ errorMessage = error;
+ }
+
+ // Provide more user-friendly error messages
+ if (errorMessage.includes("No audio stream found")) {
+ errorMessage = "No audio found in the video file";
+ } else if (errorMessage.includes("Model file not found")) {
+ errorMessage = "Caption model not found. Please download it first";
+ } else if (errorMessage.includes("Failed to load Whisper model")) {
+ errorMessage =
+ "Failed to load the caption model. Try downloading it again";
+ }
+
+ toast.error("Failed to generate captions: " + errorMessage);
+ } finally {
+ setIsGenerating(false);
+ }
+ };
+
+ // Segment operations that update project directly
+ const deleteSegment = (id: string) => {
+ if (!project?.captions?.segments) return;
+
+ setProject(
+ "captions",
+ "segments",
+ project.captions.segments.filter((segment) => segment.id !== id)
+ );
+ };
+
+ const updateSegment = (
+ id: string,
+ updates: Partial<{ start: number; end: number; text: string }>
+ ) => {
+ if (!project?.captions?.segments) return;
+
+ setProject(
+ "captions",
+ "segments",
+ project.captions.segments.map((segment) =>
+ segment.id === id ? { ...segment, ...updates } : segment
+ )
+ );
+ };
+
+ const addSegment = (time: number) => {
+ if (!project?.captions) return;
+
+ const id = `segment-${Date.now()}`;
+ setProject("captions", "segments", [
+ ...project.captions.segments,
+ {
+ id,
+ start: time,
+ end: time + 2,
+ text: "New caption",
+ },
+ ]);
+ };
+
+ return (
+ <div class="flex flex-col h-full">
+ <div
+ class="p-[0.75rem] text-[0.875rem] h-full transition-[height] duration-200"
+ ref={(el) => (scrollContainerRef = el)}
+ onScroll={() => {
+ if (!scrollState.isScrolling && scrollContainerRef) {
+ setScrollState("isScrolling", true);
+ setScrollState("lastScrollTop", scrollContainerRef.scrollTop);
+
+ // Reset scrolling flag after scroll ends
+ setTimeout(() => {
+ setScrollState("isScrolling", false);
+ }, 150);
+ }
+ }}
+ >
+ <Field name="Captions" icon={<IconCapMessageBubble />}>
+ <div class="flex flex-col gap-4">
+ <Subfield name="Enable Captions">
+ <Toggle
+ checked={captionSettings.enabled}
+ onChange={(checked) => updateCaptionSetting("enabled", checked)}
+ />
+ </Subfield>
+
+ <Show when={captionSettings.enabled}>
+ <div class="space-y-6 transition-all duration-200">
+ {/* Model Selection and Download Section */}
+ <div class="space-y-4">
+ <div class="space-y-2">
+ <label class="text-xs text-gray-500">Current Model</label>
+ <KSelect<string>
+ options={MODEL_OPTIONS.filter((m) =>
+ downloadedModels().includes(m.name)
+ ).map((m) => m.name)}
+ value={selectedModel()}
+ onChange={(value: string | null) => {
+ if (value) {
+ batch(() => {
+ setSelectedModel(value);
+ setModelExists(downloadedModels().includes(value));
+ });
+ }
+ }}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {
+ MODEL_OPTIONS.find(
+ (m) => m.name === props.item.rawValue
+ )?.label
+ }
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="flex flex-row items-center h-9 px-3 gap-2 border rounded-lg border-gray-200 w-full text-gray-700 text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-colors">
+ <KSelect.Value<string> class="flex-1 text-left truncate">
+ {(state) => {
+ const model = MODEL_OPTIONS.find(
+ (m) => m.name === state.selectedOption()
+ );
+ return (
+ <span>{model?.label || "Select a model"}</span>
+ );
+ }}
+ </KSelect.Value>
+ <KSelect.Icon>
+ <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180" />
+ </KSelect.Icon>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={topLeftAnimateClasses}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="max-h-48 overflow-y-auto"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </div>
+
+ <div class="space-y-2">
+ <label class="text-xs text-gray-500">
+ Download New Model
+ </label>
+ <KSelect<string>
+ options={MODEL_OPTIONS.map((m) => m.name)}
+ value={selectedModel()}
+ onChange={(value: string | null) => {
+ if (value) setSelectedModel(value);
+ }}
+ disabled={isDownloading()}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {
+ MODEL_OPTIONS.find(
+ (m) => m.name === props.item.rawValue
+ )?.label
+ }
+ {downloadedModels().includes(props.item.rawValue)
+ ? " (Downloaded)"
+ : ""}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="flex flex-row items-center h-9 px-3 gap-2 border rounded-lg border-gray-200 w-full text-gray-700 text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-colors">
+ <KSelect.Value<string> class="flex-1 text-left truncate">
+ {(state) => {
+ const model = MODEL_OPTIONS.find(
+ (m) => m.name === state.selectedOption()
+ );
+ return (
+ <span>{model?.label || "Select a model"}</span>
+ );
+ }}
+ </KSelect.Value>
+ <KSelect.Icon>
+ <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180" />
+ </KSelect.Icon>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={topLeftAnimateClasses}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="max-h-48 overflow-y-auto"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </div>
+
+ <Show
+ when={isDownloading()}
+ fallback={
+ <Button
+ class="w-full"
+ onClick={downloadModel}
+ disabled={
+ isDownloading() ||
+ downloadedModels().includes(selectedModel())
+ }
+ >
+ Download{" "}
+ {
+ MODEL_OPTIONS.find((m) => m.name === selectedModel())
+ ?.label
+ }
+ </Button>
+ }
+ >
+ <div class="space-y-2">
+ <div class="w-full bg-gray-100 rounded-full h-2">
+ <div
+ class="bg-blue-500 h-2 rounded-full transition-all duration-300"
+ style={{ width: `${downloadProgress()}%` }}
+ />
+ </div>
+ <p class="text-xs text-center text-gray-500">
+ Downloading{" "}
+ {
+ MODEL_OPTIONS.find(
+ (m) => m.name === downloadingModel()
+ )?.label
+ }
+ : {Math.round(downloadProgress())}%
+ </p>
+ </div>
+ </Show>
+ </div>
+
+ {/* Language Selection */}
+ <Subfield name="Language">
+ <KSelect<string>
+ options={LANGUAGE_OPTIONS.map((l) => l.code)}
+ value={selectedLanguage()}
+ onChange={(value: string | null) => {
+ if (value) setSelectedLanguage(value);
+ }}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {
+ LANGUAGE_OPTIONS.find(
+ (l) => l.code === props.item.rawValue
+ )?.label
+ }
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="flex flex-row items-center h-9 px-3 gap-2 border rounded-lg border-gray-200 w-full text-gray-700 text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-colors">
+ <KSelect.Value<string> class="flex-1 text-left truncate">
+ {(state) => {
+ const language = LANGUAGE_OPTIONS.find(
+ (l) => l.code === state.selectedOption()
+ );
+ return (
+ <span>
+ {language?.label || "Select a language"}
+ </span>
+ );
+ }}
+ </KSelect.Value>
+ <KSelect.Icon>
+ <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180" />
+ </KSelect.Icon>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={topLeftAnimateClasses}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="max-h-48 overflow-y-auto"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </Subfield>
+
+ {/* Generate Captions Button */}
+ <Show when={hasAudio()}>
+ <Button
+ onClick={generateCaptions}
+ disabled={isGenerating()}
+ class="w-full"
+ >
+ {isGenerating() ? "Generating..." : "Generate Captions"}
+ </Button>
+ </Show>
+
+ {/* Font Settings */}
+ <Field name="Font Settings" icon={<IconCapMessageBubble />}>
+ <div class="space-y-3">
+ <div class="flex flex-col gap-2">
+ <span class="text-gray-500 text-sm">Font Family</span>
+ <KSelect<string>
+ options={fontOptions.map((f) => f.value)}
+ value={captionSettings.font}
+ onChange={(value) => {
+ if (value === null) return;
+ updateCaptionSetting("font", value);
+ }}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {
+ fontOptions.find(
+ (f) => f.value === props.item.rawValue
+ )?.label
+ }
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="w-full flex items-center justify-between rounded-lg shadow px-3 py-2 bg-white border border-gray-300">
+ <KSelect.Value<string>>
+ {(state) =>
+ fontOptions.find(
+ (f) => f.value === state.selectedOption()
+ )?.label
+ }
+ </KSelect.Value>
+ <KSelect.Icon>
+ <IconCapChevronDown />
+ </KSelect.Icon>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={topLeftAnimateClasses}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="max-h-48 overflow-y-auto"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </div>
+
+ <div class="flex flex-col gap-2">
+ <span class="text-gray-500 text-sm">Size</span>
+ <Slider
+ value={[captionSettings.size || 24]}
+ onChange={(v) => updateCaptionSetting("size", v[0])}
+ minValue={12}
+ maxValue={48}
+ step={1}
+ />
+ </div>
+
+ <div class="flex flex-col gap-2">
+ <span class="text-gray-500 text-sm">Font Color</span>
+ <RgbInput
+ value={captionSettings.color || "#FFFFFF"}
+ onChange={(value) =>
+ updateCaptionSetting("color", value)
+ }
+ />
+ </div>
+ </div>
+ </Field>
+
+ {/* Background Settings */}
+ <Field
+ name="Background Settings"
+ icon={<IconCapMessageBubble />}
+ >
+ <div class="space-y-3">
+ <div class="flex flex-col gap-2">
+ <span class="text-gray-500 text-sm">
+ Background Color
+ </span>
+ <RgbInput
+ value={captionSettings.backgroundColor || "#000000"}
+ onChange={(value) =>
+ updateCaptionSetting("backgroundColor", value)
+ }
+ />
+ </div>
+
+ <div class="flex flex-col gap-2">
+ <span class="text-gray-500 text-sm">
+ Background Opacity
+ </span>
+ <Slider
+ value={[captionSettings.backgroundOpacity || 80]}
+ onChange={(v) =>
+ updateCaptionSetting("backgroundOpacity", v[0])
+ }
+ minValue={0}
+ maxValue={100}
+ step={1}
+ />
+ </div>
+ </div>
+ </Field>
+
+ {/* Position Settings */}
+ <Field name="Position" icon={<IconCapMessageBubble />}>
+ <KSelect<string>
+ options={["top", "bottom"]}
+ value={captionSettings.position || "bottom"}
+ onChange={(value) => {
+ if (value === null) return;
+ updateCaptionSetting("position", value);
+ }}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1 capitalize">
+ {props.item.rawValue}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="w-full flex items-center justify-between rounded-lg shadow px-3 py-2 bg-white border border-gray-300">
+ <KSelect.Value<string>>
+ {(state) => (
+ <span class="capitalize">
+ {state.selectedOption()}
+ </span>
+ )}
+ </KSelect.Value>
+ <KSelect.Icon>
+ <IconCapChevronDown />
+ </KSelect.Icon>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={topLeftAnimateClasses}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </Field>
+
+ {/* Style Options */}
+ <Field name="Style Options" icon={<IconCapMessageBubble />}>
+ <div class="space-y-3">
+ <div class="flex flex-col gap-4">
+ <Subfield name="Bold">
+ <Toggle
+ checked={captionSettings.bold}
+ onChange={(checked) =>
+ updateCaptionSetting("bold", checked)
+ }
+ />
+ </Subfield>
+ <Subfield name="Italic">
+ <Toggle
+ checked={captionSettings.italic}
+ onChange={(checked) =>
+ updateCaptionSetting("italic", checked)
+ }
+ />
+ </Subfield>
+ <Subfield name="Outline">
+ <Toggle
+ checked={captionSettings.outline}
+ onChange={(checked) =>
+ updateCaptionSetting("outline", checked)
+ }
+ />
+ </Subfield>
+ </div>
+
+ <Show when={captionSettings.outline}>
+ <div class="flex flex-col gap-2">
+ <span class="text-gray-500 text-sm">Outline Color</span>
+ <RgbInput
+ value={captionSettings.outlineColor || "#000000"}
+ onChange={(value) =>
+ updateCaptionSetting("outlineColor", value)
+ }
+ />
+ </div>
+ </Show>
+ </div>
+ </Field>
+
+ {/* Export Options */}
+ <Field name="Export Options" icon={<IconCapMessageBubble />}>
+ <Subfield name="Export with Subtitles">
+ <Toggle
+ checked={captionSettings.exportWithSubtitles}
+ onChange={(checked) =>
+ updateCaptionSetting("exportWithSubtitles", checked)
+ }
+ />
+ </Subfield>
+ </Field>
+
+ {/* Caption Segments Section */}
+ <Show when={project.captions?.segments.length}>
+ <Field
+ name="Caption Segments"
+ icon={<IconCapMessageBubble />}
+ >
+ <div class="space-y-4">
+ <div class="flex items-center justify-between">
+ <Button
+ onClick={() => addSegment(editorState.playbackTime)}
+ class="w-full"
+ >
+ Add at Current Time
+ </Button>
+ </div>
+
+ <div class="max-h-[300px] overflow-y-auto space-y-3 pr-2">
+ {project.captions?.segments.length === 0 ? (
+ <p class="text-sm text-gray-500">
+ No caption segments found.
+ </p>
+ ) : (
+ project.captions?.segments.map((segment) => (
+ <div class="bg-gray-50 dark:bg-gray-100 border border-gray-200 rounded-lg p-4 space-y-4">
+ <div class="flex flex-col space-y-4">
+ <div class="flex space-x-4">
+ <div class="flex-1">
+ <label class="text-xs text-gray-400 dark:text-gray-500">
+ Start Time
+ </label>
+ <Input
+ type="number"
+ class="w-full"
+ value={segment.start.toFixed(1)}
+ step="0.1"
+ min={0}
+ onChange={(e) =>
+ updateSegment(segment.id, {
+ start: parseFloat(e.target.value),
+ })
+ }
+ />
+ </div>
+ <div class="flex-1">
+ <label class="text-xs text-gray-400 dark:text-gray-500">
+ End Time
+ </label>
+ <Input
+ type="number"
+ class="w-full"
+ value={segment.end.toFixed(1)}
+ step="0.1"
+ min={segment.start}
+ onChange={(e) =>
+ updateSegment(segment.id, {
+ end: parseFloat(e.target.value),
+ })
+ }
+ />
+ </div>
+ </div>
+
+ <div class="space-y-2">
+ <label class="text-xs text-gray-400 dark:text-gray-500">
+ Caption Text
+ </label>
+ <div class="w-full px-3 py-2 bg-white dark:bg-gray-50 border border-gray-200 rounded-lg text-sm focus-within:border-blue-500 focus-within:ring-1 focus-within:ring-blue-500 transition-colors">
+ <textarea
+ class="w-full resize-none outline-none bg-transparent text-[--text-primary]"
+ value={segment.text}
+ rows={2}
+ onChange={(e) =>
+ updateSegment(segment.id, {
+ text: e.target.value,
+ })
+ }
+ />
+ </div>
+ </div>
+
+ <div class="flex justify-end">
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => deleteSegment(segment.id)}
+ class="text-gray-50 dark:text-gray-500 inline-flex items-center gap-1.5"
+ >
+ <IconDelete />
+ Delete
+ </Button>
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ </Field>
+ </Show>
+ </div>
+ </Show>
+ </div>
+ </Field>
+ </div>
+ </div>
+ );
+}
+
+function IconDelete() {
+ return (
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ class="size-4"
+ >
+ <path
+ d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"
+ fill="currentColor"
+ />
+ </svg>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 6c544ef7e..08906742b 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -66,6 +66,7 @@ import {
Subfield,
topSlideAnimateClasses,
} from "./ui";
+import { CaptionsTab } from "./CaptionsTab";
const BACKGROUND_SOURCES = {
wallpaper: "Wallpaper",
@@ -209,7 +210,8 @@ export function ConfigSidebar() {
| "transcript"
| "audio"
| "cursor"
- | "hotkeys",
+ | "hotkeys"
+ | "captions",
});
let scrollRef!: HTMLDivElement;
@@ -230,10 +232,6 @@ export function ConfigSidebar() {
(s) => s.camera === null
),
},
- // {
- // id: "transcript" as const,
- // icon: IconCapMessageBubble,
- // },
{ id: TAB_IDS.audio, icon: IconCapAudioOn },
{
id: TAB_IDS.cursor,
@@ -242,8 +240,12 @@ export function ConfigSidebar() {
meta().type === "multiple" && (meta() as any).segments[0].cursor
),
},
+ window.FLAGS.captions && {
+ id: "captions" as const,
+ icon: IconCapMessageBubble,
+ },
// { id: "hotkeys" as const, icon: IconCapHotkeys },
- ]}
+ ].filter(Boolean)}
>
{(item) => (
<KTabs.Trigger
@@ -281,21 +283,6 @@ export function ConfigSidebar() {
>
<BackgroundConfig scrollRef={scrollRef} />
<CameraConfig scrollRef={scrollRef} />
- <KTabs.Content value="transcript" class="flex flex-col gap-6">
- <Field name="Transcript" icon={<IconCapMessageBubble />}>
- <div class="p-1 rounded-md border bg-gray-1 text-gray-11 text-wrap">
- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac
- purus sit amet nunc ultrices ultricies. Nullam nec scelerisque
- nunc. Nullam nec scelerisque nunc.
- </div>
- <button
- type="button"
- class="w-full bg-gray-10/20 hover:bg-gray-10/30 transition-colors duration-100 rounded-full py-1.5"
- >
- Edit
- </button>
- </Field>
- </KTabs.Content>
<KTabs.Content value="audio" class="flex flex-col gap-6">
<Field
name="Audio Controls"
@@ -547,6 +534,9 @@ export function ConfigSidebar() {
</ComingSoonTooltip>
</Field>
</KTabs.Content>
+ <KTabs.Content value="captions" class="flex flex-col gap-6">
+ <CaptionsTab />
+ </KTabs.Content>
</div>
<Show when={editorState.timeline.selection}>
{(selection) => (
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index a660a95fd..53d26224a 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -4,12 +4,23 @@ import { createEventListener } from "@solid-primitives/event-listener";
import { createEffect, createSignal, Show } from "solid-js";
import { cx } from "cva";
+import {
+ For,
+ Suspense,
+ createResource,
+ on,
+ onMount,
+ onCleanup,
+} from "solid-js";
+import { reconcile, createStore } from "solid-js/store";
+
import Tooltip from "~/components/Tooltip";
import { commands } from "~/utils/tauri";
-import AspectRatioSelect from "./AspectRatioSelect";
import { FPS, OUTPUT_SIZE, useEditorContext } from "./context";
import { ComingSoonTooltip, EditorButton, Slider } from "./ui";
import { formatTime } from "./utils";
+import { captionsStore } from "~/store/captions";
+import AspectRatioSelect from "./AspectRatioSelect";
export function Player() {
const {
@@ -20,8 +31,77 @@ export function Player() {
editorState,
setEditorState,
zoomOutLimit,
+ setProject,
} = useEditorContext();
+ // Load captions on mount
+ onMount(async () => {
+ if (editorInstance && editorInstance.path) {
+ // Still load captions into the store since they will be used by the GPU renderer
+ await captionsStore.loadCaptions(editorInstance.path);
+
+ // Synchronize captions settings with project configuration
+ // This ensures the GPU renderer will receive the caption settings
+ if (editorInstance && project) {
+ const updatedProject = { ...project };
+
+ // Add captions data to project configuration if it doesn't exist
+ if (
+ !updatedProject.captions &&
+ captionsStore.state.segments.length > 0
+ ) {
+ updatedProject.captions = {
+ segments: captionsStore.state.segments.map((segment) => ({
+ id: segment.id,
+ start: segment.start,
+ end: segment.end,
+ text: segment.text,
+ })),
+ settings: {
+ enabled: captionsStore.state.settings.enabled,
+ font: captionsStore.state.settings.font,
+ size: captionsStore.state.settings.size,
+ color: captionsStore.state.settings.color,
+ backgroundColor: captionsStore.state.settings.backgroundColor,
+ backgroundOpacity: captionsStore.state.settings.backgroundOpacity,
+ position: captionsStore.state.settings.position,
+ bold: captionsStore.state.settings.bold,
+ italic: captionsStore.state.settings.italic,
+ outline: captionsStore.state.settings.outline,
+ outlineColor: captionsStore.state.settings.outlineColor,
+ exportWithSubtitles:
+ captionsStore.state.settings.exportWithSubtitles,
+ },
+ };
+
+ // Update the project with captions data
+ setProject(updatedProject);
+
+ // Save the updated project configuration
+ await commands.setProjectConfig(updatedProject);
+ }
+ }
+ }
+ });
+
+ // Continue to update current caption when playback time changes
+ // This is still needed for CaptionsTab to highlight the current caption
+ createEffect(() => {
+ const time = editorState.playbackTime;
+ // Only update captions if we have a valid time and segments exist
+ if (
+ time !== undefined &&
+ time >= 0 &&
+ captionsStore.state.segments.length > 0
+ ) {
+ captionsStore.updateCurrentCaption(time);
+ }
+ });
+
+ const [canvasContainerRef, setCanvasContainerRef] =
+ createSignal<HTMLDivElement>();
+ const containerBounds = createElementBounds(canvasContainerRef);
+
const isAtEnd = () => {
const total = totalDuration();
return total > 0 && total - editorState.playbackTime <= 0.1;
@@ -150,7 +230,6 @@ export function Player() {
<div class="flex flex-row flex-1 gap-4 justify-end items-center">
<div class="flex-1" />
<EditorButton<typeof KToggleButton>
- disabled={!window.FLAGS.split}
pressed={editorState.timeline.interactMode === "split"}
onChange={(v: boolean) =>
setEditorState("timeline", "interactMode", v ? "split" : "seek")
diff --git a/apps/desktop/src/store/captions.ts b/apps/desktop/src/store/captions.ts
new file mode 100644
index 000000000..a89773195
--- /dev/null
+++ b/apps/desktop/src/store/captions.ts
@@ -0,0 +1,203 @@
+import { createRoot, createEffect } from "solid-js";
+import { createStore } from "solid-js/store";
+import { CaptionSegment, commands } from "~/utils/tauri";
+
+// export type CaptionSegment = {
+// id: string;
+// start: number;
+// end: number;
+// text: string;
+// };
+
+export type CaptionSettings = {
+ enabled: boolean;
+ font: string;
+ size: number;
+ color: string;
+ backgroundColor: string;
+ backgroundOpacity: number;
+ position: string;
+ bold: boolean;
+ italic: boolean;
+ outline: boolean;
+ outlineColor: string;
+ exportWithSubtitles: boolean;
+};
+
+export type CaptionsState = {
+ segments: CaptionSegment[];
+ settings: CaptionSettings;
+ currentCaption: string | null;
+};
+
+function createCaptionsStore() {
+ const [state, setState] = createStore<CaptionsState>({
+ segments: [],
+ settings: {
+ enabled: false,
+ font: "System Sans-Serif",
+ size: 24,
+ color: "#FFFFFF",
+ backgroundColor: "#000000",
+ backgroundOpacity: 80,
+ position: "bottom",
+ bold: true,
+ italic: false,
+ outline: true,
+ outlineColor: "#000000",
+ exportWithSubtitles: false,
+ },
+ currentCaption: null
+ });
+
+ return {
+ state,
+ setState,
+
+ // Actions
+ updateSettings(settings: Partial<CaptionSettings>) {
+ setState("settings", prev => ({ ...prev, ...settings }));
+ },
+
+ updateSegments(segments: CaptionSegment[]) {
+ setState("segments", segments);
+ },
+
+ setCurrentCaption(caption: string | null) {
+ setState("currentCaption", caption);
+ },
+
+ // New methods for segment operations
+ deleteSegment(id: string) {
+ setState("segments", prev => prev.filter(segment => segment.id !== id));
+ },
+
+ updateSegment(id: string, updates: Partial<{start: number, end: number, text: string}>) {
+ setState("segments", prev => prev.map(segment =>
+ segment.id === id ? { ...segment, ...updates } : segment
+ ));
+ },
+
+ addSegment(time: number) {
+ const id = `segment-${Date.now()}`;
+ setState("segments", prev => [
+ ...prev,
+ {
+ id,
+ start: time,
+ end: time + 2,
+ text: "New caption"
+ }
+ ]);
+ },
+
+ // Load captions for a video
+ async loadCaptions(videoPath: string) {
+ try {
+ const captionsData = await commands.loadCaptions(videoPath);
+ if (captionsData) {
+ setState(prev => ({
+ ...prev,
+ segments: captionsData.segments,
+ settings: captionsData.settings || {
+ enabled: true,
+ font: "Arial",
+ size: 24,
+ color: "#FFFFFF",
+ backgroundColor: "#000000",
+ backgroundOpacity: 80,
+ position: "bottom",
+ bold: true,
+ italic: false,
+ outline: true,
+ outlineColor: "#000000",
+ exportWithSubtitles: false,
+ }
+ }));
+ }
+
+ // Try loading from localStorage as backup
+ try {
+ const localCaptionsData = JSON.parse(localStorage.getItem(`captions-${videoPath}`) || '{}');
+ if (localCaptionsData.segments) {
+ setState("segments", localCaptionsData.segments);
+ }
+ if (localCaptionsData.settings) {
+ setState("settings", localCaptionsData.settings);
+ }
+ } catch (e) {
+ console.error("Error loading saved captions from localStorage:", e);
+ }
+ } catch (e) {
+ console.error("Error loading captions:", e);
+ }
+ },
+
+ // Save captions for a video
+ async saveCaptions(videoPath: string) {
+ try {
+ const captionsData = {
+ segments: state.segments,
+ settings: {
+ enabled: state.settings.enabled,
+ font: state.settings.font,
+ size: state.settings.size,
+ color: state.settings.color,
+ backgroundColor: state.settings.backgroundColor,
+ backgroundOpacity: state.settings.backgroundOpacity,
+ position: state.settings.position,
+ bold: state.settings.bold,
+ italic: state.settings.italic,
+ outline: state.settings.outline,
+ outlineColor: state.settings.outlineColor,
+ exportWithSubtitles: state.settings.exportWithSubtitles
+ }
+ };
+
+ await commands.saveCaptions(videoPath, captionsData);
+ localStorage.setItem(`captions-${videoPath}`, JSON.stringify(captionsData));
+ } catch (e) {
+ console.error("Error saving captions:", e);
+ }
+ },
+
+ // Update current caption based on playback time
+ updateCurrentCaption(time: number) {
+ // Binary search for the correct segment
+ const findSegment = (time: number, segments: CaptionSegment[]): CaptionSegment | undefined => {
+ let left = 0;
+ let right = segments.length - 1;
+
+ while (left <= right) {
+ const mid = Math.floor((left + right) / 2);
+ const segment = segments[mid];
+
+ if (time >= segment.start && time < segment.end) {
+ return segment;
+ }
+
+ if (time < segment.start) {
+ right = mid - 1;
+ } else {
+ left = mid + 1;
+ }
+ }
+
+ return undefined;
+ };
+
+ // Find the current segment using binary search
+ const currentSegment = findSegment(time, state.segments);
+
+ // Only update if the caption has changed
+ if (currentSegment?.text !== state.currentCaption) {
+ setState("currentCaption", currentSegment?.text || null);
+ }
+ }
+ };
+}
+
+// Create a singleton instance
+const captionsStore = createRoot(() => createCaptionsStore());
+
+export { captionsStore };
\ No newline at end of file
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 11186204b..a933fe4d4 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -172,6 +172,60 @@ async getEditorMeta() : Promise<RecordingMeta> {
},
async setServerUrl(serverUrl: string) : Promise<null> {
return await TAURI_INVOKE("set_server_url", { serverUrl });
+},
+/**
+ * Function to handle creating directories for the model
+ */
+async createDir(path: string, recursive: boolean) : Promise<null> {
+ return await TAURI_INVOKE("create_dir", { path, recursive });
+},
+/**
+ * Function to save the model file
+ */
+async saveModelFile(path: string, data: number[]) : Promise<null> {
+ return await TAURI_INVOKE("save_model_file", { path, data });
+},
+/**
+ * Function to transcribe audio from a video file using Whisper
+ */
+async transcribeAudio(videoPath: string, modelPath: string, language: string) : Promise<CaptionData> {
+ return await TAURI_INVOKE("transcribe_audio", { videoPath, modelPath, language });
+},
+/**
+ * Function to save caption data to a file
+ */
+async saveCaptions(videoId: string, captions: CaptionData) : Promise<null> {
+ return await TAURI_INVOKE("save_captions", { videoId, captions });
+},
+/**
+ * Function to load caption data from a file
+ */
+async loadCaptions(videoId: string) : Promise<CaptionData | null> {
+ return await TAURI_INVOKE("load_captions", { videoId });
+},
+/**
+ * Helper function to download a Whisper model from Hugging Face Hub
+ */
+async downloadWhisperModel(modelName: string, outputPath: string) : Promise<null> {
+ return await TAURI_INVOKE("download_whisper_model", { modelName, outputPath });
+},
+/**
+ * Function to check if a model file exists
+ */
+async checkModelExists(modelPath: string) : Promise<boolean> {
+ return await TAURI_INVOKE("check_model_exists", { modelPath });
+},
+/**
+ * Function to delete a downloaded model
+ */
+async deleteWhisperModel(modelPath: string) : Promise<null> {
+ return await TAURI_INVOKE("delete_whisper_model", { modelPath });
+},
+/**
+ * Export captions to an SRT file
+ */
+async exportCaptionsSrt(videoId: string) : Promise<string | null> {
+ return await TAURI_INVOKE("export_captions_srt", { videoId });
}
}
@@ -182,6 +236,7 @@ export const events = __makeEvents__<{
audioInputLevelChange: AudioInputLevelChange,
authenticationInvalid: AuthenticationInvalid,
currentRecordingChanged: CurrentRecordingChanged,
+downloadProgress: DownloadProgress,
editorStateChanged: EditorStateChanged,
newNotification: NewNotification,
newScreenshotAdded: NewScreenshotAdded,
@@ -200,6 +255,7 @@ uploadProgress: UploadProgress
audioInputLevelChange: "audio-input-level-change",
authenticationInvalid: "authentication-invalid",
currentRecordingChanged: "current-recording-changed",
+downloadProgress: "download-progress",
editorStateChanged: "editor-state-changed",
newNotification: "new-notification",
newScreenshotAdded: "new-screenshot-added",
@@ -242,6 +298,10 @@ export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition;
export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }
export type CameraXPosition = "left" | "center" | "right"
export type CameraYPosition = "top" | "bottom"
+export type CaptionData = { segments: CaptionSegment[]; settings: CaptionSettings | null }
+export type CaptionSegment = { id: string; start: number; end: number; text: string }
+export type CaptionSettings = { enabled: boolean; font: string; size: number; color: string; backgroundColor: string; backgroundOpacity: number; position: string; bold: boolean; italic: boolean; outline: boolean; outlineColor: string; exportWithSubtitles: boolean }
+export type CaptionsData = { segments: CaptionSegment[]; settings: CaptionSettings }
export type CaptureScreen = { id: number; name: string; refresh_rate: number }
export type CaptureWindow = { id: number; owner_name: string; name: string; bounds: Bounds; refresh_rate: number }
export type CommercialLicense = { licenseKey: string; expiryDate: number | null; refresh: number; activatedOn: number }
@@ -254,11 +314,12 @@ export type CursorConfiguration = { hide?: boolean; hideWhenIdle: boolean; size:
export type CursorMeta = { imagePath: string; hotspot: XY<number> }
export type CursorType = "pointer" | "circle"
export type Cursors = { [key in string]: string } | { [key in string]: CursorMeta }
+export type DownloadProgress = { progress: number; message: string }
export type EditorStateChanged = { playhead_position: number }
export type ExportCompression = "Minimal" | "Social" | "Web" | "Potato"
export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }
export type ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression }
-export type Flags = { split: boolean }
+export type Flags = { captions: boolean }
export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }
export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; customCursorCapture?: boolean; systemAudioCapture?: boolean; serverUrl?: string;
/**
@@ -287,7 +348,7 @@ export type Platform = "MacOS" | "Windows"
export type PostStudioRecordingBehaviour = "openEditor" | "showOverlay"
export type Preset = { name: string; config: ProjectConfiguration }
export type PresetsStore = { presets: Preset[]; default: number | null }
-export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null }
+export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null; captions?: CaptionsData | null }
export type ProjectRecordings = { segments: SegmentRecordings[] }
export type RecordingMeta = (StudioRecordingMeta | InstantRecordingMeta) & { platform: Platform | null; pretty_name: string; sharing?: SharingMeta | null }
export type RecordingMetaWithType = ((StudioRecordingMeta | InstantRecordingMeta) & { platform: Platform | null; pretty_name: string; sharing?: SharingMeta | null }) & { type: RecordingType }
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index e28b782b0..3b4900b3a 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -74,7 +74,8 @@ impl Renderer {
let mut frame_renderer = FrameRenderer::new(&self.render_constants);
- let mut layers = RendererLayers::new(&self.render_constants.device);
+ let mut layers =
+ RendererLayers::new(&self.render_constants.device, &self.render_constants.queue);
loop {
while let Some(msg) = self.rx.recv().await {
diff --git a/crates/flags/src/lib.rs b/crates/flags/src/lib.rs
index bb6812da1..a5e9bc9e7 100644
--- a/crates/flags/src/lib.rs
+++ b/crates/flags/src/lib.rs
@@ -1,7 +1,9 @@
#[derive(serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct Flags {
- pub split: bool,
+ pub captions: bool,
}
-pub const FLAGS: Flags = Flags { split: true };
+pub const FLAGS: Flags = Flags {
+ captions: false, // cfg!(debug_assertions),
+};
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
index 3cf70f120..24e579be2 100644
--- a/crates/project/Cargo.toml
+++ b/crates/project/Cargo.toml
@@ -13,3 +13,5 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1.0.127"
either = "1.13.0"
relative-path = { version = "1.9.3", features = ["serde"] }
+log = "0.4"
+tracing = "0.1.41"
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 6e4188f59..b40d850ff 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -444,6 +444,71 @@ impl TimelineConfiguration {
pub const WALLPAPERS_PATH: &str = "assets/backgrounds/macOS";
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptionSegment {
+ pub id: String,
+ pub start: f32,
+ pub end: f32,
+ pub text: String,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptionSettings {
+ pub enabled: bool,
+ pub font: String,
+ pub size: u32,
+ pub color: String,
+ #[serde(alias = "backgroundColor")]
+ pub background_color: String,
+ #[serde(alias = "backgroundOpacity")]
+ pub background_opacity: u32,
+ pub position: String,
+ pub bold: bool,
+ pub italic: bool,
+ pub outline: bool,
+ #[serde(alias = "outlineColor")]
+ pub outline_color: String,
+ #[serde(alias = "exportWithSubtitles")]
+ pub export_with_subtitles: bool,
+}
+
+impl Default for CaptionSettings {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ font: "System Sans-Serif".to_string(),
+ size: 24,
+ color: "#FFFFFF".to_string(),
+ background_color: "#000000".to_string(),
+ background_opacity: 80,
+ position: "bottom".to_string(),
+ bold: true,
+ italic: false,
+ outline: true,
+ outline_color: "#000000".to_string(),
+ export_with_subtitles: false,
+ }
+ }
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptionsData {
+ pub segments: Vec<CaptionSegment>,
+ pub settings: CaptionSettings,
+}
+
+impl Default for CaptionsData {
+ fn default() -> Self {
+ Self {
+ segments: Vec::new(),
+ settings: CaptionSettings::default(),
+ }
+ }
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ProjectConfiguration {
@@ -455,6 +520,8 @@ pub struct ProjectConfiguration {
pub hotkeys: HotkeysConfiguration,
#[serde(default)]
pub timeline: Option<TimelineConfiguration>,
+ #[serde(default)]
+ pub captions: Option<CaptionsData>,
}
impl ProjectConfiguration {
@@ -491,6 +558,7 @@ impl Default for ProjectConfiguration {
cursor: CursorConfiguration::default(),
hotkeys: HotkeysConfiguration::default(),
timeline: None,
+ captions: None,
}
}
}
diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rs
index 57cd95793..9f1283196 100644
--- a/crates/project/src/meta.rs
+++ b/crates/project/src/meta.rs
@@ -6,8 +6,10 @@ use std::{
collections::HashMap,
path::{Path, PathBuf},
};
+use tracing::{debug, info, warn};
+// use tracing::{debug, warn};
-use crate::{CursorEvents, CursorImage, CursorImages, ProjectConfiguration, XY};
+use crate::{CaptionsData, CursorEvents, CursorImage, CursorImages, ProjectConfiguration, XY};
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct VideoMeta {
@@ -105,7 +107,28 @@ impl RecordingMeta {
}
pub fn project_config(&self) -> ProjectConfiguration {
- ProjectConfiguration::load(&self.project_path).unwrap_or_default()
+ let mut config = ProjectConfiguration::load(&self.project_path).unwrap_or_default();
+
+ // Try to load captions from captions.json if it exists
+ let captions_path = self.project_path.join("captions.json");
+ debug!("Checking for captions at: {:?}", captions_path);
+
+ if let Ok(captions_str) = std::fs::read_to_string(&captions_path) {
+ debug!("Found captions.json, attempting to parse");
+ if let Ok(captions_data) = serde_json::from_str::<CaptionsData>(&captions_str) {
+ info!(
+ "Successfully loaded captions with {} segments",
+ captions_data.segments.len()
+ );
+ config.captions = Some(captions_data);
+ } else {
+ warn!("Failed to parse captions.json");
+ }
+ } else {
+ debug!("No captions.json found");
+ }
+
+ config
}
pub fn output_path(&self) -> PathBuf {
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 203027dbe..b199d7a7e 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -26,6 +26,7 @@ thiserror.workspace = true
wgpu.workspace = true
bezier_easing = "0.1.1"
reactive_graph = "0.1.5"
+glyphon = "0.6.0"
tracing.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rs
new file mode 100644
index 000000000..db57576aa
--- /dev/null
+++ b/crates/rendering/src/layers/captions.rs
@@ -0,0 +1,409 @@
+use bytemuck::{Pod, Zeroable};
+use cap_project::XY;
+use glyphon::{
+ Attrs, Buffer, Cache, Color, Family, FontSystem, Metrics, Resolution, Shaping, SwashCache,
+ TextArea, TextAtlas, TextBounds, TextRenderer, Viewport,
+};
+use log::{debug, info, warn};
+use wgpu::{util::DeviceExt, Device, Queue};
+
+use crate::{
+ layers, parse_color_component, DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants,
+};
+
+/// Represents a caption segment with timing and text
+#[derive(Debug, Clone)]
+pub struct CaptionSegment {
+ pub id: String,
+ pub start: f32,
+ pub end: f32,
+ pub text: String,
+}
+
+/// Settings for caption rendering
+#[repr(C)]
+#[derive(Copy, Clone, Pod, Zeroable, Debug)]
+pub struct CaptionSettings {
+ pub enabled: u32, // 0 = disabled, 1 = enabled
+ pub font_size: f32,
+ pub color: [f32; 4],
+ pub background_color: [f32; 4],
+ pub position: u32, // 0 = top, 1 = middle, 2 = bottom
+ pub outline: u32, // 0 = disabled, 1 = enabled
+ pub outline_color: [f32; 4],
+ pub font: u32, // 0 = SansSerif, 1 = Serif, 2 = Monospace
+ pub _padding: [f32; 1], // for alignment
+}
+
+impl Default for CaptionSettings {
+ fn default() -> Self {
+ Self {
+ enabled: 1,
+ font_size: 24.0,
+ color: [1.0, 1.0, 1.0, 1.0], // white
+ background_color: [0.0, 0.0, 0.0, 0.8], // 80% black
+ position: 2, // bottom
+ outline: 1, // enabled
+ outline_color: [0.0, 0.0, 0.0, 1.0], // black
+ font: 0, // SansSerif
+ _padding: [0.0],
+ }
+ }
+}
+
+/// Caption layer that renders text using GPU
+pub struct CaptionsLayer {
+ settings_buffer: wgpu::Buffer,
+ font_system: FontSystem,
+ swash_cache: SwashCache,
+ text_atlas: TextAtlas,
+ text_renderer: TextRenderer,
+ text_buffer: Buffer,
+ current_text: Option<String>,
+ current_segment_time: f32,
+ viewport: Viewport,
+}
+
+impl CaptionsLayer {
+ /// Create a new captions layer
+ pub fn new(device: &Device, queue: &Queue) -> Self {
+ info!("Initializing new CaptionsLayer");
+ // Create default settings buffer
+ let settings = CaptionSettings::default();
+ let settings_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Caption Settings Buffer"),
+ contents: bytemuck::cast_slice(&[settings]),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ });
+
+ // Initialize glyphon text rendering components
+ let mut font_system = FontSystem::new();
+ let swash_cache = SwashCache::new();
+ let cache = Cache::new(device);
+ let viewport = Viewport::new(device, &cache);
+ let mut text_atlas =
+ TextAtlas::new(device, queue, &cache, wgpu::TextureFormat::Rgba8UnormSrgb);
+ let text_renderer = TextRenderer::new(
+ &mut text_atlas,
+ device,
+ wgpu::MultisampleState::default(),
+ None,
+ );
+
+ // Create an empty buffer with default metrics
+ let metrics = Metrics::new(24.0, 24.0 * 1.2); // Default font size and line height
+ let mut text_buffer = Buffer::new_empty(metrics);
+
+ Self {
+ settings_buffer,
+ font_system,
+ swash_cache,
+ text_atlas,
+ text_renderer,
+ text_buffer,
+ current_text: None,
+ current_segment_time: 0.0,
+ viewport,
+ }
+ }
+
+ /// Update the settings for caption rendering
+ pub fn update_settings(&mut self, queue: &Queue, settings: CaptionSettings) {
+ queue.write_buffer(&self.settings_buffer, 0, bytemuck::cast_slice(&[settings]));
+ }
+
+ /// Update the current caption text and timing
+ pub fn update_caption(&mut self, text: Option<String>, time: f32) {
+ debug!("Updating caption - Text: {:?}, Time: {}", text, time);
+ if self.current_text != text {
+ if let Some(content) = &text {
+ info!("Setting new caption text: {}", content);
+ // Update the text buffer with new content
+ let metrics = Metrics::new(24.0, 24.0 * 1.2);
+ self.text_buffer = Buffer::new_empty(metrics);
+ self.text_buffer.set_text(
+ &mut self.font_system,
+ content,
+ Attrs::new(),
+ Shaping::Advanced,
+ );
+ }
+ self.current_text = text;
+ }
+ self.current_segment_time = time;
+ }
+
+ pub fn prepare(
+ &mut self,
+ uniforms: &ProjectUniforms,
+ segment_frames: &DecodedSegmentFrames,
+ output_size: XY<u32>,
+ constants: &RenderVideoConstants,
+ ) {
+ // Render captions if there are any caption segments to display
+ if let Some(caption_data) = &uniforms.project.captions {
+ if caption_data.settings.enabled {
+ // Find the current caption for this time
+ let current_time = segment_frames.segment_time;
+
+ if let Some(current_caption) =
+ find_caption_at_time_project(current_time, &caption_data.segments)
+ {
+ // Get caption text and time for use in rendering
+ let caption_text = current_caption.text.clone();
+
+ // Create settings for the caption
+ let settings = CaptionSettings {
+ enabled: 1,
+ font_size: caption_data.settings.size as f32,
+ color: [
+ parse_color_component(&caption_data.settings.color, 0),
+ parse_color_component(&caption_data.settings.color, 1),
+ parse_color_component(&caption_data.settings.color, 2),
+ 1.0,
+ ],
+ background_color: [
+ parse_color_component(&caption_data.settings.background_color, 0),
+ parse_color_component(&caption_data.settings.background_color, 1),
+ parse_color_component(&caption_data.settings.background_color, 2),
+ caption_data.settings.background_opacity as f32 / 100.0,
+ ],
+ position: match caption_data.settings.position.as_str() {
+ "top" => 0,
+ "middle" => 1,
+ _ => 2, // default to bottom
+ },
+ outline: if caption_data.settings.outline { 1 } else { 0 },
+ outline_color: [
+ parse_color_component(&caption_data.settings.outline_color, 0),
+ parse_color_component(&caption_data.settings.outline_color, 1),
+ parse_color_component(&caption_data.settings.outline_color, 2),
+ 1.0,
+ ],
+ font: match caption_data.settings.font.as_str() {
+ "System Serif" => 1,
+ "System Monospace" => 2,
+ _ => 0, // Default to SansSerif for "System Sans-Serif" and any other value
+ },
+ _padding: [0.0],
+ };
+
+ self.update_caption(Some(caption_text), current_time);
+
+ if settings.enabled == 0 {
+ return;
+ }
+
+ if self.current_text.is_none() {
+ return;
+ }
+
+ if let Some(text) = &self.current_text {
+ let (width, height) = (output_size.x, output_size.y);
+
+ // Access device and queue from the pipeline's constants
+ let device = &constants.device;
+ let queue = &constants.queue;
+
+ // Find caption position based on settings
+ let y_position = match settings.position {
+ 0 => height as f32 * 0.1, // top
+ 1 => height as f32 * 0.5, // middle
+ _ => height as f32 * 0.85, // bottom (default)
+ };
+
+ // Set up caption appearance
+ let color = Color::rgb(
+ (settings.color[0] * 255.0) as u8,
+ (settings.color[1] * 255.0) as u8,
+ (settings.color[2] * 255.0) as u8,
+ );
+
+ // Get outline color if needed
+ let outline_color = Color::rgb(
+ (settings.outline_color[0] * 255.0) as u8,
+ (settings.outline_color[1] * 255.0) as u8,
+ (settings.outline_color[2] * 255.0) as u8,
+ );
+
+ // Calculate text bounds
+ let font_size = settings.font_size * (height as f32 / 1080.0); // Scale font size based on resolution
+ let metrics = Metrics::new(font_size, font_size * 1.2); // 1.2 line height
+
+ // Create a new buffer with explicit size for this frame
+ let mut updated_buffer = Buffer::new(&mut self.font_system, metrics);
+
+ // Set explicit width to enable proper text wrapping and centering
+ // Set width to 90% of screen width for better appearance
+ let text_width = width as f32 * 0.9;
+ updated_buffer.set_size(&mut self.font_system, Some(text_width), None);
+ updated_buffer.set_wrap(&mut self.font_system, glyphon::Wrap::Word);
+
+ // Position text in the center horizontally
+ // The bounds dictate the rendering area
+ let bounds = TextBounds {
+ left: ((width as f32 - text_width) / 2.0) as i32, // Center the text horizontally
+ top: y_position as i32,
+ right: ((width as f32 + text_width) / 2.0) as i32, // Center + width
+ bottom: (y_position + font_size * 4.0) as i32, // Increased height for better visibility
+ };
+
+ // Apply text styling directly when setting the text
+ // Create text attributes with or without outline
+ let font_family = match settings.font {
+ 0 => Family::SansSerif,
+ 1 => Family::Serif,
+ 2 => Family::Monospace,
+ _ => Family::SansSerif, // Default to SansSerif for any other value
+ };
+ let attrs = Attrs::new().family(font_family).color(color);
+
+ // Apply text to buffer
+ updated_buffer.set_text(
+ &mut self.font_system,
+ text,
+ attrs,
+ Shaping::Advanced,
+ );
+
+ // Replace the existing buffer
+ self.text_buffer = updated_buffer;
+
+ // Update the viewport with explicit resolution
+ self.viewport.update(queue, Resolution { width, height });
+
+ // Background color
+ let bg_color = if settings.background_color[3] > 0.01 {
+ // Create a new text area with background color
+ Color::rgba(
+ (settings.background_color[0] * 255.0) as u8,
+ (settings.background_color[1] * 255.0) as u8,
+ (settings.background_color[2] * 255.0) as u8,
+ (settings.background_color[3] * 255.0) as u8,
+ )
+ } else {
+ Color::rgba(0, 0, 0, 0)
+ };
+
+ // Prepare text areas for rendering
+ let mut text_areas = Vec::new();
+
+ // Add background if enabled
+ if settings.background_color[3] > 0.01 {
+ text_areas.push(TextArea {
+ buffer: &self.text_buffer,
+ left: bounds.left as f32, // Match the bounds left for positioning
+ top: y_position,
+ scale: 1.0,
+ bounds,
+ default_color: bg_color,
+ custom_glyphs: &[],
+ });
+ }
+
+ // Add outline if enabled (by rendering the text multiple times with slight offsets in different positions)
+ if settings.outline == 1 {
+ info!("Rendering with outline");
+ // Outline is created by drawing the text multiple times with small offsets in different directions
+ let outline_offsets = [
+ (-1.0, -1.0),
+ (0.0, -1.0),
+ (1.0, -1.0),
+ (-1.0, 0.0),
+ (1.0, 0.0),
+ (-1.0, 1.0),
+ (0.0, 1.0),
+ (1.0, 1.0),
+ ];
+
+ for (offset_x, offset_y) in outline_offsets.iter() {
+ text_areas.push(TextArea {
+ buffer: &self.text_buffer,
+ left: bounds.left as f32 + offset_x, // Match bounds with small offset for outline
+ top: y_position + offset_y,
+ scale: 1.0,
+ bounds,
+ default_color: outline_color,
+ custom_glyphs: &[],
+ });
+ }
+ }
+
+ // Add main text (rendered last, on top of everything)
+ text_areas.push(TextArea {
+ buffer: &self.text_buffer,
+ left: bounds.left as f32, // Match the bounds left for positioning
+ top: y_position,
+ scale: 1.0,
+ bounds,
+ default_color: color,
+ custom_glyphs: &[],
+ });
+
+ // Prepare text rendering
+ match self.text_renderer.prepare(
+ device,
+ queue,
+ &mut self.font_system,
+ &mut self.text_atlas,
+ &self.viewport,
+ text_areas,
+ &mut self.swash_cache,
+ ) {
+ Ok(_) => {}
+ Err(e) => warn!("Error preparing text: {:?}", e),
+ }
+ }
+ } else {
+ }
+ } else {
+ }
+ } else {
+ }
+ }
+
+ /// Render the current caption to the frame
+ pub fn render<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>) {
+ match self
+ .text_renderer
+ .render(&self.text_atlas, &self.viewport, pass)
+ {
+ Ok(_) => {}
+ Err(e) => warn!("Error rendering text: {:?}", e),
+ }
+ }
+}
+
+/// Function to find the current caption segment based on playback time
+pub fn find_caption_at_time(time: f32, segments: &[CaptionSegment]) -> Option<&CaptionSegment> {
+ segments
+ .iter()
+ .find(|segment| time >= segment.start && time < segment.end)
+}
+
+// Adding a new version that accepts cap_project::CaptionSegment
+/// Function to find the current caption segment from cap_project::CaptionSegment based on playback time
+pub fn find_caption_at_time_project(
+ time: f32,
+ segments: &[cap_project::CaptionSegment],
+) -> Option<CaptionSegment> {
+ segments
+ .iter()
+ .find(|segment| time >= segment.start && time < segment.end)
+ .map(|segment| CaptionSegment {
+ id: segment.id.clone(),
+ start: segment.start,
+ end: segment.end,
+ text: segment.text.clone(),
+ })
+}
+
+/// Convert from cap_project::CaptionSegment to our internal CaptionSegment
+pub fn convert_project_caption(segment: &cap_project::CaptionSegment) -> CaptionSegment {
+ CaptionSegment {
+ id: segment.id.clone(),
+ start: segment.start,
+ end: segment.end,
+ text: segment.text.clone(),
+ }
+}
diff --git a/crates/rendering/src/layers/mod.rs b/crates/rendering/src/layers/mod.rs
index 8605a463b..1469690f2 100644
--- a/crates/rendering/src/layers/mod.rs
+++ b/crates/rendering/src/layers/mod.rs
@@ -1,11 +1,13 @@
mod background;
mod blur;
mod camera;
+mod captions;
mod cursor;
mod display;
pub use background::*;
pub use blur::*;
pub use camera::*;
+pub use captions::*;
pub use cursor::*;
pub use display::*;
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 8fe98a7b3..8d3d12f02 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -11,7 +11,7 @@ use frame_pipeline::finish_encoder;
use futures::future::OptionFuture;
use futures::FutureExt;
use layers::{
- Background, BackgroundLayer, BlurLayer, CameraLayer, CursorLayer, DisplayLayer,
+ Background, BackgroundLayer, BlurLayer, CameraLayer, CaptionsLayer, CursorLayer, DisplayLayer,
GradientOrColorPipeline, ImageBackgroundPipeline,
};
use specta::Type;
@@ -21,6 +21,7 @@ use tokio::sync::mpsc;
use tracing::subscriber::DefaultGuard;
use image::GenericImageView;
+use log::{debug, info, warn};
use std::{path::PathBuf, time::Instant};
mod composite_frame;
@@ -205,11 +206,10 @@ pub async fn render_video_to_channel(
);
let mut frame_number = 0;
- let background = project.background.source.clone();
let mut frame_renderer = FrameRenderer::new(&constants);
- let mut layers = RendererLayers::new(&constants.device);
+ let mut layers = RendererLayers::new(&constants.device, &constants.queue);
loop {
if frame_number >= total_frames {
@@ -938,7 +938,7 @@ impl<'a> FrameRenderer<'a> {
);
produce_frame(
- &self.constants,
+ self.constants,
segment_frames,
uniforms,
cursor,
@@ -955,16 +955,18 @@ pub struct RendererLayers {
display: DisplayLayer,
cursor: CursorLayer,
camera: CameraLayer,
+ captions: CaptionsLayer,
}
impl RendererLayers {
- pub fn new(device: &wgpu::Device) -> Self {
+ pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
Self {
background: BackgroundLayer::new(device),
background_blur: BlurLayer::new(device),
display: DisplayLayer::new(device),
cursor: CursorLayer::new(device),
camera: CameraLayer::new(device),
+ captions: CaptionsLayer::new(device, queue),
}
}
@@ -1025,6 +1027,15 @@ impl RendererLayers {
);
}
+ // if let Some(captions) = &uniforms.project.captions {
+ // self.captions.prepare(
+ // uniforms,
+ // segment_frames,
+ // uniforms.resolution_base,
+ // constants,
+ // );
+ // }
+
Ok(())
}
@@ -1083,6 +1094,11 @@ impl RendererLayers {
let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
self.camera.render(&mut pass);
}
+
+ // {
+ // let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ // self.captions.render(&mut pass);
+ // }
}
}
@@ -1213,6 +1229,29 @@ async fn produce_frame(
.await?)
}
+// Helper function to parse color components from hex strings
+fn parse_color_component(hex_color: &str, index: usize) -> f32 {
+ // Remove # prefix if present
+ let color = hex_color.trim_start_matches('#');
+
+ // Parse the color component
+ if color.len() == 6 {
+ // Standard hex color #RRGGBB
+ let start = index * 2;
+ if let Ok(value) = u8::from_str_radix(&color[start..start + 2], 16) {
+ return value as f32 / 255.0;
+ }
+ }
+
+ // Default fallback values
+ match index {
+ 0 => 1.0, // Red default
+ 1 => 1.0, // Green default
+ 2 => 1.0, // Blue default
+ _ => 1.0, // Alpha default
+ }
+}
+
pub fn create_shader_render_pipeline(
device: &wgpu::Device,
bind_group_layout: &wgpu::BindGroupLayout,
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index c0409dc01..09ff520c5 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -23,6 +23,7 @@ declare global {
const IconCapCorners: typeof import('~icons/cap/corners.jsx')['default']
const IconCapCrop: typeof import('~icons/cap/crop.jsx')['default']
const IconCapCursor: typeof import('~icons/cap/cursor.jsx')['default']
+ const IconCapDownload: typeof import('~icons/cap/download.jsx')['default']
const IconCapEditor: typeof import('~icons/cap/editor.jsx')['default']
const IconCapEnlarge: typeof import('~icons/cap/enlarge.jsx')['default']
const IconCapFile: typeof import('~icons/cap/file.jsx')['default']
@@ -54,6 +55,7 @@ declare global {
const IconCapPresets: typeof import('~icons/cap/presets.jsx')['default']
const IconCapPrev: typeof import('~icons/cap/prev.jsx')['default']
const IconCapRedo: typeof import('~icons/cap/redo.jsx')['default']
+ const IconCapRefresh: typeof import('~icons/cap/refresh.jsx')['default']
const IconCapRestart: typeof import('~icons/cap/restart.jsx')['default']
const IconCapScissors: typeof import('~icons/cap/scissors.jsx')['default']
const IconCapSettings: typeof import('~icons/cap/settings.jsx')['default']