SubtitleEdit/libse/UknownFormatImporterJson.cs

259 lines
9.2 KiB
C#
Raw Normal View History

2017-02-11 17:02:22 +01:00
using Nikse.SubtitleEdit.Core.SubtitleFormats;
using System;
using System.Collections.Generic;
2017-02-11 17:02:22 +01:00
using System.Globalization;
2018-07-10 22:05:22 +02:00
using System.Linq;
2017-02-11 17:02:22 +01:00
using System.Text;
namespace Nikse.SubtitleEdit.Core
{
public class UknownFormatImporterJson
{
public Subtitle AutoGuessImport(List<string> lines)
2017-02-11 17:02:22 +01:00
{
var sb = new StringBuilder();
foreach (string s in lines)
sb.Append(s);
var allText = sb.ToString().Trim();
if (!allText.Contains("{", StringComparison.Ordinal))
return new Subtitle();
var subtitle1 = new Subtitle();
try
{
int count = 0;
foreach (string line in allText.Split('{', '}', '[', ']'))
{
count++;
ReadParagraph(line, subtitle1);
2017-02-11 17:02:22 +01:00
if (count > 20 && subtitle1.Paragraphs.Count == 0)
break;
}
}
catch (Exception)
{
// ignored
}
var subtitle2 = new Subtitle();
try
{
int count = 0;
foreach (string line in allText.Split('{', '}'))
{
count++;
ReadParagraph(line, subtitle2);
2017-02-11 17:02:22 +01:00
if (count > 20 && subtitle2.Paragraphs.Count == 0)
break;
}
}
catch (Exception)
{
// ignored
}
var subtitle3 = new Subtitle();
try
{
int count = 0;
foreach (var line in Json.ReadObjectArray(allText))
{
count++;
ReadParagraph(line, subtitle3);
2017-02-11 17:02:22 +01:00
if (count > 20 && subtitle3.Paragraphs.Count == 0)
break;
}
}
catch (Exception)
{
// ignored
}
2018-07-10 22:05:22 +02:00
if (subtitle1.Paragraphs.Count >= subtitle2.Paragraphs.Count && subtitle1.Paragraphs.Count >= subtitle3.Paragraphs.Count)
2017-02-11 17:02:22 +01:00
{
subtitle1.Renumber();
return FixTimeCodeMsOrSeconds(subtitle1);
2017-02-11 17:02:22 +01:00
}
2018-07-10 22:05:22 +02:00
if (subtitle2.Paragraphs.Count >= subtitle1.Paragraphs.Count && subtitle2.Paragraphs.Count >= subtitle3.Paragraphs.Count)
2017-02-11 17:02:22 +01:00
{
subtitle2.Renumber();
return FixTimeCodeMsOrSeconds(subtitle2);
2017-02-11 17:02:22 +01:00
}
subtitle3.Renumber();
return FixTimeCodeMsOrSeconds(subtitle3);
2017-02-11 17:02:22 +01:00
}
private Subtitle FixTimeCodeMsOrSeconds(Subtitle subtitle)
2017-02-11 17:02:22 +01:00
{
if (subtitle == null || subtitle.Paragraphs.Count < 5)
return subtitle;
double totalDuration = 0;
int msFound = 0;
foreach (var p in subtitle.Paragraphs)
{
totalDuration += p.Duration.TotalMilliseconds;
if (p.Style.Contains("\"startMs\"") ||
p.Style.Contains("\"start_ms\"") ||
p.Style.Contains("\"startMillis\"") ||
p.Style.Contains("\"start_millis\"") ||
p.Style.Contains("\"startMilliseconds\"") ||
p.Style.Contains("\"start_millisecondsMs\""))
{
msFound++;
}
}
if (totalDuration / subtitle.Paragraphs.Count > 1000000 || msFound == subtitle.Paragraphs.Count)
{
// Time codes were read as seconds, but they are actually milliseconds,
// so all time codes are divided by 1000.
foreach (var p in subtitle.Paragraphs)
{
p.StartTime.TotalMilliseconds = p.StartTime.TotalMilliseconds / TimeCode.BaseUnit;
p.EndTime.TotalMilliseconds = p.EndTime.TotalMilliseconds / TimeCode.BaseUnit;
}
}
return new Subtitle(subtitle.Paragraphs);
}
private static void ReadParagraph(string s, Subtitle subtitle)
{
s = s.Trim();
if (s.Length < 7)
{
return;
}
2018-07-10 22:05:22 +02:00
if (!s.EndsWith('}'))
s += '}';
2017-02-11 17:02:22 +01:00
var start = ReadStartTag(s);
var end = ReadEndTag(s);
var duration = ReadDurationTag(s);
var text = ReadTextTag(s);
var originalStart = start;
2017-02-11 17:02:22 +01:00
if (start != null && start.Contains(":") && start.Length >= 11 && start.Length <= 12 && start.Split(new[] { ':', ',', '.' }, StringSplitOptions.RemoveEmptyEntries).Length == 4)
2017-02-11 17:02:22 +01:00
{
start = DecodeFormatToSeconds(start);
}
if (end != null && end.Contains(":") && end.Length >= 11 && end.Length <= 12 && end.Split(new[] { ':', ',', '.' }, StringSplitOptions.RemoveEmptyEntries).Length == 4)
2017-02-11 17:02:22 +01:00
{
end = DecodeFormatToSeconds(end);
}
if (start != null && end != null && text != null)
{
start = start.TrimEnd('s');
end = end.TrimEnd('s');
2017-02-11 17:02:22 +01:00
double startSeconds;
double endSeconds;
if (double.TryParse(start, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out startSeconds) &&
double.TryParse(end, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out endSeconds))
{
var p = new Paragraph(Json.DecodeJsonText(text), startSeconds * TimeCode.BaseUnit, endSeconds * TimeCode.BaseUnit) { Extra = originalStart, Style = s };
subtitle.Paragraphs.Add(p);
2017-02-11 17:02:22 +01:00
}
}
else if (start != null && duration != null && text != null)
{
start = start.TrimEnd('s');
duration = duration.TrimEnd('s');
2017-02-11 17:02:22 +01:00
double startSeconds;
double durationSeconds;
if (double.TryParse(start, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out startSeconds) &&
double.TryParse(duration, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out durationSeconds))
{
var p = new Paragraph(Json.DecodeJsonText(text), startSeconds * TimeCode.BaseUnit, (startSeconds + durationSeconds) * TimeCode.BaseUnit) { Extra = originalStart, Style = s };
subtitle.Paragraphs.Add(p);
2017-02-11 17:02:22 +01:00
}
}
}
private static string DecodeFormatToSeconds(string s)
2017-02-11 17:02:22 +01:00
{
var ms = s.Length == 11 && s[8] == ':' ? TimeCode.ParseHHMMSSFFToMilliseconds(s) : TimeCode.ParseToMilliseconds(s);
return (ms / TimeCode.BaseUnit).ToString(CultureInfo.InvariantCulture);
}
private static string ReadStartTag(string s)
2017-02-11 17:02:22 +01:00
{
return ReadFirstMultiTag(s, new[]
{
"start",
"startTime", "start_time", "starttime",
"startMillis", "start_Millis", "startmillis",
2017-02-11 17:02:22 +01:00
"startMs", "start_ms", "startms",
"startMilliseconds", "start_Millisesonds", "startmilliseconds",
2017-02-11 17:02:22 +01:00
});
}
private static string ReadEndTag(string s)
2017-02-11 17:02:22 +01:00
{
return ReadFirstMultiTag(s, new[]
{
"end",
"endTime", "end_time", "endtime",
"endMillis", "end_Millis", "endmillis",
2017-02-11 17:02:22 +01:00
"endMs", "end_ms", "startms",
"endMilliseconds", "end_Millisesonds", "endmilliseconds",
2017-02-11 17:02:22 +01:00
});
}
private static string ReadDurationTag(string s)
2017-02-11 17:02:22 +01:00
{
return ReadFirstMultiTag(s, new[]
{
"duration",
"dur",
});
}
private static string ReadTextTag(string s)
2017-02-11 17:02:22 +01:00
{
2018-07-11 20:24:11 +02:00
var idx = s.IndexOf("\"text", StringComparison.OrdinalIgnoreCase);
if (idx < 0)
return null;
s = s.Substring(idx);
idx = s.IndexOf(']');
if (idx > 0)
s = s.Substring(0, idx + 1);
2018-07-10 22:05:22 +02:00
var text = Json.ReadTag(s, "text");
2017-02-11 17:02:22 +01:00
var textLines = Json.ReadArray(s, "text");
2018-07-10 22:05:22 +02:00
bool isArray = s.Contains("[");
if (isArray && textLines.Any(p => p == "end_time" || p == "endTime" || p == "end" || p == "endMs" || p == "endMilliseconds" || p == "end_ms"))
isArray = false;
if (!isArray && !string.IsNullOrEmpty(text))
{
return text.Replace("&#039;", "'");
}
2017-02-11 17:02:22 +01:00
if (textLines != null && textLines.Count > 0)
{
return string.Join(Environment.NewLine, textLines);
}
return ReadFirstMultiTag(s, new[] { "text", "content" });
}
private static string ReadFirstMultiTag(string s, string[] tags)
2017-02-11 17:02:22 +01:00
{
foreach (var tag in tags)
{
var res = Json.ReadTag(s, tag);
if (!string.IsNullOrEmpty(res))
return res;
}
return null;
}
}
}