SsaParser.cs 17 KB

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