private void FillStyles() { listViewStyles.AutoSizeLastColumn(); var styles = new List <string>(); var formatType = _format.GetType(); if (formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha)) { styles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header); } else if (formatType == typeof(TimedText10) || formatType == typeof(ItunesTimedText)) { styles = TimedText10.GetStylesFromHeader(_subtitle.Header); } else if (formatType == typeof(Sami) || formatType == typeof(SamiModern)) { styles = _subtitle.Header == null?Sami.GetStylesFromSubtitle(_subtitle) : Sami.GetStylesFromHeader(_subtitle.Header); } _loading = true; listViewStyles.Items.Clear(); listViewStyles.Items.AddRange(styles.OrderBy(p => p).Select(p => new ListViewItem { Text = p }).ToArray()); _loading = false; }
private void FillStyles() { listViewStyles.Columns[listViewStyles.Columns.Count - 1].Width = -2; var styles = new List <string>(); var formatType = _format.GetType(); if (formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha)) { styles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header); } else if (formatType == typeof(TimedText10) || formatType == typeof(ItunesTimedText)) { styles = TimedText10.GetStylesFromHeader(_subtitle.Header); } else if (formatType == typeof(Sami) || formatType == typeof(SamiModern)) { styles = _subtitle.Header == null?Sami.GetStylesFromSubtitle(_subtitle) : Sami.GetStylesFromHeader(_subtitle.Header); } listViewStyles.Items.Clear(); foreach (var style in styles.OrderBy(p => p)) { listViewStyles.Items.Add(style); } }
private void RefreshCheckBoxes(string language) { _netflixQualityController = new NetflixQualityController { Language = language, VideoFileName = _videoFileName }; checkBoxNoItalics.Checked = !_netflixQualityController.AllowItalics; checkBoxNoItalics.Enabled = !_netflixQualityController.AllowItalics; var sceneChangesExists = false; if (_netflixQualityController.VideoExists) { if (SceneChangeHelper.FromDisk(_videoFileName).Count > 0) { sceneChangesExists = true; } } checkBoxSceneChange.Checked = _netflixQualityController.VideoExists && sceneChangesExists; checkBoxSceneChange.Enabled = _netflixQualityController.VideoExists && sceneChangesExists; var checkFrameRate = _subtitleFormat.GetType() == new NetflixTimedText().GetType(); checkBoxTtmlFrameRate.Checked = checkFrameRate; checkBoxTtmlFrameRate.Enabled = checkFrameRate; checkBoxDialogHypenNoSpace.Text = !_netflixQualityController.DualSpeakersHasHyphenAndNoSpace ? "Dual Speakers: Use a hyphen with a space" : "Dual Speakers: Use a hyphen without a space"; checkBox17CharsPerSecond.Text = string.Format(LanguageSettings.Current.NetflixQualityCheck.MaximumXCharsPerSecond, _netflixQualityController.CharactersPerSecond); checkBoxMaxLineLength.Text = string.Format(LanguageSettings.Current.NetflixQualityCheck.MaximumLineLength, _netflixQualityController.SingleLineMaxLength); }
private void RefreshCheckBoxes(string language) { _netflixQualityController = new NetflixQualityController { Language = language, VideoFileName = _videoFileName, FrameRate = _frameRate }; checkBoxNoItalics.Checked = !_netflixQualityController.AllowItalics; checkBoxNoItalics.Enabled = !_netflixQualityController.AllowItalics; int halfSecGapInFrames = (int)Math.Round(_frameRate / 2, MidpointRounding.AwayFromZero); checkBoxGapBridge.Text = $"Frame gap: 3 to {halfSecGapInFrames - 1} frames => 2 frames"; var shotChangesExist = false; if (_netflixQualityController.VideoExists) { if (ShotChangeHelper.FromDisk(_videoFileName).Count > 0) { shotChangesExist = true; } } checkBoxShotChange.Checked = shotChangesExist; checkBoxShotChange.Enabled = shotChangesExist; var checkFrameRate = _subtitleFormat.GetType() == new NetflixTimedText().GetType(); checkBoxTtmlFrameRate.Checked = checkFrameRate; checkBoxTtmlFrameRate.Enabled = checkFrameRate; var speakerStyle = _netflixQualityController.SpeakerStyle; var checkBoxSpeakerStyleText = "Dual Speakers: Use a hyphen without a space"; if (speakerStyle == DialogType.DashBothLinesWithSpace) { checkBoxSpeakerStyleText = "Dual Speakers: Use a hyphen with a space"; } else if (speakerStyle == DialogType.DashSecondLineWithSpace) { checkBoxSpeakerStyleText = "Dual Speakers: Use a hyphen with a space to denote the second speaker only"; } else if (speakerStyle == DialogType.DashSecondLineWithoutSpace) { checkBoxSpeakerStyleText = "Dual Speakers: Use a hyphen without a space to denote the second speaker only"; } checkBoxSpeakerStyle.Text = checkBoxSpeakerStyleText; checkBox17CharsPerSecond.Text = string.Format(LanguageSettings.Current.NetflixQualityCheck.MaximumXCharsPerSecond, _netflixQualityController.CharactersPerSecond); checkBoxMaxLineLength.Text = string.Format(LanguageSettings.Current.NetflixQualityCheck.MaximumLineLength, _netflixQualityController.SingleLineMaxLength); }
private void RefreshCheckBoxes(string language) { _netflixQualityController = new NetflixQualityController { Language = language, VideoFileName = _videoFileName }; checkBoxNoItalics.Checked = !_netflixQualityController.AllowItalics; checkBoxNoItalics.Enabled = !_netflixQualityController.AllowItalics; var sceneChangesExists = false; if (_netflixQualityController.VideoExists) { if (SceneChangeHelper.FromDisk(_videoFileName).Count > 0) { sceneChangesExists = true; } } checkBoxSceneChange.Checked = _netflixQualityController.VideoExists && sceneChangesExists; checkBoxSceneChange.Enabled = _netflixQualityController.VideoExists && sceneChangesExists; var checkFrameRate = _subtitleFormat.GetType() == new NetflixTimedText().GetType(); checkBoxTtmlFrameRate.Checked = checkFrameRate; checkBoxTtmlFrameRate.Enabled = checkFrameRate; var speakerStyle = _netflixQualityController.SpeakerStyle; var checkBoxSpeakerStyleText = "Dual Speakers: Use a hyphen without a space"; if (speakerStyle == DialogType.DashBothLinesWithSpace) { checkBoxSpeakerStyleText = "Dual Speakers: Use a hyphen with a space"; } else if (speakerStyle == DialogType.DashSecondLineWithSpace) { checkBoxSpeakerStyleText = "Dual Speakers: Use a hyphen with a space to denote the second speaker only"; } else if (speakerStyle == DialogType.DashSecondLineWithoutSpace) { checkBoxSpeakerStyleText = "Dual Speakers: Use a hyphen without a space to denote the second speaker only"; } checkBoxSpeakerStyle.Text = checkBoxSpeakerStyleText; checkBox17CharsPerSecond.Text = string.Format(LanguageSettings.Current.NetflixQualityCheck.MaximumXCharsPerSecond, _netflixQualityController.CharactersPerSecond); checkBoxMaxLineLength.Text = string.Format(LanguageSettings.Current.NetflixQualityCheck.MaximumLineLength, _netflixQualityController.SingleLineMaxLength); }
private void RefreshCheckBoxes(string language) { _netflixQualityController = new NetflixQualityController { Language = language }; checkBoxNoItalics.Checked = !_netflixQualityController.AllowItalics; checkBoxNoItalics.Enabled = !_netflixQualityController.AllowItalics; var checkFrameRate = _subtitleFormat.GetType() == new NetflixTimedText().GetType(); checkBoxTtmlFrameRate.Checked = checkFrameRate; checkBoxTtmlFrameRate.Enabled = checkFrameRate; checkBoxDialogHypenNoSpace.Checked = _netflixQualityController.DualSpeakersHasHyphenAndNoSpace; checkBoxDialogHypenNoSpace.Enabled = _netflixQualityController.DualSpeakersHasHyphenAndNoSpace; checkBox17CharsPerSecond.Text = string.Format(Configuration.Settings.Language.NetflixQualityCheck.MaximumXCharsPerSecond, _netflixQualityController.CharactersPerSecond); checkBoxMaxLineLength.Text = string.Format(Configuration.Settings.Language.NetflixQualityCheck.MaximumLineLength, _netflixQualityController.SingleLineMaxLength); }
private string CleanText(string s, int index) { var cleanText = s.Replace("</p>", string.Empty).Trim(); var indexOfP = cleanText.IndexOf(SplitterString.Trim(), StringComparison.Ordinal); if (indexOfP >= 0 && indexOfP < 4) { cleanText = cleanText.Remove(0, indexOfP); } cleanText = cleanText.Replace(SplitterString, string.Empty).Trim(); if (cleanText.Contains('\n') && !cleanText.Contains('\r')) { cleanText = cleanText.Replace("\n", Environment.NewLine); } cleanText = cleanText.Replace(" ...", "..."); cleanText = cleanText.Replace("<br/>", Environment.NewLine); cleanText = cleanText.Replace("<br />", Environment.NewLine); cleanText = cleanText.Replace("< br/>", Environment.NewLine); cleanText = cleanText.Replace("<br/ >", Environment.NewLine); cleanText = cleanText.Replace("<br / >", Environment.NewLine); cleanText = cleanText.Replace("< br />", Environment.NewLine); cleanText = cleanText.Replace("< br / >", Environment.NewLine); cleanText = cleanText.Replace("< br/ >", Environment.NewLine); cleanText = cleanText.Replace(Environment.NewLine + " ", Environment.NewLine); cleanText = cleanText.Replace(" " + Environment.NewLine, Environment.NewLine); var formatType = _subtitleFormat.GetType(); if (formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha)) { cleanText = cleanText.Replace("{i1}", "{\\i1}"); cleanText = cleanText.Replace("{i0}", "{\\i0}"); cleanText = cleanText.Replace("{b1}", "{\\b1}"); cleanText = cleanText.Replace("{b0}", "{\\b0}"); cleanText = cleanText.Replace("{u1}", "{\\u1}"); cleanText = cleanText.Replace("{u0}", "{\\u0}"); cleanText = cleanText.Replace("{s1}", "{\\s1}"); cleanText = cleanText.Replace("{s0}", "{\\s0}"); cleanText = cleanText.Replace("{c&H", "{\\c&H"); cleanText = cleanText.Replace("{1&H", "{\\1c&H"); cleanText = cleanText.Replace("{2c&H", "{\\2c&H"); cleanText = cleanText.Replace("{3c&H", "{\\3c&H"); cleanText = cleanText.Replace("{4c&H", "{\\4c&H"); cleanText = cleanText.Replace("{alpha&H", "{\\alpha&H"); cleanText = cleanText.Replace("{1a&H", "{\\1a&H"); cleanText = cleanText.Replace("{2a&H", "{\\2a&H"); cleanText = cleanText.Replace("{3a&H", "{\\3a&H"); cleanText = cleanText.Replace("{4a&H", "{\\4a&H"); cleanText = cleanText.Replace("{fn", "{\\fn"); cleanText = cleanText.Replace("{fs", "{\\fs"); cleanText = cleanText.Replace("{an", "{\\an"); cleanText = cleanText.Replace("{be", "{\\be"); cleanText = cleanText.Replace("{pos", "{\\pos"); cleanText = cleanText.Replace("{fad", "{\\fad"); cleanText = cleanText.Replace("{move", "{\\move"); cleanText = cleanText.Replace("{fscx", "{\\fscx"); cleanText = cleanText.Replace("{fscy", "{\\fscy"); cleanText = cleanText.Replace("{bord", "{\\bord"); cleanText = cleanText.Replace("{xbord", "{\\xbord"); cleanText = cleanText.Replace("{ybord", "{\\ybord"); cleanText = cleanText.Replace("{shad", "{\\shad"); cleanText = cleanText.Replace("{xshad", "{\\xshad"); cleanText = cleanText.Replace("{yshad", "{\\yshad"); cleanText = cleanText.Replace("{fr", "{\\fr"); cleanText = cleanText.Replace("{fsp", "{\\fsp"); cleanText = cleanText.Replace("{fay", "{\\fay"); cleanText = cleanText.Replace("{fax", "{\\fax"); cleanText = cleanText.Replace("{org(", "{\\org("); cleanText = cleanText.Replace("{t(", "{\\t("); cleanText = cleanText.Replace("{clip", "{\\clip"); cleanText = cleanText.Replace("{iclip", "{\\iclip"); cleanText = cleanText.Replace("{blur", "{\\blur"); } cleanText = cleanText.Replace("<I>", "<i>"); cleanText = cleanText.Replace("< I>", "<i>"); cleanText = cleanText.Replace("</ i>", "</i>"); cleanText = cleanText.Replace("</ I>", "</i>"); cleanText = cleanText.Replace("</I>", "</i>"); cleanText = cleanText.Replace("< i >", "<i>"); if (cleanText.StartsWith("<i> ", StringComparison.Ordinal)) { cleanText = cleanText.Remove(3, 1); } if (cleanText.EndsWith(" </i>", StringComparison.Ordinal)) { cleanText = cleanText.Remove(cleanText.Length - 5, 1); } cleanText = cleanText.Replace(Environment.NewLine + "<i> ", Environment.NewLine + "<i>"); cleanText = cleanText.Replace(" </i>" + Environment.NewLine, "</i>" + Environment.NewLine); if (_autoSplit[index]) { cleanText = Utilities.AutoBreakLine(cleanText); } if (Utilities.GetNumberOfLines(cleanText) == 1 && Utilities.GetNumberOfLines(_subtitle.Paragraphs[index].Text) == 2) { if (!_autoSplit[index]) { cleanText = Utilities.AutoBreakLine(cleanText); } } return(cleanText); }
internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList <SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage, double?targetFrameRate, bool removeTextForHi, bool fixCommonErrors, bool redoCasing) { double oldFrameRate = Configuration.Settings.General.CurrentFrameRate; try { // adjust offset if (!string.IsNullOrEmpty(offset) && (offset.StartsWith("/offset:", StringComparison.Ordinal) || offset.StartsWith("offset:", StringComparison.Ordinal))) { string[] parts = offset.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 5) { try { var ts = new TimeSpan(0, int.Parse(parts[1].TrimStart('-')), int.Parse(parts[2]), int.Parse(parts[3]), int.Parse(parts[4])); if (parts[1].StartsWith('-')) { sub.AddTimeToAllParagraphs(ts.Negate()); } else { sub.AddTimeToAllParagraphs(ts); } } catch { Console.Write(" (unable to read offset " + offset + ")"); } } } // adjust frame rate if (targetFrameRate.HasValue) { sub.ChangeFrameRate(Configuration.Settings.General.CurrentFrameRate, targetFrameRate.Value); Configuration.Settings.General.CurrentFrameRate = targetFrameRate.Value; } if (removeTextForHi) { var hiSettings = new Core.Forms.RemoveTextForHISettings(); var hiLib = new Core.Forms.RemoveTextForHI(hiSettings); foreach (var p in sub.Paragraphs) { p.Text = hiLib.RemoveTextFromHearImpaired(p.Text); } } if (fixCommonErrors) { using (var fce = new FixCommonErrors { BatchMode = true }) { for (int i = 0; i < 3; i++) { fce.RunBatch(sub, format, targetEncoding, Configuration.Settings.Tools.BatchConvertLanguage); sub = fce.FixedSubtitle; } } } if (redoCasing) { using (var changeCasing = new ChangeCasing()) { changeCasing.FixCasing(sub, LanguageAutoDetect.AutoDetectGoogleLanguage(sub)); } using (var changeCasingNames = new ChangeCasingNames()) { changeCasingNames.Initialize(sub); changeCasingNames.FixCasing(); } } bool targetFormatFound = false; string outputFileName; foreach (SubtitleFormat sf in formats) { if (sf.IsTextBased && (sf.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || sf.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))) { targetFormatFound = true; sf.BatchMode = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, sf.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); if (sf.IsFrameBased && !sub.WasLoadedWithFrameNumbers) { sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate); } else if (sf.IsTimeBased && sub.WasLoadedWithFrameNumbers) { sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); } if ((sf.GetType() == typeof(WebVTT) || sf.GetType() == typeof(WebVTTFileWithLineNumber))) { targetEncoding = Encoding.UTF8; } if (sf.GetType() == typeof(ItunesTimedText) || sf.GetType() == typeof(ScenaristClosedCaptions) || sf.GetType() == typeof(ScenaristClosedCaptionsDropFrame)) { Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM using (var file = new StreamWriter(outputFileName, false, outputEnc)) // open file with encoding { file.Write(sub.ToText(sf)); } // save and close it } else if (targetEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml))) { Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM using (var file = new StreamWriter(outputFileName, false, outputEnc)) // open file with encoding { file.Write(sub.ToText(sf)); } // save and close it } else { try { File.WriteAllText(outputFileName, sub.ToText(sf), targetEncoding); } catch (Exception ex) { Console.WriteLine(ex.Message); errors++; return(false); } } if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern)) { var sami = (Sami)format; foreach (string className in Sami.GetStylesFromHeader(sub.Header)) { var newSub = new Subtitle(); foreach (Paragraph p in sub.Paragraphs) { if (p.Extra != null && p.Extra.Trim().Equals(className.Trim(), StringComparison.OrdinalIgnoreCase)) { newSub.Paragraphs.Add(p); } } if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count) { string s = fileName; if (s.LastIndexOf('.') > 0) { s = s.Insert(s.LastIndexOf('.'), "_" + className); } else { s += "_" + className + format.Extension; } outputFileName = FormatOutputFileNameForBatchConvert(s, sf.Extension, outputFolder, overwrite); File.WriteAllText(outputFileName, newSub.ToText(sf), targetEncoding); } } } Console.WriteLine(" done."); break; } } if (!targetFormatFound) { var ebu = new Ebu(); if (ebu.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); Ebu.Save(outputFileName, sub, true); Console.WriteLine(" done."); } } if (!targetFormatFound) { var pac = new Pac(); if (pac.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || toFormat.Equals("pac", StringComparison.OrdinalIgnoreCase) || toFormat.Equals(".pac", StringComparison.OrdinalIgnoreCase)) { pac.BatchMode = true; int codePage; if (!string.IsNullOrEmpty(pacCodePage) && int.TryParse(pacCodePage, out codePage)) { pac.CodePage = codePage; } targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); pac.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var cavena890 = new Cavena890(); if (cavena890.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); cavena890.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, cheetahCaption.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); CheetahCaption.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var ayato = new Ayato(); if (ayato.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ayato.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); ayato.Save(outputFileName, null, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, capMakerPlus.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); CapMakerPlus.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { if (Configuration.Settings.Language.BatchConvert.PlainText == toFormat || Configuration.Settings.Language.BatchConvert.PlainText.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ".txt", outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); File.WriteAllText(outputFileName, ExportText.GeneratePlainText(sub, false, false, false, false, false, false, string.Empty, true, false, true, true, false), targetEncoding); Console.WriteLine(" done."); } } if (!targetFormatFound) { if (string.Compare(BatchConvert.BluRaySubtitle, toFormat, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(BatchConvert.BluRaySubtitle.Replace(" ", string.Empty), toFormat, StringComparison.OrdinalIgnoreCase) == 0) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ".sup", outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); using (var form = new ExportPngXml()) { form.Initialize(sub, format, "BLURAYSUP", fileName, null, null); var binarySubtitleFile = new FileStream(outputFileName, FileMode.Create); int width = 1920; int height = 1080; var parts = Configuration.Settings.Tools.ExportBluRayVideoResolution.Split('x'); if (parts.Length == 2 && Utilities.IsInteger(parts[0]) && Utilities.IsInteger(parts[1])) { width = int.Parse(parts[0]); height = int.Parse(parts[1]); } for (int index = 0; index < sub.Paragraphs.Count; index++) { var mp = form.MakeMakeBitmapParameter(index, width, height); mp.LineJoin = Configuration.Settings.Tools.ExportPenLineJoin; mp.Bitmap = ExportPngXml.GenerateImageFromTextWithStyle(mp); ExportPngXml.MakeBluRaySupImage(mp); binarySubtitleFile.Write(mp.Buffer, 0, mp.Buffer.Length); } binarySubtitleFile.Close(); } Console.WriteLine(" done."); } else if (string.Compare(BatchConvert.VobSubSubtitle, toFormat, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(BatchConvert.VobSubSubtitle.Replace(" ", string.Empty), toFormat, StringComparison.OrdinalIgnoreCase) == 0) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ".sub", outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); using (var form = new ExportPngXml()) { form.Initialize(sub, format, "VOBSUB", fileName, null, null); int width = 720; int height = 576; var parts = Configuration.Settings.Tools.ExportVobSubVideoResolution.Split('x'); if (parts.Length == 2 && Utilities.IsInteger(parts[0]) && Utilities.IsInteger(parts[1])) { width = int.Parse(parts[0]); height = int.Parse(parts[1]); } var cfg = Configuration.Settings.Tools; var languageIndex = IfoParser.LanguageCodes.IndexOf(LanguageAutoDetect.AutoDetectGoogleLanguageOrNull(sub)); if (languageIndex < 0) { languageIndex = IfoParser.LanguageCodes.IndexOf("en"); } using (var vobSubWriter = new VobSubWriter(outputFileName, width, height, cfg.ExportBottomMargin, cfg.ExportBottomMargin, 32, cfg.ExportFontColor, cfg.ExportBorderColor, !cfg.ExportVobAntiAliasingWithTransparency, IfoParser.LanguageNames[languageIndex], IfoParser.LanguageCodes[languageIndex])) { for (int index = 0; index < sub.Paragraphs.Count; index++) { var mp = form.MakeMakeBitmapParameter(index, width, height); mp.LineJoin = Configuration.Settings.Tools.ExportPenLineJoin; mp.Bitmap = ExportPngXml.GenerateImageFromTextWithStyle(mp); vobSubWriter.WriteParagraph(mp.P, mp.Bitmap, mp.Alignment); } vobSubWriter.WriteIdxFile(); } } Console.WriteLine(" done."); } } if (!targetFormatFound) { Console.WriteLine("{0}: {1} - target format '{2}' not found!", count, fileName, toFormat); errors++; return(false); } converted++; return(true); } finally { Configuration.Settings.General.CurrentFrameRate = oldFrameRate; } }
public static void Convert(string title, string[] args) // E.g.: /convert *.txt SubRip { const int ATTACH_PARENT_PROCESS = -1; if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux()) { NativeMethods.AttachConsole(ATTACH_PARENT_PROCESS); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(title + " - Batch converter"); Console.WriteLine(); Console.WriteLine("- Syntax: SubtitleEdit /convert <pattern> <name-of-format-without-spaces> [/offset:hh:mm:ss:ms] [/encoding:<encoding name>] [/fps:<frame rate>] [/targetfps:<frame rate>] [/inputfolder:<input folder>] [/outputfolder:<output folder>] [/removetextforhi] [/fixcommonerrors] [/pac-codepage:<code page>]"); Console.WriteLine(); Console.WriteLine(" example: SubtitleEdit /convert *.srt sami"); Console.WriteLine(" list available formats: SubtitleEdit /convert /list"); Console.WriteLine(); string currentDir = Directory.GetCurrentDirectory(); if (args.Length < 4) { if (args.Length == 3 && (args[2].Equals("/list", StringComparison.OrdinalIgnoreCase) || args[2].Equals("-list", StringComparison.OrdinalIgnoreCase))) { Console.WriteLine("- Supported formats (input/output):"); foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats) { Console.WriteLine(" " + format.Name.Replace(" ", string.Empty)); } Console.WriteLine(); Console.WriteLine("- Supported formats (input only):"); Console.WriteLine(" " + CapMakerPlus.NameOfFormat); Console.WriteLine(" " + Captionate.NameOfFormat); Console.WriteLine(" " + Cavena890.NameOfFormat); Console.WriteLine(" " + CheetahCaption.NameOfFormat); Console.WriteLine(" " + Chk.NameOfFormat); Console.WriteLine(" Matroska (.mkv)"); Console.WriteLine(" Matroska subtitle (.mks)"); Console.WriteLine(" " + NciCaption.NameOfFormat); Console.WriteLine(" " + AvidStl.NameOfFormat); Console.WriteLine(" " + Pac.NameOfFormat); Console.WriteLine(" " + Spt.NameOfFormat); Console.WriteLine(" " + Ultech130.NameOfFormat); Console.WriteLine("- For Blu-ray .sup output use: '" + BatchConvert.BluRaySubtitle.Replace(" ", string.Empty) + "'"); Console.WriteLine("- For VobSub .sub output use: '" + BatchConvert.VobSubSubtitle.Replace(" ", string.Empty) + "'"); } Console.WriteLine(); Console.Write(currentDir + ">"); if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux()) { NativeMethods.FreeConsole(); } Environment.Exit(1); } int count = 0; int converted = 0; int errors = 0; try { string pattern = args[2]; string toFormat = args[3]; string offset = GetArgument(args, "/offset:"); var fps = GetArgument(args, "/fps:"); if (fps.Length > 6) { fps = fps.Remove(0, 5).Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".").Trim(); double d; if (double.TryParse(fps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d)) { Configuration.Settings.General.CurrentFrameRate = d; } } var targetFps = GetArgument(args, "/targetfps:"); double?targetFrameRate = null; if (targetFps.Length > 12) { targetFps = targetFps.Remove(0, 11).Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".").Trim(); double d; if (double.TryParse(targetFps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d)) { targetFrameRate = d; } } var targetEncodingName = GetArgument(args, "/encoding:");; var targetEncoding = Encoding.UTF8; try { if (!string.IsNullOrEmpty(targetEncodingName)) { targetEncodingName = targetEncodingName.Substring(10); if (!string.IsNullOrEmpty(targetEncodingName)) { targetEncoding = Encoding.GetEncoding(targetEncodingName); } } } catch (Exception exception) { Console.WriteLine("Unable to set encoding (" + exception.Message + ") - using UTF-8"); targetEncoding = Encoding.UTF8; } var outputFolder = GetArgument(args, "/outputfolder:");; if (outputFolder.Length > "/outputFolder:".Length) { outputFolder = outputFolder.Remove(0, "/outputFolder:".Length); if (!Directory.Exists(outputFolder)) { outputFolder = string.Empty; } } var inputFolder = GetArgument(args, "/inputFolder:", Directory.GetCurrentDirectory()); if (inputFolder.Length > "/inputFolder:".Length) { inputFolder = inputFolder.Remove(0, "/inputFolder:".Length); if (!Directory.Exists(inputFolder)) { inputFolder = Directory.GetCurrentDirectory(); } } var pacCodePage = GetArgument(args, "/pac-codepage:"); if (pacCodePage.Length > "/pac-codepage:".Length) { pacCodePage = pacCodePage.Remove(0, "/pac-codepage:".Length); if (string.Compare("Latin", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0) { pacCodePage = "0"; } else if (string.Compare("Greek", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0) { pacCodePage = "1"; } else if (string.Compare("Czech", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0) { pacCodePage = "2"; } else if (string.Compare("Arabic", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0) { pacCodePage = "3"; } else if (string.Compare("Hebrew", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0) { pacCodePage = "4"; } else if (string.Compare("Encoding", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0) { pacCodePage = "5"; } else if (string.Compare("Cyrillic", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0) { pacCodePage = "6"; } } bool overwrite = GetArgument(args, "/overwrite", string.Empty).Equals("/overwrite"); bool removeTextForHi = GetArgument(args, "/removetextforhi", string.Empty).Equals("/removetextforhi"); bool fixCommonErrors = GetArgument(args, "/fixcommonerrors", string.Empty).Equals("/fixcommonerrors"); bool redoCasing = GetArgument(args, "/redocasing", string.Empty).Equals("/redocasing"); string[] files; string inputDirectory = Directory.GetCurrentDirectory(); if (!string.IsNullOrEmpty(inputFolder)) { inputDirectory = inputFolder; } if (pattern.Contains(',') && !File.Exists(pattern)) { files = pattern.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int k = 0; k < files.Length; k++) { files[k] = files[k].Trim(); } } else { int indexOfDirectorySeparatorChar = pattern.LastIndexOf(Path.DirectorySeparatorChar); if (indexOfDirectorySeparatorChar > 0 && indexOfDirectorySeparatorChar < pattern.Length) { pattern = pattern.Substring(indexOfDirectorySeparatorChar + 1); inputDirectory = args[2].Substring(0, indexOfDirectorySeparatorChar); } files = Directory.GetFiles(inputDirectory, pattern); } var formats = SubtitleFormat.AllSubtitleFormats; foreach (string fName in files) { string fileName = fName; count++; if (!string.IsNullOrEmpty(inputFolder) && File.Exists(Path.Combine(inputFolder, fileName))) { fileName = Path.Combine(inputFolder, fileName); } if (File.Exists(fileName)) { var sub = new Subtitle(); SubtitleFormat format = null; bool done = false; if (Path.GetExtension(fileName).Equals(".mkv", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(fileName).Equals(".mks", StringComparison.OrdinalIgnoreCase)) { using (var matroska = new MatroskaFile(fileName)) { if (matroska.IsValid) { var tracks = matroska.GetTracks(); if (tracks.Count > 0) { foreach (var track in tracks) { if (track.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("{0}: {1} - Cannot convert from VobSub image based format!", fileName, toFormat); } else if (track.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("{0}: {1} - Cannot convert from Blu-ray image based format!", fileName, toFormat); } else { var ss = matroska.GetSubtitle(track.TrackNumber, null); format = Utilities.LoadMatroskaTextSubtitle(track, matroska, ss, sub); string newFileName = fileName; if (tracks.Count > 1) { newFileName = fileName.Insert(fileName.Length - 4, "_" + track.TrackNumber + "_" + track.Language.Replace("?", string.Empty).Replace("!", string.Empty).Replace("*", string.Empty).Replace(",", string.Empty).Replace("/", string.Empty).Trim()); } if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha)) { if (toFormat.ToLower() != AdvancedSubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty) && toFormat.ToLower() != SubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty)) { foreach (SubtitleFormat sf in formats) { if (sf.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || sf.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)) { format.RemoveNativeFormatting(sub, sf); break; } } } } BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing); done = true; } } } } } } if (FileUtil.IsBluRaySup(fileName)) { Console.WriteLine("Found Blu-Ray subtitle format"); ConvertBluRaySubtitle(fileName, toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing); done = true; } if (!done && FileUtil.IsVobSub(fileName)) { Console.WriteLine("Found VobSub subtitle format"); ConvertVobSubSubtitle(fileName, toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing); done = true; } var fi = new FileInfo(fileName); if (fi.Length < 10 * 1024 * 1024 && !done) // max 10 mb { Encoding encoding; format = sub.LoadSubtitle(fileName, out encoding, null, true); if (format == null || format.GetType() == typeof(Ebu)) { var ebu = new Ebu(); if (ebu.IsMine(null, fileName)) { ebu.LoadSubtitle(sub, null, fileName); format = ebu; } } if (format == null) { var pac = new Pac(); if (pac.IsMine(null, fileName)) { pac.BatchMode = true; if (!string.IsNullOrEmpty(pacCodePage) && Utilities.IsInteger(pacCodePage)) { pac.CodePage = int.Parse(pacCodePage); } else { pac.CodePage = -1; } pac.LoadSubtitle(sub, null, fileName); format = pac; } } if (format == null) { var cavena890 = new Cavena890(); if (cavena890.IsMine(null, fileName)) { cavena890.LoadSubtitle(sub, null, fileName); format = cavena890; } } if (format == null) { var spt = new Spt(); if (spt.IsMine(null, fileName)) { spt.LoadSubtitle(sub, null, fileName); format = spt; } } if (format == null) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.IsMine(null, fileName)) { cheetahCaption.LoadSubtitle(sub, null, fileName); format = cheetahCaption; } } if (format == null) { var chk = new Chk(); if (chk.IsMine(null, fileName)) { chk.LoadSubtitle(sub, null, fileName); format = chk; } } if (format == null) { var ayato = new Ayato(); if (ayato.IsMine(null, fileName)) { ayato.LoadSubtitle(sub, null, fileName); format = ayato; } } if (format == null) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.IsMine(null, fileName)) { capMakerPlus.LoadSubtitle(sub, null, fileName); format = capMakerPlus; } } if (format == null) { var captionate = new Captionate(); if (captionate.IsMine(null, fileName)) { captionate.LoadSubtitle(sub, null, fileName); format = captionate; } } if (format == null) { var ultech130 = new Ultech130(); if (ultech130.IsMine(null, fileName)) { ultech130.LoadSubtitle(sub, null, fileName); format = ultech130; } } if (format == null) { var nciCaption = new NciCaption(); if (nciCaption.IsMine(null, fileName)) { nciCaption.LoadSubtitle(sub, null, fileName); format = nciCaption; } } if (format == null) { var tsb4 = new TSB4(); if (tsb4.IsMine(null, fileName)) { tsb4.LoadSubtitle(sub, null, fileName); format = tsb4; } } if (format == null) { var avidStl = new AvidStl(); if (avidStl.IsMine(null, fileName)) { avidStl.LoadSubtitle(sub, null, fileName); format = avidStl; } } if (format == null) { var elr = new ELRStudioClosedCaption(); if (elr.IsMine(null, fileName)) { elr.LoadSubtitle(sub, null, fileName); format = elr; } } } if (format == null) { if (fi.Length < 1024 * 1024) // max 1 mb { Console.WriteLine("{0}: {1} - input file format unknown!", fileName, toFormat); } else { Console.WriteLine("{0}: {1} - input file too large!", fileName, toFormat); } } else if (!done) { BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing); } } else { Console.WriteLine("{0}: {1} - file not found!", count, fileName); errors++; } } } catch (Exception exception) { Console.WriteLine(); Console.WriteLine("Ups - an error occured: " + exception.Message); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("{0} file(s) converted", converted); Console.WriteLine(); Console.Write(currentDir + ">"); if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux()) { NativeMethods.FreeConsole(); } if (count == converted && errors == 0) { Environment.Exit(0); } else { Environment.Exit(1); } }
public ModifySelection(Subtitle subtitle, SubtitleFormat format, SubtitleListView subtitleListView) { UiUtil.PreInitialize(this); InitializeComponent(); UiUtil.FixFonts(this); _loading = true; _subtitle = subtitle; _format = format; _subtitleListView = subtitleListView; labelInfo.Text = string.Empty; comboBoxRule.SelectedIndex = 0; Text = Configuration.Settings.Language.ModifySelection.Title; buttonOK.Text = Configuration.Settings.Language.General.Ok; buttonCancel.Text = Configuration.Settings.Language.General.Cancel; buttonApply.Text = Configuration.Settings.Language.General.Apply; groupBoxRule.Text = Configuration.Settings.Language.ModifySelection.Rule; groupBoxWhatToDo.Text = Configuration.Settings.Language.ModifySelection.DoWithMatches; checkBoxCaseSensitive.Text = Configuration.Settings.Language.ModifySelection.CaseSensitive; radioButtonNewSelection.Text = Configuration.Settings.Language.ModifySelection.MakeNewSelection; radioButtonAddToSelection.Text = Configuration.Settings.Language.ModifySelection.AddToCurrentSelection; radioButtonSubtractFromSelection.Text = Configuration.Settings.Language.ModifySelection.SubtractFromCurrentSelection; radioButtonIntersect.Text = Configuration.Settings.Language.ModifySelection.IntersectWithCurrentSelection; columnHeaderApply.Text = Configuration.Settings.Language.General.Apply; columnHeaderLine.Text = Configuration.Settings.Language.General.LineNumber; columnHeaderText.Text = Configuration.Settings.Language.General.Text; toolStripMenuItemInverseSelection.Text = Configuration.Settings.Language.Main.Menu.Edit.InverseSelection; toolStripMenuItemSelectAll.Text = Configuration.Settings.Language.Main.Menu.ContextMenu.SelectAll; listViewStyles.Visible = false; UiUtil.FixLargeFonts(this, buttonOK); comboBoxRule.Items.Clear(); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.Contains); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.StartsWith); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.EndsWith); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.NoContains); comboBoxRule.Items.Add(Configuration.Settings.Language.ChangeCasing.AllUppercase); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.RegEx); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.UnequalLines); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.EqualLines); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.DurationLessThan); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.DurationGreaterThan); comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.MoreThanTwoLines); if (_format.HasStyleSupport) { comboBoxRule.Items.Add(Configuration.Settings.Language.General.Style); } if (_format.HasStyleSupport && (_format.GetType() == typeof(AdvancedSubStationAlpha) || _format.GetType() == typeof(SubStationAlpha))) { comboBoxRule.Items.Add(Configuration.Settings.Language.General.Actor); } checkBoxCaseSensitive.Checked = Configuration.Settings.Tools.ModifySelectionCaseSensitive; textBoxText.Text = Configuration.Settings.Tools.ModifySelectionText; if (Configuration.Settings.Tools.ModifySelectionRule == "Starts with") { comboBoxRule.SelectedIndex = FunctionStartsWith; } else if (Configuration.Settings.Tools.ModifySelectionRule == "Ends with") { comboBoxRule.SelectedIndex = FunctionEndsWith; } else if (Configuration.Settings.Tools.ModifySelectionRule == "Not contains") { comboBoxRule.SelectedIndex = FunctionNotContains; } else if (Configuration.Settings.Tools.ModifySelectionRule == "AllUppercase") { comboBoxRule.SelectedIndex = FunctionAlUppercase; } else if (Configuration.Settings.Tools.ModifySelectionRule == "RegEx") { comboBoxRule.SelectedIndex = FunctionRegEx; } else if (Configuration.Settings.Tools.ModifySelectionRule == "Duration <") { comboBoxRule.SelectedIndex = FunctionDurationLessThan; } else if (Configuration.Settings.Tools.ModifySelectionRule == "Duration >") { comboBoxRule.SelectedIndex = FunctionDurationGreaterThan; } else if (Configuration.Settings.Tools.ModifySelectionRule == "More than two lines") { comboBoxRule.SelectedIndex = FunctionMoreThanTwoLines; } else if (Configuration.Settings.Tools.ModifySelectionRule == "Style" && _format.HasStyleSupport) { comboBoxRule.SelectedIndex = FunctionStyle; } else if (Configuration.Settings.Tools.ModifySelectionRule == "Actor" && (_format.GetType() == typeof(AdvancedSubStationAlpha) || _format.GetType() == typeof(SubStationAlpha))) { comboBoxRule.SelectedIndex = FunctionActor; } else { comboBoxRule.SelectedIndex = 0; } if (!_format.HasStyleSupport) { listViewFixes.Columns.Remove(columnHeaderStyle); } ModifySelection_Resize(null, null); _loading = false; Preview(); }
public ModifySelection(Subtitle subtitle, SubtitleFormat format, SubtitleListView subtitleListView) { UiUtil.PreInitialize(this); InitializeComponent(); UiUtil.FixFonts(this); _loading = true; _subtitle = subtitle; _format = format; _subtitleListView = subtitleListView; labelInfo.Text = string.Empty; comboBoxRule.SelectedIndex = 0; Text = LanguageSettings.Current.ModifySelection.Title; buttonOK.Text = LanguageSettings.Current.General.Ok; buttonCancel.Text = LanguageSettings.Current.General.Cancel; buttonApply.Text = LanguageSettings.Current.General.Apply; groupBoxRule.Text = LanguageSettings.Current.ModifySelection.Rule; groupBoxWhatToDo.Text = LanguageSettings.Current.ModifySelection.DoWithMatches; checkBoxCaseSensitive.Text = LanguageSettings.Current.ModifySelection.CaseSensitive; radioButtonNewSelection.Text = LanguageSettings.Current.ModifySelection.MakeNewSelection; radioButtonAddToSelection.Text = LanguageSettings.Current.ModifySelection.AddToCurrentSelection; radioButtonSubtractFromSelection.Text = LanguageSettings.Current.ModifySelection.SubtractFromCurrentSelection; radioButtonIntersect.Text = LanguageSettings.Current.ModifySelection.IntersectWithCurrentSelection; columnHeaderApply.Text = LanguageSettings.Current.General.Apply; columnHeaderLine.Text = LanguageSettings.Current.General.LineNumber; columnHeaderText.Text = LanguageSettings.Current.General.Text; toolStripMenuItemInverseSelection.Text = LanguageSettings.Current.Main.Menu.Edit.InverseSelection; toolStripMenuItemSelectAll.Text = LanguageSettings.Current.Main.Menu.ContextMenu.SelectAll; listViewStyles.Visible = false; UiUtil.FixLargeFonts(this, buttonOK); comboBoxRule.Items.Clear(); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.Contains); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.StartsWith); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.EndsWith); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.NoContains); comboBoxRule.Items.Add(LanguageSettings.Current.ChangeCasing.AllUppercase); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.RegEx); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.OddLines); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.EvenLines); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.DurationLessThan); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.DurationGreaterThan); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.ExactlyOneLine); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.ExactlyTwoLines); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.MoreThanTwoLines); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.Bookmarked); comboBoxRule.Items.Add(LanguageSettings.Current.ModifySelection.BlankLines); if (_format.HasStyleSupport) { comboBoxRule.Items.Add(LanguageSettings.Current.General.Style); } if (_format.HasStyleSupport && (_format.GetType() == typeof(AdvancedSubStationAlpha) || _format.GetType() == typeof(SubStationAlpha))) { comboBoxRule.Items.Add(LanguageSettings.Current.General.Actor); } checkBoxCaseSensitive.Checked = Configuration.Settings.Tools.ModifySelectionCaseSensitive; textBoxText.Text = Configuration.Settings.Tools.ModifySelectionText; switch (Configuration.Settings.Tools.ModifySelectionRule) { case StartsWith: comboBoxRule.SelectedIndex = FunctionStartsWith; break; case EndsWith: comboBoxRule.SelectedIndex = FunctionEndsWith; break; case NotContains: comboBoxRule.SelectedIndex = FunctionNotContains; break; case AllUppercase: comboBoxRule.SelectedIndex = FunctionAllUppercase; break; case RegEx: comboBoxRule.SelectedIndex = FunctionRegEx; break; case Odd: comboBoxRule.SelectedIndex = FunctionOdd; break; case Even: comboBoxRule.SelectedIndex = FunctionEven; break; case DurationLessThan: comboBoxRule.SelectedIndex = FunctionDurationLessThan; break; case DurationGreaterThan: comboBoxRule.SelectedIndex = FunctionDurationGreaterThan; break; case ExactlyOneLine: comboBoxRule.SelectedIndex = FunctionExactlyOneLine; break; case ExactlyTwoLines: comboBoxRule.SelectedIndex = FunctionExactlyTwoLines; break; case MoreThanTwoLines: comboBoxRule.SelectedIndex = FunctionMoreThanTwoLines; break; case Bookmarked: comboBoxRule.SelectedIndex = FunctionBookmarked; break; case BlankLines: comboBoxRule.SelectedIndex = FunctionBlankLines; break; case Style when _format.HasStyleSupport: comboBoxRule.SelectedIndex = FunctionStyle; break; case Actor when _format.GetType() == typeof(AdvancedSubStationAlpha) || _format.GetType() == typeof(SubStationAlpha): comboBoxRule.SelectedIndex = FunctionActor; break; default: comboBoxRule.SelectedIndex = FunctionContains; break; } if (!_format.HasStyleSupport) { listViewFixes.Columns.Remove(columnHeaderStyle); } _loading = false; Preview(); }
internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList <SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage, double?targetFrameRate) { double oldFrameRate = Configuration.Settings.General.CurrentFrameRate; try { // adjust offset if (!string.IsNullOrEmpty(offset) && (offset.StartsWith("/offset:") || offset.StartsWith("offset:"))) { string[] parts = offset.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 5) { try { var ts = new TimeSpan(0, int.Parse(parts[1].TrimStart('-')), int.Parse(parts[2]), int.Parse(parts[3]), int.Parse(parts[4])); if (parts[1].StartsWith('-')) { sub.AddTimeToAllParagraphs(ts.Negate()); } else { sub.AddTimeToAllParagraphs(ts); } } catch { Console.Write(" (unable to read offset " + offset + ")"); } } } // adjust frame rate if (targetFrameRate.HasValue) { sub.ChangeFrameRate(Configuration.Settings.General.CurrentFrameRate, targetFrameRate.Value); Configuration.Settings.General.CurrentFrameRate = targetFrameRate.Value; } bool targetFormatFound = false; string outputFileName; foreach (SubtitleFormat sf in formats) { if (sf.IsTextBased && (sf.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || sf.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))) { targetFormatFound = true; sf.BatchMode = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, sf.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); if (sf.IsFrameBased && !sub.WasLoadedWithFrameNumbers) { sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate); } else if (sf.IsTimeBased && sub.WasLoadedWithFrameNumbers) { sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); } if ((sf.GetType() == typeof(WebVTT) || sf.GetType() == typeof(WebVTTFileWithLineNumber))) { targetEncoding = Encoding.UTF8; } if (sf.GetType() == typeof(ItunesTimedText) || sf.GetType() == typeof(ScenaristClosedCaptions) || sf.GetType() == typeof(ScenaristClosedCaptionsDropFrame)) { Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM using (var file = new StreamWriter(outputFileName, false, outputEnc)) // open file with encoding { file.Write(sub.ToText(sf)); } // save and close it } else if (targetEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml))) { Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM using (var file = new StreamWriter(outputFileName, false, outputEnc)) // open file with encoding { file.Write(sub.ToText(sf)); } // save and close it } else { try { File.WriteAllText(outputFileName, sub.ToText(sf), targetEncoding); } catch (Exception ex) { Console.WriteLine(ex.Message); errors++; return(false); } } if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern)) { var sami = (Sami)format; foreach (string className in Sami.GetStylesFromHeader(sub.Header)) { var newSub = new Subtitle(); foreach (Paragraph p in sub.Paragraphs) { if (p.Extra != null && p.Extra.Trim().Equals(className.Trim(), StringComparison.OrdinalIgnoreCase)) { newSub.Paragraphs.Add(p); } } if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count) { string s = fileName; if (s.LastIndexOf('.') > 0) { s = s.Insert(s.LastIndexOf('.'), "_" + className); } else { s += "_" + className + format.Extension; } outputFileName = FormatOutputFileNameForBatchConvert(s, sf.Extension, outputFolder, overwrite); File.WriteAllText(outputFileName, newSub.ToText(sf), targetEncoding); } } } Console.WriteLine(" done."); break; } } if (!targetFormatFound) { var ebu = new Ebu(); if (ebu.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); Ebu.Save(outputFileName, sub, true); Console.WriteLine(" done."); } } if (!targetFormatFound) { var pac = new Pac(); if (pac.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || toFormat.Equals("pac", StringComparison.OrdinalIgnoreCase) || toFormat.Equals(".pac", StringComparison.OrdinalIgnoreCase)) { pac.BatchMode = true; int codePage; if (!string.IsNullOrEmpty(pacCodePage) && int.TryParse(pacCodePage, out codePage)) { pac.CodePage = codePage; } targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); pac.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var cavena890 = new Cavena890(); if (cavena890.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); cavena890.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, cheetahCaption.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); CheetahCaption.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, capMakerPlus.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); CapMakerPlus.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { if (Configuration.Settings.Language.BatchConvert.PlainText == toFormat || Configuration.Settings.Language.BatchConvert.PlainText.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ".txt", outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); File.WriteAllText(outputFileName, ExportText.GeneratePlainText(sub, false, false, false, false, false, false, string.Empty, true, false, true, true, false), targetEncoding); Console.WriteLine(" done."); } } if (!targetFormatFound) { Console.WriteLine("{0}: {1} - target format '{2}' not found!", count, fileName, toFormat); errors++; return(false); } converted++; return(true); } finally { Configuration.Settings.General.CurrentFrameRate = oldFrameRate; } }
private static SubtitleFormat GetSubtitleFormat(SubtitleFormat format, string fileName, Subtitle sub, string pacCodePage) { if (format == null || format.GetType() == typeof(Ebu)) { var ebu = new Ebu(); if (ebu.IsMine(null, fileName)) { ebu.LoadSubtitle(sub, null, fileName); format = ebu; } } if (format == null) { var pac = new Pac(); if (pac.IsMine(null, fileName)) { pac.BatchMode = true; if (!string.IsNullOrEmpty(pacCodePage) && Utilities.IsInteger(pacCodePage)) { pac.CodePage = int.Parse(pacCodePage); } else { pac.CodePage = -1; } pac.LoadSubtitle(sub, null, fileName); format = pac; } } if (format == null) { var cavena890 = new Cavena890(); if (cavena890.IsMine(null, fileName)) { cavena890.LoadSubtitle(sub, null, fileName); format = cavena890; } } if (format == null) { var spt = new Spt(); if (spt.IsMine(null, fileName)) { spt.LoadSubtitle(sub, null, fileName); format = spt; } } if (format == null) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.IsMine(null, fileName)) { cheetahCaption.LoadSubtitle(sub, null, fileName); format = cheetahCaption; } } if (format == null) { var chk = new Chk(); if (chk.IsMine(null, fileName)) { chk.LoadSubtitle(sub, null, fileName); format = chk; } } if (format == null) { var ayato = new Ayato(); if (ayato.IsMine(null, fileName)) { ayato.LoadSubtitle(sub, null, fileName); format = ayato; } } if (format == null) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.IsMine(null, fileName)) { capMakerPlus.LoadSubtitle(sub, null, fileName); format = capMakerPlus; } } if (format == null) { var captionate = new Captionate(); if (captionate.IsMine(null, fileName)) { captionate.LoadSubtitle(sub, null, fileName); format = captionate; } } if (format == null) { var ultech130 = new Ultech130(); if (ultech130.IsMine(null, fileName)) { ultech130.LoadSubtitle(sub, null, fileName); format = ultech130; } } if (format == null) { var nciCaption = new NciCaption(); if (nciCaption.IsMine(null, fileName)) { nciCaption.LoadSubtitle(sub, null, fileName); format = nciCaption; } } if (format == null) { var tsb4 = new TSB4(); if (tsb4.IsMine(null, fileName)) { tsb4.LoadSubtitle(sub, null, fileName); format = tsb4; } } if (format == null) { var avidStl = new AvidStl(); if (avidStl.IsMine(null, fileName)) { avidStl.LoadSubtitle(sub, null, fileName); format = avidStl; } } if (format == null) { var elr = new ELRStudioClosedCaption(); if (elr.IsMine(null, fileName)) { elr.LoadSubtitle(sub, null, fileName); format = elr; } } return format; }
private static SubtitleFormat ConvertToMatroska(MatroskaFile matroska, MatroskaTrackInfo track, SubtitleFormat format, Subtitle sub, string fileName, List<MatroskaTrackInfo> tracks, string toFormat, IList<SubtitleFormat> formats, string offset, Encoding targetEncoding, string outputFolder, int count, bool overwrite, string pacCodePage, double? targetFrameRate, ref int converted, ref int errors, ref bool done) { var ss = matroska.GetSubtitle(track.TrackNumber, null); format = Utilities.LoadMatroskaTextSubtitle(track, matroska, ss, sub); string newFileName = fileName; if (tracks.Count > 1) { newFileName = fileName .Insert(fileName.Length - 4, "_" + track.TrackNumber + "_" + track.Language .Replace("?", string.Empty) .Replace("!", string.Empty) .Replace("*", string.Empty) .Replace(",", string.Empty) .Replace("/", string.Empty) .Trim()); } bool isSubStationAlpha = format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha); if (isSubStationAlpha) { if (toFormat.ToLower() != AdvancedSubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty) && toFormat.ToLower() != SubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty)) { foreach (SubtitleFormat subtitleFormat in formats) { if (subtitleFormat .Name .Replace(" ", string.Empty) .Equals(toFormat, StringComparison.OrdinalIgnoreCase) || subtitleFormat .Name .Replace(" ", string.Empty) .Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)) { format.RemoveNativeFormatting(sub, subtitleFormat); break; } } } } BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, overwrite, pacCodePage, targetFrameRate); done = true; return format; }
internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList<SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage, double? targetFrameRate) { double oldFrameRate = Configuration.Settings.General.CurrentFrameRate; try { // adjust offset AdjustOffset(offset, sub); // adjust frame rate if (targetFrameRate.HasValue) { sub.ChangeFrameRate(Configuration.Settings.General.CurrentFrameRate, targetFrameRate.Value); Configuration.Settings.General.CurrentFrameRate = targetFrameRate.Value; } bool targetFormatFound = false; string outputFileName; foreach (SubtitleFormat subtitleFormat in formats) { if (subtitleFormat.IsTextBased && ( subtitleFormat.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || subtitleFormat.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))) { targetFormatFound = true; subtitleFormat.BatchMode = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, subtitleFormat.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); if (subtitleFormat.IsFrameBased && !sub.WasLoadedWithFrameNumbers) { sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate); } else if (subtitleFormat.IsTimeBased && sub.WasLoadedWithFrameNumbers) { sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); } if ((subtitleFormat.GetType() == typeof(WebVTT) || subtitleFormat.GetType() == typeof(WebVTTFileWithLineNumber))) { targetEncoding = Encoding.UTF8; } if (subtitleFormat.GetType() == typeof(ItunesTimedText) || subtitleFormat.GetType() == typeof(ScenaristClosedCaptions) || subtitleFormat.GetType() == typeof(ScenaristClosedCaptionsDropFrame)) { Encoding outputEnc = new UTF8Encoding(false); using (var file = new StreamWriter(outputFileName, false, outputEnc)) { file.Write(sub.ToText(subtitleFormat)); } } else if (targetEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml))) { Encoding outputEnc = new UTF8Encoding(false); using (var file = new StreamWriter(outputFileName, false, outputEnc)) { file.Write(sub.ToText(subtitleFormat)); } } else { try { File.WriteAllText(outputFileName, sub.ToText(subtitleFormat), targetEncoding); } catch (Exception ex) { Console.WriteLine(ex.Message); errors++; return false; } } if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern)) { //var sami = (Sami)format; foreach (string className in Sami.GetStylesFromHeader(sub.Header)) { var newSub = new Subtitle(); foreach (Paragraph p in sub.Paragraphs) { if (p.Extra != null && p.Extra.Trim().Equals(className.Trim(), StringComparison.OrdinalIgnoreCase)) { newSub.Paragraphs.Add(p); } } if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count) { string s = fileName; if (s.LastIndexOf('.') > 0) { s = s.Insert(s.LastIndexOf('.'), "_" + className); } else { s += "_" + className + format.Extension; } outputFileName = FormatOutputFileNameForBatchConvert(s, subtitleFormat.Extension, outputFolder, overwrite); File.WriteAllText(outputFileName, newSub.ToText(subtitleFormat), targetEncoding); } } } Console.WriteLine(" done."); break; } } if (!targetFormatFound) { var ebu = new Ebu(); if (ebu.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); Ebu.Save(outputFileName, sub, true); Console.WriteLine(" done."); } } if (!targetFormatFound) { var pac = new Pac(); if (pac.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || toFormat.Equals("pac", StringComparison.OrdinalIgnoreCase) || toFormat.Equals(".pac", StringComparison.OrdinalIgnoreCase)) { pac.BatchMode = true; int codePage; if (!string.IsNullOrEmpty(pacCodePage) && int.TryParse(pacCodePage, out codePage)) { pac.CodePage = codePage; } targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); pac.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var cavena890 = new Cavena890(); if (cavena890.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); cavena890.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, cheetahCaption.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); CheetahCaption.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, capMakerPlus.Extension, outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); CapMakerPlus.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { if (Configuration.Settings.Language.BatchConvert.PlainText == toFormat || Configuration.Settings.Language.BatchConvert.PlainText.Replace(" ", string.Empty) .Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ".txt", outputFolder, overwrite); Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName); File.WriteAllText(outputFileName, ExportText.GeneratePlainText(sub, false, false, false, false, false, false, string.Empty, true, false, true, true, false), targetEncoding); Console.WriteLine(" done."); } } if (!targetFormatFound) { Console.WriteLine("{0}: {1} - target format '{2}' not found!", count, fileName, toFormat); errors++; return false; } converted++; return true; } finally { Configuration.Settings.General.CurrentFrameRate = oldFrameRate; } }
public static void Convert(string title, string[] args) // E.g.: /convert *.txt SubRip { const int ATTACH_PARENT_PROCESS = -1; if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux()) { NativeMethods.AttachConsole(ATTACH_PARENT_PROCESS); } var currentFolder = Directory.GetCurrentDirectory(); Console.WriteLine(); Console.WriteLine(title + " - Batch converter"); Console.WriteLine(); if (args.Length < 4) { if (args.Length == 3 && (args[2].Equals("/list", StringComparison.OrdinalIgnoreCase) || args[2].Equals("-list", StringComparison.OrdinalIgnoreCase))) { Console.WriteLine("- Supported formats (input/output):"); foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats) { Console.WriteLine(" " + format.Name.Replace(" ", string.Empty)); } Console.WriteLine(); Console.WriteLine("- Supported formats (input only):"); Console.WriteLine(" " + CapMakerPlus.NameOfFormat); Console.WriteLine(" " + Captionate.NameOfFormat); Console.WriteLine(" " + Cavena890.NameOfFormat); Console.WriteLine(" " + CheetahCaption.NameOfFormat); Console.WriteLine(" " + Chk.NameOfFormat); Console.WriteLine(" Matroska (.mkv)"); Console.WriteLine(" Matroska subtitle (.mks)"); Console.WriteLine(" " + NciCaption.NameOfFormat); Console.WriteLine(" " + AvidStl.NameOfFormat); Console.WriteLine(" " + Pac.NameOfFormat); Console.WriteLine(" " + Spt.NameOfFormat); Console.WriteLine(" " + Ultech130.NameOfFormat); Console.WriteLine("- For Blu-ray .sup output use: '" + BatchConvert.BluRaySubtitle.Replace(" ", string.Empty) + "'"); Console.WriteLine("- For VobSub .sub output use: '" + BatchConvert.VobSubSubtitle.Replace(" ", string.Empty) + "'"); } else { Console.WriteLine("- Usage: SubtitleEdit /convert <pattern> <name-of-format-without-spaces> [<optional-parameters>]"); Console.WriteLine(); Console.WriteLine(" pattern:"); Console.WriteLine(" one or more file name patterns separated by commas"); Console.WriteLine(" relative patterns are relative to /inputfolder if specified"); Console.WriteLine(" optional-parameters:"); Console.WriteLine(" /offset:hh:mm:ss:ms"); Console.WriteLine(" /fps:<frame rate>"); Console.WriteLine(" /targetfps:<frame rate>"); Console.WriteLine(" /encoding:<encoding name>"); Console.WriteLine(" /pac-codepage:<code page>"); Console.WriteLine(" /inputfolder:<folder name>"); Console.WriteLine(" /outputfolder:<folder name>"); Console.WriteLine(" /removetextforhi"); Console.WriteLine(" /fixcommonerrors"); Console.WriteLine(" /redocasing"); Console.WriteLine(" /multiplereplace"); Console.WriteLine(); Console.WriteLine(" example: SubtitleEdit /convert *.srt sami"); Console.WriteLine(" list available formats: SubtitleEdit /convert /list"); } Console.WriteLine(); if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux()) { Console.Write(currentFolder + ">"); NativeMethods.FreeConsole(); } Environment.Exit(1); } int count = 0; int converted = 0; int errors = 0; try { var pattern = args[2].Trim(); var targetFormat = args[3].Trim().Replace(" ", string.Empty); var offset = GetArgument(args, "offset:"); double?targetFrameRate = null; { var fps = GetArgument(args, "targetfps:"); if (fps.Length > 1) { fps = fps.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "."); double d; if (double.TryParse(fps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d)) { targetFrameRate = d; } } fps = GetArgument(args, "fps:"); if (fps.Length > 1) { fps = fps.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "."); double d; if (double.TryParse(fps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d)) { Configuration.Settings.General.CurrentFrameRate = d; } } } var targetEncoding = Encoding.UTF8; try { var encodingName = GetArgument(args, "encoding:"); if (encodingName.Length > 0) { targetEncoding = Encoding.GetEncoding(encodingName); } } catch (Exception exception) { Console.WriteLine("Unable to set encoding (" + exception.Message + ") - using UTF-8"); } var outputFolder = string.Empty; { var folder = GetArgument(args, "outputfolder:"); if (folder.Length > 0 && Directory.Exists(folder)) { outputFolder = folder; } } var inputFolder = currentFolder; { var folder = GetArgument(args, "inputFolder:"); if (folder.Length > 0 && Directory.Exists(folder)) { inputFolder = folder; } } int pacCodePage = -1; { var pcp = GetArgument(args, "pac-codepage:"); if (pcp.Length > 0) { if (pcp.Equals("Latin", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageLatin; } else if (pcp.Equals("Greek", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageGreek; } else if (pcp.Equals("Czech", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageLatinCzech; } else if (pcp.Equals("Arabic", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageArabic; } else if (pcp.Equals("Hebrew", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageHebrew; } else if (pcp.Equals("Thai", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageThai; } else if (pcp.Equals("Cyrillic", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageCyrillic; } else if (pcp.Equals("CHT", StringComparison.OrdinalIgnoreCase) || pcp.Replace(" ", string.Empty).Equals("TraditionalChinese", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageChineseTraditional; } else if (pcp.Equals("CHS", StringComparison.OrdinalIgnoreCase) || pcp.Replace(" ", string.Empty).Equals("SimplifiedChinese", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageChineseSimplified; } else if (pcp.Equals("Korean", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageKorean; } else if (pcp.Equals("Japanese", StringComparison.OrdinalIgnoreCase)) { pacCodePage = Pac.CodePageJapanese; } else if (!int.TryParse(pcp, out pacCodePage) || !Pac.IsValidCodePage(pacCodePage)) { Console.WriteLine("Unknown pac code page '" + pcp + "' - using default code page"); pacCodePage = -1; } } } bool overwrite = GetArgument(args, "overwrite").Equals("overwrite"); bool removeTextForHi = GetArgument(args, "removetextforhi").Equals("removetextforhi"); bool fixCommonErrors = GetArgument(args, "fixcommonerrors").Equals("fixcommonerrors"); bool redoCasing = GetArgument(args, "redocasing").Equals("redocasing"); bool multipleReplace = GetArgument(args, "multiplereplace").Equals("multiplereplace"); var patterns = Enumerable.Empty <string>(); if (pattern.Contains(',') && !File.Exists(pattern)) { patterns = pattern.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(fn => fn.Trim()).Where(fn => fn.Length > 0); } else { patterns = patterns.DefaultIfEmpty(pattern); } var files = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (var p in patterns) { var folderName = Path.GetDirectoryName(p); var fileName = Path.GetFileName(p); if (string.IsNullOrEmpty(folderName) || string.IsNullOrEmpty(fileName)) { folderName = inputFolder; fileName = p; } else if (!Path.IsPathRooted(folderName)) { folderName = Path.Combine(inputFolder, folderName); } foreach (var fn in Directory.EnumerateFiles(folderName, fileName)) { files.Add(fn); // silently ignore duplicates } } var formats = SubtitleFormat.AllSubtitleFormats; foreach (var fileName in files) { count++; var fileInfo = new FileInfo(fileName); if (fileInfo.Exists) { var sub = new Subtitle(); SubtitleFormat format = null; bool done = false; if (fileInfo.Extension.Equals(".mkv", StringComparison.OrdinalIgnoreCase) || fileInfo.Extension.Equals(".mks", StringComparison.OrdinalIgnoreCase)) { using (var matroska = new MatroskaFile(fileName)) { if (matroska.IsValid) { var tracks = matroska.GetTracks(); if (tracks.Count > 0) { foreach (var track in tracks) { if (track.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("{0}: {1} - Cannot convert from VobSub image based format!", fileName, targetFormat); } else if (track.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("{0}: {1} - Cannot convert from Blu-ray image based format!", fileName, targetFormat); } else { var ss = matroska.GetSubtitle(track.TrackNumber, null); format = Utilities.LoadMatroskaTextSubtitle(track, matroska, ss, sub); string newFileName = fileName; if (tracks.Count > 1) { newFileName = fileName.Insert(fileName.Length - 4, "_" + track.TrackNumber + "_" + track.Language.Replace("?", string.Empty).Replace("!", string.Empty).Replace("*", string.Empty).Replace(",", string.Empty).Replace("/", string.Empty).Trim()); } if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha)) { if (!AdvancedSubStationAlpha.NameOfFormat.Replace(" ", string.Empty).Equals(targetFormat, StringComparison.OrdinalIgnoreCase) && !SubStationAlpha.NameOfFormat.Replace(" ", string.Empty).Equals(targetFormat, StringComparison.OrdinalIgnoreCase)) { foreach (SubtitleFormat sf in formats) { if (sf.Name.Replace(" ", string.Empty).Equals(targetFormat, StringComparison.OrdinalIgnoreCase)) { format.RemoveNativeFormatting(sub, sf); break; } } } } BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing, multipleReplace); done = true; } } } } } } if (!done && FileUtil.IsBluRaySup(fileName)) { Console.WriteLine("Found Blu-Ray subtitle format"); ConvertBluRaySubtitle(fileName, targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing, multipleReplace); done = true; } if (!done && FileUtil.IsVobSub(fileName)) { Console.WriteLine("Found VobSub subtitle format"); ConvertVobSubSubtitle(fileName, targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing, multipleReplace); done = true; } if (!done && fileInfo.Length < 10 * 1024 * 1024) // max 10 mb { Encoding encoding; format = sub.LoadSubtitle(fileName, out encoding, null, true); if (format == null || format.GetType() == typeof(Ebu)) { var ebu = new Ebu(); if (ebu.IsMine(null, fileName)) { ebu.LoadSubtitle(sub, null, fileName); format = ebu; } } if (format == null) { var pac = new Pac(); if (pac.IsMine(null, fileName)) { pac.BatchMode = true; pac.CodePage = pacCodePage; pac.LoadSubtitle(sub, null, fileName); format = pac; } } if (format == null) { var cavena890 = new Cavena890(); if (cavena890.IsMine(null, fileName)) { cavena890.LoadSubtitle(sub, null, fileName); format = cavena890; } } if (format == null) { var spt = new Spt(); if (spt.IsMine(null, fileName)) { spt.LoadSubtitle(sub, null, fileName); format = spt; } } if (format == null) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.IsMine(null, fileName)) { cheetahCaption.LoadSubtitle(sub, null, fileName); format = cheetahCaption; } } if (format == null) { var chk = new Chk(); if (chk.IsMine(null, fileName)) { chk.LoadSubtitle(sub, null, fileName); format = chk; } } if (format == null) { var ayato = new Ayato(); if (ayato.IsMine(null, fileName)) { ayato.LoadSubtitle(sub, null, fileName); format = ayato; } } if (format == null) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.IsMine(null, fileName)) { capMakerPlus.LoadSubtitle(sub, null, fileName); format = capMakerPlus; } } if (format == null) { var captionate = new Captionate(); if (captionate.IsMine(null, fileName)) { captionate.LoadSubtitle(sub, null, fileName); format = captionate; } } if (format == null) { var ultech130 = new Ultech130(); if (ultech130.IsMine(null, fileName)) { ultech130.LoadSubtitle(sub, null, fileName); format = ultech130; } } if (format == null) { var nciCaption = new NciCaption(); if (nciCaption.IsMine(null, fileName)) { nciCaption.LoadSubtitle(sub, null, fileName); format = nciCaption; } } if (format == null) { var tsb4 = new TSB4(); if (tsb4.IsMine(null, fileName)) { tsb4.LoadSubtitle(sub, null, fileName); format = tsb4; } } if (format == null) { var avidStl = new AvidStl(); if (avidStl.IsMine(null, fileName)) { avidStl.LoadSubtitle(sub, null, fileName); format = avidStl; } } if (format == null) { var elr = new ELRStudioClosedCaption(); if (elr.IsMine(null, fileName)) { elr.LoadSubtitle(sub, null, fileName); format = elr; } } } if (format == null) { if (fileInfo.Length < 1024 * 1024) // max 1 mb { Console.WriteLine("{0}: {1} - input file format unknown!", fileName, targetFormat); } else { Console.WriteLine("{0}: {1} - input file too large!", fileName, targetFormat); } } else if (!done) { BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing, multipleReplace); } } else { Console.WriteLine("{0}: {1} - file not found!", count, fileName); errors++; } } } catch (Exception exception) { Console.WriteLine(); Console.WriteLine("Oops - an error occured: " + exception.Message); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("{0} file(s) converted", converted); Console.WriteLine(); if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux()) { Console.Write(currentFolder + ">"); NativeMethods.FreeConsole(); } if (count == converted && errors == 0) { Environment.Exit(0); } else { Environment.Exit(1); } }