internal void Initialize(Bitmap bitmap, int pixelsIsSpace, bool rightToLeft, NOcrDb nOcrDb, VobSubOcr vobSubOcr) { _bitmap = bitmap; var nbmp = new NikseBitmap(bitmap); nbmp.ReplaceNonWhiteWithTransparent(); bitmap = nbmp.GetBitmap(); _bitmap2 = bitmap; _nocrChars = nOcrDb.OcrCharacters; _matchList = new List<VobSubOcr.CompareMatch>(); _vobSubOcr = vobSubOcr; int minLineHeight = 6; _imageList = NikseBitmapImageSplitter.SplitBitmapToLettersNew(nbmp, pixelsIsSpace, rightToLeft, Configuration.Settings.VobSubOcr.TopToBottom, minLineHeight); // _imageList = NikseBitmapImageSplitter.SplitBitmapToLetters(nbmp, pixelsIsSpace, rightToLeft, Configuration.Settings.VobSubOcr.TopToBottom); int index = 0; while (index < _imageList.Count) { ImageSplitterItem item = _imageList[index]; if (item.NikseBitmap == null) { listBoxInspectItems.Items.Add(item.SpecialCharacter); _matchList.Add(null); } else { nbmp = item.NikseBitmap; nbmp.ReplaceNonWhiteWithTransparent(); item.Y += nbmp.CropTopTransparent(0); nbmp.CropTransparentSidesAndBottom(0, true); nbmp.ReplaceTransparentWith(Color.Black); //get nocr matches Nikse.SubtitleEdit.Forms.VobSubOcr.CompareMatch match = vobSubOcr.GetNOcrCompareMatchNew(item, nbmp, nOcrDb, false, false); if (match == null) { listBoxInspectItems.Items.Add("?"); _matchList.Add(null); } else { listBoxInspectItems.Items.Add(match.Text); _matchList.Add(match); } } index++; } }
internal void Initialize(Bitmap vobSubImage, ImageSplitterItem character, Point position, bool italicChecked, bool showShrink, VobSubOcr.CompareMatch bestGuess, List<VobSubOcr.ImageCompareAddition> additions, VobSubOcr vobSubForm) { NikseBitmap nbmp = new NikseBitmap(vobSubImage); nbmp.ReplaceTransparentWith(Color.Black); vobSubImage = nbmp.GetBitmap(); radioButtonHot.Checked = true; ShrinkSelection = false; ExpandSelection = false; textBoxCharacters.Text = string.Empty; _vobSubForm = vobSubForm; _additions = additions; _nocrChar = new NOcrChar(); _nocrChar.MarginTop = character.Y - character.ParentY; _imageWidth = character.NikseBitmap.Width; _imageHeight = character.NikseBitmap.Height; _drawLineOn = false; _warningNoNotForegroundLinesShown = false; buttonShrinkSelection.Visible = showShrink; if (position.X != -1 && position.Y != -1) { StartPosition = FormStartPosition.Manual; Left = position.X; Top = position.Y; } pictureBoxSubtitleImage.Image = vobSubImage; pictureBoxCharacter.Image = character.NikseBitmap.GetBitmap(); Bitmap org = (Bitmap)vobSubImage.Clone(); Bitmap bm = new Bitmap(org.Width, org.Height); Graphics g = Graphics.FromImage(bm); g.DrawImage(org, 0, 0, org.Width, org.Height); g.DrawRectangle(Pens.Red, character.X, character.Y, character.NikseBitmap.Width, character.NikseBitmap.Height - 1); g.Dispose(); pictureBoxSubtitleImage.Image = bm; pictureBoxCharacter.Top = labelCharacters.Top + 16; SizePictureBox(); checkBoxItalic.Checked = italicChecked; _history = new List<NOcrChar>(); _historyIndex = -1; }
/// <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; }
private bool LoadDvbFromMatroska(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska, bool batchMode) { ShowStatus(_language.ParsingMatroskaFile); Refresh(); Cursor.Current = Cursors.WaitCursor; var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress); TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress); Cursor.Current = Cursors.Default; MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile); _subtitleListViewIndex = -1; if (!batchMode) ResetSubtitle(); _subtitle.Paragraphs.Clear(); var subtitleImages = new List<DvbSubPes>(); var subtitle = new Subtitle(); Utilities.LoadMatroskaTextSubtitle(matroskaSubtitleInfo, matroska, sub, _subtitle); for (int index = 0; index < sub.Count; index++) { try { var msub = sub[index]; DvbSubPes pes = null; if (msub.Data.Length > 9 && msub.Data[0] == 15 && msub.Data[1] >= SubtitleSegment.PageCompositionSegment && msub.Data[1] <= SubtitleSegment.DisplayDefinitionSegment) // sync byte + segment id { var buffer = new byte[msub.Data.Length + 3]; Buffer.BlockCopy(msub.Data, 0, buffer, 2, msub.Data.Length); buffer[0] = 32; buffer[1] = 0; buffer[buffer.Length - 1] = 255; pes = new DvbSubPes(0, buffer); } else if (VobSubParser.IsMpeg2PackHeader(msub.Data)) { pes = new DvbSubPes(msub.Data, Mpeg2Header.Length); } else if (VobSubParser.IsPrivateStream1(msub.Data, 0)) { pes = new DvbSubPes(msub.Data, 0); } else if (msub.Data.Length > 9 && msub.Data[0] == 32 && msub.Data[1] == 0 && msub.Data[2] == 14 && msub.Data[3] == 16) { pes = new DvbSubPes(0, msub.Data); } if (pes == null && subtitle.Paragraphs.Count > 0) { var last = subtitle.Paragraphs[subtitle.Paragraphs.Count - 1]; if (last.Duration.TotalMilliseconds < 100) { last.EndTime.TotalMilliseconds = msub.Start; if (last.Duration.TotalMilliseconds > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds) { last.EndTime.TotalMilliseconds = last.StartTime.TotalMilliseconds + 3000; } } } if (pes != null && pes.PageCompositions != null && pes.PageCompositions.Any(p => p.Regions.Count > 0)) { subtitleImages.Add(pes); subtitle.Paragraphs.Add(new Paragraph(string.Empty, msub.Start, msub.End)); } } catch { // continue } } if (subtitleImages.Count == 0) { return false; } for (int index = 0; index < subtitle.Paragraphs.Count; index++) { var p = subtitle.Paragraphs[index]; if (p.Duration.TotalMilliseconds < 200) { p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + 3000; } var next = subtitle.GetParagraphOrDefault(index + 1); if (next != null && next.StartTime.TotalMilliseconds < p.EndTime.TotalMilliseconds) { p.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines; } } using (var formSubOcr = new VobSubOcr()) { formSubOcr.Initialize(subtitle, subtitleImages, Configuration.Settings.VobSubOcr, null); // TODO: language??? if (_loading) { formSubOcr.Icon = (Icon)Icon.Clone(); formSubOcr.ShowInTaskbar = true; formSubOcr.ShowIcon = true; } if (formSubOcr.ShowDialog(this) == DialogResult.OK) { ResetSubtitle(); _subtitle.Paragraphs.Clear(); _subtitle.WasLoadedWithFrameNumbers = false; foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs) _subtitle.Paragraphs.Add(p); ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = Path.GetFileNameWithoutExtension(matroska.Path); _converted = true; Text = Title; Configuration.Settings.Save(); return true; } } return false; }
private void LoadMp4Subtitle(string fileName, Trak mp4SubtitleTrack) { if (mp4SubtitleTrack.Mdia.IsVobSubSubtitle) { var subPicturesWithTimeCodes = new List<VobSubOcr.SubPicturesWithSeparateTimeCodes>(); for (int i = 0; i < mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes.Count; i++) { if (mp4SubtitleTrack.Mdia.Minf.Stbl.SubPictures.Count > i) { var start = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.StartTimeCodes[i]); var end = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes[i]); subPicturesWithTimeCodes.Add(new VobSubOcr.SubPicturesWithSeparateTimeCodes(mp4SubtitleTrack.Mdia.Minf.Stbl.SubPictures[i], start, end)); } } using (var formSubOcr = new VobSubOcr()) { formSubOcr.Initialize(subPicturesWithTimeCodes, Configuration.Settings.VobSubOcr, fileName); // TODO: language??? if (formSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile); _subtitleListViewIndex = -1; FileNew(); _subtitle.WasLoadedWithFrameNumbers = false; foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs) _subtitle.Paragraphs.Add(p); ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = Path.GetFileNameWithoutExtension(fileName); _converted = true; Text = Title; Configuration.Settings.Save(); } } } else { MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile); _subtitleListViewIndex = -1; FileNew(); for (int i = 0; i < mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes.Count; i++) { if (mp4SubtitleTrack.Mdia.Minf.Stbl.Texts.Count > i) { var start = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.StartTimeCodes[i]); var end = TimeSpan.FromSeconds(mp4SubtitleTrack.Mdia.Minf.Stbl.EndTimeCodes[i]); string text = mp4SubtitleTrack.Mdia.Minf.Stbl.Texts[i]; var p = new Paragraph(text, start.TotalMilliseconds, end.TotalMilliseconds); if (p.EndTime.TotalMilliseconds - p.StartTime.TotalMilliseconds > Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds) p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds; if (mp4SubtitleTrack.Mdia.IsClosedCaption && string.IsNullOrEmpty(text)) { // do not add empty lines } else { _subtitle.Paragraphs.Add(p); } } } SetEncoding(Encoding.UTF8); ShowStatus(_language.SubtitleImportedFromMatroskaFile); _subtitle.Renumber(); _subtitle.WasLoadedWithFrameNumbers = false; if (fileName.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase) || fileName.EndsWith(".m4v", StringComparison.OrdinalIgnoreCase)) { _fileName = fileName.Substring(0, fileName.Length - 4); Text = Title + " - " + _fileName; } else { Text = Title; } _fileDateTime = new DateTime(); _converted = true; SubtitleListview1.Fill(_subtitle, _subtitleAlternate); if (_subtitle.Paragraphs.Count > 0) SubtitleListview1.SelectIndexAndEnsureVisible(0); ShowSource(); } }
private bool ImportSubtitleFromTransportStream(string fileName) { ShowStatus(_language.ParsingTransportStream); Refresh(); var tsParser = new TransportStreamParser(); tsParser.Parse(fileName, (pos, total) => UpdateProgress(pos, total, _language.ParsingTransportStreamFile)); ShowStatus(string.Empty); TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress); if (tsParser.SubtitlePacketIds.Count == 0) { MessageBox.Show(_language.NoSubtitlesFound); return false; } int packedId = tsParser.SubtitlePacketIds[0]; if (tsParser.SubtitlePacketIds.Count > 1) { using (var subChooser = new TransportStreamSubtitleChooser()) { subChooser.Initialize(tsParser, fileName); if (subChooser.ShowDialog(this) == DialogResult.Cancel) return false; packedId = tsParser.SubtitlePacketIds[subChooser.SelectedIndex]; } } var subtitles = tsParser.GetDvbSubtitles(packedId); using (var formSubOcr = new VobSubOcr()) { formSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName); if (formSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle); _subtitle.Paragraphs.Clear(); SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle.WasLoadedWithFrameNumbers = false; _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs) { _subtitle.Paragraphs.Add(p); } ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = string.Empty; Text = Title; Configuration.Settings.Save(); return true; } return false; } }
private bool LoadBluRaySubFromMatroska(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska) { if (matroskaSubtitleInfo.ContentEncodingType == 1) { MessageBox.Show(_language.NoSupportEncryptedVobSub); } ShowStatus(_language.ParsingMatroskaFile); Refresh(); Cursor.Current = Cursors.WaitCursor; var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress); TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress); Cursor.Current = Cursors.Default; int noOfErrors = 0; string lastError = string.Empty; MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile); _subtitleListViewIndex = -1; _subtitle.Paragraphs.Clear(); var subtitles = new List<BluRaySupParser.PcsData>(); var log = new StringBuilder(); foreach (var p in sub) { byte[] buffer = null; if (matroskaSubtitleInfo.ContentEncodingType == 0) // compressed with zlib { var outStream = new MemoryStream(); var outZStream = new zlib.ZOutputStream(outStream); var inStream = new MemoryStream(p.Data); try { CopyStream(inStream, outZStream); buffer = new byte[outZStream.TotalOut]; outStream.Position = 0; outStream.Read(buffer, 0, buffer.Length); } catch (Exception exception) { var tc = new TimeCode(p.Start); lastError = tc + ": " + exception.Message + ": " + exception.StackTrace; noOfErrors++; } finally { outZStream.Close(); inStream.Close(); } } else { buffer = p.Data; } if (buffer != null && buffer.Length > 100) { var ms = new MemoryStream(buffer); var list = BluRaySupParser.ParseBluRaySup(ms, log, true); foreach (var sup in list) { sup.StartTime = (long)((p.Start - 1) * 90.0); sup.EndTime = (long)((p.End - 1) * 90.0); subtitles.Add(sup); // fix overlapping if (subtitles.Count > 1 && sub[subtitles.Count - 2].End > sub[subtitles.Count - 1].Start) subtitles[subtitles.Count - 2].EndTime = subtitles[subtitles.Count - 1].StartTime - 1; } ms.Close(); } else if (subtitles.Count > 0) { var lastSub = subtitles[subtitles.Count - 1]; if (lastSub.StartTime == lastSub.EndTime) { lastSub.EndTime = (long)((p.Start - 1) * 90.0); if (lastSub.EndTime - lastSub.StartTime > 1000000) lastSub.EndTime = lastSub.StartTime; } } } if (noOfErrors > 0) { MessageBox.Show(string.Format("{0} error(s) occurred during extraction of bdsup\r\n\r\n{1}", noOfErrors, lastError)); } using (var formSubOcr = new VobSubOcr()) { formSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, matroska.Path); if (_loading) { formSubOcr.Icon = (Icon)Icon.Clone(); formSubOcr.ShowInTaskbar = true; formSubOcr.ShowIcon = true; } if (formSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle); _subtitle.Paragraphs.Clear(); SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle.WasLoadedWithFrameNumbers = false; _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs) { _subtitle.Paragraphs.Add(p); } ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = string.Empty; Text = Title; Configuration.Settings.Save(); return true; } } return false; }
private void ImportAndOcrSrt(Subtitle subtitle) { using (var formSubOcr = new VobSubOcr()) { formSubOcr.Initialize(subtitle, 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 (var 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; } } }
private void ToolStripMenuItemImportDvdSubtitlesClick(object sender, EventArgs e) { if (!ContinueNewOrExit()) { return; } using (var formSubRip = new DvdSubRip(Handle)) { if (formSubRip.ShowDialog(this) == DialogResult.OK) { using (var showSubtitles = new DvdSubRipChooseLanguage()) { showSubtitles.Initialize(formSubRip.MergedVobSubPacks, formSubRip.Palette, formSubRip.Languages, formSubRip.SelectedLanguage); if (formSubRip.Languages.Count == 1 || showSubtitles.ShowDialog(this) == DialogResult.OK) { using (var formSubOcr = new VobSubOcr()) { var subs = formSubRip.MergedVobSubPacks; if (showSubtitles.SelectedVobSubMergedPacks != null) subs = showSubtitles.SelectedVobSubMergedPacks; formSubOcr.Initialize(subs, formSubRip.Palette, Configuration.Settings.VobSubOcr, formSubRip.SelectedLanguage); if (formSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle); FileNew(); _subtitle.Paragraphs.Clear(); SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle.WasLoadedWithFrameNumbers = false; _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs) { _subtitle.Paragraphs.Add(p); } ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0, true); _fileName = string.Empty; Text = Title; Configuration.Settings.Save(); } } } } } } }
internal void Initialize(Bitmap vobSubImage, ImageSplitterItem character, Point position, bool italicChecked, bool showShrink, VobSubOcr.CompareMatch bestGuess, List<VobSubOcr.ImageCompareAddition> additions, VobSubOcr vobSubForm) { ShrinkSelection = false; ExpandSelection = false; textBoxCharacters.Text = string.Empty; if (bestGuess != null) { buttonGuess.Visible = false; // hm... not too useful :( buttonGuess.Text = bestGuess.Text; } else { buttonGuess.Visible = false; } _vobSubForm = vobSubForm; _additions = additions; buttonShrinkSelection.Visible = showShrink; checkBoxItalic.Checked = italicChecked; if (position.X != -1 && position.Y != -1) { StartPosition = FormStartPosition.Manual; Left = position.X; Top = position.Y; } pictureBoxSubtitleImage.Image = vobSubImage; pictureBoxCharacter.Image = character.NikseBitmap.GetBitmap(); if (_additions.Count > 0) { var last = _additions[_additions.Count - 1]; buttonLastEdit.Visible = true; if (last.Italic) buttonLastEdit.Font = new System.Drawing.Font(buttonLastEdit.Font.FontFamily, buttonLastEdit.Font.Size, FontStyle.Italic); else buttonLastEdit.Font = new System.Drawing.Font(buttonLastEdit.Font.FontFamily, buttonLastEdit.Font.Size); pictureBoxLastEdit.Visible = true; pictureBoxLastEdit.Image = last.Image.GetBitmap(); buttonLastEdit.Text = string.Format(Configuration.Settings.Language.VobSubOcrCharacter.EditLastX, last.Text); pictureBoxLastEdit.Top = buttonLastEdit.Top - last.Image.Height + buttonLastEdit.Height; } else { buttonLastEdit.Visible = false; pictureBoxLastEdit.Visible = false; } Bitmap org = (Bitmap)vobSubImage.Clone(); Bitmap bm = new Bitmap(org.Width, org.Height); Graphics g = Graphics.FromImage(bm); g.DrawImage(org, 0, 0, org.Width, org.Height); g.DrawRectangle(Pens.Red, character.X, character.Y, character.NikseBitmap.Width, character.NikseBitmap.Height - 1); g.Dispose(); pictureBoxSubtitleImage.Image = bm; pictureBoxCharacter.Top = labelCharacters.Top + 16; pictureBoxLastEdit.Left = buttonLastEdit.Left + buttonLastEdit.Width + 5; }
private void ImportAndOcrSon(string fileName, Son format, List<string> list) { using (var formSubOcr = new VobSubOcr()) { var sub = new Subtitle(); format.LoadSubtitle(sub, list, fileName); sub.FileName = fileName; formSubOcr.Initialize(sub, Configuration.Settings.VobSubOcr, true); if (formSubOcr.ShowDialog(this) == DialogResult.OK) { this.MakeHistoryForUndo(this._language.BeforeImportingBdnXml); this.FileNew(); this._subtitle.Paragraphs.Clear(); this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); this._subtitle.WasLoadedWithFrameNumbers = false; this._subtitle.CalculateFrameNumbersFromTimeCodes(this.CurrentFrameRate); foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs) { this._subtitle.Paragraphs.Add(p); } this.ShowSource(); this.SubtitleListview1.Fill(this._subtitle, this._subtitleAlternate); this._subtitleListViewIndex = -1; this.SubtitleListview1.FirstVisibleIndex = -1; this.SubtitleListview1.SelectIndexAndEnsureVisible(0); this._fileName = Path.ChangeExtension(formSubOcr.FileName, ".srt"); this.SetTitle(); this._converted = true; } } }
private void buttonConvert_Click(object sender, EventArgs e) { if (listViewInputFiles.Items.Count == 0) { MessageBox.Show(Configuration.Settings.Language.BatchConvert.NothingToConvert); return; } if (!checkBoxOverwriteOriginalFiles.Checked) { if (textBoxOutputFolder.Text.Length < 2) { MessageBox.Show(Configuration.Settings.Language.BatchConvert.PleaseChooseOutputFolder); return; } if (!Directory.Exists(textBoxOutputFolder.Text)) { try { Directory.CreateDirectory(textBoxOutputFolder.Text); } catch (Exception exception) { MessageBox.Show(exception.Message); return; } } } _converting = true; buttonConvert.Enabled = false; buttonCancel.Enabled = false; progressBar1.Style = ProgressBarStyle.Blocks; progressBar1.Maximum = listViewInputFiles.Items.Count; progressBar1.Value = 0; progressBar1.Visible = progressBar1.Maximum > 2; string toFormat = comboBoxSubtitleFormats.Text; groupBoxOutput.Enabled = false; groupBoxConvertOptions.Enabled = false; buttonInputBrowse.Enabled = false; buttonSearchFolder.Enabled = false; comboBoxFilter.Enabled = false; textBoxFilter.Enabled = false; _count = 0; _converted = 0; _errors = 0; _abort = false; var worker1 = new BackgroundWorker(); var worker2 = new BackgroundWorker(); var worker3 = new BackgroundWorker(); worker1.DoWork += DoThreadWork; worker1.RunWorkerCompleted += ThreadWorkerCompleted; worker2.DoWork += DoThreadWork; worker2.RunWorkerCompleted += ThreadWorkerCompleted; worker3.DoWork += DoThreadWork; worker3.RunWorkerCompleted += ThreadWorkerCompleted; listViewInputFiles.BeginUpdate(); foreach (ListViewItem item in listViewInputFiles.Items) item.SubItems[3].Text = "-"; listViewInputFiles.EndUpdate(); Refresh(); int index = 0; while (index < listViewInputFiles.Items.Count && _abort == false) { ListViewItem item = listViewInputFiles.Items[index]; string fileName = item.Text; try { SubtitleFormat format = null; var sub = new Subtitle(); var fi = new FileInfo(fileName); if (fi.Length < 1024 * 1024) // max 1 mb { Encoding encoding; format = sub.LoadSubtitle(fileName, out encoding, null); if (format == null) { var ebu = new Ebu(); if (ebu.IsMine(null, fileName)) { ebu.LoadSubtitle(sub, null, fileName); format = ebu; } } if (format == null) { var pac = new Pac(); if (pac.IsMine(null, fileName)) { pac.BatchMode = true; pac.LoadSubtitle(sub, null, fileName); format = pac; } } if (format == null) { var cavena890 = new Cavena890(); if (cavena890.IsMine(null, fileName)) { cavena890.LoadSubtitle(sub, null, fileName); format = cavena890; } } if (format == null) { var spt = new Spt(); if (spt.IsMine(null, fileName)) { spt.LoadSubtitle(sub, null, fileName); format = spt; } } if (format == null) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.IsMine(null, fileName)) { cheetahCaption.LoadSubtitle(sub, null, fileName); format = cheetahCaption; } } if (format == null) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.IsMine(null, fileName)) { capMakerPlus.LoadSubtitle(sub, null, fileName); format = capMakerPlus; } } if (format == null) { var captionate = new Captionate(); if (captionate.IsMine(null, fileName)) { captionate.LoadSubtitle(sub, null, fileName); format = captionate; } } if (format == null) { var ultech130 = new Ultech130(); if (ultech130.IsMine(null, fileName)) { ultech130.LoadSubtitle(sub, null, fileName); format = ultech130; } } if (format == null) { var nciCaption = new NciCaption(); if (nciCaption.IsMine(null, fileName)) { nciCaption.LoadSubtitle(sub, null, fileName); format = nciCaption; } } if (format == null) { var avidStl = new AvidStl(); if (avidStl.IsMine(null, fileName)) { avidStl.LoadSubtitle(sub, null, fileName); format = avidStl; } } if (format == null) { var elr = new ELRStudioClosedCaption(); if (elr.IsMine(null, fileName)) { elr.LoadSubtitle(sub, null, fileName); format = elr; } } if (format == null) { var enc = LanguageAutoDetect.GetEncodingFromFile(fileName); var s = File.ReadAllText(fileName, enc); // check for RTF file if (fileName.EndsWith(".rtf", StringComparison.OrdinalIgnoreCase) && 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) { sub = genericParseSubtitle; format = new SubRip(); } } if (format != null && format.GetType() == typeof(MicroDvd)) { if (sub != null && sub.Paragraphs.Count > 0 && sub.Paragraphs[0].Duration.TotalMilliseconds < 1001) { if (sub.Paragraphs[0].Text.StartsWith("29.", StringComparison.Ordinal) || sub.Paragraphs[0].Text.StartsWith("23.", StringComparison.Ordinal) || sub.Paragraphs[0].Text.StartsWith("29,", StringComparison.Ordinal) || sub.Paragraphs[0].Text.StartsWith("23,", StringComparison.Ordinal) || sub.Paragraphs[0].Text == "24" || sub.Paragraphs[0].Text == "25" || sub.Paragraphs[0].Text == "30" || sub.Paragraphs[0].Text == "60") sub.Paragraphs.RemoveAt(0); } } } var bluRaySubtitles = new List<BluRaySupParser.PcsData>(); bool isVobSub = false; bool isMatroska = false; if (format == null && fileName.EndsWith(".sup", StringComparison.OrdinalIgnoreCase) && FileUtil.IsBluRaySup(fileName)) { var log = new StringBuilder(); bluRaySubtitles = BluRaySupParser.ParseBluRaySup(fileName, log); } else if (format == null && fileName.EndsWith(".sub", StringComparison.OrdinalIgnoreCase) && FileUtil.IsVobSub(fileName)) { isVobSub = true; } else if (format == null && (fileName.EndsWith(".mkv", StringComparison.OrdinalIgnoreCase) || fileName.EndsWith(".mks", StringComparison.OrdinalIgnoreCase)) && item.SubItems[2].Text.StartsWith("Matroska")) { isMatroska = true; } if (format == null && bluRaySubtitles.Count == 0 && !isVobSub && !isMatroska) { IncrementAndShowProgress(); } else { if (isMatroska && (Path.GetExtension(fileName).Equals(".mkv", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(fileName).Equals(".mks", StringComparison.OrdinalIgnoreCase))) { using (var matroska = new MatroskaFile(fileName)) { if (matroska.IsValid) { foreach (var track in matroska.GetTracks(true)) { if (track.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase)) { // TODO: Convert from VobSub image based format! } else if (track.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase)) { // TODO: Convert from Blu-ray image based format! } else if (track.CodecId.Equals("S_TEXT/UTF8", StringComparison.OrdinalIgnoreCase) || track.CodecId.Equals("S_TEXT/SSA", StringComparison.OrdinalIgnoreCase) || track.CodecId.Equals("S_TEXT/ASS", StringComparison.OrdinalIgnoreCase)) { var mkvSub = matroska.GetSubtitle(track.TrackNumber, null); Utilities.LoadMatroskaTextSubtitle(track, matroska, mkvSub, sub); break; } } } } } else if (bluRaySubtitles.Count > 0) { item.SubItems[3].Text = Configuration.Settings.Language.BatchConvert.Ocr; using (var vobSubOcr = new VobSubOcr()) { vobSubOcr.FileName = Path.GetFileName(fileName); vobSubOcr.InitializeBatch(bluRaySubtitles, Configuration.Settings.VobSubOcr, fileName); sub = vobSubOcr.SubtitleFromOcr; } } else if (isVobSub) { item.SubItems[3].Text = Configuration.Settings.Language.BatchConvert.Ocr; using (var vobSubOcr = new VobSubOcr()) { vobSubOcr.InitializeBatch(fileName, Configuration.Settings.VobSubOcr); sub = vobSubOcr.SubtitleFromOcr; } } if (comboBoxSubtitleFormats.Text == AdvancedSubStationAlpha.NameOfFormat && _assStyle != null) { sub.Header = _assStyle; } else if (comboBoxSubtitleFormats.Text == SubStationAlpha.NameOfFormat && _ssaStyle != null) { sub.Header = _ssaStyle; } bool skip = CheckSkipFilter(fileName, format, sub); if (skip) { item.SubItems[3].Text = Configuration.Settings.Language.BatchConvert.FilterSkipped; } else { foreach (Paragraph p in sub.Paragraphs) { if (checkBoxRemoveTextForHI.Checked) { p.Text = _removeTextForHearingImpaired.RemoveTextFromHearImpaired(p.Text); } if (checkBoxRemoveFormatting.Checked) { p.Text = HtmlUtil.RemoveHtmlTags(p.Text, true); } } sub.RemoveEmptyLines(); if (checkBoxFixCasing.Checked) { _changeCasing.FixCasing(sub, LanguageAutoDetect.AutoDetectGoogleLanguage(sub)); _changeCasingNames.Initialize(sub); _changeCasingNames.FixCasing(); } double fromFrameRate; double toFrameRate; if (double.TryParse(comboBoxFrameRateFrom.Text.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out fromFrameRate) && double.TryParse(comboBoxFrameRateTo.Text.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out toFrameRate)) { sub.ChangeFrameRate(fromFrameRate, toFrameRate); } if (timeUpDownAdjust.TimeCode.TotalMilliseconds > 0.00001) { var totalMilliseconds = timeUpDownAdjust.TimeCode.TotalMilliseconds; if (radioButtonShowEarlier.Checked) totalMilliseconds *= -1; sub.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(totalMilliseconds)); } while (worker1.IsBusy && worker2.IsBusy && worker3.IsBusy) { Application.DoEvents(); System.Threading.Thread.Sleep(100); } var parameter = new ThreadDoWorkParameter(checkBoxFixCommonErrors.Checked, checkBoxMultipleReplace.Checked, checkBoxSplitLongLines.Checked, checkBoxAutoBalance.Checked, checkBoxSetMinimumDisplayTimeBetweenSubs.Checked, item, sub, GetCurrentSubtitleFormat(), GetCurrentEncoding(), Configuration.Settings.Tools.BatchConvertLanguage, fileName, toFormat, format); if (!worker1.IsBusy) worker1.RunWorkerAsync(parameter); else if (!worker2.IsBusy) worker2.RunWorkerAsync(parameter); else if (!worker3.IsBusy) worker3.RunWorkerAsync(parameter); } } } catch { IncrementAndShowProgress(); } index++; } while (worker1.IsBusy || worker2.IsBusy || worker3.IsBusy) { try { Application.DoEvents(); } catch { } System.Threading.Thread.Sleep(100); } _converting = false; labelStatus.Text = string.Empty; progressBar1.Visible = false; TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress); buttonConvert.Enabled = true; buttonCancel.Enabled = true; groupBoxOutput.Enabled = true; groupBoxConvertOptions.Enabled = true; buttonInputBrowse.Enabled = true; buttonSearchFolder.Enabled = true; comboBoxFilter.Enabled = true; textBoxFilter.Enabled = true; }
internal void InitializeFromVobSubOcr(Subtitle subtitle, SubtitleFormat format, string exportType, string fileName, VobSubOcr vobSubOcr, string languageString) { _vobSubOcr = vobSubOcr; Initialize(subtitle, format, exportType, fileName, null); //set language if (!string.IsNullOrEmpty(languageString)) { if (languageString.Contains("(") && !languageString.StartsWith("(")) languageString = languageString.Substring(0, languageString.IndexOf("(", StringComparison.Ordinal) - 1).Trim(); for (int i = 0; i < comboBoxLanguage.Items.Count; i++) { string l = comboBoxLanguage.Items[i].ToString(); if (l == languageString && i < comboBoxLanguage.Items.Count) comboBoxLanguage.SelectedIndex = i; } } //Disable options not available when exporting existing images comboBoxSubtitleFont.Enabled = false; comboBoxSubtitleFontSize.Enabled = false; buttonColor.Visible = false; panelColor.Visible = false; checkBoxBold.Visible = false; checkBoxSimpleRender.Visible = false; comboBox3D.Enabled = false; numericUpDownDepth3D.Enabled = false; buttonBorderColor.Visible = false; panelBorderColor.Visible = false; labelBorderWidth.Visible = false; comboBoxBorderWidth.Visible = false; buttonShadowColor.Visible = false; panelShadowColor.Visible = false; labelShadowWidth.Visible = false; comboBoxShadowWidth.Visible = false; labelShadowTransparency.Visible = false; numericUpDownShadowTransparency.Visible = false; labelLineHeight.Visible = false; numericUpDownLineSpacing.Visible = false; }
private static void ConvertVobSubSubtitle(string fileName, string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList<SubtitleFormat> formats, bool overwrite, string pacCodePage, double? targetFrameRate) { var format = Utilities.GetSubtitleFormatByFriendlyName(toFormat) ?? new SubRip(); Console.WriteLine("Loading subtitles from file \"{0}\"", fileName); Subtitle sub; using (var vobSubOcr = new VobSubOcr()) { Console.WriteLine("Using OCR to extract subtitles"); vobSubOcr.InitializeBatch(fileName, Configuration.Settings.VobSubOcr); sub = vobSubOcr.SubtitleFromOcr; Console.WriteLine("Extracted subtitles from file \"{0}\"", fileName); } if (sub != null) { Console.WriteLine("Converted subtitle"); BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, overwrite, pacCodePage, targetFrameRate); } }
private static void ConvertBluRaySubtitle(string fileName, string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList<SubtitleFormat> formats, bool overwrite, string pacCodePage, double? targetFrameRate, bool removeTextForHi, bool fixCommonErrors, bool redoCasing) { SubtitleFormat format = Utilities.GetSubtitleFormatByFriendlyName(toFormat) ?? new SubRip(); var log = new StringBuilder(); Console.WriteLine("Loading subtitles from file \"{0}\"", fileName); var bluRaySubtitles = BluRaySupParser.ParseBluRaySup(fileName, log); Subtitle sub; using (var vobSubOcr = new VobSubOcr()) { Console.WriteLine("Using OCR to extract subtitles"); vobSubOcr.FileName = Path.GetFileName(fileName); vobSubOcr.InitializeBatch(bluRaySubtitles, Configuration.Settings.VobSubOcr, fileName); sub = vobSubOcr.SubtitleFromOcr; Console.WriteLine("Extracted subtitles from file \"{0}\"", fileName); } if (sub != null) { Console.WriteLine("Converted subtitle"); BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing); } }
private void ImportAndOcrSpDvdSup(string fileName, bool showInTaskbar) { var spList = new List<SpHeader>(); using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { var buffer = new byte[SpHeader.SpHeaderLength]; int bytesRead = fs.Read(buffer, 0, buffer.Length); var header = new SpHeader(buffer); while (header.Identifier == "SP" && bytesRead > 0 && header.NextBlockPosition > 4) { buffer = new byte[header.NextBlockPosition]; bytesRead = fs.Read(buffer, 0, buffer.Length); if (bytesRead == buffer.Length) { header.AddPicture(buffer); spList.Add(header); } buffer = new byte[SpHeader.SpHeaderLength]; bytesRead = fs.Read(buffer, 0, buffer.Length); header = new SpHeader(buffer); } } using (var vobSubOcr = new VobSubOcr()) { if (showInTaskbar) { vobSubOcr.Icon = (Icon)this.Icon.Clone(); vobSubOcr.ShowInTaskbar = true; vobSubOcr.ShowIcon = true; } vobSubOcr.Initialize(fileName, null, Configuration.Settings.VobSubOcr, spList); if (vobSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingVobSubFile); FileNew(); _subtitle.Paragraphs.Clear(); SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle.WasLoadedWithFrameNumbers = false; _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); foreach (var p in vobSubOcr.SubtitleFromOcr.Paragraphs) { _subtitle.Paragraphs.Add(p); } ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = Path.ChangeExtension(vobSubOcr.FileName, ".srt"); SetTitle(); _converted = true; Configuration.Settings.Save(); } } }
private void ImportAndOcrVobSubSubtitleNew(string fileName, bool showInTaskbar) { if (!IsVobSubFile(fileName, true)) { return; } using (var vobSubOcr = new VobSubOcr()) { if (showInTaskbar) { vobSubOcr.Icon = (Icon)this.Icon.Clone(); vobSubOcr.ShowInTaskbar = true; vobSubOcr.ShowIcon = true; } if (vobSubOcr.Initialize(fileName, Configuration.Settings.VobSubOcr, this) && vobSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingVobSubFile); FileNew(); _subtitle.Paragraphs.Clear(); SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle.WasLoadedWithFrameNumbers = false; _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); foreach (var p in vobSubOcr.SubtitleFromOcr.Paragraphs) { _subtitle.Paragraphs.Add(p); } ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = Path.ChangeExtension(vobSubOcr.FileName, ".srt"); SetTitle(); _converted = true; Configuration.Settings.Save(); } } }
private void ImportAndOcrBluRaySup(string fileName, bool showInTaskbar) { var log = new StringBuilder(); var subtitles = BluRaySupParser.ParseBluRaySup(fileName, log); if (subtitles.Count > 0) { var vobSubOcr = new VobSubOcr(); if (showInTaskbar) { vobSubOcr.Icon = (Icon)this.Icon.Clone(); vobSubOcr.ShowInTaskbar = true; vobSubOcr.ShowIcon = true; } _formPositionsAndSizes.SetPositionAndSize(vobSubOcr); vobSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName); vobSubOcr.FileName = Path.GetFileName(fileName); if (vobSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingBluRaySupFile); FileNew(); _subtitle.Paragraphs.Clear(); SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle.WasLoadedWithFrameNumbers = false; _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); foreach (Paragraph p in vobSubOcr.SubtitleFromOcr.Paragraphs) { _subtitle.Paragraphs.Add(p); } ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = Path.ChangeExtension(vobSubOcr.FileName, ".srt"); SetTitle(); _converted = true; Configuration.Settings.Save(); } _formPositionsAndSizes.SavePositionAndSize(vobSubOcr); } }
private void ImportAndOcrBluRaySup(string fileName, bool showInTaskbar) { var log = new StringBuilder(); var subtitles = BluRaySupParser.ParseBluRaySup(fileName, log); if (subtitles.Count == 0) { string msg = _language.BlurayNotSubtitlesFound + Environment.NewLine + Environment.NewLine + log.ToString(); if (msg.Length > 800) msg = msg.Substring(0, 800); MessageBox.Show(msg.Trim() + "..."); return; } using (var vobSubOcr = new VobSubOcr()) { if (showInTaskbar) { vobSubOcr.Icon = (Icon)Icon.Clone(); vobSubOcr.ShowInTaskbar = true; vobSubOcr.ShowIcon = true; } vobSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName); vobSubOcr.FileName = Path.GetFileName(fileName); if (vobSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingBluRaySupFile); FileNew(); _subtitle.Paragraphs.Clear(); SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle.WasLoadedWithFrameNumbers = false; _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); foreach (var p in vobSubOcr.SubtitleFromOcr.Paragraphs) { _subtitle.Paragraphs.Add(p); } ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = Path.ChangeExtension(vobSubOcr.FileName, ".srt"); SetTitle(); _converted = true; Configuration.Settings.Save(); } } }
private void ImportAndOcrSst(string fileName, SonicScenaristBitmaps format, List<string> list) { Subtitle sub = new Subtitle(); format.LoadSubtitle(sub, list, fileName); sub.FileName = fileName; var formSubOcr = new VobSubOcr(); _formPositionsAndSizes.SetPositionAndSize(formSubOcr); formSubOcr.Initialize(sub, Configuration.Settings.VobSubOcr, true); 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); }
private bool LoadVobSubFromMatroska(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska) { if (matroskaSubtitleInfo.ContentEncodingType == 1) { MessageBox.Show(_language.NoSupportEncryptedVobSub); } ShowStatus(_language.ParsingMatroskaFile); Refresh(); Cursor.Current = Cursors.WaitCursor; var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress); TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress); Cursor.Current = Cursors.Default; MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile); _subtitleListViewIndex = -1; _subtitle.Paragraphs.Clear(); List<VobSubMergedPack> mergedVobSubPacks = new List<VobSubMergedPack>(); var idx = new Core.VobSub.Idx(matroskaSubtitleInfo.CodecPrivate.SplitToLines()); foreach (var p in sub) { if (matroskaSubtitleInfo.ContentEncodingType == 0) // compressed with zlib { bool error = false; var outStream = new MemoryStream(); var outZStream = new zlib.ZOutputStream(outStream); var inStream = new MemoryStream(p.Data); byte[] buffer = null; try { CopyStream(inStream, outZStream); buffer = new byte[outZStream.TotalOut]; outStream.Position = 0; outStream.Read(buffer, 0, buffer.Length); } catch (Exception exception) { MessageBox.Show(exception.Message + Environment.NewLine + Environment.NewLine + exception.StackTrace); error = true; } finally { outZStream.Close(); inStream.Close(); } if (!error && buffer.Length > 2) mergedVobSubPacks.Add(new VobSubMergedPack(buffer, TimeSpan.FromMilliseconds(p.Start), 32, null)); } else { mergedVobSubPacks.Add(new VobSubMergedPack(p.Data, TimeSpan.FromMilliseconds(p.Start), 32, null)); } if (mergedVobSubPacks.Count > 0) mergedVobSubPacks[mergedVobSubPacks.Count - 1].EndTime = TimeSpan.FromMilliseconds(p.End); // fix overlapping (some versions of Handbrake makes overlapping time codes - thx Hawke) if (mergedVobSubPacks.Count > 1 && mergedVobSubPacks[mergedVobSubPacks.Count - 2].EndTime > mergedVobSubPacks[mergedVobSubPacks.Count - 1].StartTime) mergedVobSubPacks[mergedVobSubPacks.Count - 2].EndTime = TimeSpan.FromMilliseconds(mergedVobSubPacks[mergedVobSubPacks.Count - 1].StartTime.TotalMilliseconds - 1); } using (var formSubOcr = new VobSubOcr()) { formSubOcr.Initialize(mergedVobSubPacks, idx.Palette, Configuration.Settings.VobSubOcr, null); // TODO: language??? if (_loading) { formSubOcr.Icon = (Icon)Icon.Clone(); formSubOcr.ShowInTaskbar = true; formSubOcr.ShowIcon = true; } if (formSubOcr.ShowDialog(this) == DialogResult.OK) { ResetSubtitle(); _subtitle.Paragraphs.Clear(); _subtitle.WasLoadedWithFrameNumbers = false; foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs) _subtitle.Paragraphs.Add(p); ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = Path.GetFileNameWithoutExtension(matroska.Path); _converted = true; Text = Title; Configuration.Settings.Save(); return true; } } return false; }
private void LoadVobSubFromMatroska(MatroskaSubtitleInfo matroskaSubtitleInfo, string fileName) { if (matroskaSubtitleInfo.ContentEncodingType == 1) { MessageBox.Show("Encrypted vobsub content not supported"); } bool isValid; var matroska = new Matroska(); ShowStatus(_language.ParsingMatroskaFile); Refresh(); Cursor.Current = Cursors.WaitCursor; List<SubtitleSequence> sub = matroska.GetMatroskaSubtitle(fileName, (int)matroskaSubtitleInfo.TrackNumber, out isValid, MatroskaProgress); Cursor.Current = Cursors.Default; if (isValid) { MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile); _subtitleListViewIndex = -1; _subtitle.Paragraphs.Clear(); List<VobSubMergedPack> mergedVobSubPacks = new List<VobSubMergedPack>(); Nikse.SubtitleEdit.Logic.VobSub.Idx idx = new Logic.VobSub.Idx(matroskaSubtitleInfo.CodecPrivate.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); foreach (SubtitleSequence p in sub) { if (matroskaSubtitleInfo.ContentEncodingType == 0) // compressed with zlib { bool error = false; MemoryStream outStream = new MemoryStream(); ComponentAce.Compression.Libs.zlib.ZOutputStream outZStream = new ComponentAce.Compression.Libs.zlib.ZOutputStream(outStream); MemoryStream inStream = new MemoryStream(p.BinaryData); byte[] buffer = null; try { CopyStream(inStream, outZStream); buffer = new byte[outZStream.TotalOut]; outStream.Position = 0; outStream.Read(buffer, 0, buffer.Length); } catch (Exception exception) { MessageBox.Show(exception.Message + Environment.NewLine + Environment.NewLine + exception.StackTrace); error = true; } finally { outStream.Close(); outZStream.Close(); inStream.Close(); } if (!error) mergedVobSubPacks.Add(new VobSubMergedPack(buffer, TimeSpan.FromMilliseconds(p.StartMilliseconds), 32, null)); } else { mergedVobSubPacks.Add(new VobSubMergedPack(p.BinaryData, TimeSpan.FromMilliseconds(p.StartMilliseconds), 32, null)); } mergedVobSubPacks[mergedVobSubPacks.Count - 1].EndTime = TimeSpan.FromMilliseconds(p.EndMilliseconds); // fix overlapping (some versions of Handbrake makes overlapping time codes - thx Hawke) if (mergedVobSubPacks.Count > 1 && mergedVobSubPacks[mergedVobSubPacks.Count - 2].EndTime > mergedVobSubPacks[mergedVobSubPacks.Count - 1].StartTime) mergedVobSubPacks[mergedVobSubPacks.Count - 2].EndTime = TimeSpan.FromMilliseconds(mergedVobSubPacks[mergedVobSubPacks.Count - 1].StartTime.TotalMilliseconds - 1); } var formSubOcr = new VobSubOcr(); _formPositionsAndSizes.SetPositionAndSize(formSubOcr); formSubOcr.Initialize(mergedVobSubPacks, idx.Palette, Configuration.Settings.VobSubOcr, null); //TODO - language??? if (_loading) { formSubOcr.Icon = (Icon)this.Icon.Clone(); formSubOcr.ShowInTaskbar = true; formSubOcr.ShowIcon = true; } if (formSubOcr.ShowDialog(this) == DialogResult.OK) { ResetSubtitle(); _subtitle.Paragraphs.Clear(); _subtitle.WasLoadedWithFrameNumbers = false; 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.GetFileNameWithoutExtension(fileName); _converted = true; Text = Title; Configuration.Settings.Save(); } _formPositionsAndSizes.SavePositionAndSize(formSubOcr); } }
private void ImportSubtitleFromDvbSupFile(string fileName) { using (var formSubOcr = new VobSubOcr()) { var subtitles = TransportStreamParser.GetDvbSup(fileName); formSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName); if (formSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle); _subtitle.Paragraphs.Clear(); SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat); _subtitle.WasLoadedWithFrameNumbers = false; _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate); foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs) { _subtitle.Paragraphs.Add(p); } ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = string.Empty; Text = Title; Configuration.Settings.Save(); } } }
private void LoadBluRaySubFromMatroska(MatroskaSubtitleInfo matroskaSubtitleInfo, string fileName) { if (matroskaSubtitleInfo.ContentEncodingType == 1) { MessageBox.Show("Encrypted vobsub content not supported"); } bool isValid; var matroska = new Matroska(); ShowStatus(_language.ParsingMatroskaFile); Refresh(); Cursor.Current = Cursors.WaitCursor; List<SubtitleSequence> sub = matroska.GetMatroskaSubtitle(fileName, (int)matroskaSubtitleInfo.TrackNumber, out isValid, MatroskaProgress); Cursor.Current = Cursors.Default; int noOfErrors = 0; string lastError = string.Empty; if (isValid) { MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile); _subtitleListViewIndex = -1; _subtitle.Paragraphs.Clear(); var subtitles = new List<Nikse.SubtitleEdit.Logic.BluRaySup.BluRaySupParser.PcsData>(); StringBuilder log = new StringBuilder(); foreach (SubtitleSequence p in sub) { byte[] buffer = null; if (matroskaSubtitleInfo.ContentEncodingType == 0) // compressed with zlib { MemoryStream outStream = new MemoryStream(); ComponentAce.Compression.Libs.zlib.ZOutputStream outZStream = new ComponentAce.Compression.Libs.zlib.ZOutputStream(outStream); MemoryStream inStream = new MemoryStream(p.BinaryData); try { CopyStream(inStream, outZStream); buffer = new byte[outZStream.TotalOut]; outStream.Position = 0; outStream.Read(buffer, 0, buffer.Length); } catch (Exception exception) { TimeCode tc = new TimeCode(TimeSpan.FromMilliseconds(p.StartMilliseconds)); lastError = tc.ToString() + ": " + exception.Message + ": " + exception.StackTrace; noOfErrors++; } finally { outStream.Close(); outZStream.Close(); inStream.Close(); } } else { buffer = p.BinaryData; } if (buffer != null && buffer.Length > 100) { MemoryStream ms = new MemoryStream(buffer); var list = BluRaySupParser.ParseBluRaySup(ms, log, true); foreach (var sup in list) { sup.StartTime = (long)((p.StartMilliseconds - 45) * 90.0); sup.EndTime = (long)((p.EndMilliseconds - 45) * 90.0); subtitles.Add(sup); // fix overlapping if (subtitles.Count > 1 && sub[subtitles.Count - 2].EndMilliseconds > sub[subtitles.Count - 1].StartMilliseconds) subtitles[subtitles.Count - 2].EndTime = subtitles[subtitles.Count - 1].StartTime - 1; } ms.Close(); } } if (noOfErrors > 0) { MessageBox.Show(string.Format("{0} errror(s) occured during extraction of bdsup\r\n\r\n{1}", noOfErrors, lastError)); } var formSubOcr = new VobSubOcr(); _formPositionsAndSizes.SetPositionAndSize(formSubOcr); formSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName); if (_loading) { formSubOcr.Icon = (Icon)this.Icon.Clone(); formSubOcr.ShowInTaskbar = true; formSubOcr.ShowIcon = true; } if (formSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle); _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 = string.Empty; Text = Title; Configuration.Settings.Save(); } _formPositionsAndSizes.SavePositionAndSize(formSubOcr); } }
private bool ImportSubtitleFromDivX(string fileName) { var count = 0; var list = new List<XSub>(); using (var f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var searchBuffer = new byte[2048]; long pos = 0; long length = f.Length - 50; while (pos < length) { f.Position = pos; int readCount = f.Read(searchBuffer, 0, searchBuffer.Length); for (int i = 0; i < readCount; i++) { if (searchBuffer[i] != 0x5b || (i + 4 < readCount && (searchBuffer[i + 1] < 0x30 || searchBuffer[i + 1] > 0x39 || searchBuffer[i + 3] != 0x3a))) { continue; } f.Position = pos + i + 1; var buffer = new byte[26]; f.Read(buffer, 0, buffer.Length); if (buffer[2] == 0x3a && // : buffer[5] == 0x3a && // : buffer[8] == 0x2e && // . buffer[12] == 0x2d && // - buffer[15] == 0x3a && // : buffer[18] == 0x3a && // : buffer[21] == 0x2e && // . buffer[25] == 0x5d) // ] { // subtitle time code string timeCode = Encoding.ASCII.GetString(buffer, 0, 25); f.Read(buffer, 0, 2); int width = BitConverter.ToUInt16(buffer, 0); f.Read(buffer, 0, 2); int height = BitConverter.ToUInt16(buffer, 0); f.Read(buffer, 0, 2); int x = BitConverter.ToUInt16(buffer, 0); f.Read(buffer, 0, 2); int y = BitConverter.ToUInt16(buffer, 0); f.Read(buffer, 0, 2); int xEnd = BitConverter.ToUInt16(buffer, 0); f.Read(buffer, 0, 2); int yEnd = BitConverter.ToUInt16(buffer, 0); f.Read(buffer, 0, 2); int RleLength = BitConverter.ToUInt16(buffer, 0); var colorBuffer = new byte[4 * 3]; // four colors with rgb (3 bytes) f.Read(colorBuffer, 0, colorBuffer.Length); buffer = new byte[RleLength]; int bytesRead = f.Read(buffer, 0, buffer.Length); if (width > 0 && height > 0 && bytesRead == buffer.Length) { var xSub = new XSub(timeCode, width, height, colorBuffer, buffer); list.Add(xSub); count++; } } } pos += searchBuffer.Length; } } if (count == 0) { return false; } using (var formSubOcr = new VobSubOcr()) { formSubOcr.Initialize(list, Configuration.Settings.VobSubOcr, fileName); // TODO: language??? if (formSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile); _subtitleListViewIndex = -1; FileNew(); _subtitle.WasLoadedWithFrameNumbers = false; foreach (var p in formSubOcr.SubtitleFromOcr.Paragraphs) _subtitle.Paragraphs.Add(p); ShowSource(); SubtitleListview1.Fill(_subtitle, _subtitleAlternate); _subtitleListViewIndex = -1; SubtitleListview1.FirstVisibleIndex = -1; SubtitleListview1.SelectIndexAndEnsureVisible(0); _fileName = Path.GetFileNameWithoutExtension(fileName); _converted = true; Text = Title; Configuration.Settings.Save(); OpenVideo(fileName); } } return true; }
private bool ImportSubtitleFromTransportStream(string fileName) { if (string.IsNullOrEmpty(_language.ParsingTransportStream)) ShowStatus("Parsing transport stream - please wait..."); else ShowStatus(_language.ParsingTransportStream); Refresh(); var tsParser = new Nikse.SubtitleEdit.Logic.TransportStream.TransportStreamParser(); tsParser.ParseTsFile(fileName); ShowStatus(string.Empty); if (tsParser.SubtitlePacketIds.Count == 0) { MessageBox.Show(_language.NoSubtitlesFound); return false; } int packedId = tsParser.SubtitlePacketIds[0]; if (tsParser.SubtitlePacketIds.Count > 1) { var subChooser = new TransportStreamSubtitleChooser(); _formPositionsAndSizes.SetPositionAndSize(subChooser); subChooser.Initialize(tsParser, fileName); if (subChooser.ShowDialog(this) == DialogResult.Cancel) return false; packedId = tsParser.SubtitlePacketIds[subChooser.SelectedIndex]; _formPositionsAndSizes.SavePositionAndSize(subChooser); } var subtitles = tsParser.GetDvbSubtitles(packedId); var formSubOcr = new VobSubOcr(); _formPositionsAndSizes.SetPositionAndSize(formSubOcr); formSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName); if (formSubOcr.ShowDialog(this) == DialogResult.OK) { MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle); _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 = string.Empty; Text = Title; Configuration.Settings.Save(); _formPositionsAndSizes.SavePositionAndSize(formSubOcr); return true; } _formPositionsAndSizes.SavePositionAndSize(formSubOcr); return false; }
private void buttonSaveAs_Click(object sender, EventArgs e) { if (listBox1.Items.Count > -1) { if (_languages != null && comboBoxLanguages.SelectedIndex >= 0 && comboBoxLanguages.SelectedIndex < _languages.Count) SelectedLanguageString = _languages[comboBoxLanguages.SelectedIndex]; else SelectedLanguageString = null; var subs = new List<VobSubMergedPack>(); foreach (var x in listBox1.Items) { subs.Add((x as SubListBoxItem).SubPack); } var formSubOcr = new VobSubOcr(); formSubOcr.InitializeQuick(subs, _palette, Configuration.Settings.VobSubOcr, SelectedLanguageString); var subtitle = formSubOcr.ReadyVobSubRip(); var exportBdnXmlPng = new ExportPngXml(); exportBdnXmlPng.InitializeFromVobSubOcr(subtitle, new Nikse.SubtitleEdit.Logic.SubtitleFormats.SubRip(), "VOBSUB", "DVD", formSubOcr, SelectedLanguageString); exportBdnXmlPng.ShowDialog(this); } }
private void buttonConvert_Click(object sender, EventArgs e) { if (listViewInputFiles.Items.Count == 0) { MessageBox.Show(Configuration.Settings.Language.BatchConvert.NothingToConvert); return; } if (!checkBoxOverwriteOriginalFiles.Checked) { if (textBoxOutputFolder.Text.Length < 2) { MessageBox.Show(Configuration.Settings.Language.BatchConvert.PleaseChooseOutputFolder); return; } else if (!Directory.Exists(textBoxOutputFolder.Text)) { try { Directory.CreateDirectory(textBoxOutputFolder.Text); } catch (Exception exception) { MessageBox.Show(exception.Message); return; } } } _converting = true; buttonConvert.Enabled = false; buttonCancel.Enabled = false; progressBar1.Style = ProgressBarStyle.Blocks; progressBar1.Maximum = listViewInputFiles.Items.Count; progressBar1.Value = 0; progressBar1.Visible = progressBar1.Maximum > 2; string toFormat = comboBoxSubtitleFormats.Text; groupBoxOutput.Enabled = false; groupBoxConvertOptions.Enabled = false; buttonInputBrowse.Enabled = false; buttonSearchFolder.Enabled = false; _count = 0; _converted = 0; _errors = 0; _abort = false; BackgroundWorker worker1 = new BackgroundWorker(); BackgroundWorker worker2 = new BackgroundWorker(); BackgroundWorker worker3 = new BackgroundWorker(); worker1.DoWork += DoThreadWork; worker1.RunWorkerCompleted += ThreadWorkerCompleted; worker2.DoWork += DoThreadWork; worker2.RunWorkerCompleted += ThreadWorkerCompleted; worker3.DoWork += DoThreadWork; worker3.RunWorkerCompleted += ThreadWorkerCompleted; listViewInputFiles.BeginUpdate(); foreach (ListViewItem item in listViewInputFiles.Items) item.SubItems[3].Text = "-"; listViewInputFiles.EndUpdate(); Refresh(); int index = 0; while (index < listViewInputFiles.Items.Count && _abort == false) { ListViewItem item = listViewInputFiles.Items[index]; string fileName = item.Text; try { SubtitleFormat format = null; Encoding encoding; var sub = new Subtitle(); var fi = new FileInfo(fileName); if (fi.Length < 1024 * 1024) // max 1 mb { format = sub.LoadSubtitle(fileName, out encoding, null); if (format == null) { var ebu = new Ebu(); if (ebu.IsMine(null, fileName)) { ebu.LoadSubtitle(sub, null, fileName); format = ebu; } } if (format == null) { var pac = new Pac(); if (pac.IsMine(null, fileName)) { pac.LoadSubtitle(sub, null, fileName); format = pac; } } if (format == null) { var cavena890 = new Cavena890(); if (cavena890.IsMine(null, fileName)) { cavena890.LoadSubtitle(sub, null, fileName); format = cavena890; } } if (format == null) { var spt = new Spt(); if (spt.IsMine(null, fileName)) { spt.LoadSubtitle(sub, null, fileName); format = spt; } } if (format == null) { var cheetahCaption = new CheetahCaption(); if (cheetahCaption.IsMine(null, fileName)) { cheetahCaption.LoadSubtitle(sub, null, fileName); format = cheetahCaption; } } if (format == null) { var capMakerPlus = new CapMakerPlus(); if (capMakerPlus.IsMine(null, fileName)) { capMakerPlus.LoadSubtitle(sub, null, fileName); format = capMakerPlus; } } if (format == null) { var captionate = new Captionate(); if (captionate.IsMine(null, fileName)) { captionate.LoadSubtitle(sub, null, fileName); format = captionate; } } if (format == null) { var ultech130 = new Ultech130(); if (ultech130.IsMine(null, fileName)) { ultech130.LoadSubtitle(sub, null, fileName); format = ultech130; } } if (format == null) { var nciCaption = new NciCaption(); if (nciCaption.IsMine(null, fileName)) { nciCaption.LoadSubtitle(sub, null, fileName); format = nciCaption; } } if (format == null) { var avidStl = new AvidStl(); if (avidStl.IsMine(null, fileName)) { avidStl.LoadSubtitle(sub, null, fileName); format = avidStl; } } if (format == null) { var elr = new ELRStudioClosedCaption(); if (elr.IsMine(null, fileName)) { elr.LoadSubtitle(sub, null, fileName); format = elr; } } if (format != null && format.GetType() == typeof(MicroDvd)) { if (sub != null && sub.Paragraphs.Count > 0 && sub.Paragraphs[0].Duration.TotalMilliseconds < 1001) { if (sub.Paragraphs[0].Text.StartsWith("29.") || sub.Paragraphs[0].Text.StartsWith("23.") || sub.Paragraphs[0].Text.StartsWith("29,") || sub.Paragraphs[0].Text.StartsWith("23,") || sub.Paragraphs[0].Text == "24" || sub.Paragraphs[0].Text == "25" || sub.Paragraphs[0].Text == "30" || sub.Paragraphs[0].Text == "60") sub.Paragraphs.RemoveAt(0); } } } var bluRaySubtitles = new List<BluRaySupParser.PcsData>(); bool isVobSub = false; bool isMatroska = false; if (format == null && fileName.ToLower().EndsWith(".sup") && Main.IsBluRaySupFile(fileName)) { var log = new StringBuilder(); bluRaySubtitles = BluRaySupParser.ParseBluRaySup(fileName, log); } else if (format == null && fileName.ToLower().EndsWith(".sub") && Main.HasVobSubHeader(fileName)) { isVobSub = true; } else if (format == null && fileName.ToLower().EndsWith(".mkv") && item.SubItems[2].Text.StartsWith("Matroska")) { isMatroska = true; } if (format == null && bluRaySubtitles.Count == 0 && !isVobSub && !isMatroska) { if (progressBar1.Value < progressBar1.Maximum) progressBar1.Value++; labelStatus.Text = progressBar1.Value + " / " + progressBar1.Maximum; } else { if (isMatroska) { if (Path.GetExtension(fileName).ToLower() == ".mkv" || Path.GetExtension(fileName).ToLower() == ".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) { var subtitleList = mkv.GetMatroskaSubtitleTracks(fileName, out isValid); if (subtitleList.Count > 0) { foreach (MatroskaSubtitleInfo x in subtitleList) { if (x.CodecId.ToUpper() == "S_VOBSUB") { //TODO: convert from VobSub image based format } else if (x.CodecId.ToUpper() == "S_HDMV/PGS") { //TODO: convert from Blu-ray image based format } else if (x.CodecId.ToUpper() == "S_TEXT/UTF8" || x.CodecId.ToUpper() == "S_TEXT/SSA" || x.CodecId.ToUpper() == "S_TEXT/ASS") { _matroskaListViewItem = item; List<SubtitleSequence> mkvSub = mkv.GetMatroskaSubtitle(fileName, (int)x.TrackNumber, out isValid, MatroskaProgress); bool isSsa = false; if (x.CodecPrivate.ToLower().Contains("[script info]")) { if (x.CodecPrivate.ToLower().Contains("[V4 Styles]".ToLower())) format = new SubStationAlpha(); else format = new AdvancedSubStationAlpha(); isSsa = true; } else { format = new SubRip(); } if (isSsa) { foreach (Paragraph p in Main.LoadMatroskaSSa(x, fileName, format, mkvSub).Paragraphs) { sub.Paragraphs.Add(p); } } else { foreach (SubtitleSequence p in mkvSub) { sub.Paragraphs.Add(new Paragraph(p.Text, p.StartMilliseconds, p.EndMilliseconds)); } } break; } } } } } } else if (bluRaySubtitles.Count > 0) { item.SubItems[3].Text = "OCR..."; var vobSubOcr = new VobSubOcr(); vobSubOcr.FileName = Path.GetFileName(fileName); vobSubOcr.InitializeBatch(bluRaySubtitles, Configuration.Settings.VobSubOcr, fileName); sub = vobSubOcr.SubtitleFromOcr; } else if (isVobSub) { item.SubItems[3].Text = "OCR..."; var vobSubOcr = new VobSubOcr(); vobSubOcr.InitializeBatch(fileName, Configuration.Settings.VobSubOcr, true); sub = vobSubOcr.SubtitleFromOcr; } if (comboBoxSubtitleFormats.Text == new AdvancedSubStationAlpha().Name && _assStyle != null) { sub.Header = _assStyle; } else if (comboBoxSubtitleFormats.Text == new SubStationAlpha().Name && _ssaStyle != null) { sub.Header = _ssaStyle; } int prevIndex = -1; foreach (Paragraph p in sub.Paragraphs) { string prevText = string.Empty; var prev = sub.GetParagraphOrDefault(prevIndex); if (prev != null) prevText = prev.Text; prevIndex++; if (checkBoxRemoveTextForHI.Checked) { p.Text = _removeForHI.RemoveTextFromHearImpaired(p.Text, prevText); } if (checkBoxRemoveFormatting.Checked) { p.Text = Utilities.RemoveHtmlTags(p.Text); if (p.Text.StartsWith("{") && p.Text.Length > 6 && p.Text[5] == '}') p.Text = p.Text.Remove(0, 6); if (p.Text.StartsWith("{") && p.Text.Length > 6 && p.Text[4] == '}') p.Text = p.Text.Remove(0, 5); } } if (checkBoxFixCasing.Checked) { _changeCasing.FixCasing(sub, Utilities.AutoDetectGoogleLanguage(sub)); _changeCasingNames.Initialize(sub); _changeCasingNames.FixCasing(); } double fromFrameRate; double toFrameRate; if (double.TryParse(comboBoxFrameRateFrom.Text, out fromFrameRate) && double.TryParse(comboBoxFrameRateTo.Text, out toFrameRate)) { sub.ChangeFramerate(fromFrameRate, toFrameRate); } if (timeUpDownAdjust.TimeCode.TotalMilliseconds > 0.00001) { var totalMilliseconds = timeUpDownAdjust.TimeCode.TotalMilliseconds; if (radioButtonShowEarlier.Checked) totalMilliseconds *= -1; sub.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(totalMilliseconds)); } while (worker1.IsBusy && worker2.IsBusy && worker3.IsBusy) { Application.DoEvents(); System.Threading.Thread.Sleep(100); } ThreadDoWorkParameter parameter = new ThreadDoWorkParameter(checkBoxFixCommonErrors.Checked, checkBoxMultipleReplace.Checked, checkBoxSplitLongLines.Checked, checkBoxAutoBalance.Checked, checkBoxSetMinimumDisplayTimeBetweenSubs.Checked, item, sub, GetCurrentSubtitleFormat(), GetCurrentEncoding(), Configuration.Settings.Tools.BatchConvertLanguage, fileName, toFormat, format); if (!worker1.IsBusy) worker1.RunWorkerAsync(parameter); else if (!worker2.IsBusy) worker2.RunWorkerAsync(parameter); else if (!worker3.IsBusy) worker3.RunWorkerAsync(parameter); } } catch { if (progressBar1.Value < progressBar1.Maximum) progressBar1.Value++; labelStatus.Text = progressBar1.Value + " / " + progressBar1.Maximum; } index++; } while (worker1.IsBusy || worker2.IsBusy || worker3.IsBusy) { try { Application.DoEvents(); } catch { } System.Threading.Thread.Sleep(100); } _converting = false; labelStatus.Text = string.Empty; progressBar1.Visible = false; buttonConvert.Enabled = true; buttonCancel.Enabled = true; groupBoxOutput.Enabled = true; groupBoxConvertOptions.Enabled = true; buttonInputBrowse.Enabled = true; buttonSearchFolder.Enabled = true; }