Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Implement captions support

Richie McIlroy2dba2de99a96
diff --git a/apps/desktop/src-tauri/src/captions.rs b/apps/desktop/src-tauri/src/captions.rs
index 05678af59..cfb75f914 100644
--- a/apps/desktop/src-tauri/src/captions.rs
+++ b/apps/desktop/src-tauri/src/captions.rs
@@ -18,12 +18,10 @@ use tokio::sync::Mutex;
use tracing::instrument;
use whisper_rs::{FullParams, SamplingStrategy, WhisperContext, WhisperContextParameters};
-// Re-export caption types from cap_project
-pub use cap_project::{CaptionSegment, CaptionSettings};
+pub use cap_project::{CaptionSegment, CaptionSettings, CaptionWord};
use crate::http_client;
-// 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>,
@@ -39,15 +37,12 @@ impl Default for CaptionData {
}
}
-// Model context is shared and cached
lazy_static::lazy_static! {
- static ref WHISPER_CONTEXT: Arc<Mutex<Option<WhisperContext>>> = Arc::new(Mutex::new(None));
+ static ref WHISPER_CONTEXT: Arc<Mutex<Option<Arc<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]
#[instrument]
@@ -55,7 +50,6 @@ 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]
#[instrument]
@@ -63,15 +57,12 @@ 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}"))?;
@@ -79,21 +70,23 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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));
- }
+ let mut push_source = |path: Option<&str>| {
+ if let Some(path) = path {
+ let full_path = base_path.join(path);
+ if !audio_sources.contains(&full_path) {
+ audio_sources.push(full_path);
+ }
+ }
+ };
- // Add microphone audio if available
- if let Some(audio) = segment["audio"]["path"].as_str() {
- audio_sources.push(base_path.join(audio));
- }
+ push_source(segment["system_audio"]["path"].as_str());
+ push_source(segment["mic"]["path"].as_str());
+ push_source(segment["audio"]["path"].as_str());
}
}
@@ -103,7 +96,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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;
@@ -121,7 +113,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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",
@@ -129,24 +120,20 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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());
}
}
@@ -158,7 +145,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
}
}
- // No matter what, ensure we have mono audio for Whisper
if channel_count > 1 {
log::info!("Converting final mixed audio from {channel_count} channels to mono");
mixed_samples = convert_to_mono(&mixed_samples, channel_count);
@@ -169,7 +155,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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}"))?;
@@ -199,7 +184,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
.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,
@@ -210,9 +194,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
)
.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!(
@@ -229,15 +211,12 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
);
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,
@@ -245,7 +224,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
);
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,
@@ -254,7 +232,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
};
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,
@@ -262,7 +239,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
);
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 {
@@ -284,7 +260,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
continue;
}
- // Process each encoded packet
loop {
let mut packet = ffmpeg::Packet::empty();
match encoder.receive_packet(&mut packet) {
@@ -299,12 +274,10 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
}
}
- // 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);
@@ -313,7 +286,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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}"));
@@ -327,7 +299,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
Ok(())
} else {
- // Handle regular video file
let mut input =
avformat::input(&video_path).map_err(|e| format!("Failed to open video file: {e}"))?;
@@ -338,25 +309,20 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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()
@@ -373,11 +339,9 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
.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)
@@ -385,16 +349,13 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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,
@@ -405,7 +366,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
)
.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),
@@ -413,22 +373,15 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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));
}
@@ -441,14 +394,12 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
}
}
- // 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 decoder.receive_frame(&mut decoded_frame).is_ok() {
if let Err(e) = resampler.run(&decoded_frame, &mut resampled_frame) {
log::warn!("Failed to resample audio: {e}");
@@ -460,12 +411,10 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
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) {
@@ -478,7 +427,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
}
}
- // Flush the decoder
decoder
.send_eof()
.map_err(|e| format!("Failed to send EOF to decoder: {e}"))?;
@@ -492,7 +440,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
.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);
@@ -507,7 +454,6 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
}
}
- // Close the output file with trailer
output
.write_trailer()
.map_err(|e| format!("Failed to write trailer: {e}"))?;
@@ -516,24 +462,32 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
}
}
-/// 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);
+ let ctx_arc = Arc::new(ctx);
+ *context_guard = Some(ctx_arc.clone());
- // 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)
+ Ok(ctx_arc)
+}
+
+fn is_special_token(token_text: &str) -> bool {
+ let trimmed = token_text.trim();
+ if trimmed.is_empty() {
+ return true;
+ }
+
+ trimmed.contains('[')
+ || trimmed.contains(']')
+ || trimmed.contains("_TT_")
+ || trimmed.contains("_BEG_")
+ || trimmed.contains("<|")
}
-/// Process audio file with Whisper for transcription
fn process_with_whisper(
audio_path: &PathBuf,
context: Arc<WhisperContext>,
@@ -541,19 +495,16 @@ fn process_with_whisper(
) -> 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
+ params.set_token_timestamps(true);
+ params.set_language(Some(if language == "auto" { "auto" } else { language }));
+ params.set_max_len(i32::MAX);
- // Load audio file
let mut audio_file = File::open(audio_path)
.map_err(|e| format!("Failed to open audio file: {e} at path: {audio_path:?}"))?;
let mut audio_data = Vec::new();
@@ -563,7 +514,6 @@ fn process_with_whisper(
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() {
@@ -574,14 +524,12 @@ fn process_with_whisper(
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: {min_sample}, max: {max_sample}, avg: {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;
@@ -589,7 +537,6 @@ fn process_with_whisper(
}
}
- // Run the transcription
let mut state = context
.create_state()
.map_err(|e| format!("Failed to create Whisper state: {e}"))?;
@@ -598,7 +545,6 @@ fn process_with_whisper(
.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}"))?;
@@ -608,11 +554,10 @@ fn process_with_whisper(
let mut segments = Vec::new();
for i in 0..num_segments {
- let text = state
+ let raw_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}"))?;
@@ -620,27 +565,91 @@ fn process_with_whisper(
.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()
+ raw_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(),
- });
+ let mut words = Vec::new();
+ let num_tokens = state
+ .full_n_tokens(i)
+ .map_err(|e| format!("Failed to get token count: {e}"))?;
+
+ let mut current_word = String::new();
+ let mut word_start: Option<f32> = None;
+ let mut word_end: f32 = start_time;
+
+ for t in 0..num_tokens {
+ let token_text = state.full_get_token_text(i, t).unwrap_or_default();
+
+ if is_special_token(&token_text) {
+ continue;
+ }
+
+ let token_data = state.full_get_token_data(i, t).ok();
+
+ if let Some(data) = token_data {
+ let token_start = (data.t0 as f32) / 100.0;
+ let token_end = (data.t1 as f32) / 100.0;
+
+ if token_text.starts_with(' ') || token_text.starts_with('\n') {
+ if !current_word.is_empty() {
+ if let Some(ws) = word_start {
+ words.push(CaptionWord {
+ text: current_word.trim().to_string(),
+ start: ws,
+ end: word_end,
+ });
+ }
+ }
+ current_word = token_text.trim().to_string();
+ word_start = None;
+ } else {
+ if word_start.is_none() {
+ word_start = Some(token_start);
+ }
+ current_word.push_str(&token_text);
+ }
+ word_end = token_end;
+ }
+ }
+
+ if !current_word.trim().is_empty() {
+ if let Some(ws) = word_start {
+ words.push(CaptionWord {
+ text: current_word.trim().to_string(),
+ start: ws,
+ end: word_end,
+ });
+ }
}
+
+ if words.is_empty() {
+ continue;
+ }
+
+ let segment_text = words
+ .iter()
+ .map(|word| word.text.clone())
+ .collect::<Vec<_>>()
+ .join(" ");
+
+ let segment_start = words.first().map(|word| word.start).unwrap_or(start_time);
+ let segment_end = words.last().map(|word| word.end).unwrap_or(end_time);
+
+ segments.push(CaptionSegment {
+ id: format!("segment-{i}"),
+ start: segment_start,
+ end: segment_end,
+ text: segment_text,
+ words,
+ });
}
log::info!("Successfully processed {} segments", segments.len());
@@ -651,7 +660,6 @@ fn process_with_whisper(
})
}
-/// Function to transcribe audio from a video file using Whisper
#[tauri::command]
#[specta::specta]
#[instrument]
@@ -660,7 +668,6 @@ pub async fn transcribe_audio(
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}"));
}
@@ -669,11 +676,9 @@ pub async fn transcribe_audio(
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) => {
@@ -682,14 +687,12 @@ pub async fn transcribe_audio(
}
}
- // 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) => {
@@ -698,8 +701,15 @@ pub async fn transcribe_audio(
}
};
- // Process with Whisper and handle errors
- match process_with_whisper(&audio_path, context, &language) {
+ let audio_path_clone = audio_path.clone();
+ let language_clone = language.clone();
+ let whisper_result = tokio::task::spawn_blocking(move || {
+ process_with_whisper(&audio_path_clone, context, &language_clone)
+ })
+ .await
+ .map_err(|e| format!("Whisper task panicked: {e}"))?;
+
+ match whisper_result {
Ok(captions) => {
if captions.segments.is_empty() {
log::warn!("No caption segments were generated");
@@ -714,7 +724,6 @@ pub async fn transcribe_audio(
}
}
-/// Function to save caption data to a file
#[tauri::command]
#[specta::specta]
#[instrument(skip(app))]
@@ -739,13 +748,10 @@ pub async fn save_captions(
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
@@ -769,6 +775,18 @@ pub async fn save_captions(
"text".to_string(),
serde_json::Value::String(seg.text.clone()),
);
+ let words_array: Vec<serde_json::Value> = seg
+ .words
+ .iter()
+ .map(|w| {
+ serde_json::json!({
+ "text": w.text,
+ "start": w.start,
+ "end": w.end
+ })
+ })
+ .collect();
+ segment.insert("words".to_string(), serde_json::Value::Array(words_array));
segment
})
.collect::<Vec<_>>(),
@@ -780,7 +798,6 @@ pub async fn save_captions(
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(),
@@ -827,13 +844,22 @@ pub async fn save_captions(
"exportWithSubtitles".to_string(),
serde_json::Value::Bool(settings.export_with_subtitles),
);
+ settings_obj.insert(
+ "highlightColor".to_string(),
+ serde_json::Value::String(settings.highlight_color.clone()),
+ );
+ settings_obj.insert(
+ "fadeDuration".to_string(),
+ serde_json::Value::Number(
+ serde_json::Number::from_f64(settings.fade_duration as f64).unwrap(),
+ ),
+ );
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}")
@@ -848,16 +874,12 @@ pub async fn save_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()),
@@ -865,18 +887,33 @@ pub fn parse_captions_json(json: &str) -> Result<cap_project::CaptionsData, Stri
segment.get("end").and_then(|v| v.as_f64()),
segment.get("text").and_then(|v| v.as_str()),
) {
+ let mut words = Vec::new();
+ if let Some(words_array) = segment.get("words").and_then(|v| v.as_array()) {
+ for word in words_array {
+ if let (Some(w_text), Some(w_start), Some(w_end)) = (
+ word.get("text").and_then(|v| v.as_str()),
+ word.get("start").and_then(|v| v.as_f64()),
+ word.get("end").and_then(|v| v.as_f64()),
+ ) {
+ words.push(cap_project::CaptionWord {
+ text: w_text.to_string(),
+ start: w_start as f32,
+ end: w_end as f32,
+ });
+ }
+ }
+ }
segments.push(cap_project::CaptionSegment {
id: id.to_string(),
start: start as f32,
end: end as f32,
text: text.to_string(),
+ words,
});
}
}
- // 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())
@@ -896,7 +933,6 @@ pub fn parse_captions_json(json: &str) -> Result<cap_project::CaptionsData, Stri
.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"))
@@ -941,6 +977,19 @@ pub fn parse_captions_json(json: &str) -> Result<cap_project::CaptionsData, Stri
.and_then(|v| v.as_bool())
.unwrap_or(false);
+ let highlight_color = settings_obj
+ .get("highlightColor")
+ .or_else(|| settings_obj.get("highlight_color"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("#FFFF00")
+ .to_string();
+
+ let fade_duration = settings_obj
+ .get("fadeDuration")
+ .or_else(|| settings_obj.get("fade_duration"))
+ .and_then(|v| v.as_f64())
+ .unwrap_or(0.15) as f32;
+
cap_project::CaptionSettings {
enabled,
font,
@@ -954,9 +1003,10 @@ pub fn parse_captions_json(json: &str) -> Result<cap_project::CaptionsData, Stri
outline,
outline_color,
export_with_subtitles,
+ highlight_color,
+ fade_duration,
}
} else {
- // Use default settings if none provided
cap_project::CaptionSettings::default()
};
@@ -969,7 +1019,6 @@ pub fn parse_captions_json(json: &str) -> Result<cap_project::CaptionsData, Stri
}
}
-/// Function to load caption data from a file
#[tauri::command]
#[specta::specta]
#[instrument(skip(app))]
@@ -1002,7 +1051,6 @@ pub async fn load_captions(
project_captions.segments.len()
);
- // Create the CaptionData structure
let tauri_captions = CaptionData {
segments: project_captions.segments,
settings: Some(project_captions.settings),
@@ -1017,18 +1065,14 @@ pub async fn load_captions(
}
}
-/// 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);
@@ -1036,7 +1080,6 @@ fn app_captions_dir(app: &AppHandle, video_id: &str) -> Result<PathBuf, String>
Ok(captions_dir)
}
-// Add new type for download progress
#[derive(Debug, Serialize, Type, tauri_specta::Event, Clone)]
pub struct DownloadProgress {
pub progress: f64,
@@ -1047,7 +1090,6 @@ impl DownloadProgress {
const EVENT_NAME: &'static str = "download-progress";
}
-/// Helper function to download a Whisper model from Hugging Face Hub
#[tauri::command]
#[specta::specta]
#[instrument(skip(window))]
@@ -1057,7 +1099,6 @@ pub async fn download_whisper_model(
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",
@@ -1065,10 +1106,9 @@ pub async fn download_whisper_model(
"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
+ _ => "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.bin",
};
- // Create the client and download the model
let response = app
.state::<http_client::HttpClient>()
.get(model_url)
@@ -1083,10 +1123,8 @@ pub async fn download_whisper_model(
));
}
- // 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}"))?;
@@ -1095,15 +1133,13 @@ pub async fn download_whisper_model(
.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
+ const CHUNK_SIZE: usize = 1024 * 1024;
while !bytes.is_empty() {
let chunk_size = std::cmp::min(CHUNK_SIZE, bytes.len());
let chunk = bytes.split_to(chunk_size);
@@ -1114,7 +1150,6 @@ pub async fn download_whisper_model(
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 {
@@ -1132,7 +1167,6 @@ pub async fn download_whisper_model(
.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}"))?;
@@ -1140,7 +1174,6 @@ pub async fn download_whisper_model(
Ok(())
}
-/// Function to check if a model file exists
#[tauri::command]
#[specta::specta]
#[instrument]
@@ -1148,7 +1181,6 @@ 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]
#[instrument]
@@ -1164,15 +1196,12 @@ pub async fn delete_whisper_model(model_path: String) -> Result<(), String> {
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,
@@ -1184,7 +1213,6 @@ fn captions_to_srt(captions: &CaptionData) -> String {
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;
@@ -1193,7 +1221,6 @@ fn format_srt_time(seconds: f64) -> String {
format!("{hours:02}:{minutes:02}:{secs:02},{millis:03}")
}
-/// Export captions to an SRT file
#[tauri::command]
#[specta::specta]
#[instrument(skip(app))]
@@ -1203,7 +1230,6 @@ pub async fn export_captions_srt(
) -> Result<Option<PathBuf>, String> {
tracing::info!("Starting SRT export for video_id: {}", video_id);
- // Load captions
let captions = match load_captions(app.clone(), video_id.clone()).await? {
Some(c) => {
tracing::info!("Found {} caption segments to export", c.segments.len());
@@ -1215,8 +1241,6 @@ pub async fn export_captions_srt(
}
};
- // 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
@@ -1224,16 +1248,13 @@ pub async fn export_captions_srt(
.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);
@@ -1246,7 +1267,6 @@ pub async fn export_captions_srt(
}
}
-// 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();
@@ -1266,11 +1286,9 @@ fn convert_to_mono(samples: &[f32], channels: usize) -> Vec<f32> {
mono_samples
}
-// Helper function to mix two sample arrays together
fn mix_samples(dest: &mut [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/routes/editor/CaptionsTab.tsx b/apps/desktop/src/routes/editor/CaptionsTab.tsx
index d6677d16b..bc1db3a3d 100644
--- a/apps/desktop/src/routes/editor/CaptionsTab.tsx
+++ b/apps/desktop/src/routes/editor/CaptionsTab.tsx
@@ -4,12 +4,22 @@ import { createWritableMemo } from "@solid-primitives/memo";
import { createElementSize } from "@solid-primitives/resize-observer";
import { appLocalDataDir, join } from "@tauri-apps/api/path";
import { exists } from "@tauri-apps/plugin-fs";
-import { batch, createEffect, createSignal, onMount, Show } from "solid-js";
+import { cx } from "cva";
+import {
+ batch,
+ createEffect,
+ createSignal,
+ For,
+ onMount,
+ Show,
+} from "solid-js";
import { createStore } from "solid-js/store";
import toast from "solid-toast";
import { Toggle } from "~/components/Toggle";
import type { CaptionSegment, CaptionSettings } from "~/utils/tauri";
import { commands, events } from "~/utils/tauri";
+import IconLucideCheck from "~icons/lucide/check";
+import IconLucideDownload from "~icons/lucide/download";
import { FPS, useEditorContext } from "./context";
import { TextInput } from "./TextInput";
import {
@@ -23,10 +33,11 @@ import {
topLeftAnimateClasses,
} from "./ui";
-// Model information
interface ModelOption {
name: string;
label: string;
+ size: string;
+ description: string;
}
interface LanguageOption {
@@ -40,11 +51,18 @@ interface FontOption {
}
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" },
+ {
+ name: "small",
+ label: "Small",
+ size: "466MB",
+ description: "Balanced speed/accuracy",
+ },
+ {
+ name: "medium",
+ label: "Medium",
+ size: "1.5GB",
+ description: "Slower, more accurate",
+ },
];
const LANGUAGE_OPTIONS: LanguageOption[] = [
@@ -64,7 +82,21 @@ const LANGUAGE_OPTIONS: LanguageOption[] = [
{ code: "zh", label: "Chinese" },
];
-const DEFAULT_MODEL = "tiny";
+interface PositionOption {
+ value: string;
+ label: string;
+}
+
+const POSITION_OPTIONS: PositionOption[] = [
+ { value: "top-left", label: "Top Left" },
+ { value: "top-center", label: "Top Center" },
+ { value: "top-right", label: "Top Right" },
+ { value: "bottom-left", label: "Bottom Left" },
+ { value: "bottom-center", label: "Bottom Center" },
+ { value: "bottom-right", label: "Bottom Right" },
+];
+
+const DEFAULT_MODEL = "small";
const MODEL_FOLDER = "transcription_models";
// Custom flat button component since we can't import it
@@ -184,21 +216,22 @@ export function CaptionsTab() {
// 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",
+ font: "System Sans-Serif",
size: 24,
color: "#FFFFFF",
backgroundColor: "#000000",
backgroundOpacity: 80,
- position: "bottom",
+ position: "bottom-center",
bold: true,
italic: false,
outline: true,
outlineColor: "#000000",
exportWithSubtitles: false,
+ highlightColor: "#FFFF00",
+ fadeDuration: 0.15,
},
);
@@ -293,22 +326,23 @@ export function CaptionsTab() {
if (!project || !editorInstance) return;
if (!project.captions) {
- // Initialize captions with default settings
setProject("captions", {
segments: [],
settings: {
enabled: false,
- font: "Arial",
+ font: "System Sans-Serif",
size: 24,
color: "#FFFFFF",
backgroundColor: "#000000",
backgroundOpacity: 80,
- position: "bottom",
+ position: "bottom-center",
bold: true,
italic: false,
outline: true,
outlineColor: "#000000",
exportWithSubtitles: false,
+ highlightColor: "#FFFF00",
+ fadeDuration: 0.15,
},
});
}
@@ -344,6 +378,13 @@ export function CaptionsTab() {
setModelExists(await checkModelExists(selectedModel()));
}
+ // Restore previously selected model
+ const savedModel = localStorage.getItem("selectedTranscriptionModel");
+ if (savedModel && MODEL_OPTIONS.some((m) => m.name === savedModel)) {
+ setSelectedModel(savedModel);
+ setModelExists(await checkModelExists(savedModel));
+ }
+
// Check if the video has audio
if (editorInstance && editorInstance.recordings) {
const hasAudioTrack = editorInstance.recordings.segments.some(
@@ -384,6 +425,14 @@ export function CaptionsTab() {
}
});
+ // Save selected model when it changes
+ createEffect(() => {
+ const model = selectedModel();
+ if (model) {
+ localStorage.setItem("selectedTranscriptionModel", model);
+ }
+ });
+
// Effect to update current caption based on playback time
createEffect(() => {
if (!project?.captions?.segments || editorState.playbackTime === undefined)
@@ -606,165 +655,113 @@ export function CaptionsTab() {
<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
+ Transcription 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>
- )}
+ <div class="grid grid-cols-2 gap-3">
+ <For each={MODEL_OPTIONS}>
+ {(model) => {
+ const isDownloaded = () =>
+ downloadedModels().includes(model.name);
+ const isSelected = () =>
+ selectedModel() === model.name;
+
+ return (
+ <button
+ class={cx(
+ "flex flex-col text-left p-3 rounded-lg border transition-all relative",
+ isSelected()
+ ? "border-blue-500 bg-blue-50/50 ring-1 ring-blue-500"
+ : "border-gray-200 hover:border-gray-300 bg-white",
+ )}
+ onClick={() => {
+ setSelectedModel(model.name);
+ }}
+ >
+ <div class="flex items-center justify-between w-full mb-1">
+ <span class="font-medium text-sm">
+ {model.label}
+ </span>
+ <Show when={isDownloaded()}>
+ <div
+ class="text-green-500"
+ title="Downloaded"
+ >
+ <IconLucideCheck class="size-4" />
+ </div>
+ </Show>
+ </div>
+ <span class="text-xs text-gray-500 mb-2">
+ {model.description}
+ </span>
+ <div class="flex items-center justify-between mt-auto">
+ <span class="text-[10px] px-1.5 py-0.5 bg-gray-100 rounded text-gray-500">
+ {model.size}
+ </span>
+ </div>
+ </button>
+ );
+ }}
+ </For>
+ </div>
+ </div>
+
+ <div class="pt-2">
+ <Show
+ when={downloadedModels().includes(selectedModel())}
+ fallback={
+ <div class="space-y-2">
+ <Button
+ class="w-full flex items-center justify-center gap-2"
+ onClick={downloadModel}
+ disabled={isDownloading()}
+ >
+ <Show
+ when={isDownloading()}
+ fallback={
+ <>
+ <IconLucideDownload class="size-4" />
+ Download{" "}
+ {
+ MODEL_OPTIONS.find(
+ (m) => m.name === selectedModel(),
+ )?.label
+ }{" "}
+ Model
+ </>
+ }
+ >
+ Downloading... {Math.round(downloadProgress())}%
+ </Show>
+ </Button>
+ <Show when={isDownloading()}>
+ <div class="w-full bg-gray-100 rounded-full h-1.5 overflow-hidden">
+ <div
+ class="bg-blue-500 h-1.5 rounded-full transition-all duration-300"
+ style={{ width: `${downloadProgress()}%` }}
+ />
+ </div>
+ </Show>
+ </div>
+ }
>
- <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}
+ <Show when={hasAudio()}>
+ <Button
+ onClick={generateCaptions}
+ disabled={isGenerating()}
+ class="w-full"
>
- <MenuItemList<typeof KSelect.Listbox>
- class="max-h-48 overflow-y-auto"
- as={KSelect.Listbox}
- />
- </PopperContent>
- </KSelect.Portal>
- </KSelect>
+ {isGenerating()
+ ? "Generating..."
+ : "Generate Captions"}
+ </Button>
+ </Show>
+ </Show>
</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)}
@@ -818,17 +815,6 @@ export function CaptionsTab() {
</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">
@@ -943,8 +929,8 @@ export function CaptionsTab() {
{/* Position Settings */}
<Field name="Position" icon={<IconCapMessageBubble />}>
<KSelect<string>
- options={["top", "bottom"]}
- value={captionSettings.position || "bottom"}
+ options={POSITION_OPTIONS.map((p) => p.value)}
+ value={captionSettings.position || "bottom-center"}
onChange={(value) => {
if (value === null) return;
updateCaptionSetting("position", value);
@@ -954,8 +940,12 @@ export function CaptionsTab() {
as={KSelect.Item}
item={props.item}
>
- <KSelect.ItemLabel class="flex-1 capitalize">
- {props.item.rawValue}
+ <KSelect.ItemLabel class="flex-1">
+ {
+ POSITION_OPTIONS.find(
+ (p) => p.value === props.item.rawValue,
+ )?.label
+ }
</KSelect.ItemLabel>
</MenuItem>
)}
@@ -963,8 +953,12 @@ export function CaptionsTab() {
<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>
+ {
+ POSITION_OPTIONS.find(
+ (p) => p.value === state.selectedOption(),
+ )?.label
+ }
</span>
)}
</KSelect.Value>
@@ -985,6 +979,38 @@ export function CaptionsTab() {
</KSelect>
</Field>
+ {/* Highlight & Animation */}
+ <Field name="Animation" icon={<IconCapMessageBubble />}>
+ <div class="space-y-3">
+ <div class="flex flex-col gap-2">
+ <span class="text-gray-500 text-sm">Highlight Color</span>
+ <RgbInput
+ value={captionSettings.highlightColor || "#FFFF00"}
+ onChange={(value) =>
+ updateCaptionSetting("highlightColor", value)
+ }
+ />
+ </div>
+ <div class="flex flex-col gap-2">
+ <span class="text-gray-500 text-sm">
+ Fade Duration (seconds)
+ </span>
+ <Slider
+ value={[(captionSettings.fadeDuration || 0.15) * 100]}
+ onChange={(v) =>
+ updateCaptionSetting("fadeDuration", v[0] / 100)
+ }
+ minValue={0}
+ maxValue={50}
+ step={1}
+ />
+ <span class="text-xs text-gray-400 text-right">
+ {(captionSettings.fadeDuration || 0.15).toFixed(2)}s
+ </span>
+ </div>
+ </div>
+ </Field>
+
{/* Style Options */}
<Field name="Style Options" icon={<IconCapMessageBubble />}>
<div class="space-y-3">
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 76ee3cfc2..c273110ad 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -613,6 +613,65 @@ impl MaskSegment {
}
}
+#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct TextSegment {
+ pub start: f64,
+ pub end: f64,
+ #[serde(default = "TextSegment::default_enabled")]
+ pub enabled: bool,
+ #[serde(default = "TextSegment::default_content")]
+ pub content: String,
+ #[serde(default = "TextSegment::default_center")]
+ pub center: XY<f64>,
+ #[serde(default = "TextSegment::default_size")]
+ pub size: XY<f64>,
+ #[serde(default = "TextSegment::default_font_family")]
+ pub font_family: String,
+ #[serde(default = "TextSegment::default_font_size")]
+ pub font_size: f32,
+ #[serde(default = "TextSegment::default_font_weight")]
+ pub font_weight: f32,
+ #[serde(default)]
+ pub italic: bool,
+ #[serde(default = "TextSegment::default_color")]
+ pub color: String,
+}
+
+impl TextSegment {
+ fn default_enabled() -> bool {
+ true
+ }
+
+ fn default_content() -> String {
+ "Text".to_string()
+ }
+
+ fn default_center() -> XY<f64> {
+ XY::new(0.5, 0.5)
+ }
+
+ fn default_size() -> XY<f64> {
+ XY::new(0.35, 0.2)
+ }
+
+ fn default_font_family() -> String {
+ "sans-serif".to_string()
+ }
+
+ fn default_font_size() -> f32 {
+ 48.0
+ }
+
+ fn default_font_weight() -> f32 {
+ 700.0
+ }
+
+ fn default_color() -> String {
+ "#ffffff".to_string()
+ }
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub enum SceneMode {
@@ -640,6 +699,8 @@ pub struct TimelineConfiguration {
pub scene_segments: Vec<SceneSegment>,
#[serde(default)]
pub mask_segments: Vec<MaskSegment>,
+ #[serde(default)]
+ pub text_segments: Vec<TextSegment>,
}
impl TimelineConfiguration {
@@ -666,6 +727,14 @@ impl TimelineConfiguration {
pub const WALLPAPERS_PATH: &str = "assets/backgrounds/macOS";
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptionWord {
+ pub text: String,
+ pub start: f32,
+ pub end: f32,
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct CaptionSegment {
@@ -673,6 +742,20 @@ pub struct CaptionSegment {
pub start: f32,
pub end: f32,
pub text: String,
+ #[serde(default)]
+ pub words: Vec<CaptionWord>,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq)]
+#[serde(rename_all = "kebab-case")]
+pub enum CaptionPosition {
+ TopLeft,
+ TopCenter,
+ TopRight,
+ #[default]
+ BottomLeft,
+ BottomCenter,
+ BottomRight,
}
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
@@ -686,6 +769,7 @@ pub struct CaptionSettings {
pub background_color: String,
#[serde(alias = "backgroundOpacity")]
pub background_opacity: u32,
+ #[serde(default)]
pub position: String,
pub bold: bool,
pub italic: bool,
@@ -694,6 +778,26 @@ pub struct CaptionSettings {
pub outline_color: String,
#[serde(alias = "exportWithSubtitles")]
pub export_with_subtitles: bool,
+ #[serde(
+ alias = "highlightColor",
+ default = "CaptionSettings::default_highlight_color"
+ )]
+ pub highlight_color: String,
+ #[serde(
+ alias = "fadeDuration",
+ default = "CaptionSettings::default_fade_duration"
+ )]
+ pub fade_duration: f32,
+}
+
+impl CaptionSettings {
+ fn default_highlight_color() -> String {
+ "#FFFF00".to_string()
+ }
+
+ fn default_fade_duration() -> f32 {
+ 0.15
+ }
}
impl Default for CaptionSettings {
@@ -705,12 +809,14 @@ impl Default for CaptionSettings {
color: "#FFFFFF".to_string(),
background_color: "#000000".to_string(),
background_opacity: 80,
- position: "bottom".to_string(),
+ position: "bottom-center".to_string(),
bold: true,
italic: false,
outline: true,
outline_color: "#000000".to_string(),
export_with_subtitles: false,
+ highlight_color: Self::default_highlight_color(),
+ fade_duration: Self::default_fade_duration(),
}
}
}
@@ -878,6 +984,8 @@ pub struct ProjectConfiguration {
pub clips: Vec<ClipConfiguration>,
#[serde(default)]
pub annotations: Vec<Annotation>,
+ #[serde(default, skip_serializing)]
+ pub hidden_text_segments: Vec<usize>,
}
fn camera_config_needs_migration(value: &Value) -> bool {
diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rs
index 5e1f6bcb8..fa16fa9ed 100644
--- a/crates/rendering/src/layers/captions.rs
+++ b/crates/rendering/src/layers/captions.rs
@@ -1,38 +1,42 @@
-#![allow(unused)] // TODO: This module is still being implemented
-
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,
+ TextArea, TextAtlas, TextBounds, TextRenderer, Viewport, Weight,
};
-use log::{debug, info, warn};
+use log::{debug, warn};
use wgpu::{Device, Queue, util::DeviceExt};
use crate::{DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants, parse_color_component};
-/// Represents a caption segment with timing and text
+#[derive(Debug, Clone)]
+pub struct CaptionWord {
+ pub text: String,
+ pub start: f32,
+ pub end: f32,
+}
+
#[derive(Debug, Clone)]
pub struct CaptionSegment {
pub id: String,
pub start: f32,
pub end: f32,
pub text: String,
+ pub words: Vec<CaptionWord>,
}
-/// Settings for caption rendering
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable, Debug)]
pub struct CaptionSettings {
- pub enabled: u32, // 0 = disabled, 1 = enabled
+ pub enabled: u32,
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 position: u32,
+ pub outline: u32,
pub outline_color: [f32; 4],
- pub font: u32, // 0 = SansSerif, 1 = Serif, 2 = Monospace
- pub _padding: [f32; 1], // for alignment
+ pub font: u32,
+ pub _padding: [f32; 1],
}
impl Default for CaptionSettings {
@@ -40,18 +44,55 @@ impl Default for CaptionSettings {
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
+ color: [1.0, 1.0, 1.0, 1.0],
+ background_color: [0.0, 0.0, 0.0, 0.8],
+ position: 5,
+ outline: 1,
+ outline_color: [0.0, 0.0, 0.0, 1.0],
+ font: 0,
_padding: [0.0],
}
}
}
-/// Caption layer that renders text using GPU
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum CaptionPosition {
+ TopLeft,
+ TopCenter,
+ TopRight,
+ BottomLeft,
+ BottomCenter,
+ BottomRight,
+}
+
+impl CaptionPosition {
+ fn from_str(s: &str) -> Self {
+ match s {
+ "top-left" => Self::TopLeft,
+ "top-center" | "top" => Self::TopCenter,
+ "top-right" => Self::TopRight,
+ "bottom-left" => Self::BottomLeft,
+ "bottom-right" => Self::BottomRight,
+ _ => Self::BottomCenter,
+ }
+ }
+
+ fn y_factor(&self) -> f32 {
+ match self {
+ Self::TopLeft | Self::TopCenter | Self::TopRight => 0.08,
+ Self::BottomLeft | Self::BottomCenter | Self::BottomRight => 0.85,
+ }
+ }
+
+ fn x_alignment(&self) -> f32 {
+ match self {
+ Self::TopLeft | Self::BottomLeft => 0.05,
+ Self::TopCenter | Self::BottomCenter => 0.5,
+ Self::TopRight | Self::BottomRight => 0.95,
+ }
+ }
+}
+
pub struct CaptionsLayer {
settings_buffer: wgpu::Buffer,
font_system: FontSystem,
@@ -60,13 +101,13 @@ pub struct CaptionsLayer {
text_renderer: TextRenderer,
text_buffer: Buffer,
current_text: Option<String>,
- current_segment_time: f32,
+ current_segment_start: f32,
+ current_segment_end: f32,
viewport: Viewport,
}
impl CaptionsLayer {
pub fn new(device: &Device, queue: &Queue) -> Self {
- // Create default settings buffer
let settings = CaptionSettings::default();
let settings_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Caption Settings Buffer"),
@@ -74,7 +115,6 @@ impl CaptionsLayer {
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
- // Initialize glyphon text rendering components
let font_system = FontSystem::new();
let swash_cache = SwashCache::new();
let cache = Cache::new(device);
@@ -88,8 +128,7 @@ impl CaptionsLayer {
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 metrics = Metrics::new(24.0, 24.0 * 1.2);
let text_buffer = Buffer::new_empty(metrics);
Self {
@@ -100,35 +139,35 @@ impl CaptionsLayer {
text_renderer,
text_buffer,
current_text: None,
- current_segment_time: 0.0,
+ current_segment_start: 0.0,
+ current_segment_end: 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: {text:?}, Time: {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;
+ pub fn update_caption(&mut self, text: Option<String>, start: f32, end: f32) {
+ debug!("Updating caption - Text: {text:?}, Start: {start}, End: {end}");
+ self.current_text = text;
+ self.current_segment_start = start;
+ self.current_segment_end = end;
+ }
+
+ fn calculate_fade_opacity(&self, current_time: f32, fade_duration: f32) -> f32 {
+ if fade_duration <= 0.0 {
+ return 1.0;
}
- self.current_segment_time = time;
+
+ let time_from_start = current_time - self.current_segment_start;
+ let time_to_end = self.current_segment_end - current_time;
+
+ let fade_in = (time_from_start / fade_duration).min(1.0);
+ let fade_out = (time_to_end / fade_duration).min(1.0);
+
+ fade_in.min(fade_out).max(0.0)
}
pub fn prepare(
@@ -138,182 +177,213 @@ impl CaptionsLayer {
output_size: XY<u32>,
constants: &RenderVideoConstants,
) {
- // Render captions if there are any caption segments to display
- if let Some(caption_data) = &uniforms.project.captions
- && caption_data.settings.enabled
- {
- // Find the current caption for this time
+ if let Some(caption_data) = &uniforms.project.captions {
+ if !caption_data.settings.enabled {
+ return;
+ }
+
let current_time = segment_frames.segment_time;
+ let fade_duration = caption_data.settings.fade_duration;
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();
+ let caption_words = current_caption.words.clone();
+ self.update_caption(
+ Some(caption_text.clone()),
+ current_caption.start,
+ current_caption.end,
+ );
- // 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;
- }
+ let fade_opacity = self.calculate_fade_opacity(current_time, fade_duration);
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)
- };
+ let position = CaptionPosition::from_str(&caption_data.settings.position);
+ let y_position = height as f32 * position.y_factor();
- // 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,
- );
+ let base_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),
+ ];
- // 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,
- );
+ let highlight_color_rgb = [
+ parse_color_component(&caption_data.settings.highlight_color, 0),
+ parse_color_component(&caption_data.settings.highlight_color, 1),
+ parse_color_component(&caption_data.settings.highlight_color, 2),
+ ];
+
+ let outline_color_rgb = [
+ 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),
+ ];
+
+ let _bg_opacity =
+ (caption_data.settings.background_opacity as f32 / 100.0) * fade_opacity;
- // 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
+ let font_size = caption_data.settings.size as f32 * (height as f32 / 1080.0);
+ let metrics = Metrics::new(font_size, font_size * 1.2);
- // 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 x_offset = match position.x_alignment() {
+ x if x < 0.3 => (width as f32 * 0.05) as i32,
+ x if x > 0.7 => (width as f32 * 0.05) as i32,
+ _ => ((width as f32 - text_width) / 2.0) as i32,
+ };
+
let bounds = TextBounds {
- left: ((width as f32 - text_width) / 2.0) as i32, // Center the text horizontally
+ left: x_offset,
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
+ right: (x_offset as f32 + text_width) as i32,
+ bottom: (y_position + font_size * 4.0) as i32,
};
- // 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 font_family = match caption_data.settings.font.as_str() {
+ "System Serif" => Family::Serif,
+ "System Monospace" => Family::Monospace,
+ _ => Family::SansSerif,
};
- 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);
+ let weight = if caption_data.settings.bold {
+ Weight::BOLD
+ } else {
+ Weight::NORMAL
+ };
- // Replace the existing buffer
- self.text_buffer = updated_buffer;
+ 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 = text.as_str();
+ let mut last_end = 0usize;
+
+ for (idx, word) in caption_words.iter().enumerate() {
+ if let Some(start_pos) = full_text[last_end..].find(&word.text) {
+ let abs_start = last_end + start_pos;
+
+ if abs_start > last_end {
+ let space = &full_text[last_end..abs_start];
+ rich_text.push((
+ space,
+ Attrs::new().family(font_family).weight(weight).color(
+ Color::rgba(
+ (base_color[0] * 255.0) as u8,
+ (base_color[1] * 255.0) as u8,
+ (base_color[2] * 255.0) as u8,
+ (fade_opacity * 255.0) as u8,
+ ),
+ ),
+ ));
+ }
+
+ let is_current = Some(idx) == current_word_idx;
+ let word_color = if is_current {
+ Color::rgba(
+ (highlight_color_rgb[0] * 255.0) as u8,
+ (highlight_color_rgb[1] * 255.0) as u8,
+ (highlight_color_rgb[2] * 255.0) as u8,
+ (fade_opacity * 255.0) as u8,
+ )
+ } else {
+ Color::rgba(
+ (base_color[0] * 255.0) as u8,
+ (base_color[1] * 255.0) as u8,
+ (base_color[2] * 255.0) as u8,
+ (fade_opacity * 255.0) as u8,
+ )
+ };
+
+ let word_end = abs_start + word.text.len();
+ rich_text.push((
+ &full_text[abs_start..word_end],
+ Attrs::new()
+ .family(font_family)
+ .weight(weight)
+ .color(word_color),
+ ));
+ last_end = word_end;
+ }
+ }
- // Update the viewport with explicit resolution
- self.viewport.update(queue, Resolution { width, height });
+ if last_end < full_text.len() {
+ rich_text.push((
+ &full_text[last_end..],
+ Attrs::new()
+ .family(font_family)
+ .weight(weight)
+ .color(Color::rgba(
+ (base_color[0] * 255.0) as u8,
+ (base_color[1] * 255.0) as u8,
+ (base_color[2] * 255.0) as u8,
+ (fade_opacity * 255.0) as u8,
+ )),
+ ));
+ }
- // 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,
- )
+ updated_buffer.set_rich_text(
+ &mut self.font_system,
+ rich_text,
+ &Attrs::new().family(font_family).weight(weight),
+ Shaping::Advanced,
+ None,
+ );
} else {
- Color::rgba(0, 0, 0, 0)
- };
+ let color = Color::rgba(
+ (base_color[0] * 255.0) as u8,
+ (base_color[1] * 255.0) as u8,
+ (base_color[2] * 255.0) as u8,
+ (fade_opacity * 255.0) as u8,
+ );
+ let attrs = Attrs::new().family(font_family).weight(weight).color(color);
+ updated_buffer.set_text(
+ &mut self.font_system,
+ text,
+ &attrs,
+ Shaping::Advanced,
+ );
+ }
+
+ self.text_buffer = updated_buffer;
+ self.viewport.update(queue, Resolution { width, height });
- // 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: &[],
- });
- }
+ let outline_color = Color::rgba(
+ (outline_color_rgb[0] * 255.0) as u8,
+ (outline_color_rgb[1] * 255.0) as u8,
+ (outline_color_rgb[2] * 255.0) as u8,
+ (fade_opacity * 255.0) as u8,
+ );
- // 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
+ if caption_data.settings.outline {
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),
+ (-1.5, -1.5),
+ (0.0, -1.5),
+ (1.5, -1.5),
+ (-1.5, 0.0),
+ (1.5, 0.0),
+ (-1.5, 1.5),
+ (0.0, 1.5),
+ (1.5, 1.5),
];
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
+ left: bounds.left as f32 + offset_x,
top: y_position + offset_y,
scale: 1.0,
bounds,
@@ -323,18 +393,23 @@ impl CaptionsLayer {
}
}
- // Add main text (rendered last, on top of everything)
+ let default_color = Color::rgba(
+ (base_color[0] * 255.0) as u8,
+ (base_color[1] * 255.0) as u8,
+ (base_color[2] * 255.0) as u8,
+ (fade_opacity * 255.0) as u8,
+ );
+
text_areas.push(TextArea {
buffer: &self.text_buffer,
- left: bounds.left as f32, // Match the bounds left for positioning
+ left: bounds.left as f32,
top: y_position,
scale: 1.0,
bounds,
- default_color: color,
+ default_color,
custom_glyphs: &[],
});
- // Prepare text rendering
match self.text_renderer.prepare(
device,
queue,
@@ -352,7 +427,6 @@ impl CaptionsLayer {
}
}
- /// Render the current caption to the frame
pub fn render<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>) {
match self
.text_renderer
@@ -364,15 +438,12 @@ impl CaptionsLayer {
}
}
-/// 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],
@@ -385,5 +456,14 @@ pub fn find_caption_at_time_project(
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(),
})
}