SsaParser.cs 17 KB

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