Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Improve caption logging and rendering features

Richie McIlroyd8c32e049215
diff --git a/apps/desktop/src-tauri/src/captions.rs b/apps/desktop/src-tauri/src/captions.rs
index cfb75f914..53d701d6d 100644
--- a/apps/desktop/src-tauri/src/captions.rs
+++ b/apps/desktop/src-tauri/src/captions.rs
@@ -58,7 +58,9 @@ pub async fn save_model_file(path: String, data: Vec<u8>) -> Result<(), String>
}
async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Result<(), String> {
+ log::info!("=== EXTRACT AUDIO START ===");
log::info!("Attempting to extract audio from: {video_path}");
+ log::info!("Output path: {:?}", output_path);
if video_path.ends_with(".cap") {
log::info!("Detected .cap project directory");
@@ -152,9 +154,22 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
}
if mixed_samples.is_empty() {
+ log::error!("No audio samples after processing all sources");
return Err("Failed to process any audio sources".to_string());
}
+ log::info!("Final mixed audio: {} samples", mixed_samples.len());
+ let mix_rms =
+ (mixed_samples.iter().map(|&s| s * s).sum::<f32>() / mixed_samples.len() as f32).sqrt();
+ log::info!("Mixed audio RMS: {:.4}", mix_rms);
+
+ if mix_rms < 0.001 {
+ log::warn!(
+ "WARNING: Mixed audio RMS is very low ({:.6}) - audio may be nearly silent!",
+ mix_rms
+ );
+ }
+
let mut output = avformat::output(&output_path)
.map_err(|e| format!("Failed to create output file: {e}"))?;
@@ -297,6 +312,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
.write_trailer()
.map_err(|e| format!("Failed to write trailer: {e}"))?;
+ log::info!("=== EXTRACT AUDIO END (from .cap) ===");
Ok(())
} else {
let mut input =
@@ -458,6 +474,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
.write_trailer()
.map_err(|e| format!("Failed to write trailer: {e}"))?;
+ log::info!("=== EXTRACT AUDIO END (from video) ===");
Ok(())
}
}
@@ -465,6 +482,11 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re
async fn get_whisper_context(model_path: &str) -> Result<Arc<WhisperContext>, String> {
let mut context_guard = WHISPER_CONTEXT.lock().await;
+ if let Some(ref existing) = *context_guard {
+ log::info!("Reusing cached Whisper context");
+ return Ok(existing.clone());
+ }
+
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}"))?;
@@ -481,11 +503,17 @@ fn is_special_token(token_text: &str) -> bool {
return true;
}
- trimmed.contains('[')
+ let is_special = trimmed.contains('[')
|| trimmed.contains(']')
|| trimmed.contains("_TT_")
|| trimmed.contains("_BEG_")
- || trimmed.contains("<|")
+ || trimmed.contains("<|");
+
+ if is_special {
+ log::debug!("Filtering special token: {:?}", token_text);
+ }
+
+ is_special
}
fn process_with_whisper(
@@ -493,7 +521,9 @@ fn process_with_whisper(
context: Arc<WhisperContext>,
language: &str,
) -> Result<CaptionData, String> {
+ log::info!("=== WHISPER TRANSCRIPTION START ===");
log::info!("Processing audio file: {audio_path:?}");
+ log::info!("Language setting: {}", language);
let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 });
@@ -505,6 +535,8 @@ fn process_with_whisper(
params.set_language(Some(if language == "auto" { "auto" } else { language }));
params.set_max_len(i32::MAX);
+ log::info!("Whisper params - translate: false, token_timestamps: true, max_len: MAX");
+
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();
@@ -522,18 +554,39 @@ fn process_with_whisper(
}
}
- log::info!("Converted {} samples to f32 format", audio_data_f32.len());
+ let duration_seconds = audio_data_f32.len() as f32 / WHISPER_SAMPLE_RATE as f32;
+ log::info!(
+ "Converted {} samples to f32 format (duration: {:.2}s at {}Hz)",
+ audio_data_f32.len(),
+ duration_seconds,
+ WHISPER_SAMPLE_RATE
+ );
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}");
+ let rms = (audio_data_f32.iter().map(|&s| s * s).sum::<f32>()
+ / audio_data_f32.len() as f32)
+ .sqrt();
+ log::info!(
+ "Audio samples - min: {:.4}, max: {:.4}, avg: {:.6}, RMS: {:.4}",
+ min_sample,
+ max_sample,
+ avg_sample,
+ rms
+ );
- let sample_count = audio_data_f32.len().min(10);
- for i in 0..sample_count {
- let idx = i * audio_data_f32.len() / sample_count;
- log::info!("Sample {}: {}", idx, audio_data_f32[idx]);
+ if rms < 0.001 {
+ log::warn!(
+ "WARNING: Audio RMS is very low ({:.6}) - audio may be nearly silent!",
+ rms
+ );
+ }
+
+ log::info!("First 20 audio samples:");
+ for i in 0..audio_data_f32.len().min(20) {
+ log::info!(" Sample[{}] = {:.6}", i, audio_data_f32[i]);
}
}
@@ -569,7 +622,7 @@ fn process_with_whisper(
let end_time = (end_i64 as f32) / 100.0;
log::info!(
- "Segment {}: start={}, end={}, text='{}'",
+ "=== Segment {}: start={:.2}s, end={:.2}s, raw_text='{}'",
i,
start_time,
end_time,
@@ -581,14 +634,24 @@ fn process_with_whisper(
.full_n_tokens(i)
.map_err(|e| format!("Failed to get token count: {e}"))?;
+ log::info!(" Segment {} has {} tokens", i, num_tokens);
+
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();
+ let token_id = state.full_get_token_id(i, t).unwrap_or(0);
+ let token_prob = state.full_get_token_prob(i, t).unwrap_or(0.0);
if is_special_token(&token_text) {
+ log::debug!(
+ " Token[{}]: id={}, text={:?} -> SKIPPED (special)",
+ t,
+ token_id,
+ token_text
+ );
continue;
}
@@ -598,9 +661,25 @@ fn process_with_whisper(
let token_start = (data.t0 as f32) / 100.0;
let token_end = (data.t1 as f32) / 100.0;
+ log::info!(
+ " Token[{}]: id={}, text={:?}, t0={:.2}s, t1={:.2}s, prob={:.4}",
+ t,
+ token_id,
+ token_text,
+ token_start,
+ token_end,
+ token_prob
+ );
+
if token_text.starts_with(' ') || token_text.starts_with('\n') {
if !current_word.is_empty() {
if let Some(ws) = word_start {
+ log::info!(
+ " -> Completing word: '{}' ({:.2}s - {:.2}s)",
+ current_word.trim(),
+ ws,
+ word_end
+ );
words.push(CaptionWord {
text: current_word.trim().to_string(),
start: ws,
@@ -609,19 +688,39 @@ fn process_with_whisper(
}
}
current_word = token_text.trim().to_string();
- word_start = None;
+ word_start = Some(token_start);
+ log::debug!(
+ " -> Starting new word: '{}' at {:.2}s",
+ current_word,
+ token_start
+ );
} else {
if word_start.is_none() {
word_start = Some(token_start);
+ log::debug!(" -> Word start set to {:.2}s", token_start);
}
current_word.push_str(&token_text);
+ log::debug!(" -> Appending to word: '{}'", current_word);
}
word_end = token_end;
+ } else {
+ log::warn!(
+ " Token[{}]: id={}, text={:?} -> NO TIMING DATA",
+ t,
+ token_id,
+ token_text
+ );
}
}
if !current_word.trim().is_empty() {
if let Some(ws) = word_start {
+ log::info!(
+ " -> Final word: '{}' ({:.2}s - {:.2}s)",
+ current_word.trim(),
+ ws,
+ word_end
+ );
words.push(CaptionWord {
text: current_word.trim().to_string(),
start: ws,
@@ -630,7 +729,19 @@ fn process_with_whisper(
}
}
+ log::info!(" Segment {} produced {} words", i, words.len());
+ for (w_idx, word) in words.iter().enumerate() {
+ log::info!(
+ " Word[{}]: '{}' ({:.2}s - {:.2}s)",
+ w_idx,
+ word.text,
+ word.start,
+ word.end
+ );
+ }
+
if words.is_empty() {
+ log::warn!(" Segment {} has no words, skipping", i);
continue;
}
@@ -652,7 +763,23 @@ fn process_with_whisper(
});
}
- log::info!("Successfully processed {} segments", segments.len());
+ log::info!("=== WHISPER TRANSCRIPTION COMPLETE ===");
+ log::info!("Total segments: {}", segments.len());
+
+ let total_words: usize = segments.iter().map(|s| s.words.len()).sum();
+ log::info!("Total words: {}", total_words);
+
+ log::info!("=== FINAL TRANSCRIPTION SUMMARY ===");
+ for segment in &segments {
+ log::info!(
+ "Segment '{}' ({:.2}s - {:.2}s): {}",
+ segment.id,
+ segment.start,
+ segment.end,
+ segment.text
+ );
+ }
+ log::info!("=== END SUMMARY ===");
Ok(CaptionData {
segments,
@@ -668,16 +795,24 @@ pub async fn transcribe_audio(
model_path: String,
language: String,
) -> Result<CaptionData, String> {
+ log::info!("=== TRANSCRIBE AUDIO COMMAND START ===");
+ log::info!("Video path: {}", video_path);
+ log::info!("Model path: {}", model_path);
+ log::info!("Language: {}", language);
+
if !std::path::Path::new(&video_path).exists() {
+ log::error!("Video file not found at path: {}", video_path);
return Err(format!("Video file not found at path: {video_path}"));
}
if !std::path::Path::new(&model_path).exists() {
+ log::error!("Model file not found at path: {}", model_path);
return Err(format!("Model file not found at path: {model_path}"));
}
let temp_dir = tempdir().map_err(|e| format!("Failed to create temporary directory: {e}"))?;
let audio_path = temp_dir.path().join("audio.wav");
+ log::info!("Temp audio path: {:?}", audio_path);
match extract_audio_from_video(&video_path, &audio_path).await {
Ok(_) => log::info!("Successfully extracted audio to {audio_path:?}"),
@@ -688,13 +823,24 @@ pub async fn transcribe_audio(
}
if !audio_path.exists() {
+ log::error!("Audio file was not created at {:?}", audio_path);
return Err("Failed to create audio file for transcription".to_string());
}
- log::info!("Audio file created at: {audio_path:?}");
+ let audio_metadata = std::fs::metadata(&audio_path).ok();
+ if let Some(meta) = &audio_metadata {
+ log::info!(
+ "Audio file created at: {:?}, size: {} bytes",
+ audio_path,
+ meta.len()
+ );
+ }
let context = match get_whisper_context(&model_path).await {
- Ok(ctx) => ctx,
+ 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}"));
@@ -703,6 +849,7 @@ pub async fn transcribe_audio(
let audio_path_clone = audio_path.clone();
let language_clone = language.clone();
+ log::info!("Starting Whisper transcription in blocking task...");
let whisper_result = tokio::task::spawn_blocking(move || {
process_with_whisper(&audio_path_clone, context, &language_clone)
})
@@ -711,14 +858,32 @@ pub async fn transcribe_audio(
match whisper_result {
Ok(captions) => {
+ log::info!("=== TRANSCRIBE AUDIO RESULT ===");
+ 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");
return Err("No speech detected in the audio".to_string());
}
+
+ log::info!("=== TRANSCRIBE AUDIO COMMAND END (success) ===");
Ok(captions)
}
Err(e) => {
log::error!("Failed to process audio with Whisper: {e}");
+ log::info!("=== TRANSCRIBE AUDIO COMMAND END (error) ===");
Err(format!("Failed to transcribe audio: {e}"))
}
}
@@ -732,7 +897,30 @@ pub async fn save_captions(
video_id: String,
captions: CaptionData,
) -> Result<(), String> {
+ tracing::info!("=== SAVE CAPTIONS START ===");
tracing::info!("Saving captions for video_id: {}", video_id);
+ tracing::info!("Received {} segments to save", captions.segments.len());
+
+ for (idx, segment) in captions.segments.iter().enumerate() {
+ tracing::info!(
+ " Segment[{}] '{}': '{}' ({} words, {:.2}s - {:.2}s)",
+ idx,
+ segment.id,
+ segment.text,
+ segment.words.len(),
+ segment.start,
+ segment.end
+ );
+ for (w_idx, word) in segment.words.iter().enumerate() {
+ tracing::debug!(
+ " Word[{}]: '{}' ({:.2}s - {:.2}s)",
+ w_idx,
+ word.text,
+ word.start,
+ word.end
+ );
+ }
+ }
let captions_dir = app_captions_dir(&app, &video_id)?;
@@ -871,6 +1059,7 @@ pub async fn save_captions(
})?;
tracing::info!("Successfully saved captions");
+ tracing::info!("=== SAVE CAPTIONS END ===");
Ok(())
}
@@ -1026,11 +1215,15 @@ pub async fn load_captions(
app: AppHandle,
video_id: String,
) -> Result<Option<CaptionData>, String> {
+ tracing::info!("=== LOAD CAPTIONS START ===");
+ tracing::info!("Loading captions for video_id: {}", video_id);
+
let captions_dir = app_captions_dir(&app, &video_id)?;
let captions_path = captions_dir.join("captions.json");
if !captions_path.exists() {
tracing::info!("No captions file found at: {:?}", captions_path);
+ tracing::info!("=== LOAD CAPTIONS END (no file) ===");
return Ok(None);
}
@@ -1043,6 +1236,8 @@ pub async fn load_captions(
}
};
+ tracing::info!("Captions JSON length: {} bytes", json.len());
+
tracing::info!("Parsing captions JSON");
match parse_captions_json(&json) {
Ok(project_captions) => {
@@ -1051,15 +1246,29 @@ pub async fn load_captions(
project_captions.segments.len()
);
+ for (idx, segment) in project_captions.segments.iter().enumerate() {
+ tracing::info!(
+ " Loaded Segment[{}] '{}': '{}' ({} words, {:.2}s - {:.2}s)",
+ idx,
+ segment.id,
+ segment.text,
+ segment.words.len(),
+ segment.start,
+ segment.end
+ );
+ }
+
let tauri_captions = CaptionData {
segments: project_captions.segments,
settings: Some(project_captions.settings),
};
+ tracing::info!("=== LOAD CAPTIONS END (success) ===");
Ok(Some(tauri_captions))
}
Err(e) => {
tracing::error!("Failed to parse captions: {}", e);
+ tracing::info!("=== LOAD CAPTIONS END (error) ===");
Err(format!("Failed to parse captions: {e}"))
}
}
diff --git a/apps/desktop/src/routes/editor/CaptionsTab.tsx b/apps/desktop/src/routes/editor/CaptionsTab.tsx
index bc1db3a3d..12e474576 100644
--- a/apps/desktop/src/routes/editor/CaptionsTab.tsx
+++ b/apps/desktop/src/routes/editor/CaptionsTab.tsx
@@ -125,6 +125,23 @@ const fontOptions = [
{ value: "System Monospace", label: "System Monospace" },
];
+const defaultCaptionSettings: CaptionSettings = {
+ enabled: false,
+ font: "System Sans-Serif",
+ size: 24,
+ color: "#FFFFFF",
+ backgroundColor: "#000000",
+ backgroundOpacity: 90,
+ position: "bottom-center",
+ bold: true,
+ italic: false,
+ outline: true,
+ outlineColor: "#000000",
+ exportWithSubtitles: false,
+ highlightColor: "#FFFF00",
+ fadeDuration: 0.15,
+};
+
// Add type definitions at the top
interface CaptionsResponse {
segments: CaptionSegment[];
@@ -217,22 +234,9 @@ export function CaptionsTab() {
const size = createElementSize(() => scrollContainerRef);
const [captionSettings, setCaptionSettings] = createStore(
- project?.captions?.settings || {
- enabled: false,
- font: "System Sans-Serif",
- size: 24,
- color: "#FFFFFF",
- backgroundColor: "#000000",
- backgroundOpacity: 80,
- position: "bottom-center",
- bold: true,
- italic: false,
- outline: true,
- outlineColor: "#000000",
- exportWithSubtitles: false,
- highlightColor: "#FFFF00",
- fadeDuration: 0.15,
- },
+ project?.captions?.settings
+ ? { ...defaultCaptionSettings, ...project.captions.settings }
+ : { ...defaultCaptionSettings },
);
// Sync caption settings with project and update player
@@ -328,22 +332,7 @@ export function CaptionsTab() {
if (!project.captions) {
setProject("captions", {
segments: [],
- settings: {
- enabled: false,
- font: "System Sans-Serif",
- size: 24,
- color: "#FFFFFF",
- backgroundColor: "#000000",
- backgroundOpacity: 80,
- position: "bottom-center",
- bold: true,
- italic: false,
- outline: true,
- outlineColor: "#000000",
- exportWithSubtitles: false,
- highlightColor: "#FFFF00",
- fadeDuration: 0.15,
- },
+ settings: { ...defaultCaptionSettings },
});
}
});
@@ -914,7 +903,7 @@ export function CaptionsTab() {
Background Opacity
</span>
<Slider
- value={[captionSettings.backgroundOpacity || 80]}
+ value={[captionSettings.backgroundOpacity ?? 90]}
onChange={(v) =>
updateCaptionSetting("backgroundOpacity", v[0])
}
diff --git a/apps/desktop/src/store/captions.ts b/apps/desktop/src/store/captions.ts
index 14fa50ff6..d57ded241 100644
--- a/apps/desktop/src/store/captions.ts
+++ b/apps/desktop/src/store/captions.ts
@@ -1,28 +1,10 @@
import { createEffect, createRoot } from "solid-js";
import { createStore } from "solid-js/store";
-import { type CaptionSegment, commands } from "~/utils/tauri";
-
-// export type CaptionSegment = {
-// id: string;
-// start: number;
-// end: number;
-// text: string;
-// };
-
-export type CaptionSettings = {
- enabled: boolean;
- font: string;
- size: number;
- color: string;
- backgroundColor: string;
- backgroundOpacity: number;
- position: string;
- bold: boolean;
- italic: boolean;
- outline: boolean;
- outlineColor: string;
- exportWithSubtitles: boolean;
-};
+import {
+ type CaptionSegment,
+ type CaptionSettings,
+ commands,
+} from "~/utils/tauri";
export type CaptionsState = {
segments: CaptionSegment[];
@@ -30,23 +12,27 @@ export type CaptionsState = {
currentCaption: string | null;
};
+const defaultCaptionSettings: CaptionSettings = {
+ enabled: false,
+ font: "System Sans-Serif",
+ size: 24,
+ color: "#FFFFFF",
+ backgroundColor: "#000000",
+ backgroundOpacity: 90,
+ position: "bottom-center",
+ bold: true,
+ italic: false,
+ outline: true,
+ outlineColor: "#000000",
+ exportWithSubtitles: false,
+ highlightColor: "#FFFFFF",
+ fadeDuration: 0.15,
+};
+
function createCaptionsStore() {
const [state, setState] = createStore<CaptionsState>({
segments: [],
- settings: {
- enabled: false,
- font: "System Sans-Serif",
- size: 24,
- color: "#FFFFFF",
- backgroundColor: "#000000",
- backgroundOpacity: 80,
- position: "bottom",
- bold: true,
- italic: false,
- outline: true,
- outlineColor: "#000000",
- exportWithSubtitles: false,
- },
+ settings: { ...defaultCaptionSettings },
currentCaption: null,
});
@@ -103,23 +89,13 @@ function createCaptionsStore() {
try {
const captionsData = await commands.loadCaptions(videoPath);
if (captionsData) {
+ const loadedSettings = captionsData.settings
+ ? { ...defaultCaptionSettings, ...captionsData.settings }
+ : { ...defaultCaptionSettings, enabled: true };
setState((prev) => ({
...prev,
segments: captionsData.segments,
- settings: captionsData.settings || {
- enabled: true,
- font: "Arial",
- size: 24,
- color: "#FFFFFF",
- backgroundColor: "#000000",
- backgroundOpacity: 80,
- position: "bottom",
- bold: true,
- italic: false,
- outline: true,
- outlineColor: "#000000",
- exportWithSubtitles: false,
- },
+ settings: loadedSettings,
}));
}
@@ -132,7 +108,10 @@ function createCaptionsStore() {
setState("segments", localCaptionsData.segments);
}
if (localCaptionsData.settings) {
- setState("settings", localCaptionsData.settings);
+ setState("settings", {
+ ...defaultCaptionSettings,
+ ...localCaptionsData.settings,
+ });
}
} catch (e) {
console.error("Error loading saved captions from localStorage:", e);
@@ -160,6 +139,8 @@ function createCaptionsStore() {
outline: state.settings.outline,
outlineColor: state.settings.outlineColor,
exportWithSubtitles: state.settings.exportWithSubtitles,
+ highlightColor: state.settings.highlightColor,
+ fadeDuration: state.settings.fadeDuration,
},
};
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index c273110ad..289401aec 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -792,7 +792,7 @@ pub struct CaptionSettings {
impl CaptionSettings {
fn default_highlight_color() -> String {
- "#FFFF00".to_string()
+ "#FFFFFF".to_string()
}
fn default_fade_duration() -> f32 {
@@ -808,7 +808,7 @@ impl Default for CaptionSettings {
size: 24,
color: "#FFFFFF".to_string(),
background_color: "#000000".to_string(),
- background_opacity: 80,
+ background_opacity: 90,
position: "bottom-center".to_string(),
bold: true,
italic: false,
diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rs
index fa16fa9ed..67831ae2c 100644
--- a/crates/rendering/src/layers/captions.rs
+++ b/crates/rendering/src/layers/captions.rs
@@ -1,11 +1,12 @@
use bytemuck::{Pod, Zeroable};
use cap_project::XY;
+use glyphon::cosmic_text::LayoutRunIter;
use glyphon::{
Attrs, Buffer, Cache, Color, Family, FontSystem, Metrics, Resolution, Shaping, SwashCache,
TextArea, TextAtlas, TextBounds, TextRenderer, Viewport, Weight,
};
use log::{debug, warn};
-use wgpu::{Device, Queue, util::DeviceExt};
+use wgpu::{Device, Queue, include_wgsl, util::DeviceExt};
use crate::{DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants, parse_color_component};
@@ -45,7 +46,7 @@ impl Default for CaptionSettings {
enabled: 1,
font_size: 24.0,
color: [1.0, 1.0, 1.0, 1.0],
- background_color: [0.0, 0.0, 0.0, 0.8],
+ background_color: [0.0, 0.0, 0.0, 0.9],
position: 5,
outline: 1,
outline_color: [0.0, 0.0, 0.0, 1.0],
@@ -55,6 +56,16 @@ impl Default for CaptionSettings {
}
}
+#[repr(C)]
+#[derive(Copy, Clone, Pod, Zeroable, Debug)]
+struct CaptionBackgroundUniforms {
+ rect: [f32; 4],
+ color: [f32; 4],
+ radius: f32,
+ _padding: [f32; 3],
+ _padding2: [f32; 4],
+}
+
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CaptionPosition {
TopLeft,
@@ -93,6 +104,51 @@ impl CaptionPosition {
}
}
+const BASE_TEXT_OPACITY: f32 = 0.8;
+const MAX_WORDS_PER_LINE: usize = 6;
+const BOUNCE_OFFSET_PIXELS: f32 = 8.0;
+
+fn wrap_text_by_words(text: &str, max_words: usize) -> String {
+ let words: Vec<&str> = text.split_whitespace().collect();
+ if words.is_empty() {
+ return String::new();
+ }
+
+ let mut result = String::new();
+ for (i, word) in words.iter().enumerate() {
+ if i > 0 {
+ if i % max_words == 0 {
+ result.push('\n');
+ } else {
+ result.push(' ');
+ }
+ }
+ result.push_str(word);
+ }
+ result
+}
+
+fn calculate_bounce_offset(_fade_opacity: f32, time_from_start: f32, time_to_end: f32, fade_duration: f32) -> f32 {
+ if fade_duration <= 0.0 {
+ return 0.0;
+ }
+
+ 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 {
+ let ease = 1.0 - fade_in_progress;
+ let bounce = ease * ease;
+ -bounce * BOUNCE_OFFSET_PIXELS
+ } else if fade_out_progress < 1.0 {
+ let ease = 1.0 - fade_out_progress;
+ let bounce = ease * ease;
+ bounce * BOUNCE_OFFSET_PIXELS
+ } else {
+ 0.0
+ }
+}
+
pub struct CaptionsLayer {
settings_buffer: wgpu::Buffer,
font_system: FontSystem,
@@ -104,6 +160,12 @@ pub struct CaptionsLayer {
current_segment_start: f32,
current_segment_end: f32,
viewport: Viewport,
+ background_pipeline: wgpu::RenderPipeline,
+ background_bind_group: wgpu::BindGroup,
+ background_uniform_buffer: wgpu::Buffer,
+ background_scissor: Option<[u32; 4]>,
+ output_size: (u32, u32),
+ has_caption: bool,
}
impl CaptionsLayer {
@@ -131,6 +193,84 @@ impl CaptionsLayer {
let metrics = Metrics::new(24.0, 24.0 * 1.2);
let text_buffer = Buffer::new_empty(metrics);
+ let background_uniforms = CaptionBackgroundUniforms {
+ rect: [0.0; 4],
+ color: [0.0; 4],
+ radius: 0.0,
+ _padding: [0.0; 3],
+ _padding2: [0.0; 4],
+ };
+
+ let background_uniform_buffer =
+ device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Caption Background Uniform Buffer"),
+ contents: bytemuck::bytes_of(&background_uniforms),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ });
+
+ let background_bind_group_layout =
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Caption Background Bind Group Layout"),
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }],
+ });
+
+ let background_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Caption Background Bind Group"),
+ layout: &background_bind_group_layout,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: background_uniform_buffer.as_entire_binding(),
+ }],
+ });
+
+ let background_shader =
+ device.create_shader_module(include_wgsl!("../shaders/caption_bg.wgsl"));
+
+ let background_pipeline_layout =
+ device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Caption Background Pipeline Layout"),
+ bind_group_layouts: &[&background_bind_group_layout],
+ push_constant_ranges: &[],
+ });
+
+ let background_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Caption Background Pipeline"),
+ layout: Some(&background_pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &background_shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &background_shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview: None,
+ cache: None,
+ });
+
Self {
settings_buffer,
font_system,
@@ -142,6 +282,12 @@ impl CaptionsLayer {
current_segment_start: 0.0,
current_segment_end: 0.0,
viewport,
+ background_pipeline,
+ background_bind_group,
+ background_uniform_buffer,
+ background_scissor: None,
+ output_size: (0, 0),
+ has_caption: false,
}
}
@@ -156,18 +302,18 @@ impl CaptionsLayer {
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;
- }
-
+ fn calculate_fade_opacity(&self, current_time: f32, fade_duration: f32) -> (f32, f32, f32) {
let time_from_start = current_time - self.current_segment_start;
let time_to_end = self.current_segment_end - current_time;
+
+ if fade_duration <= 0.0 {
+ 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);
- fade_in.min(fade_out).max(0.0)
+ (fade_in.min(fade_out).max(0.0), time_from_start, time_to_end)
}
pub fn prepare(
@@ -177,257 +323,377 @@ impl CaptionsLayer {
output_size: XY<u32>,
constants: &RenderVideoConstants,
) {
- if let Some(caption_data) = &uniforms.project.captions {
- if !caption_data.settings.enabled {
- return;
- }
+ self.has_caption = false;
+ self.background_scissor = None;
+ self.output_size = (output_size.x, output_size.y);
+
+ let Some(caption_data) = &uniforms.project.captions else {
+ self.current_text = None;
+ return;
+ };
+
+ if !caption_data.settings.enabled {
+ self.current_text = None;
+ 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)
- {
- 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,
- );
-
- 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);
- let device = &constants.device;
- let queue = &constants.queue;
-
- let position = CaptionPosition::from_str(&caption_data.settings.position);
- let y_position = height as f32 * position.y_factor();
-
- 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),
- ];
-
- 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;
-
- let font_size = caption_data.settings.size as f32 * (height as f32 / 1080.0);
- let metrics = Metrics::new(font_size, font_size * 1.2);
-
- let mut updated_buffer = Buffer::new(&mut self.font_system, metrics);
-
- 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);
-
- 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 current_time = segment_frames.segment_time;
+ let fade_duration = caption_data.settings.fade_duration;
- let bounds = TextBounds {
- left: x_offset,
- top: y_position as i32,
- right: (x_offset as f32 + text_width) as i32,
- bottom: (y_position + font_size * 4.0) as i32,
- };
+ let Some(current_caption) =
+ find_caption_at_time_project(current_time, &caption_data.segments)
+ else {
+ self.current_text = None;
+ return;
+ };
- let font_family = match caption_data.settings.font.as_str() {
- "System Serif" => Family::Serif,
- "System Monospace" => Family::Monospace,
- _ => Family::SansSerif,
- };
+ self.update_caption(
+ Some(current_caption.text.clone()),
+ current_caption.start,
+ current_caption.end,
+ );
- let weight = if caption_data.settings.bold {
- Weight::BOLD
+ 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);
+ 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 (width, height) = (output_size.x, output_size.y);
+ let device = &constants.device;
+ let queue = &constants.queue;
+
+ let position = CaptionPosition::from_str(&caption_data.settings.position);
+ let margin = width as f32 * 0.05;
+
+ 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),
+ ];
+
+ 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 background_color_rgb = [
+ 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),
+ ];
+
+ let background_alpha = ((caption_data.settings.background_opacity as f32 / 100.0)
+ * fade_opacity)
+ .clamp(0.0, 1.0);
+
+ let font_size = caption_data.settings.size as f32 * (height as f32 / 1080.0);
+ let metrics = Metrics::new(font_size, font_size * 1.2);
+
+ let mut updated_buffer = Buffer::new(&mut self.font_system, metrics);
+ let wrap_width = (width as f32 - margin * 2.0).max(font_size);
+ updated_buffer.set_size(&mut self.font_system, Some(wrap_width), None);
+ updated_buffer.set_wrap(&mut self.font_system, glyphon::Wrap::Word);
+
+ let font_family = match caption_data.settings.font.as_str() {
+ "System Serif" => Family::Serif,
+ "System Monospace" => Family::Monospace,
+ _ => Family::SansSerif,
+ };
+
+ let weight = if caption_data.settings.bold {
+ Weight::BOLD
+ } else {
+ Weight::NORMAL
+ };
+
+ let base_alpha = (fade_opacity * BASE_TEXT_OPACITY).clamp(0.0, 1.0);
+ 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;
+
+ 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,
+ (base_alpha * 255.0) as u8,
+ )),
+ ));
+ }
+
+ let is_current = Some(idx) == current_word_idx;
+ let alpha = if is_current {
+ highlight_alpha
} else {
- Weight::NORMAL
+ base_alpha
};
- 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;
- }
- }
-
- 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,
- )),
- ));
- }
-
- updated_buffer.set_rich_text(
- &mut self.font_system,
- rich_text,
- &Attrs::new().family(font_family).weight(weight),
- Shaping::Advanced,
- None,
- );
+ let color_rgb = if is_current {
+ highlight_color_rgb
} else {
- let color = Color::rgba(
+ base_color
+ };
+
+ 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(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,
+ )),
+ ));
+ last_end = word_end;
+ }
+ }
+
+ 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,
- );
- let attrs = Attrs::new().family(font_family).weight(weight).color(color);
- updated_buffer.set_text(
- &mut self.font_system,
- text,
- &attrs,
- Shaping::Advanced,
- );
- }
+ (base_alpha * 255.0) as u8,
+ )),
+ ));
+ }
- self.text_buffer = updated_buffer;
- self.viewport.update(queue, Resolution { width, height });
-
- let mut text_areas = Vec::new();
-
- 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,
- );
-
- if caption_data.settings.outline {
- let outline_offsets = [
- (-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,
- top: y_position + offset_y,
- scale: 1.0,
- bounds,
- default_color: outline_color,
- custom_glyphs: &[],
- });
- }
- }
+ updated_buffer.set_rich_text(
+ &mut self.font_system,
+ rich_text,
+ &Attrs::new().family(font_family).weight(weight),
+ Shaping::Advanced,
+ None,
+ );
+ } else {
+ 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,
+ (base_alpha * 255.0) as u8,
+ );
+ let attrs = Attrs::new().family(font_family).weight(weight).color(color);
+ updated_buffer.set_text(
+ &mut self.font_system,
+ caption_text.as_str(),
+ &attrs,
+ Shaping::Advanced,
+ );
+ }
- 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,
- top: y_position,
- scale: 1.0,
- bounds,
- default_color,
- custom_glyphs: &[],
- });
-
- match self.text_renderer.prepare(
- device,
- queue,
- &mut self.font_system,
- &mut self.text_atlas,
- &self.viewport,
- text_areas,
- &mut self.swash_cache,
- ) {
- Ok(_) => {}
- Err(e) => warn!("Error preparing text: {e:?}"),
- }
- }
+ let mut layout_width: f32 = 0.0;
+ let mut layout_height: f32 = 0.0;
+ for run in LayoutRunIter::new(&updated_buffer) {
+ layout_width = layout_width.max(run.line_w);
+ layout_height = layout_height.max(run.line_top + run.line_height);
+ }
+
+ if layout_height == 0.0 {
+ layout_height = font_size * 1.2;
+ layout_width = layout_width.max(font_size);
+ }
+
+ let available_width = (width as f32 - margin * 2.0).max(1.0);
+ let padding = font_size * 0.4;
+ let corner_radius = font_size * 0.45;
+ let text_width = layout_width.min(available_width);
+ let text_height = layout_height;
+ let box_width = (text_width + padding * 2.0).min(available_width).max(1.0);
+ let box_height = (text_height + padding * 2.0).min(height as f32).max(1.0);
+
+ let background_left = match position {
+ CaptionPosition::TopLeft | CaptionPosition::BottomLeft => margin,
+ CaptionPosition::TopRight | CaptionPosition::BottomRight => {
+ (width as f32 - margin - box_width).max(0.0)
}
+ _ => ((width as f32 - box_width) / 2.0).max(0.0),
+ };
+
+ let center_y = height as f32 * position.y_factor();
+ let base_background_top =
+ (center_y - box_height / 2.0).clamp(0.0, (height as f32 - box_height).max(0.0));
+ let background_top = (base_background_top + bounce_offset).clamp(0.0, (height as f32 - box_height).max(0.0));
+
+ let text_left = background_left + padding;
+ let text_top = background_top + padding;
+
+ let bounds = TextBounds {
+ left: text_left.floor() as i32,
+ top: text_top.floor() as i32,
+ right: (text_left + text_width).ceil() as i32,
+ bottom: (text_top + text_height).ceil() as i32,
+ };
+
+ self.text_buffer = updated_buffer;
+ self.viewport.update(queue, Resolution { width, height });
+
+ let mut text_areas = Vec::new();
+
+ 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,
+ );
+
+ if caption_data.settings.outline {
+ let outline_offsets = [
+ (-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: text_left + offset_x,
+ top: text_top + offset_y,
+ scale: 1.0,
+ bounds,
+ default_color: outline_color,
+ custom_glyphs: &[],
+ });
+ }
+ }
+
+ 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,
+ (base_alpha * 255.0) as u8,
+ );
+
+ text_areas.push(TextArea {
+ buffer: &self.text_buffer,
+ left: text_left,
+ top: text_top,
+ scale: 1.0,
+ bounds,
+ default_color,
+ custom_glyphs: &[],
+ });
+
+ match self.text_renderer.prepare(
+ device,
+ queue,
+ &mut self.font_system,
+ &mut self.text_atlas,
+ &self.viewport,
+ text_areas,
+ &mut self.swash_cache,
+ ) {
+ Ok(_) => {}
+ Err(e) => warn!("Error preparing text: {e:?}"),
+ }
+
+ let rect = CaptionBackgroundUniforms {
+ rect: [
+ background_left.max(0.0),
+ background_top.max(0.0),
+ box_width,
+ box_height,
+ ],
+ color: [
+ background_color_rgb[0],
+ background_color_rgb[1],
+ background_color_rgb[2],
+ background_alpha,
+ ],
+ radius: corner_radius.min(box_width / 2.0).min(box_height / 2.0),
+ _padding: [0.0; 3],
+ _padding2: [0.0; 4],
+ };
+
+ queue.write_buffer(
+ &self.background_uniform_buffer,
+ 0,
+ bytemuck::bytes_of(&rect),
+ );
+
+ let scissor_x = background_left.max(0.0).floor() as u32;
+ let scissor_y = background_top.max(0.0).floor() as u32;
+ let max_width = width.saturating_sub(scissor_x);
+ let max_height = height.saturating_sub(scissor_y);
+
+ if max_width == 0 || max_height == 0 {
+ self.has_caption = false;
+ return;
+ }
+
+ let scissor_width = box_width.ceil().max(1.0).min(max_width as f32) as u32;
+ let scissor_height = box_height.ceil().max(1.0).min(max_height as f32) as u32;
+
+ if scissor_width == 0 || scissor_height == 0 {
+ self.has_caption = false;
+ return;
}
+
+ self.background_scissor = Some([scissor_x, scissor_y, scissor_width, scissor_height]);
+ self.has_caption = true;
+ }
+
+ pub fn has_content(&self) -> bool {
+ self.has_caption
}
pub fn render<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>) {
+ if !self.has_caption {
+ return;
+ }
+
+ if let Some([x, y, width, height]) = self.background_scissor {
+ pass.set_scissor_rect(x, y, width, height);
+ pass.set_pipeline(&self.background_pipeline);
+ pass.set_bind_group(0, &self.background_bind_group, &[]);
+ pass.draw(0..6, 0..1);
+ pass.set_scissor_rect(x, y, width, height);
+ } else if self.output_size.0 > 0 && self.output_size.1 > 0 {
+ pass.set_scissor_rect(0, 0, self.output_size.0, self.output_size.1);
+ }
+
match self
.text_renderer
.render(&self.text_atlas, &self.viewport, pass)
@@ -435,6 +701,10 @@ impl CaptionsLayer {
Ok(_) => {}
Err(e) => warn!("Error rendering text: {e:?}"),
}
+
+ if self.output_size.0 > 0 && self.output_size.1 > 0 {
+ pass.set_scissor_rect(0, 0, self.output_size.0, self.output_size.1);
+ }
}
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index b1cf3cb30..756ba5bc4 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1572,7 +1572,6 @@ pub struct RendererLayers {
camera_only: CameraLayer,
mask: MaskLayer,
text: TextLayer,
- #[allow(unused)]
captions: CaptionsLayer,
}
@@ -1658,6 +1657,13 @@ impl RendererLayers {
&uniforms.texts,
);
+ self.captions.prepare(
+ uniforms,
+ segment_frames,
+ XY::new(uniforms.output_size.0, uniforms.output_size.1),
+ constants,
+ );
+
Ok(())
}
@@ -1738,6 +1744,11 @@ impl RendererLayers {
let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
self.text.render(&mut pass);
}
+
+ if self.captions.has_content() {
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ self.captions.render(&mut pass);
+ }
}
}
diff --git a/crates/rendering/src/shaders/caption_bg.wgsl b/crates/rendering/src/shaders/caption_bg.wgsl
new file mode 100644
index 000000000..a34504967
--- /dev/null
+++ b/crates/rendering/src/shaders/caption_bg.wgsl
@@ -0,0 +1,45 @@
+struct BackgroundUniforms {
+ rect: vec4<f32>,
+ color: vec4<f32>,
+ radius: f32,
+ _padding: vec3<f32>,
+};
+
+@group(0) @binding(0) var<uniform> uniforms: BackgroundUniforms;
+
+struct VertexOutput {
+ @builtin(position) position: vec4<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
+ var positions = array<vec2<f32>, 6>(
+ vec2<f32>(-1.0, -1.0),
+ vec2<f32>(1.0, -1.0),
+ vec2<f32>(-1.0, 1.0),
+ vec2<f32>(-1.0, 1.0),
+ vec2<f32>(1.0, -1.0),
+ vec2<f32>(1.0, 1.0),
+ );
+
+ var output: VertexOutput;
+ output.position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
+ return output;
+}
+
+@fragment
+fn fs_main(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
+ let rect_min = uniforms.rect.xy;
+ let rect_size = uniforms.rect.zw;
+ let rect_center = rect_min + rect_size * 0.5;
+ let radius = uniforms.radius;
+ let half_size = rect_size * 0.5;
+
+ let local = position.xy - rect_center;
+ let dist = abs(local) - (half_size - vec2<f32>(radius, radius));
+ let outside = max(dist, vec2<f32>(0.0, 0.0));
+ let distance = length(outside) - radius;
+ let alpha = clamp(1.0 - distance, 0.0, 1.0);
+
+ return vec4<f32>(uniforms.color.rgb, uniforms.color.a * alpha);
+}