Ejemplo n.º 1
0
        private void toolStripMenuItemInsertTextFromSub_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = _languageGeneral.OpenSubtitle;
            openFileDialog1.FileName = string.Empty;
            openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                if (!File.Exists(openFileDialog1.FileName))
                    return;

                var fi = new FileInfo(openFileDialog1.FileName);
                if (fi.Length > 1024 * 1024 * 10) // max 10 mb
                {
                    if (MessageBox.Show(string.Format(_language.FileXIsLargerThan10Mb + Environment.NewLine +
                                                      Environment.NewLine +
                                                      _language.ContinueAnyway,
                                                      openFileDialog1.FileName), Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                        return;
                }

                Encoding encoding = null;
                var tmp = new Subtitle();
                SubtitleFormat format = tmp.LoadSubtitle(openFileDialog1.FileName, out encoding, encoding);

                if (format != null)
                {
                    if (format.IsFrameBased)
                        tmp.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                    else
                        tmp.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                    if (Configuration.Settings.General.RemoveBlankLinesWhenOpening)
                        tmp.RemoveEmptyLines();

                    if (SubtitleListview1.SelectedIndices.Count < 1)
                        return;

                    MakeHistoryForUndo(_language.BeforeColumnShiftCellsDown);

                    int index = FirstSelectedIndex;
                    for (int i = 0; i < tmp.Paragraphs.Count; i++)
                    {

                        {
                            for (int k = _subtitle.Paragraphs.Count - 2; k > index; k--)
                            {
                                _subtitle.Paragraphs[k + 1].Text = _subtitle.Paragraphs[k].Text;
                            }
                        }
                    }
                    for (int i = 0; i + index < _subtitle.Paragraphs.Count && i < tmp.Paragraphs.Count; i++)
                        _subtitle.Paragraphs[index + i].Text = tmp.Paragraphs[i].Text;
                    if (IsFramesRelevant && CurrentFrameRate > 0)
                        _subtitle.CalculateFrameNumbersFromTimeCodesNoCheck(CurrentFrameRate);
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    SubtitleListview1.SelectIndexAndEnsureVisible(index, true);
                    RefreshSelectedParagraph();
                }
            }

        }
Ejemplo n.º 2
0
        private void AppendTextVisuallyToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (IsSubtitleLoaded)
            {
                ReloadFromSourceView();

                if (MessageBox.Show(_language.SubtitleAppendPrompt, _language.SubtitleAppendPromptTitle, MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
                {
                    openFileDialog1.Title = _language.OpenSubtitleToAppend;
                    openFileDialog1.FileName = string.Empty;
                    openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
                    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                    {
                        bool success = false;
                        string fileName = openFileDialog1.FileName;
                        if (File.Exists(fileName))
                        {
                            var subtitleToAppend = new Subtitle();
                            Encoding encoding;
                            SubtitleFormat format = null;

                            // do not allow blu-ray/vobsub
                            string extension = Path.GetExtension(fileName).ToLower();
                            if (extension == ".sub" && (IsVobSubFile(fileName, false) || IsSpDvdSupFile(fileName)))
                            {
                                format = null;
                            }
                            else if (extension == ".sup" && IsBluRaySupFile(fileName))
                            {
                                format = null;
                            }
                            else
                            {
                                format = subtitleToAppend.LoadSubtitle(fileName, out encoding, null);
                                if (GetCurrentSubtitleFormat().IsFrameBased)
                                    subtitleToAppend.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                                else
                                    subtitleToAppend.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);
                            }

                            if (format != null)
                            {
                                if (subtitleToAppend != null && subtitleToAppend.Paragraphs.Count > 1)
                                {
                                    var visualSync = new VisualSync();
                                    visualSync.Initialize(toolStripButtonVisualSync.Image as Bitmap, subtitleToAppend, _fileName, _language.AppendViaVisualSyncTitle, CurrentFrameRate);
                                    visualSync.ShowDialog(this);
                                    if (visualSync.OKPressed)
                                    {
                                        if (MessageBox.Show(_language.AppendSynchronizedSubtitlePrompt, _language.SubtitleAppendPromptTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            int start = _subtitle.Paragraphs.Count +1;
                                            var fr = CurrentFrameRate;
                                            MakeHistoryForUndo(_language.BeforeAppend);
                                            foreach (Paragraph p in visualSync.Paragraphs)
                                            {
                                                if (format.IsFrameBased)
                                                    p.CalculateFrameNumbersFromTimeCodes(fr);
                                                _subtitle.Paragraphs.Add(new Paragraph(p));
                                            }
                                            if (format.GetType() == typeof(AdvancedSubStationAlpha) && GetCurrentSubtitleFormat().GetType() == typeof(AdvancedSubStationAlpha))
                                            {
                                                List<string> currentStyles = new List<string>();
                                                if (_subtitle.Header != null)
                                                    currentStyles = AdvancedSubStationAlpha.GetStylesFromHeader(_subtitle.Header);
                                                foreach (string styleName in AdvancedSubStationAlpha.GetStylesFromHeader(subtitleToAppend.Header))
                                                {
                                                    bool alreadyExists = false;
                                                    foreach (string currentStyleName in currentStyles)
                                                    {
                                                        if (currentStyleName.ToLower().Trim() == styleName.ToLower().Trim())
                                                            alreadyExists = true;
                                                    }
                                                    if (!alreadyExists)
                                                    {
                                                        var newStyle = AdvancedSubStationAlpha.GetSsaStyle(styleName, subtitleToAppend.Header);
                                                        _subtitle.Header = AdvancedSubStationAlpha.AddSsaStyle(newStyle, _subtitle.Header);
                                                    }
                                                }
                                            }

                                            _subtitle.Renumber(1);

                                            ShowSource();
                                            SubtitleListview1.Fill(_subtitle, _subtitleAlternate);

                                            // select appended lines
                                            for (int i = start; i < _subtitle.Paragraphs.Count; i++)
                                                SubtitleListview1.Items[i].Selected = true;
                                            SubtitleListview1.EnsureVisible(start);

                                            ShowStatus(string.Format(_language.SubtitleAppendedX, fileName));
                                            success = true;
                                        }
                                    }
                                    visualSync.Dispose();
                                }
                            }
                        }
                        if (!success)
                            ShowStatus(_language.SubtitleNotAppended);
                    }
                }
            }
            else
            {
                MessageBox.Show(_language.NoSubtitleLoaded, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Ejemplo n.º 3
0
        private bool LoadAlternateSubtitleFile(string fileName)
        {
            if (!File.Exists(fileName))
                return false;

            if (Path.GetExtension(fileName).ToLower() == ".sub" && IsVobSubFile(fileName, false))
                return false;

            var fi = new FileInfo(fileName);
            if (fi.Length > 1024 * 1024 * 10) // max 10 mb
            {
                if (MessageBox.Show(string.Format(_language.FileXIsLargerThan10Mb + Environment.NewLine +
                                                    Environment.NewLine +
                                                    _language.ContinueAnyway,
                                                    fileName), Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                    return false;
            }

            Encoding encoding;
            _subtitleAlternate = new Subtitle();
            _subtitleAlternateFileName = fileName;
            SubtitleFormat format = _subtitleAlternate.LoadSubtitle(fileName, out encoding, null);

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


            if (format == null)
                return false;

            if (format.IsFrameBased)
                _subtitleAlternate.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
            else
                _subtitleAlternate.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

            SetupAlternateEdit();
            return true;
        }
Ejemplo n.º 4
0
        private void ToolStripMenuItemInsertSubtitleClick(object sender, EventArgs e)
        {
            openFileDialog1.Title = _languageGeneral.OpenSubtitle;
            openFileDialog1.FileName = string.Empty;
            openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                if (!File.Exists(openFileDialog1.FileName))
                    return;

                var fi = new FileInfo(openFileDialog1.FileName);
                if (fi.Length > 1024 * 1024 * 10) // max 10 mb
                {
                    if (MessageBox.Show(string.Format(_language.FileXIsLargerThan10Mb + Environment.NewLine +
                                                      Environment.NewLine +
                                                      _language.ContinueAnyway,
                                                      openFileDialog1.FileName), Title, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                        return;
                }

                MakeHistoryForUndo(string.Format(_language.BeforeInsertLine, openFileDialog1.FileName));

                Encoding encoding = null;
                var subtitle = new Subtitle();
                SubtitleFormat format = subtitle.LoadSubtitle(openFileDialog1.FileName, out encoding, encoding);

                if (format != null)
                {
                    SaveSubtitleListviewIndexes();
                    if (format.IsFrameBased)
                        subtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                    else
                        subtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                    if (Configuration.Settings.General.RemoveBlankLinesWhenOpening)
                        subtitle.RemoveEmptyLines();

                    int index = FirstSelectedIndex + 1;
                    if (index < 0)
                        index = 0;
                    foreach (Paragraph p in subtitle.Paragraphs)
                    {
                        _subtitle.Paragraphs.Insert(index, new Paragraph(p));
                        index++;
                    }

                    if (Configuration.Settings.General.AllowEditOfOriginalSubtitle && _subtitleAlternate != null && _subtitleAlternate.Paragraphs.Count > 0)
                    {
                        index = FirstSelectedIndex;
                        if (index < 0)
                            index = 0;
                        Paragraph current = _subtitle.GetParagraphOrDefault(index);
                        if (current != null)
                        {
                            Paragraph original = Utilities.GetOriginalParagraph(index, current, _subtitleAlternate.Paragraphs);
                            if (original != null)
                            {
                                index = _subtitleAlternate.GetIndex(original);
                                foreach (Paragraph p in subtitle.Paragraphs)
                                {
                                    _subtitleAlternate.Paragraphs.Insert(index, new Paragraph(p));
                                    index++;
                                }
                                if (subtitle.Paragraphs.Count > 0)
                                    _subtitleAlternate.Renumber(1);
                            }
                        }
                    }
                    _subtitle.Renumber(1);
                    ShowSource();
                    SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                    RestoreSubtitleListviewIndexes();
                }
            }
        }
Ejemplo n.º 5
0
        public static void Convert(string title, string[] args) // E.g.: /convert *.txt SubRip
        {
            const int ATTACH_PARENT_PROCESS = -1;

            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
            {
                NativeMethods.AttachConsole(ATTACH_PARENT_PROCESS);
            }

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

            string currentDir = Directory.GetCurrentDirectory();

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

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

            int count     = 0;
            int converted = 0;
            int errors    = 0;

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

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

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

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

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

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

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

                bool overwrite       = GetArgument(args, "/overwrite", string.Empty).Equals("/overwrite");
                bool removeTextForHi = GetArgument(args, "/removetextforhi", string.Empty).Equals("/removetextforhi");
                bool fixCommonErrors = GetArgument(args, "/fixcommonerrors", string.Empty).Equals("/fixcommonerrors");
                bool redoCasing      = GetArgument(args, "/redocasing", string.Empty).Equals("/redocasing");

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

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

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

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

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

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

                                                if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha))
                                                {
                                                    if (toFormat.ToLower() != AdvancedSubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty) &&
                                                        toFormat.ToLower() != SubStationAlpha.NameOfFormat.ToLower().Replace(" ", string.Empty))
                                                    {
                                                        foreach (SubtitleFormat sf in formats)
                                                        {
                                                            if (sf.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || sf.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))
                                                            {
                                                                format.RemoveNativeFormatting(sub, sf);
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }

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

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

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

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

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

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

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

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

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

            if (count == converted && errors == 0)
            {
                Environment.Exit(0);
            }
            else
            {
                Environment.Exit(1);
            }
        }
        // E.g.: /convert *.txt SubRip
        public static void Convert(string title, string[] args)
        {
            const int attachParentProcess = -1;
            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
                NativeMethods.AttachConsole(attachParentProcess);

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

            string currentDir = Directory.GetCurrentDirectory();

            if (args.Length < 4)
            {
                bool isCommandList =
                    args[2].Equals("/list", StringComparison.OrdinalIgnoreCase) ||
                    args[2].Equals("-list", StringComparison.OrdinalIgnoreCase);

                if (args.Length == 3 && isCommandList)
                {
                    Console.WriteLine("- Supported formats (input/output):");
                    foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
                    {
                        Console.WriteLine("    " + format.Name.Replace(" ", string.Empty));
                    }

                    Console.WriteLine();
                    Console.WriteLine("- Supported formats (input only):");
                    Console.WriteLine("    " + CapMakerPlus.NameOfFormat);
                    Console.WriteLine("    " + Captionate.NameOfFormat);
                    Console.WriteLine("    " + Cavena890.NameOfFormat);
                    Console.WriteLine("    " + CheetahCaption.NameOfFormat);
                    Console.WriteLine("    " + Chk.NameOfFormat);
                    Console.WriteLine("    Matroska (.mkv)");
                    Console.WriteLine("    Matroska subtitle (.mks)");
                    Console.WriteLine("    " + NciCaption.NameOfFormat);
                    Console.WriteLine("    " + AvidStl.NameOfFormat);
                    Console.WriteLine("    " + Pac.NameOfFormat);
                    Console.WriteLine("    " + Spt.NameOfFormat);
                    Console.WriteLine("    " + Ultech130.NameOfFormat);
                }

                Console.WriteLine();
                Console.Write(currentDir + ">");

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

                Environment.Exit(1);
            }

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

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

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

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

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

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

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

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

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

                if (pattern.Contains(',') && !File.Exists(pattern))
                {
                    files = pattern.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    for (int k = 0; k < files.Length; k++)
                    {
                        files[k] = files[k].Trim();
                    }
                }
                else
                {
                    int indexOfDirectorySeparatorChar = pattern.LastIndexOf(Path.DirectorySeparatorChar);
                    if (indexOfDirectorySeparatorChar > 0 && indexOfDirectorySeparatorChar < pattern.Length)
                    {
                        pattern = pattern.Substring(indexOfDirectorySeparatorChar + 1);
                        inputDirectory = args[2].Substring(0, indexOfDirectorySeparatorChar);
                    }

                    files = Directory.GetFiles(inputDirectory, pattern);
                }

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

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

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

                        if (Path.GetExtension(fileName).Equals(".mkv", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(fileName).Equals(".mks", StringComparison.OrdinalIgnoreCase))
                        {
                            using (var matroska = new MatroskaFile(fileName))
                            {
                                if (matroska.IsValid)
                                {
                                    var tracks = matroska.GetTracks();
                                    if (tracks.Count > 0)
                                    {
                                        foreach (var track in tracks)
                                        {
                                            if (track.CodecId.Equals("S_VOBSUB", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Console.WriteLine("{0}: {1} - Cannot convert from VobSub image based format!", fileName, toFormat);
                                            }
                                            else if (track.CodecId.Equals("S_HDMV/PGS", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Console.WriteLine("{0}: {1} - Cannot convert from Blu-ray image based format!", fileName, toFormat);
                                            }
                                            else
                                            {
                                                format = ConvertToMatroska(matroska, track, format, sub, fileName, tracks, toFormat, formats, offset, targetEncoding, outputFolder, count, overwrite, pacCodePage, targetFrameRate, ref converted, ref errors, ref done);
                                            }
                                        }
                                    }
                                }
                            }
                        }

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

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

                            format = GetSubtitleFormat(format, fileName, sub, pacCodePage);
                        }

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

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

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

            if (count == converted && errors == 0)
            {
                Environment.Exit(0);
            }
            else
            {
                Environment.Exit(1);
            }
        }
Ejemplo n.º 7
0
        private void VerifyDragDrop(ListView listView, DragEventArgs e)
        {
            var files = e.Data.GetData(DataFormats.FileDrop) as string[];
            if (files.Length > 1)
            {
                MessageBox.Show(Configuration.Settings.Language.Main.DropOnlyOneFile,
                    "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string filePath = files[0];
            var listExt = new List<string>();
            foreach (var s in Utilities.GetOpenDialogFilter().Split("*".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                if (s.EndsWith(";"))
                    listExt.Add(s.Trim(';'));
            }
            if (!listExt.Contains(Path.GetExtension(filePath)))
                return;
            if (Main.HasVobSubHeader(filePath) || Main.IsBluRaySupFile(filePath))
            {
                MessageBox.Show(Configuration.Settings.Language.CompareSubtitles.CannotCompareWithImageBasedSubtitles);
                return;
            }
            Encoding encoding;
            if (listView.Name == "subtitleListView1")
            {
                _subtitle1 = new Subtitle();
                _subtitle1.LoadSubtitle(filePath, out encoding, null);
                subtitleListView1.Fill(_subtitle1);
                subtitleListView1.SelectIndexAndEnsureVisible(0);
                subtitleListView2.SelectIndexAndEnsureVisible(0);
                labelSubtitle1.Text = filePath;
                _language1 = Utilities.AutoDetectGoogleLanguage(_subtitle1);
                if (_subtitle1.Paragraphs.Count > 0)
                    CompareSubtitles();
            }
            else
            {
                _subtitle2 = new Subtitle();
                _subtitle2.LoadSubtitle(filePath, out encoding, null);
                subtitleListView2.Fill(_subtitle2);
                subtitleListView1.SelectIndexAndEnsureVisible(0);
                subtitleListView2.SelectIndexAndEnsureVisible(0);
                labelSubtitle2.Text = filePath;
                if (_subtitle2.Paragraphs.Count > 0)
                    CompareSubtitles();
            }
        }
Ejemplo n.º 8
0
        private void AddInputFile(string fileName)
        {
            try
            {
                var fi = new FileInfo(fileName);
                var item = new ListViewItem(fileName);
                item.SubItems.Add(Utilities.FormatBytesToDisplayFileSize(fi.Length));

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

                    if (format == null)
                    {
                        var ebu = new Ebu();
                        if (ebu.IsMine(null, fileName))
                        {
                            format = ebu;
                        }
                    }
                    if (format == null)
                    {
                        var pac = new Pac();
                        if (pac.IsMine(null, fileName))
                        {
                            format = pac;
                        }
                    }
                    if (format == null)
                    {
                        var cavena890 = new Cavena890();
                        if (cavena890.IsMine(null, fileName))
                        {
                            format = cavena890;
                        }
                    }
                    if (format == null)
                    {
                        var spt = new Spt();
                        if (spt.IsMine(null, fileName))
                        {
                            format = spt;
                        }
                    }
                    if (format == null)
                    {
                        var cheetahCaption = new CheetahCaption();
                        if (cheetahCaption.IsMine(null, fileName))
                        {
                            format = cheetahCaption;
                        }
                    }
                    if (format == null)
                    {
                        var 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")
                    {
                        var 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
            {
            }
        }
Ejemplo n.º 9
0
        private void importNewTimeCodesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = Configuration.Settings.Language.General.OpenSubtitle;
            openFileDialog1.FileName = string.Empty;
            openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;
                if (!File.Exists(fileName))
                    return;

                var fi = new FileInfo(fileName);
                if (fi.Length > 1024 * 1024 * 10) // max 10 mb
                {
                    if (MessageBox.Show(string.Format(Configuration.Settings.Language.Main.FileXIsLargerThan10MB + Environment.NewLine +
                                                      Environment.NewLine +
                                                      Configuration.Settings.Language.Main.ContinueAnyway,
                                                      fileName), Text, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                        return;
                }

                Subtitle sub = new Subtitle();
                Encoding encoding;
                SubtitleFormat format = sub.LoadSubtitle(fileName, out encoding, null);
                if (format == null)
                    return;

                int index = 0;
                foreach (Paragraph p in sub.Paragraphs)
                {
                    if (index < _subtitle.Paragraphs.Count)
                    {
                        Paragraph currentP = _subtitle.Paragraphs[index];
                        currentP.StartTime.TotalMilliseconds = p.StartTime.TotalMilliseconds;
                        currentP.EndTime.TotalMilliseconds = p.EndTime.TotalMilliseconds;
                        subtitleListView1.SetStartTime(index, currentP);
                    }
                    index++;
                }
            }
        }
Ejemplo n.º 10
0
        private void ButtonOpenSubtitle2Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = string.Empty;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (Main.HasVobSubHeader(openFileDialog1.FileName) || Main.IsBluRaySupFile(openFileDialog1.FileName))
                {
                    MessageBox.Show(Configuration.Settings.Language.CompareSubtitles.CannotCompareWithImageBasedSubtitles);
                    return;
                }
                _subtitle2 = new Subtitle();
                Encoding encoding;
                _subtitle2.LoadSubtitle(openFileDialog1.FileName, out encoding, null);
                subtitleListView2.Fill(_subtitle2);
                subtitleListView1.SelectIndexAndEnsureVisible(0);
                subtitleListView2.SelectIndexAndEnsureVisible(0);
                labelSubtitle2.Text = openFileDialog1.FileName;
                if (_subtitle2.Paragraphs.Count > 0)
                    CompareSubtitles();
            }
        }
Ejemplo n.º 11
0
        private void buttonExport_Click(object sender, EventArgs e)
        {
            if (listViewStyles.SelectedItems.Count != 1)
                return;

            string styleName = listViewStyles.SelectedItems[0].Text;

            saveFileDialogStyle.Title = Configuration.Settings.Language.SubStationAlphaStyles.ExportStyleToFile;
            saveFileDialogStyle.InitialDirectory = Configuration.DataDirectory;
            if (_isSubStationAlpha)
            {
                saveFileDialogStyle.Filter = new SubStationAlpha().Name + "|*.ssa|" + Configuration.Settings.Language.General.AllFiles + "|*.*";
                saveFileDialogStyle.FileName = "my_styles.ssa";
            }
            else
            {
                saveFileDialogStyle.Filter = new AdvancedSubStationAlpha().Name + "|*.ass|" + Configuration.Settings.Language.General.AllFiles + "|*.*";
                saveFileDialogStyle.FileName = "my_styles.ass";
            }

            if (saveFileDialogStyle.ShowDialog(this) == DialogResult.OK)
            {
                if (File.Exists(saveFileDialogStyle.FileName))
                {
                    Encoding encoding = null;
                    var s = new Subtitle();
                    var format = s.LoadSubtitle(saveFileDialogStyle.FileName, out encoding, null);
                    if (format == null)
                    {
                        MessageBox.Show("Not subtitle format: " + _format.Name);
                        return;
                    }
                    else if (format.Name != _format.Name)
                    {
                        MessageBox.Show(string.Format("Cannot save {1} style in {0} file!", format.Name, _format.Name));
                        return;
                    }
                    else
                    {
                        var sb = new StringBuilder();
                        bool stylesOn = false;
                        bool done = false;
                        string styleFormat = "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding";
                        foreach (string line in File.ReadAllLines(saveFileDialogStyle.FileName))
                        {
                            if (line.ToLower().StartsWith("format:"))
                            {
                                styleFormat = line;
                            }
                            else if (line.ToLower().StartsWith("style:"))
                            {
                                stylesOn = true;
                            }
                            else if (stylesOn && !done)
                            {
                                done = true;
                                SsaStyle style = GetSsaStyle(styleName);
                                if (_isSubStationAlpha)
                                {
                                    sb.AppendLine(style.ToRawSsa(styleFormat));
                                }
                                else
                                {
                                    sb.AppendLine(style.ToRawAss(styleFormat));
                                }
                            }
                            sb.AppendLine(line);
                            if (stylesOn && line.Replace(" ", string.Empty).Trim().ToLower().StartsWith("style:" + styleName.Replace(" ", string.Empty).Trim().ToLower() + ","))
                            {
                                MessageBox.Show(string.Format(Configuration.Settings.Language.SubStationAlphaStyles.StyleAlreadyExits, styleName));
                                return;
                            }
                        }
                        File.WriteAllText(saveFileDialogStyle.FileName, sb.ToString(), Encoding.UTF8);
                    }
                }
                else
                {
                    var sb = new StringBuilder();
                    foreach (string line in Header.Replace(Environment.NewLine, "\n").Split('\n'))
                    {
                        if (line.ToLower().StartsWith("style:"))
                        {
                            if (line.ToLower().Replace(" ", string.Empty).StartsWith("style:" + styleName.ToLower().Trim()))
                                sb.AppendLine(line);
                        }
                        else
                        {
                            sb.AppendLine(line);
                        }
                    }
                    string content = sb.ToString();
                    if (content.Trim().EndsWith("[Events]"))
                    {
                        content = content.Trim() + Environment.NewLine +
                            "Format: Layer, Start, End, Style, Actor, MarginL, MarginR, MarginV, Effect, Text" + Environment.NewLine +
                            "Dialogue: 0,0:00:31.91,0:00:33.91,Default,,0,0,0,,My Styles :)";
                    }
                    File.WriteAllText(saveFileDialogStyle.FileName, content, Encoding.UTF8);
                }
            }
            if (!string.IsNullOrEmpty(Configuration.Settings.Language.SubStationAlphaStyles.StyleXImportedFromFileY)) // TODO: Remove in 3.4
                labelStatus.Text = string.Format(Configuration.Settings.Language.SubStationAlphaStyles.StyleXExportedToFileY, styleName, saveFileDialogStyle.FileName);
            timerClearStatus.Start();
        }
Ejemplo n.º 12
0
        private void buttonImport_Click(object sender, EventArgs e)
        {
            openFileDialogImport.Title = Configuration.Settings.Language.SubStationAlphaStyles.ImportStyleFromFile;
            openFileDialogImport.InitialDirectory = Configuration.DataDirectory;
            if (_isSubStationAlpha)
            {
                openFileDialogImport.Filter = new SubStationAlpha().Name + "|*.ssa|" + Configuration.Settings.Language.General.AllFiles + "|*.*";
                saveFileDialogStyle.FileName = "my_styles.ssa";
            }
            else
            {
                openFileDialogImport.Filter = new AdvancedSubStationAlpha().Name + "|*.ass|" + Configuration.Settings.Language.General.AllFiles + "|*.*";
                saveFileDialogStyle.FileName = "my_styles.ass";
            }

            if (openFileDialogImport.ShowDialog(this) == DialogResult.OK)
            {
                Encoding encoding = null;
                var s = new Subtitle();
                var format = s.LoadSubtitle(openFileDialogImport.FileName, out encoding, null);
                if (format != null && format.HasStyleSupport)
                {
                    var styles = AdvancedSubStationAlpha.GetStylesFromHeader(s.Header);
                    if (styles.Count > 0)
                    {
                        var cs = new ChooseStyle(s, format.GetType() == typeof(SubStationAlpha));
                        if (cs.ShowDialog(this) == DialogResult.OK && cs.SelectedStyleName != null)
                        {
                            SsaStyle style = AdvancedSubStationAlpha.GetSsaStyle(cs.SelectedStyleName, s.Header);
                            if (GetSsaStyle(style.Name).LoadedFromHeader)
                            {
                                int count = 2;
                                bool doRepeat = GetSsaStyle(style.Name + count.ToString()).LoadedFromHeader;
                                while (doRepeat)
                                {
                                    doRepeat = GetSsaStyle(style.Name + count.ToString()).LoadedFromHeader;
                                    count++;
                                }
                                style.RawLine = style.RawLine.Replace(" " + style.Name + ",", " " + style.Name + count.ToString() + ",");
                                style.Name = style.Name + count.ToString();
                            }

                            _doUpdate = false;
                            AddStyle(listViewStyles, style, _subtitle, _isSubStationAlpha);
                            SsaStyle oldStyle = GetSsaStyle(listViewStyles.Items[0].Text);
                            Header = Header.Trim();
                            if (Header.EndsWith("[Events]"))
                            {
                                Header = Header.Substring(0, Header.Length - "[Events]".Length).Trim();
                                Header += Environment.NewLine + style.RawLine;
                                Header += Environment.NewLine + Environment.NewLine + "[Events]" + Environment.NewLine;
                            }
                            else
                            {
                                Header = Header.Trim() + Environment.NewLine + style.RawLine + Environment.NewLine;
                            }

                            listViewStyles.Items[listViewStyles.Items.Count - 1].Selected = true;
                            listViewStyles.Items[listViewStyles.Items.Count - 1].EnsureVisible();
                            listViewStyles.Items[listViewStyles.Items.Count - 1].Focused = true;
                            textBoxStyleName.Text = style.Name;
                            textBoxStyleName.Focus();
                            _doUpdate = true;
                            SetControlsFromStyle(style);
                            listViewStyles_SelectedIndexChanged(null, null);

                            if (!string.IsNullOrEmpty(Configuration.Settings.Language.SubStationAlphaStyles.StyleXImportedFromFileY)) // TODO: Remove in 3.4
                                labelStatus.Text = string.Format(Configuration.Settings.Language.SubStationAlphaStyles.StyleXImportedFromFileY, style.Name, openFileDialogImport.FileName);
                            timerClearStatus.Start();
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
        private void ButtonOpenSubtitle2Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = string.Empty;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (Main.HasVobSubHeader(openFileDialog1.FileName) || Main.IsBluRaySupFile(openFileDialog1.FileName))
                {
                    MessageBox.Show(Configuration.Settings.Language.CompareSubtitles.CannotCompareWithImageBasedSubtitles);
                    return;
                }
                _subtitle2 = new Subtitle();
                Encoding encoding;
                var format = _subtitle2.LoadSubtitle(openFileDialog1.FileName, out encoding, null);
                if (format == null)
                {
                    var pac = new Pac();
                    if (pac.IsMine(null, openFileDialog1.FileName))
                    {
                        pac.BatchMode = true;
                        pac.LoadSubtitle(_subtitle2, null, openFileDialog1.FileName);
                        format = pac;
                    }
                }
                if (format == null)
                {
                    var cavena890 = new Cavena890();
                    if (cavena890.IsMine(null, openFileDialog1.FileName))
                    {
                        cavena890.LoadSubtitle(_subtitle2, null, openFileDialog1.FileName);
                        format = cavena890;
                    }
                }

                subtitleListView2.Fill(_subtitle2);
                subtitleListView1.SelectIndexAndEnsureVisible(0);
                subtitleListView2.SelectIndexAndEnsureVisible(0);
                labelSubtitle2.Text = openFileDialog1.FileName;
                if (_subtitle2.Paragraphs.Count > 0)
                    CompareSubtitles();
            }
        }
Ejemplo n.º 14
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);
        }
        /// <summary>
        /// The sort and load.
        /// </summary>
        private void SortAndLoad()
        {
            this.JoinedFormat = new SubRip(); // default subtitle format
            string header = null;
            SubtitleFormat lastFormat = null;
            var subtitles = new List<Subtitle>();
            for (int k = 0; k < this._fileNamesToJoin.Count; k++)
            {
                string fileName = this._fileNamesToJoin[k];
                try
                {
                    var sub = new Subtitle();
                    Encoding encoding;
                    var format = sub.LoadSubtitle(fileName, out encoding, null);
                    if (format == null)
                    {
                        for (int j = k; j < this._fileNamesToJoin.Count; j++)
                        {
                            this._fileNamesToJoin.RemoveAt(j);
                        }

                        MessageBox.Show("Unkown subtitle format: " + fileName);
                        return;
                    }

                    if (sub.Header != null)
                    {
                        header = sub.Header;
                    }

                    if (lastFormat == null || lastFormat.FriendlyName == format.FriendlyName)
                    {
                        lastFormat = format;
                    }
                    else
                    {
                        lastFormat = new SubRip(); // default subtitle format
                    }

                    subtitles.Add(sub);
                }
                catch (Exception exception)
                {
                    for (int j = k; j < this._fileNamesToJoin.Count; j++)
                    {
                        this._fileNamesToJoin.RemoveAt(j);
                    }

                    MessageBox.Show(exception.Message);
                    return;
                }
            }

            this.JoinedFormat = lastFormat;

            for (int outer = 0; outer < subtitles.Count; outer++)
            {
                for (int inner = 1; inner < subtitles.Count; inner++)
                {
                    var a = subtitles[inner - 1];
                    var b = subtitles[inner];
                    if (a.Paragraphs.Count > 0 && b.Paragraphs.Count > 0 && a.Paragraphs[0].StartTime.TotalMilliseconds > b.Paragraphs[0].StartTime.TotalMilliseconds)
                    {
                        string t1 = this._fileNamesToJoin[inner - 1];
                        this._fileNamesToJoin[inner - 1] = this._fileNamesToJoin[inner];
                        this._fileNamesToJoin[inner] = t1;

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

            this.listViewParts.BeginUpdate();
            this.listViewParts.Items.Clear();
            int i = 0;
            foreach (string fileName in this._fileNamesToJoin)
            {
                Subtitle sub = subtitles[i];
                var lvi = new ListViewItem(string.Format("{0:#,###,###}", sub.Paragraphs.Count));
                if (sub.Paragraphs.Count > 0)
                {
                    lvi.SubItems.Add(sub.Paragraphs[0].StartTime.ToString());
                    lvi.SubItems.Add(sub.Paragraphs[sub.Paragraphs.Count - 1].StartTime.ToString());
                }
                else
                {
                    lvi.SubItems.Add("-");
                    lvi.SubItems.Add("-");
                }

                lvi.SubItems.Add(fileName);
                this.listViewParts.Items.Add(lvi);
                i++;
            }

            this.listViewParts.EndUpdate();

            this.JoinedSubtitle = new Subtitle();
            if (this.JoinedFormat.FriendlyName != SubRip.NameOfFormat)
            {
                this.JoinedSubtitle.Header = header;
            }

            foreach (Subtitle sub in subtitles)
            {
                foreach (Paragraph p in sub.Paragraphs)
                {
                    this.JoinedSubtitle.Paragraphs.Add(p);
                }
            }

            this.JoinedSubtitle.Renumber();
            this.labelTotalLines.Text = string.Format(Configuration.Settings.Language.JoinSubtitles.TotalNumberOfLinesX, this.JoinedSubtitle.Paragraphs.Count);
        }
Ejemplo n.º 16
0
 private void SearchFolder(string path)
 {
     foreach (string fileName in Directory.GetFiles(path))
     {
         try
         {
             string ext = Path.GetExtension(fileName).ToLower();
             if (ext != ".png" && ext != ".jpg" && ext != ".dll" && ext != ".exe" && ext != ".zip")
             {
                 var fi = new FileInfo(fileName);
                 if (fi.Length < 1024 * 1024) // max 1 mb
                 {
                     Encoding encoding;
                     var sub = new Subtitle();
                     SubtitleFormat format = sub.LoadSubtitle(fileName, out encoding, null);
                     if (format != null)
                     {
                         var item = new ListViewItem(fileName);
                         item.SubItems.Add(Utilities.FormatBytesToDisplayFileSize(fi.Length));
                         item.SubItems.Add(format.Name);
                         item.SubItems.Add("-");
                         listViewInputFiles.Items.Add(item);
                     }
                 }
                 progressBar1.Refresh();
                 Application.DoEvents();
                 if (_abort)
                     return;
             }
         }
         catch
         {
         }
     }
     if (checkBoxScanFolderRecursive.Checked)
     {
         foreach (string directory in Directory.GetDirectories(path))
         {
             if (directory != "." && directory != "..")
                 SearchFolder(directory);
             if (_abort)
                 return;
         }
     }
 }
Ejemplo n.º 17
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;
            }
        }
Ejemplo n.º 18
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 += DoThreadWork;
            worker1.RunWorkerCompleted += ThreadWorkerCompleted;
            worker2.DoWork += DoThreadWork;
            worker2.RunWorkerCompleted += ThreadWorkerCompleted;
            worker3.DoWork += DoThreadWork;
            worker3.RunWorkerCompleted += ThreadWorkerCompleted;

            listViewInputFiles.BeginUpdate();
            foreach (ListViewItem item in listViewInputFiles.Items)
                item.SubItems[3].Text = "-";
            listViewInputFiles.EndUpdate();
            Refresh();

            int index = 0;
            while (index < listViewInputFiles.Items.Count && _abort == false)
            {
                ListViewItem item = listViewInputFiles.Items[index];
                string fileName = item.Text;

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

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

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

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

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

                    }

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

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

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

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

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

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

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

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

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

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

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

                }
                catch
                {
                    if (progressBar1.Value < progressBar1.Maximum)
                        progressBar1.Value++;
                    labelStatus.Text = progressBar1.Value + " / " + progressBar1.Maximum;
                }
                index++;
            }
            while (worker1.IsBusy || worker2.IsBusy || worker3.IsBusy)
            {
                try
                {
                    Application.DoEvents();
                }
                catch
                {
                }
                System.Threading.Thread.Sleep(100);
            }
            _converting = false;
            labelStatus.Text = string.Empty;
            progressBar1.Visible = false;
            buttonConvert.Enabled = true;
            buttonCancel.Enabled = true;
            groupBoxOutput.Enabled = true;
            groupBoxConvertOptions.Enabled = true;
            buttonInputBrowse.Enabled = true;
            buttonSearchFolder.Enabled = true;
        }
Ejemplo n.º 19
0
        private void toolStripMenuItemImportTimeCodes_Click(object sender, EventArgs e)
        {
            if (_subtitle.Paragraphs.Count < 1)
            {
                MessageBox.Show(_language.NoSubtitleLoaded, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            openFileDialog1.Title = _languageGeneral.OpenSubtitle;
            openFileDialog1.FileName = string.Empty;
            openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                Encoding encoding = null;
                Subtitle timeCodeSubtitle = new Subtitle();
                SubtitleFormat format = timeCodeSubtitle.LoadSubtitle(openFileDialog1.FileName, out encoding, encoding);
                if (format == null)
                {
                    ShowUnknownSubtitle();
                    return;
                }

                if (timeCodeSubtitle.Paragraphs.Count != _subtitle.Paragraphs.Count && !string.IsNullOrEmpty(_language.ImportTimeCodesDifferentNumberOfLinesWarning))
                {
                    if (MessageBox.Show(string.Format(_language.ImportTimeCodesDifferentNumberOfLinesWarning, timeCodeSubtitle.Paragraphs.Count, _subtitle.Paragraphs.Count), _title, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                        return;
                }

                MakeHistoryForUndo(_language.BeforeTimeCodeImport);

                if (GetCurrentSubtitleFormat().IsFrameBased)
                    timeCodeSubtitle.CalculateTimeCodesFromFrameNumbers(CurrentFrameRate);
                else
                    timeCodeSubtitle.CalculateFrameNumbersFromTimeCodes(CurrentFrameRate);

                int count = 0;
                for (int i = 0; i < timeCodeSubtitle.Paragraphs.Count; i++)
                {
                    Paragraph existing = _subtitle.GetParagraphOrDefault(i);
                    Paragraph newTimeCode = timeCodeSubtitle.GetParagraphOrDefault(i);
                    if (existing == null || newTimeCode == null)
                        break;
                    existing.StartTime.TotalMilliseconds = newTimeCode.StartTime.TotalMilliseconds;
                    existing.EndTime.TotalMilliseconds = newTimeCode.EndTime.TotalMilliseconds;
                    existing.StartFrame = newTimeCode.StartFrame;
                    existing.EndFrame = newTimeCode.EndFrame;
                    count++;

                }
                ShowStatus(string.Format(_language.TimeCodeImportedFromXY, Path.GetFileName(openFileDialog1.FileName), count));
                SaveSubtitleListviewIndexes();
                ShowSource();
                SubtitleListview1.Fill(_subtitle, _subtitleAlternate);
                RestoreSubtitleListviewIndexes();
            }

        }
Ejemplo n.º 20
0
        private void importTextWithMatchingTimeCodesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = Configuration.Settings.Language.General.OpenSubtitle;
            openFileDialog1.FileName = string.Empty;
            openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;
                if (!File.Exists(fileName))
                    return;

                var fi = new FileInfo(fileName);
                if (fi.Length > 1024 * 1024 * 10) // max 10 mb
                {
                    if (MessageBox.Show(string.Format(Configuration.Settings.Language.Main.FileXIsLargerThan10Mb + Environment.NewLine +
                                                      Environment.NewLine +
                                                      Configuration.Settings.Language.Main.ContinueAnyway,
                                                      fileName), Text, MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                        return;
                }

                Subtitle sub = new Subtitle();
                Encoding encoding = null;
                SubtitleFormat format = sub.LoadSubtitle(fileName, out encoding, encoding);
                if (format == null || sub == null)
                    return;

                int index = 0;
                foreach (Paragraph p in sub.Paragraphs)
                {
                    foreach (Paragraph currentP in _subtitle.Paragraphs)
                    {
                        if (string.IsNullOrEmpty(currentP.Text) && Math.Abs(p.StartTime.TotalMilliseconds - currentP.StartTime.TotalMilliseconds) <= 40)
                        {
                            currentP.Text = p.Text;
                            subtitleListView1.SetText(index, p.Text);
                            break;
                        }
                    }
                    index++;
                }

            }
        }
        public static void Convert(string title, string[] args) // E.g.: /convert *.txt SubRip
        {
            const int ATTACH_PARENT_PROCESS = -1;

            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
            {
                NativeMethods.AttachConsole(ATTACH_PARENT_PROCESS);
            }

            var currentFolder = Directory.GetCurrentDirectory();

            Console.WriteLine();
            Console.WriteLine(title + " - Batch converter");
            Console.WriteLine();

            if (args.Length < 4)
            {
                if (args.Length == 3 && (args[2].Equals("/list", StringComparison.OrdinalIgnoreCase) || args[2].Equals("-list", StringComparison.OrdinalIgnoreCase)))
                {
                    Console.WriteLine("- Supported formats (input/output):");
                    foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
                    {
                        Console.WriteLine("    " + format.Name.Replace(" ", string.Empty));
                    }
                    Console.WriteLine();
                    Console.WriteLine("- Supported formats (input only):");
                    Console.WriteLine("    " + CapMakerPlus.NameOfFormat);
                    Console.WriteLine("    " + Captionate.NameOfFormat);
                    Console.WriteLine("    " + Cavena890.NameOfFormat);
                    Console.WriteLine("    " + CheetahCaption.NameOfFormat);
                    Console.WriteLine("    " + Chk.NameOfFormat);
                    Console.WriteLine("    Matroska (.mkv)");
                    Console.WriteLine("    Matroska subtitle (.mks)");
                    Console.WriteLine("    " + NciCaption.NameOfFormat);
                    Console.WriteLine("    " + AvidStl.NameOfFormat);
                    Console.WriteLine("    " + Pac.NameOfFormat);
                    Console.WriteLine("    " + Spt.NameOfFormat);
                    Console.WriteLine("    " + Ultech130.NameOfFormat);
                    Console.WriteLine("- For Blu-ray .sup output use: '" + BatchConvert.BluRaySubtitle.Replace(" ", string.Empty) + "'");
                    Console.WriteLine("- For VobSub .sub output use: '" + BatchConvert.VobSubSubtitle.Replace(" ", string.Empty) + "'");
                }
                else
                {
                    Console.WriteLine("- Usage: SubtitleEdit /convert <pattern> <name-of-format-without-spaces> [<optional-parameters>]");
                    Console.WriteLine();
                    Console.WriteLine("    pattern:");
                    Console.WriteLine("        one or more file name patterns separated by commas");
                    Console.WriteLine("        relative patterns are relative to /inputfolder if specified");
                    Console.WriteLine("    optional-parameters:");
                    Console.WriteLine("        /offset:hh:mm:ss:ms");
                    Console.WriteLine("        /fps:<frame rate>");
                    Console.WriteLine("        /targetfps:<frame rate>");
                    Console.WriteLine("        /encoding:<encoding name>");
                    Console.WriteLine("        /pac-codepage:<code page>");
                    Console.WriteLine("        /inputfolder:<folder name>");
                    Console.WriteLine("        /outputfolder:<folder name>");
                    Console.WriteLine("        /removetextforhi");
                    Console.WriteLine("        /fixcommonerrors");
                    Console.WriteLine("        /redocasing");
                    Console.WriteLine("        /multiplereplace");
                    Console.WriteLine();
                    Console.WriteLine("    example: SubtitleEdit /convert *.srt sami");
                    Console.WriteLine("    list available formats: SubtitleEdit /convert /list");
                }
                Console.WriteLine();

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

            int count     = 0;
            int converted = 0;
            int errors    = 0;

            try
            {
                var pattern      = args[2].Trim();
                var targetFormat = args[3].Trim().Replace(" ", string.Empty);
                var offset       = GetArgument(args, "offset:");

                double?targetFrameRate = null;
                {
                    var fps = GetArgument(args, "targetfps:");
                    if (fps.Length > 1)
                    {
                        fps = fps.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".");
                        double d;
                        if (double.TryParse(fps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
                        {
                            targetFrameRate = d;
                        }
                    }

                    fps = GetArgument(args, "fps:");
                    if (fps.Length > 1)
                    {
                        fps = fps.Replace(',', '.').Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ".");
                        double d;
                        if (double.TryParse(fps, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
                        {
                            Configuration.Settings.General.CurrentFrameRate = d;
                        }
                    }
                }

                var targetEncoding = Encoding.UTF8;
                try
                {
                    var encodingName = GetArgument(args, "encoding:");
                    if (encodingName.Length > 0)
                    {
                        targetEncoding = Encoding.GetEncoding(encodingName);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Unable to set encoding (" + exception.Message + ") - using UTF-8");
                }

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

                var inputFolder = currentFolder;
                {
                    var folder = GetArgument(args, "inputFolder:");
                    if (folder.Length > 0 && Directory.Exists(folder))
                    {
                        inputFolder = folder;
                    }
                }

                int pacCodePage = -1;
                {
                    var pcp = GetArgument(args, "pac-codepage:");
                    if (pcp.Length > 0)
                    {
                        if (pcp.Equals("Latin", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageLatin;
                        }
                        else if (pcp.Equals("Greek", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageGreek;
                        }
                        else if (pcp.Equals("Czech", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageLatinCzech;
                        }
                        else if (pcp.Equals("Arabic", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageArabic;
                        }
                        else if (pcp.Equals("Hebrew", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageHebrew;
                        }
                        else if (pcp.Equals("Thai", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageThai;
                        }
                        else if (pcp.Equals("Cyrillic", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageCyrillic;
                        }
                        else if (pcp.Equals("CHT", StringComparison.OrdinalIgnoreCase) || pcp.Replace(" ", string.Empty).Equals("TraditionalChinese", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageChineseTraditional;
                        }
                        else if (pcp.Equals("CHS", StringComparison.OrdinalIgnoreCase) || pcp.Replace(" ", string.Empty).Equals("SimplifiedChinese", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageChineseSimplified;
                        }
                        else if (pcp.Equals("Korean", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageKorean;
                        }
                        else if (pcp.Equals("Japanese", StringComparison.OrdinalIgnoreCase))
                        {
                            pacCodePage = Pac.CodePageJapanese;
                        }
                        else if (!int.TryParse(pcp, out pacCodePage) || !Pac.IsValidCodePage(pacCodePage))
                        {
                            Console.WriteLine("Unknown pac code page '" + pcp + "' - using default code page");
                            pacCodePage = -1;
                        }
                    }
                }

                bool overwrite       = GetArgument(args, "overwrite").Equals("overwrite");
                bool removeTextForHi = GetArgument(args, "removetextforhi").Equals("removetextforhi");
                bool fixCommonErrors = GetArgument(args, "fixcommonerrors").Equals("fixcommonerrors");
                bool redoCasing      = GetArgument(args, "redocasing").Equals("redocasing");
                bool multipleReplace = GetArgument(args, "multiplereplace").Equals("multiplereplace");

                var patterns = Enumerable.Empty <string>();

                if (pattern.Contains(',') && !File.Exists(pattern))
                {
                    patterns = pattern.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(fn => fn.Trim()).Where(fn => fn.Length > 0);
                }
                else
                {
                    patterns = patterns.DefaultIfEmpty(pattern);
                }

                var files = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                foreach (var p in patterns)
                {
                    var folderName = Path.GetDirectoryName(p);
                    var fileName   = Path.GetFileName(p);
                    if (string.IsNullOrEmpty(folderName) || string.IsNullOrEmpty(fileName))
                    {
                        folderName = inputFolder;
                        fileName   = p;
                    }
                    else if (!Path.IsPathRooted(folderName))
                    {
                        folderName = Path.Combine(inputFolder, folderName);
                    }
                    foreach (var fn in Directory.EnumerateFiles(folderName, fileName))
                    {
                        files.Add(fn); // silently ignore duplicates
                    }
                }

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

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

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

                                                if (format.GetType() == typeof(AdvancedSubStationAlpha) || format.GetType() == typeof(SubStationAlpha))
                                                {
                                                    if (!AdvancedSubStationAlpha.NameOfFormat.Replace(" ", string.Empty).Equals(targetFormat, StringComparison.OrdinalIgnoreCase) &&
                                                        !SubStationAlpha.NameOfFormat.Replace(" ", string.Empty).Equals(targetFormat, StringComparison.OrdinalIgnoreCase))
                                                    {
                                                        foreach (SubtitleFormat sf in formats)
                                                        {
                                                            if (sf.Name.Replace(" ", string.Empty).Equals(targetFormat, StringComparison.OrdinalIgnoreCase))
                                                            {
                                                                format.RemoveNativeFormatting(sub, sf);
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }

                                                BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, overwrite, pacCodePage, targetFrameRate, removeTextForHi, fixCommonErrors, redoCasing, multipleReplace);
                                                done = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }

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

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

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

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

            Console.WriteLine();
            Console.WriteLine("{0} file(s) converted", converted);
            Console.WriteLine();

            if (!Configuration.IsRunningOnMac() && !Configuration.IsRunningOnLinux())
            {
                Console.Write(currentFolder + ">");
                NativeMethods.FreeConsole();
            }

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