SsaParser.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Threading;
  6. using MediaBrowser.Model.Extensions;
  7. using MediaBrowser.Model.MediaInfo;
  8. namespace MediaBrowser.MediaEncoding.Subtitles
  9. {
  10. /// <summary>
  11. /// Credit to https://github.com/SubtitleEdit/subtitleedit/blob/a299dc4407a31796364cc6ad83f0d3786194ba22/src/Logic/SubtitleFormats/SubStationAlpha.cs
  12. /// </summary>
  13. public class SsaParser : ISubtitleParser
  14. {
  15. public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken)
  16. {
  17. var trackInfo = new SubtitleTrackInfo();
  18. var trackEvents = new List<SubtitleTrackEvent>();
  19. using (var reader = new StreamReader(stream))
  20. {
  21. bool eventsStarted = false;
  22. string[] format = "Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text".Split(',');
  23. int indexLayer = 0;
  24. int indexStart = 1;
  25. int indexEnd = 2;
  26. int indexStyle = 3;
  27. int indexName = 4;
  28. int indexEffect = 8;
  29. int indexText = 9;
  30. int lineNumber = 0;
  31. var header = new StringBuilder();
  32. string line;
  33. while ((line = reader.ReadLine()) != null)
  34. {
  35. cancellationToken.ThrowIfCancellationRequested();
  36. lineNumber++;
  37. if (!eventsStarted)
  38. header.AppendLine(line);
  39. if (line.Trim().ToLower() == "[events]")
  40. {
  41. eventsStarted = true;
  42. }
  43. else if (!string.IsNullOrEmpty(line) && line.Trim().StartsWith(";"))
  44. {
  45. // skip comment lines
  46. }
  47. else if (eventsStarted && line.Trim().Length > 0)
  48. {
  49. string s = line.Trim().ToLower();
  50. if (s.StartsWith("format:"))
  51. {
  52. if (line.Length > 10)
  53. {
  54. format = line.ToLower().Substring(8).Split(',');
  55. for (int i = 0; i < format.Length; i++)
  56. {
  57. if (format[i].Trim().ToLower() == "layer")
  58. indexLayer = i;
  59. else if (format[i].Trim().ToLower() == "start")
  60. indexStart = i;
  61. else if (format[i].Trim().ToLower() == "end")
  62. indexEnd = i;
  63. else if (format[i].Trim().ToLower() == "text")
  64. indexText = i;
  65. else if (format[i].Trim().ToLower() == "effect")
  66. indexEffect = i;
  67. else if (format[i].Trim().ToLower() == "style")
  68. indexStyle = i;
  69. }
  70. }
  71. }
  72. else if (!string.IsNullOrEmpty(s))
  73. {
  74. string text = string.Empty;
  75. string start = string.Empty;
  76. string end = string.Empty;
  77. string style = string.Empty;
  78. string layer = string.Empty;
  79. string effect = string.Empty;
  80. string name = string.Empty;
  81. string[] splittedLine;
  82. if (s.StartsWith("dialogue:"))
  83. splittedLine = line.Substring(10).Split(',');
  84. else
  85. splittedLine = line.Split(',');
  86. for (int i = 0; i < splittedLine.Length; i++)
  87. {
  88. if (i == indexStart)
  89. start = splittedLine[i].Trim();
  90. else if (i == indexEnd)
  91. end = splittedLine[i].Trim();
  92. else if (i == indexLayer)
  93. layer = splittedLine[i];
  94. else if (i == indexEffect)
  95. effect = splittedLine[i];
  96. else if (i == indexText)
  97. text = splittedLine[i];
  98. else if (i == indexStyle)
  99. style = splittedLine[i];
  100. else if (i == indexName)
  101. name = splittedLine[i];
  102. else if (i > indexText)
  103. text += "," + splittedLine[i];
  104. }
  105. try
  106. {
  107. var p = new SubtitleTrackEvent();
  108. p.StartPositionTicks = GetTimeCodeFromString(start);
  109. p.EndPositionTicks = GetTimeCodeFromString(end);
  110. p.Text = GetFormattedText(text);
  111. trackEvents.Add(p);
  112. }
  113. catch
  114. {
  115. }
  116. }
  117. }
  118. }
  119. //if (header.Length > 0)
  120. //subtitle.Header = header.ToString();
  121. //subtitle.Renumber(1);
  122. }
  123. trackInfo.TrackEvents = trackEvents.ToArray();
  124. return trackInfo;
  125. }
  126. private static long GetTimeCodeFromString(string time)
  127. {
  128. // h:mm:ss.cc
  129. string[] timeCode = time.Split(':', '.');
  130. return new TimeSpan(0, int.Parse(timeCode[0]),
  131. int.Parse(timeCode[1]),
  132. int.Parse(timeCode[2]),
  133. int.Parse(timeCode[3]) * 10).Ticks;
  134. }
  135. public static string GetFormattedText(string text)
  136. {
  137. text = text.Replace("\\n", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase);
  138. bool italic = false;
  139. for (int i = 0; i < 10; i++) // just look ten times...
  140. {
  141. if (text.Contains(@"{\fn"))
  142. {
  143. int start = text.IndexOf(@"{\fn");
  144. int end = text.IndexOf('}', start);
  145. if (end > 0 && !text.Substring(start).StartsWith("{\\fn}"))
  146. {
  147. string fontName = text.Substring(start + 4, end - (start + 4));
  148. string extraTags = string.Empty;
  149. CheckAndAddSubTags(ref fontName, ref extraTags, out italic);
  150. text = text.Remove(start, end - start + 1);
  151. if (italic)
  152. text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + "><i>");
  153. else
  154. text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + ">");
  155. int indexOfEndTag = text.IndexOf("{\\fn}", start);
  156. if (indexOfEndTag > 0)
  157. text = text.Remove(indexOfEndTag, "{\\fn}".Length).Insert(indexOfEndTag, "</font>");
  158. else
  159. text += "</font>";
  160. }
  161. }
  162. if (text.Contains(@"{\fs"))
  163. {
  164. int start = text.IndexOf(@"{\fs");
  165. int end = text.IndexOf('}', start);
  166. if (end > 0 && !text.Substring(start).StartsWith("{\\fs}"))
  167. {
  168. string fontSize = text.Substring(start + 4, end - (start + 4));
  169. string extraTags = string.Empty;
  170. CheckAndAddSubTags(ref fontSize, ref extraTags, out italic);
  171. if (IsInteger(fontSize))
  172. {
  173. text = text.Remove(start, end - start + 1);
  174. if (italic)
  175. text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + "><i>");
  176. else
  177. text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + ">");
  178. int indexOfEndTag = text.IndexOf("{\\fs}", start);
  179. if (indexOfEndTag > 0)
  180. text = text.Remove(indexOfEndTag, "{\\fs}".Length).Insert(indexOfEndTag, "</font>");
  181. else
  182. text += "</font>";
  183. }
  184. }
  185. }
  186. if (text.Contains(@"{\c"))
  187. {
  188. int start = text.IndexOf(@"{\c");
  189. int end = text.IndexOf('}', start);
  190. if (end > 0 && !text.Substring(start).StartsWith("{\\c}"))
  191. {
  192. string color = text.Substring(start + 4, end - (start + 4));
  193. string extraTags = string.Empty;
  194. CheckAndAddSubTags(ref color, ref extraTags, out italic);
  195. color = color.Replace("&", string.Empty).TrimStart('H');
  196. color = color.PadLeft(6, '0');
  197. // switch to rrggbb from bbggrr
  198. color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
  199. color = color.ToLower();
  200. text = text.Remove(start, end - start + 1);
  201. if (italic)
  202. text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
  203. else
  204. text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
  205. int indexOfEndTag = text.IndexOf("{\\c}", start);
  206. if (indexOfEndTag > 0)
  207. text = text.Remove(indexOfEndTag, "{\\c}".Length).Insert(indexOfEndTag, "</font>");
  208. else
  209. text += "</font>";
  210. }
  211. }
  212. if (text.Contains(@"{\1c")) // "1" specifices primary color
  213. {
  214. int start = text.IndexOf(@"{\1c");
  215. int end = text.IndexOf('}', start);
  216. if (end > 0 && !text.Substring(start).StartsWith("{\\1c}"))
  217. {
  218. string color = text.Substring(start + 5, end - (start + 5));
  219. string extraTags = string.Empty;
  220. CheckAndAddSubTags(ref color, ref extraTags, out italic);
  221. color = color.Replace("&", string.Empty).TrimStart('H');
  222. color = color.PadLeft(6, '0');
  223. // switch to rrggbb from bbggrr
  224. color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
  225. color = color.ToLower();
  226. text = text.Remove(start, end - start + 1);
  227. if (italic)
  228. text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
  229. else
  230. text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
  231. text += "</font>";
  232. }
  233. }
  234. }
  235. text = text.Replace(@"{\i1}", "<i>");
  236. text = text.Replace(@"{\i0}", "</i>");
  237. text = text.Replace(@"{\i}", "</i>");
  238. if (CountTagInText(text, "<i>") > CountTagInText(text, "</i>"))
  239. text += "</i>";
  240. text = text.Replace(@"{\u1}", "<u>");
  241. text = text.Replace(@"{\u0}", "</u>");
  242. text = text.Replace(@"{\u}", "</u>");
  243. if (CountTagInText(text, "<u>") > CountTagInText(text, "</u>"))
  244. text += "</u>";
  245. text = text.Replace(@"{\b1}", "<b>");
  246. text = text.Replace(@"{\b0}", "</b>");
  247. text = text.Replace(@"{\b}", "</b>");
  248. if (CountTagInText(text, "<b>") > CountTagInText(text, "</b>"))
  249. text += "</b>";
  250. return text;
  251. }
  252. private static bool IsInteger(string s)
  253. {
  254. if (int.TryParse(s, out var i))
  255. return true;
  256. return false;
  257. }
  258. private static int CountTagInText(string text, string tag)
  259. {
  260. int count = 0;
  261. int index = text.IndexOf(tag);
  262. while (index >= 0)
  263. {
  264. count++;
  265. if (index == text.Length)
  266. return count;
  267. index = text.IndexOf(tag, index + 1);
  268. }
  269. return count;
  270. }
  271. private static void CheckAndAddSubTags(ref string tagName, ref string extraTags, out bool italic)
  272. {
  273. italic = false;
  274. int indexOfSPlit = tagName.IndexOf(@"\");
  275. if (indexOfSPlit > 0)
  276. {
  277. string rest = tagName.Substring(indexOfSPlit).TrimStart('\\');
  278. tagName = tagName.Remove(indexOfSPlit);
  279. for (int i = 0; i < 10; i++)
  280. {
  281. if (rest.StartsWith("fs") && rest.Length > 2)
  282. {
  283. indexOfSPlit = rest.IndexOf(@"\");
  284. string fontSize = rest;
  285. if (indexOfSPlit > 0)
  286. {
  287. fontSize = rest.Substring(0, indexOfSPlit);
  288. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  289. }
  290. else
  291. {
  292. rest = string.Empty;
  293. }
  294. extraTags += " size=\"" + fontSize.Substring(2) + "\"";
  295. }
  296. else if (rest.StartsWith("fn") && rest.Length > 2)
  297. {
  298. indexOfSPlit = rest.IndexOf(@"\");
  299. string fontName = rest;
  300. if (indexOfSPlit > 0)
  301. {
  302. fontName = rest.Substring(0, indexOfSPlit);
  303. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  304. }
  305. else
  306. {
  307. rest = string.Empty;
  308. }
  309. extraTags += " face=\"" + fontName.Substring(2) + "\"";
  310. }
  311. else if (rest.StartsWith("c") && rest.Length > 2)
  312. {
  313. indexOfSPlit = rest.IndexOf(@"\");
  314. string fontColor = rest;
  315. if (indexOfSPlit > 0)
  316. {
  317. fontColor = rest.Substring(0, indexOfSPlit);
  318. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  319. }
  320. else
  321. {
  322. rest = string.Empty;
  323. }
  324. string color = fontColor.Substring(2);
  325. color = color.Replace("&", string.Empty).TrimStart('H');
  326. color = color.PadLeft(6, '0');
  327. // switch to rrggbb from bbggrr
  328. color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
  329. color = color.ToLower();
  330. extraTags += " color=\"" + color + "\"";
  331. }
  332. else if (rest.StartsWith("i1") && rest.Length > 1)
  333. {
  334. indexOfSPlit = rest.IndexOf(@"\");
  335. italic = true;
  336. if (indexOfSPlit > 0)
  337. {
  338. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  339. }
  340. else
  341. {
  342. rest = string.Empty;
  343. }
  344. }
  345. else if (rest.Length > 0 && rest.Contains("\\"))
  346. {
  347. indexOfSPlit = rest.IndexOf(@"\");
  348. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  349. }
  350. }
  351. }
  352. }
  353. }
  354. }