Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add WhisperX server integration and advanced caption timing

Richie McIlroyf789af9e8fc6
diff --git a/apps/desktop/src-tauri/src/captions.rs b/apps/desktop/src-tauri/src/captions.rs
index 9904909fc..15a953ba5 100644
--- a/apps/desktop/src-tauri/src/captions.rs
+++ b/apps/desktop/src-tauri/src/captions.rs
@@ -10,6 +10,7 @@ use specta::Type;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
+use std::process::Command;
use std::sync::Arc;
use tauri::{AppHandle, Emitter, Manager, Window};
use tempfile::tempdir;
@@ -799,6 +800,660 @@ fn process_with_whisper(
})
}
+fn find_python() -> Option<String> {
+ let python_commands = if cfg!(target_os = "windows") {
+ vec!["python", "python3", "py"]
+ } else {
+ vec!["python3", "python"]
+ };
+
+ for cmd in python_commands {
+ if let Ok(output) = Command::new(cmd).arg("--version").output() {
+ if output.status.success() {
+ let version = String::from_utf8_lossy(&output.stdout);
+ if version.contains("Python 3")
+ || String::from_utf8_lossy(&output.stderr).contains("Python 3")
+ {
+ log::info!("Found Python 3 at: {}", cmd);
+ return Some(cmd.to_string());
+ }
+ }
+ }
+ }
+ None
+}
+
+const WHISPERX_WHL_URL: &str =
+ "https://github.com/m-bain/whisperX/releases/download/v3.7.4/whisperx-3.7.4-py3-none-any.whl";
+const WHISPERX_WHL_NAME: &str = "whisperx-3.7.4-py3-none-any.whl";
+
+lazy_static::lazy_static! {
+ static ref WHISPERX_SERVER: Arc<Mutex<Option<WhisperXServer>>> = Arc::new(Mutex::new(None));
+}
+
+struct WhisperXServer {
+ child: std::process::Child,
+ stdin: std::io::BufWriter<std::process::ChildStdin>,
+ stdout: std::io::BufReader<std::process::ChildStdout>,
+ model_size: String,
+}
+
+impl Drop for WhisperXServer {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ }
+}
+
+fn get_whisperx_server_script() -> String {
+ r#"
+import os
+import sys
+import json
+
+hf_cache = sys.argv[1]
+torch_cache = sys.argv[2]
+models_cache = sys.argv[3]
+
+os.environ["HF_HOME"] = hf_cache
+os.environ["HUGGINGFACE_HUB_CACHE"] = hf_cache
+os.environ["TORCH_HOME"] = torch_cache
+os.environ["XDG_CACHE_HOME"] = models_cache
+
+import warnings
+warnings.filterwarnings("ignore")
+
+import torch
+torch.hub.set_dir(torch_cache)
+
+original_torch_load = torch.load
+def patched_torch_load(*args, **kwargs):
+ kwargs['weights_only'] = False
+ return original_torch_load(*args, **kwargs)
+torch.load = patched_torch_load
+
+import whisperx
+
+device = "cuda" if torch.cuda.is_available() else "cpu"
+compute_type = "float16" if device == "cuda" else "int8"
+
+cached_model = None
+cached_model_size = None
+cached_align_models = {}
+
+def load_or_get_model(model_size, language, download_root):
+ global cached_model, cached_model_size
+
+ if cached_model is not None and cached_model_size == model_size:
+ return cached_model
+
+ print(f"STDERR:Loading WhisperX model: {model_size} on {device}", file=sys.stderr, flush=True)
+ cached_model = whisperx.load_model(model_size, device, compute_type=compute_type, language=language, download_root=download_root)
+ cached_model_size = model_size
+ return cached_model
+
+def load_or_get_align_model(language_code):
+ global cached_align_models
+
+ if language_code in cached_align_models:
+ return cached_align_models[language_code]
+
+ print(f"STDERR:Loading alignment model for: {language_code}", file=sys.stderr, flush=True)
+ model_a, metadata = whisperx.load_align_model(language_code=language_code, device=device)
+ cached_align_models[language_code] = (model_a, metadata)
+ return model_a, metadata
+
+print("READY", flush=True)
+
+for line in sys.stdin:
+ try:
+ request = json.loads(line.strip())
+ audio_file = request["audio_file"]
+ model_size = request["model_size"]
+ language = request.get("language")
+ download_root = request["download_root"]
+
+ if language == "" or language == "auto":
+ language = None
+
+ model = load_or_get_model(model_size, language, download_root)
+
+ print(f"STDERR:Loading audio...", file=sys.stderr, flush=True)
+ audio = whisperx.load_audio(audio_file)
+
+ print(f"STDERR:Transcribing...", file=sys.stderr, flush=True)
+ result = model.transcribe(audio, batch_size=16)
+
+ detected_lang = result["language"]
+ print(f"STDERR:Detected language: {detected_lang}", file=sys.stderr, flush=True)
+
+ model_a, metadata = load_or_get_align_model(detected_lang)
+
+ print(f"STDERR:Aligning words...", file=sys.stderr, flush=True)
+ result = whisperx.align(result["segments"], model_a, metadata, audio, device, return_char_alignments=False)
+
+ output = {"segments": []}
+ for seg in result["segments"]:
+ segment = {
+ "start": seg["start"],
+ "end": seg["end"],
+ "text": seg["text"],
+ "words": []
+ }
+ if "words" in seg:
+ for w in seg["words"]:
+ word = {"word": w.get("word", "")}
+ if "start" in w:
+ word["start"] = w["start"]
+ if "end" in w:
+ word["end"] = w["end"]
+ segment["words"].append(word)
+ output["segments"].append(segment)
+
+ print(f"STDERR:WhisperX completed: {len(output['segments'])} segments", file=sys.stderr, flush=True)
+ print(json.dumps({"success": True, "result": output}), flush=True)
+
+ except Exception as e:
+ print(json.dumps({"success": False, "error": str(e)}), flush=True)
+"#.to_string()
+}
+
+fn ensure_server_script_exists() -> Result<PathBuf, String> {
+ let cache_dir = get_whisperx_cache_dir()?;
+ let script_path = cache_dir.join("whisperx_server.py");
+
+ if !script_path.exists() {
+ std::fs::write(&script_path, get_whisperx_server_script())
+ .map_err(|e| format!("Failed to write server script: {}", e))?;
+ log::info!("Created WhisperX server script at {:?}", script_path);
+ }
+
+ Ok(script_path)
+}
+
+fn start_whisperx_server(
+ venv_python: &PathBuf,
+ model_size: &str,
+) -> Result<WhisperXServer, String> {
+ let models_cache = get_whisperx_models_cache_dir()?;
+ let hf_cache = get_huggingface_cache_dir()?;
+ let torch_cache = get_torch_cache_dir()?;
+
+ let script_path = ensure_server_script_exists()?;
+
+ log::info!("Starting WhisperX server with model size: {}", model_size);
+
+ let mut child = Command::new(venv_python)
+ .arg(&script_path)
+ .arg(hf_cache.to_string_lossy().to_string())
+ .arg(torch_cache.to_string_lossy().to_string())
+ .arg(models_cache.to_string_lossy().to_string())
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .map_err(|e| format!("Failed to start WhisperX server: {}", e))?;
+
+ let stdin = child
+ .stdin
+ .take()
+ .ok_or_else(|| "Failed to get stdin".to_string())?;
+ let stdout = child
+ .stdout
+ .take()
+ .ok_or_else(|| "Failed to get stdout".to_string())?;
+ let stderr = child
+ .stderr
+ .take()
+ .ok_or_else(|| "Failed to get stderr".to_string())?;
+
+ let stdin = std::io::BufWriter::new(stdin);
+ let mut stdout = std::io::BufReader::new(stdout);
+
+ std::thread::spawn(move || {
+ use std::io::BufRead;
+ let reader = std::io::BufReader::new(stderr);
+ for line in reader.lines() {
+ if let Ok(line) = line {
+ if line.starts_with("STDERR:") {
+ log::info!("[WhisperX] {}", &line[7..]);
+ } else {
+ log::info!("[WhisperX stderr] {}", line);
+ }
+ }
+ }
+ });
+
+ use std::io::BufRead;
+ let mut ready_line = String::new();
+ let start_time = std::time::Instant::now();
+ let timeout = std::time::Duration::from_secs(120);
+
+ loop {
+ if start_time.elapsed() > timeout {
+ let _ = child.kill();
+ return Err("WhisperX server startup timed out".to_string());
+ }
+
+ ready_line.clear();
+ match stdout.read_line(&mut ready_line) {
+ Ok(0) => {
+ let _ = child.kill();
+ return Err("WhisperX server closed unexpectedly".to_string());
+ }
+ Ok(_) => {
+ if ready_line.trim() == "READY" {
+ log::info!(
+ "WhisperX server is ready (took {:.1}s)",
+ start_time.elapsed().as_secs_f32()
+ );
+ break;
+ }
+ }
+ Err(e) => {
+ let _ = child.kill();
+ return Err(format!("Error reading from WhisperX server: {}", e));
+ }
+ }
+ }
+
+ Ok(WhisperXServer {
+ child,
+ stdin,
+ stdout,
+ model_size: model_size.to_string(),
+ })
+}
+
+fn transcribe_with_server(
+ server: &mut WhisperXServer,
+ audio_path: &PathBuf,
+ model_size: &str,
+ language: &str,
+) -> Result<CaptionData, String> {
+ use std::io::{BufRead, Write};
+
+ let models_cache = get_whisperx_models_cache_dir()?;
+
+ let request = serde_json::json!({
+ "audio_file": audio_path.to_string_lossy(),
+ "model_size": model_size,
+ "language": if language == "auto" { "" } else { language },
+ "download_root": models_cache.to_string_lossy(),
+ });
+
+ log::info!("Sending transcription request to WhisperX server");
+
+ writeln!(server.stdin, "{}", request.to_string())
+ .map_err(|e| format!("Failed to send request to server: {}", e))?;
+ server
+ .stdin
+ .flush()
+ .map_err(|e| format!("Failed to flush request: {}", e))?;
+
+ let mut response_line = String::new();
+ server
+ .stdout
+ .read_line(&mut response_line)
+ .map_err(|e| format!("Failed to read response from server: {}", e))?;
+
+ let response: serde_json::Value = serde_json::from_str(&response_line)
+ .map_err(|e| format!("Failed to parse server response: {}", e))?;
+
+ if !response["success"].as_bool().unwrap_or(false) {
+ let error = response["error"].as_str().unwrap_or("Unknown error");
+ return Err(format!("WhisperX server error: {}", error));
+ }
+
+ let whisperx_result: WhisperXOutput = serde_json::from_value(response["result"].clone())
+ .map_err(|e| format!("Failed to parse WhisperX output: {}", e))?;
+
+ log::info!(
+ "WhisperX server produced {} segments",
+ whisperx_result.segments.len()
+ );
+
+ let mut segments = Vec::new();
+ const MAX_WORDS_PER_SEGMENT: usize = 6;
+
+ for (seg_idx, whisperx_seg) in whisperx_result.segments.iter().enumerate() {
+ log::info!(
+ "Segment {}: '{}' ({:.2}s - {:.2}s) with {} words",
+ seg_idx,
+ whisperx_seg.text.trim(),
+ whisperx_seg.start,
+ whisperx_seg.end,
+ whisperx_seg.words.len()
+ );
+
+ let mut words: Vec<CaptionWord> = Vec::new();
+
+ for (word_idx, w) in whisperx_seg.words.iter().enumerate() {
+ let word_text = w.word.trim().to_string();
+ if word_text.is_empty() {
+ continue;
+ }
+
+ let word_start = w.start.unwrap_or_else(|| {
+ if word_idx == 0 {
+ whisperx_seg.start
+ } else if let Some(prev) = words.last() {
+ prev.end as f64
+ } else {
+ whisperx_seg.start
+ }
+ });
+
+ let word_end = w.end.unwrap_or_else(|| {
+ if word_idx == whisperx_seg.words.len() - 1 {
+ whisperx_seg.end
+ } else {
+ word_start + 0.2
+ }
+ });
+
+ words.push(CaptionWord {
+ text: word_text,
+ start: word_start as f32,
+ end: word_end as f32,
+ });
+ }
+
+ if words.is_empty() {
+ continue;
+ }
+
+ let word_chunks: Vec<Vec<CaptionWord>> = words
+ .chunks(MAX_WORDS_PER_SEGMENT)
+ .map(|chunk| chunk.to_vec())
+ .collect();
+
+ for (chunk_idx, chunk_words) in word_chunks.into_iter().enumerate() {
+ let segment_text = chunk_words
+ .iter()
+ .map(|word| word.text.clone())
+ .collect::<Vec<_>>()
+ .join(" ");
+
+ let segment_start = chunk_words
+ .first()
+ .map(|w| w.start)
+ .unwrap_or(whisperx_seg.start as f32);
+ let segment_end = chunk_words
+ .last()
+ .map(|w| w.end)
+ .unwrap_or(whisperx_seg.end as f32);
+
+ segments.push(CaptionSegment {
+ id: format!("segment-{}-{}", seg_idx, chunk_idx),
+ start: segment_start,
+ end: segment_end,
+ text: segment_text,
+ words: chunk_words,
+ });
+ }
+ }
+
+ Ok(CaptionData {
+ segments,
+ settings: Some(cap_project::CaptionSettings::default()),
+ })
+}
+
+fn get_whisperx_cache_dir() -> Result<PathBuf, String> {
+ let cache_dir = dirs::cache_dir()
+ .or_else(dirs::data_local_dir)
+ .ok_or_else(|| "Could not determine cache directory".to_string())?;
+ let whisperx_dir = cache_dir.join("cap").join("whisperx");
+ std::fs::create_dir_all(&whisperx_dir)
+ .map_err(|e| format!("Failed to create whisperx cache directory: {}", e))?;
+ Ok(whisperx_dir)
+}
+
+fn get_whisperx_models_cache_dir() -> Result<PathBuf, String> {
+ let cache_dir = get_whisperx_cache_dir()?;
+ let models_dir = cache_dir.join("models");
+ std::fs::create_dir_all(&models_dir)
+ .map_err(|e| format!("Failed to create whisperx models cache directory: {}", e))?;
+ Ok(models_dir)
+}
+
+fn get_huggingface_cache_dir() -> Result<PathBuf, String> {
+ let cache_dir = get_whisperx_cache_dir()?;
+ let hf_dir = cache_dir.join("huggingface");
+ std::fs::create_dir_all(&hf_dir)
+ .map_err(|e| format!("Failed to create huggingface cache directory: {}", e))?;
+ Ok(hf_dir)
+}
+
+fn get_torch_cache_dir() -> Result<PathBuf, String> {
+ let cache_dir = get_whisperx_cache_dir()?;
+ let torch_dir = cache_dir.join("torch");
+ std::fs::create_dir_all(&torch_dir)
+ .map_err(|e| format!("Failed to create torch cache directory: {}", e))?;
+ Ok(torch_dir)
+}
+
+fn get_venv_python() -> Result<PathBuf, String> {
+ let cache_dir = get_whisperx_cache_dir()?;
+ let venv_dir = cache_dir.join("venv");
+
+ if cfg!(target_os = "windows") {
+ Ok(venv_dir.join("Scripts").join("python.exe"))
+ } else {
+ Ok(venv_dir.join("bin").join("python"))
+ }
+}
+
+fn create_venv_if_needed(system_python: &str) -> Result<PathBuf, String> {
+ let cache_dir = get_whisperx_cache_dir()?;
+ let venv_dir = cache_dir.join("venv");
+ let venv_python = get_venv_python()?;
+
+ if venv_python.exists() {
+ log::info!("Virtual environment already exists at: {:?}", venv_dir);
+ return Ok(venv_python);
+ }
+
+ log::info!(
+ "Creating virtual environment at: {:?} using {}",
+ venv_dir,
+ system_python
+ );
+
+ let output = Command::new(system_python)
+ .args(["-m", "venv", venv_dir.to_str().unwrap()])
+ .output()
+ .map_err(|e| format!("Failed to create venv: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!("Failed to create virtual environment: {}", stderr));
+ }
+
+ if !venv_python.exists() {
+ return Err("Virtual environment was created but python not found".to_string());
+ }
+
+ log::info!("Virtual environment created successfully");
+
+ log::info!("Upgrading pip in virtual environment...");
+ let pip_upgrade = Command::new(&venv_python)
+ .args(["-m", "pip", "install", "--upgrade", "pip"])
+ .output();
+
+ if let Err(e) = pip_upgrade {
+ log::warn!("Failed to upgrade pip in venv: {}", e);
+ }
+
+ Ok(venv_python)
+}
+
+fn download_whisperx_whl() -> Result<PathBuf, String> {
+ let cache_dir = get_whisperx_cache_dir()?;
+ let whl_path = cache_dir.join(WHISPERX_WHL_NAME);
+
+ if whl_path.exists() {
+ log::info!("WhisperX wheel already cached at: {:?}", whl_path);
+ return Ok(whl_path);
+ }
+
+ log::info!("Downloading WhisperX wheel from: {}", WHISPERX_WHL_URL);
+
+ let output = Command::new("curl")
+ .args([
+ "-L",
+ "-o",
+ whl_path.to_str().unwrap(),
+ "--create-dirs",
+ WHISPERX_WHL_URL,
+ ])
+ .output()
+ .map_err(|e| format!("Failed to run curl: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!("Failed to download WhisperX wheel: {}", stderr));
+ }
+
+ if !whl_path.exists() {
+ return Err("WhisperX wheel was not downloaded".to_string());
+ }
+
+ log::info!("Successfully downloaded WhisperX wheel to: {:?}", whl_path);
+ Ok(whl_path)
+}
+
+fn install_whisperx_in_venv(venv_python: &PathBuf) -> Result<(), String> {
+ log::info!("Installing whisperx in virtual environment...");
+
+ let whl_path = download_whisperx_whl()?;
+ log::info!("Installing WhisperX from: {:?}", whl_path);
+
+ let install_result = Command::new(venv_python)
+ .args(["-m", "pip", "install", whl_path.to_str().unwrap()])
+ .output()
+ .map_err(|e| format!("Failed to run pip install: {}", e))?;
+
+ if !install_result.status.success() {
+ let stderr = String::from_utf8_lossy(&install_result.stderr);
+ return Err(format!("Failed to install whisperx: {}", stderr));
+ }
+
+ log::info!("Successfully installed whisperx in virtual environment");
+ Ok(())
+}
+
+fn setup_whisperx_environment(system_python: &str) -> Result<PathBuf, String> {
+ let venv_python = create_venv_if_needed(system_python)?;
+
+ let check_output = Command::new(&venv_python)
+ .args(["-c", "import whisperx; print('ok')"])
+ .output();
+
+ let whisperx_installed = check_output
+ .map(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("ok"))
+ .unwrap_or(false);
+
+ if whisperx_installed {
+ log::info!("WhisperX already installed in virtual environment");
+ return Ok(venv_python);
+ }
+
+ install_whisperx_in_venv(&venv_python)?;
+ Ok(venv_python)
+}
+
+#[derive(Debug, Deserialize)]
+struct WhisperXWord {
+ word: String,
+ start: Option<f64>,
+ end: Option<f64>,
+}
+
+#[derive(Debug, Deserialize)]
+struct WhisperXSegment {
+ start: f64,
+ end: f64,
+ text: String,
+ #[serde(default)]
+ words: Vec<WhisperXWord>,
+}
+
+#[derive(Debug, Deserialize)]
+struct WhisperXOutput {
+ segments: Vec<WhisperXSegment>,
+}
+
+fn get_model_size_from_path(model_path: &str) -> &str {
+ if model_path.contains("large") {
+ "large-v3"
+ } else if model_path.contains("medium") {
+ "medium"
+ } else if model_path.contains("small") {
+ "small"
+ } else if model_path.contains("base") {
+ "base"
+ } else {
+ "tiny"
+ }
+}
+
+#[tauri::command]
+#[specta::specta]
+#[instrument]
+pub async fn prewarm_whisperx(model_path: String) -> Result<bool, String> {
+ if !std::path::Path::new(&model_path).exists() {
+ log::info!("No model downloaded, skipping WhisperX pre-warm");
+ return Ok(false);
+ }
+
+ let system_python = match find_python() {
+ Some(p) => p,
+ None => {
+ log::info!("Python not found, skipping WhisperX pre-warm");
+ return Ok(false);
+ }
+ };
+
+ let venv_python = match setup_whisperx_environment(&system_python) {
+ Ok(p) => p,
+ Err(e) => {
+ log::info!("WhisperX environment not ready: {}, skipping pre-warm", e);
+ return Ok(false);
+ }
+ };
+
+ let model_size = get_model_size_from_path(&model_path).to_string();
+
+ log::info!(
+ "Pre-warming WhisperX server with model size: {}",
+ model_size
+ );
+
+ tokio::task::spawn_blocking(move || {
+ let mut server_guard = WHISPERX_SERVER.blocking_lock();
+
+ if server_guard.is_some() {
+ log::info!("WhisperX server already running, pre-warm not needed");
+ return;
+ }
+
+ match start_whisperx_server(&venv_python, &model_size) {
+ Ok(server) => {
+ log::info!(
+ "WhisperX server pre-warmed successfully - transcriptions will be fast!"
+ );
+ *server_guard = Some(server);
+ }
+ Err(e) => {
+ log::warn!("Failed to pre-warm WhisperX server: {}", e);
+ }
+ }
+ });
+
+ Ok(true)
+}
+
#[tauri::command]
#[specta::specta]
#[instrument]
@@ -848,6 +1503,118 @@ pub async fn transcribe_audio(
);
}
+ let model_size = get_model_size_from_path(&model_path);
+ log::info!("Detected model size: {}", model_size);
+
+ if let Some(system_python) = find_python() {
+ log::info!("Found system Python at: {}", system_python);
+
+ match setup_whisperx_environment(&system_python) {
+ Ok(venv_python) => {
+ let audio_path_clone = audio_path.clone();
+ let language_clone = language.clone();
+ let model_size_clone = model_size.to_string();
+ let venv_python_clone = venv_python.clone();
+
+ log::info!("Attempting to use persistent WhisperX server...");
+ let whisperx_result = tokio::task::spawn_blocking(move || {
+ let mut server_guard = WHISPERX_SERVER.blocking_lock();
+
+ let need_new_server = match &*server_guard {
+ Some(server) => {
+ if server.model_size != model_size_clone {
+ log::info!(
+ "Model size changed from {} to {}, restarting server",
+ server.model_size,
+ model_size_clone
+ );
+ true
+ } else {
+ false
+ }
+ }
+ None => true,
+ };
+
+ if need_new_server {
+ *server_guard = None;
+
+ match start_whisperx_server(&venv_python_clone, &model_size_clone) {
+ Ok(server) => {
+ log::info!("WhisperX server started successfully");
+ *server_guard = Some(server);
+ }
+ Err(e) => {
+ log::warn!("Failed to start WhisperX server: {}", e);
+ return Err(e);
+ }
+ }
+ } else {
+ log::info!("Reusing existing WhisperX server (models already loaded!)");
+ }
+
+ if let Some(server) = server_guard.as_mut() {
+ transcribe_with_server(
+ server,
+ &audio_path_clone,
+ &model_size_clone,
+ &language_clone,
+ )
+ } else {
+ Err("Server not available".to_string())
+ }
+ })
+ .await
+ .map_err(|e| format!("WhisperX task panicked: {e}"));
+
+ match whisperx_result {
+ Ok(Ok(captions)) => {
+ log::info!("=== TRANSCRIBE AUDIO RESULT (WhisperX) ===");
+ log::info!(
+ "Transcription produced {} segments",
+ captions.segments.len()
+ );
+
+ for (idx, segment) in captions.segments.iter().enumerate() {
+ log::info!(
+ " Result Segment[{}]: '{}' ({} words)",
+ idx,
+ segment.text,
+ segment.words.len()
+ );
+ }
+
+ if captions.segments.is_empty() {
+ log::warn!("No caption segments were generated by WhisperX");
+ } else {
+ log::info!("=== TRANSCRIBE AUDIO COMMAND END (WhisperX success) ===");
+ return Ok(captions);
+ }
+ }
+ Ok(Err(e)) => {
+ log::warn!("WhisperX failed: {}. Falling back to built-in Whisper.", e);
+ }
+ Err(e) => {
+ log::warn!(
+ "WhisperX task error: {}. Falling back to built-in Whisper.",
+ e
+ );
+ }
+ }
+ }
+ Err(e) => {
+ log::warn!(
+ "Failed to setup WhisperX environment: {}. Falling back to built-in Whisper.",
+ e
+ );
+ }
+ }
+ } else {
+ log::info!("Python not found, using built-in Whisper");
+ }
+
+ log::info!("Using built-in Whisper for transcription");
+
let context = match get_whisper_context(&model_path).await {
Ok(ctx) => {
log::info!("Whisper context ready");
@@ -1054,6 +1821,18 @@ pub async fn save_captions(
serde_json::Number::from_f64(settings.fade_duration as f64).unwrap(),
),
);
+ settings_obj.insert(
+ "lingerDuration".to_string(),
+ serde_json::Value::Number(
+ serde_json::Number::from_f64(settings.linger_duration as f64).unwrap(),
+ ),
+ );
+ settings_obj.insert(
+ "wordTransitionDuration".to_string(),
+ serde_json::Value::Number(
+ serde_json::Number::from_f64(settings.word_transition_duration as f64).unwrap(),
+ ),
+ );
json_obj.insert(
"settings".to_string(),
@@ -1191,6 +1970,18 @@ pub fn parse_captions_json(json: &str) -> Result<cap_project::CaptionsData, Stri
.and_then(|v| v.as_f64())
.unwrap_or(0.15) as f32;
+ let linger_duration = settings_obj
+ .get("lingerDuration")
+ .or_else(|| settings_obj.get("linger_duration"))
+ .and_then(|v| v.as_f64())
+ .unwrap_or(0.4) as f32;
+
+ let word_transition_duration = settings_obj
+ .get("wordTransitionDuration")
+ .or_else(|| settings_obj.get("word_transition_duration"))
+ .and_then(|v| v.as_f64())
+ .unwrap_or(0.25) as f32;
+
cap_project::CaptionSettings {
enabled,
font,
@@ -1206,6 +1997,8 @@ pub fn parse_captions_json(json: &str) -> Result<cap_project::CaptionsData, Stri
export_with_subtitles,
highlight_color,
fade_duration,
+ linger_duration,
+ word_transition_duration,
}
} else {
cap_project::CaptionSettings::default()
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 406c04fa8..12c876e2f 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1,3 +1,5 @@
+#![recursion_limit = "256"]
+
mod api;
mod audio;
mod audio_meter;
@@ -2372,6 +2374,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
await_camera_preview_ready,
captions::create_dir,
captions::save_model_file,
+ captions::prewarm_whisperx,
captions::transcribe_audio,
captions::save_captions,
captions::load_captions,
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index 37cc8f10b..8fa1eb331 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -21,7 +21,9 @@ use tokio::sync::RwLock;
use tracing::{debug, error, instrument, warn};
use crate::{
- App, ArcLock, RequestScreenCapturePrewarm, fake_window,
+ App, ArcLock, RequestScreenCapturePrewarm,
+ editor_window::PendingEditorInstances,
+ fake_window,
general_settings::{self, AppTheme, GeneralSettingsStore},
permissions,
recording_settings::RecordingTargetMode,
@@ -229,15 +231,21 @@ impl ShowCapWindow {
pub async fn show(&self, app: &AppHandle<Wry>) -> tauri::Result<WebviewWindow> {
if let Self::Editor { project_path } = &self {
let state = app.state::<EditorWindowIds>();
- let mut s = state.ids.lock().unwrap();
- if !s.iter().any(|(path, _)| path == project_path) {
- s.push((
- project_path.clone(),
- state
+ let window_id = {
+ let mut s = state.ids.lock().unwrap();
+ if !s.iter().any(|(path, _)| path == project_path) {
+ let id = state
.counter
- .fetch_add(1, std::sync::atomic::Ordering::SeqCst),
- ));
- }
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ s.push((project_path.clone(), id));
+ id
+ } else {
+ s.iter().find(|(path, _)| path == project_path).unwrap().1
+ }
+ };
+
+ let window_label = CapWindowId::Editor { id: window_id }.label();
+ PendingEditorInstances::start_prewarm(app, window_label, project_path.clone()).await;
}
if let Self::ScreenshotEditor { path } = &self {
@@ -544,7 +552,16 @@ impl ShowCapWindow {
if let Some(id) = state.selected_camera_id.clone()
&& !state.camera_in_use
{
- let _ = state.camera_feed.ask(feeds::camera::SetInput { id }).await;
+ match state.camera_feed.ask(feeds::camera::SetInput { id }).await {
+ Ok(ready_future) => {
+ if let Err(err) = ready_future.await {
+ error!("Camera failed to initialize: {err}");
+ }
+ }
+ Err(err) => {
+ error!("Failed to send SetInput to camera feed: {err}");
+ }
+ }
state.camera_in_use = true;
}
diff --git a/apps/desktop/src/routes/editor/CaptionsTab.tsx b/apps/desktop/src/routes/editor/CaptionsTab.tsx
index 6b33586ef..610a7ded0 100644
--- a/apps/desktop/src/routes/editor/CaptionsTab.tsx
+++ b/apps/desktop/src/routes/editor/CaptionsTab.tsx
@@ -207,9 +207,16 @@ export function CaptionsTab() {
}),
);
- setDownloadedModels(
- models.filter((m) => m.downloaded).map((m) => m.name),
- );
+ const downloadedModelNames = models
+ .filter((m) => m.downloaded)
+ .map((m) => m.name);
+ setDownloadedModels(downloadedModelNames);
+
+ if (downloadedModelNames.length > 0) {
+ const modelToPrewarm = downloadedModelNames[0];
+ const modelPath = await join(modelsPath, `${modelToPrewarm}.bin`);
+ commands.prewarmWhisperx(modelPath).catch(() => {});
+ }
const savedModel = localStorage.getItem("selectedTranscriptionModel");
if (savedModel && MODEL_OPTIONS.some((m) => m.name === savedModel)) {
@@ -577,7 +584,12 @@ export function CaptionsTab() {
</div>
</div>
- <div class={cx(!hasCaptions() && "opacity-50 pointer-events-none")}>
+ <div
+ class={cx(
+ "space-y-4",
+ !hasCaptions() && "opacity-50 pointer-events-none",
+ )}
+ >
<Field name="Font Settings" icon={<IconCapMessageBubble />}>
<div class="space-y-3">
<div class="flex flex-col gap-2">
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 81690864d..fcce4eb7b 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -238,6 +238,9 @@ async createDir(path: string, recursive: boolean) : Promise<null> {
async saveModelFile(path: string, data: number[]) : Promise<null> {
return await TAURI_INVOKE("save_model_file", { path, data });
},
+async prewarmWhisperx(modelPath: string) : Promise<boolean> {
+ return await TAURI_INVOKE("prewarm_whisperx", { modelPath });
+},
async transcribeAudio(videoPath: string, modelPath: string, language: string) : Promise<CaptionData> {
return await TAURI_INVOKE("transcribe_audio", { videoPath, modelPath, language });
},
@@ -364,7 +367,7 @@ 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; words?: CaptionWord[] }
-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; highlightColor?: string; fadeDuration?: number }
+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; highlightColor?: string; fadeDuration?: number; lingerDuration?: number; wordTransitionDuration?: number }
export type CaptionWord = { text: string; start: number; end: number }
export type CaptionsData = { segments: CaptionSegment[]; settings: CaptionSettings }
export type CaptureDisplay = { id: DisplayId; name: string; refresh_rate: number }
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index e5094d754..ad73c3bc9 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -788,6 +788,16 @@ pub struct CaptionSettings {
default = "CaptionSettings::default_fade_duration"
)]
pub fade_duration: f32,
+ #[serde(
+ alias = "lingerDuration",
+ default = "CaptionSettings::default_linger_duration"
+ )]
+ pub linger_duration: f32,
+ #[serde(
+ alias = "wordTransitionDuration",
+ default = "CaptionSettings::default_word_transition_duration"
+ )]
+ pub word_transition_duration: f32,
}
impl CaptionSettings {
@@ -798,6 +808,14 @@ impl CaptionSettings {
fn default_fade_duration() -> f32 {
0.15
}
+
+ fn default_linger_duration() -> f32 {
+ 0.4
+ }
+
+ fn default_word_transition_duration() -> f32 {
+ 0.25
+ }
}
impl Default for CaptionSettings {
@@ -817,6 +835,8 @@ impl Default for CaptionSettings {
export_with_subtitles: false,
highlight_color: Self::default_highlight_color(),
fade_duration: Self::default_fade_duration(),
+ linger_duration: Self::default_linger_duration(),
+ word_transition_duration: Self::default_word_transition_duration(),
}
}
}
diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rs
index b7497f5ac..98a99b7da 100644
--- a/crates/rendering/src/layers/captions.rs
+++ b/crates/rendering/src/layers/captions.rs
@@ -107,6 +107,7 @@ impl CaptionPosition {
const BASE_TEXT_OPACITY: f32 = 0.8;
const MAX_WORDS_PER_LINE: usize = 6;
const BOUNCE_OFFSET_PIXELS: f32 = 8.0;
+const CLOSE_TRANSITION_BOUNCE_DURATION: f32 = 0.12;
fn wrap_text_by_words(text: &str, max_words: usize) -> String {
let words: Vec<&str> = text.split_whitespace().collect();
@@ -133,7 +134,25 @@ fn calculate_bounce_offset(
time_from_start: f32,
time_to_end: f32,
fade_duration: f32,
+ skip_fade_in: bool,
+ skip_fade_out: bool,
) -> f32 {
+ if skip_fade_in && time_from_start < CLOSE_TRANSITION_BOUNCE_DURATION {
+ let progress = (time_from_start / CLOSE_TRANSITION_BOUNCE_DURATION).clamp(0.0, 1.0);
+ let ease = 1.0 - progress;
+ let bounce = ease * ease;
+ return -bounce * BOUNCE_OFFSET_PIXELS;
+ }
+
+ if skip_fade_out && time_to_end < 0.0 {
+ let time_past_end = -time_to_end;
+ if time_past_end < CLOSE_TRANSITION_BOUNCE_DURATION {
+ let progress = (time_past_end / CLOSE_TRANSITION_BOUNCE_DURATION).clamp(0.0, 1.0);
+ let bounce = progress * progress;
+ return bounce * BOUNCE_OFFSET_PIXELS;
+ }
+ }
+
if fade_duration <= 0.0 {
return 0.0;
}
@@ -141,11 +160,11 @@ fn calculate_bounce_offset(
let fade_in_progress = (time_from_start / fade_duration).clamp(0.0, 1.0);
let fade_out_progress = (time_to_end / fade_duration).clamp(0.0, 1.0);
- if fade_in_progress < 1.0 {
+ if fade_in_progress < 1.0 && !skip_fade_in {
let ease = 1.0 - fade_in_progress;
let bounce = ease * ease;
-bounce * BOUNCE_OFFSET_PIXELS
- } else if fade_out_progress < 1.0 {
+ } else if fade_out_progress < 1.0 && !skip_fade_out {
let ease = 1.0 - fade_out_progress;
let bounce = ease * ease;
bounce * BOUNCE_OFFSET_PIXELS
@@ -154,6 +173,66 @@ fn calculate_bounce_offset(
}
}
+fn ease_out_cubic(t: f32) -> f32 {
+ let t = t.clamp(0.0, 1.0);
+ 1.0 - (1.0 - t).powi(3)
+}
+
+fn ease_in_cubic(t: f32) -> f32 {
+ let t = t.clamp(0.0, 1.0);
+ t * t * t
+}
+
+fn calculate_word_highlight(
+ current_time: f32,
+ word: &CaptionWord,
+ word_idx: usize,
+ all_words: &[CaptionWord],
+ transition_duration: f32,
+) -> f32 {
+ if transition_duration <= 0.0 {
+ if current_time >= word.start && current_time < word.end {
+ return 1.0;
+ }
+ return 0.0;
+ }
+
+ let next_word_start = if word_idx + 1 < all_words.len() {
+ Some(all_words[word_idx + 1].start)
+ } else {
+ None
+ };
+
+ if current_time >= word.start && current_time < word.end {
+ let time_since_start = current_time - word.start;
+ let fade_in = ease_out_cubic(time_since_start / transition_duration);
+ return fade_in;
+ }
+
+ if current_time >= word.end {
+ if let Some(next_start) = next_word_start {
+ if current_time < next_start {
+ let time_since_end = current_time - word.end;
+ let gap_duration = next_start - word.end;
+ let effective_duration = transition_duration.min(gap_duration);
+
+ if time_since_end < effective_duration {
+ let progress = time_since_end / effective_duration;
+ return 1.0 - ease_in_cubic(progress);
+ }
+ }
+ } else {
+ let time_since_end = current_time - word.end;
+ if time_since_end < transition_duration {
+ let progress = time_since_end / transition_duration;
+ return 1.0 - ease_in_cubic(progress);
+ }
+ }
+ }
+
+ 0.0
+}
+
pub struct CaptionsLayer {
settings_buffer: wgpu::Buffer,
font_system: FontSystem,
@@ -307,7 +386,14 @@ impl CaptionsLayer {
self.current_segment_end = end;
}
- fn calculate_fade_opacity(&self, current_time: f32, fade_duration: f32) -> (f32, f32, f32) {
+ fn calculate_fade_opacity(
+ &self,
+ current_time: f32,
+ fade_duration: f32,
+ linger_duration: f32,
+ skip_fade_in: bool,
+ skip_fade_out: bool,
+ ) -> (f32, f32, f32) {
let time_from_start = current_time - self.current_segment_start;
let time_to_end = self.current_segment_end - current_time;
@@ -315,8 +401,24 @@ impl CaptionsLayer {
return (1.0, time_from_start, time_to_end);
}
- let fade_in = (time_from_start / fade_duration).min(1.0);
- let fade_out = (time_to_end / fade_duration).min(1.0);
+ let fade_in = if skip_fade_in {
+ 1.0
+ } else {
+ (time_from_start / fade_duration).min(1.0)
+ };
+
+ let fade_out = if skip_fade_out {
+ 1.0
+ } else {
+ let effective_time_to_end = time_to_end + linger_duration;
+ if effective_time_to_end > linger_duration {
+ 1.0
+ } else if effective_time_to_end > 0.0 {
+ (effective_time_to_end / fade_duration).min(1.0)
+ } else {
+ 0.0
+ }
+ };
(fade_in.min(fade_out).max(0.0), time_from_start, time_to_end)
}
@@ -344,14 +446,23 @@ impl CaptionsLayer {
let current_time = segment_frames.segment_time;
let fade_duration = caption_data.settings.fade_duration;
-
- let Some(current_caption) =
- find_caption_at_time_project(current_time, &caption_data.segments)
- else {
+ let linger_duration = caption_data.settings.linger_duration;
+ let word_transition_duration = caption_data.settings.word_transition_duration;
+
+ let Some(caption_result) = find_caption_at_time_project(
+ current_time,
+ &caption_data.segments,
+ linger_duration,
+ fade_duration,
+ ) else {
self.current_text = None;
return;
};
+ let current_caption = caption_result.segment;
+ let skip_fade_in = caption_result.skip_fade_in;
+ let skip_fade_out = caption_result.skip_fade_out;
+
self.update_caption(
Some(current_caption.text.clone()),
current_caption.start,
@@ -361,15 +472,26 @@ impl CaptionsLayer {
let raw_caption_text = self.current_text.clone().unwrap_or_default();
let caption_text = wrap_text_by_words(&raw_caption_text, MAX_WORDS_PER_LINE);
let caption_words = current_caption.words.clone();
- let (fade_opacity, time_from_start, time_to_end) =
- self.calculate_fade_opacity(current_time, fade_duration);
+ let (fade_opacity, time_from_start, time_to_end) = self.calculate_fade_opacity(
+ current_time,
+ fade_duration,
+ linger_duration,
+ skip_fade_in,
+ skip_fade_out,
+ );
if fade_opacity <= 0.0 {
self.current_text = None;
return;
}
- let bounce_offset =
- calculate_bounce_offset(fade_opacity, time_from_start, time_to_end, fade_duration);
+ let bounce_offset = calculate_bounce_offset(
+ fade_opacity,
+ time_from_start,
+ time_to_end,
+ fade_duration,
+ skip_fade_in,
+ skip_fade_out,
+ );
let (width, height) = (output_size.x, output_size.y);
let device = &constants.device;
@@ -430,10 +552,6 @@ impl CaptionsLayer {
let highlight_alpha = fade_opacity.clamp(0.0, 1.0);
if !caption_words.is_empty() {
- let current_word_idx = caption_words
- .iter()
- .position(|w| current_time >= w.start && current_time < w.end);
-
let mut rich_text: Vec<(&str, Attrs)> = Vec::new();
let full_text = caption_text.as_str();
let mut last_end = 0usize;
@@ -458,18 +576,22 @@ impl CaptionsLayer {
));
}
- let is_current = Some(idx) == current_word_idx;
- let alpha = if is_current {
- highlight_alpha
- } else {
- base_alpha
- };
+ let word_highlight = calculate_word_highlight(
+ current_time,
+ word,
+ idx,
+ &caption_words,
+ word_transition_duration,
+ );
- let color_rgb = if is_current {
- highlight_color_rgb
- } else {
- base_color
- };
+ let blended_color = [
+ base_color[0] + (highlight_color_rgb[0] - base_color[0]) * word_highlight,
+ base_color[1] + (highlight_color_rgb[1] - base_color[1]) * word_highlight,
+ base_color[2] + (highlight_color_rgb[2] - base_color[2]) * word_highlight,
+ ];
+
+ let blended_alpha =
+ base_alpha + (highlight_alpha - base_alpha) * word_highlight;
let word_end = abs_start + word.text.len();
rich_text.push((
@@ -478,10 +600,10 @@ impl CaptionsLayer {
.family(font_family)
.weight(weight)
.color(Color::rgba(
- (color_rgb[0] * 255.0) as u8,
- (color_rgb[1] * 255.0) as u8,
- (color_rgb[2] * 255.0) as u8,
- (alpha * 255.0) as u8,
+ (blended_color[0] * 255.0) as u8,
+ (blended_color[1] * 255.0) as u8,
+ (blended_color[2] * 255.0) as u8,
+ (blended_alpha * 255.0) as u8,
)),
));
last_end = word_end;
@@ -734,26 +856,87 @@ pub fn find_caption_at_time(time: f32, segments: &[CaptionSegment]) -> Option<&C
.find(|segment| time >= segment.start && time < segment.end)
}
+pub struct CaptionAtTime {
+ pub segment: CaptionSegment,
+ pub skip_fade_in: bool,
+ pub skip_fade_out: bool,
+}
+
+const CLOSE_TRANSITION_THRESHOLD: f32 = 0.4;
+
+fn convert_project_segment(segment: &cap_project::CaptionSegment) -> CaptionSegment {
+ CaptionSegment {
+ id: segment.id.clone(),
+ start: segment.start,
+ end: segment.end,
+ text: segment.text.clone(),
+ words: segment
+ .words
+ .iter()
+ .map(|w| CaptionWord {
+ text: w.text.clone(),
+ start: w.start,
+ end: w.end,
+ })
+ .collect(),
+ }
+}
+
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(),
- words: segment
- .words
- .iter()
- .map(|w| CaptionWord {
- text: w.text.clone(),
- start: w.start,
- end: w.end,
- })
- .collect(),
- })
+ linger_duration: f32,
+ fade_duration: f32,
+) -> Option<CaptionAtTime> {
+ let extended_end = linger_duration + fade_duration;
+
+ for (idx, segment) in segments.iter().enumerate() {
+ if time >= segment.start && time < segment.end {
+ let prev_segment = if idx > 0 {
+ Some(&segments[idx - 1])
+ } else {
+ None
+ };
+ let next_segment = segments.get(idx + 1);
+
+ let skip_fade_in = prev_segment
+ .map(|prev| segment.start - prev.end < CLOSE_TRANSITION_THRESHOLD)
+ .unwrap_or(false);
+ let skip_fade_out = next_segment
+ .map(|next| next.start - segment.end < CLOSE_TRANSITION_THRESHOLD)
+ .unwrap_or(false);
+
+ return Some(CaptionAtTime {
+ segment: convert_project_segment(segment),
+ skip_fade_in,
+ skip_fade_out,
+ });
+ }
+ }
+
+ for (idx, segment) in segments.iter().enumerate() {
+ if time >= segment.end && time < segment.end + extended_end {
+ let prev_segment = if idx > 0 {
+ Some(&segments[idx - 1])
+ } else {
+ None
+ };
+ let next_segment = segments.get(idx + 1);
+
+ let skip_fade_in = prev_segment
+ .map(|prev| segment.start - prev.end < CLOSE_TRANSITION_THRESHOLD)
+ .unwrap_or(false);
+ let skip_fade_out = next_segment
+ .map(|next| next.start - segment.end < CLOSE_TRANSITION_THRESHOLD)
+ .unwrap_or(false);
+
+ return Some(CaptionAtTime {
+ segment: convert_project_segment(segment),
+ skip_fade_in,
+ skip_fade_out,
+ });
+ }
+ }
+
+ None
}