Пример #1
0
        private static VideoInfo TryReadVideoInfoViaMatroskaHeader(string fileName)
        {
            var info = new VideoInfo { Success = false };

            try
            {
                bool hasConstantFrameRate = false;
                bool success = false;
                double frameRate = 0;
                int width = 0;
                int height = 0;
                double milliseconds = 0;
                string videoCodec = string.Empty;

                var matroskaParser = new Matroska();
                matroskaParser.GetMatroskaInfo(fileName, ref success, ref hasConstantFrameRate, ref frameRate, ref width, ref height, ref milliseconds, ref videoCodec);
                if (success)
                {
                    info.Width = width;
                    info.Height = height;
                    info.FramesPerSecond = frameRate;
                    info.Success = true;
                    info.TotalMilliseconds = milliseconds;
                    info.TotalSeconds = milliseconds / 1000.0;
                    info.TotalFrames = info.TotalSeconds * frameRate;
                    info.VideoCodec = videoCodec;
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
            return info;
        }
Пример #2
0
        private void SubtitleListview1_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (files.Length == 1)
            {
                if (ContinueNewOrExit())
                {
                    string fileName = files[0];

                    saveFileDialog1.InitialDirectory = System.IO.Path.GetDirectoryName(fileName);
                    openFileDialog1.InitialDirectory = System.IO.Path.GetDirectoryName(fileName);

                    var fi = new FileInfo(fileName);
                    string ext = Path.GetExtension(fileName).ToLower();

                    if (ext == ".mkv")
                    {
                        bool isValid;
                        var matroska = new Matroska();
                        var subtitleList = matroska.GetMatroskaSubtitleTracks(fileName, out isValid);
                        if (isValid)
                        {
                            if (subtitleList.Count == 0)
                            {
                                MessageBox.Show(_language.NoSubtitlesFound);
                            }
                            else if (subtitleList.Count > 1)
                            {
                                MatroskaSubtitleChooser subtitleChooser = new MatroskaSubtitleChooser();
                                subtitleChooser.Initialize(subtitleList);
                                if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                {
                                    LoadMatroskaSubtitle(subtitleList[subtitleChooser.SelectedIndex], fileName, false);
                                }
                            }
                            else
                            {
                                LoadMatroskaSubtitle(subtitleList[0], fileName, false);
                            }
                        }
                        return;
                    }

                    if (fi.Length < 1024 * 1024 * 2) // max 2 mb
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else if (fi.Length < 150000000 && ext == ".sub" && IsVobSubFile(fileName, true)) // max 150 mb
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else if (fi.Length < 250000000 && ext == ".sup" && IsBluRaySupFile(fileName)) // max 250 mb
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else if ((ext == ".ts" || ext == ".rec" || ext == ".mpg" || ext == ".mpeg") && IsTransportStream(fileName))
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else if (ext == ".m2ts" && IsM2TransportStream(fileName))
                    {
                        OpenSubtitle(fileName, null);
                    }
                    else
                    {
                        MessageBox.Show(string.Format(_language.DropFileXNotAccepted, fileName));
                    }
                }
            }
            else
            {
                MessageBox.Show(_language.DropOnlyOneFile);
            }
        }
Пример #3
0
        private void LoadBluRaySubFromMatroska(MatroskaSubtitleInfo matroskaSubtitleInfo, string fileName)
        {
            if (matroskaSubtitleInfo.ContentEncodingType == 1)
            {
                MessageBox.Show("Encrypted vobsub content not supported");
            }

            bool isValid;
            var matroska = new Matroska();

            ShowStatus(_language.ParsingMatroskaFile);
            Refresh();
            Cursor.Current = Cursors.WaitCursor;
            List<SubtitleSequence> sub = matroska.GetMatroskaSubtitle(fileName, (int)matroskaSubtitleInfo.TrackNumber, out isValid, MatroskaProgress);
            Cursor.Current = Cursors.Default;
            int noOfErrors = 0;
            string lastError = string.Empty;

            if (isValid)
            {
                MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                _subtitleListViewIndex = -1;
                _subtitle.Paragraphs.Clear();
                var subtitles = new List<Nikse.SubtitleEdit.Logic.BluRaySup.BluRaySupParser.PcsData>();
                StringBuilder log = new StringBuilder();
                foreach (SubtitleSequence p in sub)
                {
                    byte[] buffer = null;
                    if (matroskaSubtitleInfo.ContentEncodingType == 0) // compressed with zlib
                    {
                        MemoryStream outStream = new MemoryStream();
                        ComponentAce.Compression.Libs.zlib.ZOutputStream outZStream = new ComponentAce.Compression.Libs.zlib.ZOutputStream(outStream);
                        MemoryStream inStream = new MemoryStream(p.BinaryData);
                        try
                        {
                            CopyStream(inStream, outZStream);
                            buffer = new byte[outZStream.TotalOut];
                            outStream.Position = 0;
                            outStream.Read(buffer, 0, buffer.Length);
                        }
                        catch (Exception exception)
                        {
                            TimeCode tc = new TimeCode(TimeSpan.FromMilliseconds(p.StartMilliseconds));
                            lastError = tc.ToString() + ": " + exception.Message + ": " + exception.StackTrace;
                            noOfErrors++;
                        }
                        finally
                        {
                            outStream.Close();
                            outZStream.Close();
                            inStream.Close();
                        }
                    }
                    else
                    {
                        buffer = p.BinaryData;
                    }
                    if (buffer != null && buffer.Length > 100)
                    {
                        MemoryStream ms = new MemoryStream(buffer);
                        var list = BluRaySupParser.ParseBluRaySup(ms, log, true);
                        foreach (var sup in list)
                        {
                            sup.StartTime = (long)((p.StartMilliseconds - 45) * 90.0);
                            sup.EndTime = (long)((p.EndMilliseconds - 45) * 90.0);
                            subtitles.Add(sup);

                            // fix overlapping
                            if (subtitles.Count > 1 && sub[subtitles.Count - 2].EndMilliseconds > sub[subtitles.Count - 1].StartMilliseconds)
                                subtitles[subtitles.Count - 2].EndTime = subtitles[subtitles.Count - 1].StartTime - 1;
                        }
                        ms.Close();
                    }
                }

                if (noOfErrors > 0)
                {
                    MessageBox.Show(string.Format("{0} errror(s) occured during extraction of bdsup\r\n\r\n{1}", noOfErrors, lastError));
                }

                var formSubOcr = new VobSubOcr();
                _formPositionsAndSizes.SetPositionAndSize(formSubOcr);
                formSubOcr.Initialize(subtitles, Configuration.Settings.VobSubOcr, fileName);
                if (_loading)
                {
                    formSubOcr.Icon = (Icon)this.Icon.Clone();
                    formSubOcr.ShowInTaskbar = true;
                    formSubOcr.ShowIcon = true;
                }
                if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                {
                    MakeHistoryForUndo(_language.BeforeImportingDvdSubtitle);

                    _subtitle.Paragraphs.Clear();
                    SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                    _subtitle.WasLoadedWithFrameNumbers = false;
                    _subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                    foreach (Paragraph p in formSubOcr.SubtitleFromOcr.Paragraphs)
                    {
                        _subtitle.Paragraphs.Add(p);
                    }

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

                    _fileName = string.Empty;
                    Text = Title;

                    Configuration.Settings.Save();
                }
                _formPositionsAndSizes.SavePositionAndSize(formSubOcr);
            }
        }
Пример #4
0
        private void LoadVobSubFromMatroska(MatroskaSubtitleInfo matroskaSubtitleInfo, string fileName)
        {
            if (matroskaSubtitleInfo.ContentEncodingType == 1)
            {
                MessageBox.Show("Encrypted vobsub content not supported");
            }

            bool isValid;
            var matroska = new Matroska();

            ShowStatus(_language.ParsingMatroskaFile);
            Refresh();
            Cursor.Current = Cursors.WaitCursor;
            List<SubtitleSequence> sub = matroska.GetMatroskaSubtitle(fileName, (int)matroskaSubtitleInfo.TrackNumber, out isValid, MatroskaProgress);
            Cursor.Current = Cursors.Default;

            if (isValid)
            {
                MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                _subtitleListViewIndex = -1;
                _subtitle.Paragraphs.Clear();

                List<VobSubMergedPack> mergedVobSubPacks = new List<VobSubMergedPack>();
                Nikse.SubtitleEdit.Logic.VobSub.Idx idx = new Logic.VobSub.Idx(matroskaSubtitleInfo.CodecPrivate.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                foreach (SubtitleSequence p in sub)
                {
                    if (matroskaSubtitleInfo.ContentEncodingType == 0) // compressed with zlib
                    {
                        bool error = false;
                        MemoryStream outStream = new MemoryStream();
                        ComponentAce.Compression.Libs.zlib.ZOutputStream outZStream = new ComponentAce.Compression.Libs.zlib.ZOutputStream(outStream);
                        MemoryStream inStream = new MemoryStream(p.BinaryData);
                        byte[] buffer = null;
                        try
                        {
                            CopyStream(inStream, outZStream);
                            buffer = new byte[outZStream.TotalOut];
                            outStream.Position = 0;
                            outStream.Read(buffer, 0, buffer.Length);
                        }
                        catch (Exception exception)
                        {
                            MessageBox.Show(exception.Message + Environment.NewLine + Environment.NewLine + exception.StackTrace);
                            error = true;
                        }
                        finally
                        {
                            outStream.Close();
                            outZStream.Close();
                            inStream.Close();
                        }

                        if (!error)
                            mergedVobSubPacks.Add(new VobSubMergedPack(buffer, TimeSpan.FromMilliseconds(p.StartMilliseconds), 32, null));
                    }
                    else
                    {
                        mergedVobSubPacks.Add(new VobSubMergedPack(p.BinaryData, TimeSpan.FromMilliseconds(p.StartMilliseconds), 32, null));
                    }
                    mergedVobSubPacks[mergedVobSubPacks.Count - 1].EndTime = TimeSpan.FromMilliseconds(p.EndMilliseconds);

                    // fix overlapping (some versions of Handbrake makes overlapping time codes - thx Hawke)
                    if (mergedVobSubPacks.Count > 1 && mergedVobSubPacks[mergedVobSubPacks.Count - 2].EndTime > mergedVobSubPacks[mergedVobSubPacks.Count - 1].StartTime)
                        mergedVobSubPacks[mergedVobSubPacks.Count - 2].EndTime = TimeSpan.FromMilliseconds(mergedVobSubPacks[mergedVobSubPacks.Count - 1].StartTime.TotalMilliseconds - 1);
                }

                var formSubOcr = new VobSubOcr();
                _formPositionsAndSizes.SetPositionAndSize(formSubOcr);
                formSubOcr.Initialize(mergedVobSubPacks, idx.Palette, Configuration.Settings.VobSubOcr, null); //TODO - language???
                if (_loading)
                {
                    formSubOcr.Icon = (Icon)this.Icon.Clone();
                    formSubOcr.ShowInTaskbar = true;
                    formSubOcr.ShowIcon = true;
                }
                if (formSubOcr.ShowDialog(this) == DialogResult.OK)
                {
                    ResetSubtitle();
                    _subtitle.Paragraphs.Clear();
                    _subtitle.WasLoadedWithFrameNumbers = false;
                    foreach (Paragraph p in formSubOcr.SubtitleFromOcr.Paragraphs)
                        _subtitle.Paragraphs.Add(p);

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

                    _fileName =  Path.GetFileNameWithoutExtension(fileName);
                    _converted = true;
                    Text = Title;

                    Configuration.Settings.Save();
                }
                _formPositionsAndSizes.SavePositionAndSize(formSubOcr);
            }
        }
Пример #5
0
        internal void LoadMatroskaSubtitle(MatroskaSubtitleInfo matroskaSubtitleInfo, string fileName, bool batchMode)
        {
            bool isValid;
            bool isSsa = false;
            var matroska = new Matroska();
            SubtitleFormat format;

            if (matroskaSubtitleInfo.CodecId.ToUpper() == "S_VOBSUB")
            {
                if (batchMode)
                    return;
                LoadVobSubFromMatroska(matroskaSubtitleInfo, fileName);
                return;
            }
            if (matroskaSubtitleInfo.CodecId.ToUpper() == "S_HDMV/PGS")
            {
                if (batchMode)
                    return;
                LoadBluRaySubFromMatroska(matroskaSubtitleInfo, fileName);
                return;
            }

            ShowStatus(_language.ParsingMatroskaFile);
            Refresh();
            Cursor.Current = Cursors.WaitCursor;
            List<SubtitleSequence> sub = matroska.GetMatroskaSubtitle(fileName, (int)matroskaSubtitleInfo.TrackNumber, out isValid, MatroskaProgress);
            Cursor.Current = Cursors.Default;
            if (isValid)
            {
                MakeHistoryForUndo(_language.BeforeImportFromMatroskaFile);
                _subtitleListViewIndex = -1;
                if (!batchMode)
                    ResetSubtitle();
                _subtitle.Paragraphs.Clear();

                if (matroskaSubtitleInfo.CodecPrivate.ToLower().Contains("[script info]"))
                {
                    if (matroskaSubtitleInfo.CodecPrivate.ToLower().Contains("[V4 Styles]".ToLower()))
                        format = new SubStationAlpha();
                    else
                        format = new AdvancedSubStationAlpha();
                    isSsa = true;
                    if (_networkSession == null)
                    {
                        SubtitleListview1.ShowExtraColumn(Configuration.Settings.Language.General.Style);
                        SubtitleListview1.DisplayExtraFromExtra = true;
                    }
                }
                else
                {
                    format = new SubRip();
                    if (_networkSession == null && SubtitleListview1.IsExtraColumnVisible)
                        SubtitleListview1.HideExtraColumn();
                }

                comboBoxSubtitleFormats.SelectedIndexChanged -= ComboBoxSubtitleFormatsSelectedIndexChanged;
                SetCurrentFormat(format);
                comboBoxSubtitleFormats.SelectedIndexChanged += ComboBoxSubtitleFormatsSelectedIndexChanged;

                if (isSsa)
                {
                    foreach (Paragraph p in LoadMatroskaSSa(matroskaSubtitleInfo, fileName, 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);
                            }
                            else if (line.Trim().ToLower().StartsWith("dialogue:"))
                            {
                                eventsStarted = true;
                                fontsStarted = false;
                                graphicsStarted = false;
                            }
                            else if (line.Trim().ToLower() == "[events]")
                            {
                                eventsStarted = true;
                                fontsStarted = false;
                                graphicsStarted = false;
                            }
                            else if (line.Trim().ToLower() == "[fonts]")
                            {
                                eventsStarted = false;
                                fontsStarted = true;
                                graphicsStarted = false;
                            }
                            else if (line.Trim().ToLower() == "[graphics]")
                            {
                                eventsStarted = false;
                                fontsStarted = false;
                                graphicsStarted = true;
                            }
                        }
                        _subtitle.Header = header.ToString();
                    }
                }
                else
                {
                    foreach (SubtitleSequence p in sub)
                    {
                        _subtitle.Paragraphs.Add(new Paragraph(p.Text, p.StartMilliseconds, p.EndMilliseconds));
                    }
                }

                SetEncoding(Encoding.UTF8);
                ShowStatus(_language.SubtitleImportedFromMatroskaFile);
                _subtitle.Renumber(1);
                _subtitle.WasLoadedWithFrameNumbers = false;
                if (fileName.ToLower().EndsWith(".mkv") || fileName.ToLower().EndsWith(".mks"))
                {
                    _fileName = fileName.Substring(0, fileName.Length - 4);
                    Text = Title + " - " + _fileName;
                }
                else
                {
                    Text = Title;
                }
                _fileDateTime = new DateTime();

                _converted = true;

                if (batchMode)
                    return;

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

                ShowSource();
            }
        }
Пример #6
0
        internal Subtitle LoadMatroskaSubtitleForSync(MatroskaSubtitleInfo matroskaSubtitleInfo, string fileName)
        {
            Subtitle subtitle = new Subtitle();
            bool isValid;
            bool isSsa = false;
            var matroska = new Matroska();
            SubtitleFormat format;

            if (matroskaSubtitleInfo.CodecId.ToUpper() == "S_VOBSUB")
            {
                return subtitle;
            }
            if (matroskaSubtitleInfo.CodecId.ToUpper() == "S_HDMV/PGS")
            {
                return subtitle;
            }

            List<SubtitleSequence> sub = matroska.GetMatroskaSubtitle(fileName, (int)matroskaSubtitleInfo.TrackNumber, out isValid, MatroskaProgress);
            if (isValid)
            {
                 if (matroskaSubtitleInfo.CodecPrivate.ToLower().Contains("[script info]"))
                {
                    if (matroskaSubtitleInfo.CodecPrivate.ToLower().Contains("[V4 Styles]".ToLower()))
                        format = new SubStationAlpha();
                    else
                        format = new AdvancedSubStationAlpha();
                    isSsa = true;
                }
                else
                {
                    format = new SubRip();
                }

                if (isSsa)
                {
                    foreach (Paragraph p in LoadMatroskaSSa(matroskaSubtitleInfo, fileName, format, sub).Paragraphs)
                    {
                        subtitle.Paragraphs.Add(p);
                    }
                }
                else
                {
                    foreach (SubtitleSequence p in sub)
                    {
                        subtitle.Paragraphs.Add(new Paragraph(p.Text, p.StartMilliseconds, p.EndMilliseconds));
                    }
                }

            }
            return subtitle;
        }
Пример #7
0
 private void ImportSubtitleFromMatroskaFile(string fileName)
 {
     bool isValid;
     var matroska = new Matroska();
     var subtitleList = matroska.GetMatroskaSubtitleTracks(fileName, out isValid);
     if (isValid)
     {
         if (subtitleList.Count == 0)
         {
             MessageBox.Show(_language.NoSubtitlesFound);
         }
         else
         {
             if (ContinueNewOrExit())
             {
                 if (subtitleList.Count > 1)
                 {
                     MatroskaSubtitleChooser subtitleChooser = new MatroskaSubtitleChooser();
                     subtitleChooser.Initialize(subtitleList);
                     if (_loading)
                     {
                         subtitleChooser.Icon = (Icon)this.Icon.Clone();
                         subtitleChooser.ShowInTaskbar = true;
                         subtitleChooser.ShowIcon = true;
                     }
                     if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                     {
                         LoadMatroskaSubtitle(subtitleList[subtitleChooser.SelectedIndex], fileName, false);
                         if (Path.GetExtension(fileName).ToLower() == ".mkv")
                             OpenVideo(fileName);
                     }
                 }
                 else
                 {
                     LoadMatroskaSubtitle(subtitleList[0], fileName, false);
                     if (Path.GetExtension(fileName).ToLower() == ".mkv")
                         OpenVideo(fileName);
                 }
             }
         }
     }
     else
     {
         MessageBox.Show(string.Format(_language.NotAValidMatroskaFileX, fileName));
     }
 }
Пример #8
0
        private void BatchConvert(string[] args) // E.g.: /convert *.txt SubRip
        {
            const int ATTACH_PARENT_PROCESS = -1;
            if (!Utilities.IsRunningOnMac() && !Utilities.IsRunningOnLinux())
                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:msec] [/encoding:<encoding name>] [/fps:<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].ToLower() == "/list" || args[2].ToLower() == "-list"))
                {
                    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("    " + new CapMakerPlus().FriendlyName);
                    Console.WriteLine("    " + new Captionate().FriendlyName);
                    Console.WriteLine("    " + new Cavena890().FriendlyName);
                    Console.WriteLine("    " + new CheetahCaption().FriendlyName);
                    Console.WriteLine("    " + new Ebu().FriendlyName);
                    Console.WriteLine("    Matroska (.mkv)");
                    Console.WriteLine("    Matroska subtitle (.mks)");
                    Console.WriteLine("    " + new NciCaption().FriendlyName);
                    Console.WriteLine("    " + new AvidStl().FriendlyName);
                    Console.WriteLine("    " + new Pac().FriendlyName);
                    Console.WriteLine("    " + new Spt().FriendlyName);
                    Console.WriteLine("    " + new Ultech130().FriendlyName);
                }

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

            int count = 0;
            int converted = 0;
            int errors = 0;
            string inputDirectory = string.Empty;
            try
            {
                int max = args.Length;

                string pattern = args[2];
                string toFormat = args[3];
                string offset = string.Empty;
                for (int idx = 4; idx < max; idx++)
                    if (args.Length > idx && args[idx].ToLower().StartsWith("/offset:"))
                        offset = args[idx].ToLower();

                string fps = string.Empty;
                for (int idx = 4; idx < max; idx++)
                    if (args.Length > idx && args[idx].ToLower().StartsWith("/fps:"))
                        fps = args[idx].ToLower();
                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))
                    {
                        toolStripComboBoxFrameRate.Text = d.ToString(System.Globalization.CultureInfo.InvariantCulture);
                        Configuration.Settings.General.CurrentFrameRate = d;
                    }
                }

                string targetEncodingName = string.Empty;
                for (int idx = 4; idx < max; idx++)
                    if (args.Length > idx && args[idx].ToLower().StartsWith("/encoding:"))
                        targetEncodingName = args[idx].ToLower();
                Encoding 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;
                }

                string outputFolder = string.Empty;
                for (int idx = 4; idx < max; idx++)
                    if (args.Length > idx && args[idx].ToLower().StartsWith("/outputfolder:"))
                        outputFolder = args[idx].ToLower();
                if (outputFolder.Length > "/outputFolder:".Length)
                {
                    outputFolder = outputFolder.Remove(0, "/outputFolder:".Length);
                    if (!Directory.Exists(outputFolder))
                        outputFolder = string.Empty;
                }

                string inputFolder = Directory.GetCurrentDirectory();
                for (int idx = 4; idx < max; idx++)
                    if (args.Length > idx && args[idx].ToLower().StartsWith("/inputFolder:"))
                        inputFolder = args[idx].ToLower();
                if (inputFolder.Length > "/inputFolder:".Length)
                {
                    inputFolder = inputFolder.Remove(0, "/inputFolder:".Length);
                    if (!Directory.Exists(inputFolder))
                        inputFolder = Directory.GetCurrentDirectory();
                }

                string pacCodePage = string.Empty;
                for (int idx = 4; idx < max; idx++)
                    if (args.Length > idx && args[idx].ToLower().StartsWith("/pac-codepage:"))
                        pacCodePage = args[idx].ToLower();
                if (pacCodePage.Length > "/pac-codepage:".Length)
                    pacCodePage = pacCodePage.Remove(0, "/pac-codepage:".Length);

                bool overwrite = false;
                for (int idx=4; idx < max; idx++)
                    if (args.Length > idx && args[idx].ToLower() == ("/overwrite"))
                        overwrite = true;

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

                if (pattern.Contains(",") && !File.Exists(pattern))
                {
                    files = pattern.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    for (int k = 0; k < files.Length; k++)
                        files[k] = files[k].Trim();
                }
                else
                {
                    int indexOfDirectorySeparatorChar = pattern.LastIndexOf(Path.DirectorySeparatorChar.ToString());
                    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))
                    {
                        Encoding encoding;
                        var sub = new Subtitle();
                        SubtitleFormat format = null;
                        bool done = false;

                        if (Path.GetExtension(fileName).ToLower() == ".mkv" || Path.GetExtension(fileName).ToLower() == ".mks")
                        {
                            Matroska mkv = new Matroska();
                            bool isValid = false;
                            bool hasConstantFrameRate = false;
                            double frameRate = 0;
                            int width = 0;
                            int height = 0;
                            double milliseconds = 0;
                            string videoCodec = string.Empty;
                            mkv.GetMatroskaInfo(fileName, ref isValid, ref hasConstantFrameRate, ref frameRate, ref width, ref height, ref milliseconds, ref videoCodec);
                            if (isValid)
                            {
                                var subtitleList = mkv.GetMatroskaSubtitleTracks(fileName, out isValid);
                                if (subtitleList.Count > 0)
                                {
                                    foreach (MatroskaSubtitleInfo x in subtitleList)
                                    {
                                        if (x.CodecId.ToUpper() == "S_VOBSUB")
                                        {
                                            Console.WriteLine(string.Format("{0}: {1} - Cannot convert from VobSub image based format!", count, fileName, toFormat));
                                        }
                                        else if (x.CodecId.ToUpper() == "S_HDMV/PGS")
                                        {
                                            Console.WriteLine(string.Format("{0}: {1} - Cannot convert from Blu-ray image based format!", count, fileName, toFormat));
                                        }
                                        else
                                        {
                                            LoadMatroskaSubtitle(x, fileName, true);
                                            sub = _subtitle;
                                            format = GetCurrentSubtitleFormat();
                                            string newFileName = fileName;
                                            if (subtitleList.Count > 1)
                                                newFileName = fileName.Insert(fileName.Length - 4, "_" + x.TrackNumber +  "_" + x.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() != new AdvancedSubStationAlpha().Name.ToLower().Replace(" ", string.Empty) &&
                                                    toFormat.ToLower() != new SubStationAlpha().Name.ToLower().Replace(" ", string.Empty))
                                                {

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

                                                }
                                            }

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

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

                            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 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(string.Format("{0}: {1} - input file format unknown!", count, fileName, toFormat));
                            else
                                Console.WriteLine(string.Format("{0}: {1} - input file too large!", count, fileName, toFormat));
                        }
                        else if (!done)
                        {
                            BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, sub, format, overwrite, pacCodePage);
                        }
                    }
                    else
                    {
                        Console.WriteLine(string.Format("{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(string.Format("{0} file(s) converted", converted));
            Console.WriteLine();
            Console.Write(currentDir + ">");

            if (!Utilities.IsRunningOnMac() && !Utilities.IsRunningOnLinux())
                FreeConsole();

            if (count == converted && errors == 0)
                Environment.Exit(0);
            else
                Environment.Exit(1);
        }
Пример #9
0
        private void OpenSubtitle(string fileName, Encoding encoding, string videoFileName, string originalFileName)
        {
            if (File.Exists(fileName))
            {
                bool videoFileLoaded = false;
                string ext = Path.GetExtension(fileName).ToLower();

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

                openFileDialog1.InitialDirectory = Path.GetDirectoryName(fileName);

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

                if (ext == ".sup")
                {
                    if (IsBluRaySupFile(fileName))
                    {
                        ImportAndOcrBluRaySup(fileName, _loading);
                        return;
                    }
                    else if (IsSpDvdSupFile(fileName))
                    {
                        ImportAndOcrSpDvdSup(fileName, _loading);
                        return;
                    }
                }

                if (ext == ".mkv" || ext == ".mks")
                {
                    Matroska mkv = new Matroska();
                    bool isValid = false;
                    bool hasConstantFrameRate = false;
                    double frameRate = 0;
                    int width = 0;
                    int height = 0;
                    double milliseconds = 0;
                    string videoCodec = string.Empty;
                    mkv.GetMatroskaInfo(fileName, ref isValid, ref hasConstantFrameRate, ref frameRate, ref width, ref height, ref milliseconds, ref videoCodec);
                    if (isValid)
                    {
                        ImportSubtitleFromMatroskaFile(fileName);
                        return;
                    }
                }

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

                var fi = new FileInfo(fileName);

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

                if ((ext == ".m2ts") && fi.Length > 10000 && IsM2TransportStream(fileName))
                {
                    ImportSubtitleFromTransportStream(fileName);
                    return;
                }

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

                if (fi.Length > 1024 * 1024 * 10) // max 10 mb
                {

                    // retry bluray sup (file with wrong extension)
                    if (IsBluRaySupFile(fileName))
                    {
                        ImportAndOcrBluRaySup(fileName, _loading);
                        return;
                    }

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


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

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

                bool change = _changeSubtitleToString != SerializeSubtitle(_subtitle);
                if (change)
                    change = _lastDoNotPrompt != SerializeSubtitle(_subtitle);

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (format == null)
                {
                    try
                    {
                        var bdnXml = new BdnXml();
                        string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName));
                        var list = new List<string>();
                        foreach (string l in arr)
                            list.Add(l);
                        if (bdnXml.IsMine(list, fileName))
                        {
                            if (ContinueNewOrExit())
                            {
                                ImportAndOcrBdnXml(fileName, bdnXml, list);
                            }
                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                if (format == null)
                {
                    try
                    {
                        var fcpImage = new FinalCutProImage();
                        string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName));
                        var list = new List<string>();
                        foreach (string l in arr)
                            list.Add(l);
                        if (fcpImage.IsMine(list, fileName))
                        {
                            if (ContinueNewOrExit())
                            {
                                ImportAndOcrDost(fileName, fcpImage, list);
                            }
                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

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

                if (fileName.ToLower().EndsWith(".dost"))
                {
                    try
                    {
                        var dost = new Dost();
                        string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName));
                        var list = new List<string>();
                        foreach (string l in arr)
                            list.Add(l);
                        if (dost.IsMine(list, fileName))
                        {
                            if (ContinueNewOrExit())
                                ImportAndOcrDost(fileName, dost, list);
                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                if (format == null || format.Name == new Scenarist().Name)
                {
                    try
                    {
                        var son = new Son();
                        string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName));
                        var list = new List<string>();
                        foreach (string l in arr)
                            list.Add(l);
                        if (son.IsMine(list, fileName))
                        {
                            if (ContinueNewOrExit())
                                ImportAndOcrSon(fileName, son, list);
                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

                if (format == null || format.Name == new SubRip().Name)
                {
                    if (_subtitle.Paragraphs.Count > 1)
                    {
                        int imageCount = 0;
                        foreach (Paragraph p in _subtitle.Paragraphs)
                        {
                            string s = p.Text.ToLower();
                            if (s.EndsWith(".bmp") || s.EndsWith(".png") || s.EndsWith(".jpg") || s.EndsWith(".tif"))
                            {
                                imageCount++;
                            }
                        }
                        if (imageCount > 2 && imageCount >= _subtitle.Paragraphs.Count - 2)
                        {
                            if (ContinueNewOrExit())
                                ImportAndOcrSrt(fileName, _subtitle);
                            return;

                        }
                    }
                }

                if (format == null || format.Name == new Scenarist().Name)
                {
                    try
                    {
                        var sst = new SonicScenaristBitmaps();
                        string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName));
                        var list = new List<string>();
                        foreach (string l in arr)
                            list.Add(l);
                        if (sst.IsMine(list, fileName))
                        {
                            if (ContinueNewOrExit())
                                ImportAndOcrSst(fileName, sst, list);
                            return;
                        }
                    }
                    catch
                    {
                        format = null;
                    }
                }

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

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

                // retry bluray (file with wrong extension)
                if (format == null && fi.Length > 500 && IsBluRaySupFile(fileName))
                {
                    ImportAndOcrBluRaySup(fileName, _loading);
                    return;
                }

                // retry SP dvd (file with wrong extension)
                if (format == null && fi.Length > 500 && IsSpDvdSupFile(fileName))
                {
                    ImportAndOcrSpDvdSup(fileName, _loading);
                    return;
                }

                // check for idx file
                if (format == null && fi.Length > 100 && ext == ".idx")
                {
                    if (string.IsNullOrEmpty(_language.ErrorLoadIdx))
                        MessageBox.Show("Cannot read/edit .idx files. Idx files are a part of an idx/sub file pair (also called VobSub), and SE can open the .sub file.");
                    else
                        MessageBox.Show(_language.ErrorLoadIdx);
                    return;
                }

                // check for .rar file
                if (format == null && fi.Length > 100 && IsRarFile(fileName))
                {
                    if (string.IsNullOrEmpty(_language.ErrorLoadRar))
                        MessageBox.Show("This file seems to be a compressed .rar file. SE cannot open compressed files.");
                    else
                        MessageBox.Show(_language.ErrorLoadRar);
                    return;
                }

                // check for .zip file
                if (format == null && fi.Length > 100 && IsZipFile(fileName))
                {
                    if (string.IsNullOrEmpty(_language.ErrorLoadZip))
                        MessageBox.Show("This file seems to be a compressed .zip file. SE cannot open compressed files.");
                    else
                        MessageBox.Show(_language.ErrorLoadZip);
                    return;
                }


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

                        // check for RTF file
                        if (fileName.ToLower().EndsWith(".rtf") && !s.Trim().StartsWith("{\\rtf"))
                        {
                            var rtBox = new System.Windows.Forms.RichTextBox();
                            rtBox.Rtf = s;
                            s = rtBox.Text;
                        }
                        var uknownFormatImporter = new UknownFormatImporter();
                        uknownFormatImporter.UseFrames = true;
                        var genericParseSubtitle = uknownFormatImporter.AutoGuessImport(s.Replace(Environment.NewLine, "\n").Split('\n'));
                        if (genericParseSubtitle.Paragraphs.Count > 1)
                        {
                            _subtitle = genericParseSubtitle;
                            SetCurrentFormat(Configuration.Settings.General.DefaultSubtitleFormat);
                            SetEncoding(Configuration.Settings.General.DefaultEncoding);
                            encoding = GetCurrentEncoding();
                            justConverted = true;
                            format = GetCurrentSubtitleFormat();
                            ShowStatus("Guessed subtitle format via generic subtitle parser!");
                        }
                    }
                    catch
                    {
                    }
                }


                _fileDateTime = File.GetLastWriteTime(fileName);

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

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

                    foreach (Paragraph p in _subtitle.Paragraphs)
                    {
                        p.Text = p.Text.Replace("<і>", "<i>").Replace("</і>", "</i>");  // different unicode chars
                    }

                    _subtitleListViewIndex = -1;
                    SetCurrentFormat(format);
                    _subtitleAlternateFileName = null;
                    if (LoadAlternateSubtitleFile(originalFileName))
                        _subtitleAlternateFileName = originalFileName;


                    // Seungki begin
                    _splitDualSami = false;
                    if (Configuration.Settings.SubtitleSettings.SamiDisplayTwoClassesAsTwoSubtitles && format.GetType() == typeof(Sami) && Sami.GetStylesFromHeader(_subtitle.Header).Count == 2)
                    {
                        List<string> classes = Sami.GetStylesFromHeader(_subtitle.Header);
                        var s1 = new Subtitle(_subtitle);
                        var s2 = new Subtitle(_subtitle);
                        s1.Paragraphs.Clear();
                        s2.Paragraphs.Clear();
                        foreach (Paragraph p in _subtitle.Paragraphs)
                        {
                            if (p.Extra != null && p.Extra.ToLower() == classes[0].ToLower())
                                s1.Paragraphs.Add(p);
                            else
                                s2.Paragraphs.Add(p);
                        }
                        if (s1.Paragraphs.Count == 0 || s2.Paragraphs.Count == 0)
                            return;

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


                    textBoxSource.Text = _subtitle.ToText(format);
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    if (SubtitleListview1.Items.Count > 0)
                        SubtitleListview1.Items[0].Selected = true;
                    _findHelper = null;
                    _spellCheckForm = null;

                    if (_resetVideo)
                    {
                        _videoFileName = null;
                        _videoInfo = null;
                        _videoAudioTrackNumber = -1;
                        labelVideoInfo.Text = Configuration.Settings.Language.General.NoVideoLoaded;
                        audioVisualizer.WavePeaks = null;
                        audioVisualizer.ResetSpectrogram();
                        audioVisualizer.Invalidate();
                    }

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

                    if (Configuration.Settings.RecentFiles.Files.Count > 0 &&
                        Configuration.Settings.RecentFiles.Files[0].FileName == fileName)
                    {
                    }
                    else
                    {
                        Configuration.Settings.RecentFiles.Add(fileName, _videoFileName, _subtitleAlternateFileName);
                        Configuration.Settings.Save();
                        UpdateRecentFilesUI();
                    }
                    _fileName = fileName;
                    SetTitle();
                    ShowStatus(string.Format(_language.LoadedSubtitleX, _fileName));
                    _sourceViewChange = false;
                    _changeSubtitleToString = SerializeSubtitle(_subtitle);
                    _converted = false;
                    ResetHistory();

                    SetUndockedWindowsTitle();

                    if (justConverted)
                    {
                        _converted = true;
                        ShowStatus(string.Format(_language.LoadedSubtitleX, _fileName) + " - " + string.Format(_language.ConvertedToX, format.FriendlyName));
                    }
                    if (Configuration.Settings.General.AutoConvertToUtf8)
                        encoding = Encoding.UTF8;
                    SetEncoding(encoding);

                    if (format.GetType() == typeof(SubStationAlpha))
                    {
                        string errors = AdvancedSubStationAlpha.CheckForErrors(_subtitle.Header);
                        if (!string.IsNullOrEmpty(errors))
                            MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        errors = (format as SubStationAlpha).Errors;
                        if (!string.IsNullOrEmpty(errors))
                            MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else if (format.GetType() == typeof(AdvancedSubStationAlpha))
                    {
                        string errors = AdvancedSubStationAlpha.CheckForErrors(_subtitle.Header);
                        if (!string.IsNullOrEmpty(errors))
                            MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        errors = (format as AdvancedSubStationAlpha).Errors;
                        if (!string.IsNullOrEmpty(errors))
                            MessageBox.Show(errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else if (format.GetType() == typeof(SubRip))
                    {
                        string errors = (format as SubRip).Errors;
                        if (!string.IsNullOrEmpty(errors))
                            MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else if (format.GetType() == typeof(MicroDvd))
                    {
                        string errors = (format as MicroDvd).Errors;
                        if (!string.IsNullOrEmpty(errors))
                            MessageBox.Show(this, errors, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    var info = new FileInfo(fileName);
                    if (info.Length < 50)
                    {
                        _findHelper = null;
                        _spellCheckForm = null;
                        _videoFileName = null;
                        _videoInfo = null;
                        _videoAudioTrackNumber = -1;
                        labelVideoInfo.Text = Configuration.Settings.Language.General.NoVideoLoaded;
                        audioVisualizer.WavePeaks = null;
                        audioVisualizer.ResetSpectrogram();
                        audioVisualizer.Invalidate();

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

                        MessageBox.Show(_language.FileIsEmptyOrShort);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(fileName) && fileName.ToLower().EndsWith(".xml"))
                        {
                            string[] arr = File.ReadAllLines(fileName, Utilities.GetEncodingFromFile(fileName));
                            var sb = new StringBuilder();
                            foreach (string l in arr)
                                sb.AppendLine(l);
                            string xmlAsString = sb.ToString().Trim();
                            if (xmlAsString.Contains("http://www.w3.org/ns/ttml") && xmlAsString.Contains("<?xml version="))
                            {
                                var xml = new System.Xml.XmlDocument();
                                try
                                {
                                    xml.LoadXml(xmlAsString);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Timed text is not valid: " + ex.Message);
                                    return;
                                }
                            }

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

                        ShowUnknownSubtitle();
                        return;
                    }
                }

                if (!videoFileLoaded && mediaPlayer.VideoPlayer != null)
                {
                    mediaPlayer.VideoPlayer.DisposeVideoPlayer();
                    mediaPlayer.VideoPlayer = null;
                    timer1.Stop();
                }
            }
            else
            {
                MessageBox.Show(string.Format(_language.FileNotFound, fileName));
            }
        }
Пример #10
0
        private void pointSyncViaOtherSubtitleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SyncPointsSync pointSync = new SyncPointsSync();
            openFileDialog1.Title = _language.OpenOtherSubtitle;
            openFileDialog1.FileName = string.Empty;
            openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
            if (openFileDialog1.ShowDialog() == DialogResult.OK && File.Exists(openFileDialog1.FileName))
            {
                Subtitle sub = new Subtitle();
                Encoding enc;
                string fileName = openFileDialog1.FileName;

                //TODO: Check for mkv etc
                if (Path.GetExtension(fileName).ToLower() == ".sub" && IsVobSubFile(fileName, false))
                {
                    MessageBox.Show("VobSub files not supported here");
                    return;
                }

                if (Path.GetExtension(fileName).ToLower() == ".sup")
                {
                    if (IsBluRaySupFile(fileName))
                    {
                        MessageBox.Show("Bluray sup files not supported here");
                        return;
                    }
                    else if (IsSpDvdSupFile(fileName))
                    {
                        MessageBox.Show("Dvd sup files not supported here");
                        return;
                    }
                }

                if (Path.GetExtension(fileName).ToLower() == ".mkv" || Path.GetExtension(fileName).ToLower() == ".mks")
                {
                    Matroska mkv = new Matroska();
                    bool isValid = false;
                    bool hasConstantFrameRate = false;
                    double frameRate = 0;
                    int width = 0;
                    int height = 0;
                    double milliseconds = 0;
                    string videoCodec = string.Empty;
                    mkv.GetMatroskaInfo(fileName, ref isValid, ref hasConstantFrameRate, ref frameRate, ref width, ref height, ref milliseconds, ref videoCodec);
                    if (isValid)
                    {
                        var subtitleList = mkv.GetMatroskaSubtitleTracks(fileName, out isValid);
                        if (isValid)
                        {
                            if (subtitleList.Count == 0)
                            {
                                MessageBox.Show(_language.NoSubtitlesFound);
                                return;
                            }
                            else
                            {
                                if (subtitleList.Count > 1)
                                {
                                    MatroskaSubtitleChooser subtitleChooser = new MatroskaSubtitleChooser();
                                    subtitleChooser.Initialize(subtitleList);
                                    if (_loading)
                                    {
                                        subtitleChooser.Icon = (Icon)this.Icon.Clone();
                                        subtitleChooser.ShowInTaskbar = true;
                                        subtitleChooser.ShowIcon = true;
                                    }
                                    if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                                    {
                                        sub = LoadMatroskaSubtitleForSync(subtitleList[subtitleChooser.SelectedIndex], fileName);
                                    }
                                }
                                else
                                {
                                    sub = LoadMatroskaSubtitleForSync(subtitleList[0], fileName);
                                }
                            }
                        }
                    }
                }

                if (Path.GetExtension(fileName).ToLower() == ".divx" || Path.GetExtension(fileName).ToLower() == ".avi")
                {
                    MessageBox.Show("Divx files not supported here");
                    return;
                }

                var fi = new FileInfo(fileName);

                if ((Path.GetExtension(fileName).ToLower() == ".mp4" || Path.GetExtension(fileName).ToLower() == ".m4v" || Path.GetExtension(fileName).ToLower() == ".3gp")
                    && fi.Length > 10000)
                {
                    var mp4Parser = new Logic.Mp4.Mp4Parser(fileName);
                    var mp4SubtitleTracks = mp4Parser.GetSubtitleTracks();
                    if (mp4SubtitleTracks.Count == 0)
                    {
                        MessageBox.Show(_language.NoSubtitlesFound);
                        return;
                    }
                    else if (mp4SubtitleTracks.Count == 1)
                    {
                        sub = LoadMp4SubtitleForSync(fileName, mp4SubtitleTracks[0]);
                    }
                    else
                    {
                        var subtitleChooser = new MatroskaSubtitleChooser();
                        subtitleChooser.Initialize(mp4SubtitleTracks);
                        if (subtitleChooser.ShowDialog(this) == DialogResult.OK)
                        {
                            sub = LoadMp4SubtitleForSync(fileName, mp4SubtitleTracks[0]);
                        }
                    }
                }

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

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

                pointSync.Initialize(_subtitle, _fileName, _videoFileName, _videoAudioTrackNumber, fileName, sub);
                mediaPlayer.Pause();
                if (pointSync.ShowDialog(this) == DialogResult.OK)
                {
                    _subtitleListViewIndex = -1;
                    MakeHistoryForUndo(_language.BeforePointSynchronization);
                    _subtitle.Paragraphs.Clear();
                    foreach (Paragraph p in pointSync.FixedSubtitle.Paragraphs)
                        _subtitle.Paragraphs.Add(p);
                    _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                    ShowStatus(_language.PointSynchronizationDone);
                    ShowSource();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                }
                _videoFileName = pointSync.VideoFileName;
            }
        }
Пример #11
0
        private void buttonConvert_Click(object sender, EventArgs e)
        {
            if (listViewInputFiles.Items.Count == 0)
            {
                MessageBox.Show(Configuration.Settings.Language.BatchConvert.NothingToConvert);
                return;
            }

            if (!checkBoxOverwriteOriginalFiles.Checked)
            {
                if (textBoxOutputFolder.Text.Length < 2)
                {
                    MessageBox.Show(Configuration.Settings.Language.BatchConvert.PleaseChooseOutputFolder);
                    return;
                }
                else if (!Directory.Exists(textBoxOutputFolder.Text))
                {
                    try
                    {
                        Directory.CreateDirectory(textBoxOutputFolder.Text);
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                        return;
                    }
                }
            }

            _converting = true;
            buttonConvert.Enabled = false;
            buttonCancel.Enabled = false;
            progressBar1.Style = ProgressBarStyle.Blocks;
            progressBar1.Maximum = listViewInputFiles.Items.Count;
            progressBar1.Value = 0;
            progressBar1.Visible = progressBar1.Maximum > 2;
            string toFormat = comboBoxSubtitleFormats.Text;
            groupBoxOutput.Enabled = false;
            groupBoxConvertOptions.Enabled = false;
            buttonInputBrowse.Enabled = false;
            buttonSearchFolder.Enabled = false;
            _count = 0;
            _converted = 0;
            _errors = 0;
            _abort = false;

            BackgroundWorker worker1 = new BackgroundWorker();
            BackgroundWorker worker2 = new BackgroundWorker();
            BackgroundWorker worker3 = new BackgroundWorker();
            worker1.DoWork += new DoWorkEventHandler(DoThreadWork);
            worker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ThreadWorkerCompleted);
            worker2.DoWork += new DoWorkEventHandler(DoThreadWork);
            worker2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ThreadWorkerCompleted);
            worker3.DoWork += new DoWorkEventHandler(DoThreadWork);
            worker3.RunWorkerCompleted += new RunWorkerCompletedEventHandler(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;
                string friendlyName = item.SubItems[1].Text;

                try
                {
                    SubtitleFormat format = null;
                    Encoding encoding;
                    var sub = new Subtitle();
                    var fi = new FileInfo(fileName);
                    if (fi.Length < 1024 * 1024) // max 1 mb
                    {
                        format = sub.LoadSubtitle(fileName, out encoding, null);

                        if (format == null)
                        {
                            var ebu = new Ebu();
                            if (ebu.IsMine(null, fileName))
                            {
                                ebu.LoadSubtitle(sub, null, fileName);
                                format = ebu;
                            }
                        }
                        if (format == null)
                        {
                            var pac = new Pac();
                            if (pac.IsMine(null, fileName))
                            {
                                pac.LoadSubtitle(sub, null, fileName);
                                format = pac;
                            }
                        }
                        if (format == null)
                        {
                            var cavena890 = new Cavena890();
                            if (cavena890.IsMine(null, fileName))
                            {
                                cavena890.LoadSubtitle(sub, null, fileName);
                                format = cavena890;
                            }
                        }
                        if (format == null)
                        {
                            var spt = new Spt();
                            if (spt.IsMine(null, fileName))
                            {
                                spt.LoadSubtitle(sub, null, fileName);
                                format = spt;
                            }
                        }
                        if (format == null)
                        {
                            var cheetahCaption = new CheetahCaption();
                            if (cheetahCaption.IsMine(null, fileName))
                            {
                                cheetahCaption.LoadSubtitle(sub, null, fileName);
                                format = cheetahCaption;
                            }
                        }
                        if (format == null)
                        {
                            var capMakerPlus = new CapMakerPlus();
                            if (capMakerPlus.IsMine(null, fileName))
                            {
                                capMakerPlus.LoadSubtitle(sub, null, fileName);
                                format = capMakerPlus;
                            }
                        }
                        if (format == null)
                        {
                            var captionate = new Captionate();
                            if (captionate.IsMine(null, fileName))
                            {
                                captionate.LoadSubtitle(sub, null, fileName);
                                format = captionate;
                            }
                        }
                        if (format == null)
                        {
                            var ultech130 = new Ultech130();
                            if (ultech130.IsMine(null, fileName))
                            {
                                ultech130.LoadSubtitle(sub, null, fileName);
                                format = ultech130;
                            }
                        }
                        if (format == null)
                        {
                            var nciCaption = new NciCaption();
                            if (nciCaption.IsMine(null, fileName))
                            {
                                nciCaption.LoadSubtitle(sub, null, fileName);
                                format = nciCaption;
                            }
                        }

                        if (format == null)
                        {
                            var avidStl = new AvidStl();
                            if (avidStl.IsMine(null, fileName))
                            {
                                avidStl.LoadSubtitle(sub, null, fileName);
                                format = avidStl;
                            }
                        }

                        if (format == null)
                        {
                            var elr = new ELRStudioClosedCaption();
                            if (elr.IsMine(null, fileName))
                            {
                                elr.LoadSubtitle(sub, null, fileName);
                                format = elr;
                            }
                        }

                        if (format != null && format.GetType() == typeof(MicroDvd))
                        {
                            if (sub != null && sub.Paragraphs.Count > 0 && sub.Paragraphs[0].Duration.TotalMilliseconds < 1001)
                            {
                                if (sub.Paragraphs[0].Text.StartsWith("29.") || sub.Paragraphs[0].Text.StartsWith("23.") ||
                                    sub.Paragraphs[0].Text.StartsWith("29,") || sub.Paragraphs[0].Text.StartsWith("23,") ||
                                    sub.Paragraphs[0].Text == "24" || sub.Paragraphs[0].Text == "25" ||
                                    sub.Paragraphs[0].Text == "30" || sub.Paragraphs[0].Text == "60")
                                    sub.Paragraphs.RemoveAt(0);
                            }
                        }

                    }

                    List<Nikse.SubtitleEdit.Logic.BluRaySup.BluRaySupParser.PcsData> bluRaySubtitles = new List<Nikse.SubtitleEdit.Logic.BluRaySup.BluRaySupParser.PcsData>();
                    bool isVobSub = false;
                    bool isMatroska = false;
                    if (format == null && fileName.ToLower().EndsWith(".sup") && Main.IsBluRaySupFile(fileName))
                    {
                        var log = new StringBuilder();
                        bluRaySubtitles = BluRaySupParser.ParseBluRaySup(fileName, log);
                    }
                    else if (format == null && fileName.ToLower().EndsWith(".sub") && Main.HasVobSubHeader(fileName))
                    {
                        isVobSub = true;
                    }
                    else if (format == null && fileName.ToLower().EndsWith(".mkv") && item.SubItems[2].Text.StartsWith("Matroska"))
                    {
                        isMatroska = true;
                    }

                    if (format == null && bluRaySubtitles.Count == 0 && !isVobSub && !isMatroska)
                    {
                        if (progressBar1.Value < progressBar1.Maximum)
                            progressBar1.Value++;
                        labelStatus.Text = progressBar1.Value + " / " + progressBar1.Maximum;
                    }
                    else
                    {
                        if (isMatroska)
                        {
                            if (Path.GetExtension(fileName).ToLower() == ".mkv" || Path.GetExtension(fileName).ToLower() == ".mks")
                            {
                                Matroska mkv = new Matroska();
                                bool isValid = false;
                                bool hasConstantFrameRate = false;
                                double frameRate = 0;
                                int width = 0;
                                int height = 0;
                                double milliseconds = 0;
                                string videoCodec = string.Empty;
                                mkv.GetMatroskaInfo(fileName, ref isValid, ref hasConstantFrameRate, ref frameRate, ref width, ref height, ref milliseconds, ref videoCodec);
                                if (isValid)
                                {
                                    var subtitleList = mkv.GetMatroskaSubtitleTracks(fileName, out isValid);
                                    if (subtitleList.Count > 0)
                                    {
                                        foreach (MatroskaSubtitleInfo x in subtitleList)
                                        {
                                            if (x.CodecId.ToUpper() == "S_VOBSUB")
                                            {
                                                //TODO: convert from VobSub image based format
                                            }
                                            else if (x.CodecId.ToUpper() == "S_HDMV/PGS")
                                            {
                                                //TODO: convert from Blu-ray image based format
                                            }
                                            else if (x.CodecId.ToUpper() == "S_TEXT/UTF8" || x.CodecId.ToUpper() == "S_TEXT/SSA" || x.CodecId.ToUpper() == "S_TEXT/ASS")
                                            {
                                                _matroskaListViewItem = item;
                                                List<SubtitleSequence> mkvSub = mkv.GetMatroskaSubtitle(fileName, (int)x.TrackNumber, out isValid, MatroskaProgress);

                                                bool isSsa = false;
                                                if (x.CodecPrivate.ToLower().Contains("[script info]"))
                                                {
                                                    if (x.CodecPrivate.ToLower().Contains("[V4 Styles]".ToLower()))
                                                        format = new SubStationAlpha();
                                                    else
                                                        format = new AdvancedSubStationAlpha();
                                                    isSsa = true;
                                                }
                                                else
                                                {
                                                    format = new SubRip();
                                                }

                                                if (isSsa)
                                                {
                                                    foreach (Paragraph p in Main.LoadMatroskaSSa(x, fileName, format, mkvSub).Paragraphs)
                                                    {
                                                        sub.Paragraphs.Add(p);
                                                    }
                                                }
                                                else
                                                {
                                                    foreach (SubtitleSequence p in mkvSub)
                                                    {
                                                        sub.Paragraphs.Add(new Paragraph(p.Text, p.StartMilliseconds, p.EndMilliseconds));
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else if (bluRaySubtitles.Count > 0)
                        {
                            item.SubItems[3].Text = "OCR...";
                            var vobSubOcr = new VobSubOcr();
                            vobSubOcr.FileName = Path.GetFileName(fileName);
                            vobSubOcr.InitializeBatch(bluRaySubtitles, Configuration.Settings.VobSubOcr, fileName);
                            sub = vobSubOcr.SubtitleFromOcr;
                        }
                        else if (isVobSub)
                        {
                            item.SubItems[3].Text = "OCR...";
                            var vobSubOcr = new VobSubOcr();
                            vobSubOcr.InitializeBatch(fileName, Configuration.Settings.VobSubOcr, true);
                            sub = vobSubOcr.SubtitleFromOcr;
                        }

                        if (comboBoxSubtitleFormats.Text == new AdvancedSubStationAlpha().Name && _assStyle != null)
                        {
                            sub.Header = _assStyle;
                        }
                        else if (comboBoxSubtitleFormats.Text == new SubStationAlpha().Name && _ssaStyle != null)
                        {
                            sub.Header = _ssaStyle;
                        }

                        int prevIndex = -1;
                        foreach (Paragraph p in sub.Paragraphs)
                        {
                            string prevText = string.Empty;
                            var prev = sub.GetParagraphOrDefault(prevIndex);
                            if (prev != null)
                                prevText = prev.Text;
                            prevIndex++;

                            if (checkBoxRemoveTextForHI.Checked)
                            {
                                p.Text = _removeForHI.RemoveTextFromHearImpaired(p.Text, prevText);
                            }
                            if (checkBoxRemoveFormatting.Checked)
                            {
                                p.Text = Utilities.RemoveHtmlTags(p.Text);
                                if (p.Text.StartsWith("{") && p.Text.Length > 6 && p.Text[5] == '}')
                                    p.Text = p.Text.Remove(0, 6);
                                if (p.Text.StartsWith("{") && p.Text.Length > 6 && p.Text[4] == '}')
                                    p.Text = p.Text.Remove(0, 5);
                            }
                        }
                        if (checkBoxFixCasing.Checked)
                        {
                            _changeCasing.FixCasing(sub, Utilities.AutoDetectGoogleLanguage(sub));
                            _changeCasingNames.Initialize(sub);
                            _changeCasingNames.FixCasing();
                        }

                        double fromFrameRate;
                        double toFrameRate;
                        if (double.TryParse(comboBoxFrameRateFrom.Text, out fromFrameRate) &&
                            double.TryParse(comboBoxFrameRateTo.Text, out toFrameRate))
                        {
                            sub.ChangeFramerate(fromFrameRate, toFrameRate);
                        }

                        if (timeUpDownAdjust.TimeCode.TotalMilliseconds > 0.00001)
                        {
                            var totalMilliseconds = timeUpDownAdjust.TimeCode.TotalMilliseconds;
                            if (radioButtonShowEarlier.Checked)
                                totalMilliseconds *= -1;
                            sub.AddTimeToAllParagraphs(TimeSpan.FromMilliseconds(totalMilliseconds));
                        }

                        while (worker1.IsBusy && worker2.IsBusy && worker3.IsBusy)
                        {
                            Application.DoEvents();
                            System.Threading.Thread.Sleep(100);
                        }

                        ThreadDoWorkParameter parameter = new ThreadDoWorkParameter(checkBoxFixCommonErrors.Checked, checkBoxMultipleReplace.Checked, checkBoxSplitLongLines.Checked, checkBoxAutoBalance.Checked, checkBoxSetMinimumDisplayTimeBetweenSubs.Checked, item, sub, GetCurrentSubtitleFormat(), GetCurrentEncoding(), Configuration.Settings.Tools.BatchConvertLanguage, fileName, toFormat, format);
                        if (!worker1.IsBusy)
                            worker1.RunWorkerAsync(parameter);
                        else if (!worker2.IsBusy)
                            worker2.RunWorkerAsync(parameter);
                        else if (!worker3.IsBusy)
                            worker3.RunWorkerAsync(parameter);
                    }

                }
                catch
                {
                    if (progressBar1.Value < progressBar1.Maximum)
                        progressBar1.Value++;
                    labelStatus.Text = progressBar1.Value + " / " + progressBar1.Maximum;
                }
                index++;
            }
            while (worker1.IsBusy || worker2.IsBusy || worker3.IsBusy)
            {
                try
                {
                    Application.DoEvents();
                }
                catch
                {
                }
                System.Threading.Thread.Sleep(100);
            }
            _converting = false;
            labelStatus.Text = string.Empty;
            progressBar1.Visible = false;
            buttonConvert.Enabled = true;
            buttonCancel.Enabled = true;
            groupBoxOutput.Enabled = true;
            groupBoxConvertOptions.Enabled = true;
            buttonInputBrowse.Enabled = true;
            buttonSearchFolder.Enabled = true;
        }
Пример #12
0
        private void AddInputFile(string fileName)
        {
            try
            {
                FileInfo fi = new FileInfo(fileName);
                var item = new ListViewItem(fileName);
                item.SubItems.Add(Utilities.FormatBytesToDisplayFileSize(fi.Length));

                SubtitleFormat format = null;
                Encoding encoding;
                var sub = new Subtitle();
                var _subtitle = new Subtitle();
                if (fi.Length < 1024 * 1024) // max 1 mb
                {
                    format = sub.LoadSubtitle(fileName, out encoding, null);

                    if (format == null)
                    {
                        var ebu = new Ebu();
                        if (ebu.IsMine(null, fileName))
                        {
                            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 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)
                {
                    if (Main.IsBluRaySupFile(fileName))
                    {
                        item.SubItems.Add("Blu-ray");
                    }
                    else if (Main.HasVobSubHeader(fileName))
                    {
                        item.SubItems.Add("VobSub");
                    }
                    else if (Path.GetExtension(fileName).ToLower() == ".mkv" || Path.GetExtension(fileName).ToLower() == ".mks")
                    {
                        Matroska mkv = new Matroska();
                        bool isValid = false;
                        bool hasConstantFrameRate = false;
                        double frameRate = 0;
                        int width = 0;
                        int height = 0;
                        double milliseconds = 0;
                        string videoCodec = string.Empty;
                        mkv.GetMatroskaInfo(fileName, ref isValid, ref hasConstantFrameRate, ref frameRate, ref width, ref height, ref milliseconds, ref videoCodec);
                        int mkvCount = 0;
                        if (isValid)
                        {
                            var subtitleList = mkv.GetMatroskaSubtitleTracks(fileName, out isValid);
                            if (subtitleList.Count > 0)
                            {
                                foreach (MatroskaSubtitleInfo x in subtitleList)
                                {
                                    if (x.CodecId.ToUpper() == "S_VOBSUB")
                                    {
                                        //TODO: convert from VobSub image based format!
                                    }
                                    else if (x.CodecId.ToUpper() == "S_HDMV/PGS")
                                    {
                                        //TODO: convert from Blu-ray image based format!
                                    }
                                    else if (x.CodecId.ToUpper() == "S_TEXT/UTF8" || x.CodecId.ToUpper() == "S_TEXT/SSA" || x.CodecId.ToUpper() == "S_TEXT/ASS")
                                    {
                                        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
            {
            }
        }
Пример #13
0
        public List<SubtitleSequence> GetMatroskaSubtitle(string fileName, int trackNumber, out bool isValid, Matroska.LoadMatroskaCallback callback)
        {
            byte b;
            bool done;
            UInt32 matroskaId;
            int sizeOfSize;
            long dataSize;
            long afterPosition;
            bool endOfFile;
            _subtitleRipTrackNumber = trackNumber;

            f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            matroskaId = GetMatroskaId();
            if (matroskaId != 0x1A45DFA3) // matroska file must start with ebml header
            {
                isValid = false;
            }
            else
            {
                isValid = true;
                b = (byte)f.ReadByte();
                sizeOfSize = GetMatroskaVariableIntLength(b);
                dataSize = GetMatroskaDataSize(sizeOfSize, b);

                f.Seek(dataSize, SeekOrigin.Current);

                done = false;
                endOfFile = false;
                while (endOfFile == false && done == false)
                {
                    matroskaId = GetMatroskaId();
                    if (matroskaId == 0)
                    {
                        done = true;
                    }
                    else
                    {
                        b = (byte)f.ReadByte();
                        sizeOfSize = GetMatroskaVariableIntLength(b);
                        dataSize = GetMatroskaDataSize(sizeOfSize, b);

                        if (matroskaId == 0x1549A966) // segment info
                        {
                            afterPosition = f.Position + dataSize;
                            AnalyzeMatroskaSegmentInformation(afterPosition);
                            f.Seek(afterPosition, SeekOrigin.Begin);
                        }
                        else if (matroskaId == 0x1654AE6B)  // tracks
                        {
                            afterPosition = f.Position + dataSize;
                            AnalyzeMatroskaTracks();
                            f.Seek(afterPosition, SeekOrigin.Begin);
                        }
                        else if (matroskaId == 0x1F43B675) // cluster
                        {
                            afterPosition = f.Position + dataSize;
                            AnalyzeMatroskaCluster();
                            f.Seek(afterPosition, SeekOrigin.Begin);
                        }
                        else if (matroskaId != 0x18538067) // segment
                        {
                            f.Seek(dataSize, SeekOrigin.Current);
                        }
                    }
                    if (callback != null)
                        callback.Invoke(f.Position, f.Length);
                    endOfFile = f.Position >= f.Length;
                }
            }
            f.Close();
            f.Dispose();
            f = null;

            return _subtitleRip;
        }
Пример #14
0
        private void AddWareForm_Shown(object sender, EventArgs e)
        {
            Refresh();
            var audioTrackNames = new List<string>();
            var mkvAudioTrackNumbers = new Dictionary<int, int>();
            int numberOfAudioTracks = 0;
            if (labelVideoFileName.Text.Length > 1 && File.Exists(labelVideoFileName.Text))
            {
                if (labelVideoFileName.Text.ToLower().EndsWith(".mkv"))
                { // Choose for number of audio tracks in matroska files
                    try
                    {
                        var mkv = new Matroska(labelVideoFileName.Text);
                        if (mkv.IsValid)
                        {
                            var trackInfo = mkv.GetTrackInfo();
                            foreach (var ti in trackInfo)
                            {
                                if (ti.IsAudio)
                                {
                                    numberOfAudioTracks++;
                                    if (ti.CodecId != null && ti.Language != null)
                                        audioTrackNames.Add("#" + ti.TrackNumber + ": " + ti.CodecId.Replace("\0", string.Empty) + " - " + ti.Language.Replace("\0", string.Empty));
                                    else
                                        audioTrackNames.Add("#" + ti.TrackNumber.ToString());
                                    mkvAudioTrackNumbers.Add(mkvAudioTrackNumbers.Count, ti.TrackNumber);
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }
                else if (labelVideoFileName.Text.ToLower().EndsWith(".mp4") || labelVideoFileName.Text.ToLower().EndsWith(".m4v"))
                { // Choose for number of audio tracks in mp4 files
                    try
                    {
                        var mp4 = new Nikse.SubtitleEdit.Logic.Mp4.Mp4Parser(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());
                        }
                        numberOfAudioTracks = tracks.Count;
                    }
                    catch
                    {
                    }
                }

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

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

                // check for delay in matroska files
                if (labelVideoFileName.Text.ToLower().EndsWith(".mkv"))
                {
                    try
                    {
                        var mkv = new Matroska(labelVideoFileName.Text);
                        if (mkv.IsValid)
                        {
                            _delayInMilliseconds = (int)mkv.GetTrackStartTime(mkvAudioTrackNumbers[_audioTrackNumber]);
                        }
                    }
                    catch
                    {
                        _delayInMilliseconds = 0;
                    }
                }

                buttonRipWave_Click(null, null);
            }
            else if (_wavFileName != null)
            {
                FixWaveOnly();
            }
        }