SsaParser.cs 2.8 KB

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