SrtParser.cs 3.1 KB

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