1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use self::errors::*;
use self::errors::ErrorKind::*;
use {SubtitleEntry, SubtitleFile};
use combine::char::{char, string};
use combine::combinator::{eof, parser as p, skip_many};
use combine::primitives::Parser;
use errors::Result as SubtitleParserResult;
use formats::common::*;
use itertools::Itertools;
use std::iter::once;
use timetypes::{TimePoint, TimeSpan};
#[allow(missing_docs)]
pub mod errors {
error_chain! {
errors {
ExpectedIndexLine(line: String) {
display("expected SubRip index line, found '{}'", line)
}
ExpectedTimestampLine(line: String) {
display("expected SubRip timespan line, found '{}'", line)
}
ErrorAtLine(line_num: usize) {
display("parse error at line `{}`", line_num)
}
}
}
}
enum SrtParserState {
Emptyline,
Index(i64),
Timing(i64, TimeSpan),
Dialog(i64, TimeSpan, Vec<String>),
}
#[derive(Debug, Clone)]
pub struct SrtFile {
v: Vec<SrtLine>,
}
#[derive(Debug, Clone)]
struct SrtLine {
timespan: TimeSpan,
index: i64,
texts: Vec<String>,
}
impl SrtFile {
pub fn parse(s: &str) -> SubtitleParserResult<SrtFile> {
let file_opt = Self::parse_file(s);
match file_opt {
Ok(file) => Ok(file),
Err(err) => Err(err.into()),
}
}
}
impl SrtFile {
fn parse_file(i: &str) -> Result<SrtFile> {
use self::SrtParserState::*;
let mut result: Vec<SrtLine> = Vec::new();
let (_, s) = split_bom(i);
let mut state: SrtParserState = Emptyline;
for (line_num, line) in s.lines().chain(once("")).enumerate() {
state = match state {
Emptyline => {
if line.trim().is_empty() {
Emptyline
} else {
Index(Self::parse_index_line(line_num, line)?)
}
}
Index(index) => Timing(index, Self::parse_timespan_line(line_num, line)?),
Timing(index, timespan) => Self::state_expect_dialog(line, &mut result, index, timespan, Vec::new()),
Dialog(index, timespan, texts) => Self::state_expect_dialog(line, &mut result, index, timespan, texts),
};
}
Ok(SrtFile { v: result })
}
fn state_expect_dialog(line: &str, result: &mut Vec<SrtLine>, index: i64, timespan: TimeSpan, mut texts: Vec<String>) -> SrtParserState {
if line.trim().is_empty() {
result.push(SrtLine {
index: index,
timespan: timespan,
texts: texts,
});
SrtParserState::Emptyline
} else {
texts.push(line.trim().to_string());
SrtParserState::Dialog(index, timespan, texts)
}
}
fn parse_index_line(line_num: usize, s: &str) -> Result<i64> {
s.trim()
.parse::<i64>()
.chain_err(|| ExpectedIndexLine(s.to_string()))
.chain_err(|| ErrorAtLine(line_num))
}
fn parse_timespan_line(line_num: usize, line: &str) -> Result<TimeSpan> {
let timestamp = |s| {
(
p(number_i64),
char(':'),
p(number_i64),
char(':'),
p(number_i64),
char(','),
p(number_i64),
)
.map(|t| TimePoint::from_components(t.0, t.2, t.4, t.6))
.parse_stream(s)
};
(
skip_many(ws()),
p(×tamp),
skip_many(ws()),
string("-->"),
skip_many(ws()),
p(×tamp),
skip_many(ws()),
eof(),
)
.map(|t| TimeSpan::new(t.1, t.5))
.parse(line)
.map(|x| x.0)
.map_err(|_| Error::from(ExpectedTimestampLine(line.to_string())))
.chain_err(|| ErrorAtLine(line_num))
}
}
impl SubtitleFile for SrtFile {
fn get_subtitle_entries(&self) -> SubtitleParserResult<Vec<SubtitleEntry>> {
let timings = self.v
.iter()
.map(|line| {
SubtitleEntry::new(line.timespan, line.texts.iter().join("\n"))
})
.collect();
Ok(timings)
}
fn update_subtitle_entries(&mut self, new_subtitle_entries: &[SubtitleEntry]) -> SubtitleParserResult<()> {
assert_eq!(self.v.len(), new_subtitle_entries.len());
for (line_ref, new_entry_ref) in self.v.iter_mut().zip(new_subtitle_entries) {
line_ref.timespan = new_entry_ref.timespan;
if let Some(ref text) = new_entry_ref.line {
line_ref.texts = text.lines().map(str::to_string).collect();
}
}
Ok(())
}
fn to_data(&self) -> SubtitleParserResult<Vec<u8>> {
let timepoint_to_str = |t: TimePoint| -> String {
format!(
"{:02}:{:02}:{:02},{:03}",
t.hours(),
t.mins_comp(),
t.secs_comp(),
t.msecs_comp()
)
};
let line_to_str = |line: &SrtLine| -> String {
format!(
"{}\n{} --> {}\n{}\n\n",
line.index,
timepoint_to_str(line.timespan.start),
timepoint_to_str(line.timespan.end),
line.texts.join("\n")
)
};
Ok(
self.v
.iter()
.map(line_to_str)
.collect::<String>()
.into_bytes(),
)
}
}
impl SrtFile {
pub fn create(v: Vec<(TimeSpan, String)>) -> SubtitleParserResult<SrtFile> {
let file_parts = v.into_iter()
.enumerate()
.map(|(i, (ts, text))| {
SrtLine {
index: i as i64 + 1,
timespan: ts,
texts: text.lines().map(str::to_string).collect(),
}
})
.collect();
Ok(SrtFile { v: file_parts })
}
}
#[cfg(test)]
mod tests {
#[test]
fn create_srt_test() {
use timetypes::{TimePoint, TimeSpan};
use SubtitleFile;
let lines = vec![
(
TimeSpan::new(TimePoint::from_msecs(1500), TimePoint::from_msecs(3700)),
"line1".to_string()
),
(
TimeSpan::new(TimePoint::from_msecs(4500), TimePoint::from_msecs(8700)),
"line2".to_string()
),
];
let file = super::SrtFile::create(lines).unwrap();
let data_string = String::from_utf8(file.to_data().unwrap()).unwrap();
let expected = "1\n00:00:01,500 --> 00:00:03,700\nline1\n\n2\n00:00:04,500 --> 00:00:08,700\nline2\n\n".to_string();
println!("\n{:?}\n{:?}", data_string, expected);
assert_eq!(data_string, expected);
}
}