private Subtitle ImportTimeCodesInFramesOnSameSeparateLine(List <string> lines)
        {
            Paragraph p        = null;
            var       subtitle = new Subtitle();
            var       sb       = new StringBuilder();

            for (int idx = 0; idx < lines.Count; idx++)
            {
                string line = lines[idx];
                string lineWithPerhapsOnlyNumbers = GetLineWithPerhapsOnlyNumbers(line);
                bool   allNumbers = lineWithPerhapsOnlyNumbers.Length > 0;
                foreach (char c in lineWithPerhapsOnlyNumbers)
                {
                    if (!char.IsDigit(c))
                    {
                        allNumbers = false;
                    }
                }
                if (allNumbers && lineWithPerhapsOnlyNumbers.Length > 2)
                {
                    string[] arr = line.Replace('-', ' ').Replace('>', ' ').Replace('{', ' ').Replace('}', ' ').Replace('[', ' ').Replace(']', ' ').Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Length == 2)
                    {
                        string[] start = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        string[] end   = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        if (start.Length == 1 && end.Length == 1)
                        {
                            if (p != null)
                            {
                                p.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(p);
                            }
                            p = new Paragraph();
                            sb.Clear();
                            try
                            {
                                if (UseFrames)
                                {
                                    p.StartTime.TotalMilliseconds = SubtitleFormat.FramesToMilliseconds(int.Parse(start[0]));
                                    p.EndTime.TotalMilliseconds   = SubtitleFormat.FramesToMilliseconds(int.Parse(end[0]));
                                }
                                else
                                {
                                    p.StartTime.TotalMilliseconds = double.Parse(start[0]);
                                    p.EndTime.TotalMilliseconds   = double.Parse(end[0]);
                                }
                            }
                            catch
                            {
                                p = null;
                            }
                        }
                    }
                    else if (arr.Length == 3)
                    {
                        string[] start    = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        string[] end      = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        string[] duration = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);

                        if (end.Length == 1 && duration.Length == 1)
                        {
                            start = end;
                            end   = duration;
                        }

                        if (start.Length == 1 && end.Length == 1)
                        {
                            if (p != null)
                            {
                                p.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(p);
                            }
                            p = new Paragraph();
                            sb.Clear();
                            try
                            {
                                if (UseFrames)
                                {
                                    p.StartTime.TotalMilliseconds = SubtitleFormat.FramesToMilliseconds(int.Parse(start[0]));
                                    p.EndTime.TotalMilliseconds   = SubtitleFormat.FramesToMilliseconds(int.Parse(end[0]));
                                }
                                else
                                {
                                    p.StartTime.TotalMilliseconds = double.Parse(start[0]);
                                    p.EndTime.TotalMilliseconds   = double.Parse(end[0]);
                                }
                            }
                            catch
                            {
                                p = null;
                            }
                        }
                    }
                }
                if (p != null && !allNumbers && line.Length > 1)
                {
                    line = line.Trim();
                    if (line.StartsWith("}{}", StringComparison.Ordinal) || line.StartsWith("][]", StringComparison.Ordinal))
                    {
                        line = line.Remove(0, 3);
                    }

                    sb.AppendLine(line.Trim());
                }
            }
            if (p != null)
            {
                p.Text = sb.ToString().Trim();
                subtitle.Paragraphs.Add(p);
            }
            subtitle.Renumber();
            return(subtitle);
        }
Example #2
0
        public string ToHHMMSSPeriodFF()
        {
            var ts     = TimeSpan;
            var frames = Math.Round(ts.Milliseconds / (BaseUnit / Configuration.Settings.General.CurrentFrameRate));

            if (frames >= Configuration.Settings.General.CurrentFrameRate - 0.001)
            {
                return(string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds + 1, 0));
            }
            return(string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, SubtitleFormat.MillisecondsToFramesMaxFrameRate(ts.Milliseconds)));
        }
        public SubStationAlphaStylesBatchConvert(Subtitle subtitle, SubtitleFormat format)
            : base(subtitle)
        {
            UiUtil.PreInitialize(this);
            InitializeComponent();
            UiUtil.FixFonts(this);

            comboBoxWrapStyle.SelectedIndex = 2;
            comboBoxCollision.SelectedIndex = 0;
            _header            = subtitle.Header;
            _isSubStationAlpha = format.Name == SubStationAlpha.NameOfFormat;
            if (_header == null || !_header.Contains("style:", StringComparison.OrdinalIgnoreCase))
            {
                ResetHeader();
            }

            comboBoxFontName.Items.Clear();
            foreach (var x in FontFamily.Families)
            {
                comboBoxFontName.Items.Add(x.Name);
            }

            var l = Configuration.Settings.Language.SubStationAlphaStyles;

            Text = l.Title;
            groupBoxProperties.Text      = l.Properties;
            groupBoxFont.Text            = l.Font;
            labelFontName.Text           = l.FontName;
            labelFontSize.Text           = l.FontSize;
            checkBoxFontItalic.Text      = Configuration.Settings.Language.General.Italic;
            checkBoxFontBold.Text        = Configuration.Settings.Language.General.Bold;
            checkBoxFontUnderline.Text   = Configuration.Settings.Language.General.Underline;
            groupBoxAlignment.Text       = l.Alignment;
            radioButtonTopLeft.Text      = l.TopLeft;
            radioButtonTopCenter.Text    = l.TopCenter;
            radioButtonTopRight.Text     = l.TopRight;
            radioButtonMiddleLeft.Text   = l.MiddleLeft;
            radioButtonMiddleCenter.Text = l.MiddleCenter;
            radioButtonMiddleRight.Text  = l.MiddleRight;
            radioButtonBottomLeft.Text   = l.BottomLeft;
            radioButtonBottomCenter.Text = l.BottomCenter;
            radioButtonBottomRight.Text  = l.BottomRight;
            groupBoxColors.Text          = l.Colors;
            buttonPrimaryColor.Text      = l.Primary;
            buttonSecondaryColor.Text    = l.Secondary;
            buttonOutlineColor.Text      = l.Outline;
            buttonBackColor.Text         = l.Shadow;
            groupBoxMargins.Text         = l.Margins;
            labelMarginLeft.Text         = l.MarginLeft;
            labelMarginRight.Text        = l.MarginRight;
            labelMarginVertical.Text     = l.MarginVertical;
            groupBoxBorder.Text          = l.Border;
            radioButtonOutline.Text      = l.Outline;
            labelShadow.Text             = l.PlusShadow;
            radioButtonOpaqueBox.Text    = l.OpaqueBox;
            groupBoxPreview.Text         = Configuration.Settings.Language.General.Preview;

            if (_isSubStationAlpha)
            {
                Text = l.TitleSubstationAlpha;
                buttonOutlineColor.Text       = l.Tertiary;
                buttonBackColor.Text          = l.Back;
                checkBoxFontUnderline.Visible = false;

                labelWrapStyle.Visible               = false;
                comboBoxWrapStyle.Visible            = false;
                checkBoxScaleBorderAndShadow.Visible = false;

                numericUpDownOutline.Increment         = 1;
                numericUpDownOutline.DecimalPlaces     = 0;
                numericUpDownShadowWidth.Increment     = 1;
                numericUpDownShadowWidth.DecimalPlaces = 0;
            }

            buttonOK.Text     = Configuration.Settings.Language.General.Ok;
            buttonCancel.Text = Configuration.Settings.Language.General.Cancel;

            UiUtil.FixLargeFonts(this, buttonCancel);

            comboBoxFontName.Left      = labelFontName.Left + labelFontName.Width + 10;
            numericUpDownFontSize.Left = labelFontSize.Left + labelFontSize.Width + 10;
            if (comboBoxFontName.Left > numericUpDownFontSize.Left)
            {
                numericUpDownFontSize.Left = comboBoxFontName.Left;
            }
            else
            {
                comboBoxFontName.Left = numericUpDownFontSize.Left;
            }

            numericUpDownOutline.Left     = radioButtonOutline.Left + radioButtonOutline.Width + 5;
            labelShadow.Left              = numericUpDownOutline.Left + numericUpDownOutline.Width + 5;
            numericUpDownShadowWidth.Left = labelShadow.Left + labelShadow.Width + 5;
            checkBoxFontItalic.Left       = checkBoxFontBold.Left + checkBoxFontBold.Width + 12;
            checkBoxFontUnderline.Left    = checkBoxFontItalic.Left + checkBoxFontItalic.Width + 12;

            var l2 = Configuration.Settings.Language.SubStationAlphaProperties;

            groupBoxResolution.Text           = l2.Resolution;
            labelVideoResolution.Text         = l2.VideoResolution;
            groupBoxOptions.Text              = l2.Options;
            labelCollision.Text               = l2.Collision;
            labelWrapStyle.Text               = l2.WrapStyle;
            checkBoxScaleBorderAndShadow.Text = l2.ScaleBorderAndShadow;
        }
Example #4
0
 /// <summary>
 /// Load a subtitle from a file.
 /// Check "OriginalFormat" to see what subtitle format was used.
 /// Check "OriginalEncoding" to see what text encoding was used.
 /// </summary>
 /// <param name="fileName">File name of subtitle to load.</param>
 /// <param name="format">SubtitleFormat to use.</param>
 /// <returns>Loaded subtitle, null if format does not match the file.</returns>
 public static Subtitle Parse(string fileName, SubtitleFormat format)
 {
     return(Parse(fileName, new List <SubtitleFormat> {
         format
     }));
 }
        public void Check(Subtitle subtitle, NetflixQualityController controller)
        {
            if (controller.Language == "ja")
            {
                return;
            }

            for (int index = 0; index < subtitle.Paragraphs.Count; index++)
            {
                var p    = subtitle.Paragraphs[index];
                var next = subtitle.GetParagraphOrDefault(index + 1);
                if (next == null)
                {
                    continue;
                }

                double twoFramesGap = 1000.0 / controller.FrameRate * 2.0;
                var    gapInFrames  = SubtitleFormat.MillisecondsToFrames(next.StartTime.TotalMilliseconds) - SubtitleFormat.MillisecondsToFrames(p.EndTime.TotalMilliseconds);
                if (gapInFrames >= 3 && gapInFrames <= 11 && !p.StartTime.IsMaxTime)
                {
                    var fixedParagraph = new Paragraph(p, false)
                    {
                        EndTime = { TotalMilliseconds = next.StartTime.TotalMilliseconds - twoFramesGap }
                    };
                    string comment = "3-11 frames gap => 2 frames gap";
                    controller.AddRecord(p, fixedParagraph, comment);
                }
            }
        }
Example #6
0
 public SubtitleFormat ReloadLoadSubtitle(List <string> lines, string fileName, SubtitleFormat format)
 {
     Paragraphs.Clear();
     if (format != null && format.IsMine(lines, fileName))
     {
         format.LoadSubtitle(this, lines, fileName);
         _format = format;
         return(format);
     }
     foreach (SubtitleFormat subtitleFormat in SubtitleFormat.AllSubtitleFormats)
     {
         if (subtitleFormat.IsMine(lines, fileName))
         {
             subtitleFormat.LoadSubtitle(this, lines, fileName);
             _format = subtitleFormat;
             return(subtitleFormat);
         }
     }
     return(null);
 }
Example #7
0
 /// <exception cref="EncodingNotSupportedException">Thrown if the encoding is not supported by the platform.</exception>
 /// <exception cref="UnknownSubtitleFormatException">Thrown if the subtitle format could not be detected.</exception>
 private string TestCodePage(FileStream fileStream, int codePage, out Encoding encoding, out SubtitleFormat format)
 {
     /* Check the encoding */
     TestCodePageCommon(codePage, out encoding);
     return(TestEncoding(fileStream, encoding, out format));
 }
        public SubtitleFormat ReloadLoadSubtitle(List<string> lines, string fileName)
        {
            Paragraphs.Clear();
            foreach (SubtitleFormat subtitleFormat in SubtitleFormat.AllSubtitleFormats)
            {
                if (subtitleFormat.IsMine(lines, fileName))
                {
                    subtitleFormat.LoadSubtitle(this, lines, fileName);
                    format = subtitleFormat;
                    return subtitleFormat;
                }
            }

            return null;
        }
 /// <summary>
 /// Creates subtitle as text in it's native format
 /// </summary>
 /// <param name="format">Format to output</param>
 /// <returns>Native format as text string</returns>
 public string ToText(SubtitleFormat format)
 {
     return format.ToText(this, Path.GetFileNameWithoutExtension(FileName));
 }
        public SubtitleFormat LoadSubtitle(string fileName, out Encoding encoding, Encoding useThisEncoding, bool batchMode)
        {
            FileName = fileName;

            paragraphs = new List<Paragraph>();

            var lines = new List<string>();
            StreamReader reader;
            if (useThisEncoding != null)
            {
                try
                {
                    reader = new StreamReader(fileName, useThisEncoding);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                    encoding = Encoding.UTF8;
                    return null;
                }
            }
            else
            {
                try
                {
                    reader = new StreamReader(fileName, Utilities.GetEncodingFromFile(fileName), true);
                }
                catch
                {
                    try
                    {
                        Stream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        reader = new StreamReader(fileStream);
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                        encoding = Encoding.UTF8;
                        return null;
                    }
                }
            }

            encoding = reader.CurrentEncoding;
            while (!reader.EndOfStream)
            {
                lines.Add(reader.ReadLine());
            }

            reader.Close();

            foreach (SubtitleFormat subtitleFormat in SubtitleFormat.AllSubtitleFormats)
            {
                if (subtitleFormat.IsMine(lines, fileName))
                {
                    Header = null;
                    subtitleFormat.BatchMode = batchMode;
                    subtitleFormat.LoadSubtitle(this, lines, fileName);
                    format = subtitleFormat;
                    WasLoadedWithFrameNumbers = format.IsFrameBased;
                    if (WasLoadedWithFrameNumbers)
                    {
                        CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                    }

                    return subtitleFormat;
                }
            }

            if (useThisEncoding == null)
            {
                return LoadSubtitle(fileName, out encoding, Encoding.Unicode);
            }

            return null;
        }
        public void MakeHistoryForUndo(string description, SubtitleFormat subtitleFormat, DateTime fileModified, Subtitle original, string originalSubtitleFileName, int lineNumber, int linePosition, int linePositionAlternate)
        {
            // don't fill memory with history - use a max rollback points
            if (history.Count > MaximumHistoryItems)
            {
                history.RemoveAt(0);
            }

            history.Add(new HistoryItem(history.Count, this, description, FileName, fileModified, subtitleFormat.FriendlyName, original, originalSubtitleFileName, lineNumber, linePosition, linePositionAlternate));
        }
        internal static Subtitle LoadMatroskaSSA(MatroskaTrackInfo matroskaSubtitleInfo, string fileName, SubtitleFormat format, List<MatroskaSubtitle> sub)
        {
            var subtitle = new Subtitle { Header = matroskaSubtitleInfo.CodecPrivate };
            var lines = subtitle.Header.Trim().SplitToLines().ToList();

            var footer = new StringBuilder();
            var comments = new Subtitle();
            if (!string.IsNullOrEmpty(matroskaSubtitleInfo.CodecPrivate))
            {
                bool footerOn = false;
                foreach (string line in lines)
                {
                    if (footerOn)
                    {
                        footer.AppendLine(line);
                    }
                    else if (line.Trim() == "[Events]")
                    {
                    }
                    else if (line.Trim() == "[Fonts]" || line.Trim() == "[Graphics]")
                    {
                        footerOn = true;
                        footer.AppendLine();
                        footer.AppendLine();
                        footer.AppendLine(line);
                    }
                    else if (line.StartsWith("Comment:", StringComparison.Ordinal))
                    {
                        var arr = line.Split(',');
                        if (arr.Length > 3)
                        {
                            arr = arr[1].Split(new[] { ':', '.' });
                            if (arr.Length == 4)
                            {
                                int hour;
                                int min;
                                int sec;
                                int ms;
                                if (int.TryParse(arr[0], out hour) && int.TryParse(arr[1], out min) && int.TryParse(arr[2], out sec) && int.TryParse(arr[3], out ms))
                                {
                                    comments.Paragraphs.Add(new Paragraph(new TimeCode(hour, min, sec, ms * 10), new TimeCode(0, 0, 0, 0), line));
                                }
                            }
                        }
                    }
                }
            }

            const string headerFormat = "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text";
            if (!subtitle.Header.Contains("[Events]"))
            {
                subtitle.Header = subtitle.Header.Trim() + Environment.NewLine + Environment.NewLine + "[Events]" + Environment.NewLine + headerFormat + Environment.NewLine;
            }
            else
            {
                subtitle.Header = subtitle.Header.Remove(subtitle.Header.IndexOf("[Events]", StringComparison.Ordinal));
                subtitle.Header = subtitle.Header.Trim() + Environment.NewLine + Environment.NewLine + "[Events]" + Environment.NewLine + headerFormat + Environment.NewLine;
            }

            lines = subtitle.Header.Trim().SplitToLines().ToList();

            const string timeCodeFormat = "{0}:{1:00}:{2:00}.{3:00}"; // h:mm:ss.cc
            foreach (var mp in sub)
            {
                var p = new Paragraph(string.Empty, mp.Start, mp.End);
                string start = string.Format(timeCodeFormat, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds / 10);
                string end = string.Format(timeCodeFormat, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds / 10);

                // MKS contains this: ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text
                lines.AddRange(from cp in comments.Paragraphs where cp.StartTime.TotalMilliseconds <= p.StartTime.TotalMilliseconds select cp.Text);

                for (int commentIndex = comments.Paragraphs.Count - 1; commentIndex >= 0; commentIndex--)
                {
                    var cp = comments.Paragraphs[commentIndex];
                    if (cp.StartTime.TotalMilliseconds <= p.StartTime.TotalMilliseconds)
                    {
                        comments.Paragraphs.RemoveAt(commentIndex);
                    }
                }

                string text = mp.Text.Replace(Environment.NewLine, "\\N");
                int idx = text.IndexOf(',') + 1;
                if (idx > 0 && idx < text.Length)
                {
                    text = text.Remove(0, idx); // remove ReadOrder
                    idx = text.IndexOf(',');
                    text = text.Insert(idx, "," + start + "," + end);
                    lines.Add("Dialogue: " + text);
                }
            }

            lines.AddRange(comments.Paragraphs.Select(cp => cp.Text));

            lines.AddRange(footer.ToString().SplitToLines());

            format.LoadSubtitle(subtitle, lines, fileName);
            return subtitle;
        }
        public static void SetSaveDialogFilter(SaveFileDialog saveFileDialog, SubtitleFormat currentFormat)
        {
            var sb = new StringBuilder();
            int index = 0;
            foreach (SubtitleFormat format in SubtitleFormat.AllSubtitleFormats)
            {
                sb.Append(format.Name + "|*" + format.Extension + "|");
                if (currentFormat.Name == format.Name)
                {
                    saveFileDialog.FilterIndex = index + 1;
                }

                index++;
            }

            saveFileDialog.Filter = sb.ToString().TrimEnd('|');
        }
        private static SubtitleFormat GetSubtitleFormat(SubtitleFormat format, string fileName, Subtitle sub, string pacCodePage)
        {
            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;
                }
            }
            return format;
        }
Example #15
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);
            }
        }
        private void ResetHeader()
        {
            SubtitleFormat format;
            if (this.isSubStationAlpha)
            {
                format = new SubStationAlpha();
            }
            else
            {
                format = new AdvancedSubStationAlpha();
            }

            var sub = new Subtitle();
            string text = format.ToText(sub, string.Empty);
            var lines = new List<string>();
            foreach (string line in text.SplitToLines())
            {
                lines.Add(line);
            }

            format.LoadSubtitle(sub, lines, string.Empty);
            this.header = sub.Header;
        }
Example #17
0
        internal void Initialize(Subtitle subtitle, Subtitle target, string title, Encoding encoding, SubtitleFormat subtitleFormat)
        {
            if (!string.IsNullOrEmpty(title))
            {
                Text = title;
            }

            subtitle.Renumber(); // "Renumber" is required for translation engine atm

            labelPleaseWait.Visible = false;
            progressBar1.Visible    = false;
            _subtitle               = subtitle;
            _encoding               = encoding;
            _subtitleFormat         = subtitleFormat;
            buttonTranslate.Enabled = false;

            if (target != null)
            {
                TranslatedSubtitle = new Subtitle(target);
                TranslatedSubtitle.Renumber();
                subtitleListViewTarget.Fill(TranslatedSubtitle);
            }
            else
            {
                TranslatedSubtitle = new Subtitle(subtitle);
                foreach (var paragraph in TranslatedSubtitle.Paragraphs)
                {
                    paragraph.Text = string.Empty;
                }
            }

            _sourceLanguageIsoCode = EvaluateDefaultSourceLanguageCode(encoding, _subtitle);
            _targetLanguageIsoCode = EvaluateDefaultTargetLanguageCode(_sourceLanguageIsoCode);

            InitTranslationServices();
            InitParagraphHandlingStrategies();

            subtitleListViewSource.Fill(subtitle);
            Translate_Resize(null, null);

            _autoSplit = new bool[_subtitle.Paragraphs.Count];
        }
        private void SetSsaStyle(string styleName, string propertyName, string propertyValue)
        {
            int propertyIndex = -1;
            int nameIndex = -1;
            var sb = new StringBuilder();
            foreach (var line in this.header.Split(Utilities.NewLineChars, StringSplitOptions.None))
            {
                string s = line.Trim().ToLower();
                if (s.StartsWith("format:", StringComparison.Ordinal))
                {
                    if (line.Length > 10)
                    {
                        var format = line.ToLower().Substring(8).Split(',');
                        for (int i = 0; i < format.Length; i++)
                        {
                            string f = format[i].Trim().ToLower();
                            if (f == "name")
                            {
                                nameIndex = i;
                            }

                            if (f == propertyName)
                            {
                                propertyIndex = i;
                            }
                        }
                    }

                    sb.AppendLine(line);
                }
                else if (s.Replace(" ", string.Empty).StartsWith("style:", StringComparison.Ordinal))
                {
                    if (line.Length > 10)
                    {
                        bool correctLine = false;
                        var format = line.Substring(6).Split(',');
                        for (int i = 0; i < format.Length; i++)
                        {
                            string f = format[i].Trim();
                            if (i == nameIndex)
                            {
                                correctLine = f.Equals(styleName, StringComparison.OrdinalIgnoreCase);
                            }
                        }

                        if (correctLine)
                        {
                            sb.Append(line.Substring(0, 6) + " ");
                            format = line.Substring(6).Split(',');
                            for (int i = 0; i < format.Length; i++)
                            {
                                string f = format[i].Trim();
                                if (i == propertyIndex)
                                {
                                    sb.Append(propertyValue);
                                }
                                else
                                {
                                    sb.Append(f);
                                }

                                if (i < format.Length - 1)
                                {
                                    sb.Append(',');
                                }
                            }

                            sb.AppendLine();
                        }
                        else
                        {
                            sb.AppendLine(line);
                        }
                    }
                    else
                    {
                        sb.AppendLine(line);
                    }
                }
                else
                {
                    sb.AppendLine(line);
                }
            }

            this.header = sb.ToString().Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
        }
Example #19
0
 /// <summary>
 /// Creates subtitle as text in its native format.
 /// </summary>
 /// <param name="format">Format to output</param>
 /// <returns>Native format as text string</returns>
 public string ToText(SubtitleFormat format)
 {
     return(format.ToText(this, Path.GetFileNameWithoutExtension(FileName)));
 }
        public SubStationAlphaStyles(Subtitle subtitle, SubtitleFormat format)
            : base(subtitle)
        {
            this.InitializeComponent();

            this.labelStatus.Text = string.Empty;
            this.header = subtitle.Header;
            this.format = format;
            this.isSubStationAlpha = this.format.Name == SubStationAlpha.NameOfFormat;
            if (this.header == null || !this.header.Contains("style:", StringComparison.OrdinalIgnoreCase))
            {
                this.ResetHeader();
            }

            this.comboBoxFontName.Items.Clear();
            foreach (var x in FontFamily.Families)
            {
                this.comboBoxFontName.Items.Add(x.Name);
            }

            var l = Configuration.Settings.Language.SubStationAlphaStyles;
            this.Text = l.Title;
            this.groupBoxStyles.Text = l.Styles;
            this.listViewStyles.Columns[0].Text = l.Name;
            this.listViewStyles.Columns[1].Text = l.FontName;
            this.listViewStyles.Columns[2].Text = l.FontSize;
            this.listViewStyles.Columns[3].Text = l.UseCount;
            this.listViewStyles.Columns[4].Text = l.Primary;
            this.listViewStyles.Columns[5].Text = l.Outline;
            this.groupBoxProperties.Text = l.Properties;
            this.labelStyleName.Text = l.Name;
            this.groupBoxFont.Text = l.Font;
            this.labelFontName.Text = l.FontName;
            this.labelFontSize.Text = l.FontSize;
            this.checkBoxFontItalic.Text = Configuration.Settings.Language.General.Italic;
            this.checkBoxFontBold.Text = Configuration.Settings.Language.General.Bold;
            this.checkBoxFontUnderline.Text = Configuration.Settings.Language.General.Underline;
            this.groupBoxAlignment.Text = l.Alignment;
            this.radioButtonTopLeft.Text = l.TopLeft;
            this.radioButtonTopCenter.Text = l.TopCenter;
            this.radioButtonTopRight.Text = l.TopRight;
            this.radioButtonMiddleLeft.Text = l.MiddleLeft;
            this.radioButtonMiddleCenter.Text = l.MiddleCenter;
            this.radioButtonMiddleRight.Text = l.MiddleRight;
            this.radioButtonBottomLeft.Text = l.BottomLeft;
            this.radioButtonBottomCenter.Text = l.BottomCenter;
            this.radioButtonBottomRight.Text = l.BottomRight;
            this.groupBoxColors.Text = l.Colors;
            this.buttonPrimaryColor.Text = l.Primary;
            this.buttonSecondaryColor.Text = l.Secondary;
            this.buttonOutlineColor.Text = l.Outline;
            this.buttonBackColor.Text = l.Shadow;
            this.groupBoxMargins.Text = l.Margins;
            this.labelMarginLeft.Text = l.MarginLeft;
            this.labelMarginRight.Text = l.MarginRight;
            this.labelMarginRight.Text = l.MarginRight;
            this.labelMarginVertical.Text = l.MarginVertical;
            this.groupBoxBorder.Text = l.Border;
            this.radioButtonOutline.Text = l.Outline;
            this.labelShadow.Text = l.PlusShadow;
            this.radioButtonOpaqueBox.Text = l.OpaqueBox;
            this.buttonImport.Text = l.Import;
            this.buttonExport.Text = l.Export;
            this.buttonCopy.Text = l.Copy;
            this.buttonAdd.Text = l.New;
            this.buttonRemove.Text = l.Remove;
            this.buttonRemoveAll.Text = l.RemoveAll;
            this.groupBoxPreview.Text = Configuration.Settings.Language.General.Preview;

            if (this.isSubStationAlpha)
            {
                this.Text = l.TitleSubstationAlpha;
                this.buttonOutlineColor.Text = l.Tertiary;
                this.buttonBackColor.Text = l.Back;
                this.listViewStyles.Columns[5].Text = l.Back;
                this.checkBoxFontUnderline.Visible = false;
            }

            this.buttonOK.Text = Configuration.Settings.Language.General.Ok;
            this.buttonCancel.Text = Configuration.Settings.Language.General.Cancel;

            this.InitializeListView();
            Utilities.FixLargeFonts(this, this.buttonCancel);

            this.comboBoxFontName.Left = this.labelFontName.Left + this.labelFontName.Width + 10;
            this.numericUpDownFontSize.Left = this.labelFontSize.Left + this.labelFontSize.Width + 10;
            if (comboBoxFontName.Left > this.numericUpDownFontSize.Left)
            {
                this.numericUpDownFontSize.Left = this.comboBoxFontName.Left;
            }
            else
            {
                this.comboBoxFontName.Left = this.numericUpDownFontSize.Left;
            }

            this.numericUpDownOutline.Left = this.radioButtonOutline.Left + this.radioButtonOutline.Width + 5;
            this.labelShadow.Left = this.numericUpDownOutline.Left + this.numericUpDownOutline.Width + 5;
            this.numericUpDownShadowWidth.Left = this.labelShadow.Left + this.labelShadow.Width + 5;
            this.listViewStyles.Columns[5].Width = -2;
            this.checkBoxFontItalic.Left = this.checkBoxFontBold.Left + this.checkBoxFontBold.Width + 12;
            this.checkBoxFontUnderline.Left = this.checkBoxFontItalic.Left + this.checkBoxFontItalic.Width + 12;
        }
        private static SubtitleFormat ConvertToMatroska(MatroskaFile matroska, MatroskaTrackInfo track, SubtitleFormat format, Subtitle sub, string fileName, List<MatroskaTrackInfo> tracks, string toFormat, IList<SubtitleFormat> formats, string offset, Encoding targetEncoding, string outputFolder, int count, bool overwrite, string pacCodePage, double? targetFrameRate, ref int converted, ref int errors, ref bool done)
        {
            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());
            }

            bool isSubStationAlpha =
                format.GetType() == typeof(AdvancedSubStationAlpha) ||
                format.GetType() == typeof(SubStationAlpha);

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

            BatchConvertSave(toFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, newFileName, sub, format, overwrite, pacCodePage, targetFrameRate);
            done = true;
            return format;
        }
Example #22
0
 public static void InitializeSubtitleFormatComboBox(ToolStripComboBox comboBox, SubtitleFormat format)
 {
     InitializeSubtitleFormatComboBox(comboBox.ComboBox, format);
     comboBox.DropDownWidth += 5; // .Net quirk?
 }
Example #23
0
 private SubtitleFormat FinalizeFormat(string fileName, bool batchMode, double?sourceFrameRate, List <string> lines, SubtitleFormat subtitleFormat, bool loadSubtitle)
 {
     Header = null;
     subtitleFormat.BatchMode            = batchMode;
     subtitleFormat.BatchSourceFrameRate = sourceFrameRate;
     if (loadSubtitle)
     {
         subtitleFormat.LoadSubtitle(this, lines, fileName);
     }
     OriginalFormat = subtitleFormat;
     return(subtitleFormat);
 }
Example #24
0
 public static void InitializeSubtitleFormatComboBox(ComboBox comboBox, SubtitleFormat format)
 {
     InitializeSubtitleFormatComboBox(comboBox, new[] { format.FriendlyName }, format.FriendlyName);
 }
Example #25
0
        public ModifySelection(Subtitle subtitle, SubtitleFormat format, SubtitleListView subtitleListView)
        {
            UiUtil.PreInitialize(this);
            InitializeComponent();
            UiUtil.FixFonts(this);
            _loading                   = true;
            _subtitle                  = subtitle;
            _format                    = format;
            _subtitleListView          = subtitleListView;
            labelInfo.Text             = string.Empty;
            comboBoxRule.SelectedIndex = 0;
            Text                                  = Configuration.Settings.Language.ModifySelection.Title;
            buttonOK.Text                         = Configuration.Settings.Language.General.Ok;
            buttonCancel.Text                     = Configuration.Settings.Language.General.Cancel;
            buttonApply.Text                      = Configuration.Settings.Language.General.Apply;
            groupBoxRule.Text                     = Configuration.Settings.Language.ModifySelection.Rule;
            groupBoxWhatToDo.Text                 = Configuration.Settings.Language.ModifySelection.DoWithMatches;
            checkBoxCaseSensitive.Text            = Configuration.Settings.Language.ModifySelection.CaseSensitive;
            radioButtonNewSelection.Text          = Configuration.Settings.Language.ModifySelection.MakeNewSelection;
            radioButtonAddToSelection.Text        = Configuration.Settings.Language.ModifySelection.AddToCurrentSelection;
            radioButtonSubtractFromSelection.Text = Configuration.Settings.Language.ModifySelection.SubtractFromCurrentSelection;
            radioButtonIntersect.Text             = Configuration.Settings.Language.ModifySelection.IntersectWithCurrentSelection;
            columnHeaderApply.Text                = Configuration.Settings.Language.General.Apply;
            columnHeaderLine.Text                 = Configuration.Settings.Language.General.LineNumber;
            columnHeaderText.Text                 = Configuration.Settings.Language.General.Text;
            listViewStyles.Visible                = false;

            UiUtil.FixLargeFonts(this, buttonOK);

            comboBoxRule.Items.Clear();
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.Contains);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.StartsWith);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.EndsWith);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.NoContains);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.RegEx);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.UnequalLines);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.EqualLines);
            if (_format.HasStyleSupport)
            {
                comboBoxRule.Items.Add(Configuration.Settings.Language.General.Style);
            }

            checkBoxCaseSensitive.Checked = Configuration.Settings.Tools.ModifySelectionCaseSensitive;
            textBox1.Text = Configuration.Settings.Tools.ModifySelectionText;
            if (Configuration.Settings.Tools.ModifySelectionRule == "Starts with")
            {
                comboBoxRule.SelectedIndex = FunctionStartsWith;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "Ends with")
            {
                comboBoxRule.SelectedIndex = FunctionEndsWith;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "Not contains")
            {
                comboBoxRule.SelectedIndex = FunctionNotContains;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "RegEx")
            {
                comboBoxRule.SelectedIndex = FunctionRegEx;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "Style" && _format.HasStyleSupport)
            {
                comboBoxRule.SelectedIndex = FunctionStyle;
            }
            else
            {
                comboBoxRule.SelectedIndex = 0;
            }

            if (!_format.HasStyleSupport)
            {
                listViewFixes.Columns.Remove(columnHeaderStyle);
            }
            ModifySelection_Resize(null, null);

            _loading = false;
            Preview();
        }
Example #26
0
        public SubStationAlphaProperties(Subtitle subtitle, SubtitleFormat format, string videoFileName, string subtitleFileName)
        {
            InitializeComponent();
            _subtitle          = subtitle;
            _isSubStationAlpha = format.FriendlyName == new SubStationAlpha().FriendlyName;
            _videoFileName     = videoFileName;

            var l = Configuration.Settings.Language.SubStationAlphaProperties;

            if (_isSubStationAlpha)
            {
                Text = l.TitleSubstationAlpha;
                labelWrapStyle.Visible               = false;
                comboBoxWrapStyle.Visible            = false;
                checkBoxScaleBorderAndShadow.Visible = false;
                Height = Height - (comboBoxWrapStyle.Height + checkBoxScaleBorderAndShadow.Height + 8);
            }
            else
            {
                Text = l.Title;
            }

            comboBoxWrapStyle.SelectedIndex = 2;
            comboBoxCollision.SelectedIndex = 0;

            string header = subtitle.Header;

            if (subtitle.Header == null)
            {
                SubStationAlpha ssa   = new SubStationAlpha();
                var             sub   = new Subtitle();
                var             lines = new List <string>();
                foreach (string line in subtitle.ToText(ssa).Replace(Environment.NewLine, "\n").Split('\n'))
                {
                    lines.Add(line);
                }
                string title = "Untitled";
                if (!string.IsNullOrEmpty(subtitleFileName))
                {
                    title = Path.GetFileNameWithoutExtension(subtitleFileName);
                }
                else if (!string.IsNullOrEmpty(videoFileName))
                {
                    title = Path.GetFileNameWithoutExtension(videoFileName);
                }
                ssa.LoadSubtitle(sub, lines, title);
                header = sub.Header;
            }

            if (header != null)
            {
                foreach (string line in header.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                {
                    string s = line.ToLower().Trim();
                    if (s.StartsWith("title:"))
                    {
                        textBoxTitle.Text = s.Remove(0, 6).Trim();
                    }
                    else if (s.StartsWith("original script:"))
                    {
                        textBoxOriginalScript.Text = s.Remove(0, 16).Trim();
                    }
                    else if (s.StartsWith("original translation:"))
                    {
                        textBoxTranslation.Text = s.Remove(0, 21).Trim();
                    }
                    else if (s.StartsWith("original editing:"))
                    {
                        textBoxEditing.Text = s.Remove(0, 17).Trim();
                    }
                    else if (s.StartsWith("original timing:"))
                    {
                        textBoxTiming.Text = s.Remove(0, 16).Trim();
                    }
                    else if (s.StartsWith("synch point:"))
                    {
                        textBoxSyncPoint.Text = s.Remove(0, 12).Trim();
                    }
                    else if (s.StartsWith("script updated by:"))
                    {
                        textBoxUpdatedBy.Text = s.Remove(0, 18).Trim();
                    }
                    else if (s.StartsWith("update details:"))
                    {
                        textBoxUpdateDetails.Text = s.Remove(0, 15).Trim();
                    }
                    else if (s.StartsWith("collisions:"))
                    {
                        if (s.Remove(0, 11).Trim() == "reverse")
                        {
                            comboBoxCollision.SelectedIndex = 1;
                        }
                    }
                    else if (s.StartsWith("playresx:"))
                    {
                        int number;
                        if (int.TryParse(s.Remove(0, 9).Trim(), out number))
                        {
                            numericUpDownVideoWidth.Value = number;
                        }
                    }
                    else if (s.StartsWith("playresy:"))
                    {
                        int number;
                        if (int.TryParse(s.Remove(0, 9).Trim(), out number))
                        {
                            numericUpDownVideoHeight.Value = number;
                        }
                    }
                    else if (s.StartsWith("scaledborderandshadow:"))
                    {
                        checkBoxScaleBorderAndShadow.Checked = s.Remove(0, 22).Trim().ToLower() == "yes";
                    }
                }
            }

            groupBoxScript.Text               = l.Script;
            labelTitle.Text                   = l.ScriptTitle;
            labelOriginalScript.Text          = l.OriginalScript;
            labelTranslation.Text             = l.Translation;
            labelEditing.Text                 = l.Editing;
            labelTiming.Text                  = l.Timing;
            labelSyncPoint.Text               = l.SyncPoint;
            labelUpdatedBy.Text               = l.UpdatedBy;
            labelUpdateDetails.Text           = l.UpdateDetails;
            groupBoxResolution.Text           = l.Resolution;
            labelVideoResolution.Text         = l.VideoResolution;
            groupBoxOptions.Text              = l.Options;
            labelCollision.Text               = l.Collision;
            labelWrapStyle.Text               = l.WrapStyle;
            checkBoxScaleBorderAndShadow.Text = l.ScaleBorderAndShadow;

            buttonOK.Text     = Configuration.Settings.Language.General.Ok;
            buttonCancel.Text = Configuration.Settings.Language.General.Cancel;

            FixLargeFonts();
        }
Example #27
0
        public ModifySelection(Subtitle subtitle, SubtitleFormat format, SubtitleListView subtitleListView)
        {
            UiUtil.PreInitialize(this);
            InitializeComponent();
            UiUtil.FixFonts(this);
            _loading                   = true;
            _subtitle                  = subtitle;
            _format                    = format;
            _subtitleListView          = subtitleListView;
            labelInfo.Text             = string.Empty;
            comboBoxRule.SelectedIndex = 0;
            Text                                   = Configuration.Settings.Language.ModifySelection.Title;
            buttonOK.Text                          = Configuration.Settings.Language.General.Ok;
            buttonCancel.Text                      = Configuration.Settings.Language.General.Cancel;
            buttonApply.Text                       = Configuration.Settings.Language.General.Apply;
            groupBoxRule.Text                      = Configuration.Settings.Language.ModifySelection.Rule;
            groupBoxWhatToDo.Text                  = Configuration.Settings.Language.ModifySelection.DoWithMatches;
            checkBoxCaseSensitive.Text             = Configuration.Settings.Language.ModifySelection.CaseSensitive;
            radioButtonNewSelection.Text           = Configuration.Settings.Language.ModifySelection.MakeNewSelection;
            radioButtonAddToSelection.Text         = Configuration.Settings.Language.ModifySelection.AddToCurrentSelection;
            radioButtonSubtractFromSelection.Text  = Configuration.Settings.Language.ModifySelection.SubtractFromCurrentSelection;
            radioButtonIntersect.Text              = Configuration.Settings.Language.ModifySelection.IntersectWithCurrentSelection;
            columnHeaderApply.Text                 = Configuration.Settings.Language.General.Apply;
            columnHeaderLine.Text                  = Configuration.Settings.Language.General.LineNumber;
            columnHeaderText.Text                  = Configuration.Settings.Language.General.Text;
            toolStripMenuItemInverseSelection.Text = Configuration.Settings.Language.Main.Menu.Edit.InverseSelection;
            toolStripMenuItemSelectAll.Text        = Configuration.Settings.Language.Main.Menu.ContextMenu.SelectAll;

            listViewStyles.Visible = false;

            UiUtil.FixLargeFonts(this, buttonOK);

            comboBoxRule.Items.Clear();
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.Contains);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.StartsWith);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.EndsWith);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.NoContains);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ChangeCasing.AllUppercase);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.RegEx);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.UnequalLines);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.EqualLines);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.DurationLessThan);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.DurationGreaterThan);
            comboBoxRule.Items.Add(Configuration.Settings.Language.ModifySelection.MoreThanTwoLines);
            if (_format.HasStyleSupport)
            {
                comboBoxRule.Items.Add(Configuration.Settings.Language.General.Style);
            }
            if (_format.HasStyleSupport && (_format.GetType() == typeof(AdvancedSubStationAlpha) || _format.GetType() == typeof(SubStationAlpha)))
            {
                comboBoxRule.Items.Add(Configuration.Settings.Language.General.Actor);
            }

            checkBoxCaseSensitive.Checked = Configuration.Settings.Tools.ModifySelectionCaseSensitive;
            textBoxText.Text = Configuration.Settings.Tools.ModifySelectionText;
            if (Configuration.Settings.Tools.ModifySelectionRule == "Starts with")
            {
                comboBoxRule.SelectedIndex = FunctionStartsWith;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "Ends with")
            {
                comboBoxRule.SelectedIndex = FunctionEndsWith;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "Not contains")
            {
                comboBoxRule.SelectedIndex = FunctionNotContains;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "AllUppercase")
            {
                comboBoxRule.SelectedIndex = FunctionAlUppercase;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "RegEx")
            {
                comboBoxRule.SelectedIndex = FunctionRegEx;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "Duration <")
            {
                comboBoxRule.SelectedIndex = FunctionDurationLessThan;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "Duration >")
            {
                comboBoxRule.SelectedIndex = FunctionDurationGreaterThan;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "More than two lines")
            {
                comboBoxRule.SelectedIndex = FunctionMoreThanTwoLines;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "Style" && _format.HasStyleSupport)
            {
                comboBoxRule.SelectedIndex = FunctionStyle;
            }
            else if (Configuration.Settings.Tools.ModifySelectionRule == "Actor" && (_format.GetType() == typeof(AdvancedSubStationAlpha) || _format.GetType() == typeof(SubStationAlpha)))
            {
                comboBoxRule.SelectedIndex = FunctionActor;
            }
            else
            {
                comboBoxRule.SelectedIndex = 0;
            }

            if (!_format.HasStyleSupport)
            {
                listViewFixes.Columns.Remove(columnHeaderStyle);
            }
            ModifySelection_Resize(null, null);

            _loading = false;
            Preview();
        }
Example #28
0
        public SubtitleFormat LoadSubtitle(string fileName, out Encoding encoding, Encoding useThisEncoding, bool batchMode)
        {
            FileName = fileName;

            _paragraphs = new List <Paragraph>();

            var          lines = new List <string>();
            StreamReader sr;

            if (useThisEncoding != null)
            {
                try
                {
                    sr = new StreamReader(fileName, useThisEncoding);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                    encoding = Encoding.UTF8;
                    return(null);
                }
            }
            else
            {
                try
                {
                    sr = new StreamReader(fileName, Utilities.GetEncodingFromFile(fileName), true);
                }
                catch
                {
                    try
                    {
                        Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        sr = new StreamReader(fs);
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                        encoding = Encoding.UTF8;
                        return(null);
                    }
                }
            }

            encoding = sr.CurrentEncoding;
            while (!sr.EndOfStream)
            {
                lines.Add(sr.ReadLine());
            }
            sr.Close();

            foreach (SubtitleFormat subtitleFormat in SubtitleFormat.AllSubtitleFormats)
            {
                if (subtitleFormat.IsMine(lines, fileName))
                {
                    Header = null;
                    subtitleFormat.BatchMode = batchMode;
                    subtitleFormat.LoadSubtitle(this, lines, fileName);
                    _format = subtitleFormat;
                    _wasLoadedWithFrameNumbers = _format.IsFrameBased;
                    if (_wasLoadedWithFrameNumbers)
                    {
                        CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                    }
                    return(subtitleFormat);
                }
            }

            if (useThisEncoding == null)
            {
                return(LoadSubtitle(fileName, out encoding, Encoding.Unicode));
            }

            return(null);
        }
        private Subtitle ImportTimeCodesInFramesAndTextOnSameLine(List <string> lines)
        {
            var       regexTimeCodes1 = new Regex(@"\d+", RegexOptions.Compiled);
            Paragraph p        = null;
            var       subtitle = new Subtitle();
            var       sb       = new StringBuilder();

            for (int idx = 0; idx < lines.Count; idx++)
            {
                string line = lines[idx];

                var matches = regexTimeCodes1.Matches(line);
                if (matches.Count >= 2)
                {
                    string start = matches[0].ToString();
                    string end   = matches[1].ToString();

                    if (p != null)
                    {
                        p.Text = sb.ToString().Trim();
                        subtitle.Paragraphs.Add(p);
                    }
                    p = new Paragraph();
                    sb.Clear();
                    try
                    {
                        if (UseFrames)
                        {
                            p.StartTime.TotalMilliseconds = SubtitleFormat.FramesToMilliseconds(int.Parse(start));
                            p.EndTime.TotalMilliseconds   = SubtitleFormat.FramesToMilliseconds(int.Parse(end));
                        }
                        else
                        {
                            p.StartTime.TotalMilliseconds = double.Parse(start);
                            p.EndTime.TotalMilliseconds   = double.Parse(end);
                        }
                    }
                    catch
                    {
                        p = null;
                    }

                    if (matches[0].Index < 9)
                    {
                        line = line.Remove(0, matches[0].Index);
                    }

                    line = line.Replace(matches[0].ToString(), string.Empty);
                    line = line.Replace(matches[1].ToString(), string.Empty);
                    line = line.Trim();
                    if (line.StartsWith("}{}", StringComparison.Ordinal) || line.StartsWith("][]", StringComparison.Ordinal))
                    {
                        line = line.Remove(0, 3);
                    }

                    line = line.Trim();
                }
                if (p != null && line.Length > 1)
                {
                    sb.AppendLine(line.Trim());
                    if (sb.Length > 200)
                    {
                        return(new Subtitle());
                    }
                }
            }
            if (p != null)
            {
                p.Text = sb.ToString().Trim();
                subtitle.Paragraphs.Add(p);
            }
            subtitle.Renumber();
            return(subtitle);
        }
Example #30
0
        public static int BridgeGaps(Subtitle subtitle, int minMsBetweenLines, bool divideEven, double maxMs, List <int> fixedIndexes, Dictionary <string, string> dic, bool useFrames)
        {
            int fixedCount = 0;

            if (minMsBetweenLines > maxMs)
            {
                string message = $"{nameof(DurationsBridgeGaps)}: {nameof(minMsBetweenLines)} cannot be larger than {nameof(maxMs)}!";
                SeLogger.Error(new InvalidOperationException(message), message);
                return(0);
            }

            int count = subtitle.Paragraphs.Count - 1;

            for (int i = 0; i < count; i++)
            {
                var cur  = subtitle.Paragraphs[i];
                var next = subtitle.Paragraphs[i + 1];

                double currentGap = next.StartTime.TotalMilliseconds - cur.EndTime.TotalMilliseconds;

                // there shouldn't be adjustment if current gaps is shorter or equal than minimum gap or greater than maximum gaps
                if (currentGap <= minMsBetweenLines || currentGap > maxMs)
                {
                    continue;
                }

                // next paragraph start-time will be pull to try to meet the current paragraph
                if (divideEven)
                {
                    next.StartTime.TotalMilliseconds -= currentGap / 2.0;
                }

                cur.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - minMsBetweenLines;
                if (fixedIndexes != null)
                {
                    fixedIndexes.Add(i);
                    fixedIndexes.Add(i + 1);
                }
                fixedCount++;

                double newGap = next.StartTime.TotalMilliseconds - cur.EndTime.TotalMilliseconds;
                if (useFrames)
                {
                    dic?.Add(cur.Id, $"{SubtitleFormat.MillisecondsToFrames(currentGap)} => {SubtitleFormat.MillisecondsToFrames(newGap)}");
                }
                else
                {
                    dic?.Add(cur.Id, $"{currentGap / TimeCode.BaseUnit:0.000} => {newGap / TimeCode.BaseUnit:0.000}");
                }
            }

            return(fixedCount);
        }
        private static TimeCode DecodeTime(string[] parts)
        {
            try
            {
                string hour    = parts[0];
                string minutes = parts[1];
                string seconds = parts[2];
                string frames;
                if (parts.Length < 4)
                {
                    frames  = seconds;
                    seconds = minutes;
                    minutes = hour;
                    hour    = "0";
                }
                else
                {
                    frames = parts[3];
                }

                if (frames.Length < 3)
                {
                    return(new TimeCode(int.Parse(hour), int.Parse(minutes), int.Parse(seconds), SubtitleFormat.FramesToMillisecondsMax999(int.Parse(frames))));
                }

                return(new TimeCode(int.Parse(hour), int.Parse(minutes), int.Parse(seconds), int.Parse(frames)));
            }
            catch
            {
                return(new TimeCode());
            }
        }
Example #32
0
        internal static string GetParagraph(string template, string start, string end, string text, string translation, int number, string actor, TimeCode duration, string timeCodeTemplate)
        {
            string d = duration.ToString();

            if (timeCodeTemplate == "ff" || timeCodeTemplate == "f")
            {
                d = SubtitleFormat.MillisecondsToFrames(duration.TotalMilliseconds).ToString(CultureInfo.InvariantCulture);
            }
            if (timeCodeTemplate == "zzz" || timeCodeTemplate == "zz" || timeCodeTemplate == "z")
            {
                d = duration.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
            }
            if (timeCodeTemplate == "sss" || timeCodeTemplate == "ss" || timeCodeTemplate == "s")
            {
                d = duration.Seconds.ToString(CultureInfo.InvariantCulture);
            }
            else if (timeCodeTemplate.EndsWith("ss.ff", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}.{SubtitleFormat.MillisecondsToFramesMaxFrameRate(duration.Milliseconds):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss:ff", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}:{SubtitleFormat.MillisecondsToFramesMaxFrameRate(duration.Milliseconds):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss,ff", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00},{SubtitleFormat.MillisecondsToFramesMaxFrameRate(duration.Milliseconds):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss;ff", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00};{SubtitleFormat.MillisecondsToFramesMaxFrameRate(duration.Milliseconds):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss;ff", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00};{SubtitleFormat.MillisecondsToFramesMaxFrameRate(duration.Milliseconds):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss.zzz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}.{duration.Milliseconds:000}";
            }
            else if (timeCodeTemplate.EndsWith("ss:zzz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}:{duration.Milliseconds:000}";
            }
            else if (timeCodeTemplate.EndsWith("ss,zzz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00},{duration.Milliseconds:000}";
            }
            else if (timeCodeTemplate.EndsWith("ss;zzz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00};{duration.Milliseconds:000}";
            }
            else if (timeCodeTemplate.EndsWith("ss;zzz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00};{duration.Milliseconds:000}";
            }
            else if (timeCodeTemplate.EndsWith("ss.zz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}.{Math.Round(duration.Milliseconds / 10.0):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss:zz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}:{Math.Round(duration.Milliseconds / 10.0):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss,zz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00},{Math.Round(duration.Milliseconds / 10.0):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss;zz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00};{Math.Round(duration.Milliseconds / 10.0):00}";
            }

            string s = template;

            s = s.Replace("{{", "@@@@_@@@{");
            s = s.Replace("}}", "}@@@_@@@@");
            s = string.Format(s, start, end, text, translation, number + 1, number, d, actor);
            s = s.Replace("@@@@_@@@", "{");
            s = s.Replace("@@@_@@@@", "}");
            return(s);
        }
Example #33
0
        internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList <SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage, double?targetFrameRate, bool removeTextForHi, bool fixCommonErrors, bool redoCasing)
        {
            double oldFrameRate = Configuration.Settings.General.CurrentFrameRate;

            try
            {
                // adjust offset
                if (!string.IsNullOrEmpty(offset) && (offset.StartsWith("/offset:", StringComparison.Ordinal) || offset.StartsWith("offset:", StringComparison.Ordinal)))
                {
                    string[] parts = offset.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length == 5)
                    {
                        try
                        {
                            var ts = new TimeSpan(0, int.Parse(parts[1].TrimStart('-')), int.Parse(parts[2]), int.Parse(parts[3]), int.Parse(parts[4]));
                            if (parts[1].StartsWith('-'))
                            {
                                sub.AddTimeToAllParagraphs(ts.Negate());
                            }
                            else
                            {
                                sub.AddTimeToAllParagraphs(ts);
                            }
                        }
                        catch
                        {
                            Console.Write(" (unable to read offset " + offset + ")");
                        }
                    }
                }

                // adjust frame rate
                if (targetFrameRate.HasValue)
                {
                    sub.ChangeFrameRate(Configuration.Settings.General.CurrentFrameRate, targetFrameRate.Value);
                    Configuration.Settings.General.CurrentFrameRate = targetFrameRate.Value;
                }

                if (removeTextForHi)
                {
                    var hiSettings = new Core.Forms.RemoveTextForHISettings();
                    var hiLib      = new Core.Forms.RemoveTextForHI(hiSettings);
                    foreach (var p in sub.Paragraphs)
                    {
                        p.Text = hiLib.RemoveTextFromHearImpaired(p.Text);
                    }
                }
                if (fixCommonErrors)
                {
                    using (var fce = new FixCommonErrors {
                        BatchMode = true
                    })
                    {
                        for (int i = 0; i < 3; i++)
                        {
                            fce.RunBatch(sub, format, targetEncoding, Configuration.Settings.Tools.BatchConvertLanguage);
                            sub = fce.FixedSubtitle;
                        }
                    }
                }
                if (redoCasing)
                {
                    using (var changeCasing = new ChangeCasing())
                    {
                        changeCasing.FixCasing(sub, LanguageAutoDetect.AutoDetectGoogleLanguage(sub));
                    }
                    using (var changeCasingNames = new ChangeCasingNames())
                    {
                        changeCasingNames.Initialize(sub);
                        changeCasingNames.FixCasing();
                    }
                }

                bool   targetFormatFound = false;
                string outputFileName;
                foreach (SubtitleFormat sf in formats)
                {
                    if (sf.IsTextBased && (sf.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || sf.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)))
                    {
                        targetFormatFound = true;
                        sf.BatchMode      = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, sf.Extension, outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        if (sf.IsFrameBased && !sub.WasLoadedWithFrameNumbers)
                        {
                            sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate);
                        }
                        else if (sf.IsTimeBased && sub.WasLoadedWithFrameNumbers)
                        {
                            sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                        }

                        if ((sf.GetType() == typeof(WebVTT) || sf.GetType() == typeof(WebVTTFileWithLineNumber)))
                        {
                            targetEncoding = Encoding.UTF8;
                        }

                        if (sf.GetType() == typeof(ItunesTimedText) || sf.GetType() == typeof(ScenaristClosedCaptions) || sf.GetType() == typeof(ScenaristClosedCaptionsDropFrame))
                        {
                            Encoding outputEnc = new UTF8Encoding(false);                         // create encoding with no BOM
                            using (var file = new StreamWriter(outputFileName, false, outputEnc)) // open file with encoding
                            {
                                file.Write(sub.ToText(sf));
                            } // save and close it
                        }
                        else if (targetEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml)))
                        {
                            Encoding outputEnc = new UTF8Encoding(false);                         // create encoding with no BOM
                            using (var file = new StreamWriter(outputFileName, false, outputEnc)) // open file with encoding
                            {
                                file.Write(sub.ToText(sf));
                            } // save and close it
                        }
                        else
                        {
                            try
                            {
                                File.WriteAllText(outputFileName, sub.ToText(sf), targetEncoding);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                errors++;
                                return(false);
                            }
                        }

                        if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern))
                        {
                            var sami = (Sami)format;
                            foreach (string className in Sami.GetStylesFromHeader(sub.Header))
                            {
                                var newSub = new Subtitle();
                                foreach (Paragraph p in sub.Paragraphs)
                                {
                                    if (p.Extra != null && p.Extra.Trim().Equals(className.Trim(), StringComparison.OrdinalIgnoreCase))
                                    {
                                        newSub.Paragraphs.Add(p);
                                    }
                                }
                                if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count)
                                {
                                    string s = fileName;
                                    if (s.LastIndexOf('.') > 0)
                                    {
                                        s = s.Insert(s.LastIndexOf('.'), "_" + className);
                                    }
                                    else
                                    {
                                        s += "_" + className + format.Extension;
                                    }
                                    outputFileName = FormatOutputFileNameForBatchConvert(s, sf.Extension, outputFolder, overwrite);
                                    File.WriteAllText(outputFileName, newSub.ToText(sf), targetEncoding);
                                }
                            }
                        }
                        Console.WriteLine(" done.");
                        break;
                    }
                }
                if (!targetFormatFound)
                {
                    var ebu = new Ebu();
                    if (ebu.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        Ebu.Save(outputFileName, sub, true);
                        Console.WriteLine(" done.");
                    }
                }
                if (!targetFormatFound)
                {
                    var pac = new Pac();
                    if (pac.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) || toFormat.Equals("pac", StringComparison.OrdinalIgnoreCase) || toFormat.Equals(".pac", StringComparison.OrdinalIgnoreCase))
                    {
                        pac.BatchMode = true;
                        int codePage;
                        if (!string.IsNullOrEmpty(pacCodePage) && int.TryParse(pacCodePage, out codePage))
                        {
                            pac.CodePage = codePage;
                        }
                        targetFormatFound = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        pac.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }
                if (!targetFormatFound)
                {
                    var cavena890 = new Cavena890();
                    if (cavena890.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        cavena890.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }
                if (!targetFormatFound)
                {
                    var cheetahCaption = new CheetahCaption();
                    if (cheetahCaption.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, cheetahCaption.Extension, outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        CheetahCaption.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }
                if (!targetFormatFound)
                {
                    var ayato = new Ayato();
                    if (ayato.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, ayato.Extension, outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        ayato.Save(outputFileName, null, sub);
                        Console.WriteLine(" done.");
                    }
                }
                if (!targetFormatFound)
                {
                    var capMakerPlus = new CapMakerPlus();
                    if (capMakerPlus.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, capMakerPlus.Extension, outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        CapMakerPlus.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }
                if (!targetFormatFound)
                {
                    if (Configuration.Settings.Language.BatchConvert.PlainText == toFormat || Configuration.Settings.Language.BatchConvert.PlainText.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, ".txt", outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        File.WriteAllText(outputFileName, ExportText.GeneratePlainText(sub, false, false, false, false, false, false, string.Empty, true, false, true, true, false), targetEncoding);
                        Console.WriteLine(" done.");
                    }
                }
                if (!targetFormatFound)
                {
                    if (string.Compare(BatchConvert.BluRaySubtitle, toFormat, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(BatchConvert.BluRaySubtitle.Replace(" ", string.Empty), toFormat, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        targetFormatFound = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, ".sup", outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        using (var form = new ExportPngXml())
                        {
                            form.Initialize(sub, format, "BLURAYSUP", fileName, null, null);
                            var binarySubtitleFile = new FileStream(outputFileName, FileMode.Create);
                            int width  = 1920;
                            int height = 1080;
                            var parts  = Configuration.Settings.Tools.ExportBluRayVideoResolution.Split('x');
                            if (parts.Length == 2 && Utilities.IsInteger(parts[0]) && Utilities.IsInteger(parts[1]))
                            {
                                width  = int.Parse(parts[0]);
                                height = int.Parse(parts[1]);
                            }
                            for (int index = 0; index < sub.Paragraphs.Count; index++)
                            {
                                var mp = form.MakeMakeBitmapParameter(index, width, height);
                                mp.LineJoin = Configuration.Settings.Tools.ExportPenLineJoin;
                                mp.Bitmap   = ExportPngXml.GenerateImageFromTextWithStyle(mp);
                                ExportPngXml.MakeBluRaySupImage(mp);
                                binarySubtitleFile.Write(mp.Buffer, 0, mp.Buffer.Length);
                            }
                            binarySubtitleFile.Close();
                        }
                        Console.WriteLine(" done.");
                    }
                    else if (string.Compare(BatchConvert.VobSubSubtitle, toFormat, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(BatchConvert.VobSubSubtitle.Replace(" ", string.Empty), toFormat, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        targetFormatFound = true;
                        outputFileName    = FormatOutputFileNameForBatchConvert(fileName, ".sub", outputFolder, overwrite);
                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        using (var form = new ExportPngXml())
                        {
                            form.Initialize(sub, format, "VOBSUB", fileName, null, null);
                            int width  = 720;
                            int height = 576;
                            var parts  = Configuration.Settings.Tools.ExportVobSubVideoResolution.Split('x');
                            if (parts.Length == 2 && Utilities.IsInteger(parts[0]) && Utilities.IsInteger(parts[1]))
                            {
                                width  = int.Parse(parts[0]);
                                height = int.Parse(parts[1]);
                            }

                            var cfg           = Configuration.Settings.Tools;
                            var languageIndex = IfoParser.LanguageCodes.IndexOf(LanguageAutoDetect.AutoDetectGoogleLanguageOrNull(sub));
                            if (languageIndex < 0)
                            {
                                languageIndex = IfoParser.LanguageCodes.IndexOf("en");
                            }
                            using (var vobSubWriter = new VobSubWriter(outputFileName, width, height, cfg.ExportBottomMargin, cfg.ExportBottomMargin, 32, cfg.ExportFontColor, cfg.ExportBorderColor, !cfg.ExportVobAntiAliasingWithTransparency, IfoParser.LanguageNames[languageIndex], IfoParser.LanguageCodes[languageIndex]))
                            {
                                for (int index = 0; index < sub.Paragraphs.Count; index++)
                                {
                                    var mp = form.MakeMakeBitmapParameter(index, width, height);
                                    mp.LineJoin = Configuration.Settings.Tools.ExportPenLineJoin;
                                    mp.Bitmap   = ExportPngXml.GenerateImageFromTextWithStyle(mp);
                                    vobSubWriter.WriteParagraph(mp.P, mp.Bitmap, mp.Alignment);
                                }
                                vobSubWriter.WriteIdxFile();
                            }
                        }
                        Console.WriteLine(" done.");
                    }
                }
                if (!targetFormatFound)
                {
                    Console.WriteLine("{0}: {1} - target format '{2}' not found!", count, fileName, toFormat);
                    errors++;
                    return(false);
                }
                converted++;
                return(true);
            }
            finally
            {
                Configuration.Settings.General.CurrentFrameRate = oldFrameRate;
            }
        }
        public static string GetTimeCode(TimeCode timeCode, string template)
        {
            var t = template;
            var templateTrimmed = t.Trim();

            if (templateTrimmed == "ss")
            {
                t = t.Replace("ss", $"{timeCode.TotalSeconds:00}");
            }

            if (templateTrimmed == "s")
            {
                t = t.Replace("s", $"{timeCode.TotalSeconds}");
            }

            if (templateTrimmed == "zzz")
            {
                t = t.Replace("zzz", $"{timeCode.TotalMilliseconds:000}");
            }

            if (templateTrimmed == "z")
            {
                t = t.Replace("z", $"{timeCode.TotalMilliseconds}");
            }

            if (templateTrimmed == "ff")
            {
                t = t.Replace("ff", $"{SubtitleFormat.MillisecondsToFrames(timeCode.TotalMilliseconds)}");
            }

            var totalSeconds = (int)timeCode.TotalSeconds;

            if (t.StartsWith("ssssssss", StringComparison.Ordinal))
            {
                t = t.Replace("ssssssss", $"{totalSeconds:00000000}");
            }

            if (t.StartsWith("sssssss", StringComparison.Ordinal))
            {
                t = t.Replace("sssssss", $"{totalSeconds:0000000}");
            }

            if (t.StartsWith("ssssss", StringComparison.Ordinal))
            {
                t = t.Replace("ssssss", $"{totalSeconds:000000}");
            }

            if (t.StartsWith("sssss", StringComparison.Ordinal))
            {
                t = t.Replace("sssss", $"{totalSeconds:00000}");
            }

            if (t.StartsWith("ssss", StringComparison.Ordinal))
            {
                t = t.Replace("ssss", $"{totalSeconds:0000}");
            }

            if (t.StartsWith("sss", StringComparison.Ordinal))
            {
                t = t.Replace("sss", $"{totalSeconds:000}");
            }

            if (t.StartsWith("ss", StringComparison.Ordinal))
            {
                t = t.Replace("ss", $"{totalSeconds:00}");
            }

            var totalMilliseconds = (long)timeCode.TotalMilliseconds;

            if (t.StartsWith("zzzzzzzz", StringComparison.Ordinal))
            {
                t = t.Replace("zzzzzzzz", $"{totalMilliseconds:00000000}");
            }

            if (t.StartsWith("zzzzzzz", StringComparison.Ordinal))
            {
                t = t.Replace("zzzzzzz", $"{totalMilliseconds:0000000}");
            }

            if (t.StartsWith("zzzzzz", StringComparison.Ordinal))
            {
                t = t.Replace("zzzzzz", $"{totalMilliseconds:000000}");
            }

            if (t.StartsWith("zzzzz", StringComparison.Ordinal))
            {
                t = t.Replace("zzzzz", $"{totalMilliseconds:00000}");
            }

            if (t.StartsWith("zzzz", StringComparison.Ordinal))
            {
                t = t.Replace("zzzz", $"{totalMilliseconds:0000}");
            }

            if (t.StartsWith("zzz", StringComparison.Ordinal))
            {
                t = t.Replace("zzz", $"{totalMilliseconds:000}");
            }

            t = t.Replace("hh", $"{timeCode.Hours:00}");
            t = t.Replace("h", $"{timeCode.Hours}");
            t = t.Replace("mm", $"{timeCode.Minutes:00}");
            t = t.Replace("m", $"{timeCode.Minutes}");
            t = t.Replace("ss", $"{timeCode.Seconds:00}");
            t = t.Replace("s", $"{timeCode.Seconds}");
            t = t.Replace("zzz", $"{timeCode.Milliseconds:000}");
            t = t.Replace("zz", $"{Math.Round(timeCode.Milliseconds / 10.0):00}");
            t = t.Replace("z", $"{Math.Round(timeCode.Milliseconds / 100.0):0}");
            t = t.Replace("ff", $"{SubtitleFormat.MillisecondsToFramesMaxFrameRate(timeCode.Milliseconds):00}");
            t = t.Replace("f", $"{SubtitleFormat.MillisecondsToFramesMaxFrameRate(timeCode.Milliseconds)}");
            return(t);
        }
Example #35
0
        public void Initialize(Subtitle subtitle, string fileName, SubtitleFormat format)
        {
            ShowBasic = false;
            _subtitle = subtitle;
            if (string.IsNullOrEmpty(fileName))
            {
                textBoxFileName.Text = Configuration.Settings.Language.SplitSubtitle.Untitled;
            }
            else
            {
                textBoxFileName.Text = fileName;
            }

            _fileName = fileName;
            foreach (Paragraph p in _subtitle.Paragraphs)
            {
                _totalNumberOfCharacters += HtmlUtil.RemoveHtmlTags(p.Text, true).Length;
            }

            labelLines.Text      = string.Format(Configuration.Settings.Language.Split.NumberOfLinesX, _subtitle.Paragraphs.Count);
            labelCharacters.Text = string.Format(Configuration.Settings.Language.Split.NumberOfCharactersX, _totalNumberOfCharacters);

            try
            {
                numericUpDownParts.Value = Configuration.Settings.Tools.SplitNumberOfParts;
            }
            catch
            {
                // ignored
            }

            if (Configuration.Settings.Tools.SplitVia.Trim().Equals("lines", StringComparison.OrdinalIgnoreCase))
            {
                RadioButtonLines.Checked = true;
            }
            else
            {
                radioButtonCharacters.Checked = true;
            }

            UiUtil.InitializeSubtitleFormatComboBox(comboBoxSubtitleFormats, format.FriendlyName);

            UiUtil.InitializeTextEncodingComboBox(comboBoxEncoding);

            if (numericUpDownParts.Maximum > _subtitle.Paragraphs.Count)
            {
                numericUpDownParts.Maximum = (int)Math.Round(_subtitle.Paragraphs.Count / 2.0);
            }

            if (!string.IsNullOrEmpty(_fileName))
            {
                textBoxOutputFolder.Text = Path.GetDirectoryName(_fileName);
            }
            else if (string.IsNullOrEmpty(Configuration.Settings.Tools.SplitOutputFolder) || !Directory.Exists(Configuration.Settings.Tools.SplitOutputFolder))
            {
                textBoxOutputFolder.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            }
            else
            {
                textBoxOutputFolder.Text = Configuration.Settings.Tools.SplitOutputFolder;
            }
        }
        internal static string GetParagraph(string template, string start, string end, string text, string translation, int number, string actor, TimeCode duration, string timeCodeTemplate, Paragraph p)
        {
            var cps = Utilities.GetCharactersPerSecond(p);
            var d   = duration.ToString();

            if (timeCodeTemplate == "ff" || timeCodeTemplate == "f")
            {
                d = SubtitleFormat.MillisecondsToFrames(duration.TotalMilliseconds).ToString(CultureInfo.InvariantCulture);
            }

            if (timeCodeTemplate == "zzz" || timeCodeTemplate == "zz" || timeCodeTemplate == "z")
            {
                d = duration.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
            }

            if (timeCodeTemplate == "sss" || timeCodeTemplate == "ss" || timeCodeTemplate == "s")
            {
                d = duration.Seconds.ToString(CultureInfo.InvariantCulture);
            }
            else if (timeCodeTemplate.EndsWith("ss.ff", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}.{SubtitleFormat.MillisecondsToFramesMaxFrameRate(duration.Milliseconds):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss:ff", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}:{SubtitleFormat.MillisecondsToFramesMaxFrameRate(duration.Milliseconds):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss,ff", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00},{SubtitleFormat.MillisecondsToFramesMaxFrameRate(duration.Milliseconds):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss;ff", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00};{SubtitleFormat.MillisecondsToFramesMaxFrameRate(duration.Milliseconds):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss.zzz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}.{duration.Milliseconds:000}";
            }
            else if (timeCodeTemplate.EndsWith("ss:zzz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}:{duration.Milliseconds:000}";
            }
            else if (timeCodeTemplate.EndsWith("ss,zzz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00},{duration.Milliseconds:000}";
            }
            else if (timeCodeTemplate.EndsWith("ss;zzz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00};{duration.Milliseconds:000}";
            }
            else if (timeCodeTemplate.EndsWith("ss.zz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}.{Math.Round(duration.Milliseconds / 10.0):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss:zz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00}:{Math.Round(duration.Milliseconds / 10.0):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss,zz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00},{Math.Round(duration.Milliseconds / 10.0):00}";
            }
            else if (timeCodeTemplate.EndsWith("ss;zz", StringComparison.Ordinal))
            {
                d = $"{duration.Seconds:00};{Math.Round(duration.Milliseconds / 10.0):00}";
            }

            var lines = text.SplitToLines();
            var line1 = string.Empty;
            var line2 = string.Empty;

            if (lines.Count > 0)
            {
                line1 = lines[0];
            }

            if (lines.Count > 1)
            {
                line2 = lines[1];
            }

            var s = template;

            s = s.Replace("{{", "@@@@_@@@{");
            s = s.Replace("}}", "}@@@_@@@@");
            s = string.Format(s, start, end, text, translation, number + 1, number, d, actor, line1, line2,
                              cps.ToString(CultureInfo.InvariantCulture).Replace(".", ","),
                              cps.ToString(CultureInfo.InvariantCulture),
                              text.Length,
                              p.Text.RemoveChar('\r', '\n').Length,
                              p.Text.RemoveChar('\r', '\n').Length + lines.Count - 1,
                              p.Text.RemoveChar('\r', '\n').Length + (lines.Count - 1) * 2);
            s = s.Replace("@@@@_@@@", "{");
            s = s.Replace("@@@_@@@@", "}");
            return(s);
        }
Example #37
0
        public SubtitleFormat LoadSubtitle(string fileName, out Encoding encoding, Encoding useThisEncoding, bool batchMode, double?sourceFrameRate = null)
        {
            FileName = fileName;

            _paragraphs = new List <Paragraph>();

            StreamReader sr;

            if (useThisEncoding != null)
            {
                try
                {
                    sr = new StreamReader(fileName, useThisEncoding);
                }
                catch (Exception exception)
                {
                    System.Diagnostics.Debug.WriteLine(exception.Message);
                    encoding = Encoding.UTF8;
                    return(null);
                }
            }
            else
            {
                try
                {
                    sr = new StreamReader(fileName, LanguageAutoDetect.GetEncodingFromFile(fileName), true);
                }
                catch
                {
                    try
                    {
                        Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        sr = new StreamReader(fs);
                    }
                    catch (Exception exception)
                    {
                        System.Diagnostics.Debug.WriteLine(exception.Message);
                        encoding = Encoding.UTF8;
                        return(null);
                    }
                }
            }

            encoding = sr.CurrentEncoding;
            var lines = sr.ReadToEnd().SplitToLines();

            sr.Close();

            foreach (SubtitleFormat subtitleFormat in SubtitleFormat.AllSubtitleFormats)
            {
                if (subtitleFormat.IsMine(lines, fileName))
                {
                    Header = null;
                    subtitleFormat.BatchMode            = batchMode;
                    subtitleFormat.BatchSourceFrameRate = sourceFrameRate;
                    subtitleFormat.LoadSubtitle(this, lines, fileName);
                    _format = subtitleFormat;
                    _wasLoadedWithFrameNumbers = _format.IsFrameBased;
                    if (_wasLoadedWithFrameNumbers)
                    {
                        CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                    }
                    return(subtitleFormat);
                }
            }

            if (useThisEncoding == null)
            {
                return(LoadSubtitle(fileName, out encoding, Encoding.Unicode));
            }

            return(null);
        }
Example #38
0
        public string ToShortStringHHMMSSFF()
        {
            var ts = TimeSpan;

            if (ts.Minutes == 0 && ts.Hours == 0)
            {
                return(string.Format("{0:00}:{1:00}", ts.Seconds, SubtitleFormat.MillisecondsToFramesMaxFrameRate(ts.Milliseconds)));
            }
            if (ts.Hours == 0)
            {
                return(string.Format("{0:00}:{1:00}:{2:00}", ts.Minutes, ts.Seconds, SubtitleFormat.MillisecondsToFramesMaxFrameRate(ts.Milliseconds)));
            }
            return(string.Format("{0:00}:{1:00}:{2:00}:{3:00}", ts.Hours, ts.Minutes, ts.Seconds, SubtitleFormat.MillisecondsToFramesMaxFrameRate(ts.Milliseconds)));
        }
Example #39
0
        public string GetFileNameWithTargetLanguage(string oldFileName, string videoFileName, Subtitle oldSubtitle, SubtitleFormat subtitleFormat)
        {
            if (!string.IsNullOrEmpty(_targetTwoLetterIsoLanguageName))
            {
                if (!string.IsNullOrEmpty(videoFileName))
                {
                    return(Path.GetFileNameWithoutExtension(videoFileName) + "." + _targetTwoLetterIsoLanguageName.ToLowerInvariant() + subtitleFormat.Extension);
                }

                if (!string.IsNullOrEmpty(oldFileName))
                {
                    var s = Path.GetFileNameWithoutExtension(oldFileName);
                    if (oldSubtitle != null)
                    {
                        var lang = "." + LanguageAutoDetect.AutoDetectGoogleLanguage(oldSubtitle);
                        if (lang.Length == 3 && s.EndsWith(lang, StringComparison.OrdinalIgnoreCase))
                        {
                            s = s.Remove(s.Length - 3);
                        }
                    }
                    return(s + "." + _targetTwoLetterIsoLanguageName.ToLowerInvariant() + subtitleFormat.Extension);
                }
            }
            return(null);
        }
Example #40
0
        public string ToHHMMSSPeriodFF()
        {
            var ts = TimeSpan;

            return(string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, SubtitleFormat.MillisecondsToFramesMaxFrameRate(ts.Milliseconds)));
        }
Example #41
0
 /// <exception cref="EncodingNotSupportedException">Thrown if the encoding is not supported by the platform.</exception>
 /// <exception cref="UnknownSubtitleFormatException">Thrown if the subtitle format could not be detected.</exception>
 internal string Read(string path, out Encoding encoding, out SubtitleFormat format)
 {
     using (FileStream fileStream = FileInputOutput.OpenFileForReading(path)) {
         return(ReadSubtitleText(true, fileStream, out encoding, out format));
     }
 }
        internal static bool BatchConvertSave(string toFormat, string offset, Encoding targetEncoding, string outputFolder, int count, ref int converted, ref int errors, IList<SubtitleFormat> formats, string fileName, Subtitle sub, SubtitleFormat format, bool overwrite, string pacCodePage, double? targetFrameRate)
        {
            double oldFrameRate = Configuration.Settings.General.CurrentFrameRate;
            try
            {
                // adjust offset
                AdjustOffset(offset, sub);

                // adjust frame rate
                if (targetFrameRate.HasValue)
                {
                    sub.ChangeFrameRate(Configuration.Settings.General.CurrentFrameRate, targetFrameRate.Value);
                    Configuration.Settings.General.CurrentFrameRate = targetFrameRate.Value;
                }

                bool targetFormatFound = false;
                string outputFileName;
                foreach (SubtitleFormat subtitleFormat in formats)
                {
                    if (subtitleFormat.IsTextBased && (
                        subtitleFormat.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) ||
                        subtitleFormat.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase)))
                    {
                        targetFormatFound = true;
                        subtitleFormat.BatchMode = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, subtitleFormat.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);

                        if (subtitleFormat.IsFrameBased && !sub.WasLoadedWithFrameNumbers)
                        {
                            sub.CalculateFrameNumbersFromTimeCodesNoCheck(Configuration.Settings.General.CurrentFrameRate);
                        }
                        else if (subtitleFormat.IsTimeBased && sub.WasLoadedWithFrameNumbers)
                        {
                            sub.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                        }

                        if ((subtitleFormat.GetType() == typeof(WebVTT) || subtitleFormat.GetType() == typeof(WebVTTFileWithLineNumber)))
                        {
                            targetEncoding = Encoding.UTF8;
                        }

                        if (subtitleFormat.GetType() == typeof(ItunesTimedText) || subtitleFormat.GetType() == typeof(ScenaristClosedCaptions) || subtitleFormat.GetType() == typeof(ScenaristClosedCaptionsDropFrame))
                        {
                            Encoding outputEnc = new UTF8Encoding(false);
                            using (var file = new StreamWriter(outputFileName, false, outputEnc))
                            {
                                file.Write(sub.ToText(subtitleFormat));
                            }
                        }
                        else if (targetEncoding == Encoding.UTF8 && (format.GetType() == typeof(TmpegEncAW5) || format.GetType() == typeof(TmpegEncXml)))
                        {
                            Encoding outputEnc = new UTF8Encoding(false);
                            using (var file = new StreamWriter(outputFileName, false, outputEnc))
                            {
                                file.Write(sub.ToText(subtitleFormat));
                            }
                        }
                        else
                        {
                            try
                            {
                                File.WriteAllText(outputFileName, sub.ToText(subtitleFormat), targetEncoding);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                errors++;
                                return false;
                            }
                        }

                        if (format.GetType() == typeof(Sami) || format.GetType() == typeof(SamiModern))
                        {
                            //var sami = (Sami)format;
                            foreach (string className in Sami.GetStylesFromHeader(sub.Header))
                            {
                                var newSub = new Subtitle();
                                foreach (Paragraph p in sub.Paragraphs)
                                {
                                    if (p.Extra != null && p.Extra.Trim().Equals(className.Trim(), StringComparison.OrdinalIgnoreCase))
                                    {
                                        newSub.Paragraphs.Add(p);
                                    }
                                }

                                if (newSub.Paragraphs.Count > 0 && newSub.Paragraphs.Count < sub.Paragraphs.Count)
                                {
                                    string s = fileName;
                                    if (s.LastIndexOf('.') > 0)
                                    {
                                        s = s.Insert(s.LastIndexOf('.'), "_" + className);
                                    }
                                    else
                                    {
                                        s += "_" + className + format.Extension;
                                    }

                                    outputFileName = FormatOutputFileNameForBatchConvert(s, subtitleFormat.Extension, outputFolder, overwrite);
                                    File.WriteAllText(outputFileName, newSub.ToText(subtitleFormat), targetEncoding);
                                }
                            }
                        }
                        Console.WriteLine(" done.");
                        break;
                    }
                }

                if (!targetFormatFound)
                {
                    var ebu = new Ebu();
                    if (ebu.Name.Replace(" ", string.Empty).Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, ebu.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        Ebu.Save(outputFileName, sub, true);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    var pac = new Pac();
                    if (pac.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase) ||
                        toFormat.Equals("pac", StringComparison.OrdinalIgnoreCase) ||
                        toFormat.Equals(".pac", StringComparison.OrdinalIgnoreCase))
                    {
                        pac.BatchMode = true;
                        int codePage;

                        if (!string.IsNullOrEmpty(pacCodePage) && int.TryParse(pacCodePage, out codePage))
                        {
                            pac.CodePage = codePage;
                        }

                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, pac.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        pac.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    var cavena890 = new Cavena890();
                    if (cavena890.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, cavena890.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        cavena890.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    var cheetahCaption = new CheetahCaption();
                    if (cheetahCaption.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, cheetahCaption.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        CheetahCaption.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    var capMakerPlus = new CapMakerPlus();
                    if (capMakerPlus.Name.Replace(" ", string.Empty).Equals(toFormat, StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, capMakerPlus.Extension, outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        CapMakerPlus.Save(outputFileName, sub);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    if (Configuration.Settings.Language.BatchConvert.PlainText == toFormat ||
                        Configuration.Settings.Language.BatchConvert.PlainText.Replace(" ", string.Empty)
                        .Equals(toFormat.Replace(" ", string.Empty), StringComparison.OrdinalIgnoreCase))
                    {
                        targetFormatFound = true;
                        outputFileName = FormatOutputFileNameForBatchConvert(fileName, ".txt", outputFolder, overwrite);

                        Console.Write("{0}: {1} -> {2}...", count, Path.GetFileName(fileName), outputFileName);
                        File.WriteAllText(outputFileName, ExportText.GeneratePlainText(sub, false, false, false, false, false, false, string.Empty, true, false, true, true, false), targetEncoding);
                        Console.WriteLine(" done.");
                    }
                }

                if (!targetFormatFound)
                {
                    Console.WriteLine("{0}: {1} - target format '{2}' not found!", count, fileName, toFormat);
                    errors++;
                    return false;
                }

                converted++;
                return true;
            }

            finally
            {
                Configuration.Settings.General.CurrentFrameRate = oldFrameRate;
            }
        }