-
Notifications
You must be signed in to change notification settings - Fork 40
/
VttParser.cs
executable file
·296 lines (262 loc) · 10.8 KB
/
VttParser.cs
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
#nullable enable
namespace SubtitlesParser.Classes.Parsers
{
/// <summary>
/// Parser for the .vtt subtitles files. Does not handle formatting tags within the text; that has to be parsed separately.
///
/// A .vtt file looks like:
/// WEBVTT
///
/// CUE - 1
/// 00:00:10.500 --> 00:00:13.000
/// Elephant's Dream
///
/// CUE - 2
/// 00:00:15.000 --> 00:00:18.000
/// At the left we can see...
/// </summary>
public class VttParser : ISubtitlesParser
{
private static readonly Regex _rxLongTimestamp = new Regex("(?<H>[0-9]+):(?<M>[0-9]+):(?<S>[0-9]+)[,\\.](?<m>[0-9]+)", RegexOptions.Compiled);
private static readonly Regex _rxShortTimestamp = new Regex("(?<M>[0-9]+):(?<S>[0-9]+)[,\\.](?<m>[0-9]+)", RegexOptions.Compiled);
// Properties -----------------------------------------------------------------------
private readonly string[] _delimiters = new string[] { "-->", "- >", "->" };
// Constructors --------------------------------------------------------------------
public VttParser() { }
// Methods -------------------------------------------------------------------------
public List<SubtitleItem> ParseStream(Stream vttStream, Encoding encoding)
{
// test if stream if readable and seekable (just a check, should be good)
if (!vttStream.CanRead || !vttStream.CanSeek)
{
var message = string.Format("Stream must be seekable and readable in a subtitles parser. " +
"Operation interrupted; isSeekable: {0} - isReadable: {1}",
vttStream.CanSeek, vttStream.CanSeek);
throw new ArgumentException(message);
}
// seek the beginning of the stream
vttStream.Position = 0;
var reader = new StreamReader(vttStream, encoding, detectEncodingFromByteOrderMarks: true);
var items = new List<SubtitleItem>();
var vttSubParts = GetVttSubTitleParts(reader).GetEnumerator();
if (false == vttSubParts.MoveNext())
{
throw new FormatException("Parsing as VTT returned no VTT part.");
}
do
{
var lines = vttSubParts.Current
.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => s.Trim())
.Where(l => !string.IsNullOrEmpty(l));
var item = new SubtitleItem();
foreach (var line in lines)
{
if (item.StartTime == 0 && item.EndTime == 0)
{
// we look for the timecodes first
var success = TryParseTimecodeLine(line, out int startTc, out int endTc);
if (success)
{
item.StartTime = startTc;
item.EndTime = endTc;
}
}
else
{
// we found the timecode, now we get the text
item.Lines.Add(line);
}
}
if ((item.StartTime != 0 || item.EndTime != 0) && item.Lines.Any())
{
// parsing succeeded
items.Add(item);
}
}
while (vttSubParts.MoveNext());
return items;
}
public async Task<List<SubtitleItem>> ParseStreamAsync(Stream vttStream, Encoding encoding)
{
// test if stream if readable and seekable (just a check, should be good)
if (!vttStream.CanRead || !vttStream.CanSeek)
{
var message = string.Format("Stream must be seekable and readable in a subtitles parser. " +
"Operation interrupted; isSeekable: {0} - isReadable: {1}",
vttStream.CanSeek, vttStream.CanSeek);
throw new ArgumentException(message);
}
// seek the beginning of the stream
vttStream.Position = 0;
var reader = new StreamReader(vttStream, encoding, detectEncodingFromByteOrderMarks: true);
var items = new List<SubtitleItem>();
var vttBlockEnumerator = GetVttSubTitlePartsAsync(reader).GetAsyncEnumerator();
if (await vttBlockEnumerator.MoveNextAsync() == false)
{
throw new FormatException("Parsing as VTT returned no VTT part.");
}
do
{
var lines = vttBlockEnumerator.Current
.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => s.Trim())
.Where(l => !string.IsNullOrEmpty(l));
var item = new SubtitleItem();
foreach (var line in lines)
{
if (item.StartTime == 0 && item.EndTime == 0)
{
// we look for the timecodes first
var success = TryParseTimecodeLine(line, out int startTc, out int endTc);
if (success)
{
item.StartTime = startTc;
item.EndTime = endTc;
}
}
else
{
// we found the timecode, now we get the text
item.Lines.Add(line);
}
}
if ((item.StartTime != 0 || item.EndTime != 0) && item.Lines.Any())
{
// parsing succeeded
items.Add(item);
}
}
while (await vttBlockEnumerator.MoveNextAsync());
return items;
}
/// <summary>
/// Enumerates the subtitle parts in a VTT file based on the standard line break observed between them.
/// A VTT subtitle part is in the form:
///
/// CUE - 1
/// 00:00:20.000 --> 00:00:24.400
/// Altocumulus clouds occur between six thousand
///
/// The first line is optional, as well as the hours in the time codes.
/// </summary>
/// <param name="reader">The textreader associated with the vtt file</param>
/// <returns>An IEnumerable(string) object containing all the subtitle parts</returns>
private IEnumerable<string> GetVttSubTitleParts(TextReader reader)
{
string line;
var sb = new StringBuilder();
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line.Trim()))
{
// return only if not empty
var res = sb.ToString().TrimEnd();
if (!string.IsNullOrEmpty(res))
{
yield return res;
}
sb = new StringBuilder();
}
else
{
sb.AppendLine(line);
}
}
if (sb.Length > 0)
{
yield return sb.ToString();
}
}
private async IAsyncEnumerable<string> GetVttSubTitlePartsAsync(TextReader reader)
{
string line;
var sb = new StringBuilder();
while ((line = await reader.ReadLineAsync()) != null)
{
if (string.IsNullOrEmpty(line.Trim()))
{
// return only if not empty
var res = sb.ToString().TrimEnd();
if (!string.IsNullOrEmpty(res))
{
yield return res;
}
sb = new StringBuilder();
}
else
{
sb.AppendLine(line);
}
}
if (sb.Length > 0)
{
yield return sb.ToString();
}
}
private bool TryParseTimecodeLine(string line, out int startTc, out int endTc)
{
var parts = line.Split(_delimiters, StringSplitOptions.None);
if (parts.Length != 2)
{
// this is not a timecode line
startTc = -1;
endTc = -1;
return false;
}
else
{
startTc = ParseVttTimecode(parts[0]);
endTc = ParseVttTimecode(parts[1]);
return true;
}
}
/// <summary>
/// Takes an VTT timecode as a string and parses it into a double (in seconds). A VTT timecode reads as follows:
/// 00:00:20.000
/// or
/// 00:20.000
/// </summary>
/// <param name="s">The timecode to parse</param>
/// <returns>The parsed timecode as a TimeSpan instance. If the parsing was unsuccessful, -1 is returned (subtitles should never show)</returns>
private int ParseVttTimecode(string s)
{
int hours = 0;
int minutes = 0;
int seconds = 0;
int milliseconds = -1;
var match = _rxLongTimestamp.Match(s);
if (match.Success)
{
hours = int.Parse(match.Groups["H"].Value);
minutes = int.Parse(match.Groups["M"].Value);
seconds = int.Parse(match.Groups["S"].Value);
milliseconds = int.Parse(match.Groups["m"].Value);
}
else
{
match = _rxShortTimestamp.Match(s);
if (match.Success)
{
minutes = int.Parse(match.Groups["M"].Value);
seconds = int.Parse(match.Groups["S"].Value);
milliseconds = int.Parse(match.Groups["m"].Value);
}
}
if (milliseconds >= 0)
{
var result = new TimeSpan(0, hours, minutes, seconds, milliseconds);
var nbOfMs = (int)result.TotalMilliseconds;
return nbOfMs;
}
return -1;
}
}
}