-
Notifications
You must be signed in to change notification settings - Fork 40
/
MicroDvdParser.cs
184 lines (163 loc) · 6.59 KB
/
MicroDvdParser.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SubtitlesParser.Classes.Parsers
{
/// <summary>
/// Parser for MicroDVD .sub subtitles files
///
/// A .sub file looks like this:
/// {1}{1}29.970
/// {0}{180}PIRATES OF THE CARIBBEAN|English subtitlez by tHe.b0dY
/// {509}{629}Drink up me 'earties yo ho!
/// {635}{755}We kidnap and ravage and don't give a hoot.
///
/// We need the video frame rate to extract .sub files -> careful when using it
///
/// see https://en.wikipedia.org/wiki/MicroDVD
/// </summary>
public class MicroDvdParser : ISubtitlesParser
{
// Properties -----------------------------------------------------------------------
private readonly float defaultFrameRate = 25;
private readonly char[] _lineSeparators = {'|'};
// Constructors --------------------------------------------------------------------
public MicroDvdParser(){}
public MicroDvdParser(float defaultFrameRate)
{
this.defaultFrameRate = defaultFrameRate;
}
// Methods -------------------------------------------------------------------------
public List<SubtitleItem> ParseStream(Stream subStream, Encoding encoding)
{
// test if stream if readable and seekable (just a check, should be good)
if (!subStream.CanRead || !subStream.CanSeek)
{
var message = string.Format("Stream must be seekable and readable in a subtitles parser. " +
"Operation interrupted; isSeekable: {0} - isReadable: {1}",
subStream.CanSeek, subStream.CanSeek);
throw new ArgumentException(message);
}
// seek the beginning of the stream
subStream.Position = 0;
var reader = new StreamReader(subStream, encoding, true);
var items = new List<SubtitleItem>();
var line = reader.ReadLine();
// find the first relevant line
while (line != null && !IsMicroDvdLine(line))
{
line = reader.ReadLine();
}
if (line != null)
{
float frameRate;
// try to extract the framerate from the first line
var firstItem = ParseLine(line, defaultFrameRate);
if (firstItem.Lines != null && firstItem.Lines.Any())
{
var success = TryExtractFrameRate(firstItem.Lines[0], out frameRate);
if (!success)
{
Console.WriteLine("Couldn't extract frame rate of sub file with first line {0}. " +
"We use the default frame rate: {1}", line, defaultFrameRate);
frameRate = defaultFrameRate;
// treat it as a regular line
items.Add(firstItem);
}
}
else
{
frameRate = defaultFrameRate;
}
// parse other lines
line = reader.ReadLine();
while (line != null)
{
if (!string.IsNullOrEmpty(line))
{
var item = ParseLine(line, frameRate);
items.Add(item);
}
line = reader.ReadLine();
}
}
if (items.Any())
{
return items;
}
else
{
throw new ArgumentException("Stream is not in a valid MicroDVD format");
}
}
private const string LineRegex = @"^[{\[](-?\d+)[}\]][{\[](-?\d+)[}\]](.*)";
private bool IsMicroDvdLine(string line)
{
return Regex.IsMatch(line, LineRegex);
}
/// <summary>
/// Parses one line of the .sub file
///
/// ex:
/// {0}{180}PIRATES OF THE CARIBBEAN|English subtitlez by tHe.b0dY
/// </summary>
/// <param name="line">The .sub file line</param>
/// <param name="frameRate">The frame rate with which the .sub file was created</param>
/// <returns>The corresponding SubtitleItem</returns>
private SubtitleItem ParseLine(string line, float frameRate)
{
var match = Regex.Match(line, LineRegex);
if (match.Success && match.Groups.Count > 2)
{
var startFrame = match.Groups[1].Value;
var start = (int)(1000 * double.Parse(startFrame) / frameRate);
var endTime = match.Groups[2].Value;
var end = (int)(1000 * double.Parse(endTime) / frameRate);
var text = match.Groups[match.Groups.Count - 1].Value;
var lines = text.Split(_lineSeparators);
var nonEmptyLines = lines.Where(l => !string.IsNullOrEmpty(l)).ToList();
var item = new SubtitleItem
{
Lines = nonEmptyLines,
StartTime = start,
EndTime = end
};
return item;
}
else
{
var message = string.Format("The subtitle file line {0} is " +
"not in the micro dvd format. We stop the process.", line);
throw new InvalidDataException(message);
}
}
/// <summary>
/// Tries to extract the frame rate from a subtitle file line.
///
/// Supported formats are:
/// - {x}{y}25
/// - {x}{y}{...}23.976
/// </summary>
/// <param name="text">The subtitle file line</param>
/// <param name="frameRate">The frame rate if we can parse it</param>
/// <returns>True if the parsing was successful, false otherwise</returns>
private bool TryExtractFrameRate(string text, out float frameRate)
{
if (!string.IsNullOrEmpty(text))
{
var success = float.TryParse(text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture,
out frameRate);
return success;
}
else
{
frameRate = defaultFrameRate;
return false;
}
}
}
}