atmos/os_lib/web_engine/
vtt.rs1extern crate alloc;
7
8use alloc::string::String;
9use alloc::vec::Vec;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum VttParseError {
14 InvalidHeader,
15 EmptyInput,
16}
17
18#[derive(Debug, Clone, PartialEq)]
20pub struct VttCue {
21 pub id: Option<String>,
23 pub start_sec: f64,
25 pub end_sec: f64,
27 pub settings: Option<String>,
29 pub text: String,
31}
32
33#[derive(Debug, Clone, PartialEq)]
35pub struct SubtitleTrack {
36 pub label: String,
38 pub srclang: String,
40 pub kind: String,
42 pub vtt: WebVtt,
44}
45
46impl SubtitleTrack {
47 pub fn new(label: &str, srclang: &str, kind: &str, vtt: WebVtt) -> Self {
48 Self {
49 label: String::from(label),
50 srclang: String::from(srclang),
51 kind: String::from(kind),
52 vtt,
53 }
54 }
55}
56
57impl VttCue {
58 pub fn is_active_at(&self, time_sec: f64) -> bool {
60 time_sec >= self.start_sec && time_sec <= self.end_sec
61 }
62}
63
64#[derive(Debug, Clone, Default, PartialEq)]
66pub struct WebVtt {
67 pub cues: Vec<VttCue>,
68}
69
70impl WebVtt {
71 pub fn new() -> Self {
73 Self { cues: Vec::new() }
74 }
75
76 pub fn parse(input: &str) -> Result<Self, VttParseError> {
78 let trimmed = input.trim_start_matches('\u{FEFF}'); if trimmed.trim().is_empty() {
80 return Err(VttParseError::EmptyInput);
81 }
82
83 let mut lines = trimmed.lines().map(|l| l.trim_end_matches('\r'));
84
85 let header = lines.next().ok_or(VttParseError::InvalidHeader)?;
87 let header_trimmed = header.trim();
88 if !header_trimmed.starts_with("WEBVTT") {
89 return Err(VttParseError::InvalidHeader);
90 }
91
92 let mut cues = Vec::new();
93 let mut current_id: Option<String> = None;
94 let mut current_timing: Option<(f64, f64, Option<String>)> = None;
95 let mut current_text_lines: Vec<String> = Vec::new();
96 let mut in_note = false;
97 let mut in_style = false;
98
99 for line in lines {
100 let line_trim = line.trim();
101
102 if line_trim.is_empty() {
103 if in_note {
105 in_note = false;
106 } else if in_style {
107 in_style = false;
108 } else if let Some((start, end, settings)) = current_timing.take() {
109 if !current_text_lines.is_empty() {
110 let text = current_text_lines.join("\n");
111 cues.push(VttCue {
112 id: current_id.take(),
113 start_sec: start,
114 end_sec: end,
115 settings,
116 text,
117 });
118 }
119 current_text_lines.clear();
120 current_id = None;
121 } else {
122 current_id = None;
123 current_text_lines.clear();
124 }
125 continue;
126 }
127
128 if in_note || in_style {
130 continue;
131 }
132
133 if line_trim.starts_with("NOTE") {
134 in_note = true;
135 continue;
136 }
137
138 if line_trim.starts_with("STYLE") {
139 in_style = true;
140 continue;
141 }
142
143 if line.contains("-->") {
145 if let Some((start, end, settings)) = parse_timing_line(line) {
146 if end > start {
147 current_timing = Some((start, end, settings));
148 }
149 }
150 continue;
151 }
152
153 if current_timing.is_none() {
155 current_id = Some(String::from(line_trim));
156 } else {
157 current_text_lines.push(String::from(line));
159 }
160 }
161
162 if let Some((start, end, settings)) = current_timing.take() {
164 if !current_text_lines.is_empty() {
165 let text = current_text_lines.join("\n");
166 cues.push(VttCue {
167 id: current_id.take(),
168 start_sec: start,
169 end_sec: end,
170 settings,
171 text,
172 });
173 }
174 }
175
176 cues.sort_by(|a, b| a.start_sec.partial_cmp(&b.start_sec).unwrap_or(core::cmp::Ordering::Equal));
178
179 Ok(WebVtt { cues })
180 }
181
182 pub fn len(&self) -> usize {
184 self.cues.len()
185 }
186
187 pub fn is_empty(&self) -> bool {
189 self.cues.is_empty()
190 }
191
192 pub fn cues_at(&self, time_sec: f64) -> Vec<&VttCue> {
194 self.cues.iter().filter(|c| c.is_active_at(time_sec)).collect()
195 }
196
197 pub fn active_text_at(&self, time_sec: f64) -> Option<String> {
199 let active = self.cues_at(time_sec);
200 if active.is_empty() {
201 None
202 } else {
203 let combined = active.into_iter().map(|c| c.text.as_str()).collect::<Vec<_>>().join("\n");
204 Some(combined)
205 }
206 }
207}
208
209fn parse_timing_line(line: &str) -> Option<(f64, f64, Option<String>)> {
211 let mut parts = line.split("-->");
212 let start_str = parts.next()?.trim();
213 let rest = parts.next()?.trim();
214
215 let mut rest_parts = rest.split_whitespace();
216 let end_str = rest_parts.next()?.trim();
217
218 let settings = {
219 let s: Vec<&str> = rest_parts.collect();
220 if s.is_empty() {
221 None
222 } else {
223 Some(s.join(" "))
224 }
225 };
226
227 let start = parse_vtt_timestamp(start_str)?;
228 let end = parse_vtt_timestamp(end_str)?;
229
230 Some((start, end, settings))
231}
232
233pub fn parse_vtt_timestamp(s: &str) -> Option<f64> {
235 let trimmed = s.trim();
236 let mut dot_parts = trimmed.split('.');
237 let time_part = dot_parts.next()?;
238 let ms_part = dot_parts.next()?;
239
240 let ms_val: f64 = match ms_part.len() {
242 1 => ms_part.parse::<f64>().ok()? * 0.1,
243 2 => ms_part.parse::<f64>().ok()? * 0.01,
244 3 => ms_part.parse::<f64>().ok()? * 0.001,
245 _ => ms_part.get(..3)?.parse::<f64>().ok()? * 0.001,
246 };
247
248 let colon_parts: Vec<&str> = time_part.split(':').collect();
249 match colon_parts.as_slice() {
250 [min, sec] => {
251 let m = min.parse::<f64>().ok()?;
252 let s = sec.parse::<f64>().ok()?;
253 Some(m * 60.0 + s + ms_val)
254 }
255 [hour, min, sec] => {
256 let h = hour.parse::<f64>().ok()?;
257 let m = min.parse::<f64>().ok()?;
258 let s = sec.parse::<f64>().ok()?;
259 Some(h * 3600.0 + m * 60.0 + s + ms_val)
260 }
261 _ => None,
262 }
263}