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; } }
private void AppendTextVisuallyToolStripMenuItemClick(object sender, EventArgs e) { if (IsSubtitleLoaded) { ReloadFromSourceView(); if (MessageBox.Show(_language.SubtitleAppendPrompt, _language.SubtitleAppendPromptTitle, MessageBoxButtons.YesNoCancel) == DialogResult.Yes) { openFileDialog1.Title = _language.OpenSubtitleToAppend; openFileDialog1.FileName = string.Empty; openFileDialog1.Filter = Utilities.GetOpenDialogFilter(); if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { bool success = false; string fileName = openFileDialog1.FileName; if (File.Exists(fileName)) { var subtitleToAppend = new Subtitle(); Encoding encoding; SubtitleFormat format = null; // do not allow blu-ray/vobsub string extension = Path.GetExtension(fileName).ToLower(); if (extension == ".sub" && (IsVobSubFile(fileName, false) || IsSpDvdSupFile(fileName))) { format = null; } else if (extension == ".sup" && IsBluRaySupFile(fileName)) { format = null; } else { format = subtitleToAppend.LoadSubtitle(fileName, out encoding, null); if (GetCurrentSubtitleFormat().IsFrameBased) subtitleToAppend.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate); else subtitleToAppend.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); } if (format != null) { if (subtitleToAppend != null && subtitleToAppend.Paragraphs.Count > 1) { var visualSync = new VisualSync(); visualSync.Initialize(toolStripButtonVisualSync.Image as Bitmap, subtitleToAppend, _fileName, _language.AppendViaVisualSyncTitle, CurrentFrameRate); visualSync.ShowDialog(this); if (visualSync.OKPressed) { if (MessageBox.Show(_language.AppendSynchronizedSubtitlePrompt, _language.SubtitleAppendPromptTitle, MessageBoxButtons.YesNo) == DialogResult.Yes) { int start = _subtitle.Paragraphs.Count +1; var fr = CurrentFrameRate; MakeHistoryForUndo(_language.BeforeAppend); foreach (Paragraph p in visualSync.Paragraphs) { if (format.IsFrameBased) p.CalculateFrameNumbersFromTimeCodes(fr); _subtitle.Paragraphs.Add(new Paragraph(p)); } if (format.GetType() == typeof(AdvancedSubStationAlpha) && GetCurrentSubtitleFormat().GetType() == typeof(AdvancedSubStationAlpha)) { List<string> currentStyles = new List<string>(); if (_subtitle.Header != null) currentStyles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header); foreach (string styleName in AdvancedSubStationAlpha.GetStylesFromHeader(subtitleToAppend.Header)) { bool alreadyExists = false; foreach (string currentStyleName in currentStyles) { if (currentStyleName.ToLower().Trim() == styleName.ToLower().Trim()) alreadyExists = true; } if (!alreadyExists) { var newStyle = AdvancedSubStationAlpha.GetSsaStyle(styleName, subtitleToAppend.Header); _subtitle.Header = AdvancedSubStationAlpha.AddSsaStyle(newStyle, _subtitle.Header); } } } _subtitle.Renumber(1); ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); // select appended lines for (int i = start; i < _subtitle.Paragraphs.Count; i++) SubtitleListview1.Items[i].Selected = true; SubtitleListview1.EnsureVisible(start); ShowStatus(string.Format(_language.SubtitleAppendedX, fileName)); success = true; } } visualSync.Dispose(); } } } if (!success) ShowStatus(_language.SubtitleNotAppended); } } } else { MessageBox.Show(_language.NoSubtitleLoaded, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
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) { // adjust offset if (!string.IsNullOrEmpty(offset) && (offset.StartsWith("/offset:") || offset.StartsWith("offset:"))) { string[] parts = offset.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 5) { try { TimeSpan 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 + ")"); } } } bool targetFormatFound = false; string outputFileName; foreach (SubtitleFormat sf in formats) { if (sf.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower() || sf.Name.ToLower().Replace(" ", string.Empty) == toFormat.Replace(" ", string.Empty).ToLower()) { targetFormatFound = true; sf.BatchMode = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, sf.Extension, outputFolder, overwrite); Console.Write(string.Format("{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); File.WriteAllText(outputFileName, sub.ToText(sf), targetEncoding); 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.ToLower().Trim() == className.ToLower().Trim()) 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."); } } if (!targetFormatFound) { var ebu = new Ebu(); if (ebu.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower()) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite); Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName)); ebu.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var pac = new Pac(); if (pac.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower() || toFormat.ToLower() == "pac" || toFormat.ToLower() == ".pac") { pac.BatchMode = true; if (!string.IsNullOrEmpty(pacCodePage) && Utilities.IsInteger(pacCodePage)) pac.CodePage = Convert.ToInt32(pacCodePage); targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite); Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName)); pac.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var cavena890 = new Cavena890(); if (cavena890.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower()) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite); Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName)); cavena890.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower()) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, cheetahCaption.Extension, outputFolder, overwrite); Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName)); cheetahCaption.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.Name.ToLower().Replace(" ", string.Empty) == toFormat.ToLower()) { targetFormatFound = true; outputFileName = FormatOutputFileNameForBatchConvert(fileName, capMakerPlus.Extension, outputFolder, overwrite); Console.Write(string.Format("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName)); capMakerPlus.Save(outputFileName, sub); Console.WriteLine(" done."); } } if (!targetFormatFound) { Console.WriteLine(string.Format("{0}: {1} - target format '{2}' not found!", count, fileName, toFormat)); errors++; return false; } else { converted++; return true; } }
private void ToolStripMenuItemInsertSubtitleClick(object sender, EventArgs e) { openFileDialog1.Title = _languageGeneral.OpenSubtitle; openFileDialog1.FileName = string.Empty; openFileDialog1.Filter = Utilities.GetOpenDialogFilter(); if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { if (!File.Exists(openFileDialog1.FileName)) return; var fi = new FileInfo(openFileDialog1.FileName); if (fi.Length > 1024 * 1024 * 10) // max 10 mb { if (MessageBox.Show(string.Format(_language.FileXIsLargerThan10Mb + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, openFileDialog1.FileName), Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes) return; } MakeHistoryForUndo(string.Format(_language.BeforeInsertLine, openFileDialog1.FileName)); Encoding encoding = null; var subtitle = new Subtitle(); SubtitleFormat format = subtitle.LoadSubtitle(openFileDialog1.FileName, out encoding, encoding); if (format != null) { SaveSubtitleListviewIndexes(); if (format.IsFrameBased) subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate); else subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); if (Configuration.Settings.General.RemoveBlankLinesWhenOpening) subtitle.RemoveEmptyLines(); int index = FirstSelectedIndex + 1; if (index < 0) index = 0; foreach (Paragraph p in subtitle.Paragraphs) { _subtitle.Paragraphs.Insert(index, new Paragraph(p)); index++; } if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0) { index = FirstSelectedIndex; if (index < 0) index = 0; Paragraph current = _subtitle.GetParagraphOrDefault(index); if (current != null) { Paragraph original = Utilities.GetOriginalParagraph(index, current, _subtitleAlternate.Paragraphs); if (original != null) { index = _subtitleAlternate.GetIndex(original); foreach (Paragraph p in subtitle.Paragraphs) { _subtitleAlternate.Paragraphs.Insert(index, new Paragraph(p)); index++; } if (subtitle.Paragraphs.Count > 0) _subtitleAlternate.Renumber(1); } } } _subtitle.Renumber(1); ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); RestoreSubtitleListviewIndexes(); } } }
private void toolStripMenuItemInsertTextFromSub_Click(object sender, EventArgs e) { openFileDialog1.Title = _languageGeneral.OpenSubtitle; openFileDialog1.FileName = string.Empty; openFileDialog1.Filter = Utilities.GetOpenDialogFilter(); if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { if (!File.Exists(openFileDialog1.FileName)) return; var fi = new FileInfo(openFileDialog1.FileName); if (fi.Length > 1024 * 1024 * 10) // max 10 mb { if (MessageBox.Show(string.Format(_language.FileXIsLargerThan10Mb + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, openFileDialog1.FileName), Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes) return; } Encoding encoding = null; var tmp = new Subtitle(); SubtitleFormat format = tmp.LoadSubtitle(openFileDialog1.FileName, out encoding, encoding); if (format != null) { if (format.IsFrameBased) tmp.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate); else tmp.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); if (Configuration.Settings.General.RemoveBlankLinesWhenOpening) tmp.RemoveEmptyLines(); if (SubtitleListview1.SelectedIndices.Count < 1) return; MakeHistoryForUndo(_language.BeforeColumnShiftCellsDown); int index = FirstSelectedIndex; for (int i = 0; i < tmp.Paragraphs.Count; i++) { { for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--) { _subtitle.Paragraphs[k + 1].Text = _subtitle.Paragraphs[k].Text; } } } for (int i = 0; i + index < _subtitle.Paragraphs.Count && i < tmp.Paragraphs.Count; i++) _subtitle.Paragraphs[index + i].Text = tmp.Paragraphs[i].Text; if (IsFramesRelevant && CurrentFrameRate > 0) _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); SubtitleListview1.SelectIndexAndEnsureVisible(index, true); RefreshSelectedParagraph(); } } }
private void toolStripMenuItemImportTimeCodes_Click(object sender, EventArgs e) { if (_subtitle.Paragraphs.Count < 1) { MessageBox.Show(_language.NoSubtitleLoaded, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } openFileDialog1.Title = _languageGeneral.OpenSubtitle; openFileDialog1.FileName = string.Empty; openFileDialog1.Filter = Utilities.GetOpenDialogFilter(); if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { Encoding encoding = null; Subtitle timeCodeSubtitle = new Subtitle(); SubtitleFormat format = timeCodeSubtitle.LoadSubtitle(openFileDialog1.FileName, out encoding, encoding); if (format == null) { ShowUnknownSubtitle(); return; } if (timeCodeSubtitle.Paragraphs.Count != _subtitle.Paragraphs.Count && !string.IsNullOrEmpty(_language.ImportTimeCodesDifferentNumberOfLinesWarning)) { if (MessageBox.Show(string.Format(_language.ImportTimeCodesDifferentNumberOfLinesWarning, timeCodeSubtitle.Paragraphs.Count, _subtitle.Paragraphs.Count), _title, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) return; } MakeHistoryForUndo(_language.BeforeTimeCodeImport); if (GetCurrentSubtitleFormat().IsFrameBased) timeCodeSubtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate); else timeCodeSubtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); int count = 0; for (int i = 0; i < timeCodeSubtitle.Paragraphs.Count; i++) { Paragraph existing = _subtitle.GetParagraphOrDefault(i); Paragraph newTimeCode = timeCodeSubtitle.GetParagraphOrDefault(i); if (existing == null || newTimeCode == null) break; existing.StartTime.TotalMilliseconds = newTimeCode.StartTime.TotalMilliseconds; existing.EndTime.TotalMilliseconds = newTimeCode.EndTime.TotalMilliseconds; existing.StartFrame = newTimeCode.StartFrame; existing.EndFrame = newTimeCode.EndFrame; count++; } ShowStatus(string.Format(_language.TimeCodeImportedFromXY, Path.GetFileName(openFileDialog1.FileName), count)); SaveSubtitleListviewIndexes(); ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); RestoreSubtitleListviewIndexes(); } }
private bool LoadAlternateSubtitleFile(string fileName) { if (!File.Exists(fileName)) return false; if (Path.GetExtension(fileName).ToLower() == ".sub" && IsVobSubFile(fileName, false)) return false; var fi = new FileInfo(fileName); if (fi.Length > 1024 * 1024 * 10) // max 10 mb { if (MessageBox.Show(string.Format(_language.FileXIsLargerThan10Mb + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, fileName), Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes) return false; } Encoding encoding; _subtitleAlternate = new Subtitle(); _subtitleAlternateFileName = fileName; SubtitleFormat format = _subtitleAlternate.LoadSubtitle(fileName, out encoding, null); if (format == null) { var ebu = new Ebu(); if (ebu.IsMine(null, fileName)) { ebu.LoadSubtitle(_subtitleAlternate, null, fileName); format = ebu; } } if (format == null) { var pac = new Pac(); if (pac.IsMine(null, fileName)) { pac.BatchMode = true; pac.LoadSubtitle(_subtitleAlternate, null, fileName); format = pac; } } if (format == null) { var cavena890 = new Cavena890(); if (cavena890.IsMine(null, fileName)) { cavena890.LoadSubtitle(_subtitleAlternate, null, fileName); format = cavena890; } } if (format == null) { var spt = new Spt(); if (spt.IsMine(null, fileName)) { spt.LoadSubtitle(_subtitleAlternate, null, fileName); format = spt; } } if (format == null) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.IsMine(null, fileName)) { cheetahCaption.LoadSubtitle(_subtitleAlternate, null, fileName); format = cheetahCaption; } } if (format == null) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.IsMine(null, fileName)) { capMakerPlus.LoadSubtitle(_subtitleAlternate, null, fileName); format = capMakerPlus; } } if (format == null) { var captionate = new Captionate(); if (captionate.IsMine(null, fileName)) { captionate.LoadSubtitle(_subtitleAlternate, null, fileName); format = captionate; } } if (format == null) { var ultech130 = new Ultech130(); if (ultech130.IsMine(null, fileName)) { ultech130.LoadSubtitle(_subtitleAlternate, null, fileName); format = ultech130; } } if (format == null) { var nciCaption = new NciCaption(); if (nciCaption.IsMine(null, fileName)) { nciCaption.LoadSubtitle(_subtitleAlternate, null, fileName); format = nciCaption; } } if (format == null) { var tsb4 = new TSB4(); if (tsb4.IsMine(null, fileName)) { tsb4.LoadSubtitle(_subtitleAlternate, null, fileName); format = tsb4; } } if (format == null) { var avidStl = new AvidStl(); if (avidStl.IsMine(null, fileName)) { avidStl.LoadSubtitle(_subtitleAlternate, null, fileName); format = avidStl; } } if (format == null) return false; if (format.IsFrameBased) _subtitleAlternate.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate); else _subtitleAlternate.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); SetupAlternateEdit(); return true; }
private Subtitle ImportTimeCodesInFramesOnSameSeperateLine(string[] lines) { Paragraph paragraph = null; var subtitle = new Subtitle(); var sb = new StringBuilder(); foreach (string t in lines) { string line = t; string lineWithPerhapsOnlyNumbers = line .Replace(" ", string.Empty) .Replace(".", string.Empty) .Replace(",", string.Empty) .Replace("\t", string.Empty) .Replace(":", string.Empty) .Replace(";", string.Empty) .Replace("{", string.Empty) .Replace("}", string.Empty) .Replace("[", string.Empty) .Replace("]", string.Empty) .Replace("-", string.Empty) .Replace(">", string.Empty) .Replace("<", string.Empty); bool allNumbers = lineWithPerhapsOnlyNumbers.Length > 0; foreach (char c in lineWithPerhapsOnlyNumbers) { if (!char.IsDigit(c)) { allNumbers = false; } } if (allNumbers && lineWithPerhapsOnlyNumbers.Length > 2) { string[] arr = line .Replace("-", " ") .Replace(">", " ") .Replace("{", " ") .Replace("}", " ") .Replace("[", " ") .Replace("]", " ") .Trim() .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (arr.Length == 2) { string[] start = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); string[] end = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); if (start.Length == 1 && end.Length == 1) { if (paragraph != null) { paragraph.Text = sb.ToString().Trim(); subtitle.Paragraphs.Add(paragraph); } paragraph = new Paragraph(); sb = new StringBuilder(); try { if (UseFrames) { paragraph.StartFrame = int.Parse(start[0]); paragraph.EndFrame = int.Parse(end[0]); paragraph.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); } else { paragraph.StartTime.TotalMilliseconds = double.Parse(start[0]); paragraph.EndTime.TotalMilliseconds = double.Parse(end[0]); } } catch { paragraph = null; } } } else if (arr.Length == 3) { string[] start = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); string[] end = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); string[] duration = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); if (end.Length == 1 && duration.Length == 1) { start = end; end = duration; } if (start.Length == 1 && end.Length == 1) { if (paragraph != null) { paragraph.Text = sb.ToString().Trim(); subtitle.Paragraphs.Add(paragraph); } paragraph = new Paragraph(); sb = new StringBuilder(); try { if (UseFrames) { paragraph.StartFrame = int.Parse(start[0]); paragraph.EndFrame = int.Parse(end[0]); paragraph.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); } else { paragraph.StartTime.TotalMilliseconds = double.Parse(start[0]); paragraph.EndTime.TotalMilliseconds = double.Parse(end[0]); } } catch { paragraph = null; } } } } if (paragraph == null || allNumbers || line.Length <= 1) { continue; } line = line.Trim(); if (line.StartsWith("}{}") || line.StartsWith("][]")) { line = line.Remove(0, 3); } sb.AppendLine(line.Trim()); } if (paragraph != null) { paragraph.Text = sb.ToString().Trim(); subtitle.Paragraphs.Add(paragraph); } subtitle.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); subtitle.Renumber(); return subtitle; }
private Subtitle ImportTimeCodesInFramesOnSameSeperateLine(string[] lines) { Paragraph p = null; var subtitle = new Subtitle(); var sb = new StringBuilder(); for (int idx = 0; idx < lines.Length; idx++) { string line = lines[idx]; string lineWithPerhapsOnlyNumbers = line.Replace(" ", string.Empty).Replace(".", string.Empty).Replace(",", string.Empty).Replace("\t", string.Empty).Replace(":", string.Empty).Replace(";", string.Empty).Replace("{", string.Empty).Replace("}", string.Empty).Replace("[", string.Empty).Replace("]", string.Empty).Replace("-", string.Empty).Replace(">", string.Empty).Replace("<", string.Empty); bool allNumbers = lineWithPerhapsOnlyNumbers.Length > 0; foreach (char c in lineWithPerhapsOnlyNumbers) { if (!"0123456789".Contains(c.ToString())) { allNumbers = false; } } if (allNumbers && lineWithPerhapsOnlyNumbers.Length > 2) { string[] arr = line.Replace("-", " ").Replace(">", " ").Replace("{", " ").Replace("}", " ").Replace("[", " ").Replace("]", " ").Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (arr.Length == 2) { string[] start = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); string[] end = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); if (start.Length == 1 && end.Length == 1) { if (p != null) { p.Text = sb.ToString().Trim(); subtitle.Paragraphs.Add(p); } p = new Paragraph(); sb = new StringBuilder(); try { if (UseFrames) { p.StartFrame = int.Parse(start[0]); p.EndFrame = int.Parse(end[0]); p.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); } else { p.StartTime.TotalMilliseconds = double.Parse(start[0]); p.EndTime.TotalMilliseconds = double.Parse(end[0]); } } catch { p = null; } } } else if (arr.Length == 3) { string[] start = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); string[] end = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); string[] duration = arr[0].Trim().Split(new[] { '.', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries); if (end.Length == 1 && duration.Length == 1) { start = end; end = duration; } if (start.Length == 1 && end.Length == 1) { if (p != null) { p.Text = sb.ToString().Trim(); subtitle.Paragraphs.Add(p); } p = new Paragraph(); sb = new StringBuilder(); try { if (UseFrames) { p.StartFrame = int.Parse(start[0]); p.EndFrame = int.Parse(end[0]); p.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); } else { p.StartTime.TotalMilliseconds = double.Parse(start[0]); p.EndTime.TotalMilliseconds = double.Parse(end[0]); } } catch { p = null; } } } } if (p != null && !allNumbers && line.Length > 1) { line = line.Trim(); if (line.StartsWith("}{}") || line.StartsWith("][]")) { line = line.Remove(0, 3); } sb.AppendLine(line.Trim()); } } if (p != null) { p.Text = sb.ToString().Trim(); subtitle.Paragraphs.Add(p); } subtitle.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); subtitle.Renumber(1); return(subtitle); }
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 Subtitle ImportTimeCodesInFramesOnSameSeperateLine(string[] lines) { Paragraph p = null; var subtitle = new Subtitle(); var sb = new StringBuilder(); for (int idx = 0; idx < lines.Length; idx++) { string line = lines[idx]; string lineWithPerhapsOnlyNumbers = line.Replace(" ", string.Empty).Replace(".", string.Empty).Replace(",", string.Empty).Replace("\t", string.Empty).Replace(":", string.Empty).Replace(";", string.Empty).Replace("{", string.Empty).Replace("}", string.Empty).Replace("[", string.Empty).Replace("]", string.Empty).Replace("-", string.Empty).Replace(">", string.Empty).Replace("<", string.Empty); bool allNumbers = lineWithPerhapsOnlyNumbers.Length > 0; foreach (char c in lineWithPerhapsOnlyNumbers) { if (!"0123456789".Contains(c.ToString())) allNumbers = false; } if (allNumbers && lineWithPerhapsOnlyNumbers.Length > 2) { string[] arr = line.Replace("-", " ").Replace(">", " ").Replace("{", " ").Replace("}", " ").Replace("[", " ").Replace("]", " ").Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (arr.Length == 2) { string[] start = arr[0].Trim().Split(".,;:".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string[] end = arr[0].Trim().Split(".,;:".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (start.Length == 1 && end.Length == 1) { if (p != null) { p.Text = sb.ToString().Trim(); subtitle.Paragraphs.Add(p); } p = new Paragraph(); sb = new StringBuilder(); try { if (UseFrames) { p.StartFrame = int.Parse(start[0]); p.EndFrame = int.Parse(end[0]); p.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); } else { p.StartTime.TotalMilliseconds = double.Parse(start[0]); p.EndTime.TotalMilliseconds = double.Parse(end[0]); } } catch { p = null; } } } else if (arr.Length == 3) { string[] start = arr[0].Trim().Split(".,;:".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string[] end = arr[0].Trim().Split(".,;:".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string[] duration = arr[0].Trim().Split(".,;:".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (end.Length == 1 && duration.Length == 1) { start = end; end = duration; } if (start.Length == 1 && end.Length == 1) { if (p != null) { p.Text = sb.ToString().Trim(); subtitle.Paragraphs.Add(p); } p = new Paragraph(); sb = new StringBuilder(); try { if (UseFrames) { p.StartFrame = int.Parse(start[0]); p.EndFrame = int.Parse(end[0]); p.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); } else { p.StartTime.TotalMilliseconds = double.Parse(start[0]); p.EndTime.TotalMilliseconds = double.Parse(end[0]); } } catch { p = null; } } } } if (p != null && !allNumbers && line.Length > 1) { line = line.Trim(); if (line.StartsWith("}{}") || line.StartsWith("][]")) line = line.Remove(0, 3); sb.AppendLine(line.Trim()); } } if (p != null) { p.Text = sb.ToString().Trim(); subtitle.Paragraphs.Add(p); } subtitle.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate); subtitle.Renumber(1); return subtitle; }
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; } }