using Nikse.SubtitleEdit.Core.Common; using SkiaSharp; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Nikse.SubtitleEdit.Core.SubtitleFormats { /// /// https://w3c.github.io/webvtt/ /// public partial class WebVTT : SubtitleFormat { #if NET7_0_OR_GREATER [GeneratedRegex(@"^-?\d+:-?\d+:-?\d+\.-?\d+\s*-->\s*-?\d+:-?\d+:-?\d+\.-?\d+")] private static partial Regex RegexTimeCodesGen(); private static readonly Regex RegexTimeCodes = RegexTimeCodesGen(); [GeneratedRegex(@"^-?\d+:-?\d+\.-?\d+\s*-->\s*-?\d+:-?\d+:-?\d+\.-?\d+")] private static partial Regex RegexTimeCodesMiddleGen(); private static readonly Regex RegexTimeCodesMiddle = RegexTimeCodesMiddleGen(); [GeneratedRegex(@"^-?\d+:-?\d+\.-?\d+\s*-->\s*-?\d+:-?\d+\.-?\d+")] private static partial Regex RegexTimeCodesShortGen(); private static readonly Regex RegexTimeCodesShort = RegexTimeCodesShortGen(); [GeneratedRegex(@"^-?\d+:-?\d+:-?\d+\.-?\d+\s*-->\s*-?\d+:-?\d+\.-?\d+")] private static partial Regex RegexTimeCodesEndShortGen(); private static readonly Regex RegexTimeCodesEndShort = RegexTimeCodesEndShortGen(); [GeneratedRegex(@"-->\s*")] private static partial Regex RegexShortArrowGen(); private static readonly Regex RegexShortArrow = RegexShortArrowGen(); [GeneratedRegex(@"\")] private static partial Regex RegexRemoveCTagsGen(); private static readonly Regex RegexRemoveCTags = RegexRemoveCTagsGen(); [GeneratedRegex(@"\<\d+:\d+:\d+\.\d+\>")] // <00:00:10.049> private static partial Regex RegexRemoveTimeCodesGen(); private static readonly Regex RegexRemoveTimeCodes = RegexRemoveTimeCodesGen(); [GeneratedRegex(@"(\{\\an\d\})[\s\r\n]+")] private static partial Regex RegexTagsPlusWhiteSpaceGen(); private static readonly Regex RegexTagsPlusWhiteSpace = RegexTagsPlusWhiteSpaceGen(); [GeneratedRegex(@"::cue\(([a-zA-Z\._\-\d%#]*)\)\s*{")] private static partial Regex RegexCueLineGen(); private static readonly Regex RegexCueLine = RegexCueLineGen(); #else private static readonly Regex RegexTimeCodes = new Regex(@"^-?\d+:-?\d+:-?\d+\.-?\d+\s*-->\s*-?\d+:-?\d+:-?\d+\.-?\d+", RegexOptions.Compiled); private static readonly Regex RegexTimeCodesMiddle = new Regex(@"^-?\d+:-?\d+\.-?\d+\s*-->\s*-?\d+:-?\d+:-?\d+\.-?\d+", RegexOptions.Compiled); private static readonly Regex RegexTimeCodesShort = new Regex(@"^-?\d+:-?\d+\.-?\d+\s*-->\s*-?\d+:-?\d+\.-?\d+", RegexOptions.Compiled); private static readonly Regex RegexTimeCodesEndShort = new Regex(@"^-?\d+:-?\d+:-?\d+\.-?\d+\s*-->\s*-?\d+:-?\d+\.-?\d+", RegexOptions.Compiled); private static readonly Regex RegexShortArrow = new Regex(@"-->\s*", RegexOptions.Compiled); private static readonly Regex RegexRemoveCTags = new Regex(@"\", RegexOptions.Compiled); private static readonly Regex RegexRemoveTimeCodes = new Regex(@"\<\d+:\d+:\d+\.\d+\>", RegexOptions.Compiled); // <00:00:10.049> private static readonly Regex RegexTagsPlusWhiteSpace = new Regex(@"(\{\\an\d\})[\s\r\n]+", RegexOptions.Compiled); private static readonly Regex RegexCueLine = new Regex(@"::cue\(([a-zA-Z\._\-\d%#]*)\)\s*{", RegexOptions.Compiled); #endif public static readonly Dictionary DefaultColorClasses = new Dictionary { { "white", ColorUtils.FromArgb(255, 255, 255) }, { "lime", ColorUtils.FromArgb(0, 255, 0) }, { "cyan", ColorUtils.FromArgb(0, 255, 255) }, { "red", ColorUtils.FromArgb(255, 0, 0) }, { "yellow", ColorUtils.FromArgb(255, 255, 0) }, { "green", ColorUtils.FromArgb(0, 255, 0) }, { "magenta", ColorUtils.FromArgb(255, 0, 255) }, { "blue", ColorUtils.FromArgb(0, 0, 255) }, { "black", ColorUtils.FromArgb(0, 0, 0) }, }; private static readonly string[] KnownLanguages = new[] { "arabic", "hebrew", "simplifiedchinese", "traditionalchinese", "thai", "korean", "Japanese", "hungarian", "czech", "vietnamese" }; public override string Extension => ".vtt"; public override List AlternateExtensions => new List { ".webvtt" }; public const string NameOfFormat = "WebVTT"; public override string Name => NameOfFormat; // Carries the region of every cue, and the regions themselves in the header. public override bool HasPositionSupport => true; public override string ToText(Subtitle subtitle, string title) { const string timeCodeFormatHours = "{0:00}:{1:00}:{2:00}.{3:000}"; // hh:mm:ss.mmm const string paragraphWriteFormat = "{0} --> {1}{2}{5}{3}{4}{5}"; var sb = new StringBuilder(); if (subtitle.Header != null && subtitle.Header.StartsWith("WEBVTT", StringComparison.Ordinal)) { sb.AppendLine(subtitle.Header.Trim()); } else { sb.AppendLine("WEBVTT"); } sb.AppendLine(); foreach (var p in subtitle.Paragraphs) { var start = string.Format(timeCodeFormatHours, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds); var end = string.Format(timeCodeFormatHours, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds); var positionInfo = GetPositionInfoFromAssTag(p); var style = string.Empty; if (subtitle.Header != null && subtitle.Header.StartsWith("WEBVTT", StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(p.Region)) { positionInfo = $" region:{p.Region} {positionInfo}".Replace(" ", " ").TrimEnd(); } } sb.AppendLine(string.Format(paragraphWriteFormat, start, end, positionInfo, FormatText(p), style, Environment.NewLine)); } return sb.ToString().Trim(); } internal static string GetPositionInfoFromAssTag(Paragraph p) { string positionInfo; string currentTag = null; if (p.Text.StartsWith("{\\an1", StringComparison.Ordinal)) { positionInfo = Configuration.Settings.SubtitleSettings.WebVttCueAn1; currentTag = "{\\an1}"; } else if (p.Text.StartsWith("{\\an3", StringComparison.Ordinal)) { positionInfo = Configuration.Settings.SubtitleSettings.WebVttCueAn3; currentTag = "{\\an3}"; } else if (p.Text.StartsWith("{\\an4", StringComparison.Ordinal)) { positionInfo = Configuration.Settings.SubtitleSettings.WebVttCueAn4; currentTag = "{\\an4}"; } else if (p.Text.StartsWith("{\\an5", StringComparison.Ordinal)) { positionInfo = Configuration.Settings.SubtitleSettings.WebVttCueAn5; currentTag = "{\\an5}"; } else if (p.Text.StartsWith("{\\an6", StringComparison.Ordinal)) { positionInfo = Configuration.Settings.SubtitleSettings.WebVttCueAn6; currentTag = "{\\an6}"; } else if (p.Text.StartsWith("{\\an7", StringComparison.Ordinal)) { positionInfo = Configuration.Settings.SubtitleSettings.WebVttCueAn7; currentTag = "{\\an7}"; } else if (p.Text.StartsWith("{\\an8", StringComparison.Ordinal)) { positionInfo = Configuration.Settings.SubtitleSettings.WebVttCueAn8; currentTag = "{\\an8}"; } else if (p.Text.StartsWith("{\\an9", StringComparison.Ordinal)) { positionInfo = Configuration.Settings.SubtitleSettings.WebVttCueAn9; currentTag = "{\\an9}"; } else { positionInfo = Configuration.Settings.SubtitleSettings.WebVttCueAn2; } // The raw cue settings captured at load ("line:72.69% align:left position:44.90% size:10.21%") // are exact, while the WebVttCueAnX settings are coarse 3x3-grid defaults. Re-emit the raw // settings when they are still consistent with the current alignment tag (i.e. the user has // not changed the alignment since load), so line%/position% are not lost or grid-locked (#10209). if (!string.IsNullOrEmpty(p.Style) && !string.IsNullOrEmpty(GetPositionInfoRaw(p.Style)) && GetPositionInfo(p.Style) == (currentTag ?? string.Empty)) { // "region:" is written separately by the caller, so drop it here - otherwise a // cue that listed it after the other settings ("line:10% region:r1") is saved // with the region twice. positionInfo = RemoveCueSetting(p.Style, "region:").Trim(); } return (" " + positionInfo).TrimEnd(); } internal static string FormatText(Paragraph p) { var text = Utilities.RemoveSsaTags(p.Text); text = text.RemoveRecursiveLineBreaks(); text = ColorHtmlToWebVtt(text); text = EscapeEncodeText(text); return text; } public override void LoadSubtitle(Subtitle subtitle, List lines, string fileName) { _errorCount = 0; Paragraph p = null; var positionInfo = string.Empty; var hadEmptyLine = false; var numbers = 0; double addSeconds = 0; var noteOn = false; var styleOn = false; var regionOn = false; var header = new StringBuilder(); header.AppendLine("WEBVTT"); header.AppendLine(); for (var index = 0; index < lines.Count; index++) { var line = lines[index]; var next = string.Empty; var isNextTimeCode = false; if (index < lines.Count - 1) { next = lines[index + 1]; isNextTimeCode = next.Contains("-->"); } if (index == 0 && line.StartsWith("WEBVTT", StringComparison.Ordinal)) { header.Clear(); header.AppendLine(line); header.AppendLine(); continue; } if (index > 0 && string.IsNullOrEmpty(lines[index - 1]) && (line == "NOTE" || line.StartsWith("NOTE ", StringComparison.Ordinal))) { noteOn = true; if (subtitle.Paragraphs.Count == 0) { header.AppendLine(); header.AppendLine(); } } else if ((line == "STYLE" || line.StartsWith("STYLE ", StringComparison.Ordinal)) && subtitle.Paragraphs.Count == 0) { styleOn = true; header.AppendLine(); header.AppendLine(); } else if ((line == "REGION" || line.StartsWith("REGION ", StringComparison.Ordinal)) && subtitle.Paragraphs.Count == 0) { regionOn = true; header.AppendLine(); header.AppendLine(); } if (styleOn && !string.IsNullOrEmpty(line)) { header.AppendLine(line); continue; } if (regionOn && !string.IsNullOrEmpty(line)) { header.AppendLine(line); continue; } if (noteOn && !string.IsNullOrEmpty(line)) { if (subtitle.Paragraphs.Count == 0) { header.AppendLine(line); } continue; } if (index > 1) { if (Configuration.Settings.SubtitleSettings.WebVttUseMultipleXTimestampMap && line.StartsWith("X-TIMESTAMP-MAP=", StringComparison.OrdinalIgnoreCase) && line.IndexOf("MPEGTS:", StringComparison.OrdinalIgnoreCase) > 0) { addSeconds = GetXTimeStampSeconds(line); continue; } if (line == "WEBVTT") { // badly formatted web vtt file continue; } } noteOn = false; styleOn = false; regionOn = false; var s = line; var isTimeCode = line.Contains("-->"); if (isTimeCode && RegexTimeCodesMiddle.IsMatch(s)) { s = "00:" + s; // start is without hours, end is with hours } if (isTimeCode && RegexTimeCodesShort.IsMatch(s)) { // Both sides lack the hour part. Prefix the end time via the arrow // (regardless of spacing) and the start time via concatenation. s = "00:" + RegexShortArrow.Replace(s, "--> 00:", 1); } if (isTimeCode && RegexTimeCodesEndShort.IsMatch(s)) { s = RegexShortArrow.Replace(s, "--> 00:", 1); // start has hours, end is without hours } if (isNextTimeCode && Utilities.IsNumber(s) && p?.Text.Length > 0) { numbers++; } else if (index == 1 && s.StartsWith("X-TIMESTAMP-MAP=", StringComparison.OrdinalIgnoreCase) && s.IndexOf("MPEGTS:", StringComparison.OrdinalIgnoreCase) > 0) { addSeconds = GetXTimeStampSeconds(s); } else if (isTimeCode && RegexTimeCodes.IsMatch(s.TrimStart())) { if (p != null) { p.Text = p.Text.TrimEnd(); subtitle.Paragraphs.Add(p); } try { var parts = s.TrimStart().Replace("-->", "@").Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries); p = new Paragraph { StartTime = GetTimeCodeFromString(parts[0]), EndTime = GetTimeCodeFromString(parts[1]) }; p.StartTime.TotalMilliseconds += addSeconds * 1000; p.EndTime.TotalMilliseconds += addSeconds * 1000; positionInfo = GetPositionInfo(s); p.Style = GetPositionInfoRaw(s); p.Region = GetRegion(s); } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.Message); _errorCount++; p = null; } hadEmptyLine = false; } else if (p != null && hadEmptyLine && (RegexTimeCodesMiddle.IsMatch(next) || RegexTimeCodesShort.IsMatch(next) || RegexTimeCodesEndShort.IsMatch(next) || RegexTimeCodes.IsMatch(next))) { // can both be number or an "identifier" which can be text numbers++; } else if (p != null) { var text = positionInfo + line.Trim(); if (string.IsNullOrEmpty(text)) { hadEmptyLine = true; } if (string.IsNullOrEmpty(p.Text)) { p.Text = text + Environment.NewLine; } else { p.Text += text + Environment.NewLine; } positionInfo = string.Empty; } } if (p != null) { p.Text = p.Text.TrimEnd(); subtitle.Paragraphs.Add(p); } if (subtitle.Paragraphs.Count > 3 && numbers >= subtitle.Paragraphs.Count - 1 && lines[0] == "WEBVTT FILE") { // let format WebVTTFileWithLineNumber take the subtitle _errorCount = subtitle.Paragraphs.Count + 1; return; } foreach (var paragraph in subtitle.Paragraphs) { // paragraph.Text = ColorWebVttToHtml(paragraph.Text); paragraph.Text = EscapeDecodeText(paragraph.Text); paragraph.Text = RemoveWeirdRepeatingHeader(paragraph.Text); } // YouTube auto-generated captions are roll-up captions with per-word time codes, which // load as unreadable duplicated karaoke text - turn them into one cue per spoken line. if (WebVttAutoCaptionsCleaner.IsAutoCaptions(subtitle)) { WebVttAutoCaptionsCleaner.Clean(subtitle); } if (Configuration.Settings.SubtitleSettings.WebVttMergeLinesWithSameText) { var merged = MergeLinesSameTextUtils.MergeLinesWithSameTextInSubtitle(subtitle, false, 1); subtitle.Paragraphs.Clear(); subtitle.Paragraphs.AddRange(merged.Paragraphs); } // Merge consecutive cues with identical time codes (common in WebVTT as alternative to line breaks) - // but only where they sit together on screen: a caption pinned to the top over the dialogue // below it is two subtitles, not two rows of one. for (var i = subtitle.Paragraphs.Count - 2; i >= 0; i--) { var current = subtitle.Paragraphs[i]; var nextParagraph = subtitle.Paragraphs[i + 1]; if (current.StartTime.TotalMilliseconds == nextParagraph.StartTime.TotalMilliseconds && current.EndTime.TotalMilliseconds == nextParagraph.EndTime.TotalMilliseconds && current.Region == nextParagraph.Region && IsSameVerticalPlacement(current.Style, nextParagraph.Style)) { // An exact repeat (same times, same text - e.g. a concatenated/duplicated // segment) is a duplicate, not a second line: drop it instead of stacking it. if (current.Text != nextParagraph.Text) { current.Text = current.Text + Environment.NewLine + nextParagraph.Text; } subtitle.Paragraphs.RemoveAt(i + 1); } } subtitle.Renumber(); if (header.Length > 0) { subtitle.Header = header .ToString() .Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine) .Trim(); } } private static string RemoveWeirdRepeatingHeader(string input) { var text = input; text = text.FixExtraSpaces(); if (text.Contains(Environment.NewLine + "WEBVTT")) { if (text.TrimEnd().EndsWith('}') && text.Contains("STYLE")) { text = text.Remove(text.IndexOf(Environment.NewLine + "WEBVTT", StringComparison.Ordinal)).Trim(); } } else if (text.TrimEnd().EndsWith(Environment.NewLine + "WEBVTT", StringComparison.Ordinal)) { text = text.Remove(text.LastIndexOf(Environment.NewLine + "WEBVTT", StringComparison.Ordinal)).Trim(); } else if (text.Contains(Environment.NewLine + "STYLE" + Environment.NewLine)) { if (text.TrimEnd().EndsWith("}")) { text = text.Remove(text.IndexOf(Environment.NewLine + "STYLE" + Environment.NewLine, StringComparison.Ordinal)).Trim(); } } return text; } private static double GetXTimeStampSeconds(string input) { if (!Configuration.Settings.SubtitleSettings.WebVttUseXTimestampMap) { return 0; } var s = input.RemoveChar(' '); var subtractSeconds = 0d; var startIndex = s.IndexOf("LOCAL:", StringComparison.OrdinalIgnoreCase); var localSb = new StringBuilder(); for (var i = startIndex + 6; i < s.Length; i++) { var ch = s[i]; if (char.IsNumber(ch) || ch == ':' || ch == '.') { localSb.Append(ch); } else { break; } } var parts = localSb.ToString().Split(':', '.'); if (parts.Length == 3) { parts = ("00:" + localSb).Split(':', '.'); } if (parts.Length == 4) { subtractSeconds = DecodeTimeCodeMsFourParts(parts).TotalSeconds; } startIndex = s.IndexOf("MPEGTS:", StringComparison.OrdinalIgnoreCase); var tsSb = new StringBuilder(); for (int i = startIndex + 7; i < s.Length; i++) { var ch = s[i]; if (CharUtils.IsAsciiDigit(ch)) { tsSb.Append(ch); } else { break; } } if (tsSb.Length > 0 && long.TryParse(tsSb.ToString(), out var number)) { var seconds = (double)number / Configuration.Settings.SubtitleSettings.WebVttTimescale - subtractSeconds; if (seconds > 0 && seconds < 90000) // max 25 hours - or wrong timescale { return seconds; } } return 0; } /// /// A "line:" cue setting counts rows, not percent, and the WebVTT spec leaves the number of /// rows to the height of the video. Sixteen is the usual assumption - it is the one the /// "0 or -16 = top, 16 or -1 = bottom" reading of a line number is built on. /// private const double AssumedRowCount = 16.0; /// /// How far apart two cues may sit vertically and still be read as two rows of one caption. /// A row is only a few percent of the video tall, so this leaves room for a row or two of /// rounding while staying far below the gap between a caption at the top of the screen and /// the dialogue at the bottom. /// private const double SameVerticalPlacementMaxPercentApart = 15.0; /// /// Whether two cues sit close enough vertically to be two rows of one caption. /// Only a cue that says where it sits can rule the merge out, so cues without a usable /// "line:" setting keep merging exactly as they did before this check existed. /// private static bool IsSameVerticalPlacement(string cueSettings1, string cueSettings2) { return !TryGetVerticalPositionPercent(cueSettings1, out var percent1) || !TryGetVerticalPositionPercent(cueSettings2, out var percent2) || Math.Abs(percent1 - percent2) <= SameVerticalPlacementMaxPercentApart; } /// /// Reads the "line:" cue setting as a percentage down the video: 0 = top, 100 = bottom. /// Both forms are understood - a percentage, and a line number counting rows from the top /// (0 = top) or, when it is negative, from the bottom (-1 = bottom row). /// Returns false when the cue does not say, or says something we cannot read ("auto"). /// private static bool TryGetVerticalPositionPercent(string s, out double percent) { percent = 0; var line = GetTag(s, "line:"); if (string.IsNullOrEmpty(line)) { return false; } line = line.Trim(); // The spec allows an alignment suffix after a comma ("line:0,start"). GetTag only // strips it from the percent form ("line:10%,start"), so strip it here too - or the // line-number form with a suffix reads as unparsable and cannot rule a merge out. var comma = line.IndexOf(','); if (comma >= 0) { line = line.Substring(0, comma).TrimEnd(); } if (line.EndsWith('%')) { return double.TryParse(line.TrimEnd('%'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out percent); } if (!double.TryParse(line, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var lineNumber)) { return false; } percent = (lineNumber < 0 ? AssumedRowCount + lineNumber : lineNumber) * 100.0 / AssumedRowCount; return true; } internal static string GetPositionInfo(string s) { //position: x --- 0% = left, 100% = right (horizontal) //line: x --- 0 or -16 or 0% = top, 16 or -1 or 100% = bottom (vertical) var pos = GetTag(s, "position:"); var line = GetTag(s, "line:"); var positionInfo = string.Empty; var hAlignLeft = false; var hAlignRight = false; var vAlignTop = false; var vAlignMiddle = false; double number; if (!string.IsNullOrEmpty(pos) && pos.EndsWith('%') && double.TryParse(pos.TrimEnd('%'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out number)) { if (number < 25) { hAlignLeft = true; } else if (number > 75) { hAlignRight = true; } } if (!string.IsNullOrEmpty(line)) { line = line.Trim(); if (line.EndsWith('%')) { if (double.TryParse(line.TrimEnd('%'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out number)) { if (number < 25) { vAlignTop = true; } else if (number < 75) { vAlignMiddle = true; } } } else { if (double.TryParse(line, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out number)) { if (number >= 0 && number <= 7) { vAlignTop = true; // Positive numbers indicate top down } else if (number > 7 && number < 11) { vAlignMiddle = true; } } } } if (hAlignLeft) { if (vAlignTop) { return "{\\an7}"; } if (vAlignMiddle) { return "{\\an4}"; } return "{\\an1}"; } if (hAlignRight) { if (vAlignTop) { return "{\\an9}"; } if (vAlignMiddle) { return "{\\an6}"; } return "{\\an3}"; } if (vAlignTop) { return "{\\an8}"; } if (vAlignMiddle) { return "{\\an5}"; } return positionInfo; } internal static string GetPositionInfoRaw(string s) { //line: 72.69 % align:left position:44.90 % size:10.21 % var list = new List(); var idx = s.IndexOf("line:", StringComparison.Ordinal); if (idx >= 0) { list.Add(idx); } idx = s.IndexOf("align:", StringComparison.Ordinal); if (idx >= 0) { list.Add(idx); } idx = s.IndexOf("position:", StringComparison.Ordinal); if (idx >= 0) { list.Add(idx); } idx = s.IndexOf("size:", StringComparison.Ordinal); if (idx >= 0) { list.Add(idx); } if (list.Count == 0) { return string.Empty; } return s.Substring(list.Min(p => p)); } internal static string GetRegion(string s) { var region = GetTag(s, "region:"); return region; } /// /// Removes a "name:value" cue setting (and its trailing space) from a raw cue settings /// string, leaving the other settings untouched. /// internal static string RemoveCueSetting(string s, string tag) { if (string.IsNullOrEmpty(s)) { return s; } var pos = s.IndexOf(tag, StringComparison.Ordinal); if (pos < 0) { return s; } var end = s.IndexOf(' ', pos); var result = end < 0 ? s.Remove(pos) : s.Remove(pos, end - pos + 1); return result.Trim(); } private static string GetTag(string s, string tag) { if (s == null) { return null; } var pos = s.IndexOf(tag, StringComparison.Ordinal); if (pos >= 0) { var v = s.Substring(pos + tag.Length).Trim(); var end = v.IndexOf("%,", StringComparison.Ordinal); if (end >= 0) { v = v.Remove(end + 1); } end = v.IndexOf(' '); if (end >= 0) { v = v.Remove(end); } return v; } return null; } public override void RemoveNativeFormatting(Subtitle subtitle, SubtitleFormat newFormat) { var cueStyles = GetCueStyles(subtitle.Header); var italicStyles = GetStylesWith(cueStyles, "font-style:italic;"); var boldStyles = GetStylesWith(cueStyles, "font-weight:bold;"); var skipColor = HasOnlyDefaultTextColor(subtitle, cueStyles); foreach (var p in subtitle.Paragraphs) { if (p.Text.Contains('<') || p.Text.Contains('&')) { var text = p.Text.Replace("‏", string.Empty).Replace("‎", string.Empty); // or use rlm=\u202B, lrm=\u202A ? text = System.Net.WebUtility.HtmlDecode(text); var match = RegexRemoveCTags.Match(text); while (match.Success) { var start = match.Index + 1; var styles = GetStyles(match.Value); var hasItalic = italicStyles.Any(st => styles.Contains(st)); var hasBold = boldStyles.Any(st => styles.Contains(st)); var colorTag = skipColor ? null : FindBestColorTagOrDefault(styles.ToList(), cueStyles); if (hasItalic) { text = text.Insert(match.Index, ""); start += 3; } if (hasBold) { text = text.Insert(match.Index, ""); start += 3; } if (colorTag != null) { var fontString = ""; fontString = fontString.Trim('"').Trim('\''); text = text.Insert(match.Index, fontString); start += fontString.Length; text = SetEndTag(text, text.IndexOf(""); } if (hasItalic) { text = SetEndTag(text, text.IndexOf(""); } if (hasBold) { text = SetEndTag(text, text.IndexOf(""); } match = RegexRemoveCTags.Match(text, start); } text = RemoveTag("v", text); text = RemoveTag("rt", text); text = RemoveTag("ruby", text); text = RemoveTag("span", text); text = RegexRemoveCTags.Replace(text, string.Empty).Trim(); text = RegexRemoveTimeCodes.Replace(text, string.Empty).Trim(); text = RegexTagsPlusWhiteSpace.Replace(text, "$1"); p.Text = text; } } } /// /// Streaming services often put one class with their player's near-white text color on every /// cue (e.g. "color_EBEBEB" or "gainsboro"). Such a color says nothing about speakers or emphasis, /// so it should not end up as a font tag around every line in the target format. /// A single color that is not near-white (e.g. all text in gold) is a choice and is kept. /// private static bool HasOnlyDefaultTextColor(Subtitle subtitle, Dictionary cueStyles) { var colors = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var p in subtitle.Paragraphs) { if (!p.Text.Contains(" 1) { return false; } match = match.NextMatch(); } } return colors.Count == 1 && IsNearWhite(colors.First()); } private static bool IsNearWhite(string color) { try { var c = DefaultColorClasses.TryGetValue(color, out var defaultColor) ? defaultColor : ColorTranslator.FromHtml(color); var max = Math.Max(c.Red, Math.Max(c.Green, c.Blue)); var min = Math.Min(c.Red, Math.Min(c.Green, c.Blue)); return min >= 200 && max - min <= 16; } catch { return false; } } /// /// Set end tag taking nested level into account. /// private static string SetEndTag(string text, int matchIndex, string endTag) { var level = 0; var startLevel = -1; for (var i = 0; i < text.Length - 2; i++) { if (text[i] == '<') { if (text[i + 1] == 'c' && text[i + 2] == '.') { if (i == matchIndex) { startLevel = level; } level++; } else if (text[i + 1] == '/' && text[i + 2] == 'c') { level--; if (startLevel == level) { text = text.Insert(i, endTag); return text; } } } } return text + endTag; //TODO: fix } private static List GetStylesWith(Dictionary cueStyles, string searchText) { var styleList = new List(); foreach (var cueStyle in cueStyles) { if (cueStyle.Value.Contains(searchText, StringComparison.OrdinalIgnoreCase)) { styleList.Add(cueStyle.Key); } } return styleList; } private static Dictionary GetCueStyles(string header) { var dic = new Dictionary(); if (string.IsNullOrEmpty(header)) { return dic; } var matches = RegexCueLine.Matches(header); for (var i = 0; i < matches.Count; i++) { var match = matches[i]; var cueName = match.Value .Replace(" ", string.Empty) .Replace("::cue(", string.Empty) .TrimEnd('{') .TrimEnd(')') .TrimStart('.'); var end = header.IndexOf('}', match.Index + match.Length); if (end > 0) { var content = header.Substring(match.Index + match.Length, end - (match.Index + match.Length)) .Trim() .Replace(" ", string.Empty); // Ensure the last property is terminated with ';' so contains-matches like // "font-style:italic;" / "font-weight:bold;" hit when the source CSS omits // the trailing ';' (common in Apple TV WebVTT). if (content.Length > 0 && !content.EndsWith(';')) { content += ";"; } if (dic.ContainsKey(cueName)) { dic.Remove(cueName); } dic.Add(cueName, content); } } return dic; } private static string[] GetStyles(string cTag) { return cTag.Replace("').Split('.'); } private static string FindBestColorTagOrDefault(List tags, Dictionary cueStyles) { tags.Reverse(); foreach (var s in tags) { var l = s.ToLowerInvariant(); if (DefaultColorClasses.Keys.Contains(l)) { return l; } if (l.StartsWith("color") && l.Length > 6 && Utilities.IsHex(l.Remove(0, 5))) // e.g. color008000 { return "#" + l.Remove(0, 5); } // Fallback: read `color:` from the CSS body of the matching STYLE block, // e.g. `::cue(.styledotAB9216) { color:#AB9216;font-weight:bold }`. if (cueStyles != null && cueStyles.TryGetValue(s, out var css)) { var color = ToFontColor(ExtractColorFromCueCss(css)); if (color != null) { return color; } } } return null; } /// /// CSS "rgb(r,g,b)" / "rgba(r,g,b,a)" is not understood in a font tag by most players, so make /// it "#RRGGBB". Fully transparent text gets no color. Other values (hex, names) are kept as is. /// private static string ToFontColor(string cssColor) { if (cssColor == null || !cssColor.StartsWith("rgb", StringComparison.OrdinalIgnoreCase)) { return cssColor; } var start = cssColor.IndexOf('('); if (start < 0 || !cssColor.EndsWith(')')) { return null; } var arr = cssColor.Substring(start + 1, cssColor.Length - start - 2).Split(','); if (arr.Length < 3 || arr.Length > 4 || !byte.TryParse(arr[0], NumberStyles.None, CultureInfo.InvariantCulture, out var r) || !byte.TryParse(arr[1], NumberStyles.None, CultureInfo.InvariantCulture, out var g) || !byte.TryParse(arr[2], NumberStyles.None, CultureInfo.InvariantCulture, out var b)) { return null; } if (arr.Length == 4 && double.TryParse(arr[3], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var alpha) && alpha <= 0) { return null; } return $"#{r:X2}{g:X2}{b:X2}"; } private static string ExtractColorFromCueCss(string css) { if (string.IsNullOrEmpty(css)) { return null; } const string colorKey = "color:"; var idx = 0; while ((idx = css.IndexOf(colorKey, idx, StringComparison.OrdinalIgnoreCase)) >= 0) { // Skip `background-color:` etc. if (idx > 0 && (char.IsLetter(css[idx - 1]) || css[idx - 1] == '-')) { idx += colorKey.Length; continue; } var start = idx + colorKey.Length; var end = css.IndexOf(';', start); if (end < 0) { end = css.Length; } var value = css.Substring(start, end - start).Trim(); if (value.Length > 0) { return value; } idx = end; } return null; } #if NET7_0_OR_GREATER [GeneratedRegex(@"")] private static partial Regex RegexWebVttColorGen(); private static readonly Regex RegexWebVttColor = RegexWebVttColorGen(); [GeneratedRegex(@"")] private static partial Regex RegexWebVttColorHexGen(); private static readonly Regex RegexWebVttColorHex = RegexWebVttColorHexGen(); #else private static readonly Regex RegexWebVttColor = new Regex(@"", RegexOptions.Compiled); private static readonly Regex RegexWebVttColorHex = new Regex(@"", RegexOptions.Compiled); #endif internal static string ColorWebVttToHtml(string text) { var res = RunColorRegEx(text, RegexWebVttColor); res = RunColorRegEx(res, RegexWebVttColorHex); return res; } private static string RunColorRegEx(string input, Regex regex) { var res = input; var match = regex.Match(res); while (match.Success) { var value = match.Value.Substring(3, match.Value.Length - 4); if (match.Value.StartsWith("')) { value = "#" + match.Value.Substring(3 + 5, match.Value.Length - 4 - 5); } if (!KnownLanguages.Contains(value)) { var fontString = ""; fontString = fontString.Trim('"').Trim('\''); res = res.Remove(match.Index, match.Length).Insert(match.Index, fontString); var endIndex = res.IndexOf("", match.Index, StringComparison.OrdinalIgnoreCase); if (endIndex >= 0) { res = res.Remove(endIndex, 4).Insert(endIndex, ""); } else { var findString = $""; endIndex = res.IndexOf(findString, match.Index, StringComparison.OrdinalIgnoreCase); if (endIndex >= 0) { res = res.Remove(endIndex, findString.Length).Insert(endIndex, ""); } } } match = regex.Match(res, match.Index + 1); } return res; } #if NET7_0_OR_GREATER [GeneratedRegex("")] private static partial Regex RegexHtmlColorGen(); private static readonly Regex RegexHtmlColor = RegexHtmlColorGen(); [GeneratedRegex("")] private static partial Regex RegexHtmlColor2Gen(); private static readonly Regex RegexHtmlColor2 = RegexHtmlColor2Gen(); [GeneratedRegex("")] private static partial Regex RegexHtmlColor3Gen(); private static readonly Regex RegexHtmlColor3 = RegexHtmlColor3Gen(); [GeneratedRegex("")] private static partial Regex RegexHtmlColor4Gen(); private static readonly Regex RegexHtmlColor4 = RegexHtmlColor4Gen(); #else private static readonly Regex RegexHtmlColor = new Regex("", RegexOptions.Compiled); private static readonly Regex RegexHtmlColor2 = new Regex("", RegexOptions.Compiled); private static readonly Regex RegexHtmlColor3 = new Regex("", RegexOptions.Compiled); private static readonly Regex RegexHtmlColor4 = new Regex("", RegexOptions.Compiled); #endif private static string ColorHtmlToWebVtt(string text) { var res = text.Replace("", ""); if (res.IndexOf(""; fontString = fontString.Trim('"').Trim('\''); res = res.Remove(match.Index, match.Length).Insert(match.Index, fontString); // Continue after the replacement - restarting at 0 rescanned the whole cue per tag. match = RegexHtmlColor.Match(res, match.Index + fontString.Length); } match = RegexHtmlColor2.Match(res); while (match.Success) { var fontString = ""; fontString = fontString.Trim('"').Trim('\''); res = res.Remove(match.Index, match.Length).Insert(match.Index, fontString); // Continue after the replacement - restarting at 0 rescanned the whole cue per tag. match = RegexHtmlColor2.Match(res, match.Index + fontString.Length); } match = RegexHtmlColor3.Match(res); while (match.Success) { var tag = match.Value.Substring(14, match.Value.Length - 16); var fontString = ""; var closeColor = GetCloseColor(tag); if (closeColor != null) { fontString = ""; } fontString = fontString.Trim('"').Trim('\''); res = res.Remove(match.Index, match.Length).Insert(match.Index, fontString); // Continue after the replacement - restarting at 0 rescanned the whole cue per tag. match = RegexHtmlColor3.Match(res, match.Index + fontString.Length); } match = RegexHtmlColor4.Match(res); while (match.Success) { var colorName = match.Value.Substring(13, match.Value.Length - 15); var color = HtmlUtil.GetColorFromString(colorName); var tag = "." + Utilities.ColorToHexWithTransparency(color).TrimStart('#'); var fontString = ""; var closeColor = GetCloseColor(tag); if (closeColor != null) { fontString = ""; } fontString = fontString.Trim('"').Trim('\''); res = res.Remove(match.Index, match.Length).Insert(match.Index, fontString); // Continue after the replacement - restarting at 0 rescanned the whole cue per tag. match = RegexHtmlColor4.Match(res, match.Index + fontString.Length); } } return res; } private static string GetCloseColor(string tag) { try { var c = ColorTranslator.FromHtml("#" + tag.Trim('#', '.')); const int maxDiff = 25; foreach (var kvp in DefaultColorClasses) { if (Math.Abs(kvp.Value.Red - c.Red) <= maxDiff && Math.Abs(kvp.Value.Green - c.Green) <= maxDiff && Math.Abs(kvp.Value.Blue - c.Blue) <= maxDiff) { return kvp.Key; } } } catch { return null; } return null; } public static List GetVoices(Subtitle subtitle) { var list = new List(); if (subtitle?.Paragraphs != null) { foreach (var p in subtitle.Paragraphs) { foreach (var voice in GetVoices(p.Text)) { if (!list.Contains(voice)) { list.Add(voice); } } } } return list; } /// /// The names of the "<v Name>" voice tags in a single cue text, in the order they /// appear and without duplicates. /// public static List GetVoices(string text) { var list = new List(); if (string.IsNullOrEmpty(text)) { return list; } var startIndex = text.IndexOf("= 0) { var endIndex = text.IndexOf('>', startIndex); if (endIndex > startIndex) { var voice = text.Substring(startIndex + 2, endIndex - startIndex - 2).Trim(); if (!list.Contains(voice)) { list.Add(voice); } } if (startIndex == text.Length - 1) { startIndex = -1; } else { startIndex = text.IndexOf(" /// The first "<v Name>" voice of a cue text, or an empty string when it has none. /// This is WebVTT's counterpart of the actor of an ASSA line - it lives inside the cue /// text instead of in a field of its own. /// public static string GetVoice(string text) { var voices = GetVoices(text); return voices.Count > 0 ? voices[0] : string.Empty; } public static string RemoveTag(string tag, string text) { var res = text; var indexOfTag = res.IndexOf("<" + tag + " ", StringComparison.Ordinal); if (indexOfTag >= 0) { var indexOfEnd = res.IndexOf('>', indexOfTag); if (indexOfEnd > 0) { res = res.Remove(indexOfTag, indexOfEnd - indexOfTag + 1); res = res.Replace("", string.Empty); } } return res; } internal static string EscapeEncodeText(string input) { if (!input.Contains('<') && !input.Contains('>') && !input.Contains('&')) { return input; } var sb = new StringBuilder(input.Length); var max = input.Length; var i = 0; var tagOn = false; while (i < max) { var ch = input[i]; if (ch == '<') { var s = input.Substring(i); if (s.StartsWith("", StringComparison.OrdinalIgnoreCase) || s.StartsWith("", StringComparison.OrdinalIgnoreCase) || s.StartsWith("", StringComparison.OrdinalIgnoreCase) || s.StartsWith("", StringComparison.OrdinalIgnoreCase) || s.StartsWith("", StringComparison.OrdinalIgnoreCase)) { sb.Append(s.Substring(0, 3)); i += 3; } else if (s.StartsWith("') { if (tagOn) { sb.Append(ch); i++; tagOn = false; } else { sb.Append(">"); i++; } } else if (ch == '&') { var s = input.Substring(i); if (s.StartsWith("‎", StringComparison.OrdinalIgnoreCase) || s.StartsWith("&", StringComparison.OrdinalIgnoreCase) || s.StartsWith("<", StringComparison.OrdinalIgnoreCase) || s.StartsWith(">", StringComparison.OrdinalIgnoreCase) || s.Length > 3 && s[3] == ';' && char.IsLetter(s[2]) && char.IsLetter(s[1]) || s.Length > 4 && s[4] == ';' && char.IsLetter(s[3]) && char.IsLetter(s[2]) && char.IsLetter(s[1])) { sb.Append(ch); i++; } else { sb.Append("&"); i++; } } else { sb.Append(ch); i++; } } return sb.ToString(); } internal static string EscapeDecodeText(string input) { return input .Replace(">", ">") .Replace("<", "<") .Replace("&", "&"); } internal static TimeCode GetTimeCodeFromString(string time) { // hh:mm:ss.mmm var timeCode = time.Trim().Split(':', '.', ' '); return new TimeCode(int.Parse(timeCode[0]), int.Parse(timeCode[1]), int.Parse(timeCode[2]), int.Parse(timeCode[3])); } } }