Ejemplo n.º 1
0
 public void MatroskaTestInvalid()
 {
     string fileName = Path.Combine(Directory.GetCurrentDirectory(), "sample_TS_with_graphics.ts");
     using (var parser = new MatroskaFile(fileName))
     {
         Assert.IsFalse(parser.IsValid);
     }
 }
Ejemplo n.º 2
0
 public void MatroskaTestValid()
 {
     string fileName = Path.Combine(Directory.GetCurrentDirectory(), "sample_MKV_SRT.mkv");
     using (var parser = new MatroskaFile(fileName))
     {
         Assert.IsTrue(parser.IsValid);
     }
 }
Ejemplo n.º 3
0
 public void MatroskaTestIsSrt()
 {
     string fileName = Path.Combine(Directory.GetCurrentDirectory(), "sample_MKV_SRT.mkv");
     using (var parser = new MatroskaFile(fileName))
     {
         var tracks = parser.GetTracks(true);
         Assert.IsTrue(tracks[0].CodecId == "S_TEXT/UTF8");
     }
 }
Ejemplo n.º 4
0
 public void MatroskaTestDelayed500Ms()
 {
     string fileName = Path.Combine(Directory.GetCurrentDirectory(), "sample_MKV_delayed.mkv");
     using (var parser = new MatroskaFile(fileName))
     {
         var delay = parser.GetTrackStartTime(parser.GetTracks()[0].TrackNumber);
         Assert.IsTrue(delay == 500);
     }
 }
Ejemplo n.º 5
0
 public void MatroskaTestVobSubPgs()
 {
     string fileName = Path.Combine(Directory.GetCurrentDirectory(), "sample_MKV_VobSub_PGS.mkv");
     using (var parser = new MatroskaFile(fileName))
     {
         var tracks = parser.GetTracks(true);
         Assert.IsTrue(tracks[0].CodecId == "S_VOBSUB");
         Assert.IsTrue(tracks[1].CodecId == "S_HDMV/PGS");
     }
 }
Ejemplo n.º 6
0
 public void MatroskaTestSrtContent()
 {
     string fileName = Path.Combine(Directory.GetCurrentDirectory(), "sample_MKV_SRT.mkv");
     using (var parser = new MatroskaFile(fileName))
     {
         var tracks = parser.GetTracks(true);
         var subtitles = parser.GetSubtitle(Convert.ToInt32(tracks[0].TrackNumber), null);
         Assert.IsTrue(subtitles.Count == 2);
         Assert.IsTrue(subtitles[0].Text == "Line 1");
         Assert.IsTrue(subtitles[1].Text == "Line 2");
     }
 }
        private static VideoInfo TryReadVideoInfoViaMatroskaHeader(string fileName)
        {
            var info = new VideoInfo { Success = false };

            MatroskaFile matroska = null;
            try
            {
                matroska = new MatroskaFile(fileName);
                if (matroska.IsValid)
                {
                    double frameRate;
                    int width;
                    int height;
                    double milliseconds;
                    string videoCodec;
                    matroska.GetInfo(out frameRate, out width, out height, out milliseconds, out videoCodec);

                    info.Width = width;
                    info.Height = height;
                    info.FramesPerSecond = frameRate;
                    info.Success = true;
                    info.TotalMilliseconds = milliseconds;
                    info.TotalSeconds = milliseconds / TimeCode.BaseUnit;
                    info.TotalFrames = info.TotalSeconds * frameRate;
                    info.VideoCodec = videoCodec;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (matroska != null)
                {
                    matroska.Dispose();
                }
            }

            return info;
        }
Ejemplo n.º 8
0
        private void ImportSubtitleFromMatroskaFile(string fileName)
        {
            using (var matroska = new MatroskaFile(fileName))
            {
                if (matroska.IsValid)
                {
                    var subtitleList = matroska.GetTracks(true);
                    if (subtitleList.Count == 0)
                    {
                        MessageBox.Show(this._language.NoSubtitlesFound);
                    }
                    else if (this.ContinueNewOrExit())
                    {
                        if (subtitleList.Count > 1)
                        {
                            using (var subtitleChooser = new MatroskaSubtitleChooser())
                            {
                                subtitleChooser.Initialize(subtitleList);
                                if (this._loading)
                                {
                                    subtitleChooser.Icon = (Icon)this.Icon.Clone();
                                    subtitleChooser.ShowInTaskbar = true;
                                    subtitleChooser.ShowIcon = true;
                                }

                                if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                {
                                    if (this.LoadMatroskaSubtitle(subtitleList[subtitleChooser.SelectedIndex], matroska, false) && Path.GetExtension(matroska.Path).Equals(".mkv", StringComparison.OrdinalIgnoreCase))
                                    {
                                        this.OpenVideo(matroska.Path);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (this.LoadMatroskaSubtitle(subtitleList[0], matroska, false) && Path.GetExtension(matroska.Path).Equals(".mkv", StringComparison.OrdinalIgnoreCase))
                            {
                                this.OpenVideo(matroska.Path);
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show(string.Format(this._language.NotAValidMatroskaFileX, fileName));
                }
            }
        }
Ejemplo n.º 9
0
        private void DoSubtitleListview1Drop(object sender, EventArgs e)
        {
            this._dragAndDropTimer.Stop();

            if (this.ContinueNewOrExit())
            {
                string fileName = this._dragAndDropFiles[0];

                var dirName = Path.GetDirectoryName(fileName);
                this.saveFileDialog1.InitialDirectory = dirName;
                this.openFileDialog1.InitialDirectory = dirName;

                var file = new FileInfo(fileName);

                // Do not allow directory drop
                if (FileUtil.IsDirectory(fileName))
                {
                    MessageBox.Show(this._language.ErrorDirectoryDropNotAllowed, file.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var ext = file.Extension.ToLowerInvariant();

                if (ext == ".mkv")
                {
                    using (var matroska = new MatroskaFile(fileName))
                    {
                        if (matroska.IsValid)
                        {
                            var subtitleList = matroska.GetTracks(true);
                            if (subtitleList.Count == 0)
                            {
                                MessageBox.Show(this._language.NoSubtitlesFound);
                            }
                            else if (subtitleList.Count > 1)
                            {
                                using (var subtitleChooser = new MatroskaSubtitleChooser())
                                {
                                    subtitleChooser.Initialize(subtitleList);
                                    if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                    {
                                        this.LoadMatroskaSubtitle(subtitleList[subtitleChooser.SelectedIndex], matroska, false);
                                    }
                                }
                            }
                            else
                            {
                                this.LoadMatroskaSubtitle(subtitleList[0], matroska, false);
                            }
                        }
                    }

                    return;
                }

                if (file.Length < 1024 * 1024 * 2)
                {
                    // max 2 mb
                    this.OpenSubtitle(fileName, null);
                }
                else if (file.Length < 150000000 && ext == ".sub" && this.IsVobSubFile(fileName, true))
                {
                    // max 150 mb
                    this.OpenSubtitle(fileName, null);
                }
                else if (file.Length < 250000000 && ext == ".sup" && FileUtil.IsBluRaySup(fileName))
                {
                    // max 250 mb
                    this.OpenSubtitle(fileName, null);
                }
                else if ((ext == ".ts" || ext == ".rec" || ext == ".mpg" || ext == ".mpeg") && FileUtil.IsTransportStream(fileName))
                {
                    this.OpenSubtitle(fileName, null);
                }
                else if (ext == ".m2ts" && FileUtil.IsM2TransportStream(fileName))
                {
                    this.OpenSubtitle(fileName, null);
                }
                else
                {
                    MessageBox.Show(string.Format(this._language.DropFileXNotAccepted, fileName));
                }
            }
        }
Ejemplo n.º 10
0
        private void pointSyncViaOtherSubtitleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var pointSync = new SyncPointsSync())
            {
                this.openFileDialog1.Title = this._language.OpenOtherSubtitle;
                this.openFileDialog1.FileName = string.Empty;
                this.openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
                if (this.openFileDialog1.ShowDialog() == DialogResult.OK && File.Exists(this.openFileDialog1.FileName))
                {
                    var sub = new Subtitle();
                    var file = new FileInfo(this.openFileDialog1.FileName);
                    var fileName = file.FullName;
                    var extension = file.Extension.ToLowerInvariant();

                    // TODO: Check for mkv etc
                    if (extension == ".sub")
                    {
                        if (this.IsVobSubFile(fileName, false))
                        {
                            MessageBox.Show(this._language.NoSupportHereVobSub);
                            return;
                        }
                    }

                    if (extension == ".sup")
                    {
                        if (FileUtil.IsBluRaySup(fileName))
                        {
                            MessageBox.Show(this._language.NoSupportHereBluRaySup);
                            return;
                        }
                        else if (FileUtil.IsSpDvdSup(fileName))
                        {
                            MessageBox.Show(this._language.NoSupportHereDvdSup);
                            return;
                        }
                    }

                    if (extension == ".mkv" || extension == ".mks")
                    {
                        using (var matroska = new MatroskaFile(fileName))
                        {
                            if (matroska.IsValid)
                            {
                                var subtitleList = matroska.GetTracks(true);
                                if (subtitleList.Count > 1)
                                {
                                    using (var subtitleChooser = new MatroskaSubtitleChooser())
                                    {
                                        subtitleChooser.Initialize(subtitleList);
                                        if (this._loading)
                                        {
                                            subtitleChooser.Icon = (Icon)this.Icon.Clone();
                                            subtitleChooser.ShowInTaskbar = true;
                                            subtitleChooser.ShowIcon = true;
                                        }

                                        if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                        {
                                            sub = this.LoadMatroskaSubtitleForSync(subtitleList[subtitleChooser.SelectedIndex], matroska);
                                        }
                                    }
                                }
                                else if (subtitleList.Count > 0)
                                {
                                    sub = this.LoadMatroskaSubtitleForSync(subtitleList[0], matroska);
                                }
                                else
                                {
                                    MessageBox.Show(this._language.NoSubtitlesFound);
                                    return;
                                }
                            }
                        }
                    }

                    if (extension == ".divx" || extension == ".avi")
                    {
                        MessageBox.Show(this._language.NoSupportHereDivx);
                        return;
                    }

                    if ((extension == ".mp4" || extension == ".m4v" || extension == ".3gp") && file.Length > 10000)
                    {
                        var mp4Parser = new MP4Parser(fileName);
                        var mp4SubtitleTracks = mp4Parser.GetSubtitleTracks();
                        if (mp4SubtitleTracks.Count == 0)
                        {
                            MessageBox.Show(this._language.NoSubtitlesFound);
                            return;
                        }
                        else if (mp4SubtitleTracks.Count == 1)
                        {
                            sub = LoadMp4SubtitleForSync(mp4SubtitleTracks[0]);
                        }
                        else
                        {
                            using (var subtitleChooser = new MatroskaSubtitleChooser())
                            {
                                subtitleChooser.Initialize(mp4SubtitleTracks);
                                if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                {
                                    sub = LoadMp4SubtitleForSync(mp4SubtitleTracks[0]);
                                }
                            }
                        }
                    }

                    if (file.Length > 1024 * 1024 * 10 && sub.Paragraphs.Count == 0)
                    {
                        // max 10 mb
                        var text = string.Format(this._language.FileXIsLargerThan10MB + Environment.NewLine + Environment.NewLine + this._language.ContinueAnyway, fileName);
                        if (MessageBox.Show(this, text, this.Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                        {
                            return;
                        }
                    }

                    sub.Renumber();
                    if (sub.Paragraphs.Count == 0)
                    {
                        Encoding enc;
                        SubtitleFormat f = sub.LoadSubtitle(fileName, out enc, null);
                        if (f == null)
                        {
                            this.ShowUnknownSubtitle();
                            return;
                        }
                    }

                    pointSync.Initialize(this._subtitle, this._fileName, this.VideoFileName, this._videoAudioTrackNumber, fileName, sub);
                    this.mediaPlayer.Pause();
                    if (pointSync.ShowDialog(this) == DialogResult.OK)
                    {
                        this._subtitleListViewIndex = -1;
                        this.MakeHistoryForUndo(this._language.BeforePointSynchronization);
                        this._subtitle.Paragraphs.Clear();
                        foreach (var p in pointSync.FixedSubtitle.Paragraphs)
                        {
                            this._subtitle.Paragraphs.Add(p);
                        }

                        this._subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(this.CurrentFrameRate);
                        this.ShowStatus(this._language.PointSynchronizationDone);
                        this.ShowSource();
                        this.SubtitleListview1.Fill(this._subtitle, this._subtitleAlternate);
                    }

                    this.VideoFileName = pointSync.VideoFileName;
                }
            }
        }
Ejemplo n.º 11
0
        private void OpenSubtitle(string fileName, Encoding encoding, string videoFileName, string originalFileName)
        {
            if (File.Exists(fileName))
            {
                bool videoFileLoaded = false;
                var file = new FileInfo(fileName);
                var ext = file.Extension.ToLowerInvariant();

                // save last first visible index + first selected index from listview
                if (!string.IsNullOrEmpty(this._fileName))
                {
                    Configuration.Settings.RecentFiles.Add(this._fileName, this.FirstVisibleIndex, this.FirstSelectedIndex, this.VideoFileName, originalFileName);
                }

                this.openFileDialog1.InitialDirectory = file.DirectoryName;

                if (ext == ".sub" && this.IsVobSubFile(fileName, false))
                {
                    if (MessageBox.Show(this, this._language.ImportThisVobSubSubtitle, this._title, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        this.ImportAndOcrVobSubSubtitleNew(fileName, this._loading);
                    }

                    return;
                }

                if (ext == ".sup")
                {
                    if (FileUtil.IsBluRaySup(fileName))
                    {
                        this.ImportAndOcrBluRaySup(fileName, this._loading);
                        return;
                    }
                    else if (FileUtil.IsSpDvdSup(fileName))
                    {
                        this.ImportAndOcrSpDvdSup(fileName, this._loading);
                        return;
                    }
                }

                if (ext == ".mkv" || ext == ".mks")
                {
                    this.ImportSubtitleFromMatroskaFile(fileName);
                    return;
                }

                if (ext == ".divx" || ext == ".avi")
                {
                    if (this.ImportSubtitleFromDivX(fileName))
                    {
                        return;
                    }
                }

                if ((ext == ".ts" || ext == ".rec" || ext == ".mpeg" || ext == ".mpg") && file.Length > 10000 && FileUtil.IsTransportStream(fileName))
                {
                    this.ImportSubtitleFromTransportStream(fileName);
                    return;
                }

                if ((ext == ".m2ts") && file.Length > 10000 && FileUtil.IsM2TransportStream(fileName))
                {
                    bool isTextSt = false;
                    if (file.Length < 2000000)
                    {
                        var textSt = new TextST();
                        isTextSt = textSt.IsMine(null, fileName);
                    }

                    if (!isTextSt)
                    {
                        this.ImportSubtitleFromTransportStream(fileName);
                        return;
                    }
                }

                if ((ext == ".mp4" || ext == ".m4v" || ext == ".3gp") && file.Length > 10000)
                {
                    if (this.ImportSubtitleFromMp4(fileName))
                    {
                        this.OpenVideo(fileName);
                    }

                    return;
                }

                if (ext == ".mxf")
                {
                    if (FileUtil.IsMaterialExchangeFormat(fileName))
                    {
                        var parser = new MxfParser(fileName);
                        if (parser.IsValid)
                        {
                            var subtitles = parser.GetSubtitles();
                            if (subtitles.Count > 0)
                            {
                                this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                                encoding = this.GetCurrentEncoding();
                                var list = new List<string>(subtitles[0].Replace(Environment.NewLine, "\r").Replace("\n", "\r").Split('\r'));
                                this._subtitle = new Subtitle();
                                var mxfFormat = this._subtitle.ReloadLoadSubtitle(list, null);
                                this.SetCurrentFormat(mxfFormat);
                                this._fileName = Path.GetFileNameWithoutExtension(fileName);
                                this.SetTitle();
                                this.ShowStatus(string.Format(this._language.LoadedSubtitleX, this._fileName));
                                this._sourceViewChange = false;
                                this._changeSubtitleToString = SerializeSubtitle(this._subtitle);
                                this.ResetHistory();
                                this.SetUndockedWindowsTitle();
                                this._converted = true;
                                this.ShowStatus(string.Format(this._language.LoadedSubtitleX, this._fileName) + " - " + string.Format(this._language.ConvertedToX, mxfFormat.FriendlyName));

                                this.ShowSource();
                                this.SubtitleListview1.Fill(this._subtitle, this._subtitleAlternate);
                                this._subtitleListViewIndex = -1;
                                this.SubtitleListview1.FirstVisibleIndex = -1;
                                this.SubtitleListview1.SelectIndexAndEnsureVisible(0);

                                return;
                            }

                            MessageBox.Show("No subtitles found!");
                            return;
                        }
                    }
                }

                if (file.Length > 1024 * 1024 * 10)
                {
                    // max 10 mb
                    // retry Blu-ray sup (file with wrong extension)
                    if (FileUtil.IsBluRaySup(fileName))
                    {
                        this.ImportAndOcrBluRaySup(fileName, this._loading);
                        return;
                    }

                    // retry vobsub (file with wrong extension)
                    if (this.IsVobSubFile(fileName, false))
                    {
                        if (MessageBox.Show(this, this._language.ImportThisVobSubSubtitle, this._title, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            this.ImportAndOcrVobSubSubtitleNew(fileName, this._loading);
                        }

                        return;
                    }

                    var text = string.Format(this._language.FileXIsLargerThan10MB + Environment.NewLine + Environment.NewLine + this._language.ContinueAnyway, fileName);
                    if (MessageBox.Show(this, text, this.Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                    {
                        return;
                    }
                }

                if (this._subtitle.HistoryItems.Count > 0 || this._subtitle.Paragraphs.Count > 0)
                {
                    this.MakeHistoryForUndo(string.Format(this._language.BeforeLoadOf, Path.GetFileName(fileName)));
                }

                bool change = this._changeSubtitleToString != SerializeSubtitle(this._subtitle);
                if (change)
                {
                    change = this._lastDoNotPrompt != SerializeSubtitle(this._subtitle);
                }

                SubtitleFormat format = this._subtitle.LoadSubtitle(fileName, out encoding, encoding);
                if (!change)
                {
                    this._changeSubtitleToString = SerializeSubtitle(this._subtitle);
                }

                this.ShowHideTextBasedFeatures(format);

                bool justConverted = false;
                if (format == null)
                {
                    var ebu = new Ebu();
                    if (ebu.IsMine(null, fileName))
                    {
                        ebu.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = ebu;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var pac = new Pac();
                    if (pac.IsMine(null, fileName))
                    {
                        pac.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = pac;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (ext == ".m2ts")
                {
                    var textST = new TextST();
                    if (textST.IsMine(null, fileName))
                    {
                        textST.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = textST;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var pns = new Pns();
                    if (pns.IsMine(null, fileName))
                    {
                        pns.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = pns;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var cavena890 = new Cavena890();
                    if (cavena890.IsMine(null, fileName))
                    {
                        cavena890.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = cavena890;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var spt = new Spt();
                    if (spt.IsMine(null, fileName))
                    {
                        spt.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = spt;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null && ext == ".wsb")
                {
                    var wsb = new Wsb();
                    var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)));
                    if (wsb.IsMine(list, fileName))
                    {
                        wsb.LoadSubtitle(this._subtitle, list, fileName);
                        this._oldSubtitleFormat = wsb;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var cheetahCaption = new CheetahCaption();
                    if (cheetahCaption.IsMine(null, fileName))
                    {
                        cheetahCaption.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = cheetahCaption;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var capMakerPlus = new CapMakerPlus();
                    if (capMakerPlus.IsMine(null, fileName))
                    {
                        capMakerPlus.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = capMakerPlus;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var captionsInc = new CaptionsInc();
                    if (captionsInc.IsMine(null, fileName))
                    {
                        captionsInc.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = captionsInc;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var ultech130 = new Ultech130();
                    if (ultech130.IsMine(null, fileName))
                    {
                        ultech130.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = ultech130;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var nciCaption = new NciCaption();
                    if (nciCaption.IsMine(null, fileName))
                    {
                        nciCaption.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = nciCaption;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var tsb4 = new TSB4();
                    if (tsb4.IsMine(null, fileName))
                    {
                        tsb4.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = tsb4;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var avidStl = new AvidStl();
                    if (avidStl.IsMine(null, fileName))
                    {
                        avidStl.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = avidStl;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var chk = new Chk();
                    if (chk.IsMine(null, fileName))
                    {
                        chk.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = chk;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var ayato = new Ayato();
                    if (ayato.IsMine(null, fileName))
                    {
                        ayato.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = ayato;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var pacUnicode = new PacUnicode();
                    if (pacUnicode.IsMine(null, fileName))
                    {
                        pacUnicode.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = pacUnicode;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    try
                    {
                        var bdnXml = new BdnXml();
                        var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)));
                        if (bdnXml.IsMine(list, fileName))
                        {
                            if (this.ContinueNewOrExit())
                            {
                                this.ImportAndOcrBdnXml(fileName, bdnXml, list);
                            }

                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                if (format == null)
                {
                    try
                    {
                        var fcpImage = new FinalCutProImage();
                        var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)));
                        if (fcpImage.IsMine(list, fileName))
                        {
                            if (this.ContinueNewOrExit())
                            {
                                this.ImportAndOcrDost(fileName, fcpImage, list);
                            }

                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                if (format == null)
                {
                    var elr = new ELRStudioClosedCaption();
                    if (elr.IsMine(null, fileName))
                    {
                        elr.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = elr;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var asc = new TimeLineAscii();
                    if (asc.IsMine(null, fileName))
                    {
                        asc.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = asc;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var asc = new TimeLineFootageAscii();
                    if (asc.IsMine(null, fileName))
                    {
                        asc.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = asc;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (format == null)
                {
                    var mtv = new TimeLineMvt();
                    if (mtv.IsMine(null, fileName))
                    {
                        mtv.LoadSubtitle(this._subtitle, null, fileName);
                        this._oldSubtitleFormat = mtv;
                        this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                        this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                        encoding = this.GetCurrentEncoding();
                        justConverted = true;
                        format = this.GetCurrentSubtitleFormat();
                    }
                }

                if (ext == ".dost")
                {
                    try
                    {
                        var dost = new Dost();
                        var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)));
                        if (dost.IsMine(list, fileName))
                        {
                            if (this.ContinueNewOrExit())
                            {
                                this.ImportAndOcrDost(fileName, dost, list);
                            }

                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                if (format == null || format.Name == Scenarist.NameOfFormat)
                {
                    try
                    {
                        var son = new Son();
                        var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)));
                        if (son.IsMine(list, fileName))
                        {
                            if (this.ContinueNewOrExit())
                            {
                                this.ImportAndOcrSon(fileName, son, list);
                            }

                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                if (format == null || format.Name == SubRip.NameOfFormat)
                {
                    if (this._subtitle.Paragraphs.Count > 1)
                    {
                        int imageCount = 0;
                        foreach (var p in this._subtitle.Paragraphs)
                        {
                            string s = p.Text.ToLowerInvariant();
                            if (s.EndsWith(".bmp", StringComparison.Ordinal) || s.EndsWith(".png", StringComparison.Ordinal) || s.EndsWith(".jpg", StringComparison.Ordinal) || s.EndsWith(".tif", StringComparison.Ordinal))
                            {
                                imageCount++;
                            }
                        }

                        if (imageCount > 2 && imageCount >= this._subtitle.Paragraphs.Count - 2)
                        {
                            if (this.ContinueNewOrExit())
                            {
                                this.ImportAndOcrSrt(this._subtitle);
                            }

                            return;
                        }
                    }
                }

                if (format == null)
                {
                    try
                    {
                        var satBoxPng = new SatBoxPng();
                        var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)));
                        if (satBoxPng.IsMine(list, fileName))
                        {
                            var subtitle = new Subtitle();
                            satBoxPng.LoadSubtitle(subtitle, list, fileName);
                            if (this.ContinueNewOrExit())
                            {
                                this.ImportAndOcrSrt(subtitle);
                            }

                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                if (format == null || format.Name == Scenarist.NameOfFormat)
                {
                    try
                    {
                        var sst = new SonicScenaristBitmaps();
                        var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)));
                        if (sst.IsMine(list, fileName))
                        {
                            if (this.ContinueNewOrExit())
                            {
                                this.ImportAndOcrSst(fileName, sst, list);
                            }

                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                if (format == null)
                {
                    try
                    {
                        var htmlSamiArray = new HtmlSamiArray();
                        var list = new List<string>(File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)));
                        if (htmlSamiArray.IsMine(list, fileName))
                        {
                            htmlSamiArray.LoadSubtitle(this._subtitle, list, fileName);
                            this._oldSubtitleFormat = htmlSamiArray;
                            this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = this.GetCurrentEncoding();
                            justConverted = true;
                            format = this.GetCurrentSubtitleFormat();
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                // retry vobsub (file with wrong extension)
                if (format == null && file.Length > 500 && this.IsVobSubFile(fileName, false))
                {
                    if (MessageBox.Show(this, this._language.ImportThisVobSubSubtitle, this._title, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        this.ImportAndOcrVobSubSubtitleNew(fileName, this._loading);
                    }

                    return;
                }

                // retry Blu-ray (file with wrong extension)
                if (format == null && file.Length > 500 && FileUtil.IsBluRaySup(fileName))
                {
                    this.ImportAndOcrBluRaySup(fileName, this._loading);
                    return;
                }

                // retry SP DVD (file with wrong extension)
                if (format == null && file.Length > 500 && FileUtil.IsSpDvdSup(fileName))
                {
                    this.ImportAndOcrSpDvdSup(fileName, this._loading);
                    return;
                }

                // retry Matroska (file with wrong extension)
                if (format == null && !string.IsNullOrWhiteSpace(fileName))
                {
                    var matroska = new MatroskaFile(fileName);
                    if (matroska.IsValid)
                    {
                        var subtitleList = matroska.GetTracks(true);
                        if (subtitleList.Count > 0)
                        {
                            this.ImportSubtitleFromMatroskaFile(fileName);
                            return;
                        }
                    }
                }

                // check for idx file
                if (format == null && file.Length > 100 && ext == ".idx")
                {
                    MessageBox.Show(this._language.ErrorLoadIdx);
                    return;
                }

                // check for .rar file
                if (format == null && file.Length > 100 && FileUtil.IsRar(fileName))
                {
                    MessageBox.Show(this._language.ErrorLoadRar);
                    return;
                }

                // check for .zip file
                if (format == null && file.Length > 100 && FileUtil.IsZip(fileName))
                {
                    MessageBox.Show(this._language.ErrorLoadZip);
                    return;
                }

                // check for .png file
                if (format == null && file.Length > 100 && FileUtil.IsPng(fileName))
                {
                    MessageBox.Show(this._language.ErrorLoadPng);
                    return;
                }

                // check for .jpg file
                if (format == null && file.Length > 100 && FileUtil.IsJpg(fileName))
                {
                    MessageBox.Show(this._language.ErrorLoadJpg);
                    return;
                }

                // check for .srr file
                if (format == null && file.Length > 100 && ext == ".srr" && FileUtil.IsSrr(fileName))
                {
                    MessageBox.Show(this._language.ErrorLoadSrr);
                    return;
                }

                // check for Torrent file
                if (format == null && file.Length > 50 && FileUtil.IsTorrentFile(fileName))
                {
                    MessageBox.Show(this._language.ErrorLoadTorrent);
                    return;
                }

                // check for all binary zeroes (I've heard about this a few times... perhaps related to crashes?)
                if (format == null && file.Length > 50 && FileUtil.IsSubtitleFileAllBinaryZeroes(fileName))
                {
                    MessageBox.Show(this._language.ErrorLoadBinaryZeroes);
                    return;
                }

                if (format == null && file.Length < 100 * 1000000 && TransportStreamParser.IsDvbSup(fileName))
                {
                    this.ImportSubtitleFromDvbSupFile(fileName);
                    return;
                }

                if (format == null && file.Length < 500000)
                {
                    // Try to use a generic subtitle format parser (guessing subtitle format)
                    try
                    {
                        var enc = Utilities.GetEncodingFromFile(fileName);
                        var s = File.ReadAllText(fileName, enc);

                        // check for RTF file
                        if (ext == ".rtf" && s.TrimStart().StartsWith("{\\rtf", StringComparison.Ordinal))
                        {
                            using (var rtb = new RichTextBox { Rtf = s })
                            {
                                s = rtb.Text;
                            }
                        }

                        var uknownFormatImporter = new UknownFormatImporter { UseFrames = true };
                        var genericParseSubtitle = uknownFormatImporter.AutoGuessImport(s.SplitToLines());
                        if (genericParseSubtitle.Paragraphs.Count > 1)
                        {
                            this._subtitle = genericParseSubtitle;
                            this.SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            this.SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = this.GetCurrentEncoding();
                            justConverted = true;
                            format = this.GetCurrentSubtitleFormat();
                            this.ShowStatus("Guessed subtitle format via generic subtitle parser!");
                        }
                    }
                    catch
                    {
                    }
                }

                this._fileDateTime = File.GetLastWriteTime(fileName);

                if (format != null && format.IsFrameBased)
                {
                    this._subtitle.CalculateTimeCodesFromFrameNumbers(this.CurrentFrameRate);
                }
                else
                {
                    this._subtitle.CalculateFrameNumbersFromTimeCodes(this.CurrentFrameRate);
                }

                if (format != null)
                {
                    if (Configuration.Settings.General.RemoveBlankLinesWhenOpening)
                    {
                        this._subtitle.RemoveEmptyLines();
                    }

                    foreach (var p in this._subtitle.Paragraphs)
                    {
                        // Replace U+0456 (CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I) by U+0069 (LATIN SMALL LETTER I)
                        p.Text = p.Text.Replace("<і>", "<i>").Replace("</і>", "</i>");
                    }

                    this._subtitleListViewIndex = -1;
                    this.SetCurrentFormat(format);
                    this._subtitleAlternateFileName = null;
                    if (this.LoadAlternateSubtitleFile(originalFileName))
                    {
                        this._subtitleAlternateFileName = originalFileName;
                    }

                    // Seungki begin
                    this._splitDualSami = false;
                    if (Configuration.Settings.SubtitleSettings.SamiDisplayTwoClassesAsTwoSubtitles && format.GetType() == typeof(Sami) && Sami.GetStylesFromHeader(this._subtitle.Header).Count == 2)
                    {
                        var classes = Sami.GetStylesFromHeader(this._subtitle.Header);
                        var s1 = new Subtitle(this._subtitle);
                        var s2 = new Subtitle(this._subtitle);
                        s1.Paragraphs.Clear();
                        s2.Paragraphs.Clear();
                        foreach (var p in this._subtitle.Paragraphs)
                        {
                            if (p.Extra != null && p.Extra.Equals(classes[0], StringComparison.OrdinalIgnoreCase))
                            {
                                s1.Paragraphs.Add(p);
                            }
                            else
                            {
                                s2.Paragraphs.Add(p);
                            }
                        }

                        if (s1.Paragraphs.Count == 0 || s2.Paragraphs.Count == 0)
                        {
                            return;
                        }

                        this._subtitle = s1;
                        this._subtitleAlternate = s2;
                        this._subtitleAlternateFileName = this._fileName;
                        this.SubtitleListview1.HideExtraColumn();
                        this.SubtitleListview1.ShowAlternateTextColumn(classes[1]);
                        this._splitDualSami = true;
                    }

                    // Seungki end
                    this.textBoxSource.Text = this._subtitle.ToText(format);
                    this.SubtitleListview1.Fill(this._subtitle, this._subtitleAlternate);
                    if (this.SubtitleListview1.Items.Count > 0)
                    {
                        this.SubtitleListview1.Items[0].Selected = true;
                    }

                    this._findHelper = null;
                    this._spellCheckForm = null;

                    if (this._resetVideo)
                    {
                        this.VideoFileName = null;
                        this._videoInfo = null;
                        this._videoAudioTrackNumber = -1;
                        this.labelVideoInfo.Text = this._languageGeneral.NoVideoLoaded;
                        this.audioVisualizer.WavePeaks = null;
                        this.audioVisualizer.ResetSpectrogram();
                        this.audioVisualizer.Invalidate();
                    }

                    if (Configuration.Settings.General.ShowVideoPlayer || Configuration.Settings.General.ShowAudioVisualizer)
                    {
                        if (!Configuration.Settings.General.DisableVideoAutoLoading)
                        {
                            if (!string.IsNullOrEmpty(videoFileName) && File.Exists(videoFileName))
                            {
                                this.OpenVideo(videoFileName);
                            }
                            else if (!string.IsNullOrEmpty(fileName) && (this.toolStripButtonToggleVideo.Checked || this.toolStripButtonToggleWaveform.Checked))
                            {
                                this.TryToFindAndOpenVideoFile(Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName)));
                            }
                        }
                    }

                    videoFileLoaded = this.VideoFileName != null;

                    if (Configuration.Settings.RecentFiles.Files.Count > 0 && Configuration.Settings.RecentFiles.Files[0].FileName == fileName)
                    {
                    }
                    else
                    {
                        Configuration.Settings.RecentFiles.Add(fileName, this.VideoFileName, this._subtitleAlternateFileName);
                        Configuration.Settings.Save();
                        this.UpdateRecentFilesUI();
                    }

                    this._fileName = fileName;
                    this.SetTitle();
                    this.ShowStatus(string.Format(this._language.LoadedSubtitleX, this._fileName));
                    this._sourceViewChange = false;
                    this._changeSubtitleToString = SerializeSubtitle(this._subtitle);
                    this._converted = false;
                    this.ResetHistory();

                    this.SetUndockedWindowsTitle();

                    if (justConverted)
                    {
                        this._converted = true;
                        this.ShowStatus(string.Format(this._language.LoadedSubtitleX, this._fileName) + " - " + string.Format(this._language.ConvertedToX, format.FriendlyName));
                    }

                    if (Configuration.Settings.General.AutoConvertToUtf8)
                    {
                        encoding = Encoding.UTF8;
                    }

                    this.SetEncoding(encoding);

                    if (format.GetType() == typeof(SubStationAlpha))
                    {
                        string errors = AdvancedSubStationAlpha.CheckForErrors(this._subtitle.Header);
                        if (!string.IsNullOrEmpty(errors))
                        {
                            MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        errors = (format as SubStationAlpha).Errors;
                        if (!string.IsNullOrEmpty(errors))
                        {
                            MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else if (format.GetType() == typeof(AdvancedSubStationAlpha))
                    {
                        string errors = AdvancedSubStationAlpha.CheckForErrors(this._subtitle.Header);
                        if (!string.IsNullOrEmpty(errors))
                        {
                            MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        errors = (format as AdvancedSubStationAlpha).Errors;
                        if (!string.IsNullOrEmpty(errors))
                        {
                            MessageBox.Show(errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else if (format.GetType() == typeof(SubRip))
                    {
                        string errors = (format as SubRip).Errors;
                        if (!string.IsNullOrEmpty(errors))
                        {
                            MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else if (format.GetType() == typeof(MicroDvd))
                    {
                        string errors = (format as MicroDvd).Errors;
                        if (!string.IsNullOrEmpty(errors))
                        {
                            MessageBox.Show(this, errors, this.Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
                else
                {
                    if (file.Length < 50)
                    {
                        this._findHelper = null;
                        this._spellCheckForm = null;
                        this.VideoFileName = null;
                        this._videoInfo = null;
                        this._videoAudioTrackNumber = -1;
                        this.labelVideoInfo.Text = this._languageGeneral.NoVideoLoaded;
                        this.audioVisualizer.WavePeaks = null;
                        this.audioVisualizer.ResetSpectrogram();
                        this.audioVisualizer.Invalidate();

                        Configuration.Settings.RecentFiles.Add(fileName, this.FirstVisibleIndex, this.FirstSelectedIndex, this.VideoFileName, this._subtitleAlternateFileName);
                        Configuration.Settings.Save();
                        this.UpdateRecentFilesUI();
                        this._fileName = fileName;
                        this.SetTitle();
                        this.ShowStatus(string.Format(this._language.LoadedEmptyOrShort, this._fileName));
                        this._sourceViewChange = false;
                        this._converted = false;

                        MessageBox.Show(this._language.FileIsEmptyOrShort);
                    }
                    else
                    {
                        if (ext == ".xml")
                        {
                            var sb = new StringBuilder();
                            foreach (var line in File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName)))
                            {
                                sb.AppendLine(line);
                            }

                            var xmlAsString = sb.ToString().Trim();

                            if (xmlAsString.Contains("http://www.w3.org/ns/ttml") && xmlAsString.Contains("<?xml version=") || xmlAsString.Contains("http://www.w3.org/") && xmlAsString.Contains("/ttaf1"))
                            {
                                var xml = new XmlDocument();
                                try
                                {
                                    xml.LoadXml(xmlAsString);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Timed text is not valid: " + ex.Message);
                                    return;
                                }
                            }
                        }

                        this.ShowUnknownSubtitle();
                        return;
                    }
                }

                if (!videoFileLoaded && this.mediaPlayer.VideoPlayer != null)
                {
                    this.mediaPlayer.VideoPlayer.DisposeVideoPlayer();
                    this.mediaPlayer.VideoPlayer = null;
                    this.timer1.Stop();
                }

                this.ResetShowEarlierOrLater();
            }
            else
            {
                MessageBox.Show(string.Format(this._language.FileNotFound, fileName));
            }
        }
        /// <summary>
        /// The add ware form_ shown.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void AddWareForm_Shown(object sender, EventArgs e)
        {
            this.Refresh();
            var audioTrackNames = new List<string>();
            var mkvAudioTrackNumbers = new Dictionary<int, int>();
            int numberOfAudioTracks = 0;
            if (this.labelVideoFileName.Text.Length > 1 && File.Exists(this.labelVideoFileName.Text))
            {
                if (this.labelVideoFileName.Text.EndsWith(".mkv", StringComparison.OrdinalIgnoreCase))
                { // Choose for number of audio tracks in matroska files
                    MatroskaFile matroska = null;
                    try
                    {
                        matroska = new MatroskaFile(this.labelVideoFileName.Text);
                        if (matroska.IsValid)
                        {
                            foreach (var track in matroska.GetTracks())
                            {
                                if (track.IsAudio)
                                {
                                    numberOfAudioTracks++;
                                    if (track.CodecId != null && track.Language != null)
                                    {
                                        audioTrackNames.Add("#" + track.TrackNumber + ": " + track.CodecId.Replace("\0", string.Empty) + " - " + track.Language.Replace("\0", string.Empty));
                                    }
                                    else
                                    {
                                        audioTrackNames.Add("#" + track.TrackNumber);
                                    }

                                    mkvAudioTrackNumbers.Add(mkvAudioTrackNumbers.Count, track.TrackNumber);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (matroska != null)
                        {
                            matroska.Dispose();
                        }
                    }
                }
                else if (this.labelVideoFileName.Text.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase) || this.labelVideoFileName.Text.EndsWith(".m4v", StringComparison.OrdinalIgnoreCase))
                { // Choose for number of audio tracks in mp4 files
                    try
                    {
                        var mp4 = new MP4Parser(this.labelVideoFileName.Text);
                        var tracks = mp4.GetAudioTracks();
                        int i = 0;
                        foreach (var track in tracks)
                        {
                            i++;
                            if (track.Name != null && track.Mdia != null && track.Mdia.Mdhd != null && track.Mdia.Mdhd.LanguageString != null)
                            {
                                audioTrackNames.Add(i + ":  " + track.Name + " - " + track.Mdia.Mdhd.LanguageString);
                            }
                            else if (track.Name != null)
                            {
                                audioTrackNames.Add(i + ":  " + track.Name);
                            }
                            else
                            {
                                audioTrackNames.Add(i.ToString(CultureInfo.InvariantCulture));
                            }
                        }

                        numberOfAudioTracks = tracks.Count;
                    }
                    catch
                    {
                    }
                }

                if (Configuration.Settings.General.UseFFmpegForWaveExtraction)
                { // don't know how to extract audio number x via FFmpeg...
                    numberOfAudioTracks = 1;
                    this._audioTrackNumber = 0;
                }

                // Choose audio track
                if (numberOfAudioTracks > 1)
                {
                    using (var form = new ChooseAudioTrack(audioTrackNames, this._audioTrackNumber))
                    {
                        if (form.ShowDialog(this) == DialogResult.OK)
                        {
                            this._audioTrackNumber = form.SelectedTrack;
                        }
                        else
                        {
                            this.DialogResult = DialogResult.Cancel;
                            return;
                        }
                    }
                }

                // check for delay in matroska files
                if (this.labelVideoFileName.Text.EndsWith(".mkv", StringComparison.OrdinalIgnoreCase))
                {
                    MatroskaFile matroska = null;
                    try
                    {
                        matroska = new MatroskaFile(this.labelVideoFileName.Text);
                        if (matroska.IsValid)
                        {
                            this._delayInMilliseconds = (int)matroska.GetTrackStartTime(mkvAudioTrackNumbers[this._audioTrackNumber]);
                        }
                    }
                    catch
                    {
                        this._delayInMilliseconds = 0;
                    }
                    finally
                    {
                        if (matroska != null)
                        {
                            matroska.Dispose();
                        }
                    }
                }

                this.buttonRipWave_Click(null, null);
            }
            else if (this._wavFileName != null)
            {
                this.FixWaveOnly();
            }
        }
Ejemplo n.º 13
0
        internal 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;
        }
Ejemplo n.º 14
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, this.MatroskaProgress);
            TaskbarList.SetProgressState(this.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;
        }
Ejemplo n.º 15
0
        private bool LoadBluRaySubFromMatroska(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska)
        {
            if (matroskaSubtitleInfo.ContentEncodingType == 1)
            {
                MessageBox.Show(this._language.NoSupportEncryptedVobSub);
            }

            this.ShowStatus(this._language.ParsingMatroskaFile);
            this.Refresh();
            Cursor.Current = Cursors.WaitCursor;
            var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, this.MatroskaProgress);
            TaskbarList.SetProgressState(this.Handle, TaskbarButtonProgressFlags.NoProgress);
            Cursor.Current = Cursors.Default;

            int noOfErrors = 0;
            string lastError = string.Empty;
            this.MakeHistoryForUndo(this._language.BeforeImportFromMatroskaFile);
            this._subtitleListViewIndex = -1;
            this._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
                    MemoryStream outStream = new MemoryStream();
                    var outZStream = new ZOutputStream(outStream);
                    MemoryStream 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)
                {
                    MemoryStream 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) occured 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 (this._loading)
                {
                    formSubOcr.Icon = (Icon)this.Icon.Clone();
                    formSubOcr.ShowInTaskbar = true;
                    formSubOcr.ShowIcon = true;
                }

                if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                {
                    this.MakeHistoryForUndo(this._language.BeforeImportingDvdSubtitle);

                    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 = string.Empty;
                    this.Text = this.Title;

                    Configuration.Settings.Save();
                    return true;
                }
            }

            return false;
        }
        private void AddInputFile(string fileName)
        {
            try
            {
                foreach (ListViewItem lvi in listViewInputFiles.Items)
                {
                    if (lvi.Text.Equals(fileName, StringComparison.OrdinalIgnoreCase))
                        return;
                }

                var fi = new FileInfo(fileName);
                var ext = fi.Extension;
                var item = new ListViewItem(fileName);
                item.SubItems.Add(Utilities.FormatBytesToDisplayFileSize(fi.Length));

                SubtitleFormat format = null;
                var sub = new Subtitle();
                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))
                        {
                            format = ebu;
                        }
                    }
                    if (format == null)
                    {
                        var pac = new Pac();
                        if (pac.IsMine(null, fileName))
                        {
                            format = pac;
                        }
                    }
                    if (format == null)
                    {
                        var cavena890 = new Cavena890();
                        if (cavena890.IsMine(null, fileName))
                        {
                            format = cavena890;
                        }
                    }
                    if (format == null)
                    {
                        var spt = new Spt();
                        if (spt.IsMine(null, fileName))
                        {
                            format = spt;
                        }
                    }
                    if (format == null)
                    {
                        var cheetahCaption = new CheetahCaption();
                        if (cheetahCaption.IsMine(null, fileName))
                        {
                            format = cheetahCaption;
                        }
                    }
                    if (format == null)
                    {
                        var chk = new Chk();
                        if (chk.IsMine(null, fileName))
                        {
                            format = chk;
                        }
                    }
                    if (format == null)
                    {
                        var ayato = new Ayato();
                        if (ayato.IsMine(null, fileName))
                        {
                            format = ayato;
                        }
                    }
                    if (format == null)
                    {
                        var capMakerPlus = new CapMakerPlus();
                        if (capMakerPlus.IsMine(null, fileName))
                        {
                            format = capMakerPlus;
                        }
                    }
                    if (format == null)
                    {
                        var captionate = new Captionate();
                        if (captionate.IsMine(null, fileName))
                        {
                            format = captionate;
                        }
                    }
                    if (format == null)
                    {
                        var ultech130 = new Ultech130();
                        if (ultech130.IsMine(null, fileName))
                        {
                            format = ultech130;
                        }
                    }
                    if (format == null)
                    {
                        var nciCaption = new NciCaption();
                        if (nciCaption.IsMine(null, fileName))
                        {
                            format = nciCaption;
                        }
                    }
                    if (format == null)
                    {
                        var avidStl = new AvidStl();
                        if (avidStl.IsMine(null, fileName))
                        {
                            format = avidStl;
                        }
                    }
                    if (format == null)
                    {
                        var asc = new TimeLineAscii();
                        if (asc.IsMine(null, fileName))
                        {
                            format = asc;
                        }
                    }
                    if (format == null)
                    {
                        var asc = new TimeLineFootageAscii();
                        if (asc.IsMine(null, fileName))
                        {
                            format = asc;
                        }
                    }
                }

                if (format == null)
                {
                    if (FileUtil.IsBluRaySup(fileName))
                    {
                        item.SubItems.Add("Blu-ray");
                    }
                    else if (FileUtil.IsVobSub(fileName))
                    {
                        item.SubItems.Add("VobSub");
                    }
                    else if (ext.Equals(".mkv", StringComparison.OrdinalIgnoreCase) || ext.Equals(".mks", StringComparison.OrdinalIgnoreCase))
                    {
                        int mkvCount = 0;
                        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))
                                    {
                                        mkvCount++;
                                    }
                                }
                            }
                        }
                        if (mkvCount > 0)
                        {
                            item.SubItems.Add("Matroska - " + mkvCount);
                        }
                        else
                        {
                            item.SubItems.Add(Configuration.Settings.Language.UnknownSubtitle.Title);
                        }
                    }
                    else
                    {
                        item.SubItems.Add(Configuration.Settings.Language.UnknownSubtitle.Title);
                    }
                }
                else
                {
                    item.SubItems.Add(format.Name);
                }
                item.SubItems.Add("-");

                listViewInputFiles.Items.Add(item);
            }
            catch
            {
            }
        }
        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 && 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, Utilities.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;
        }
Ejemplo n.º 18
0
        private bool LoadMatroskaSubtitle(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska, bool batchMode)
        {
            if (matroskaSubtitleInfo.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase))
            {
                if (batchMode)
                {
                    return false;
                }

                return this.LoadVobSubFromMatroska(matroskaSubtitleInfo, matroska);
            }

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

                return this.LoadBluRaySubFromMatroska(matroskaSubtitleInfo, matroska);
            }

            this.ShowStatus(this._language.ParsingMatroskaFile);
            this.Refresh();
            Cursor.Current = Cursors.WaitCursor;
            var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, this.MatroskaProgress);
            TaskbarList.SetProgressState(this.Handle, TaskbarButtonProgressFlags.NoProgress);
            Cursor.Current = Cursors.Default;

            this.MakeHistoryForUndo(this._language.BeforeImportFromMatroskaFile);
            this._subtitleListViewIndex = -1;
            if (!batchMode)
            {
                this.ResetSubtitle();
            }

            this._subtitle.Paragraphs.Clear();

            var format = Utilities.LoadMatroskaTextSubtitle(matroskaSubtitleInfo, matroska, sub, this._subtitle);

            if (matroskaSubtitleInfo.CodecPrivate.Contains("[script info]", StringComparison.OrdinalIgnoreCase))
            {
                if (this._networkSession == null)
                {
                    this.SubtitleListview1.ShowExtraColumn(this._languageGeneral.Style);
                    this.SubtitleListview1.DisplayExtraFromExtra = true;
                }
            }
            else if (this._networkSession == null && this.SubtitleListview1.IsExtraColumnVisible)
            {
                this.SubtitleListview1.HideExtraColumn();
            }

            this.comboBoxSubtitleFormats.SelectedIndexChanged -= this.ComboBoxSubtitleFormatsSelectedIndexChanged;
            this.SetCurrentFormat(format);
            this.comboBoxSubtitleFormats.SelectedIndexChanged += this.ComboBoxSubtitleFormatsSelectedIndexChanged;
            this.SetEncoding(Encoding.UTF8);
            this.ShowStatus(this._language.SubtitleImportedFromMatroskaFile);
            this._subtitle.Renumber();
            this._subtitle.WasLoadedWithFrameNumbers = false;
            if (matroska.Path.EndsWith(".mkv", StringComparison.OrdinalIgnoreCase) || matroska.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
            {
                this._fileName = matroska.Path.Remove(matroska.Path.Length - 4);
                this.Text = this.Title + " - " + this._fileName;
            }
            else
            {
                this.Text = this.Title;
            }

            this._fileDateTime = new DateTime();

            this._converted = true;

            if (batchMode)
            {
                return true;
            }

            this.SubtitleListview1.Fill(this._subtitle, this._subtitleAlternate);
            if (this._subtitle.Paragraphs.Count > 0)
            {
                this.SubtitleListview1.SelectIndexAndEnsureVisible(0);
            }

            this.ShowSource();
            return true;
        }
Ejemplo n.º 19
0
        public void MatroskaTestVobSubPgsContent()
        {
            string fileName = Path.Combine(Directory.GetCurrentDirectory(), "sample_MKV_VobSub_PGS.mkv");
            using (var parser = new MatroskaFile(fileName))
            {
                var tracks = parser.GetTracks(true);
                var subtitles = parser.GetSubtitle(Convert.ToInt32(tracks[0].TrackNumber), null);
                Assert.IsTrue(subtitles.Count == 2);
                // TODO: Check bitmaps

                //subtitles = parser.GetSubtitle(Convert.ToInt32(tracks[1].TrackNumber), null);
                //Assert.IsTrue(subtitles.Count == 2);
                //check bitmaps
            }
        }
Ejemplo n.º 20
0
        private bool LoadVobSubFromMatroska(MatroskaTrackInfo matroskaSubtitleInfo, MatroskaFile matroska)
        {
            if (matroskaSubtitleInfo.ContentEncodingType == 1)
            {
                MessageBox.Show(this._language.NoSupportEncryptedVobSub);
            }

            this.ShowStatus(this._language.ParsingMatroskaFile);
            this.Refresh();
            Cursor.Current = Cursors.WaitCursor;
            var sub = matroska.GetSubtitle(matroskaSubtitleInfo.TrackNumber, this.MatroskaProgress);
            TaskbarList.SetProgressState(this.Handle, TaskbarButtonProgressFlags.NoProgress);
            Cursor.Current = Cursors.Default;

            this.MakeHistoryForUndo(this._language.BeforeImportFromMatroskaFile);
            this._subtitleListViewIndex = -1;
            this._subtitle.Paragraphs.Clear();

            List<VobSubMergedPack> mergedVobSubPacks = new List<VobSubMergedPack>();
            Idx idx = new Idx(matroskaSubtitleInfo.CodecPrivate.SplitToLines());
            foreach (var p in sub)
            {
                if (matroskaSubtitleInfo.ContentEncodingType == 0)
                {
                    // compressed with zlib
                    bool error = false;
                    MemoryStream outStream = new MemoryStream();
                    var outZStream = new ZOutputStream(outStream);
                    MemoryStream 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 (this._loading)
                {
                    formSubOcr.Icon = (Icon)this.Icon.Clone();
                    formSubOcr.ShowInTaskbar = true;
                    formSubOcr.ShowIcon = true;
                }

                if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                {
                    this.ResetSubtitle();
                    this._subtitle.Paragraphs.Clear();
                    this._subtitle.WasLoadedWithFrameNumbers = false;
                    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.GetFileNameWithoutExtension(matroska.Path);
                    this._converted = true;
                    this.Text = this.Title;

                    Configuration.Settings.Save();
                    return true;
                }
            }

            return false;
        }
Ejemplo n.º 21
0
        // E.g.: /convert *.txt SubRip
        public static void Convert(string title, string[] args)
        {
            const int ATTACH_PARENT_PROCESS = -1;
            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
                NativeMethods.AttachConsole(ATTACH_PARENT_PROCESS);

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(title + " - Batch converter");
            Console.WriteLine();
            Console.WriteLine("- Syntax: SubtitleEdit /convert <pattern> <name-of-format-without-spaces> [/offset:hh:mm:ss:ms] [/encoding:<encoding name>] [/fps:<frame rate>] [/targetfps:<frame rate>] [/inputfolder:<input folder>] [/outputfolder:<output folder>] [/pac-codepage:<code page>]");
            Console.WriteLine();
            Console.WriteLine("    example: SubtitleEdit /convert *.srt sami");
            Console.WriteLine("    list available formats: SubtitleEdit /convert /list");
            Console.WriteLine();

            string currentDir = Directory.GetCurrentDirectory();

            if (args.Length < 4)
            {
                if (args.Length == 3 && (args[2].Equals("/list", StringComparison.OrdinalIgnoreCase) || args[2].Equals("-list", StringComparison.OrdinalIgnoreCase)))
                {
                    Console.WriteLine("- Supported formats (input/output):");
                    foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
                    {
                        Console.WriteLine("    " + format.Name.Replace(" ", string.Empty));
                    }
                    Console.WriteLine();
                    Console.WriteLine("- Supported formats (input only):");
                    Console.WriteLine("    " + CapMakerPlus.NameOfFormat);
                    Console.WriteLine("    " + Captionate.NameOfFormat);
                    Console.WriteLine("    " + Cavena890.NameOfFormat);
                    Console.WriteLine("    " + CheetahCaption.NameOfFormat);
                    Console.WriteLine("    " + Chk.NameOfFormat);
                    Console.WriteLine("    Matroska (.mkv)");
                    Console.WriteLine("    Matroska subtitle (.mks)");
                    Console.WriteLine("    " + NciCaption.NameOfFormat);
                    Console.WriteLine("    " + AvidStl.NameOfFormat);
                    Console.WriteLine("    " + Pac.NameOfFormat);
                    Console.WriteLine("    " + Spt.NameOfFormat);
                    Console.WriteLine("    " + Ultech130.NameOfFormat);
                }

                Console.WriteLine();
                Console.Write(currentDir + ">");
                if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
                    NativeMethods.FreeConsole();
                Environment.Exit(1);
            }

            int count = 0;
            int converted = 0;
            int errors = 0;
            try
            {
                string pattern = args[2];
                string toFormat = args[3];
                string offset = GetArgument(args, "/offset:");

                var fps = GetArgument(args, "/fps:");
                if (fps.Length > 6)
                {
                    fps = fps.Remove(0, 5).Replace(",", ".").Trim();
                    double d;
                    if (double.TryParse(fps, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out d))
                    {
                        Configuration.Settings.General.CurrentFrameRate = d;
                    }
                }

                var targetFps = GetArgument(args, "/targetfps:");
                double? targetFrameRate = null;
                if (targetFps.Length > 12)
                {
                    targetFps = targetFps.Remove(0, 11).Replace(",", ".").Trim();
                    double d;
                    if (double.TryParse(targetFps, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out d))
                    {
                        targetFrameRate = d;
                    }
                }

                var targetEncodingName = GetArgument(args, "/encoding:"); ;
                var targetEncoding = Encoding.UTF8;
                try
                {
                    if (!string.IsNullOrEmpty(targetEncodingName))
                    {
                        targetEncodingName = targetEncodingName.Substring(10);
                        if (!string.IsNullOrEmpty(targetEncodingName))
                            targetEncoding = Encoding.GetEncoding(targetEncodingName);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Unable to set encoding (" + exception.Message + ") - using UTF-8");
                    targetEncoding = Encoding.UTF8;
                }

                var outputFolder = GetArgument(args, "/outputfolder:"); ;
                if (outputFolder.Length > "/outputFolder:".Length)
                {
                    outputFolder = outputFolder.Remove(0, "/outputFolder:".Length);
                    if (!Directory.Exists(outputFolder))
                        outputFolder = string.Empty;
                }

                var inputFolder = GetArgument(args, "/inputFolder:", Directory.GetCurrentDirectory());
                if (inputFolder.Length > "/inputFolder:".Length)
                {
                    inputFolder = inputFolder.Remove(0, "/inputFolder:".Length);
                    if (!Directory.Exists(inputFolder))
                        inputFolder = Directory.GetCurrentDirectory();
                }

                var pacCodePage = GetArgument(args, "/pac-codepage:");
                if (pacCodePage.Length > "/pac-codepage:".Length)
                {
                    pacCodePage = pacCodePage.Remove(0, "/pac-codepage:".Length);
                    if (string.Compare("Latin", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                        pacCodePage = "0";
                    else if (string.Compare("Greek", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                        pacCodePage = "1";
                    else if (string.Compare("Czech", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                        pacCodePage = "2";
                    else if (string.Compare("Arabic", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                        pacCodePage = "3";
                    else if (string.Compare("Hebrew", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                        pacCodePage = "4";
                    else if (string.Compare("Encoding", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                        pacCodePage = "5";
                    else if (string.Compare("Cyrillic", pacCodePage, StringComparison.OrdinalIgnoreCase) == 0)
                        pacCodePage = "6";
                }

                bool overwrite = GetArgument(args, "/overwrite", string.Empty).Equals("/overwrite");

                string[] files;
                string inputDirectory = Directory.GetCurrentDirectory();
                if (!string.IsNullOrEmpty(inputFolder))
                    inputDirectory = inputFolder;

                if (pattern.Contains(',') && !File.Exists(pattern))
                {
                    files = pattern.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int k = 0; k < files.Length; k++)
                        files[k] = files[k].Trim();
                }
                else
                {
                    int indexOfDirectorySeparatorChar = pattern.LastIndexOf(Path.DirectorySeparatorChar);
                    if (indexOfDirectorySeparatorChar > 0 && indexOfDirectorySeparatorChar < pattern.Length)
                    {
                        pattern = pattern.Substring(indexOfDirectorySeparatorChar + 1);
                        inputDirectory = args[2].Substring(0, indexOfDirectorySeparatorChar);
                    }
                    files = Directory.GetFiles(inputDirectory, pattern);
                }

                var formats = SubtitleFormat.AllSubtitleFormats;
                foreach (string fName in files)
                {
                    string fileName = fName;
                    count++;

                    if (!string.IsNullOrEmpty(inputFolder) && File.Exists(Path.Combine(inputFolder, fileName)))
                    {
                        fileName = Path.Combine(inputFolder, fileName);
                    }

                    if (File.Exists(fileName))
                    {
                        var sub = new Subtitle();
                        SubtitleFormat format = null;
                        bool done = false;

                        if (Path.GetExtension(fileName).Equals(".mkv", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(fileName).Equals(".mks", StringComparison.OrdinalIgnoreCase))
                        {
                            using (var matroska = new MatroskaFile(fileName))
                            {
                                if (matroska.IsValid)
                                {
                                    var tracks = matroska.GetTracks();
                                    if (tracks.Count > 0)
                                    {
                                        foreach (var track in tracks)
                                        {
                                            if (track.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Console.WriteLine("{0}: {1} - Cannot convert from VobSub image based format!", fileName, toFormat);
                                            }
                                            else if (track.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Console.WriteLine("{0}: {1} - Cannot convert from Blu-ray image based format!", fileName, toFormat);
                                            }
                                            else
                                            {
                                                var ss = matroska.GetSubtitle(track.TrackNumber, null);
                                                format = Utilities.LoadMatroskaTextSubtitle(track, matroska, ss, sub);
                                                string newFileName = fileName;
                                                if (tracks.Count > 1)
                                                    newFileName = fileName.Insert(fileName.Length - 4, "_" + track.TrackNumber + "_" + track.Language.Replace("?", string.Empty).Replace("!", string.Empty).Replace("*", string.Empty).Replace(",", string.Empty).Replace("/", string.Empty).Trim());

                                                if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha))
                                                {
                                                    if (toFormat.ToLower() != AdvancedSubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty) &&
                                                        toFormat.ToLower() != SubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty))
                                                    {

                                                        foreach (SubtitleFormat sf in formats)
                                                        {
                                                            if (sf.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || sf.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))
                                                            {
                                                                format.RemoveNativeFormatting(sub, sf);
                                                                break;
                                                            }
                                                        }

                                                    }
                                                }

                                                BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, overwrite, pacCodePage, targetFrameRate);
                                                done = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (FileUtil.IsBluRaySup(fileName))
                        {
                            Console.WriteLine("Found Blu-Ray subtitle format");
                            ConvertBluRaySubtitle(fileName, toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate);
                            done = true;
                        }
                        if (!done && FileUtil.IsVobSub(fileName))
                        {
                            Console.WriteLine("Found VobSub subtitle format");
                            ConvertVobSubSubtitle(fileName, toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, overwrite, pacCodePage, targetFrameRate);
                            done = true;
                        }

                        var fi = new FileInfo(fileName);
                        if (fi.Length < 10 * 1024 * 1024 && !done) // max 10 mb
                        {
                            Encoding encoding;
                            format = sub.LoadSubtitle(fileName, out encoding, null, true);

                            if (format == null || format.GetType() == typeof(Ebu))
                            {
                                var ebu = new Ebu();
                                if (ebu.IsMine(null, fileName))
                                {
                                    ebu.LoadSubtitle(sub, null, fileName);
                                    format = ebu;
                                }
                            }
                            if (format == null)
                            {
                                var pac = new Pac();
                                if (pac.IsMine(null, fileName))
                                {
                                    pac.BatchMode = true;

                                    if (!string.IsNullOrEmpty(pacCodePage) && Utilities.IsInteger(pacCodePage))
                                        pac.CodePage = int.Parse(pacCodePage);
                                    else
                                        pac.CodePage = -1;

                                    pac.LoadSubtitle(sub, null, fileName);
                                    format = pac;
                                }
                            }
                            if (format == null)
                            {
                                var cavena890 = new Cavena890();
                                if (cavena890.IsMine(null, fileName))
                                {
                                    cavena890.LoadSubtitle(sub, null, fileName);
                                    format = cavena890;
                                }
                            }
                            if (format == null)
                            {
                                var spt = new Spt();
                                if (spt.IsMine(null, fileName))
                                {
                                    spt.LoadSubtitle(sub, null, fileName);
                                    format = spt;
                                }
                            }
                            if (format == null)
                            {
                                var cheetahCaption = new CheetahCaption();
                                if (cheetahCaption.IsMine(null, fileName))
                                {
                                    cheetahCaption.LoadSubtitle(sub, null, fileName);
                                    format = cheetahCaption;
                                }
                            }
                            if (format == null)
                            {
                                var chk = new Chk();
                                if (chk.IsMine(null, fileName))
                                {
                                    chk.LoadSubtitle(sub, null, fileName);
                                    format = chk;
                                }
                            }
                            if (format == null)
                            {
                                var ayato = new Ayato();
                                if (ayato.IsMine(null, fileName))
                                {
                                    ayato.LoadSubtitle(sub, null, fileName);
                                    format = ayato;
                                }
                            }
                            if (format == null)
                            {
                                var capMakerPlus = new CapMakerPlus();
                                if (capMakerPlus.IsMine(null, fileName))
                                {
                                    capMakerPlus.LoadSubtitle(sub, null, fileName);
                                    format = capMakerPlus;
                                }
                            }
                            if (format == null)
                            {
                                var captionate = new Captionate();
                                if (captionate.IsMine(null, fileName))
                                {
                                    captionate.LoadSubtitle(sub, null, fileName);
                                    format = captionate;
                                }
                            }
                            if (format == null)
                            {
                                var ultech130 = new Ultech130();
                                if (ultech130.IsMine(null, fileName))
                                {
                                    ultech130.LoadSubtitle(sub, null, fileName);
                                    format = ultech130;
                                }
                            }
                            if (format == null)
                            {
                                var nciCaption = new NciCaption();
                                if (nciCaption.IsMine(null, fileName))
                                {
                                    nciCaption.LoadSubtitle(sub, null, fileName);
                                    format = nciCaption;
                                }
                            }
                            if (format == null)
                            {
                                var tsb4 = new TSB4();
                                if (tsb4.IsMine(null, fileName))
                                {
                                    tsb4.LoadSubtitle(sub, null, fileName);
                                    format = tsb4;
                                }
                            }
                            if (format == null)
                            {
                                var avidStl = new AvidStl();
                                if (avidStl.IsMine(null, fileName))
                                {
                                    avidStl.LoadSubtitle(sub, null, fileName);
                                    format = avidStl;
                                }
                            }
                            if (format == null)
                            {
                                var elr = new ELRStudioClosedCaption();
                                if (elr.IsMine(null, fileName))
                                {
                                    elr.LoadSubtitle(sub, null, fileName);
                                    format = elr;
                                }
                            }
                        }

                        if (format == null)
                        {
                            if (fi.Length < 1024 * 1024) // max 1 mb
                                Console.WriteLine("{0}: {1} - input file format unknown!", fileName, toFormat);
                            else
                                Console.WriteLine("{0}: {1} - input file too large!", fileName, toFormat);
                        }
                        else if (!done)
                        {
                            BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, overwrite, pacCodePage, targetFrameRate);
                        }
                    }
                    else
                    {
                        Console.WriteLine("{0}: {1} - file not found!", count, fileName);
                        errors++;
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine();
                Console.WriteLine("Ups - an error occured: " + exception.Message);
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine("{0} file(s) converted", converted);
            Console.WriteLine();
            Console.Write(currentDir + ">");

            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
                NativeMethods.FreeConsole();

            if (count == converted && errors == 0)
                Environment.Exit(0);
            else
                Environment.Exit(1);
        }