Skip to main content

atmos/os_lib/web_engine/
vtt.rs

1//! WebVTT (Web Video Text Tracks) 字幕・キャプションパーサーおよび再生キュー管理。
2//!
3//! W3C WebVTT 仕様に準拠し、<video> / <track> および YouTube 等の字幕オーバーレイ表示を支援する。
4//! ハードウェア非依存の純粋ロジックであり、ホストユニットテスト環境から直接検証可能。
5
6extern crate alloc;
7
8use alloc::string::String;
9use alloc::vec::Vec;
10
11/// WebVTT パースエラー種別
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum VttParseError {
14    InvalidHeader,
15    EmptyInput,
16}
17
18/// 1 件の字幕キュー(Cue)
19#[derive(Debug, Clone, PartialEq)]
20pub struct VttCue {
21    /// 識別子(オプション、例: "1", "intro-cue")
22    pub id: Option<String>,
23    /// 開始時間(秒)
24    pub start_sec: f64,
25    /// 終了時間(秒)
26    pub end_sec: f64,
27    /// キュー設定文字列(オプション、例: "align:start position:10%")
28    pub settings: Option<String>,
29    /// 字幕テキスト(改行を含む複数行可能)
30    pub text: String,
31}
32
33/// 1 つの字幕・キャプショントラック(言語・ラベル・種別・パース済みキュー情報)
34#[derive(Debug, Clone, PartialEq)]
35pub struct SubtitleTrack {
36    /// 表示用ラベル(例: "日本語", "English", "日本語 [自動生成]")
37    pub label: String,
38    /// BCP 47 言語タグ(例: "ja", "en", "es")
39    pub srclang: String,
40    /// トラック種別(例: "subtitles", "captions", "descriptions")
41    pub kind: String,
42    /// パース済みの WebVTT ドキュメント
43    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    /// 指定された再生時間(秒)にこのキューがアクティブか判定
59    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/// パース済みの WebVTT 字幕ドキュメント
65#[derive(Debug, Clone, Default, PartialEq)]
66pub struct WebVtt {
67    pub cues: Vec<VttCue>,
68}
69
70impl WebVtt {
71    /// 空の WebVTT を作成
72    pub fn new() -> Self {
73        Self { cues: Vec::new() }
74    }
75
76    /// WebVTT 文字列をパースして `WebVtt` オブジェクトを生成する。
77    pub fn parse(input: &str) -> Result<Self, VttParseError> {
78        let trimmed = input.trim_start_matches('\u{FEFF}'); // BOM を除去
79        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        // 1. ヘッダー行の検証("WEBVTT" で始まること)
86        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                // 空行はブロックの区切り
104                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            // NOTE または STYLE ブロックのスキップ
129            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            // タイムスタンプ行の検出("-->" を含む)
144            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            // タイムスタンプがまだ確定していない場合は識別子行の可能性
154            if current_timing.is_none() {
155                current_id = Some(String::from(line_trim));
156            } else {
157                // タイムスタンプ確定後はキューのテキスト行
158                current_text_lines.push(String::from(line));
159            }
160        }
161
162        // 末尾ブロックの確定
163        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        // 開始時間でソート
177        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    /// キューの総数
183    pub fn len(&self) -> usize {
184        self.cues.len()
185    }
186
187    /// キューが空か判定
188    pub fn is_empty(&self) -> bool {
189        self.cues.is_empty()
190    }
191
192    /// 指定時間(秒)にアクティブなキューの一覧を取得
193    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    /// 指定時間(秒)に表示すべき字幕テキストを取得(複数キューがある場合は改行で連結)
198    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
209/// タイムスタンプ行 `00:01.000 --> 00:04.000 [settings...]` をパース
210fn 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
233/// WebVTT タイムスタンプ(`MM:SS.mmm` または `HH:MM:SS.mmm`)を秒数(f64)にパース
234pub 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    // ミリ秒部分のパース(1〜3桁対応)
241    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}