subx_cli/core/formats/
srt.rs

1use crate::Result;
2use crate::core::formats::{
3    Subtitle, SubtitleEntry, SubtitleFormat, SubtitleFormatType, SubtitleMetadata,
4};
5use crate::error::SubXError;
6use regex::Regex;
7use std::time::Duration;
8
9/// SubRip (.srt) format parsing and serialization
10pub struct SrtFormat;
11
12impl SubtitleFormat for SrtFormat {
13    fn parse(&self, content: &str) -> Result<Subtitle> {
14        let time_regex =
15            Regex::new(r"(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})")
16                .map_err(|e| {
17                    SubXError::subtitle_format(
18                        self.format_name(),
19                        format!("Time format compilation error: {}", e),
20                    )
21                })?;
22
23        let mut entries = Vec::new();
24        let blocks: Vec<&str> = content.split("\n\n").collect();
25
26        for block in blocks {
27            if block.trim().is_empty() {
28                continue;
29            }
30            let lines: Vec<&str> = block.lines().collect();
31            if lines.len() < 3 {
32                continue;
33            }
34
35            let index: usize = lines[0].trim().parse().map_err(|e| {
36                SubXError::subtitle_format(
37                    self.format_name(),
38                    format!("Invalid sequence number: {}", e),
39                )
40            })?;
41
42            if let Some(caps) = time_regex.captures(lines[1]) {
43                let start_time = parse_time(&caps, 1)?;
44                let end_time = parse_time(&caps, 5)?;
45                let text = lines[2..].join("\n");
46
47                entries.push(SubtitleEntry {
48                    index,
49                    start_time,
50                    end_time,
51                    text,
52                    styling: None,
53                });
54            }
55        }
56
57        Ok(Subtitle {
58            entries,
59            metadata: SubtitleMetadata {
60                title: None,
61                language: None,
62                encoding: "utf-8".to_string(),
63                frame_rate: None,
64                original_format: SubtitleFormatType::Srt,
65            },
66            format: SubtitleFormatType::Srt,
67        })
68    }
69
70    fn serialize(&self, subtitle: &Subtitle) -> Result<String> {
71        let mut output = String::new();
72
73        for (i, entry) in subtitle.entries.iter().enumerate() {
74            output.push_str(&format!("{}\n", i + 1));
75            output.push_str(&format_time_range(entry.start_time, entry.end_time));
76            output.push_str(&format!("{}\n\n", entry.text));
77        }
78
79        Ok(output)
80    }
81
82    fn detect(&self, content: &str) -> bool {
83        let time_pattern =
84            Regex::new(r"\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}").unwrap();
85        time_pattern.is_match(content)
86    }
87
88    fn format_name(&self) -> &'static str {
89        "SRT"
90    }
91
92    fn file_extensions(&self) -> &'static [&'static str] {
93        &["srt"]
94    }
95}
96
97fn parse_time(caps: &regex::Captures, start_group: usize) -> Result<Duration> {
98    let hours: u64 = caps[start_group].parse().map_err(|e| {
99        SubXError::subtitle_format("SRT", format!("Time value parsing failed: {}", e))
100    })?;
101    let minutes: u64 = caps[start_group + 1].parse().map_err(|e| {
102        SubXError::subtitle_format("SRT", format!("Time value parsing failed: {}", e))
103    })?;
104    let seconds: u64 = caps[start_group + 2].parse().map_err(|e| {
105        SubXError::subtitle_format("SRT", format!("Time value parsing failed: {}", e))
106    })?;
107    let milliseconds: u64 = caps[start_group + 3].parse().map_err(|e| {
108        SubXError::subtitle_format("SRT", format!("Time value parsing failed: {}", e))
109    })?;
110
111    Ok(Duration::from_millis(
112        hours * 3600000 + minutes * 60000 + seconds * 1000 + milliseconds,
113    ))
114}
115
116fn format_time_range(start: Duration, end: Duration) -> String {
117    format!("{} --> {}\n", format_duration(start), format_duration(end))
118}
119
120fn format_duration(duration: Duration) -> String {
121    let total_ms = duration.as_millis();
122    let hours = total_ms / 3600000;
123    let minutes = (total_ms % 3600000) / 60000;
124    let seconds = (total_ms % 60000) / 1000;
125    let milliseconds = total_ms % 1000;
126
127    format!(
128        "{:02}:{:02}:{:02},{:03}",
129        hours, minutes, seconds, milliseconds
130    )
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::core::formats::{SubtitleFormat, SubtitleFormatType};
137    use std::time::Duration;
138
139    // NOTE: The following test data contains Chinese text for multi-line subtitle testing. This is allowed and does not require modification.
140    const SAMPLE_SRT: &str = "1\n00:00:01,000 --> 00:00:03,000\nHello, World!\n\n2\n00:00:05,000 --> 00:00:08,000\nThis is a test subtitle.\n多行測試\n\n";
141
142    #[test]
143    fn test_srt_parsing_basic() {
144        let format = SrtFormat;
145        let subtitle = format.parse(SAMPLE_SRT).unwrap();
146
147        assert_eq!(subtitle.entries.len(), 2);
148        assert_eq!(subtitle.format, SubtitleFormatType::Srt);
149
150        let first = &subtitle.entries[0];
151        assert_eq!(first.index, 1);
152        assert_eq!(first.start_time, Duration::from_millis(1000));
153        assert_eq!(first.end_time, Duration::from_millis(3000));
154        assert_eq!(first.text, "Hello, World!");
155
156        let second = &subtitle.entries[1];
157        assert_eq!(second.index, 2);
158        assert_eq!(second.start_time, Duration::from_millis(5000));
159        assert_eq!(second.end_time, Duration::from_millis(8000));
160        assert_eq!(second.text, "This is a test subtitle.\n多行測試");
161    }
162
163    #[test]
164    fn test_srt_serialization_roundtrip() {
165        let format = SrtFormat;
166        let subtitle = format.parse(SAMPLE_SRT).unwrap();
167        let serialized = format.serialize(&subtitle).unwrap();
168        let reparsed = format.parse(&serialized).unwrap();
169        assert_eq!(subtitle.entries.len(), reparsed.entries.len());
170        for (o, r) in subtitle.entries.iter().zip(reparsed.entries.iter()) {
171            assert_eq!(o.start_time, r.start_time);
172            assert_eq!(o.end_time, r.end_time);
173            assert_eq!(o.text, r.text);
174        }
175    }
176
177    #[test]
178    fn test_srt_detection() {
179        let format = SrtFormat;
180        assert!(format.detect(SAMPLE_SRT));
181        assert!(!format.detect("This is not SRT content"));
182        assert!(!format.detect("WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nHello"));
183    }
184
185    #[test]
186    fn test_srt_invalid_format() {
187        let format = SrtFormat;
188        let invalid_time = "1\n00:00:01 --> 00:00:03\nText\n\n";
189        let subtitle = format.parse(invalid_time).unwrap();
190        assert_eq!(subtitle.entries.len(), 0);
191        let invalid_index = "invalid\n00:00:01,000 --> 00:00:03,000\nText\n\n";
192        assert!(format.parse(invalid_index).is_err());
193    }
194
195    #[test]
196    fn test_srt_empty_and_malformed_blocks() {
197        let format = SrtFormat;
198        let subtitle = format.parse("").unwrap();
199        assert_eq!(subtitle.entries.len(), 0);
200        let subtitle = format.parse("\n\n\n").unwrap();
201        assert_eq!(subtitle.entries.len(), 0);
202        let malformed = "1\n00:00:01,000 --> 00:00:03,000\n\n";
203        let subtitle = format.parse(malformed).unwrap();
204        assert_eq!(subtitle.entries.len(), 0);
205    }
206
207    #[test]
208    fn test_time_parsing_edge_cases() {
209        let format = SrtFormat;
210        let edge = "1\n23:59:59,999 --> 23:59:59,999\nEnd of day\n\n";
211        let subtitle = format.parse(edge).unwrap();
212        assert_eq!(subtitle.entries.len(), 1);
213        let entry = &subtitle.entries[0];
214        let expected = Duration::from_millis(23 * 3600000 + 59 * 60000 + 59 * 1000 + 999);
215        assert_eq!(entry.start_time, expected);
216        assert_eq!(entry.end_time, expected);
217    }
218
219    #[test]
220    fn test_file_extensions_and_name() {
221        let format = SrtFormat;
222        assert_eq!(format.file_extensions(), &["srt"]);
223        assert_eq!(format.format_name(), "SRT");
224    }
225}