SrtParser.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Text.RegularExpressions;
  6. namespace MediaBrowser.MediaEncoding.Subtitles
  7. {
  8. public class SrtParser : ISubtitleParser
  9. {
  10. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  11. public SubtitleTrackInfo Parse(Stream stream) {
  12. var trackInfo = new SubtitleTrackInfo();
  13. using ( var reader = new StreamReader(stream))
  14. {
  15. string line;
  16. while ((line = reader.ReadLine()) != null)
  17. {
  18. if (string.IsNullOrWhiteSpace(line))
  19. {
  20. continue;
  21. }
  22. var subEvent = new SubtitleTrackEvent {Id = line};
  23. line = reader.ReadLine();
  24. var time = Regex.Split(line, @"[\t ]*-->[\t ]*");
  25. subEvent.StartPositionTicks = GetTicks(time[0]);
  26. var endTime = time[1];
  27. var idx = endTime.IndexOf(" ", StringComparison.Ordinal);
  28. if (idx > 0)
  29. endTime = endTime.Substring(0, idx);
  30. subEvent.EndPositionTicks = GetTicks(endTime);
  31. var multiline = new List<string>();
  32. while ((line = reader.ReadLine()) != null)
  33. {
  34. if (string.IsNullOrEmpty(line))
  35. {
  36. break;
  37. }
  38. multiline.Add(line);
  39. }
  40. subEvent.Text = string.Join(@"\N", multiline);
  41. subEvent.Text = Regex.Replace(subEvent.Text, @"\{(\\[\w]+\(?([\w\d]+,?)+\)?)+\}", string.Empty, RegexOptions.IgnoreCase);
  42. subEvent.Text = Regex.Replace(subEvent.Text, "<", "&lt;", RegexOptions.IgnoreCase);
  43. subEvent.Text = Regex.Replace(subEvent.Text, ">", "&gt;", RegexOptions.IgnoreCase);
  44. subEvent.Text = Regex.Replace(subEvent.Text, "&lt;(\\/?(font|b|u|i|s))((\\s+(\\w|\\w[\\w\\-]*\\w)(\\s*=\\s*(?:\\\".*?\\\"|'.*?'|[^'\\\">\\s]+))?)+\\s*|\\s*)(\\/?)&gt;", "<$1$3$7>", RegexOptions.IgnoreCase);
  45. subEvent.Text = Regex.Replace(subEvent.Text, @"\\N", "<br />",RegexOptions.IgnoreCase);
  46. trackInfo.TrackEvents.Add(subEvent);
  47. }
  48. }
  49. return trackInfo;
  50. }
  51. long GetTicks(string time) {
  52. TimeSpan span;
  53. return TimeSpan.TryParseExact(time, @"hh\:mm\:ss\.fff", _usCulture, out span)
  54. ? span.Ticks
  55. : (TimeSpan.TryParseExact(time, @"hh\:mm\:ss\,fff", _usCulture, out span)
  56. ? span.Ticks : 0);
  57. }
  58. }
  59. }