SsaParser.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. namespace MediaBrowser.MediaEncoding.Subtitles
  8. {
  9. public class SsaParser : ISubtitleParser
  10. {
  11. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  12. public SubtitleTrackInfo Parse(Stream stream)
  13. {
  14. var trackInfo = new SubtitleTrackInfo();
  15. var eventIndex = 1;
  16. using (var reader = new StreamReader(stream))
  17. {
  18. string line;
  19. while (reader.ReadLine() != "[Events]")
  20. {}
  21. var headers = ParseFieldHeaders(reader.ReadLine());
  22. while ((line = reader.ReadLine()) != null)
  23. {
  24. if (string.IsNullOrWhiteSpace(line))
  25. {
  26. continue;
  27. }
  28. if(line.StartsWith("["))
  29. break;
  30. if(string.IsNullOrEmpty(line))
  31. continue;
  32. var subEvent = new SubtitleTrackEvent { Id = eventIndex.ToString(_usCulture) };
  33. eventIndex++;
  34. var sections = line.Substring(10).Split(',');
  35. subEvent.StartPositionTicks = GetTicks(sections[headers["Start"]]);
  36. subEvent.EndPositionTicks = GetTicks(sections[headers["End"]]);
  37. subEvent.Text = string.Join(",", sections.Skip(headers["Text"]));
  38. subEvent.Text = Regex.Replace(subEvent.Text, @"\{(\\[\w]+\(?([\w\d]+,?)+\)?)+\}", string.Empty, RegexOptions.IgnoreCase);
  39. subEvent.Text = Regex.Replace(subEvent.Text, @"\\N", "<br />", RegexOptions.IgnoreCase);
  40. trackInfo.TrackEvents.Add(subEvent);
  41. }
  42. }
  43. return trackInfo;
  44. }
  45. long GetTicks(string time)
  46. {
  47. TimeSpan span;
  48. return TimeSpan.TryParseExact(time, @"h\:mm\:ss\.ff", _usCulture, out span)
  49. ? span.Ticks: 0;
  50. }
  51. private Dictionary<string,int> ParseFieldHeaders(string line) {
  52. var fields = line.Substring(8).Split(',').Select(x=>x.Trim()).ToList();
  53. var result = new Dictionary<string, int> {
  54. {"Start", fields.IndexOf("Start")},
  55. {"End", fields.IndexOf("End")},
  56. {"Text", fields.IndexOf("Text")}
  57. };
  58. return result;
  59. }
  60. }
  61. }