diff options
| author | 7illusions <z@7illusions.com> | 2014-05-12 16:55:07 +0200 |
|---|---|---|
| committer | 7illusions <z@7illusions.com> | 2014-05-12 16:55:07 +0200 |
| commit | baf5cf2544fcaad2246923f60caaf3fed4a94aaf (patch) | |
| tree | a808b700095f876e437b95c432c0220e241f9fda /MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs | |
| parent | 8f3a6279e173dcbaaa05a56556afb410ee12dd4d (diff) | |
| parent | b9b568de13d81f9db1a8502d50940475c1d79c72 (diff) | |
Merge pull request #3 from MediaBrowser/master
Sync with Master
Diffstat (limited to 'MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs')
| -rw-r--r-- | MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs new file mode 100644 index 000000000..996ef1c4e --- /dev/null +++ b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; + +namespace MediaBrowser.MediaEncoding.Subtitles +{ + public class SsaParser : ISubtitleParser + { + private readonly CultureInfo _usCulture = new CultureInfo("en-US"); + + public SubtitleTrackInfo Parse(Stream stream) + { + var trackInfo = new SubtitleTrackInfo(); + var eventIndex = 1; + using (var reader = new StreamReader(stream)) + { + string line; + while (reader.ReadLine() != "[Events]") + {} + var headers = ParseFieldHeaders(reader.ReadLine()); + + while ((line = reader.ReadLine()) != null) + { + if (string.IsNullOrWhiteSpace(line)) + { + continue; + } + if(line.StartsWith("[")) + break; + if(string.IsNullOrEmpty(line)) + continue; + var subEvent = new SubtitleTrackEvent { Id = eventIndex.ToString(_usCulture) }; + eventIndex++; + var sections = line.Substring(10).Split(','); + + subEvent.StartPositionTicks = GetTicks(sections[headers["Start"]]); + subEvent.EndPositionTicks = GetTicks(sections[headers["End"]]); + subEvent.Text = string.Join(",", sections.Skip(headers["Text"])); + subEvent.Text = Regex.Replace(subEvent.Text, @"\{(\\[\w]+\(?([\w\d]+,?)+\)?)+\}", string.Empty, RegexOptions.IgnoreCase); + subEvent.Text = Regex.Replace(subEvent.Text, @"\\N", "<br />", RegexOptions.IgnoreCase); + + trackInfo.TrackEvents.Add(subEvent); + } + } + return trackInfo; + } + + long GetTicks(string time) + { + TimeSpan span; + return TimeSpan.TryParseExact(time, @"h\:mm\:ss\.ff", _usCulture, out span) + ? span.Ticks: 0; + } + + private Dictionary<string,int> ParseFieldHeaders(string line) { + var fields = line.Substring(8).Split(',').Select(x=>x.Trim()).ToList(); + + var result = new Dictionary<string, int> { + {"Start", fields.IndexOf("Start")}, + {"End", fields.IndexOf("End")}, + {"Text", fields.IndexOf("Text")} + }; + return result; + } + } +} |
