Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Merge remote-tracking branch 'origin/main' into codex/pr-1949-resolution

Richie McIlroya5551fb4de8e
diff --cc apps/desktop/src-tauri/src/captions.rs
index 722b6b112,e8c397cf1..cd0fd5a02
--- a/apps/desktop/src-tauri/src/captions.rs
+++ b/apps/desktop/src-tauri/src/captions.rs
@@@ -53,13 -54,7 +54,8 @@@ impl Default for CaptionData
lazy_static::lazy_static! {
static ref WHISPER_CONTEXT: Arc<Mutex<Option<Arc<WhisperContext>>>> = Arc::new(Mutex::new(None));
- // std::sync::Mutex so the guard is held by the blocking thread itself.
- // If the async future is dropped mid-transcription the blocking thread
- // continues to hold this lock until it finishes, preventing a racing
- // retry from spawning a second ML session concurrently.
- // On Apple Silicon each WhisperState allocates ~700 MB of Metal (unified)
- // memory; without serialisation rapid re-clicks exhausted 44 GB of RAM.
+ static ref MODEL_DOWNLOADS: Mutex<HashMap<String, ActiveModelDownload>> = Mutex::new(HashMap::new());
+ static ref TRANSCRIPTION_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
}
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
@@@ -634,8 -643,8 +644,14 @@@ async fn extract_audio_from_video(video
}
}
--async fn get_whisper_context(model_path: &str) -> Result<Arc<WhisperContext>, String> {
-- let mut context_guard = WHISPER_CONTEXT.lock().await;
++fn lock_transcription_worker_slot() -> std::sync::MutexGuard<'static, ()> {
++ TRANSCRIPTION_LOCK
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++}
++
++fn get_whisper_context_blocking(model_path: &str) -> Result<Arc<WhisperContext>, String> {
++ let mut context_guard = WHISPER_CONTEXT.blocking_lock();
if let Some(ref existing) = *context_guard {
log::info!("Reusing cached Whisper context");
@@@ -652,6 -661,6 +668,15 @@@
Ok(ctx_arc)
}
++#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
++fn release_whisper_context_after_transcription() {
++ let mut ctx = WHISPER_CONTEXT.blocking_lock();
++ *ctx = None;
++}
++
++#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
++fn release_whisper_context_after_transcription() {}
++
fn is_special_token(token_text: &str) -> bool {
let trimmed = token_text.trim();
if trimmed.is_empty() {
@@@ -1118,25 -1314,22 +1330,14 @@@ pub async fn transcribe_audio
TranscriptionEngine::Parakeet => {
log::info!("Using Parakeet TDT engine");
let model_dir = model_path.clone();
- tokio::task::spawn_blocking(move || process_with_parakeet(&audio_path, &model_dir))
- .await
- .map_err(|e| format!("Parakeet task panicked: {e}"))?
+ tokio::task::spawn_blocking(move || {
- let _guard = TRANSCRIPTION_LOCK.lock().unwrap_or_else(|p| p.into_inner());
++ let _guard = lock_transcription_worker_slot();
+ process_with_parakeet(&audio_path, &model_dir)
+ })
+ .await
+ .map_err(|e| format!("Parakeet task panicked: {e}"))?
}
TranscriptionEngine::Whisper => {
-- let context = match get_whisper_context(&model_path).await {
-- Ok(ctx) => {
-- log::info!("Whisper context ready");
-- ctx
-- }
-- Err(e) => {
-- log::error!("Failed to initialize Whisper context: {e}");
-- return Err(format!("Failed to initialize transcription model: {e}"));
-- }
-- };
--
let transcription_hints = GeneralSettingsStore::get(&app)
.ok()
.flatten()
@@@ -1144,24 -1337,11 +1345,25 @@@
.unwrap_or_default();
log::info!("Starting Whisper transcription in blocking task...");
- let result = tokio::task::spawn_blocking(move || {
- let _guard = TRANSCRIPTION_LOCK.lock().unwrap_or_else(|p| p.into_inner());
- process_with_whisper(&audio_path, context, &language, &transcription_hints)
+ tokio::task::spawn_blocking(move || {
- process_with_whisper(&audio_path, context, &language, &transcription_hints)
++ let _guard = lock_transcription_worker_slot();
++ let context = match get_whisper_context_blocking(&model_path) {
++ Ok(ctx) => {
++ log::info!("Whisper context ready");
++ ctx
++ }
++ Err(e) => {
++ log::error!("Failed to initialize Whisper context: {e}");
++ return Err(format!("Failed to initialize transcription model: {e}"));
++ }
++ };
++ let result =
++ process_with_whisper(&audio_path, context, &language, &transcription_hints);
++ release_whisper_context_after_transcription();
++ result
})
.await
- .map_err(|e| format!("Whisper task panicked: {e}"))?;
-
- // Release the cached context so Metal buffers (~500 MB on Apple Silicon)
- // are freed after each run rather than held until the editor closes.
- // Gated to aarch64 only: on other platforms the cache improves
- // repeated-transcription latency with no meaningful memory cost.
- #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
- {
- let mut ctx = WHISPER_CONTEXT.lock().await;
- *ctx = None;
- }
-
- result
+ .map_err(|e| format!("Whisper task panicked: {e}"))?
}
};
@@@ -1890,9 -2300,129 +2322,129 @@@ async fn parakeet_model_file_sizes
.send()
.await
.map_err(|e| format!("Failed to get size for {filename}: {e}"))?;
- total_size = total_size.saturating_add(resp.content_length().unwrap_or(0));
+
+ if !resp.status().is_success() {
+ return Err(format!(
+ "Failed to get size for {filename}: HTTP {}",
+ resp.status()
+ ));
+ }
+
+ let part_size = resp
+ .content_length()
+ .filter(|size| *size > 0)
- .or_else(|| parakeet_known_part_size(*url))
++ .or_else(|| parakeet_known_part_size(url))
+ .unwrap_or(0);
+ file_size = file_size.saturating_add(part_size);
}
+ sizes.push((*filename, file_size));
}
+ Ok(sizes)
+ }
+
+ fn parakeet_model_files_match(dir: &std::path::Path, expected_files: &[(&str, u64)]) -> bool {
+ expected_files.iter().all(|(filename, expected_size)| {
+ let Ok(metadata) = std::fs::metadata(dir.join(filename)) else {
+ return false;
+ };
+
+ metadata.is_file() && (*expected_size == 0 || metadata.len() == *expected_size)
+ })
+ }
+
+ fn finalize_parakeet_model_download(
+ validated_dir: &std::path::Path,
+ staging_dir: &std::path::Path,
+ model_files: &'static [(&'static str, &'static [&'static str])],
+ ) -> Result<(), String> {
+ std::fs::create_dir_all(validated_dir)
+ .map_err(|e| format!("Failed to create model directory: {e}"))?;
+
+ for filename in PARAKEET_MODEL_CLEANUP_FILES {
+ let file_path = validated_dir.join(filename);
+ if file_path.exists() {
+ let _ = std::fs::remove_file(&file_path);
+ }
+ }
+
+ for (filename, _) in model_files {
+ let src = staging_dir.join(filename);
+ let dst = validated_dir.join(filename);
+ std::fs::rename(&src, &dst)
+ .map_err(|e| format!("Failed to move {filename} to final location: {e}"))?;
+ }
+
+ let _ = std::fs::remove_dir_all(staging_dir);
+
+ Ok(())
+ }
+
+ #[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
+ #[tauri::command]
+ #[specta::specta]
+ #[instrument(skip(app))]
+ pub async fn download_parakeet_model(app: AppHandle, output_dir: String) -> Result<(), String> {
+ let validated_dir = validate_model_path(&app, &output_dir)?;
+ let key = model_download_key(&validated_dir);
+
+ if !begin_model_download(&key, "Preparing model download".to_string()).await {
+ return wait_for_model_download(&key).await;
+ }
+
+ let download_app = app.clone();
+ let download_key = key.clone();
+ tauri::async_runtime::spawn(async move {
+ let result =
+ download_parakeet_model_to_dir(&download_app, &validated_dir, &download_key).await;
+ let final_status = match &result {
+ Ok(_) => model_download_status(
+ ModelDownloadState::Completed,
+ 100.0,
+ "Download complete".to_string(),
+ ),
+ Err(error) => model_download_status(
+ ModelDownloadState::Failed,
+ 0.0,
+ format!("Download failed: {error}"),
+ ),
+ };
+ set_model_download_status(&download_app, &download_key, final_status).await;
+ });
+
+ wait_for_model_download(&key).await
+ }
+
+ #[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
+ async fn download_parakeet_model_to_dir(
+ app: &AppHandle,
+ validated_dir: &Path,
+ download_key: &str,
+ ) -> Result<(), String> {
+ std::fs::create_dir_all(validated_dir)
+ .map_err(|e| format!("Failed to create model directory: {e}"))?;
+
+ let http_client = app.state::<http_client::HttpClient>();
+ let model_files = parakeet_model_files_for_dir(validated_dir);
+ let expected_file_sizes = parakeet_model_file_sizes(&http_client, model_files).await?;
+
+ let staging_dir = parakeet_staging_dir(validated_dir);
+ if parakeet_model_files_match(&staging_dir, &expected_file_sizes) {
+ tracing::info!("Finalizing previously completed Parakeet model download");
+ finalize_parakeet_model_download(validated_dir, &staging_dir, model_files)?;
+ invalidate_parakeet_cache_for_dir(validated_dir).await;
+ return Ok(());
+ }
+
+ if staging_dir.exists() {
+ std::fs::remove_dir_all(&staging_dir)
+ .map_err(|e| format!("Failed to clean staging directory: {e}"))?;
+ }
+ std::fs::create_dir_all(&staging_dir)
+ .map_err(|e| format!("Failed to create staging directory: {e}"))?;
+
+ let total_size = expected_file_sizes
+ .iter()
+ .fold(0_u64, |acc, (_, size)| acc.saturating_add(*size));
let mut downloaded_total: u64 = 0;
diff --cc apps/desktop/src-tauri/src/recording.rs
index 564e8f82e,7270a6505..08bd55a0e
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@@ -47,7 -47,8 +47,8 @@@ use std::
time::Duration,
};
use tauri::{AppHandle, Manager, path::BaseDirectory};
-use tauri_plugin_global_shortcut::GlobalShortcutExt;
use tauri_plugin_dialog::{DialogExt, MessageDialogBuilder};
++use tauri_plugin_global_shortcut::GlobalShortcutExt;
use tauri_specta::Event;
use tracing::*;
@@@ -2697,6 -3011,20 +3011,18 @@@ async fn handle_recording_end
let _ = window.hide();
}
+ // Destroy any target-select overlays that were hidden when recording started
+ // so they don't reappear when the main window comes back.
+ let focus_manager = handle.try_state::<crate::target_select_overlay::WindowFocusManager>();
+ for (label, window) in handle.webview_windows() {
- if let Ok(CapWindowId::TargetSelectOverlay { display_id }) =
- CapWindowId::from_str(&label)
- {
++ if let Ok(CapWindowId::TargetSelectOverlay { display_id }) = CapWindowId::from_str(&label) {
+ hide_overlay(&window);
+ if let Some(ref fm) = focus_manager {
+ fm.destroy(&display_id, handle.global_shortcut());
+ }
+ }
+ }
+
if let Some(camera) = CapWindowId::Camera.get(&handle) {
let _ = camera.hide();
}
diff --cc apps/desktop/src-tauri/src/windows.rs
index f890ee6b2,2d97c446f..51cceb978
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@@ -2251,6 -2365,20 +2365,19 @@@ impl ShowCapWindow
let window = window_builder.build()?;
lock_window_text_scale(&window);
+ #[cfg(target_os = "linux")]
+ if let Some(bounds) = display.raw_handle().physical_bounds() {
+ use tauri::{LogicalSize, PhysicalPosition};
+ let _ = window.set_position(PhysicalPosition::new(
+ bounds.position().x(),
+ bounds.position().y(),
+ ));
+ let _ = window.set_size(LogicalSize::new(
+ bounds.size().width(),
+ bounds.size().height(),
+ ));
+ }
+
-
#[cfg(target_os = "macos")]
crate::platform::set_window_level(
window.as_ref().window(),