SsaParser.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. using System;
  2. using System.Collections.Generic;
  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. /// <inheritdoc />
  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. {
  39. header.AppendLine(line);
  40. }
  41. if (string.Equals(line.Trim(), "[events]", StringComparison.OrdinalIgnoreCase))
  42. {
  43. eventsStarted = true;
  44. }
  45. else if (!string.IsNullOrEmpty(line) && line.Trim().StartsWith(";"))
  46. {
  47. // skip comment lines
  48. }
  49. else if (eventsStarted && line.Trim().Length > 0)
  50. {
  51. string s = line.Trim().ToLowerInvariant();
  52. if (s.StartsWith("format:"))
  53. {
  54. if (line.Length > 10)
  55. {
  56. format = line.ToLowerInvariant().Substring(8).Split(',');
  57. for (int i = 0; i < format.Length; i++)
  58. {
  59. if (string.Equals(format[i].Trim(), "layer", StringComparison.OrdinalIgnoreCase))
  60. {
  61. indexLayer = i;
  62. }
  63. else if (string.Equals(format[i].Trim(), "start", StringComparison.OrdinalIgnoreCase))
  64. {
  65. indexStart = i;
  66. }
  67. else if (string.Equals(format[i].Trim(), "end", StringComparison.OrdinalIgnoreCase))
  68. {
  69. indexEnd = i;
  70. }
  71. else if (string.Equals(format[i].Trim(), "text", StringComparison.OrdinalIgnoreCase))
  72. {
  73. indexText = i;
  74. }
  75. else if (string.Equals(format[i].Trim(), "effect", StringComparison.OrdinalIgnoreCase))
  76. {
  77. indexEffect = i;
  78. }
  79. else if (string.Equals(format[i].Trim(), "style", StringComparison.OrdinalIgnoreCase))
  80. {
  81. indexStyle = i;
  82. }
  83. }
  84. }
  85. }
  86. else if (!string.IsNullOrEmpty(s))
  87. {
  88. string text = string.Empty;
  89. string start = string.Empty;
  90. string end = string.Empty;
  91. string style = string.Empty;
  92. string layer = string.Empty;
  93. string effect = string.Empty;
  94. string name = string.Empty;
  95. string[] splittedLine;
  96. if (s.StartsWith("dialogue:"))
  97. {
  98. splittedLine = line.Substring(10).Split(',');
  99. }
  100. else
  101. {
  102. splittedLine = line.Split(',');
  103. }
  104. for (int i = 0; i < splittedLine.Length; i++)
  105. {
  106. if (i == indexStart)
  107. {
  108. start = splittedLine[i].Trim();
  109. }
  110. else if (i == indexEnd)
  111. {
  112. end = splittedLine[i].Trim();
  113. }
  114. else if (i == indexLayer)
  115. {
  116. layer = splittedLine[i];
  117. }
  118. else if (i == indexEffect)
  119. {
  120. effect = splittedLine[i];
  121. }
  122. else if (i == indexText)
  123. {
  124. text = splittedLine[i];
  125. }
  126. else if (i == indexStyle)
  127. {
  128. style = splittedLine[i];
  129. }
  130. else if (i == indexName)
  131. {
  132. name = splittedLine[i];
  133. }
  134. else if (i > indexText)
  135. {
  136. text += "," + splittedLine[i];
  137. }
  138. }
  139. try
  140. {
  141. var p = new SubtitleTrackEvent();
  142. p.StartPositionTicks = GetTimeCodeFromString(start);
  143. p.EndPositionTicks = GetTimeCodeFromString(end);
  144. p.Text = GetFormattedText(text);
  145. trackEvents.Add(p);
  146. }
  147. catch
  148. {
  149. }
  150. }
  151. }
  152. }
  153. // if (header.Length > 0)
  154. // subtitle.Header = header.ToString();
  155. // subtitle.Renumber(1);
  156. }
  157. trackInfo.TrackEvents = trackEvents.ToArray();
  158. return trackInfo;
  159. }
  160. private static long GetTimeCodeFromString(string time)
  161. {
  162. // h:mm:ss.cc
  163. string[] timeCode = time.Split(':', '.');
  164. return new TimeSpan(0, int.Parse(timeCode[0]),
  165. int.Parse(timeCode[1]),
  166. int.Parse(timeCode[2]),
  167. int.Parse(timeCode[3]) * 10).Ticks;
  168. }
  169. private static string GetFormattedText(string text)
  170. {
  171. text = text.Replace("\\n", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase);
  172. for (int i = 0; i < 10; i++) // just look ten times...
  173. {
  174. if (text.Contains(@"{\fn"))
  175. {
  176. int start = text.IndexOf(@"{\fn");
  177. int end = text.IndexOf('}', start);
  178. if (end > 0 && !text.Substring(start).StartsWith("{\\fn}"))
  179. {
  180. string fontName = text.Substring(start + 4, end - (start + 4));
  181. string extraTags = string.Empty;
  182. CheckAndAddSubTags(ref fontName, ref extraTags, out bool italic);
  183. text = text.Remove(start, end - start + 1);
  184. if (italic)
  185. {
  186. text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + "><i>");
  187. }
  188. else
  189. {
  190. text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + ">");
  191. }
  192. int indexOfEndTag = text.IndexOf("{\\fn}", start);
  193. if (indexOfEndTag > 0)
  194. {
  195. text = text.Remove(indexOfEndTag, "{\\fn}".Length).Insert(indexOfEndTag, "</font>");
  196. }
  197. else
  198. {
  199. text += "</font>";
  200. }
  201. }
  202. }
  203. if (text.Contains(@"{\fs"))
  204. {
  205. int start = text.IndexOf(@"{\fs");
  206. int end = text.IndexOf('}', start);
  207. if (end > 0 && !text.Substring(start).StartsWith("{\\fs}"))
  208. {
  209. string fontSize = text.Substring(start + 4, end - (start + 4));
  210. string extraTags = string.Empty;
  211. CheckAndAddSubTags(ref fontSize, ref extraTags, out bool italic);
  212. if (IsInteger(fontSize))
  213. {
  214. text = text.Remove(start, end - start + 1);
  215. if (italic)
  216. {
  217. text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + "><i>");
  218. }
  219. else
  220. {
  221. text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + ">");
  222. }
  223. int indexOfEndTag = text.IndexOf("{\\fs}", start);
  224. if (indexOfEndTag > 0)
  225. {
  226. text = text.Remove(indexOfEndTag, "{\\fs}".Length).Insert(indexOfEndTag, "</font>");
  227. }
  228. else
  229. {
  230. text += "</font>";
  231. }
  232. }
  233. }
  234. }
  235. if (text.Contains(@"{\c"))
  236. {
  237. int start = text.IndexOf(@"{\c");
  238. int end = text.IndexOf('}', start);
  239. if (end > 0 && !text.Substring(start).StartsWith("{\\c}"))
  240. {
  241. string color = text.Substring(start + 4, end - (start + 4));
  242. string extraTags = string.Empty;
  243. CheckAndAddSubTags(ref color, ref extraTags, out bool italic);
  244. color = color.Replace("&", string.Empty).TrimStart('H');
  245. color = color.PadLeft(6, '0');
  246. // switch to rrggbb from bbggrr
  247. color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
  248. color = color.ToLowerInvariant();
  249. text = text.Remove(start, end - start + 1);
  250. if (italic)
  251. {
  252. text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
  253. }
  254. else
  255. {
  256. text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
  257. }
  258. int indexOfEndTag = text.IndexOf("{\\c}", start);
  259. if (indexOfEndTag > 0)
  260. {
  261. text = text.Remove(indexOfEndTag, "{\\c}".Length).Insert(indexOfEndTag, "</font>");
  262. }
  263. else
  264. {
  265. text += "</font>";
  266. }
  267. }
  268. }
  269. if (text.Contains(@"{\1c")) // "1" specifices primary color
  270. {
  271. int start = text.IndexOf(@"{\1c");
  272. int end = text.IndexOf('}', start);
  273. if (end > 0 && !text.Substring(start).StartsWith("{\\1c}"))
  274. {
  275. string color = text.Substring(start + 5, end - (start + 5));
  276. string extraTags = string.Empty;
  277. CheckAndAddSubTags(ref color, ref extraTags, out bool italic);
  278. color = color.Replace("&", string.Empty).TrimStart('H');
  279. color = color.PadLeft(6, '0');
  280. // switch to rrggbb from bbggrr
  281. color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
  282. color = color.ToLowerInvariant();
  283. text = text.Remove(start, end - start + 1);
  284. if (italic)
  285. {
  286. text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
  287. }
  288. else
  289. {
  290. text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
  291. }
  292. text += "</font>";
  293. }
  294. }
  295. }
  296. text = text.Replace(@"{\i1}", "<i>");
  297. text = text.Replace(@"{\i0}", "</i>");
  298. text = text.Replace(@"{\i}", "</i>");
  299. if (CountTagInText(text, "<i>") > CountTagInText(text, "</i>"))
  300. {
  301. text += "</i>";
  302. }
  303. text = text.Replace(@"{\u1}", "<u>");
  304. text = text.Replace(@"{\u0}", "</u>");
  305. text = text.Replace(@"{\u}", "</u>");
  306. if (CountTagInText(text, "<u>") > CountTagInText(text, "</u>"))
  307. {
  308. text += "</u>";
  309. }
  310. text = text.Replace(@"{\b1}", "<b>");
  311. text = text.Replace(@"{\b0}", "</b>");
  312. text = text.Replace(@"{\b}", "</b>");
  313. if (CountTagInText(text, "<b>") > CountTagInText(text, "</b>"))
  314. {
  315. text += "</b>";
  316. }
  317. return text;
  318. }
  319. private static bool IsInteger(string s)
  320. => int.TryParse(s, out _);
  321. private static int CountTagInText(string text, string tag)
  322. {
  323. int count = 0;
  324. int index = text.IndexOf(tag);
  325. while (index >= 0)
  326. {
  327. count++;
  328. if (index == text.Length)
  329. {
  330. return count;
  331. }
  332. index = text.IndexOf(tag, index + 1);
  333. }
  334. return count;
  335. }
  336. private static void CheckAndAddSubTags(ref string tagName, ref string extraTags, out bool italic)
  337. {
  338. italic = false;
  339. int indexOfSPlit = tagName.IndexOf(@"\");
  340. if (indexOfSPlit > 0)
  341. {
  342. string rest = tagName.Substring(indexOfSPlit).TrimStart('\\');
  343. tagName = tagName.Remove(indexOfSPlit);
  344. for (int i = 0; i < 10; i++)
  345. {
  346. if (rest.StartsWith("fs") && rest.Length > 2)
  347. {
  348. indexOfSPlit = rest.IndexOf(@"\");
  349. string fontSize = rest;
  350. if (indexOfSPlit > 0)
  351. {
  352. fontSize = rest.Substring(0, indexOfSPlit);
  353. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  354. }
  355. else
  356. {
  357. rest = string.Empty;
  358. }
  359. extraTags += " size=\"" + fontSize.Substring(2) + "\"";
  360. }
  361. else if (rest.StartsWith("fn") && rest.Length > 2)
  362. {
  363. indexOfSPlit = rest.IndexOf(@"\");
  364. string fontName = rest;
  365. if (indexOfSPlit > 0)
  366. {
  367. fontName = rest.Substring(0, indexOfSPlit);
  368. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  369. }
  370. else
  371. {
  372. rest = string.Empty;
  373. }
  374. extraTags += " face=\"" + fontName.Substring(2) + "\"";
  375. }
  376. else if (rest.StartsWith("c") && rest.Length > 2)
  377. {
  378. indexOfSPlit = rest.IndexOf(@"\");
  379. string fontColor = rest;
  380. if (indexOfSPlit > 0)
  381. {
  382. fontColor = rest.Substring(0, indexOfSPlit);
  383. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  384. }
  385. else
  386. {
  387. rest = string.Empty;
  388. }
  389. string color = fontColor.Substring(2);
  390. color = color.Replace("&", string.Empty).TrimStart('H');
  391. color = color.PadLeft(6, '0');
  392. // switch to rrggbb from bbggrr
  393. color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
  394. color = color.ToLowerInvariant();
  395. extraTags += " color=\"" + color + "\"";
  396. }
  397. else if (rest.StartsWith("i1") && rest.Length > 1)
  398. {
  399. indexOfSPlit = rest.IndexOf(@"\");
  400. italic = true;
  401. if (indexOfSPlit > 0)
  402. {
  403. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  404. }
  405. else
  406. {
  407. rest = string.Empty;
  408. }
  409. }
  410. else if (rest.Length > 0 && rest.Contains("\\"))
  411. {
  412. indexOfSPlit = rest.IndexOf(@"\");
  413. rest = rest.Substring(indexOfSPlit).TrimStart('\\');
  414. }
  415. }
  416. }
  417. }
  418. }
  419. }