public TimedTextStyles(Subtitle subtitle, SubtitleFormat format) { InitializeComponent(); _subtitle = subtitle; _format = format; _xml = new XmlDocument(); try { _xml.LoadXml(subtitle.Header); var xnsmgr = new XmlNamespaceManager(_xml.NameTable); xnsmgr.AddNamespace("ttml", "http://www.w3.org/ns/ttml"); if (_xml.DocumentElement.SelectSingleNode("ttml:head", xnsmgr) == null) _xml.LoadXml(new TimedText10().ToText(new Subtitle(), "tt")); // load default xml } catch { _xml.LoadXml(new TimedText10().ToText(new Subtitle(), "tt")); // load default xml } _nsmgr = new XmlNamespaceManager(_xml.NameTable); _nsmgr.AddNamespace("ttml", "http://www.w3.org/ns/ttml"); _xmlHead = _xml.DocumentElement.SelectSingleNode("ttml:head", _nsmgr); foreach (FontFamily ff in FontFamily.Families) comboBoxFontName.Items.Add(ff.Name.Substring(0, 1).ToLower() + ff.Name.Substring(1)); InitializeListView(); _previewTimer.Interval = 200; _previewTimer.Tick += RefreshTimerTick; }
public void Initialize(Subtitle subtitle, string fileName, SubtitleFormat format) { ShowBasic = false; _subtitle = subtitle; if (string.IsNullOrEmpty(fileName)) textBoxFileName.Text = Configuration.Settings.Language.SplitSubtitle.Untitled; else textBoxFileName.Text = fileName; _fileName = fileName; foreach (Paragraph p in _subtitle.Paragraphs) _totalNumberOfCharacters += p.Text.Length; labelLines.Text = string.Format(Configuration.Settings.Language.Split.NumberOfLinesX, _subtitle.Paragraphs.Count); labelCharacters.Text = string.Format(Configuration.Settings.Language.Split.NumberOfCharactersX, _totalNumberOfCharacters); try { numericUpDownParts.Value = Configuration.Settings.Tools.SplitNumberOfParts; } catch { } if (Configuration.Settings.Tools.SplitVia.Trim().Equals("lines", StringComparison.OrdinalIgnoreCase)) RadioButtonLines.Checked = true; else radioButtonCharacters.Checked = true; foreach (SubtitleFormat f in SubtitleFormat.AllSubtitleFormats) { if (!f.IsVobSubIndexFile) comboBoxSubtitleFormats.Items.Add(f.FriendlyName); if (f.FriendlyName == format.FriendlyName) comboBoxSubtitleFormats.SelectedIndex = comboBoxSubtitleFormats.Items.Count - 1; } comboBoxEncoding.Items.Clear(); int encodingSelectedIndex = 0; comboBoxEncoding.Items.Add(Encoding.UTF8.EncodingName); foreach (EncodingInfo ei in Encoding.GetEncodings()) { if (ei.Name != Encoding.UTF8.BodyName && ei.CodePage >= 949 && !ei.DisplayName.Contains("EBCDIC") && ei.CodePage != 1047) { comboBoxEncoding.Items.Add(ei.CodePage + ": " + ei.DisplayName); if (ei.Name == Configuration.Settings.General.DefaultEncoding) encodingSelectedIndex = comboBoxEncoding.Items.Count - 1; } } comboBoxEncoding.SelectedIndex = encodingSelectedIndex; if (numericUpDownParts.Maximum > _subtitle.Paragraphs.Count) numericUpDownParts.Maximum = _subtitle.Paragraphs.Count / 2; if (!string.IsNullOrEmpty(_fileName)) textBoxOutputFolder.Text = Path.GetDirectoryName(_fileName); else if (string.IsNullOrEmpty(Configuration.Settings.Tools.SplitOutputFolder) || !Directory.Exists(Configuration.Settings.Tools.SplitOutputFolder)) textBoxOutputFolder.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); else textBoxOutputFolder.Text = Configuration.Settings.Tools.SplitOutputFolder; }
public void Initialize(Subtitle subtitle, string fileName, SubtitleFormat format, Encoding encoding, double lengthInSeconds) { ShowAdvanced = false; _subtitle = subtitle; _fileName = fileName; _format = format; _encoding = encoding; splitTimeUpDownAdjust.TimeCode = TimeCode.FromSeconds(lengthInSeconds); }
public ThreadDoWorkParameter(bool fixCommonErrors, bool multipleReplace, bool splitLongLinesActive, bool autoBalance, bool setMinDisplayTimeBetweenSubtitles, ListViewItem item, Subtitle subtitle, SubtitleFormat format, Encoding encoding, string language, string fileName, string toFormat, SubtitleFormat sourceFormat) { FixCommonErrors = fixCommonErrors; MultipleReplaceActive = multipleReplace; SplitLongLinesActive = splitLongLinesActive; AutoBalanceActive = autoBalance; SetMinDisplayTimeBetweenSubtitles = setMinDisplayTimeBetweenSubtitles; Item = item; Subtitle = subtitle; Format = format; Encoding = encoding; Language = language; FileName = fileName; ToFormat = toFormat; SourceFormat = sourceFormat; }
/// <summary> /// Initializes a new instance of the <see cref="Statistics"/> class. /// </summary> /// <param name="subtitle"> /// The subtitle. /// </param> /// <param name="fileName"> /// The file name. /// </param> /// <param name="format"> /// The format. /// </param> public Statistics(Subtitle subtitle, string fileName, SubtitleFormat format) { this.InitializeComponent(); this._subtitle = subtitle; this._format = format; this._l = Configuration.Settings.Language.Statistics; if (string.IsNullOrEmpty(fileName)) { this.Text = this._l.Title; } else { this.Text = string.Format(this._l.TitleWithFileName, fileName); } this.groupBoxGeneral.Text = this._l.GeneralStatistics; this.groupBoxMostUsed.Text = this._l.MostUsed; this.labelMostUsedWords.Text = this._l.MostUsedWords; this.labelMostUsedLines.Text = this._l.MostUsedLines; this.buttonExport.Text = this._l.Export; this.buttonOK.Text = Configuration.Settings.Language.General.Ok; Utilities.FixLargeFonts(this, this.buttonOK); this.CalculateGeneralStatistics(); { this.textBoxGeneral.Text = this._general; this.textBoxGeneral.SelectionStart = 0; this.textBoxGeneral.SelectionLength = 0; this.textBoxGeneral.ScrollToCaret(); } this.CalculateMostUsedWords(); { this.textBoxMostUsedWords.Text = this._mostUsedWords; } this.CalculateMostUsedLines(); { this.textBoxMostUsedLines.Text = this._mostUsedLines; } }
public Statistics(Subtitle subtitle, string fileName, SubtitleFormat format) { InitializeComponent(); _subtitle = subtitle; _format = format; _l = Configuration.Settings.Language.Statistics; if (string.IsNullOrEmpty(fileName)) Text = _l.Title; else Text = string.Format(_l.TitleWithFileName, fileName); groupBoxGeneral.Text = _l.GeneralStatistics; groupBoxMostUsed.Text = _l.MostUsed; labelMostUsedWords.Text = _l.MostUsedWords; labelMostUsedLines.Text = _l.MostUsedLines; buttonOK.Text = Configuration.Settings.Language.General.Ok; FixLargeFonts(); CalculateGeneralStatistics(); CalculateMostUsedWords(); CalculateMostUsedLines(); }
private void ComboBoxSubtitleFormatsSelectedIndexChanged(object sender, EventArgs e) { _converted = true; if (_oldSubtitleFormat == null) { if (!_loading) MakeHistoryForUndo(string.Format(_language.BeforeConvertingToX, GetCurrentSubtitleFormat().FriendlyName)); } else { _subtitle.MakeHistoryForUndo(string.Format(_language.BeforeConvertingToX, GetCurrentSubtitleFormat().FriendlyName), _oldSubtitleFormat, _fileDateTime, _subtitleAlternate, _subtitleAlternateFileName, _subtitleListViewIndex, textBoxListViewText.SelectionStart, textBoxListViewTextAlternate.SelectionStart); _oldSubtitleFormat.RemoveNativeFormatting(_subtitle, GetCurrentSubtitleFormat()); SaveSubtitleListviewIndexes(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); RestoreSubtitleListviewIndexes(); if (_oldSubtitleFormat.HasStyleSupport && _networkSession == null) { SubtitleListview1.HideExtraColumn(); } } SubtitleFormat format = GetCurrentSubtitleFormat(); if (_oldSubtitleFormat != null && !_oldSubtitleFormat.IsFrameBased && format.IsFrameBased) _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate); else if (_oldSubtitleFormat != null && _oldSubtitleFormat.IsFrameBased && !format.IsFrameBased) _subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate); ShowSource(); SubtitleListview1.DisplayExtraFromExtra = false; if (format != null) { ShowStatus(string.Format(_language.ConvertedToX, format.FriendlyName)); _oldSubtitleFormat = format; if (format.HasStyleSupport && _networkSession == null) { List<string> styles = new List<string>(); if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha)) styles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header); else if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText)) styles = TimedText10.GetStylesFromHeader(_subtitle.Header); else if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern)) styles = Sami.GetStylesFromHeader(_subtitle.Header); else if (format.Name == "Nuendo") styles = GetNuendoStyles(); foreach (Paragraph p in _subtitle.Paragraphs) { if (string.IsNullOrEmpty(p.Extra) && styles.Count > 0) p.Extra = styles[0]; } if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern)) SubtitleListview1.ShowExtraColumn(Configuration.Settings.Language.General.Class); else if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText)) SubtitleListview1.ShowExtraColumn("Style / Language"); else if (format.Name == "Nuendo") SubtitleListview1.ShowExtraColumn("Character"); //TODO: Put in language xml file else SubtitleListview1.ShowExtraColumn(Configuration.Settings.Language.General.Style); SubtitleListview1.DisplayExtraFromExtra = true; SubtitleListview1.Fill(_subtitle, _subtitleAlternate); } } }
private void ResetSubtitle() { SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle = new Subtitle(_subtitle.HistoryItems); _changeAlternateSubtitleToString = string.Empty; _changeSubtitleToString = string.Empty; _subtitleAlternateFileName = null; textBoxSource.Text = string.Empty; SubtitleListview1.Items.Clear(); _fileName = string.Empty; _fileDateTime = new DateTime(); Text = Title; _oldSubtitleFormat = null; labelSingleLine.Text = string.Empty; RemoveAlternate(true); _splitDualSami = false; SubtitleListview1.HideExtraColumn(); SubtitleListview1.DisplayExtraFromExtra = false; toolStripComboBoxFrameRate.Text = Configuration.Settings.General.DefaultFrameRate.ToString(); SetEncoding(Configuration.Settings.General.DefaultEncoding); toolStripComboBoxFrameRate.Text = Configuration.Settings.General.DefaultFrameRate.ToString(); _findHelper = null; _spellCheckForm = null; _videoFileName = null; _videoInfo = null; _videoAudioTrackNumber = -1; labelVideoInfo.Text = Configuration.Settings.Language.General.NoVideoLoaded; audioVisualizer.WavePeaks = null; audioVisualizer.ResetSpectrogram(); audioVisualizer.Invalidate(); _sourceViewChange = false; _subtitleListViewIndex = -1; textBoxListViewText.Text = string.Empty; textBoxListViewTextAlternate.Text = string.Empty; textBoxListViewText.Enabled = false; labelTextLineLengths.Text = string.Empty; labelCharactersPerSecond.Text = string.Empty; labelTextLineTotal.Text = string.Empty; _listViewTextUndoLast = null; _listViewAlternateTextUndoLast = null; _listViewTextUndoIndex = -1; if (mediaPlayer.VideoPlayer != null) { mediaPlayer.VideoPlayer.DisposeVideoPlayer(); mediaPlayer.VideoPlayer = null; } _changeSubtitleToString = SerializeSubtitle(_subtitle); _converted = false; SetUndockedWindowsTitle(); if (mediaPlayer != null) mediaPlayer.SubtitleText = string.Empty; ShowStatus(_language.New); }
private DialogResult SaveOriginalSubtitle(SubtitleFormat format) { try { string allText = _subtitleAlternate.ToText(format).Trim(); var currentEncoding = GetCurrentEncoding(); if (currentEncoding == Encoding.Default && (allText.Contains("♪") || allText.Contains("♫") | allText.Contains("♥"))) // ANSI & music/unicode symbols { if (MessageBox.Show(string.Format(_language.UnicodeMusicSymbolsAnsiWarning), Title, MessageBoxButtons.YesNo) == DialogResult.No) return DialogResult.No; } bool containsNegativeTime = false; foreach (var p in _subtitleAlternate.Paragraphs) { if (p.StartTime.TotalMilliseconds < 0 || p.EndTime.TotalMilliseconds < 0) { containsNegativeTime = true; break; } } if (containsNegativeTime && !string.IsNullOrEmpty(_language.NegativeTimeWarning)) { if (MessageBox.Show(_language.NegativeTimeWarning, Title, MessageBoxButtons.YesNo) == DialogResult.No) return DialogResult.No; } File.WriteAllText(_subtitleAlternateFileName, allText, currentEncoding); ShowStatus(string.Format(_language.SavedOriginalSubtitleX, _subtitleAlternateFileName)); _changeAlternateSubtitleToString = _subtitleAlternate.ToText(new SubRip()).Trim(); return DialogResult.OK; } catch { MessageBox.Show(string.Format(_language.UnableToSaveSubtitleX, _fileName)); return DialogResult.Cancel; } }
/// <summary> /// The sort and load. /// </summary> private void SortAndLoad() { this.JoinedFormat = new SubRip(); // default subtitle format string header = null; SubtitleFormat lastFormat = null; var subtitles = new List<Subtitle>(); for (int k = 0; k < this._fileNamesToJoin.Count; k++) { string fileName = this._fileNamesToJoin[k]; try { var sub = new Subtitle(); Encoding encoding; var format = sub.LoadSubtitle(fileName, out encoding, null); if (format == null) { for (int j = k; j < this._fileNamesToJoin.Count; j++) { this._fileNamesToJoin.RemoveAt(j); } MessageBox.Show("Unkown subtitle format: " + fileName); return; } if (sub.Header != null) { header = sub.Header; } if (lastFormat == null || lastFormat.FriendlyName == format.FriendlyName) { lastFormat = format; } else { lastFormat = new SubRip(); // default subtitle format } subtitles.Add(sub); } catch (Exception exception) { for (int j = k; j < this._fileNamesToJoin.Count; j++) { this._fileNamesToJoin.RemoveAt(j); } MessageBox.Show(exception.Message); return; } } this.JoinedFormat = lastFormat; for (int outer = 0; outer < subtitles.Count; outer++) { for (int inner = 1; inner < subtitles.Count; inner++) { var a = subtitles[inner - 1]; var b = subtitles[inner]; if (a.Paragraphs.Count > 0 && b.Paragraphs.Count > 0 && a.Paragraphs[0].StartTime.TotalMilliseconds > b.Paragraphs[0].StartTime.TotalMilliseconds) { string t1 = this._fileNamesToJoin[inner - 1]; this._fileNamesToJoin[inner - 1] = this._fileNamesToJoin[inner]; this._fileNamesToJoin[inner] = t1; var t2 = subtitles[inner - 1]; subtitles[inner - 1] = subtitles[inner]; subtitles[inner] = t2; } } } this.listViewParts.BeginUpdate(); this.listViewParts.Items.Clear(); int i = 0; foreach (string fileName in this._fileNamesToJoin) { Subtitle sub = subtitles[i]; var lvi = new ListViewItem(string.Format("{0:#,###,###}", sub.Paragraphs.Count)); if (sub.Paragraphs.Count > 0) { lvi.SubItems.Add(sub.Paragraphs[0].StartTime.ToString()); lvi.SubItems.Add(sub.Paragraphs[sub.Paragraphs.Count - 1].StartTime.ToString()); } else { lvi.SubItems.Add("-"); lvi.SubItems.Add("-"); } lvi.SubItems.Add(fileName); this.listViewParts.Items.Add(lvi); i++; } this.listViewParts.EndUpdate(); this.JoinedSubtitle = new Subtitle(); if (this.JoinedFormat.FriendlyName != SubRip.NameOfFormat) { this.JoinedSubtitle.Header = header; } foreach (Subtitle sub in subtitles) { foreach (Paragraph p in sub.Paragraphs) { this.JoinedSubtitle.Paragraphs.Add(p); } } this.JoinedSubtitle.Renumber(); this.labelTotalLines.Text = string.Format(Configuration.Settings.Language.JoinSubtitles.TotalNumberOfLinesX, this.JoinedSubtitle.Paragraphs.Count); }
public void Initialize(Subtitle subtitle, SubtitleFormat format, Encoding encoding) { _autoDetectGoogleLanguage = Utilities.AutoDetectGoogleLanguage(encoding); // Guess language via encoding if (string.IsNullOrEmpty(_autoDetectGoogleLanguage)) _autoDetectGoogleLanguage = Utilities.AutoDetectGoogleLanguage(subtitle); // Guess language based on subtitle contents if (_autoDetectGoogleLanguage.ToLower() == "zh") _autoDetectGoogleLanguage = "zh-CHS"; // Note that "zh-CHS" (Simplified Chinese) and "zh-CHT" (Traditional Chinese) are neutral cultures CultureInfo ci = CultureInfo.GetCultureInfo(_autoDetectGoogleLanguage); string threeLetterISOLanguageName = ci.ThreeLetterISOLanguageName; comboBoxLanguage.Items.Clear(); foreach (CultureInfo x in CultureInfo.GetCultures(CultureTypes.NeutralCultures)) comboBoxLanguage.Items.Add(x); comboBoxLanguage.Sorted = true; int languageIndex = 0; int j = 0; foreach (var x in comboBoxLanguage.Items) { var xci = (CultureInfo)x; if (xci.TwoLetterISOLanguageName == ci.TwoLetterISOLanguageName) { languageIndex = j; break; } else if (xci.TwoLetterISOLanguageName == "en") { languageIndex = j; } j++; } comboBoxLanguage.SelectedIndex = languageIndex; AddFixActions(subtitle, threeLetterISOLanguageName); _originalSubtitle = new Subtitle(subtitle); // copy constructor _subtitle = new Subtitle(subtitle); // copy constructor _format = format; _encoding = encoding; InitUI(); }
/// <summary> /// The initialize. /// </summary> /// <param name="subtitle"> /// The subtitle. /// </param> /// <param name="format"> /// The format. /// </param> /// <param name="exportType"> /// The export type. /// </param> /// <param name="fileName"> /// The file name. /// </param> /// <param name="videoInfo"> /// The video info. /// </param> /// <param name="videoFileName"> /// The video file name. /// </param> internal void Initialize(Subtitle subtitle, SubtitleFormat format, string exportType, string fileName, VideoInfo videoInfo, string videoFileName) { this._exportType = exportType; this._fileName = fileName; this._format = format; this._videoFileName = videoFileName; if (exportType == "BLURAYSUP") { this.Text = "Blu-ray SUP"; } else if (exportType == "VOBSUB") { this.Text = "VobSub (sub/idx)"; } else if (exportType == "FAB") { this.Text = "FAB Image Script"; } else if (exportType == "IMAGE/FRAME") { this.Text = "Image per frame"; } else if (exportType == "STL") { this.Text = "DVD Studio Pro STL"; } else if (exportType == "FCP") { this.Text = "Final Cut Pro"; } else if (exportType == "DOST") { this.Text = "DOST"; } else if (exportType == "EDL") { this.Text = "EDL"; } else if (exportType == "DCINEMA_INTEROP") { this.Text = "DCinema interop/png"; } else { this.Text = Configuration.Settings.Language.ExportPngXml.Title; } if (this._exportType == "VOBSUB" && !string.IsNullOrEmpty(Configuration.Settings.Tools.ExportVobSubFontName)) { this._subtitleFontName = Configuration.Settings.Tools.ExportVobSubFontName; } else if ((this._exportType == "BLURAYSUP" || this._exportType == "DOST") && !string.IsNullOrEmpty(Configuration.Settings.Tools.ExportBluRayFontName)) { this._subtitleFontName = Configuration.Settings.Tools.ExportBluRayFontName; } else if (this._exportType == "FCP" && !string.IsNullOrEmpty(Configuration.Settings.Tools.ExportFcpFontName)) { this._subtitleFontName = Configuration.Settings.Tools.ExportFcpFontName; } else if (!string.IsNullOrEmpty(Configuration.Settings.Tools.ExportFontNameOther)) { this._subtitleFontName = Configuration.Settings.Tools.ExportFontNameOther; } if (this._exportType == "VOBSUB" && Configuration.Settings.Tools.ExportVobSubFontSize > 0) { this._subtitleFontSize = Configuration.Settings.Tools.ExportVobSubFontSize; } else if ((this._exportType == "BLURAYSUP" || this._exportType == "DOST") && Configuration.Settings.Tools.ExportBluRayFontSize > 0) { this._subtitleFontSize = Configuration.Settings.Tools.ExportBluRayFontSize; } else if (this._exportType == "FCP" && Configuration.Settings.Tools.ExportFcpFontSize > 0) { this._subtitleFontSize = Configuration.Settings.Tools.ExportFcpFontSize; } else if (Configuration.Settings.Tools.ExportLastFontSize > 0) { this._subtitleFontSize = Configuration.Settings.Tools.ExportLastFontSize; } if (this._exportType == "FCP") { this.comboBoxImageFormat.Items.Add("8-bit png"); int i = 0; foreach (string item in this.comboBoxImageFormat.Items) { if (item == Configuration.Settings.Tools.ExportFcpImageType) { this.comboBoxImageFormat.SelectedIndex = i; } i++; } } if (this._exportType == "VOBSUB") { this.comboBoxSubtitleFontSize.SelectedIndex = 7; int i = 0; foreach (string item in this.comboBoxSubtitleFontSize.Items) { if (item == Convert.ToInt32(this._subtitleFontSize).ToString(CultureInfo.InvariantCulture)) { this.comboBoxSubtitleFontSize.SelectedIndex = i; } i++; } this.checkBoxSimpleRender.Checked = Configuration.Settings.Tools.ExportVobSubSimpleRendering; this.checkBoxTransAntiAliase.Checked = Configuration.Settings.Tools.ExportVobAntiAliasingWithTransparency; } else if (this._exportType == "BLURAYSUP" || this._exportType == "DOST" || this._exportType == "FCP") { this.comboBoxSubtitleFontSize.SelectedIndex = 16; int i = 0; foreach (string item in this.comboBoxSubtitleFontSize.Items) { if (item == Convert.ToInt32(this._subtitleFontSize).ToString(CultureInfo.InvariantCulture)) { this.comboBoxSubtitleFontSize.SelectedIndex = i; } i++; } } else { this.comboBoxSubtitleFontSize.SelectedIndex = 16; int i = 0; foreach (string item in this.comboBoxSubtitleFontSize.Items) { if (item == Convert.ToInt32(this._subtitleFontSize).ToString(CultureInfo.InvariantCulture)) { this.comboBoxSubtitleFontSize.SelectedIndex = i; } i++; } } this.groupBoxImageSettings.Text = Configuration.Settings.Language.ExportPngXml.ImageSettings; this.labelSubtitleFont.Text = Configuration.Settings.Language.ExportPngXml.FontFamily; this.labelSubtitleFontSize.Text = Configuration.Settings.Language.ExportPngXml.FontSize; this.labelResolution.Text = Configuration.Settings.Language.ExportPngXml.VideoResolution; this.buttonColor.Text = Configuration.Settings.Language.ExportPngXml.FontColor; this.checkBoxBold.Text = Configuration.Settings.Language.General.Bold; this.checkBoxSimpleRender.Text = Configuration.Settings.Language.ExportPngXml.SimpleRendering; this.checkBoxTransAntiAliase.Text = Configuration.Settings.Language.ExportPngXml.AntiAliasingWithTransparency; this.normalToolStripMenuItem.Text = Configuration.Settings.Language.Main.Menu.ContextMenu.Normal; this.italicToolStripMenuItem.Text = Configuration.Settings.Language.General.Italic; this.boxSingleLineToolStripMenuItem.Text = Configuration.Settings.Language.ExportPngXml.BoxSingleLine; this.boxMultiLineToolStripMenuItem.Text = Configuration.Settings.Language.ExportPngXml.BoxMultiLine; this.comboBox3D.Items.Clear(); this.comboBox3D.Items.Add(Configuration.Settings.Language.General.None); this.comboBox3D.Items.Add(Configuration.Settings.Language.ExportPngXml.SideBySide3D); this.comboBox3D.Items.Add(Configuration.Settings.Language.ExportPngXml.HalfTopBottom3D); this.comboBox3D.SelectedIndex = 0; this.labelDepth.Text = Configuration.Settings.Language.ExportPngXml.Depth; this.numericUpDownDepth3D.Left = this.labelDepth.Left + this.labelDepth.Width + 3; this.label3D.Text = Configuration.Settings.Language.ExportPngXml.Text3D; this.comboBox3D.Left = this.label3D.Left + this.label3D.Width + 3; this.buttonBorderColor.Text = Configuration.Settings.Language.ExportPngXml.BorderColor; // labelBorderWidth.Text = Configuration.Settings.Language.ExportPngXml.BorderWidth; this.labelBorderWidth.Text = Configuration.Settings.Language.ExportPngXml.BorderStyle; this.labelImageFormat.Text = Configuration.Settings.Language.ExportPngXml.ImageFormat; this.checkBoxFullFrameImage.Text = Configuration.Settings.Language.ExportPngXml.FullFrameImage; this.buttonExport.Text = Configuration.Settings.Language.ExportPngXml.ExportAllLines; this.buttonCancel.Text = Configuration.Settings.Language.General.Ok; this.labelLanguage.Text = Configuration.Settings.Language.ChooseLanguage.Language; this.labelFrameRate.Text = Configuration.Settings.Language.General.FrameRate; this.labelHorizontalAlign.Text = Configuration.Settings.Language.ExportPngXml.Align; this.labelBottomMargin.Text = Configuration.Settings.Language.ExportPngXml.BottomMargin; this.labelLeftRightMargin.Text = Configuration.Settings.Language.ExportPngXml.LeftRightMargin; if (Configuration.Settings.Language.ExportPngXml.Left != null && Configuration.Settings.Language.ExportPngXml.Center != null && Configuration.Settings.Language.ExportPngXml.Right != null) { this.comboBoxHAlign.Items.Clear(); this.comboBoxHAlign.Items.Add(Configuration.Settings.Language.ExportPngXml.Left); this.comboBoxHAlign.Items.Add(Configuration.Settings.Language.ExportPngXml.Center); this.comboBoxHAlign.Items.Add(Configuration.Settings.Language.ExportPngXml.Right); } this.buttonShadowColor.Text = Configuration.Settings.Language.ExportPngXml.ShadowColor; this.labelShadowWidth.Text = Configuration.Settings.Language.ExportPngXml.ShadowWidth; this.labelShadowTransparency.Text = Configuration.Settings.Language.ExportPngXml.Transparency; this.labelLineHeight.Text = Configuration.Settings.Language.ExportPngXml.LineHeight; this.linkLabelPreview.Text = Configuration.Settings.Language.General.Preview; this.linkLabelPreview.Left = this.groupBoxExportImage.Width - this.linkLabelPreview.Width - 3; this.saveImageAsToolStripMenuItem.Text = Configuration.Settings.Language.ExportPngXml.SaveImageAs; this.SubtitleListView1InitializeLanguage(Configuration.Settings.Language.General, Configuration.Settings); Utilities.InitializeSubtitleFont(this.subtitleListView1); this.SubtitleListView1AutoSizeAllColumns(); this._subtitle = new Subtitle(subtitle); this._subtitle.Header = subtitle.Header; this._subtitle.Footer = subtitle.Footer; this.panelColor.BackColor = this._subtitleColor; this.panelBorderColor.BackColor = this._borderColor; this.InitBorderStyle(); this.comboBoxHAlign.SelectedIndex = 1; this.comboBoxResolution.SelectedIndex = 3; if (Configuration.Settings.Tools.ExportLastShadowTransparency <= this.numericUpDownShadowTransparency.Maximum && Configuration.Settings.Tools.ExportLastShadowTransparency > 0) { this.numericUpDownShadowTransparency.Value = Configuration.Settings.Tools.ExportLastShadowTransparency; } if ((this._exportType == "BLURAYSUP" || this._exportType == "DOST") && !string.IsNullOrEmpty(Configuration.Settings.Tools.ExportBluRayVideoResolution)) { this.SetResolution(Configuration.Settings.Tools.ExportBluRayVideoResolution); } if (exportType == "VOBSUB") { this.comboBoxBorderWidth.SelectedIndex = 6; if (this._exportType == "VOBSUB" && !string.IsNullOrEmpty(Configuration.Settings.Tools.ExportVobSubVideoResolution)) { this.SetResolution(Configuration.Settings.Tools.ExportVobSubVideoResolution); } else { this.comboBoxResolution.SelectedIndex = 8; } this.labelLanguage.Visible = true; this.comboBoxLanguage.Visible = true; this.comboBoxLanguage.Items.Clear(); string languageCode = Utilities.AutoDetectGoogleLanguageOrNull(subtitle); if (languageCode == null) { languageCode = Configuration.Settings.Tools.ExportVobSubLanguage; } for (int i = 0; i < IfoParser.ArrayOfLanguage.Count; i++) { this.comboBoxLanguage.Items.Add(IfoParser.ArrayOfLanguage[i]); if (IfoParser.ArrayOfLanguageCode[i] == languageCode || IfoParser.ArrayOfLanguage[i] == languageCode) { this.comboBoxLanguage.SelectedIndex = i; } } if (this.comboBoxLanguage.SelectedIndex == -1 && this.comboBoxLanguage.Items.Count > 25) { this.comboBoxLanguage.SelectedIndex = 25; } } bool showImageFormat = exportType == "FAB" || exportType == "IMAGE/FRAME" || exportType == "STL" || exportType == "FCP" || exportType == "BDNXML"; this.checkBoxFullFrameImage.Visible = exportType == "FAB" || exportType == "BLURAYSUP"; this.comboBoxImageFormat.Visible = showImageFormat; this.labelImageFormat.Visible = showImageFormat; this.labelFrameRate.Visible = exportType == "BDNXML" || exportType == "BLURAYSUP" || exportType == "DOST" || exportType == "IMAGE/FRAME"; this.comboBoxFrameRate.Visible = exportType == "BDNXML" || exportType == "BLURAYSUP" || exportType == "DOST" || exportType == "IMAGE/FRAME" || exportType == "FAB" || exportType == "FCP"; this.checkBoxTransAntiAliase.Visible = exportType == "VOBSUB"; if (exportType == "BDNXML") { this.labelFrameRate.Top = this.labelLanguage.Top; this.comboBoxFrameRate.Top = this.comboBoxLanguage.Top; this.comboBoxFrameRate.Items.Add("23.976"); this.comboBoxFrameRate.Items.Add("24"); this.comboBoxFrameRate.Items.Add("25"); this.comboBoxFrameRate.Items.Add("29.97"); this.comboBoxFrameRate.Items.Add("30"); this.comboBoxFrameRate.Items.Add("50"); this.comboBoxFrameRate.Items.Add("59.94"); this.comboBoxFrameRate.SelectedIndex = 2; this.comboBoxImageFormat.Items.Clear(); this.comboBoxImageFormat.Items.Add("Png 32-bit"); this.comboBoxImageFormat.Items.Add("Png 8-bit"); if (this.comboBoxImageFormat.Items[1].ToString() == Configuration.Settings.Tools.ExportBdnXmlImageType) { this.comboBoxImageFormat.SelectedIndex = 1; } else { this.comboBoxImageFormat.SelectedIndex = 0; } } else if (exportType == "DOST") { this.labelFrameRate.Top = this.labelLanguage.Top; this.comboBoxFrameRate.Top = this.comboBoxLanguage.Top; this.comboBoxFrameRate.Items.Add("23.98"); this.comboBoxFrameRate.Items.Add("24"); this.comboBoxFrameRate.Items.Add("25"); this.comboBoxFrameRate.Items.Add("29.97"); this.comboBoxFrameRate.Items.Add("30"); this.comboBoxFrameRate.Items.Add("59.94"); this.comboBoxFrameRate.SelectedIndex = 2; } else if (exportType == "IMAGE/FRAME") { this.labelFrameRate.Top = this.labelLanguage.Top; this.comboBoxFrameRate.Top = this.comboBoxLanguage.Top; this.comboBoxFrameRate.Items.Add("23.976"); this.comboBoxFrameRate.Items.Add("24"); this.comboBoxFrameRate.Items.Add("25"); this.comboBoxFrameRate.Items.Add("29.97"); this.comboBoxFrameRate.Items.Add("30"); this.comboBoxFrameRate.Items.Add("50"); this.comboBoxFrameRate.Items.Add("59.94"); this.comboBoxFrameRate.Items.Add("60"); this.comboBoxFrameRate.SelectedIndex = 2; } else if (exportType == "BLURAYSUP") { this.labelFrameRate.Top = this.labelLanguage.Top; this.comboBoxFrameRate.Top = this.comboBoxLanguage.Top; this.comboBoxFrameRate.Items.Add("23.976"); this.comboBoxFrameRate.Items.Add("24"); this.comboBoxFrameRate.Items.Add("25"); this.comboBoxFrameRate.Items.Add("29.97"); this.comboBoxFrameRate.Items.Add("50"); this.comboBoxFrameRate.Items.Add("59.94"); this.comboBoxFrameRate.SelectedIndex = 1; this.comboBoxFrameRate.DropDownStyle = ComboBoxStyle.DropDownList; this.checkBoxFullFrameImage.Top = this.comboBoxImageFormat.Top + 2; this.panelFullFrameBackground.Top = this.checkBoxFullFrameImage.Top; } else if (exportType == "FAB") { this.labelFrameRate.Visible = true; this.comboBoxFrameRate.Items.Add("23.976"); this.comboBoxFrameRate.Items.Add("24"); this.comboBoxFrameRate.Items.Add("25"); this.comboBoxFrameRate.Items.Add("29.97"); this.comboBoxFrameRate.Items.Add("50"); this.comboBoxFrameRate.Items.Add("59.94"); this.comboBoxFrameRate.SelectedIndex = 1; this.comboBoxFrameRate.DropDownStyle = ComboBoxStyle.DropDownList; } else if (exportType == "FCP") { this.labelFrameRate.Visible = true; this.comboBoxFrameRate.Items.Add("23.976"); this.comboBoxFrameRate.Items.Add("24"); this.comboBoxFrameRate.Items.Add("25"); this.comboBoxFrameRate.Items.Add("29.97"); this.comboBoxFrameRate.Items.Add("50"); this.comboBoxFrameRate.Items.Add("59.94"); this.comboBoxFrameRate.Items.Add("60"); this.comboBoxFrameRate.SelectedIndex = 2; this.comboBoxFrameRate.DropDownStyle = ComboBoxStyle.DropDownList; } if (this.comboBoxFrameRate.Items.Count >= 2) { this.SetLastFrameRate(Configuration.Settings.Tools.ExportLastFrameRate); } this.panelShadowColor.BackColor = Configuration.Settings.Tools.ExportShadowColor; for (int i = 0; i < 1000; i++) { this.comboBoxBottomMargin.Items.Add(i); } if (Configuration.Settings.Tools.ExportBottomMargin >= 0 && Configuration.Settings.Tools.ExportBottomMargin < this.comboBoxBottomMargin.Items.Count) { this.comboBoxBottomMargin.SelectedIndex = Configuration.Settings.Tools.ExportBottomMargin; } if (exportType == "BLURAYSUP" || exportType == "IMAGE/FRAME" && Configuration.Settings.Tools.ExportBluRayBottomMargin >= 0 && Configuration.Settings.Tools.ExportBluRayBottomMargin < this.comboBoxBottomMargin.Items.Count) { this.comboBoxBottomMargin.SelectedIndex = Configuration.Settings.Tools.ExportBluRayBottomMargin; } if (this._exportType == "BLURAYSUP" || this._exportType == "VOBSUB" || this._exportType == "IMAGE/FRAME" || this._exportType == "BDNXML" || this._exportType == "DOST" || this._exportType == "FAB" || this._exportType == "EDL") { this.comboBoxBottomMargin.Visible = true; this.labelBottomMargin.Visible = true; this.comboBoxLeftRightMargin.Visible = true; this.labelLeftRightMargin.Visible = true; this.comboBoxLeftRightMargin.SelectedIndex = 10; } else { this.comboBoxBottomMargin.Visible = false; this.labelBottomMargin.Visible = false; this.comboBoxLeftRightMargin.Visible = false; this.labelLeftRightMargin.Visible = false; } this.checkBoxSkipEmptyFrameAtStart.Visible = exportType == "IMAGE/FRAME"; foreach (var x in FontFamily.Families) { if (x.IsStyleAvailable(FontStyle.Regular) || x.IsStyleAvailable(FontStyle.Bold)) { this.comboBoxSubtitleFont.Items.Add(x.Name); if (x.Name.Equals(this._subtitleFontName, StringComparison.OrdinalIgnoreCase)) { this.comboBoxSubtitleFont.SelectedIndex = this.comboBoxSubtitleFont.Items.Count - 1; } } } if (this.comboBoxSubtitleFont.SelectedIndex == -1) { this.comboBoxSubtitleFont.SelectedIndex = 0; // take first font if default font not found (e.g. linux) } if (videoInfo != null && videoInfo.Height > 0 && videoInfo.Width > 0) { this.comboBoxResolution.Items[this.comboBoxResolution.Items.Count - 1] = videoInfo.Width + "x" + videoInfo.Height; this.comboBoxResolution.SelectedIndex = this.comboBoxResolution.Items.Count - 1; } if (this._subtitleFontSize == Configuration.Settings.Tools.ExportLastFontSize && Configuration.Settings.Tools.ExportLastLineHeight >= this.numericUpDownLineSpacing.Minimum && Configuration.Settings.Tools.ExportLastLineHeight <= this.numericUpDownLineSpacing.Maximum && Configuration.Settings.Tools.ExportLastLineHeight > 0) { this.numericUpDownLineSpacing.Value = Configuration.Settings.Tools.ExportLastLineHeight; } if (Configuration.Settings.Tools.ExportLastBorderWidth >= 0 && Configuration.Settings.Tools.ExportLastBorderWidth < this.comboBoxBorderWidth.Items.Count) { try { this.comboBoxBorderWidth.SelectedIndex = Configuration.Settings.Tools.ExportLastBorderWidth; } catch { } } this.checkBoxBold.Checked = Configuration.Settings.Tools.ExportLastFontBold; if (Configuration.Settings.Tools.Export3DType >= 0 && Configuration.Settings.Tools.Export3DType < this.comboBox3D.Items.Count) { this.comboBox3D.SelectedIndex = Configuration.Settings.Tools.Export3DType; } if (Configuration.Settings.Tools.Export3DDepth >= this.numericUpDownDepth3D.Minimum && Configuration.Settings.Tools.Export3DDepth <= this.numericUpDownDepth3D.Maximum) { this.numericUpDownDepth3D.Value = Configuration.Settings.Tools.Export3DDepth; } if (Configuration.Settings.Tools.ExportHorizontalAlignment >= 0 && Configuration.Settings.Tools.ExportHorizontalAlignment < this.comboBoxHAlign.Items.Count) { this.comboBoxHAlign.SelectedIndex = Configuration.Settings.Tools.ExportHorizontalAlignment; } if (exportType == "DCINEMA_INTEROP") { this.comboBox3D.Visible = false; this.numericUpDownDepth3D.Enabled = true; this.labelDepth.Enabled = true; this.labelDepth.Text = Configuration.Settings.Language.DCinemaProperties.ZPosition; } if (this._exportType == "FCP") { this.comboBoxResolution.Items.Clear(); this.comboBoxResolution.Items.Add("NTSC-601"); this.comboBoxResolution.Items.Add("PAL-601"); this.comboBoxResolution.Items.Add("square"); this.comboBoxResolution.Items.Add("DVCPROHD-720P"); this.comboBoxResolution.Items.Add("HD-(960x720)"); this.comboBoxResolution.Items.Add("DVCPROHD-1080i60"); this.comboBoxResolution.Items.Add("HD-(1280x1080)"); this.comboBoxResolution.Items.Add("DVCPROHD-1080i50"); this.comboBoxResolution.Items.Add("HD-(1440x1080)"); this.comboBoxResolution.SelectedIndex = 3; // 720p this.buttonCustomResolution.Visible = true; // we still allow for custom resolutions this.labelLanguage.Text = "NTSC/PAL"; this.comboBoxLanguage.Items.Clear(); this.comboBoxLanguage.Items.Add("PAL"); this.comboBoxLanguage.Items.Add("NTSC"); this.comboBoxLanguage.SelectedIndex = 0; this.comboBoxLanguage.Visible = true; this.labelLanguage.Visible = true; } this.comboBoxShadowWidth.SelectedIndex = 0; bool shadowVisible = this._exportType == "BDNXML" || this._exportType == "BLURAYSUP" || this._exportType == "DOST" || this._exportType == "IMAGE/FRAME" || this._exportType == "FCP" || this._exportType == "DCINEMA_INTEROP" || this._exportType == "EDL"; this.labelShadowWidth.Visible = shadowVisible; this.buttonShadowColor.Visible = shadowVisible; this.comboBoxShadowWidth.Visible = shadowVisible; if (shadowVisible && Configuration.Settings.Tools.ExportBluRayShadow < this.comboBoxShadowWidth.Items.Count) { this.comboBoxShadowWidth.SelectedIndex = Configuration.Settings.Tools.ExportBluRayShadow; } this.panelShadowColor.Visible = shadowVisible; this.labelShadowTransparency.Visible = shadowVisible; this.numericUpDownShadowTransparency.Visible = shadowVisible; if (exportType == "BLURAYSUP" || exportType == "VOBSUB" || exportType == "BDNXML") { this.subtitleListView1.CheckBoxes = true; this.subtitleListView1.Columns.Insert(0, Configuration.Settings.Language.ExportPngXml.Forced); this.SubtitleListView1Fill(this._subtitle); if (this._vobSubOcr != null) { for (int index = 0; index < this._subtitle.Paragraphs.Count; index++) { if (this._vobSubOcr.GetIsForced(index)) { this.subtitleListView1.Items[index].Checked = true; } } } this.SubtitleListView1SelectIndexAndEnsureVisible(0); } else { this.SubtitleListView1Fill(this._subtitle); this.SubtitleListView1SelectIndexAndEnsureVisible(0); } }
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; } }
public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName) { _errorCount = 0; subtitle.Paragraphs.Clear(); if (string.IsNullOrEmpty(fileName)) { return; } byte[] array; try { array = FileUtil.ReadAllBytesShared(fileName); } catch { _errorCount++; return; } if (array.Length < 100) { return; } if (array[0] != 84 || array[1] != 83 || array[2] != 66 || array[3] != 52) { return; } for (int i = 0; i < array.Length - 20; i++) { if (array[i] == 84 && array[i + 1] == 73 && array[i + 2] == 84 && array[i + 3] == 76 && array[i + 8] == 84 && array[i + 9] == 73 && array[i + 10] == 77 && array[i + 11] == 69) // TITL + TIME { int endOfText = (int)array[i + 4]; int start = array[i + 16] + array[i + 17] * 256; if (array[i + 18] != 32) { start += array[i + 18] * 256 * 256; } int end = array[i + 20] + array[i + 21] * 256; if (array[i + 22] != 32) { end += array[i + 22] * 256 * 256; } int textStart = i; while (textStart < i + endOfText && !(array[textStart] == 0x4C && array[textStart + 1] == 0x49 && array[textStart + 2] == 0x4E && array[textStart + 3] == 0x45)) // LINE { textStart++; } int length = i + endOfText - textStart - 2; textStart += 8; string text = Encoding.Default.GetString(array, textStart, length); // text = Encoding.Default.GetString(array, i + 53, endOfText - 47); text = text.Trim('\0').Replace("\0", " ").Trim(); var item = new Paragraph(text, (double)SubtitleFormat.FramesToMilliseconds((double)start), (double)SubtitleFormat.FramesToMilliseconds((double)end)); subtitle.Paragraphs.Add(item); i += endOfText + 5; } } subtitle.RemoveEmptyLines(); subtitle.Renumber(); }
private void ComboBoxSubtitleFormatsSelectedIndexChanged(object sender, EventArgs e) { this._converted = true; if (this._oldSubtitleFormat == null) { if (!this._loading) { this.MakeHistoryForUndo(string.Format(this._language.BeforeConvertingToX, this.GetCurrentSubtitleFormat().FriendlyName)); } } else { this._subtitle.MakeHistoryForUndo(string.Format(this._language.BeforeConvertingToX, this.GetCurrentSubtitleFormat().FriendlyName), this._oldSubtitleFormat, this._fileDateTime, this._subtitleAlternate, this._subtitleAlternateFileName, this._subtitleListViewIndex, this.textBoxListViewText.SelectionStart, this.textBoxListViewTextAlternate.SelectionStart); this._oldSubtitleFormat.RemoveNativeFormatting(this._subtitle, this.GetCurrentSubtitleFormat()); this.SaveSubtitleListviewIndices(); this.SubtitleListview1.Fill(this._subtitle, this._subtitleAlternate); this.RestoreSubtitleListviewIndices(); if (this._oldSubtitleFormat.HasStyleSupport && this._networkSession == null) { this.SubtitleListview1.HideExtraColumn(); } } SubtitleFormat format = this.GetCurrentSubtitleFormat(); if (this._oldSubtitleFormat != null && !this._oldSubtitleFormat.IsFrameBased && format.IsFrameBased) { this._subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(this.CurrentFrameRate); } else if (this._oldSubtitleFormat != null && this._oldSubtitleFormat.IsFrameBased && !format.IsFrameBased) { this._subtitle.CalculateTimeCodesFromFrameNumbers(this.CurrentFrameRate); } this.ShowSource(); this.SubtitleListview1.DisplayExtraFromExtra = false; if (format != null) { this.ShowStatus(string.Format(this._language.ConvertedToX, format.FriendlyName)); this._oldSubtitleFormat = format; if (format.HasStyleSupport && this._networkSession == null) { var styles = new List<string>(); if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha)) { styles = AdvancedSubStationAlpha.GetStylesFromHeader(this._subtitle.Header); } else if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText)) { styles = TimedText10.GetStylesFromHeader(this._subtitle.Header); } else if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern)) { styles = Sami.GetStylesFromHeader(this._subtitle.Header); } else if (format.Name == "Nuendo") { styles = GetNuendoStyles(); } foreach (var p in this._subtitle.Paragraphs) { if (string.IsNullOrEmpty(p.Extra) && styles.Count > 0) { p.Extra = styles[0]; } } if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern)) { this.SubtitleListview1.ShowExtraColumn(this._languageGeneral.Class); } else if (format.GetType() == typeof(TimedText10) || format.GetType() == typeof(ItunesTimedText)) { this.SubtitleListview1.ShowExtraColumn(this._languageGeneral.StyleLanguage); } else if (format.Name == "Nuendo") { this.SubtitleListview1.ShowExtraColumn(this._languageGeneral.Character); } else { this.SubtitleListview1.ShowExtraColumn(this._languageGeneral.Style); } this.SubtitleListview1.DisplayExtraFromExtra = true; this.SubtitleListview1.Fill(this._subtitle, this._subtitleAlternate); } } this.ShowHideTextBasedFeatures(format); }
private void ShowHideTextBasedFeatures(SubtitleFormat format) { if (format != null && !format.IsTextBased) { this.textBoxSource.Enabled = false; } else { this.textBoxSource.Enabled = true; } }
private DialogResult SaveSubtitle(SubtitleFormat format) { if (string.IsNullOrEmpty(this._fileName) || this._converted) { return this.FileSaveAs(false); } try { if (format != null && !format.IsTextBased) { if (format.GetType() == typeof(Ebu)) { Ebu.Save(this._fileName, this._subtitle); } return DialogResult.OK; } string allText = this._subtitle.ToText(format); // Seungki begin if (this._splitDualSami && this._subtitleAlternate != null) { var s = new Subtitle(this._subtitle); foreach (var p in this._subtitleAlternate.Paragraphs) { s.Paragraphs.Add(p); } allText = s.ToText(format); } // Seungki end var currentEncoding = this.GetCurrentEncoding(); bool isUnicode = currentEncoding == Encoding.Unicode || currentEncoding == Encoding.UTF32 || currentEncoding == Encoding.UTF7 || currentEncoding == Encoding.UTF8; if (!isUnicode && allText.Contains(new[] { '♪', '♫', '♥', '—', '―', '…' })) { // ANSI & music/unicode symbols if (MessageBox.Show(string.Format(this._language.UnicodeMusicSymbolsAnsiWarning), this.Title, MessageBoxButtons.YesNo) == DialogResult.No) { return DialogResult.No; } } if (!isUnicode) { allText = this.NormalizeUnicode(allText); } bool containsNegativeTime = false; foreach (var p in this._subtitle.Paragraphs) { if (p.StartTime.TotalMilliseconds < 0 || p.EndTime.TotalMilliseconds < 0) { containsNegativeTime = true; break; } } if (containsNegativeTime) { if (MessageBox.Show(this._language.NegativeTimeWarning, this.Title, MessageBoxButtons.YesNo) == DialogResult.No) { return DialogResult.No; } } if (File.Exists(this._fileName)) { var fileInfo = new FileInfo(this._fileName); var fileOnDisk = fileInfo.LastWriteTime; if (this._fileDateTime != fileOnDisk && this._fileDateTime != new DateTime()) { if (MessageBox.Show(string.Format(this._language.OverwriteModifiedFile, this._fileName, fileOnDisk.ToShortDateString(), fileOnDisk.ToString("HH:mm:ss"), Environment.NewLine, this._fileDateTime.ToShortDateString(), this._fileDateTime.ToString("HH:mm:ss")), this.Title + " - " + this._language.FileOnDiskModified, MessageBoxButtons.YesNo) == DialogResult.No) { return DialogResult.No; } } if (fileInfo.IsReadOnly) { MessageBox.Show(string.Format(this._language.FileXIsReadOnly, this._fileName)); return DialogResult.No; } } if (format.GetType() == typeof(WebVTT) || format.GetType() == typeof(WebVTTFileWithLineNumber)) { this.SetEncoding(Encoding.UTF8); currentEncoding = Encoding.UTF8; } if (ModifierKeys == (Keys.Control | Keys.Shift)) { allText = allText.Replace("\r\n", "\n"); } if (format.GetType() == typeof(ItunesTimedText) || format.GetType() == typeof(ScenaristClosedCaptions) || format.GetType() == typeof(ScenaristClosedCaptionsDropFrame)) { var outputEnc = new UTF8Encoding(false); // create encoding with no BOM using (var file = new StreamWriter(this._fileName, false, outputEnc)) { // open file with encoding file.Write(allText); } } else if (currentEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml))) { var outputEnc = new UTF8Encoding(false); // create encoding with no BOM using (var file = new StreamWriter(this._fileName, false, outputEnc)) { // open file with encoding file.Write(allText); } } else { if (string.IsNullOrWhiteSpace(allText)) { MessageBox.Show(string.Format(this._language.UnableToSaveSubtitleX, this._fileName), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Stop); return DialogResult.Cancel; } using (var fs = File.Open(this._fileName, FileMode.Create, FileAccess.Write, FileShare.Read)) using (var sw = new StreamWriter(fs, currentEncoding)) { sw.Write(allText); } } this._fileDateTime = File.GetLastWriteTime(this._fileName); this.ShowStatus(string.Format(this._language.SavedSubtitleX, this._fileName)); this._changeSubtitleToString = SerializeSubtitle(this._subtitle); return DialogResult.OK; } catch (Exception exception) { MessageBox.Show(exception.Message); return DialogResult.Cancel; } }
private DialogResult SaveOriginalSubtitle(SubtitleFormat format) { try { string allText = this._subtitleAlternate.ToText(format).Trim(); var currentEncoding = this.GetCurrentEncoding(); bool isUnicode = currentEncoding == Encoding.Unicode || currentEncoding == Encoding.UTF32 || currentEncoding == Encoding.UTF7 || currentEncoding == Encoding.UTF8; if (!isUnicode && allText.Contains(new[] { '♪', '♫', '♥', '—', '―', '…' })) { // ANSI & music/unicode symbols if (MessageBox.Show(string.Format(this._language.UnicodeMusicSymbolsAnsiWarning), this.Title, MessageBoxButtons.YesNo) == DialogResult.No) { return DialogResult.No; } } if (!isUnicode) { allText = this.NormalizeUnicode(allText); } bool containsNegativeTime = false; foreach (var p in this._subtitleAlternate.Paragraphs) { if (p.StartTime.TotalMilliseconds < 0 || p.EndTime.TotalMilliseconds < 0) { containsNegativeTime = true; break; } } if (containsNegativeTime) { if (MessageBox.Show(this._language.NegativeTimeWarning, this.Title, MessageBoxButtons.YesNo) == DialogResult.No) { return DialogResult.No; } } File.WriteAllText(this._subtitleAlternateFileName, allText, currentEncoding); this.ShowStatus(string.Format(this._language.SavedOriginalSubtitleX, this._subtitleAlternateFileName)); this._changeAlternateSubtitleToString = this._subtitleAlternate.ToText(new SubRip()).Trim(); return DialogResult.OK; } catch { MessageBox.Show(string.Format(this._language.UnableToSaveSubtitleX, this._fileName)); return DialogResult.Cancel; } }
private void OpenSubtitle(string fileName, Encoding encoding, string videoFileName, string originalFileName) { if (File.Exists(fileName)) { bool videoFileLoaded = false; var file = new FileInfo(fileName); var ext = file.Extension.ToLowerInvariant(); // save last first visible index + first selected index from listview if (!string.IsNullOrEmpty(this._fileName)) { Configuration.Settings.RecentFiles.Add(this._fileName, this.FirstVisibleIndex, this.FirstSelectedIndex, this.VideoFileName, originalFileName); } this.openFileDialog1.InitialDirectory = file.DirectoryName; if (ext == ".sub" && this.IsVobSubFile(fileName, false)) { if (MessageBox.Show(this, this._language.ImportThisVobSubSubtitle, this._title, MessageBoxButtons.YesNo) == DialogResult.Yes) { this.ImportAndOcrVobSubSubtitleNew(fileName, this._loading); } return; } if (ext == ".sup") { if (FileUtil.IsBluRaySup(fileName)) { this.ImportAndOcrBluRaySup(fileName, this._loading); return; } else if (FileUtil.IsSpDvdSup(fileName)) { this.ImportAndOcrSpDvdSup(fileName, this._loading); return; } } if (ext == ".mkv" || ext == ".mks") { this.ImportSubtitleFromMatroskaFile(fileName); return; } if (ext == ".divx" || ext == ".avi") { if (this.ImportSubtitleFromDivX(fileName)) { return; } } if ((ext == ".ts" || ext == ".rec" || ext == ".mpeg" || ext == ".mpg") && file.Length > 10000 && FileUtil.IsTransportStream(fileName)) { this.ImportSubtitleFromTransportStream(fileName); return; } if ((ext == ".m2ts") && file.Length > 10000 && FileUtil.IsM2TransportStream(fileName)) { bool isTextSt = false; if (file.Length < 2000000) { var textSt = new TextST(); isTextSt = textSt.IsMine(null, fileName); } if (!isTextSt) { this.ImportSubtitleFromTransportStream(fileName); return; } } if ((ext == ".mp4" || ext == ".m4v" || ext == ".3gp") && file.Length > 10000) { if (this.ImportSubtitleFromMp4(fileName)) { this.OpenVideo(fileName); } return; } if (ext == ".mxf") { if (FileUtil.IsMaterialExchangeFormat(fileName)) { var parser = new MxfParser(fileName); if (parser.IsValid) { var subtitles = parser.GetSubtitles(); if (subtitles.Count > 0) { this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); var list = new List<string>(subtitles[0].Replace(Environment.NewLine, "\r").Replace("\n", "\r").Split('\r')); this._subtitle = new Subtitle(); var mxfFormat = this._subtitle.ReloadLoadSubtitle(list, null); this.SetCurrentFormat(mxfFormat); this._fileName = Path.GetFileNameWithoutExtension(fileName); this.SetTitle(); this.ShowStatus(string.Format(this._language.LoadedSubtitleX, this._fileName)); this._sourceViewChange = false; this._changeSubtitleToString = SerializeSubtitle(this._subtitle); this.ResetHistory(); this.SetUndockedWindowsTitle(); this._converted = true; this.ShowStatus(string.Format(this._language.LoadedSubtitleX, this._fileName) + " - " + string.Format(this._language.ConvertedToX, mxfFormat.FriendlyName)); this.ShowSource(); this.SubtitleListview1.Fill(this._subtitle, this._subtitleAlternate); this._subtitleListViewIndex = -1; this.SubtitleListview1.FirstVisibleIndex = -1; this.SubtitleListview1.SelectIndexAndEnsureVisible(0); return; } MessageBox.Show("No subtitles found!"); return; } } } if (file.Length > 1024 * 1024 * 10) { // max 10 mb // retry Blu-ray sup (file with wrong extension) if (FileUtil.IsBluRaySup(fileName)) { this.ImportAndOcrBluRaySup(fileName, this._loading); return; } // retry vobsub (file with wrong extension) if (this.IsVobSubFile(fileName, false)) { if (MessageBox.Show(this, this._language.ImportThisVobSubSubtitle, this._title, MessageBoxButtons.YesNo) == DialogResult.Yes) { this.ImportAndOcrVobSubSubtitleNew(fileName, this._loading); } return; } var text = string.Format(this._language.FileXIsLargerThan10MB + Environment.NewLine + Environment.NewLine + this._language.ContinueAnyway, fileName); if (MessageBox.Show(this, text, this.Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes) { return; } } if (this._subtitle.HistoryItems.Count > 0 || this._subtitle.Paragraphs.Count > 0) { this.MakeHistoryForUndo(string.Format(this._language.BeforeLoadOf, Path.GetFileName(fileName))); } bool change = this._changeSubtitleToString != SerializeSubtitle(this._subtitle); if (change) { change = this._lastDoNotPrompt != SerializeSubtitle(this._subtitle); } SubtitleFormat format = this._subtitle.LoadSubtitle(fileName, out encoding, encoding); if (!change) { this._changeSubtitleToString = SerializeSubtitle(this._subtitle); } this.ShowHideTextBasedFeatures(format); bool justConverted = false; if (format == null) { var ebu = new Ebu(); if (ebu.IsMine(null, fileName)) { ebu.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = ebu; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var pac = new Pac(); if (pac.IsMine(null, fileName)) { pac.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = pac; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (ext == ".m2ts") { var textST = new TextST(); if (textST.IsMine(null, fileName)) { textST.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = textST; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var pns = new Pns(); if (pns.IsMine(null, fileName)) { pns.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = pns; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var cavena890 = new Cavena890(); if (cavena890.IsMine(null, fileName)) { cavena890.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = cavena890; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var spt = new Spt(); if (spt.IsMine(null, fileName)) { spt.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = spt; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null && ext == ".wsb") { var wsb = new Wsb(); var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName))); if (wsb.IsMine(list, fileName)) { wsb.LoadSubtitle(this._subtitle, list, fileName); this._oldSubtitleFormat = wsb; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.IsMine(null, fileName)) { cheetahCaption.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = cheetahCaption; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.IsMine(null, fileName)) { capMakerPlus.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = capMakerPlus; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var captionsInc = new CaptionsInc(); if (captionsInc.IsMine(null, fileName)) { captionsInc.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = captionsInc; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var ultech130 = new Ultech130(); if (ultech130.IsMine(null, fileName)) { ultech130.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = ultech130; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var nciCaption = new NciCaption(); if (nciCaption.IsMine(null, fileName)) { nciCaption.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = nciCaption; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var tsb4 = new TSB4(); if (tsb4.IsMine(null, fileName)) { tsb4.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = tsb4; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var avidStl = new AvidStl(); if (avidStl.IsMine(null, fileName)) { avidStl.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = avidStl; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var chk = new Chk(); if (chk.IsMine(null, fileName)) { chk.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = chk; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var ayato = new Ayato(); if (ayato.IsMine(null, fileName)) { ayato.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = ayato; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var pacUnicode = new PacUnicode(); if (pacUnicode.IsMine(null, fileName)) { pacUnicode.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = pacUnicode; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { try { var bdnXml = new BdnXml(); var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName))); if (bdnXml.IsMine(list, fileName)) { if (this.ContinueNewOrExit()) { this.ImportAndOcrBdnXml(fileName, bdnXml, list); } return; } } catch { format = null; } } if (format == null) { try { var fcpImage = new FinalCutProImage(); var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName))); if (fcpImage.IsMine(list, fileName)) { if (this.ContinueNewOrExit()) { this.ImportAndOcrDost(fileName, fcpImage, list); } return; } } catch { format = null; } } if (format == null) { var elr = new ELRStudioClosedCaption(); if (elr.IsMine(null, fileName)) { elr.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = elr; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var asc = new TimeLineAscii(); if (asc.IsMine(null, fileName)) { asc.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = asc; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var asc = new TimeLineFootageAscii(); if (asc.IsMine(null, fileName)) { asc.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = asc; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (format == null) { var mtv = new TimeLineMvt(); if (mtv.IsMine(null, fileName)) { mtv.LoadSubtitle(this._subtitle, null, fileName); this._oldSubtitleFormat = mtv; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } if (ext == ".dost") { try { var dost = new Dost(); var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName))); if (dost.IsMine(list, fileName)) { if (this.ContinueNewOrExit()) { this.ImportAndOcrDost(fileName, dost, list); } return; } } catch { format = null; } } if (format == null || format.Name == Scenarist.NameOfFormat) { try { var son = new Son(); var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName))); if (son.IsMine(list, fileName)) { if (this.ContinueNewOrExit()) { this.ImportAndOcrSon(fileName, son, list); } return; } } catch { format = null; } } if (format == null || format.Name == SubRip.NameOfFormat) { if (this._subtitle.Paragraphs.Count > 1) { int imageCount = 0; foreach (var p in this._subtitle.Paragraphs) { string s = p.Text.ToLowerInvariant(); if (s.EndsWith(".bmp", StringComparison.Ordinal) || s.EndsWith(".png", StringComparison.Ordinal) || s.EndsWith(".jpg", StringComparison.Ordinal) || s.EndsWith(".tif", StringComparison.Ordinal)) { imageCount++; } } if (imageCount > 2 && imageCount >= this._subtitle.Paragraphs.Count - 2) { if (this.ContinueNewOrExit()) { this.ImportAndOcrSrt(this._subtitle); } return; } } } if (format == null) { try { var satBoxPng = new SatBoxPng(); var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName))); if (satBoxPng.IsMine(list, fileName)) { var subtitle = new Subtitle(); satBoxPng.LoadSubtitle(subtitle, list, fileName); if (this.ContinueNewOrExit()) { this.ImportAndOcrSrt(subtitle); } return; } } catch { format = null; } } if (format == null || format.Name == Scenarist.NameOfFormat) { try { var sst = new SonicScenaristBitmaps(); var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName))); if (sst.IsMine(list, fileName)) { if (this.ContinueNewOrExit()) { this.ImportAndOcrSst(fileName, sst, list); } return; } } catch { format = null; } } if (format == null) { try { var htmlSamiArray = new HtmlSamiArray(); var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName))); if (htmlSamiArray.IsMine(list, fileName)) { htmlSamiArray.LoadSubtitle(this._subtitle, list, fileName); this._oldSubtitleFormat = htmlSamiArray; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); } } catch { format = null; } } // retry vobsub (file with wrong extension) if (format == null && file.Length > 500 && this.IsVobSubFile(fileName, false)) { if (MessageBox.Show(this, this._language.ImportThisVobSubSubtitle, this._title, MessageBoxButtons.YesNo) == DialogResult.Yes) { this.ImportAndOcrVobSubSubtitleNew(fileName, this._loading); } return; } // retry Blu-ray (file with wrong extension) if (format == null && file.Length > 500 && FileUtil.IsBluRaySup(fileName)) { this.ImportAndOcrBluRaySup(fileName, this._loading); return; } // retry SP DVD (file with wrong extension) if (format == null && file.Length > 500 && FileUtil.IsSpDvdSup(fileName)) { this.ImportAndOcrSpDvdSup(fileName, this._loading); return; } // retry Matroska (file with wrong extension) if (format == null && !string.IsNullOrWhiteSpace(fileName)) { var matroska = new MatroskaFile(fileName); if (matroska.IsValid) { var subtitleList = matroska.GetTracks(true); if (subtitleList.Count > 0) { this.ImportSubtitleFromMatroskaFile(fileName); return; } } } // check for idx file if (format == null && file.Length > 100 && ext == ".idx") { MessageBox.Show(this._language.ErrorLoadIdx); return; } // check for .rar file if (format == null && file.Length > 100 && FileUtil.IsRar(fileName)) { MessageBox.Show(this._language.ErrorLoadRar); return; } // check for .zip file if (format == null && file.Length > 100 && FileUtil.IsZip(fileName)) { MessageBox.Show(this._language.ErrorLoadZip); return; } // check for .png file if (format == null && file.Length > 100 && FileUtil.IsPng(fileName)) { MessageBox.Show(this._language.ErrorLoadPng); return; } // check for .jpg file if (format == null && file.Length > 100 && FileUtil.IsJpg(fileName)) { MessageBox.Show(this._language.ErrorLoadJpg); return; } // check for .srr file if (format == null && file.Length > 100 && ext == ".srr" && FileUtil.IsSrr(fileName)) { MessageBox.Show(this._language.ErrorLoadSrr); return; } // check for Torrent file if (format == null && file.Length > 50 && FileUtil.IsTorrentFile(fileName)) { MessageBox.Show(this._language.ErrorLoadTorrent); return; } // check for all binary zeroes (I've heard about this a few times... perhaps related to crashes?) if (format == null && file.Length > 50 && FileUtil.IsSubtitleFileAllBinaryZeroes(fileName)) { MessageBox.Show(this._language.ErrorLoadBinaryZeroes); return; } if (format == null && file.Length < 100 * 1000000 && TransportStreamParser.IsDvbSup(fileName)) { this.ImportSubtitleFromDvbSupFile(fileName); return; } if (format == null && file.Length < 500000) { // Try to use a generic subtitle format parser (guessing subtitle format) try { var enc = Utilities.GetEncodingFromFile(fileName); var s = File.ReadAllText(fileName, enc); // check for RTF file if (ext == ".rtf" && s.TrimStart().StartsWith("{\\rtf", StringComparison.Ordinal)) { using (var rtb = new RichTextBox { Rtf = s }) { s = rtb.Text; } } var uknownFormatImporter = new UknownFormatImporter { UseFrames = true }; var genericParseSubtitle = uknownFormatImporter.AutoGuessImport(s.SplitToLines()); if (genericParseSubtitle.Paragraphs.Count > 1) { this._subtitle = genericParseSubtitle; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = this.GetCurrentEncoding(); justConverted = true; format = this.GetCurrentSubtitleFormat(); this.ShowStatus("Guessed subtitle format via generic subtitle parser!"); } } catch { } } this._fileDateTime = File.GetLastWriteTime(fileName); if (format != null && format.IsFrameBased) { this._subtitle.CalculateTimeCodesFromFrameNumbers(this.CurrentFrameRate); } else { this._subtitle.CalculateFrameNumbersFromTimeCodes(this.CurrentFrameRate); } if (format != null) { if (Configuration.Settings.General.RemoveBlankLinesWhenOpening) { this._subtitle.RemoveEmptyLines(); } foreach (var p in this._subtitle.Paragraphs) { // Replace U+0456 (CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I) by U+0069 (LATIN SMALL LETTER I) p.Text = p.Text.Replace("<і>", "<i>").Replace("</і>", "</i>"); } this._subtitleListViewIndex = -1; this.SetCurrentFormat(format); this._subtitleAlternateFileName = null; if (this.LoadAlternateSubtitleFile(originalFileName)) { this._subtitleAlternateFileName = originalFileName; } // Seungki begin this._splitDualSami = false; if (Configuration.Settings.SubtitleSettings.SamiDisplayTwoClassesAsTwoSubtitles && format.GetType() == typeof(Sami) && Sami.GetStylesFromHeader(this._subtitle.Header).Count == 2) { var classes = Sami.GetStylesFromHeader(this._subtitle.Header); var s1 = new Subtitle(this._subtitle); var s2 = new Subtitle(this._subtitle); s1.Paragraphs.Clear(); s2.Paragraphs.Clear(); foreach (var p in this._subtitle.Paragraphs) { if (p.Extra != null && p.Extra.Equals(classes[0], StringComparison.OrdinalIgnoreCase)) { s1.Paragraphs.Add(p); } else { s2.Paragraphs.Add(p); } } if (s1.Paragraphs.Count == 0 || s2.Paragraphs.Count == 0) { return; } this._subtitle = s1; this._subtitleAlternate = s2; this._subtitleAlternateFileName = this._fileName; this.SubtitleListview1.HideExtraColumn(); this.SubtitleListview1.ShowAlternateTextColumn(classes[1]); this._splitDualSami = true; } // Seungki end this.textBoxSource.Text = this._subtitle.ToText(format); this.SubtitleListview1.Fill(this._subtitle, this._subtitleAlternate); if (this.SubtitleListview1.Items.Count > 0) { this.SubtitleListview1.Items[0].Selected = true; } this._findHelper = null; this._spellCheckForm = null; if (this._resetVideo) { this.VideoFileName = null; this._videoInfo = null; this._videoAudioTrackNumber = -1; this.labelVideoInfo.Text = this._languageGeneral.NoVideoLoaded; this.audioVisualizer.WavePeaks = null; this.audioVisualizer.ResetSpectrogram(); this.audioVisualizer.Invalidate(); } if (Configuration.Settings.General.ShowVideoPlayer || Configuration.Settings.General.ShowAudioVisualizer) { if (!Configuration.Settings.General.DisableVideoAutoLoading) { if (!string.IsNullOrEmpty(videoFileName) && File.Exists(videoFileName)) { this.OpenVideo(videoFileName); } else if (!string.IsNullOrEmpty(fileName) && (this.toolStripButtonToggleVideo.Checked || this.toolStripButtonToggleWaveform.Checked)) { this.TryToFindAndOpenVideoFile(Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName))); } } } videoFileLoaded = this.VideoFileName != null; if (Configuration.Settings.RecentFiles.Files.Count > 0 && Configuration.Settings.RecentFiles.Files[0].FileName == fileName) { } else { Configuration.Settings.RecentFiles.Add(fileName, this.VideoFileName, this._subtitleAlternateFileName); Configuration.Settings.Save(); this.UpdateRecentFilesUI(); } this._fileName = fileName; this.SetTitle(); this.ShowStatus(string.Format(this._language.LoadedSubtitleX, this._fileName)); this._sourceViewChange = false; this._changeSubtitleToString = SerializeSubtitle(this._subtitle); this._converted = false; this.ResetHistory(); this.SetUndockedWindowsTitle(); if (justConverted) { this._converted = true; this.ShowStatus(string.Format(this._language.LoadedSubtitleX, this._fileName) + " - " + string.Format(this._language.ConvertedToX, format.FriendlyName)); } if (Configuration.Settings.General.AutoConvertToUtf8) { encoding = Encoding.UTF8; } this.SetEncoding(encoding); if (format.GetType() == typeof(SubStationAlpha)) { string errors = AdvancedSubStationAlpha.CheckForErrors(this._subtitle.Header); if (!string.IsNullOrEmpty(errors)) { MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } errors = (format as SubStationAlpha).Errors; if (!string.IsNullOrEmpty(errors)) { MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else if (format.GetType() == typeof(AdvancedSubStationAlpha)) { string errors = AdvancedSubStationAlpha.CheckForErrors(this._subtitle.Header); if (!string.IsNullOrEmpty(errors)) { MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } errors = (format as AdvancedSubStationAlpha).Errors; if (!string.IsNullOrEmpty(errors)) { MessageBox.Show(errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else if (format.GetType() == typeof(SubRip)) { string errors = (format as SubRip).Errors; if (!string.IsNullOrEmpty(errors)) { MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else if (format.GetType() == typeof(MicroDvd)) { string errors = (format as MicroDvd).Errors; if (!string.IsNullOrEmpty(errors)) { MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } else { if (file.Length < 50) { this._findHelper = null; this._spellCheckForm = null; this.VideoFileName = null; this._videoInfo = null; this._videoAudioTrackNumber = -1; this.labelVideoInfo.Text = this._languageGeneral.NoVideoLoaded; this.audioVisualizer.WavePeaks = null; this.audioVisualizer.ResetSpectrogram(); this.audioVisualizer.Invalidate(); Configuration.Settings.RecentFiles.Add(fileName, this.FirstVisibleIndex, this.FirstSelectedIndex, this.VideoFileName, this._subtitleAlternateFileName); Configuration.Settings.Save(); this.UpdateRecentFilesUI(); this._fileName = fileName; this.SetTitle(); this.ShowStatus(string.Format(this._language.LoadedEmptyOrShort, this._fileName)); this._sourceViewChange = false; this._converted = false; MessageBox.Show(this._language.FileIsEmptyOrShort); } else { if (ext == ".xml") { var sb = new StringBuilder(); foreach (var line in File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName))) { sb.AppendLine(line); } var xmlAsString = sb.ToString().Trim(); if (xmlAsString.Contains("http://www.w3.org/ns/ttml") && xmlAsString.Contains("<?xml version=") || xmlAsString.Contains("http://www.w3.org/") && xmlAsString.Contains("/ttaf1")) { var xml = new XmlDocument(); try { xml.LoadXml(xmlAsString); } catch (Exception ex) { MessageBox.Show("Timed text is not valid: " + ex.Message); return; } } } this.ShowUnknownSubtitle(); return; } } if (!videoFileLoaded && this.mediaPlayer.VideoPlayer != null) { this.mediaPlayer.VideoPlayer.DisposeVideoPlayer(); this.mediaPlayer.VideoPlayer = null; this.timer1.Stop(); } this.ResetShowEarlierOrLater(); } else { MessageBox.Show(string.Format(this._language.FileNotFound, fileName)); } }
public virtual void RemoveNativeFormatting(Subtitle subtitle, SubtitleFormat newFormat) { }
private void ComboBoxSubtitleFormatsEnter(object sender, EventArgs e) { SubtitleFormat format = GetCurrentSubtitleFormat(); if (format != null) _oldSubtitleFormat = format; }
public static Subtitle LoadMatroskaSSa(MatroskaSubtitleInfo matroskaSubtitleInfo, string fileName, SubtitleFormat format, List<SubtitleSequence> sub) { Subtitle subtitle = new Subtitle(); subtitle.Header = matroskaSubtitleInfo.CodecPrivate; var lines = new List<string>(); foreach (string l in subtitle.Header.Trim().Replace(Environment.NewLine, "\n").Split('\n')) lines.Add(l); StringBuilder footer = new StringBuilder(); Subtitle comments = new Subtitle(); if (!string.IsNullOrEmpty(matroskaSubtitleInfo.CodecPrivate)) { bool footerOn = false; foreach (string line in lines) { if (footerOn) { footer.AppendLine(line); } else if (line.Trim() == "[Events]") { footerOn = false; } else if (line.Trim() == "[Fonts]" || line.Trim() == "[Graphics]") { footerOn = true; footer.AppendLine(); footer.AppendLine(); footer.AppendLine(line); } else if (line.StartsWith("Comment:")) { var arr = line.Split(','); if (arr.Length > 3) { arr = arr[1].Split(":.".ToCharArray()); if (arr.Length == 4) { int hour; int min; int sec; int ms; if (int.TryParse(arr[0], out hour) && int.TryParse(arr[1], out min) && int.TryParse(arr[2], out sec) && int.TryParse(arr[3], out ms)) { comments.Paragraphs.Add(new Paragraph(new TimeCode(hour, min, sec, ms * 10), new TimeCode(0, 0, 0, 0), line)); } } } } } } if (!subtitle.Header.Contains("[Events]")) { subtitle.Header = subtitle.Header.Trim() + Environment.NewLine + Environment.NewLine + "[Events]" + Environment.NewLine + "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text" + Environment.NewLine; } else { subtitle.Header = subtitle.Header.Remove(subtitle.Header.IndexOf("[Events]")); subtitle.Header = subtitle.Header.Trim() + Environment.NewLine + Environment.NewLine + "[Events]" + Environment.NewLine + "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text" + Environment.NewLine; } lines = new List<string>(); foreach (string l in subtitle.Header.Trim().Replace(Environment.NewLine, "\n").Split('\n')) lines.Add(l); const string timeCodeFormat = "{0}:{1:00}:{2:00}.{3:00}"; // h:mm:ss.cc foreach (SubtitleSequence mp in sub) { Paragraph p = new Paragraph(string.Empty, mp.StartMilliseconds, mp.EndMilliseconds); string start = string.Format(timeCodeFormat, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds / 10); string end = string.Format(timeCodeFormat, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds / 10); //MKS contains this: ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text for (int commentIndex = 0; commentIndex < comments.Paragraphs.Count; commentIndex++) { var cp = comments.Paragraphs[commentIndex]; if (cp.StartTime.TotalMilliseconds <= p.StartTime.TotalMilliseconds) lines.Add(cp.Text); } for (int commentIndex = comments.Paragraphs.Count - 1; commentIndex >= 0; commentIndex--) { var cp = comments.Paragraphs[commentIndex]; if (cp.StartTime.TotalMilliseconds <= p.StartTime.TotalMilliseconds) comments.Paragraphs.RemoveAt(commentIndex); } string text = mp.Text; int idx = text.IndexOf(',') + 1; if (idx > 0 && idx < text.Length) { text = text.Remove(0, idx); // remove ReadOrder idx = text.IndexOf(','); text = text.Insert(idx, "," + start + "," + end); lines.Add("Dialogue: " + text); } } for (int commentIndex = 0; commentIndex < comments.Paragraphs.Count; commentIndex++) { var cp = comments.Paragraphs[commentIndex]; lines.Add(cp.Text); } foreach (string l in footer.ToString().Replace(Environment.NewLine, "\n").Split('\n')) lines.Add(l); format.LoadSubtitle(subtitle, lines, fileName); return subtitle; }
public void SetCurrentFormat(SubtitleFormat format) { if (format.IsVobSubIndexFile) { comboBoxSubtitleFormats.Items.Clear(); comboBoxSubtitleFormats.Items.Add(format.FriendlyName); SubtitleListview1.HideNonVobSubColumns(); } else if (comboBoxSubtitleFormats.Items.Count == 1) { SetFormatToSubRip(); SubtitleListview1.ShowAllColumns(); } int i = 0; foreach (object obj in comboBoxSubtitleFormats.Items) { if (obj.ToString() == format.FriendlyName) comboBoxSubtitleFormats.SelectedIndex = i; i++; } }
/// <summary> /// The get alignment from paragraph. /// </summary> /// <param name="p"> /// The p. /// </param> /// <param name="format"> /// The format. /// </param> /// <param name="subtitle"> /// The subtitle. /// </param> /// <returns> /// The <see cref="ContentAlignment"/>. /// </returns> private static ContentAlignment GetAlignmentFromParagraph(MakeBitmapParameter p, SubtitleFormat format, Subtitle subtitle) { var alignment = ContentAlignment.BottomCenter; if (p.AlignLeft) { alignment = ContentAlignment.BottomLeft; } else if (p.AlignRight) { alignment = ContentAlignment.BottomRight; } if (format.HasStyleSupport && !string.IsNullOrEmpty(p.P.Extra)) { if (format.GetType() == typeof(SubStationAlpha)) { var style = AdvancedSubStationAlpha.GetSsaStyle(p.P.Extra, subtitle.Header); alignment = GetSsaAlignment("{\\a" + style.Alignment + "}", alignment); } else if (format.GetType() == typeof(AdvancedSubStationAlpha)) { var style = AdvancedSubStationAlpha.GetSsaStyle(p.P.Extra, subtitle.Header); alignment = GetAssAlignment("{\\an" + style.Alignment + "}", alignment); } } string text = p.P.Text; if (format.GetType() == typeof(SubStationAlpha) && text.Length > 5) { text = p.P.Text.Substring(0, 6); alignment = GetSsaAlignment(text, alignment); } else if (text.Length > 6) { text = p.P.Text.Substring(0, 6); alignment = GetAssAlignment(text, alignment); } return alignment; }
public override void RemoveNativeFormatting(Subtitle subtitle, SubtitleFormat newFormat) { foreach (Paragraph p in subtitle.Paragraphs) { if (p.Text.Contains('<')) { string text = p.Text; text = RemoveTag("v", text); text = RemoveTag("rt", text); text = RemoveTag("ruby", text); text = RemoveTag("c", text); text = RemoveTag("span", text); p.Text = text; } } }
/// <summary> /// The initialize from vob sub ocr. /// </summary> /// <param name="subtitle"> /// The subtitle. /// </param> /// <param name="format"> /// The format. /// </param> /// <param name="exportType"> /// The export type. /// </param> /// <param name="fileName"> /// The file name. /// </param> /// <param name="vobSubOcr"> /// The vob sub ocr. /// </param> /// <param name="languageString"> /// The language string. /// </param> internal void InitializeFromVobSubOcr(Subtitle subtitle, SubtitleFormat format, string exportType, string fileName, VobSubOcr vobSubOcr, string languageString) { this._vobSubOcr = vobSubOcr; this.Initialize(subtitle, format, exportType, fileName, null, this._videoFileName); // set language if (!string.IsNullOrEmpty(languageString)) { if (languageString.Contains('(') && languageString[0] != '(') { languageString = languageString.Substring(0, languageString.IndexOf('(') - 1).Trim(); } for (int i = 0; i < this.comboBoxLanguage.Items.Count; i++) { string l = this.comboBoxLanguage.Items[i].ToString(); if (l == languageString && i < this.comboBoxLanguage.Items.Count) { this.comboBoxLanguage.SelectedIndex = i; } } } // Disable options not available when exporting existing images this.comboBoxSubtitleFont.Enabled = false; this.comboBoxSubtitleFontSize.Enabled = false; this.buttonColor.Visible = false; this.panelColor.Visible = false; this.checkBoxBold.Visible = false; this.checkBoxSimpleRender.Visible = false; this.comboBox3D.Enabled = false; this.numericUpDownDepth3D.Enabled = false; this.buttonBorderColor.Visible = false; this.panelBorderColor.Visible = false; this.labelBorderWidth.Visible = false; this.comboBoxBorderWidth.Visible = false; this.buttonShadowColor.Visible = false; this.panelShadowColor.Visible = false; this.labelShadowWidth.Visible = false; this.comboBoxShadowWidth.Visible = false; this.labelShadowTransparency.Visible = false; this.numericUpDownShadowTransparency.Visible = false; this.labelLineHeight.Visible = false; this.numericUpDownLineSpacing.Visible = false; }
public void RunBatchSettings(Subtitle subtitle, SubtitleFormat format, Encoding encoding, string language) { _autoDetectGoogleLanguage = language; var ci = CultureInfo.GetCultureInfo(_autoDetectGoogleLanguage); string threeLetterISOLanguageName = ci.ThreeLetterISOLanguageName; comboBoxLanguage.Items.Clear(); foreach (CultureInfo x in CultureInfo.GetCultures(CultureTypes.NeutralCultures)) comboBoxLanguage.Items.Add(x); comboBoxLanguage.Sorted = true; int languageIndex = 0; int j = 0; foreach (var x in comboBoxLanguage.Items) { var xci = (CultureInfo)x; if (xci.TwoLetterISOLanguageName == ci.TwoLetterISOLanguageName) { languageIndex = j; break; } else if (xci.TwoLetterISOLanguageName == "en") { languageIndex = j; } j++; } comboBoxLanguage.SelectedIndex = languageIndex; AddFixActions(subtitle, threeLetterISOLanguageName); _originalSubtitle = new Subtitle(subtitle); // copy constructor _subtitle = new Subtitle(subtitle); // copy constructor _format = format; _encoding = encoding; _onlyListFixes = false; InitUI(); groupBoxStep1.Text = string.Empty; buttonBack.Visible = false; buttonNextFinish.Visible = false; buttonCancel.Text = Configuration.Settings.Language.General.OK; }
public void RunBatch(Subtitle subtitle, SubtitleFormat format, Encoding encoding, string language) { _autoDetectGoogleLanguage = language; var ci = CultureInfo.GetCultureInfo(_autoDetectGoogleLanguage); string threeLetterISOLanguageName = ci.ThreeLetterISOLanguageName; comboBoxLanguage.Items.Clear(); foreach (CultureInfo x in CultureInfo.GetCultures(CultureTypes.NeutralCultures)) comboBoxLanguage.Items.Add(x); comboBoxLanguage.Sorted = true; int languageIndex = 0; int j = 0; foreach (var x in comboBoxLanguage.Items) { var xci = (CultureInfo)x; if (xci.TwoLetterISOLanguageName == ci.TwoLetterISOLanguageName) { languageIndex = j; break; } else if (xci.TwoLetterISOLanguageName == "en") { languageIndex = j; } j++; } comboBoxLanguage.SelectedIndex = languageIndex; AddFixActions(subtitle, threeLetterISOLanguageName); _originalSubtitle = new Subtitle(subtitle); // copy constructor _subtitle = new Subtitle(subtitle); // copy constructor _format = format; _encoding = encoding; _onlyListFixes = true; _hasFixesBeenMade = true; _numberOfImportantLogMessages = 0; _onlyListFixes = false; _totalFixes = 0; _totalErrors = 0; _batchMode = true; RunSelectedActions(); _originalSubtitle = _subtitle; }
public override void RemoveNativeFormatting(Subtitle subtitle, SubtitleFormat newFormat) { if (newFormat != null && newFormat.Name == new AdvancedSubStationAlpha().Name) { // do we need any conversion? } else { foreach (Paragraph p in subtitle.Paragraphs) { int indexOfBegin = p.Text.IndexOf('{'); string pre = string.Empty; while (indexOfBegin >= 0 && p.Text.IndexOf('}') > indexOfBegin) { string s = p.Text.Substring(indexOfBegin); if (s.StartsWith("{\\an1}", StringComparison.Ordinal) || s.StartsWith("{\\an2}", StringComparison.Ordinal) || s.StartsWith("{\\an3}", StringComparison.Ordinal) || s.StartsWith("{\\an4}", StringComparison.Ordinal) || s.StartsWith("{\\an5}", StringComparison.Ordinal) || s.StartsWith("{\\an6}", StringComparison.Ordinal) || s.StartsWith("{\\an7}", StringComparison.Ordinal) || s.StartsWith("{\\an8}", StringComparison.Ordinal) || s.StartsWith("{\\an9}", StringComparison.Ordinal)) { pre = s.Substring(0, 6); } else if (s.StartsWith("{\\an1\\", StringComparison.Ordinal) || s.StartsWith("{\\an2\\", StringComparison.Ordinal) || s.StartsWith("{\\an3\\", StringComparison.Ordinal) || s.StartsWith("{\\an4\\", StringComparison.Ordinal) || s.StartsWith("{\\an5\\", StringComparison.Ordinal) || s.StartsWith("{\\an6\\", StringComparison.Ordinal) || s.StartsWith("{\\an7\\", StringComparison.Ordinal) || s.StartsWith("{\\an8\\", StringComparison.Ordinal) || s.StartsWith("{\\an9\\", StringComparison.Ordinal)) { pre = s.Substring(0, 5) + "}"; } else if (s.StartsWith("{\\a1}", StringComparison.Ordinal) || s.StartsWith("{\\a1\\", StringComparison.Ordinal) || s.StartsWith("{\\a3}", StringComparison.Ordinal) || s.StartsWith("{\\a3\\", StringComparison.Ordinal)) { pre = s.Substring(0, 4) + "}"; } else if (s.StartsWith("{\\a9}", StringComparison.Ordinal) || s.StartsWith("{\\a9\\", StringComparison.Ordinal)) { pre = "{\\an4}"; } else if (s.StartsWith("{\\a10}", StringComparison.Ordinal) || s.StartsWith("{\\a10\\", StringComparison.Ordinal)) { pre = "{\\an5}"; } else if (s.StartsWith("{\\a11}", StringComparison.Ordinal) || s.StartsWith("{\\a11\\", StringComparison.Ordinal)) { pre = "{\\an6}"; } else if (s.StartsWith("{\\a5}", StringComparison.Ordinal) || s.StartsWith("{\\a5\\", StringComparison.Ordinal)) { pre = "{\\an7}"; } else if (s.StartsWith("{\\a6}", StringComparison.Ordinal) || s.StartsWith("{\\a6\\", StringComparison.Ordinal)) { pre = "{\\an8}"; } else if (s.StartsWith("{\\a7}", StringComparison.Ordinal) || s.StartsWith("{\\a7\\", StringComparison.Ordinal)) { pre = "{\\an9}"; } int indexOfEnd = p.Text.IndexOf('}'); p.Text = p.Text.Remove(indexOfBegin, (indexOfEnd - indexOfBegin) + 1); indexOfBegin = p.Text.IndexOf('{'); } p.Text = pre + p.Text; } } }
private void OpenSubtitle(string fileName, Encoding encoding, string videoFileName, string originalFileName) { if (File.Exists(fileName)) { bool videoFileLoaded = false; string ext = Path.GetExtension(fileName).ToLower(); // save last first visible index + first selected index from listview if (!string.IsNullOrEmpty(_fileName)) Configuration.Settings.RecentFiles.Add(_fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, originalFileName); openFileDialog1.InitialDirectory = Path.GetDirectoryName(fileName); if (ext == ".sub" && IsVobSubFile(fileName, false)) { if (MessageBox.Show(this, _language.ImportThisVobSubSubtitle, _title, MessageBoxButtons.YesNo) == DialogResult.Yes) { ImportAndOcrVobSubSubtitleNew(fileName, _loading); } return; } if (ext == ".sup") { if (IsBluRaySupFile(fileName)) { ImportAndOcrBluRaySup(fileName, _loading); return; } else if (IsSpDvdSupFile(fileName)) { ImportAndOcrSpDvdSup(fileName, _loading); return; } } if (ext == ".mkv" || ext == ".mks") { Matroska mkv = new Matroska(); bool isValid = false; bool hasConstantFrameRate = false; double frameRate = 0; int width = 0; int height = 0; double milliseconds = 0; string videoCodec = string.Empty; mkv.GetMatroskaInfo(fileName, ref isValid, ref hasConstantFrameRate, ref frameRate, ref width, ref height, ref milliseconds, ref videoCodec); if (isValid) { ImportSubtitleFromMatroskaFile(fileName); return; } } if (ext == ".divx" || ext == ".avi") { if (ImportSubtitleFromDivX(fileName)) return; } var fi = new FileInfo(fileName); if ((ext == ".ts" || ext == ".rec" || ext == ".mpeg" || ext == ".mpg") && fi.Length > 10000 && IsTransportStream(fileName)) { ImportSubtitleFromTransportStream(fileName); return; } if ((ext == ".m2ts") && fi.Length > 10000 && IsM2TransportStream(fileName)) { ImportSubtitleFromTransportStream(fileName); return; } if ((ext == ".mp4" || ext == ".m4v" || ext == ".3gp") && fi.Length > 10000) { if (ImportSubtitleFromMp4(fileName)) OpenVideo(fileName); return; } if (fi.Length > 1024 * 1024 * 10) // max 10 mb { // retry bluray sup (file with wrong extension) if (IsBluRaySupFile(fileName)) { ImportAndOcrBluRaySup(fileName, _loading); return; } // retry vobsub (file with wrong extension) if (IsVobSubFile(fileName, false)) { if (MessageBox.Show(this, _language.ImportThisVobSubSubtitle, _title, MessageBoxButtons.YesNo) == DialogResult.Yes) { ImportAndOcrVobSubSubtitleNew(fileName, _loading); } return; } if (MessageBox.Show(this, string.Format(_language.FileXIsLargerThan10Mb + Environment.NewLine + Environment.NewLine + _language.ContinueAnyway, fileName), Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes) return; } if (_subtitle.HistoryItems.Count > 0 || _subtitle.Paragraphs.Count > 0) MakeHistoryForUndo(string.Format(_language.BeforeLoadOf, Path.GetFileName(fileName))); bool change = _changeSubtitleToString != SerializeSubtitle(_subtitle); if (change) change = _lastDoNotPrompt != SerializeSubtitle(_subtitle); SubtitleFormat format = _subtitle.LoadSubtitle(fileName, out encoding, encoding); if (!change) _changeSubtitleToString = SerializeSubtitle(_subtitle); bool justConverted = false; if (format == null) { var ebu = new Ebu(); if (ebu.IsMine(null, fileName)) { ebu.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = ebu; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var pac = new Pac(); if (pac.IsMine(null, fileName)) { pac.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = pac; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var cavena890 = new Cavena890(); if (cavena890.IsMine(null, fileName)) { cavena890.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = cavena890; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var spt = new Spt(); if (spt.IsMine(null, fileName)) { spt.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = spt; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null && ext == ".wsb") { string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)); var list = new List<string>(); foreach (string l in arr) list.Add(l); var wsb = new Wsb(); if (wsb.IsMine(list, fileName)) { wsb.LoadSubtitle(_subtitle, list, fileName); _oldSubtitleFormat = wsb; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.IsMine(null, fileName)) { cheetahCaption.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = cheetahCaption; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.IsMine(null, fileName)) { capMakerPlus.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = capMakerPlus; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var captionsInc = new CaptionsInc(); if (captionsInc.IsMine(null, fileName)) { captionsInc.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = captionsInc; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var ultech130 = new Ultech130(); if (ultech130.IsMine(null, fileName)) { ultech130.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = ultech130; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var nciCaption = new NciCaption(); if (nciCaption.IsMine(null, fileName)) { nciCaption.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = nciCaption; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var tsb4 = new TSB4(); if (tsb4.IsMine(null, fileName)) { tsb4.LoadSubtitle(this._subtitle, null, fileName); _oldSubtitleFormat = tsb4; this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this.SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { var avidStl = new AvidStl(); if (avidStl.IsMine(null, fileName)) { avidStl.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = avidStl; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (format == null) { try { var bdnXml = new BdnXml(); string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)); var list = new List<string>(); foreach (string l in arr) list.Add(l); if (bdnXml.IsMine(list, fileName)) { if (ContinueNewOrExit()) { ImportAndOcrBdnXml(fileName, bdnXml, list); } return; } } catch { format = null; } } if (format == null) { try { var fcpImage = new FinalCutProImage(); string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)); var list = new List<string>(); foreach (string l in arr) list.Add(l); if (fcpImage.IsMine(list, fileName)) { if (ContinueNewOrExit()) { ImportAndOcrDost(fileName, fcpImage, list); } return; } } catch { format = null; } } if (format == null) { var elr = new ELRStudioClosedCaption(); if (elr.IsMine(null, fileName)) { elr.LoadSubtitle(_subtitle, null, fileName); _oldSubtitleFormat = elr; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } if (fileName.ToLower().EndsWith(".dost")) { try { var dost = new Dost(); string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)); var list = new List<string>(); foreach (string l in arr) list.Add(l); if (dost.IsMine(list, fileName)) { if (ContinueNewOrExit()) ImportAndOcrDost(fileName, dost, list); return; } } catch { format = null; } } if (format == null || format.Name == new Scenarist().Name) { try { var son = new Son(); string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)); var list = new List<string>(); foreach (string l in arr) list.Add(l); if (son.IsMine(list, fileName)) { if (ContinueNewOrExit()) ImportAndOcrSon(fileName, son, list); return; } } catch { format = null; } } if (format == null || format.Name == new SubRip().Name) { if (_subtitle.Paragraphs.Count > 1) { int imageCount = 0; foreach (Paragraph p in _subtitle.Paragraphs) { string s = p.Text.ToLower(); if (s.EndsWith(".bmp") || s.EndsWith(".png") || s.EndsWith(".jpg") || s.EndsWith(".tif")) { imageCount++; } } if (imageCount > 2 && imageCount >= _subtitle.Paragraphs.Count - 2) { if (ContinueNewOrExit()) ImportAndOcrSrt(fileName, _subtitle); return; } } } if (format == null || format.Name == new Scenarist().Name) { try { var sst = new SonicScenaristBitmaps(); string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)); var list = new List<string>(); foreach (string l in arr) list.Add(l); if (sst.IsMine(list, fileName)) { if (ContinueNewOrExit()) ImportAndOcrSst(fileName, sst, list); return; } } catch { format = null; } } if (format == null) { try { var htmlSamiArray = new HtmlSamiArray(); string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)); var list = new List<string>(); foreach (string l in arr) list.Add(l); if (htmlSamiArray.IsMine(list, fileName)) { htmlSamiArray.LoadSubtitle(_subtitle, list, fileName); _oldSubtitleFormat = htmlSamiArray; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); } } catch { format = null; } } // retry vobsub (file with wrong extension) if (format == null && fi.Length > 500 && IsVobSubFile(fileName, false)) { if (MessageBox.Show(this, _language.ImportThisVobSubSubtitle, _title, MessageBoxButtons.YesNo) == DialogResult.Yes) { ImportAndOcrVobSubSubtitleNew(fileName, _loading); } return; } // retry bluray (file with wrong extension) if (format == null && fi.Length > 500 && IsBluRaySupFile(fileName)) { ImportAndOcrBluRaySup(fileName, _loading); return; } // retry SP dvd (file with wrong extension) if (format == null && fi.Length > 500 && IsSpDvdSupFile(fileName)) { ImportAndOcrSpDvdSup(fileName, _loading); return; } // check for idx file if (format == null && fi.Length > 100 && ext == ".idx") { if (string.IsNullOrEmpty(_language.ErrorLoadIdx)) MessageBox.Show("Cannot read/edit .idx files. Idx files are a part of an idx/sub file pair (also called VobSub), and SE can open the .sub file."); else MessageBox.Show(_language.ErrorLoadIdx); return; } // check for .rar file if (format == null && fi.Length > 100 && IsRarFile(fileName)) { if (string.IsNullOrEmpty(_language.ErrorLoadRar)) MessageBox.Show("This file seems to be a compressed .rar file. SE cannot open compressed files."); else MessageBox.Show(_language.ErrorLoadRar); return; } // check for .zip file if (format == null && fi.Length > 100 && IsZipFile(fileName)) { if (string.IsNullOrEmpty(_language.ErrorLoadZip)) MessageBox.Show("This file seems to be a compressed .zip file. SE cannot open compressed files."); else MessageBox.Show(_language.ErrorLoadZip); return; } if (format == null && fi.Length < 500000) { // Try to use a generic subtitle format parser (guessing subtitle format) try { Encoding enc = Utilities.GetEncodingFromFile(fileName); string s = File.ReadAllText(fileName, enc); // check for RTF file if (fileName.ToLower().EndsWith(".rtf") && !s.Trim().StartsWith("{\\rtf")) { var rtBox = new System.Windows.Forms.RichTextBox(); rtBox.Rtf = s; s = rtBox.Text; } var uknownFormatImporter = new UknownFormatImporter(); uknownFormatImporter.UseFrames = true; var genericParseSubtitle = uknownFormatImporter.AutoGuessImport(s.Replace(Environment.NewLine, "\n").Split('\n')); if (genericParseSubtitle.Paragraphs.Count > 1) { _subtitle = genericParseSubtitle; SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); SetEncoding(Configuration.Settings.General.DefaultEncoding); encoding = GetCurrentEncoding(); justConverted = true; format = GetCurrentSubtitleFormat(); ShowStatus("Guessed subtitle format via generic subtitle parser!"); } } catch { } } _fileDateTime = File.GetLastWriteTime(fileName); if (format != null && format.IsFrameBased) _subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate); else _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); if (format != null) { if (Configuration.Settings.General.RemoveBlankLinesWhenOpening) { _subtitle.RemoveEmptyLines(); } foreach (Paragraph p in _subtitle.Paragraphs) { p.Text = p.Text.Replace("<і>", "<i>").Replace("</і>", "</i>"); // different unicode chars } _subtitleListViewIndex = -1; SetCurrentFormat(format); _subtitleAlternateFileName = null; if (LoadAlternateSubtitleFile(originalFileName)) _subtitleAlternateFileName = originalFileName; // Seungki begin _splitDualSami = false; if (Configuration.Settings.SubtitleSettings.SamiDisplayTwoClassesAsTwoSubtitles && format.GetType() == typeof(Sami) && Sami.GetStylesFromHeader(_subtitle.Header).Count == 2) { List<string> classes = Sami.GetStylesFromHeader(_subtitle.Header); var s1 = new Subtitle(_subtitle); var s2 = new Subtitle(_subtitle); s1.Paragraphs.Clear(); s2.Paragraphs.Clear(); foreach (Paragraph p in _subtitle.Paragraphs) { if (p.Extra != null && p.Extra.ToLower() == classes[0].ToLower()) s1.Paragraphs.Add(p); else s2.Paragraphs.Add(p); } if (s1.Paragraphs.Count == 0 || s2.Paragraphs.Count == 0) return; _subtitle = s1; _subtitleAlternate = s2; _subtitleAlternateFileName = _fileName; SubtitleListview1.HideExtraColumn(); SubtitleListview1.ShowAlternateTextColumn(classes[1]); _splitDualSami = true; } // Seungki end textBoxSource.Text = _subtitle.ToText(format); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); if (SubtitleListview1.Items.Count > 0) SubtitleListview1.Items[0].Selected = true; _findHelper = null; _spellCheckForm = null; if (_resetVideo) { _videoFileName = null; _videoInfo = null; _videoAudioTrackNumber = -1; labelVideoInfo.Text = Configuration.Settings.Language.General.NoVideoLoaded; audioVisualizer.WavePeaks = null; audioVisualizer.ResetSpectrogram(); audioVisualizer.Invalidate(); } if (Configuration.Settings.General.ShowVideoPlayer || Configuration.Settings.General.ShowAudioVisualizer) { if (!Configuration.Settings.General.DisableVideoAutoLoading) { if (!string.IsNullOrEmpty(videoFileName) && File.Exists(videoFileName)) { OpenVideo(videoFileName); } else if (!string.IsNullOrEmpty(fileName) && (toolStripButtonToggleVideo.Checked || toolStripButtonToggleWaveForm.Checked)) { TryToFindAndOpenVideoFile(Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName))); } } } videoFileLoaded = _videoFileName != null; if (Configuration.Settings.RecentFiles.Files.Count > 0 && Configuration.Settings.RecentFiles.Files[0].FileName == fileName) { } else { Configuration.Settings.RecentFiles.Add(fileName, _videoFileName, _subtitleAlternateFileName); Configuration.Settings.Save(); UpdateRecentFilesUI(); } _fileName = fileName; SetTitle(); ShowStatus(string.Format(_language.LoadedSubtitleX, _fileName)); _sourceViewChange = false; _changeSubtitleToString = SerializeSubtitle(_subtitle); _converted = false; ResetHistory(); SetUndockedWindowsTitle(); if (justConverted) { _converted = true; ShowStatus(string.Format(_language.LoadedSubtitleX, _fileName) + " - " + string.Format(_language.ConvertedToX, format.FriendlyName)); } if (Configuration.Settings.General.AutoConvertToUtf8) encoding = Encoding.UTF8; SetEncoding(encoding); if (format.GetType() == typeof(SubStationAlpha)) { string errors = AdvancedSubStationAlpha.CheckForErrors(_subtitle.Header); if (!string.IsNullOrEmpty(errors)) MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); errors = (format as SubStationAlpha).Errors; if (!string.IsNullOrEmpty(errors)) MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (format.GetType() == typeof(AdvancedSubStationAlpha)) { string errors = AdvancedSubStationAlpha.CheckForErrors(_subtitle.Header); if (!string.IsNullOrEmpty(errors)) MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); errors = (format as AdvancedSubStationAlpha).Errors; if (!string.IsNullOrEmpty(errors)) MessageBox.Show(errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (format.GetType() == typeof(SubRip)) { string errors = (format as SubRip).Errors; if (!string.IsNullOrEmpty(errors)) MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (format.GetType() == typeof(MicroDvd)) { string errors = (format as MicroDvd).Errors; if (!string.IsNullOrEmpty(errors)) MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { var info = new FileInfo(fileName); if (info.Length < 50) { _findHelper = null; _spellCheckForm = null; _videoFileName = null; _videoInfo = null; _videoAudioTrackNumber = -1; labelVideoInfo.Text = Configuration.Settings.Language.General.NoVideoLoaded; audioVisualizer.WavePeaks = null; audioVisualizer.ResetSpectrogram(); audioVisualizer.Invalidate(); Configuration.Settings.RecentFiles.Add(fileName, FirstVisibleIndex, FirstSelectedIndex, _videoFileName, _subtitleAlternateFileName); Configuration.Settings.Save(); UpdateRecentFilesUI(); _fileName = fileName; SetTitle(); ShowStatus(string.Format(_language.LoadedEmptyOrShort, _fileName)); _sourceViewChange = false; _converted = false; MessageBox.Show(_language.FileIsEmptyOrShort); } else { if (!string.IsNullOrEmpty(fileName) && fileName.ToLower().EndsWith(".xml")) { string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)); var sb = new StringBuilder(); foreach (string l in arr) sb.AppendLine(l); string xmlAsString = sb.ToString().Trim(); if (xmlAsString.Contains("http://www.w3.org/ns/ttml") && xmlAsString.Contains("<?xml version=")) { var xml = new System.Xml.XmlDocument(); try { xml.LoadXml(xmlAsString); } catch (Exception ex) { MessageBox.Show("Timed text is not valid: " + ex.Message); return; } } if (xmlAsString.Contains("http://www.w3.org/") && xmlAsString.Contains("/ttaf1")) { var xml = new System.Xml.XmlDocument(); try { xml.LoadXml(xmlAsString); } catch (Exception ex) { MessageBox.Show("Timed text is not valid: " + ex.Message); return; } } } ShowUnknownSubtitle(); return; } } if (!videoFileLoaded && mediaPlayer.VideoPlayer != null) { mediaPlayer.VideoPlayer.DisposeVideoPlayer(); mediaPlayer.VideoPlayer = null; timer1.Stop(); } } else { MessageBox.Show(string.Format(_language.FileNotFound, fileName)); } }
private DialogResult SaveSubtitle(SubtitleFormat format) { if (string.IsNullOrEmpty(_fileName) || _converted) return FileSaveAs(false); try { string allText = _subtitle.ToText(format); // Seungki begin if (_splitDualSami && _subtitleAlternate != null) { var s = new Subtitle(_subtitle); foreach (Paragraph p in _subtitleAlternate.Paragraphs) s.Paragraphs.Add(p); allText = s.ToText(format); } // Seungki end var currentEncoding = GetCurrentEncoding(); if (currentEncoding == Encoding.Default && (allText.Contains("♪") || allText.Contains("♫") || allText.Contains("♥") || allText.Contains("—") || allText.Contains("…"))) // ANSI & music/unicode symbols { if (MessageBox.Show(string.Format(_language.UnicodeMusicSymbolsAnsiWarning), Title, MessageBoxButtons.YesNo) == DialogResult.No) return DialogResult.No; } bool containsNegativeTime = false; foreach (var p in _subtitle.Paragraphs) { if (p.StartTime.TotalMilliseconds < 0 || p.EndTime.TotalMilliseconds < 0) { containsNegativeTime = true; break; } } if (containsNegativeTime && !string.IsNullOrEmpty(_language.NegativeTimeWarning)) { if (MessageBox.Show(_language.NegativeTimeWarning, Title, MessageBoxButtons.YesNo) == DialogResult.No) return DialogResult.No; } if (File.Exists(_fileName)) { DateTime fileOnDisk = File.GetLastWriteTime(_fileName); if (_fileDateTime != fileOnDisk && _fileDateTime != new DateTime()) { if (MessageBox.Show(string.Format(_language.OverwriteModifiedFile, _fileName, fileOnDisk.ToShortDateString(), fileOnDisk.ToString("HH:mm:ss"), Environment.NewLine, _fileDateTime.ToShortDateString(), _fileDateTime.ToString("HH:mm:ss")), Title + " - " + _language.FileOnDiskModified, MessageBoxButtons.YesNo) == DialogResult.No) return DialogResult.No; } File.Delete(_fileName); } if (Control.ModifierKeys == (Keys.Control | Keys.Shift)) allText = allText.Replace("\r\n", "\n"); if (format.GetType() == typeof(ItunesTimedText)) { Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM TextWriter file = new StreamWriter(_fileName, false, outputEnc); // open file with encoding file.Write(allText); file.Close(); // save and close it } else if (currentEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml))) { Encoding outputEnc = new UTF8Encoding(false); // create encoding with no BOM TextWriter file = new StreamWriter(_fileName, false, outputEnc); // open file with encoding file.Write(allText); file.Close(); // save and close it } else { if (allText.Trim().Length == 0) { MessageBox.Show(string.Format(_language.UnableToSaveSubtitleX, _fileName) + Environment.NewLine + Environment.NewLine + "Subtitle seems to be empty - try to re-save if you're working on a valid subtitle!"); return DialogResult.Cancel; } File.WriteAllText(_fileName, allText, currentEncoding); } _fileDateTime = File.GetLastWriteTime(_fileName); ShowStatus(string.Format(_language.SavedSubtitleX, _fileName)); _changeSubtitleToString = SerializeSubtitle(_subtitle); return DialogResult.OK; } catch (Exception exception) { MessageBox.Show(string.Format(_language.UnableToSaveSubtitleX, _fileName)); System.Diagnostics.Debug.Write(exception.Message); return DialogResult.Cancel; } }
private void ImportAndOcrDost(string fileName, SubtitleFormat format, List<string> list) { var sub = new Subtitle(); format.LoadSubtitle(sub, list, fileName); sub.FileName = fileName; var formSubOcr = new VobSubOcr(); _formPositionsAndSizes.SetPositionAndSize(formSubOcr); formSubOcr.Initialize(sub, Configuration.Settings.VobSubOcr, false); if (formSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingBdnXml); FileNew(); _subtitle.Paragraphs.Clear(); SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle.WasLoadedWithFrameNumbers = false; _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); foreach (Paragraph p in formSubOcr.SubtitleFromOcr.Paragraphs) { _subtitle.Paragraphs.Add(p); } ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = Path.ChangeExtension(formSubOcr.FileName, ".srt"); SetTitle(); _converted = true; } _formPositionsAndSizes.SavePositionAndSize(formSubOcr); }