public void SrtCoordinates()
        {
            var target = new SubRip();
            var subtitle = new Subtitle();
            const string text = @"1
00:00:02,001 --> 00:00:16,001  X1:000 X2:000 Y1:050 Y2:100
Let us have some! Let us have some!";
            target.LoadSubtitle(subtitle, GetSrtLines(text), null);
            string actual = subtitle.Paragraphs[0].Text;
            const string expected = "Let us have some! Let us have some!";
            Assert.AreEqual(expected, actual);
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            var data = new SubRip().ToText(subtitle, title);

            data = data.Replace("\t", " ");
            var encodedData = Json.EncodeJsonText(data);

            encodedData = encodedData.Replace("<br />", "\\n");

            var sb = new StringBuilder();

            sb.AppendLine("{");
            sb.AppendLine($"  \"data\": {{ \"websrt\" : \"{encodedData}\" }} ");
            sb.AppendLine("}");
            return(sb.ToString().Trim());
        }
        private void buttonTrain_Click(object sender, EventArgs e)
        {
            if (!File.Exists(textBoxInputFile.Text))
            {
                return;
            }

            int numberOfCharactersLeaned = 0;
            int numberOfCharactersSkipped = 0;
            var nOcrD = new NOcrDb(textBoxNOcrDb.Text);
            var lines = new List<string>();
            foreach (string line in File.ReadAllLines(textBoxInputFile.Text))
                lines.Add(line);
            var format = new SubRip();
            var sub = new Subtitle();
            format.LoadSubtitle(sub, lines, textBoxInputFile.Text);

            var charactersLearned = new List<string>();
            foreach (ListViewItem item in listViewFonts.Items)
            {
                if (item.Checked)
                {
                    _subtitleFontName = item.Text;
                    _subtitleFontSize = Convert.ToInt32(comboBoxSubtitleFontSize.Items[comboBoxSubtitleFontSize.SelectedIndex].ToString());
                    charactersLearned = new List<string>();

                    foreach (Paragraph p in sub.Paragraphs)
                    {
                        foreach (char ch in p.Text)
                        {
                            if (!char.IsWhiteSpace(ch))
                            {
                                var s = ch.ToString();
                                if (!charactersLearned.Contains(s))
                                {
                                    TrainLetter(ref numberOfCharactersLeaned, ref numberOfCharactersSkipped, nOcrD, charactersLearned, s, false);
                                    if (checkBoxBold.Checked)
                                        TrainLetter(ref numberOfCharactersLeaned, ref numberOfCharactersSkipped, nOcrD, charactersLearned, s, true);
                                }
                            }
                        }
                    }
                }
            }
            nOcrD.Save();
        }
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            _errorCount = 0;

            var sb = new StringBuilder();

            foreach (string s in lines)
            {
                sb.Append(s);
            }

            string allText        = sb.ToString();
            var    indexOfMainTag = allText.IndexOf("\"websrt\"", StringComparison.Ordinal);

            if (indexOfMainTag < 0 && !allText.Contains("\"data\""))
            {
                return;
            }

            var startIndex = allText.IndexOf('{');

            if (startIndex < 0)
            {
                return;
            }

            var json         = allText.Substring(startIndex);
            var parser       = new SeJsonParser();
            var subtitleData = parser.GetFirstObject(json, "websrt");

            if (string.IsNullOrEmpty(subtitleData))
            {
                return;
            }

            var format    = new SubRip();
            var innerJson = Json.DecodeJsonText(subtitleData);

            format.LoadSubtitle(subtitle, innerJson.SplitToLines(), null);
        }
Example #5
0
        private Subtitle LoadMatroskaSubtitleForSync(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska)
        {
            var subtitle = new Subtitle();
            bool isSsa = false;

            if (matroskaSubtitleInfo.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase))
            {
                return subtitle;
            }
            if (matroskaSubtitleInfo.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase))
            {
                return subtitle;
            }

            SubtitleFormat format;
            if (matroskaSubtitleInfo.CodecPrivate.Contains("[script info]", StringComparison.OrdinalIgnoreCase))
            {
                if (matroskaSubtitleInfo.CodecPrivate.Contains("[V4 Styles]", StringComparison.OrdinalIgnoreCase))
                    format = new SubStationAlpha();
                else
                    format = new AdvancedSubStationAlpha();
                isSsa = true;
            }
            else
            {
                format = new SubRip();
            }

            var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, MatroskaProgress);
            TaskbarList.SetProgressState(Handle, TaskbarButtonProgressFlags.NoProgress);
            if (isSsa)
            {
                foreach (var p in Utilities.LoadMatroskaSSA(matroskaSubtitleInfo, matroska.Path, format, sub).Paragraphs)
                {
                    subtitle.Paragraphs.Add(p);
                }
            }
            else
            {
                foreach (var p in sub)
                {
                    subtitle.Paragraphs.Add(new Paragraph(p.Text, p.Start, p.End));
                }
            }
            return subtitle;
        }
Example #6
0
        private void toolStripMenuItemPasteSpecial_Click(object sender, EventArgs e)
        {
            string text = Clipboard.GetText();
            var tmp = new Subtitle();
            var format = new SubRip();
            var list = new List<string>(text.SplitToLines());
            format.LoadSubtitle(tmp, list, null);

            if (SubtitleListview1.SelectedItems.Count == 1 && text.Length > 0)
            {
                var form = new ColumnPaste(SubtitleListview1.IsAlternateTextColumnVisible && _subtitleAlternate != null && Configuration.Settings.General.AllowEditOfOriginalSubtitle, tmp.Paragraphs.Count == 0);
                if (form.ShowDialog(this) == DialogResult.OK)
                {
                    MakeHistoryForUndo(_language.BeforeColumnPaste);

                    if (tmp.Paragraphs.Count == 0)
                    {
                        foreach (var line in text.SplitToLines())
                            tmp.Paragraphs.Add(new Paragraph(0, 0, line));
                    }

                    int index = FirstSelectedIndex;

                    if (!form.PasteOverwrite)
                    {
                        for (int i = 0; i < tmp.Paragraphs.Count; i++)
                        {
                            if (form.PasteAll)
                            {
                                for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                                {
                                    _subtitle.Paragraphs[k + 1] = new Paragraph(_subtitle.Paragraphs[k]);
                                }
                                if (index + i < _subtitle.Paragraphs.Count)
                                    _subtitle.Paragraphs[index + i].Text = string.Empty;
                            }
                            else if (form.PasteTimeCodesOnly)
                            {
                                for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                                {
                                    _subtitle.Paragraphs[k + 1].StartTime.TotalMilliseconds = _subtitle.Paragraphs[k].StartTime.TotalMilliseconds;
                                    _subtitle.Paragraphs[k + 1].EndTime.TotalMilliseconds = _subtitle.Paragraphs[k].EndTime.TotalMilliseconds;
                                    _subtitle.Paragraphs[k + 1].StartFrame = _subtitle.Paragraphs[k].StartFrame;
                                    _subtitle.Paragraphs[k + 1].EndFrame = _subtitle.Paragraphs[k].EndFrame;
                                }
                            }
                            else if (form.PasteTextOnly)
                            {
                                for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                                {
                                    _subtitle.Paragraphs[k + 1].Text = _subtitle.Paragraphs[k].Text;
                                }
                            }
                            else if (form.PasteOriginalTextOnly)
                            {
                                for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                                {
                                    var original = Utilities.GetOriginalParagraph(index, _subtitle.Paragraphs[k], _subtitleAlternate.Paragraphs);
                                    var originalNext = Utilities.GetOriginalParagraph(index, _subtitle.Paragraphs[k + 1], _subtitleAlternate.Paragraphs);
                                    if (original != null)
                                    {
                                        originalNext.Text = original.Text;
                                    }
                                }
                                if (index + i < _subtitle.Paragraphs.Count)
                                {
                                    var original = Utilities.GetOriginalParagraph(index, _subtitle.Paragraphs[index + i], _subtitleAlternate.Paragraphs);
                                    if (original != null)
                                        original.Text = string.Empty;
                                }
                            }
                        }
                    }
                    if (form.PasteOverwrite)
                    {
                        for (int i = 0; i + index < _subtitle.Paragraphs.Count && i < tmp.Paragraphs.Count; i++)
                            _subtitle.Paragraphs[index + i].Text = tmp.Paragraphs[i].Text;
                    }
                    else
                    {
                        for (int i = 0; i + index < _subtitle.Paragraphs.Count && i < tmp.Paragraphs.Count; i++)
                        {
                            if (index + i + 1 < _subtitle.Paragraphs.Count)
                                _subtitle.Paragraphs[index + i + 1].Text = tmp.Paragraphs[i].Text;
                        }
                    }

                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                    RefreshSelectedParagraph();
                }
                form.Dispose();
            }
        }
Example #7
0
        private void SubtitleListview1KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control) //Ctrl+c = Copy to clipboard
            {
                var tmp = new Subtitle();
                foreach (int i in SubtitleListview1.SelectedIndices)
                {
                    var p = _subtitle.GetParagraphOrDefault(i);
                    if (p != null)
                        tmp.Paragraphs.Add(new Paragraph(p));
                }
                if (tmp.Paragraphs.Count > 0)
                {
                    Clipboard.SetText(tmp.ToText(new SubRip()));
                }
                e.SuppressKeyPress = true;
            }
            else if (e.KeyData == _mainListViewCopyText)
            {
                var sb = new StringBuilder();
                foreach (int i in SubtitleListview1.SelectedIndices)
                {
                    var p = _subtitle.GetParagraphOrDefault(i);
                    if (p != null)
                        sb.AppendLine(p.Text + Environment.NewLine);
                }
                if (sb.Length > 0)
                {
                    Clipboard.SetText(sb.ToString().Trim());
                }
                e.SuppressKeyPress = true;
            }
            else if (e.KeyData == _mainListViewAutoDuration)
            {
                MakeAutoDurationSelectedLines();
            }
            else if (e.KeyData == _mainListViewFocusWaveform)
            {
                if (audioVisualizer.CanFocus)
                {
                    audioVisualizer.Focus();
                    e.SuppressKeyPress = true;
                }
            }
            else if (e.KeyData == _mainListViewGoToNextError)
            {
                GoToNextSynaxError();
                e.SuppressKeyPress = true;
            }
            else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) //Ctrl+vPaste from clipboard
            {
                if (Clipboard.ContainsText())
                {
                    var text = Clipboard.GetText();
                    var tmp = new Subtitle();
                    var format = new SubRip();
                    var list = new List<string>(text.SplitToLines());
                    format.LoadSubtitle(tmp, list, null);
                    if (SubtitleListview1.SelectedItems.Count == 1 && tmp.Paragraphs.Count > 0)
                    {
                        MakeHistoryForUndo(_language.BeforeInsertLine);
                        _makeHistoryPaused = true;
                        Paragraph lastParagraph = null;
                        Paragraph lastTempParagraph = null;
                        foreach (var p in tmp.Paragraphs)
                        {
                            InsertAfter();
                            textBoxListViewText.Text = p.Text;
                            if (lastParagraph != null)
                            {
                                double millisecondsBetween = p.StartTime.TotalMilliseconds - lastTempParagraph.EndTime.TotalMilliseconds;
                                timeUpDownStartTime.TimeCode = new TimeCode(lastParagraph.EndTime.TotalMilliseconds + millisecondsBetween);
                            }
                            SetDurationInSeconds(p.Duration.TotalSeconds);
                            lastParagraph = _subtitle.GetParagraphOrDefault(_subtitleListViewIndex);
                            lastTempParagraph = p;
                        }
                        RestartHistory();
                    }
                    else if (SubtitleListview1.Items.Count == 0 && tmp.Paragraphs.Count > 0)
                    { // insert into empty subtitle
                        MakeHistoryForUndo(_language.BeforeInsertLine);
                        foreach (var p in tmp.Paragraphs)
                        {
                            _subtitle.Paragraphs.Add(p);
                        }
                        SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                        SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                    }
                    else if (SubtitleListview1.Items.Count > 1 && tmp.Paragraphs.Count > 0)
                    {
                        // multiple lines selected - first delete, then insert
                        int firstIndex = FirstSelectedIndex;
                        if (firstIndex >= 0)
                        {
                            MakeHistoryForUndo(_language.BeforeInsertLine);
                            _makeHistoryPaused = true;

                            DeleteSelectedLines();
                            foreach (var p in tmp.Paragraphs)
                            {
                                _subtitle.Paragraphs.Insert(firstIndex, p);
                                firstIndex++;
                            }
                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                            SubtitleListview1.SelectIndexAndEnsureVisible(0, true);

                            RestartHistory();
                        }
                    }
                    else if (list.Count >= 1 && list.Count < 4)
                    {
                        // less than 4 lines of text, just insert into first selected
                        textBoxListViewText.Text = text.Trim();
                    }
                    else if (list.Count > 1 && list.Count < 2000)
                    {
                        MakeHistoryForUndo(_language.BeforeInsertLine);
                        _makeHistoryPaused = true;
                        foreach (var line in list)
                        {
                            if (!string.IsNullOrWhiteSpace(line))
                            {
                                InsertAfter();
                                textBoxListViewText.Text = Utilities.AutoBreakLine(line);
                            }
                        }
                        RestartHistory();
                    }
                }
                e.SuppressKeyPress = true;
            }
            else if (e.KeyCode == Keys.X && e.Modifiers == Keys.Control) //Ctrl+X = Cut to clipboard
            {
                var tmp = new Subtitle();
                foreach (int i in SubtitleListview1.SelectedIndices)
                {
                    var p = _subtitle.GetParagraphOrDefault(i);
                    if (p != null)
                        tmp.Paragraphs.Add(new Paragraph(p));
                }
                e.SuppressKeyPress = true;
                _cutText = tmp.ToText(new SubRip());
                ToolStripMenuItemDeleteClick(null, null);
            }
            else if (e.KeyCode == Keys.A && e.Modifiers == Keys.Control) //SelectAll
            {
                foreach (ListViewItem item in SubtitleListview1.Items)
                    item.Selected = true;
                e.SuppressKeyPress = true;
            }
            else if (e.KeyCode == Keys.D && e.Modifiers == Keys.Control) //SelectFirstSelectedItemOnly
            {
                if (SubtitleListview1.SelectedItems.Count > 0)
                {
                    bool skipFirst = true;
                    foreach (ListViewItem item in SubtitleListview1.SelectedItems)
                    {
                        if (skipFirst)
                            skipFirst = false;
                        else
                            item.Selected = false;
                    }
                    e.SuppressKeyPress = true;
                }
            }
            else if (e.KeyCode == Keys.Delete && SubtitleListview1.SelectedItems.Count > 0) //Delete
            {
                ToolStripMenuItemDeleteClick(null, null);
            }
            else if (e.KeyData == _mainInsertBefore)
            {
                InsertBefore();
                e.SuppressKeyPress = true;
            }
            else if (e.KeyData == _mainInsertAfter)
            {
                InsertAfter();
                e.SuppressKeyPress = true;
            }
            else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Home)
            {
                SubtitleListview1.FirstVisibleIndex = -1;
                SubtitleListview1.SelectIndexAndEnsureVisible(0, true);
                e.SuppressKeyPress = true;
            }
            else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.End)
            {
                SubtitleListview1.SelectIndexAndEnsureVisible(SubtitleListview1.Items.Count - 1, true);
                e.SuppressKeyPress = true;
            }
            else if (e.Modifiers == Keys.None && e.KeyCode == Keys.Enter)
            {
                SubtitleListview1_MouseDoubleClick(null, null);
            }
        }
        public void SrtNoLineNumbers()
        {
            var target = new SubRip();
            var subtitle = new Subtitle();
            const string text = @"00:00:03,000 --> 00:00:08,000
Line1.

00:00:08,000 --> 00:00:09,920
Line 2.";
            target.LoadSubtitle(subtitle, GetSrtLines(text), null);
            string actual = subtitle.Paragraphs.Count.ToString(CultureInfo.InvariantCulture);
            const string expected = "2";
            Assert.AreEqual(expected, actual);
        }
        public void SrtKeepBlankLines()
        {
            var target = new SubRip();
            var subtitle = new Subtitle();
            string subText = "Now go on!" + Environment.NewLine + Environment.NewLine + "Now go on!";
            subtitle.Paragraphs.Add(new Paragraph(subText, 0, 999));
            var text = target.ToText(subtitle, "title");

            var outSubtitle = new Subtitle();
            target.LoadSubtitle(outSubtitle, text.SplitToLines().ToList(), null);
            Assert.IsTrue(outSubtitle.Paragraphs[0].Text == subText);
        }
        public void SrtThreeLiner()
        {
            var target = new SubRip();
            var subtitle = new Subtitle();
            const string text = @"2
00:00:04.501 --> 00:00:08.500
Line 1
Line 2
Line 3";
            target.LoadSubtitle(subtitle, GetSrtLines(text), null);
            string actual = subtitle.Paragraphs[0].Text;
            string expected = "Line 1" + Environment.NewLine + "Line 2" + Environment.NewLine + "Line 3";
            Assert.AreEqual(expected, actual);
        }
        public void SrtDotsInsteadOfCommas()
        {
            var target = new SubRip();
            var subtitle = new Subtitle();
            const string text = @"2
00:00:04.501 --> 00:00:08.500
Dots instead of commas";
            target.LoadSubtitle(subtitle, GetSrtLines(text), null);
            string actual = subtitle.Paragraphs[0].Text;
            const string expected = "Dots instead of commas";
            Assert.AreEqual(expected, actual);
        }
Example #12
0
        public static SubtitleFormat LoadMatroskaTextSubtitle(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska, List<MatroskaSubtitle> sub, Subtitle subtitle)
        {
            if (subtitle == null)
                throw new ArgumentNullException("subtitle");
            subtitle.Paragraphs.Clear();

            var isSsa = false;
            SubtitleFormat format = new SubRip();
            if (matroskaSubtitleInfo.CodecPrivate.Contains("[script info]", StringComparison.OrdinalIgnoreCase))
            {
                if (matroskaSubtitleInfo.CodecPrivate.Contains("[V4 Styles]", StringComparison.OrdinalIgnoreCase))
                    format = new SubStationAlpha();
                else
                    format = new AdvancedSubStationAlpha();
                isSsa = true;
            }

            if (isSsa)
            {
                foreach (var p in LoadMatroskaSSA(matroskaSubtitleInfo, matroska.Path, format, sub).Paragraphs)
                {
                    subtitle.Paragraphs.Add(p);
                }

                if (!string.IsNullOrEmpty(matroskaSubtitleInfo.CodecPrivate))
                {
                    bool eventsStarted = false;
                    bool fontsStarted = false;
                    bool graphicsStarted = false;
                    var header = new StringBuilder();
                    foreach (string line in matroskaSubtitleInfo.CodecPrivate.Replace(Environment.NewLine, "\n").Split('\n'))
                    {
                        if (!eventsStarted && !fontsStarted && !graphicsStarted)
                        {
                            header.AppendLine(line);
                        }

                        if (line.TrimStart().StartsWith("dialog:", StringComparison.OrdinalIgnoreCase))
                        {
                            eventsStarted = true;
                            fontsStarted = false;
                            graphicsStarted = false;
                        }
                        else if (line.Trim().Equals("[events]", StringComparison.OrdinalIgnoreCase))
                        {
                            eventsStarted = true;
                            fontsStarted = false;
                            graphicsStarted = false;
                        }
                        else if (line.Trim().Equals("[fonts]", StringComparison.OrdinalIgnoreCase))
                        {
                            eventsStarted = false;
                            fontsStarted = true;
                            graphicsStarted = false;
                        }
                        else if (line.Trim().Equals("[graphics]", StringComparison.OrdinalIgnoreCase))
                        {
                            eventsStarted = false;
                            fontsStarted = false;
                            graphicsStarted = true;
                        }
                    }
                    subtitle.Header = header.ToString().TrimEnd();
                    if (!subtitle.Header.Contains("[events]", StringComparison.OrdinalIgnoreCase))
                    {
                        subtitle.Header += Environment.NewLine + Environment.NewLine + "[Events]" + Environment.NewLine;
                    }
                }
            }
            else
            {
                foreach (var p in sub)
                {
                    subtitle.Paragraphs.Add(new Paragraph(p.Text, p.Start, p.End));
                }
            }
            subtitle.Renumber();
            return format;
        }
Example #13
0
        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;
        }
Example #14
0
        private void SortAndLoad()
        {
            JoinedFormat = new SubRip(); // default subtitle format
            string header = null;
            SubtitleFormat lastFormat = null;
            var subtitles = new List<Subtitle>();
            for (int k = 0; k < _fileNamesToJoin.Count; k++)
            {
                string fileName = _fileNamesToJoin[k];
                try
                {
                    var sub = new Subtitle();
                    Encoding encoding;
                    var 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)
                    {
                        for (int j = k; j < _fileNamesToJoin.Count; j++)
                            _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 < _fileNamesToJoin.Count; j++)
                        _fileNamesToJoin.RemoveAt(j);
                    MessageBox.Show(exception.Message);
                    return;
                }
            }
            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 = _fileNamesToJoin[inner - 1];
                        _fileNamesToJoin[inner - 1] = _fileNamesToJoin[inner];
                        _fileNamesToJoin[inner] = t1;

                        var t2 = subtitles[inner - 1];
                        subtitles[inner - 1] = subtitles[inner];
                        subtitles[inner] = t2;
                    }
                }
            }

            listViewParts.BeginUpdate();
            listViewParts.Items.Clear();
            int i = 0;
            foreach (string fileName in _fileNamesToJoin)
            {
                var 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);
                listViewParts.Items.Add(lvi);
                i++;
            }
            listViewParts.EndUpdate();

            JoinedSubtitle = new Subtitle();
            if (JoinedFormat != null && JoinedFormat.FriendlyName != SubRip.NameOfFormat)
                JoinedSubtitle.Header = header;
            foreach (var sub in subtitles)
            {
                foreach (var p in sub.Paragraphs)
                {
                    JoinedSubtitle.Paragraphs.Add(p);
                }
            }
            JoinedSubtitle.Renumber();
            labelTotalLines.Text = string.Format(Configuration.Settings.Language.JoinSubtitles.TotalNumberOfLinesX, JoinedSubtitle.Paragraphs.Count);
        }