Ejemplo n.º 1
0
        public override bool IsMine(List<string> lines, string fileName)
        {
            var subtitle = new Subtitle();
            LoadSubtitle(subtitle, lines, fileName);

            if (subtitle.Paragraphs.Count > 4)
            {
                bool allStartWithNumber = true;
                foreach (Paragraph p in subtitle.Paragraphs)
                {
                    if (p.Text.Length > 1 && !Utilities.IsInteger(p.Text.Substring(0, 2)))
                    {
                        allStartWithNumber = false;
                        break;
                    }
                }
                if (allStartWithNumber)
                    return false;
            }
            if (subtitle.Paragraphs.Count > _errorCount)
            {
                if (new UnknownSubtitle33().IsMine(lines, fileName) || new UnknownSubtitle36().IsMine(lines, fileName))
                    return false;
                return true;
            }
            return false;
        }
Ejemplo n.º 2
0
        public void Initialize(Subtitle subtitle1, string subtitleFileName1, string title)
        {
            subtitleListView1.UseSyntaxColoring = false;
            subtitleListView2.UseSyntaxColoring = false;

            Compare_Resize(null, null);
            labelStatus.Text = string.Empty;
            _subtitle1 = subtitle1;
            labelSubtitle1.Text = subtitleFileName1;
            if (string.IsNullOrEmpty(subtitleFileName1))
                labelSubtitle1.Text = title;
            subtitleListView1.Fill(subtitle1);

            if (!string.IsNullOrEmpty(subtitleFileName1))
            {
                try
                {
                    openFileDialog1.InitialDirectory = Path.GetDirectoryName(subtitleFileName1);
                }
                catch
                {
                }
            }

            openFileDialog1.Filter = Utilities.GetOpenDialogFilter();
            subtitleListView1.SelectIndexAndEnsureVisible(0);
            subtitleListView2.SelectIndexAndEnsureVisible(0);
            _language1 = Utilities.AutoDetectGoogleLanguage(_subtitle1);
        }
Ejemplo n.º 3
0
 public static string GetHeaderOrFooter(string title, Subtitle subtitle, string template)
 {
     template = template.Replace("{title}", title);
     template = template.Replace("{#lines}", subtitle.Paragraphs.Count.ToString(CultureInfo.InvariantCulture));
     template = template.Replace("{tab}", "\t");
     return template;
 }
        public override string ToText(Subtitle subtitle, string title)
        {
            StringBuilder sb = new StringBuilder();
            int index = 0;
            sb.AppendLine(@"Structured titles
0000 : --:--:--:--,--:--:--:--,10
80 80 80
");

            // 0001 : 01:07:25:08,01:07:29:00,10
            // 80 80 80
            // C1Y00 Niemand zal je helpen ontsnappen.
            // C1Y00 - Een agent heeft me geholpen.
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                sb.AppendLine(string.Format("{0:0000} : {1},{2},10", index + 1, EncodeTimeCode(p.StartTime), EncodeTimeCode(p.EndTime)));
                sb.AppendLine("80 80 80");
                foreach (string line in p.Text.SplitToLines())
                {
                    sb.AppendLine("C1Y00 " + line.Trim());
                }

                sb.AppendLine();
                index++;
            }

            sb.AppendLine(string.Format("{0:0000}", index + 1) + @" : --:--:--:--,--:--:--:--,-1
80 80 80");
            return sb.ToString();
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("#\tAppearance\tCaption\t");
            sb.AppendLine();
            int count = 1;
            for (int i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                Paragraph p = subtitle.Paragraphs[i];
                string text = HtmlUtil.RemoveHtmlTags(p.Text);
                sb.AppendLine(string.Format("{0}\t{1}\t{2}\t", count.ToString().PadLeft(5, ' '), MakeTimeCode(p.StartTime), text));
                sb.AppendLine("\t\t\t\t");
                Paragraph next = subtitle.GetParagraphOrDefault(i + 1);
                if (next == null || Math.Abs(p.EndTime.TotalMilliseconds - next.StartTime.TotalMilliseconds) > 50)
                {
                    count++;
                    sb.AppendLine(string.Format("{0}\t{1}", count.ToString().PadLeft(5, ' '), MakeTimeCode(p.EndTime)));
                }

                count++;
            }

            RichTextBox rtBox = new RichTextBox();
            rtBox.Text = sb.ToString();
            string rtf = rtBox.Rtf;
            rtBox.Dispose();
            return rtf;
        }
 public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
 {
     _errorCount = 0;
     subtitle.Paragraphs.Clear();
     foreach (string line in lines)
     {
         if (regexTimeCodes.IsMatch(line))
         {
             int splitter = line.IndexOf(':') + 3;
             string text = line.Remove(0, splitter);
             var p = new Paragraph(DecodeTimeCode(line.Substring(0, splitter)), new TimeCode(0, 0, 0, 0), text);
             subtitle.Paragraphs.Add(p);
             text = text.Trim().Trim('–', '.', ';', ':').Trim();
             if (text.Length > 0 && char.IsDigit(text[0]))
                 _errorCount++;
         }
         else
         {
             _errorCount += 2;
         }
     }
     foreach (Paragraph p2 in subtitle.Paragraphs)
     {
         p2.Text = Utilities.AutoBreakLine(p2.Text);
     }
     subtitle.RecalculateDisplayTimes(Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds, null);
     subtitle.Renumber();
 }
Ejemplo n.º 7
0
        internal void Initialize(Ebu.EbuGeneralSubtitleInformation header, byte justificationCode, string fileName, Subtitle subtitle)
        {
            _header = header;
            _subtitle = subtitle;

            FillFromHeader(header);
            if (!string.IsNullOrEmpty(fileName))
            {
                try
                {
                    FillHeaderFromFile(fileName);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("EbuOptions unable to read existing file: " + fileName + "  - " + ex.Message);
                }
                string title = Path.GetFileNameWithoutExtension(fileName);
                if (title.Length > 32)
                    title = title.Substring(0, 32).Trim();
                textBoxOriginalProgramTitle.Text = title;
            }

            comboBoxJustificationCode.SelectedIndex = justificationCode;

            Text = Configuration.Settings.Language.EbuSaveOptions.Title;
            buttonOK.Text = Configuration.Settings.Language.General.Ok;
            buttonCancel.Text = Configuration.Settings.Language.General.Cancel;
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            const string Header = @"{QTtext} {font:Tahoma}
                                    {plain} {size:20}
                                    {timeScale:30}
                                    {width:160} {height:32}
                                    {timestamps:absolute} {language:0}";

            StringBuilder sb = new StringBuilder();
            sb.AppendLine(Header);
            int index = 0;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                // [00:00:07.12]
                // d’être perdu dans un brouillard de pensées,
                // [00:00:17.06] (this line is optional!)
                // (blank line optional too)
                // [00:00:26.26]
                // tout le temps,
                // [00:00:35.08]
                sb.AppendLine(string.Format("{0}{1}{2}", EncodeTimeCode(p.StartTime) + Environment.NewLine, HtmlUtil.RemoveHtmlTags(p.Text) + Environment.NewLine, EncodeTimeCode(p.EndTime) + Environment.NewLine));
                index++;
            }

            return sb.ToString();
        }
Ejemplo n.º 9
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
                "<root fps=\"25\" movie=\"program title\" language=\"GBR:English (UK)\" font=\"Arial\" style=\"normal\" size=\"48\">" + Environment.NewLine +
                "<reel start=\"\" first=\"\" last=\"\">" + Environment.NewLine +
                "</reel>" + Environment.NewLine +
                "</root>";

            var xml = new XmlDocument { XmlResolver = null };
            xml.LoadXml(xmlStructure);
            XmlNode reel = xml.DocumentElement.SelectSingleNode("reel");
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("title");

                XmlAttribute start = xml.CreateAttribute("start");
                start.InnerText = ToTimeCode(p.StartTime.TotalMilliseconds);
                paragraph.Attributes.Append(start);

                XmlAttribute end = xml.CreateAttribute("end");
                end.InnerText = ToTimeCode(p.EndTime.TotalMilliseconds);
                paragraph.Attributes.Append(end);

                paragraph.InnerText = HtmlUtil.RemoveHtmlTags(p.Text.Replace(Environment.NewLine, "|"), true);

                reel.AppendChild(paragraph);
            }

            return ToUtf8XmlString(xml);
        }
Ejemplo n.º 10
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine + "<Subtitle/>";

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmlStructure);

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("Paragraph");

                XmlNode number = xml.CreateElement("Number");
                number.InnerText = p.Number.ToString();
                paragraph.AppendChild(number);

                XmlNode start = xml.CreateElement("StartMilliseconds");
                start.InnerText = p.StartTime.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
                paragraph.AppendChild(start);

                XmlNode end = xml.CreateElement("EndMilliseconds");
                end.InnerText = p.EndTime.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
                paragraph.AppendChild(end);

                XmlNode text = xml.CreateElement("Text");
                text.InnerText = HtmlUtil.RemoveHtmlTags(p.Text);
                paragraph.AppendChild(text);

                xml.DocumentElement.AppendChild(paragraph);
            }

            return ToUtf8XmlString(xml);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// The save.
        /// </summary>
        /// <param name="fileName">
        /// The file name.
        /// </param>
        /// <param name="subtitle">
        /// The subtitle.
        /// </param>
        public static void Save(string fileName, Subtitle subtitle)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);

            // header
            fs.WriteByte(1);
            for (int i = 1; i < 23; i++)
            {
                fs.WriteByte(0);
            }

            fs.WriteByte(0x60);

            // paragraphs
            int number = 0;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                WriteParagraph(p);
                number++;
            }

            // footer
            fs.WriteByte(0xff);
            for (int i = 0; i < 11; i++)
            {
                fs.WriteByte(0);
            }

            fs.WriteByte(0x11);
            byte[] footerBuffer = Encoding.ASCII.GetBytes("dummy end of file");
            fs.Write(footerBuffer, 0, footerBuffer.Length);

            fs.Close();
        }
Ejemplo n.º 12
0
        public override string ToText(Subtitle subtitle, string title)
        {
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(subtitle.Header) && (subtitle.Header.Contains("[ar:") || subtitle.Header.Contains("[ti:")))
            {
                sb.Append(subtitle.Header);
            }

            for (int i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                Paragraph p = subtitle.Paragraphs[i];
                Paragraph next = null;
                if (i + 1 < subtitle.Paragraphs.Count)
                {
                    next = subtitle.Paragraphs[i + 1];
                }

                string text = HtmlUtil.RemoveHtmlTags(p.Text);
                text = text.Replace(Environment.NewLine, " "); // text = text.Replace(Environment.NewLine, "|");
                sb.AppendLine(string.Format("[{0:00}:{1:00}.{2:00}]{3}", p.StartTime.Hours * 60 + p.StartTime.Minutes, p.StartTime.Seconds, (int)Math.Round(p.StartTime.Milliseconds / 10.0), text));

                if (next == null || next.StartTime.TotalMilliseconds - p.EndTime.TotalMilliseconds > 100)
                {
                    TimeCode tc = new TimeCode(p.EndTime.TotalMilliseconds);
                    sb.AppendLine(string.Format("[{0:00}:{1:00}.{2:00}]{3}", tc.Hours * 60 + tc.Minutes, tc.Seconds, (int)Math.Round(tc.Milliseconds / 10.0), string.Empty));
                }
            }

            return sb.ToString().Trim();
        }
        public void Initialize(Subtitle subtitle, bool autoBalance)
        {
            _modeAutoBalance = autoBalance;
            _paragraphs = new List<Paragraph>();

            foreach (Paragraph p in subtitle.Paragraphs)
                _paragraphs.Add(p);

            if (autoBalance)
            {
                labelCondition.Text = Configuration.Settings.Language.AutoBreakUnbreakLines.OnlyBreakLinesLongerThan;
                const int start = 10;
                const int max = 60;
                for (int i = start; i <= max; i++)
                    comboBoxConditions.Items.Add(i.ToString(CultureInfo.InvariantCulture));

                int index = Configuration.Settings.Tools.MergeLinesShorterThan - (start + 1);
                if (index > 0 && index < max)
                    comboBoxConditions.SelectedIndex = index;
                else
                    comboBoxConditions.SelectedIndex = 30;

                AutoBalance();
            }
            else
            {
                labelCondition.Text = Configuration.Settings.Language.AutoBreakUnbreakLines.OnlyUnbreakLinesLongerThan;
                for (int i = 5; i < 51; i++)
                    comboBoxConditions.Items.Add(i.ToString(CultureInfo.InvariantCulture));
                comboBoxConditions.SelectedIndex = 5;

                Unbreak();
            }
            comboBoxConditions.SelectedIndexChanged += ComboBoxConditionsSelectedIndexChanged;
        }
Ejemplo n.º 14
0
        public ExportTextST(Subtitle subtitle)
        {
            InitializeComponent();

            SetGroupBoxProperties(groupBoxPropertiesPalette);
            SetGroupBoxProperties(groupBoxPropertiesRegionStyle);
            SetGroupBoxProperties(groupBoxPropertiesUserStyle);
            SetGroupBoxProperties(groupBoxPresentationSegmentRegion);
            SetGroupBoxProperties(groupBoxFontStyle);
            SetGroupBoxProperties(groupBoxChangeFontSize);
            SetGroupBoxProperties(groupBoxSubtitleText);
            SetGroupBoxProperties(groupBoxChangeFontColor);
            SetGroupBoxProperties(groupBoxFontSet);

            _subtitle = subtitle;

            _textST = new TextST
            {
                StyleSegment = TextST.DialogStyleSegment.DefaultDialogStyleSegment,
                PresentationSegments = new List<TextST.DialogPresentationSegment>(),
            };
            _textST.StyleSegment.NumberOfDialogPresentationSegments = _subtitle.Paragraphs.Count;
            foreach (var paragraph in _subtitle.Paragraphs)
            {
                var dps = new TextST.DialogPresentationSegment(paragraph, _textST.StyleSegment.RegionStyles[0]);
                _textST.PresentationSegments.Add(dps);
            }

            UpdateTreeview();
        }
Ejemplo n.º 15
0
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            _errorCount = 0;
            Paragraph p = null;
            foreach (string line in lines)
            {
                string s = line.Trim();
                if (regexTimeCodes.Match(s).Success)
                {
                    if (p != null && !string.IsNullOrEmpty(p.Text))
                        subtitle.Paragraphs.Add(p);
                    p = new Paragraph();

                    try
                    {
                        string[] arr = s.Substring(0, 11).Split(':');
                        if (arr.Length == 4)
                        {
                            int hours = int.Parse(arr[0]);
                            int minutes = int.Parse(arr[1]);
                            int seconds = int.Parse(arr[2]);
                            int frames = int.Parse(arr[3]);
                            p.StartTime = new TimeCode(hours, minutes, seconds, FramesToMillisecondsMax999(frames));
                            string text = s.Remove(0, 11).Trim();
                            p.Text = text;
                            if (text.Length > 1 && Utilities.IsInteger(text.Substring(0, 2)))
                                _errorCount++;
                        }
                    }
                    catch
                    {
                        _errorCount++;
                    }
                }
                else if (s.Length > 0)
                {
                    _errorCount++;
                }
            }
            if (p != null && !string.IsNullOrEmpty(p.Text))
                subtitle.Paragraphs.Add(p);

            int index = 1;
            foreach (Paragraph paragraph in subtitle.Paragraphs)
            {
                paragraph.Text = paragraph.Text.Replace("\\M", "♪");

                Paragraph next = subtitle.GetParagraphOrDefault(index);
                if (next != null)
                {
                    paragraph.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - 1;
                }
                else
                {
                    paragraph.EndTime.TotalMilliseconds = paragraph.StartTime.TotalMilliseconds + Utilities.GetOptimalDisplayMilliseconds(paragraph.Text);
                }
                index++;
            }
            subtitle.RemoveEmptyLines();
        }
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            StringBuilder temp = new StringBuilder();
            foreach (string l in lines)
            {
                temp.Append(l);
            }

            string all = temp.ToString();
            if (!all.Contains("{\"content\":\""))
            {
                return;
            }

            string[] arr = all.Replace("\n", string.Empty).Replace("{\"content\":\"", "\n").Split('\n');

            this._errorCount = 0;
            subtitle.Paragraphs.Clear();

            // {"content":"La ce se gandeste  Oh Ha Ni a noastra <br> de la inceputul dimineti?","start_time":314071,"end_time":317833},
            for (int i = 0; i < arr.Length; i++)
            {
                string line = arr[i].Trim();

                int indexStartTime = line.IndexOf("\"start_time\":", StringComparison.Ordinal);
                int indexEndTime = line.IndexOf("\"end_time\":", StringComparison.Ordinal);
                if (indexStartTime > 0 && indexEndTime > 0)
                {
                    int indexEndText = indexStartTime;
                    if (indexStartTime > indexEndTime)
                    {
                        indexEndText = indexEndTime;
                    }

                    string text = line.Substring(0, indexEndText - 1).Trim().TrimEnd('\"');
                    text = text.Replace("<br>", Environment.NewLine).Replace("<BR>", Environment.NewLine);
                    text = text.Replace("<br/>", Environment.NewLine).Replace("<BR/>", Environment.NewLine);
                    text = text.Replace(Environment.NewLine + " ", Environment.NewLine);
                    text = text.Replace(Environment.NewLine + " ", Environment.NewLine);
                    text = text.Replace(Environment.NewLine + " ", Environment.NewLine);
                    text = text.Replace(" " + Environment.NewLine, Environment.NewLine);
                    text = text.Replace(" " + Environment.NewLine, Environment.NewLine);
                    text = text.Replace(" " + Environment.NewLine, Environment.NewLine);
                    try
                    {
                        string start = line.Substring(indexStartTime);
                        string end = line.Substring(indexEndTime);
                        Paragraph paragraph = new Paragraph { Text = text, StartTime = { TotalMilliseconds = GetMilliseconds(start) }, EndTime = { TotalMilliseconds = GetMilliseconds(end) } };
                        subtitle.Paragraphs.Add(paragraph);
                    }
                    catch (Exception exception)
                    {
                        Debug.WriteLine(exception.Message);
                        this._errorCount++;
                    }
                }
            }

            subtitle.Renumber();
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            // 10 04 36 02
            // 10 04 37 04
            // Greetings.
            // 10 04 37 06
            // 10 04 40 08
            // It's confirmed, after reading
            // Not Out on the poster..
            // 10 04 40 15
            // 10 04 44 06
            // ..you have not come to pass you
            // time, in this unique story.
            const string paragraphWriteFormat = "{0}{3}{1}{3}{2}";
            StringBuilder sb = new StringBuilder();
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                string text = HtmlUtil.RemoveOpenCloseTags(p.Text, HtmlUtil.TagFont);
                if (!text.Contains(Environment.NewLine))
                {
                    text = Environment.NewLine + text;
                }

                sb.AppendLine(string.Format(paragraphWriteFormat, EncodeTimeCode(p.StartTime), EncodeTimeCode(p.EndTime), text, Environment.NewLine));
            }

            return sb.ToString().Trim();
        }
Ejemplo n.º 18
0
        public void Initialize(Subtitle subtitle)
        {
            _subtitle = subtitle;

            FindAllNames();
            GeneratePreview();
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            // 1
            // 00:00:04:12
            // 00:00:06:05
            // Berniukai, tik pažiūrėkit.

            // 2
            // 00:00:06:16
            // 00:00:07:20
            // Argi ne puiku?

            // 3
            // 00:00:08:02
            // 00:00:10:20
            // Tėti, ar galime čia paplaukioti?
            // -Aišku, kad galim.
            const string paragraphWriteFormat = "{4}{3}{0}{3}{1}{3}{2}{3}";
            StringBuilder sb = new StringBuilder();
            int count = 0;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                count++;
                string text = HtmlUtil.RemoveOpenCloseTags(p.Text, HtmlUtil.TagFont);
                sb.AppendLine(string.Format(paragraphWriteFormat, EncodeTimeCode(p.StartTime), EncodeTimeCode(p.EndTime), text, Environment.NewLine, count));
            }

            return sb.ToString().Trim();
        }
Ejemplo n.º 20
0
        protected StylesForm(Subtitle subtitle)
        {
            _subtitle = subtitle;

            _previewTimer.Interval = 200;
            _previewTimer.Tick += PreviewTimerTick;
        }
Ejemplo n.º 21
0
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            const int startPosition = 0xa99;
            const int textPosition = 72;

            _errorCount = 0;
            subtitle.Paragraphs.Clear();
            subtitle.Header = null;
            var buffer = FileUtil.ReadAllBytesShared(fileName);
            int index = startPosition;
            if (buffer[index] != 1)
            {
                return;
            }

            while (index + textPosition < buffer.Length)
            {
                int textLength = buffer[index + 16];
                if (textLength > 0 && index + textPosition + textLength < buffer.Length)
                {
                    string text = GetText(index + textPosition, textLength, buffer);
                    if (!string.IsNullOrWhiteSpace(text))
                    {
                        int startFrames = GetFrames(index + 4, buffer);
                        int endFrames = GetFrames(index + 8, buffer);
                        subtitle.Paragraphs.Add(new Paragraph(text, FramesToMilliseconds(startFrames), FramesToMilliseconds(endFrames)));
                    }
                }
                index += textPosition + textLength;
            }
            subtitle.Renumber();
        }
Ejemplo n.º 22
0
        public override string ToText(Subtitle subtitle, string title)
        {
            var sb = new StringBuilder(@"[");
            int count = 0;

            string guid = Guid.NewGuid().ToString();
            string segmentTypeId = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 24);

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                string id = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 24);
                if (count > 0)
                    sb.Append(',');
                sb.Append("{\"hitType\":\"tag\",\"subTrack\":null,\"tags\":[],\"track\":\"Closed Captioning\",\"startTime\":");
                sb.Append(p.StartTime.TotalSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture));
                sb.Append(",\"guid\":\"" + guid + "\",\"segmentTypeId\":\"" + segmentTypeId + "\",\"endTime\":");
                sb.Append(p.EndTime.TotalSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture));
                sb.Append(",\"id\":\"" + id + "\",\"metadata\":{\"Text\":\"");
                sb.Append(Json.EncodeJsonText(p.Text) + "\"");

                sb.Append(",\"ID\":\"\",\"Language\":\"en\"}}");
                count++;
            }
            sb.Append(']');
            return sb.ToString().Trim();
        }
Ejemplo n.º 23
0
 private static void CleanUp(Subtitle subtitle)
 {
     foreach (Paragraph p in subtitle.Paragraphs)
     {
         p.Text = p.Text.Replace("<html>", string.Empty);
         p.Text = p.Text.Replace("</html>", string.Empty);
         p.Text = p.Text.Replace("<div>", string.Empty);
         p.Text = p.Text.Replace("</div>", string.Empty);
         p.Text = p.Text.Replace("<body>", string.Empty);
         p.Text = p.Text.Replace("</body>", string.Empty);
         p.Text = p.Text.Replace("<tt>", string.Empty);
         p.Text = p.Text.Replace("</tt>", string.Empty);
         p.Text = p.Text.Replace("<tr>", string.Empty);
         p.Text = p.Text.Replace("</tr>", string.Empty);
         p.Text = p.Text.Replace("<td>", string.Empty);
         p.Text = p.Text.Replace("</td>", string.Empty);
         p.Text = p.Text.Replace("<table>", string.Empty);
         p.Text = p.Text.Replace("</table>", string.Empty);
         p.Text = p.Text.Replace("<br>", Environment.NewLine);
         p.Text = p.Text.Replace("<br/>", Environment.NewLine);
         p.Text = p.Text.Replace("<br />", Environment.NewLine);
         p.Text = p.Text.Replace("&lt;", "<");
         p.Text = p.Text.Replace("&gt;", ">");
         p.Text = p.Text.Replace("  ", " ");
         p.Text = p.Text.Replace("  ", " ");
         p.Text = p.Text.Replace("  ", " ");
         p.Text = p.Text.Replace("|", Environment.NewLine).Replace("<p>", Environment.NewLine).Replace("</p>", Environment.NewLine).Trim();
         p.Text = p.Text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine).Trim();
         p.Text = p.Text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine).Trim();
     }
     subtitle.RemoveEmptyLines();
 }
Ejemplo n.º 24
0
        public static List<string> GetVoices(Subtitle subtitle)
        {
            var list = new List<string>();
            if (subtitle != null && subtitle.Paragraphs != null)
            {
                foreach (Paragraph p in subtitle.Paragraphs)
                {
                    string s = p.Text;
                    var startIndex = s.IndexOf("<v ", StringComparison.Ordinal);
                    while (startIndex >= 0)
                    {
                        int endIndex = s.IndexOf('>', startIndex);
                        if (endIndex > startIndex)
                        {
                            string voice = s.Substring(startIndex + 2, endIndex - startIndex - 2).Trim();
                            if (!list.Contains(voice))
                                list.Add(voice);
                        }

                        if (startIndex == s.Length - 1)
                            startIndex = -1;
                        else
                            startIndex = s.IndexOf("<v ", startIndex + 1, StringComparison.Ordinal);
                    }
                }
            }
            return list;
        }
Ejemplo n.º 25
0
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            _errorCount = 0;

            var sb = new StringBuilder();
            foreach (string s in lines)
                sb.Append(s);

            string allText = sb.ToString();
            if (!allText.Contains("text_tees"))
                return;

            var times = Json.ReadArray(allText, "text_tees");
            var texts = Json.ReadArray(allText, "text_content");

            for (int i = 0; i < Math.Min(times.Count, texts.Count); i++)
            {
                try
                {

                    string text = texts[i];
                    if (text.StartsWith('['))
                    {
                        var textLines = Json.ReadArray("{\"text\":" + texts[i] + "}", "text");
                        var textSb = new StringBuilder();
                        foreach (string line in textLines)
                        {
                            string t = Json.DecodeJsonText(line);
                            if (t.StartsWith("[\"", StringComparison.Ordinal) && t.EndsWith("\"]", StringComparison.Ordinal))
                            {
                                var innerSb = new StringBuilder();
                                var innerTextLines = Json.ReadArray("{\"text\":" + t + "}", "text");
                                foreach (string innerLine in innerTextLines)
                                {
                                    innerSb.Append(' ');
                                    innerSb.Append(innerLine);
                                }
                                textSb.AppendLine(innerSb.ToString().Trim());
                            }
                            else
                            {
                                textSb.AppendLine(t);
                            }
                        }
                        text = textSb.ToString().Trim();
                        text = text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
                    }
                    var p = new Paragraph(text, int.Parse(times[i]), 0);
                    if (i + 1 < times.Count)
                        p.EndTime.TotalMilliseconds = int.Parse(times[i + 1]);
                    subtitle.Paragraphs.Add(p);
                }
                catch
                {
                    _errorCount++;
                }
            }
            subtitle.RemoveEmptyLines();
            subtitle.Renumber();
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            // <Phrase TimeStart="4020" TimeEnd="6020">
            // <Text>XYZ PRESENTS</Text>
            // </Phrase>
            string xmlStructure = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine + "<Subtitle xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"></Subtitle>";

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmlStructure);

            int id = 1;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("Phrase");

                XmlAttribute start = xml.CreateAttribute("TimeStart");
                start.InnerText = p.StartTime.TotalMilliseconds.ToString();
                paragraph.Attributes.Append(start);

                XmlAttribute duration = xml.CreateAttribute("TimeEnd");
                duration.InnerText = p.EndTime.TotalMilliseconds.ToString();
                paragraph.Attributes.Append(duration);

                XmlNode text = xml.CreateElement("Text");
                text.InnerText = HtmlUtil.RemoveHtmlTags(p.Text).Replace(Environment.NewLine, "\\n");
                paragraph.AppendChild(text);

                xml.DocumentElement.AppendChild(paragraph);
                id++;
            }

            return ToUtf8XmlString(xml);
        }
Ejemplo n.º 27
0
 public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
 {
     _errorCount = 0;
     foreach (string line in lines)
     {
         Match m = CsvLine.Match(line);
         if (m.Success)
         {
             string[] parts = line.Substring(0, m.Length).Split(Separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
             if (parts.Length == 2)
                 try
                 {
                     var start = DecodeTimeCode(parts[0]);
                     var end = DecodeTimeCode(parts[1]);
                     string text = ReadText(line.Remove(0, m.Length));
                     var p = new Paragraph(start, end, text);
                     subtitle.Paragraphs.Add(p);
                 }
                 catch
                 {
                     _errorCount++;
                 }
         }
         else if (!string.IsNullOrWhiteSpace(line))
         {
             _errorCount++;
         }
     }
     subtitle.Renumber();
 }
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            // 00:03:15:22 00:03:23:10 This is line one.
            // This is line two.
            subtitle.Paragraphs.Clear();
            this._errorCount = 0;
            foreach (string line in lines)
            {
                if (regexTimeCodes.IsMatch(line))
                {
                    string temp = line.Substring(0, regexTimeCodes.Match(line).Length);
                    string start = temp.Substring(0, 11);
                    string end = temp.Substring(12, 11);

                    string[] startParts = start.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    string[] endParts = end.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    if (startParts.Length == 4 && endParts.Length == 4)
                    {
                        string text = line.Remove(0, regexTimeCodes.Match(line).Length - 1).Trim();
                        text = text.Replace("//", Environment.NewLine);
                        Paragraph p = new Paragraph(DecodeTimeCode(startParts), DecodeTimeCode(endParts), text);
                        subtitle.Paragraphs.Add(p);
                    }
                }
                else
                {
                    this._errorCount += 10;
                }
            }

            subtitle.Renumber();
        }
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            _errorCount = 0;

            var sb = new StringBuilder();
            lines.ForEach(line => sb.AppendLine(line));
            var xml = new XmlDocument { XmlResolver = null };
            xml.LoadXml(sb.ToString().Trim());

            XmlNode div = xml.DocumentElement.SelectSingleNode("subtitles");
            foreach (XmlNode node in div.ChildNodes)
            {
                try
                {
                    //<subtitle duration="2256" effect="" end="124581" layer="0" margin-l="0" margin-r="0" margin-v="0" name="" note="" path="0" start="122325" style="Default" text="The fever hath weakened thee." translation="" />
                    var p = new Paragraph { StartTime = { TotalMilliseconds = int.Parse(node.Attributes["start"].Value) } };
                    p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + int.Parse(node.Attributes["duration"].Value);
                    p.Text = node.Attributes["text"].Value;

                    subtitle.Paragraphs.Add(p);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    _errorCount++;
                }
            }
            subtitle.Renumber();
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
                "<USFSubtitles version=\"1.0\">" + Environment.NewLine +
                @"<metadata>
            <title>Universal Subtitle Format</title>
            <author>
              <name>SubtitleEdit</name>
              <email>[email protected]</email>
              <url>http://www.nikse.dk/</url>
            </author>" + Environment.NewLine +
            "   <language code=\"eng\">English</language>" + Environment.NewLine +
            @"  <date>[DATE]</date>
            <comment>This is a USF file</comment>
              </metadata>
              <styles>
            <!-- Here we redefine the default style -->" + Environment.NewLine +
                "    <style name=\"Default\">" + Environment.NewLine +
                "      <fontstyle face=\"Arial\" size=\"24\" color=\"#FFFFFF\" back-color=\"#AAAAAA\" />" +
                Environment.NewLine +
                "      <position alignment=\"BottomCenter\" vertical-margin=\"20%\" relative-to=\"Window\" />" +
                @"    </style>
              </styles>

              <subtitles>
              </subtitles>
            </USFSubtitles>";
            xmlStructure = xmlStructure.Replace("[DATE]", DateTime.Now.ToString("yyyy-MM-dd"));

            var xml = new XmlDocument();
            xml.LoadXml(xmlStructure);
            xml.DocumentElement.SelectSingleNode("metadata/title").InnerText = title;
            var subtitlesNode = xml.DocumentElement.SelectSingleNode("subtitles");

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("subtitle");

                XmlAttribute start = xml.CreateAttribute("start");
                start.InnerText = p.StartTime.ToString().Replace(",", ".");
                paragraph.Attributes.Prepend(start);

                XmlAttribute stop = xml.CreateAttribute("stop");
                stop.InnerText = p.EndTime.ToString().Replace(",", ".");
                paragraph.Attributes.Append(stop);

                XmlNode text = xml.CreateElement("text");
                text.InnerText = HtmlUtil.RemoveHtmlTags(p.Text);
                paragraph.AppendChild(text);

                XmlAttribute style = xml.CreateAttribute("style");
                style.InnerText = "Default";
                text.Attributes.Append(style);

                subtitlesNode.AppendChild(paragraph);
            }

            return ToUtf8XmlString(xml);
        }
        private static Subtitle ImportTimeCodesAndTextOnSameLine(List <string> lines)
        {
            var       regexTimeCodes1 = new Regex(@"\d+[:.,;]{1}\d\d[:.,;]{1}\d\d[:.,;]{1}\d+", RegexOptions.Compiled);
            var       regexTimeCodes2 = new Regex(@"\d+[:.,;]{1}\d\d[:.,;]{1}\d+", RegexOptions.Compiled);
            Paragraph p        = null;
            var       subtitle = new Subtitle();
            var       sb       = new StringBuilder();

            bool isFirstLineNumber = false;

            int count = -1;

            for (int idx = 0; idx < lines.Count; idx++)
            {
                string line    = lines[idx];
                var    matches = regexTimeCodes1.Matches(line);
                if (matches.Count == 0)
                {
                    matches = regexTimeCodes2.Matches(line);
                }
                if (matches.Count == 2)
                {
                    var start = matches[0].Value.Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                    int i;
                    if (int.TryParse(start[0], out i))
                    {
                        if (count == -1 && i < 2)
                        {
                            count = i;
                        }
                        if (count != i)
                        {
                            isFirstLineNumber = false;
                            break;
                        }
                        count++;
                    }
                }
                if (count > 2)
                {
                    isFirstLineNumber = true;
                }
            }

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

                if (isFirstLineNumber)
                {
                    while (line.Length > 0 && char.IsDigit(line[0]))
                    {
                        line = line.Remove(0, 1);
                    }
                }

                var matches = regexTimeCodes1.Matches(line);
                if (matches.Count == 0)
                {
                    matches = regexTimeCodes2.Matches(line);
                }
                if (matches.Count == 2)
                {
                    string[] start = matches[0].ToString().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                    string[] end   = matches[1].ToString().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                    if ((start.Length == 3 || start.Length == 4) && (end.Length == 3 || end.Length == 4))
                    {
                        if (p != null)
                        {
                            p.Text = sb.ToString().Trim();
                            subtitle.Paragraphs.Add(p);
                        }
                        p = new Paragraph();
                        sb.Clear();
                        p.StartTime = DecodeTime(start);
                        p.EndTime   = DecodeTime(end);
                    }
                    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 (p != null)
            {
                p.Text = sb.ToString().Trim();
                subtitle.Paragraphs.Add(p);
            }

            // remove all equal headers
            if (subtitle.Paragraphs.Count > 5)
            {
                string prefix = subtitle.Paragraphs[0].Text;
                foreach (Paragraph paragraph in subtitle.Paragraphs)
                {
                    string text      = paragraph.Text.Trim();
                    var    newPrefix = new StringBuilder();
                    int    i         = 0;
                    while (i < prefix.Length && i < text.Length && text[i] == prefix[i])
                    {
                        newPrefix.Append(text[i]);
                        i++;
                    }
                    prefix = newPrefix.ToString();
                }
                if (prefix.Length > 3 && prefix[1] == ':' && prefix[2] == '\\')
                {
                    prefix = string.Empty;
                }

                if (prefix.Length > 0)
                {
                    foreach (Paragraph paragraph in subtitle.Paragraphs)
                    {
                        string text = paragraph.Text.Trim();
                        if (text.StartsWith(prefix, StringComparison.Ordinal))
                        {
                            paragraph.Text = text.Remove(0, prefix.Length);
                        }
                    }
                }
            }

            subtitle.Renumber();
            return(subtitle);
        }
        private static Subtitle ImportTimeCodesOnSameSeperateLineNoMilliseconds(List <string> lines)
        {
            Paragraph p        = null;
            var       subtitle = new Subtitle();
            var       sb       = new StringBuilder();

            char[] splitChar = { ' ' };
            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 > 5)
                {
                    string[] arr = line.Replace('-', ' ').Replace('>', ' ').Replace('{', ' ').Replace('}', ' ').Replace('[', ' ').Replace(']', ' ').Trim().Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Length == 2)
                    {
                        string[] start = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        string[] end   = arr[1].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        if ((start.Length == 3 || start.Length == 4) && (end.Length == 3 || end.Length == 4))
                        {
                            if (start.Length == 3)
                            {
                                start = (arr[0].Trim() + ".000").Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                            }
                            if (end.Length == 3)
                            {
                                end = (arr[1].Trim() + ".000").Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                            }

                            if (p != null)
                            {
                                p.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(p);
                            }
                            p = new Paragraph();
                            sb.Clear();
                            p.StartTime = DecodeTime(start);
                            p.EndTime   = DecodeTime(end);
                        }
                    }
                    else if (arr.Length == 3)
                    {
                        string[] start    = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        string[] end      = arr[1].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        string[] duration = arr[2].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);

                        if (start.Length == 3)
                        {
                            start = (arr[0].Trim() + ".000").Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        }
                        if (end.Length == 3)
                        {
                            end = (arr[1].Trim() + ".000").Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        }
                        if (duration.Length == 3)
                        {
                            duration = (arr[2].Trim() + ".000").Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        }

                        if (start.Length < 3)
                        {
                            start = end;
                            end   = duration;
                        }

                        if ((start.Length == 3 || start.Length == 4) && (end.Length == 3 || end.Length == 4))
                        {
                            if (p != null)
                            {
                                p.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(p);
                            }
                            p = new Paragraph();
                            sb.Clear();
                            p.StartTime = DecodeTime(start);
                            p.EndTime   = DecodeTime(end);
                        }
                    }
                }
                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);
        }
        private Subtitle ImportTimeCodesInFramesOnSameSeperateLine(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.StartFrame = int.Parse(start[0]);
                                    p.EndFrame   = int.Parse(end[0]);
                                    p.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                                }
                                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.StartFrame = int.Parse(start[0]);
                                    p.EndFrame   = int.Parse(end[0]);
                                    p.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                                }
                                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.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
            subtitle.Renumber();
            return(subtitle);
        }
        private static Subtitle ImportTimeCodesOnSameSeperateLine(List <string> lines)
        {
            Paragraph p        = null;
            var       subtitle = new Subtitle();
            var       sb       = new StringBuilder();

            char[] splitChars = { ' ', '\t' };
            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;
                        break;
                    }
                }
                if (allNumbers && lineWithPerhapsOnlyNumbers.Length > 5)
                {
                    string[] arr = line.Replace('-', ' ').Replace('>', ' ').Replace('{', ' ').Replace('}', ' ').Replace('[', ' ').Replace(']', ' ').Trim().Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Length == 2)
                    {
                        string[] start = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        string[] end   = arr[1].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        if ((start.Length == 3 || start.Length == 4) && (end.Length == 3 || end.Length == 4))
                        {
                            if (p != null)
                            {
                                p.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(p);
                            }
                            p = new Paragraph();
                            sb.Clear();
                            p.StartTime = DecodeTime(start);
                            p.EndTime   = DecodeTime(end);
                        }
                    }
                    else if (arr.Length > 3)
                    {
                        string[] start;
                        string[] end;
                        if (arr[0].Length > 9)
                        {
                            start = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                            end   = arr[1].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        }
                        else
                        {
                            start = arr[1].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                            end   = arr[2].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        }
                        if ((start.Length == 3 || start.Length == 4) && (end.Length == 3 || end.Length == 4))
                        {
                            if (p != null)
                            {
                                p.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(p);
                            }
                            p           = new Paragraph();
                            sb          = new StringBuilder();
                            p.StartTime = DecodeTime(start);
                            p.EndTime   = DecodeTime(end);
                        }
                    }
                }
                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);
            }

            double averateDuration = 0;

            foreach (Paragraph a in subtitle.Paragraphs)
            {
                double d = a.Duration.TotalSeconds;
                if (d > 10)
                {
                    d = 8;
                }
                averateDuration += d;
            }
            averateDuration = averateDuration / subtitle.Paragraphs.Count;
            if (averateDuration < 0.2 || (averateDuration < 0.5 && subtitle.Paragraphs.Count > 100 && subtitle.Paragraphs[subtitle.Paragraphs.Count - 1].StartTime.TotalSeconds < 140 && subtitle.Paragraphs[subtitle.Paragraphs.Count - 2].StartTime.TotalSeconds < 140))
            {
                subtitle = ImportTimeCodesOnSameSeperateLineNoMilliseconds(lines);
                int i = 0;
                foreach (Paragraph a in subtitle.Paragraphs)
                {
                    i++;
                    var next = subtitle.GetParagraphOrDefault(i);
                    if (next != null && a.EndTime.TotalMilliseconds >= next.StartTime.TotalMilliseconds)
                    {
                        a.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                    }
                }
                return(subtitle);
            }

            subtitle.Renumber();
            return(subtitle);
        }
        public static string AutoDetectLanguageName(string languageName, Subtitle subtitle)
        {
            if (string.IsNullOrEmpty(languageName))
            {
                languageName = "en_US";
            }
            int bestCount = subtitle.Paragraphs.Count / 14;

            var sb = new StringBuilder();

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                sb.AppendLine(p.Text);
            }
            string text = sb.ToString();

            List <string> dictionaryNames = Utilities.GetDictionaryLanguages();

            bool containsEnGb   = false;
            bool containsEnUs   = false;
            bool containsHrHr   = false;
            bool containsSrLatn = false;

            foreach (string name in dictionaryNames)
            {
                if (name.Contains("[en_GB]"))
                {
                    containsEnGb = true;
                }
                if (name.Contains("[en_US]"))
                {
                    containsEnUs = true;
                }
                if (name.Contains("[hr_HR]"))
                {
                    containsHrHr = true;
                }
                if (name.Contains("[sr-Latn]"))
                {
                    containsSrLatn = true;
                }
            }

            foreach (string name in dictionaryNames)
            {
                string shortName = string.Empty;
                int    start     = name.IndexOf('[');
                int    end       = name.IndexOf(']');
                if (start > 0 && end > start)
                {
                    start++;
                    shortName = name.Substring(start, end - start);
                }

                int count;
                switch (shortName)
                {
                case "da_DK":
                    count = GetCount(text, AutoDetectWordsDanish);
                    if (count > bestCount)
                    {
                        int norwegianCount = GetCount(text, "ut", "deg", "meg", "merkelig", "mye", "spørre");
                        int dutchCount     = GetCount(text, AutoDetectWordsDutch);
                        if (norwegianCount < 2 && dutchCount < count)
                        {
                            languageName = shortName;
                        }
                    }
                    break;

                case "nb_NO":
                    count = GetCount(text, AutoDetectWordsNorwegian);
                    if (count > bestCount)
                    {
                        int danishCount = GetCount(text, "siger", "dig", "mig", "mærkelig", "tilbage", "spørge");
                        int dutchCount  = GetCount(text, AutoDetectWordsDutch);
                        if (danishCount < 2 && dutchCount < count)
                        {
                            languageName = shortName;
                        }
                    }
                    break;

                case "sv_SE":
                    count = GetCount(text, AutoDetectWordsSwedish);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "en_US":
                    count = GetCount(text, AutoDetectWordsEnglish);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                        if (containsEnGb)
                        {
                            int usCount = GetCount(text, "color", "flavor", "honor", "humor", "neighbor", "honor");
                            int gbCount = GetCount(text, "colour", "flavour", "honour", "humour", "neighbour", "honour");
                            if (gbCount > usCount)
                            {
                                languageName = "en_GB";
                            }
                        }
                    }
                    break;

                case "en_GB":
                    count = GetCount(text, AutoDetectWordsEnglish);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                        if (containsEnUs)
                        {
                            int usCount = GetCount(text, "color", "flavor", "honor", "humor", "neighbor", "honor");
                            int gbCount = GetCount(text, "colour", "flavour", "honour", "humour", "neighbour", "honour");
                            if (gbCount < usCount)
                            {
                                languageName = "en_US";
                            }
                        }
                    }
                    break;

                case "es_ES":
                    count = GetCount(text, AutoDetectWordsSpanish);
                    if (count > bestCount)
                    {
                        int frenchCount     = GetCount(text, "[Cc]'est", "pas", "vous", "pour", "suis", "Pourquoi", "maison", "souviens", "quelque"); // not spanish words
                        int portugueseCount = GetCount(text, "[NnCc]ão", "Então", "h?ouve", "pessoal", "rapariga", "tivesse", "fizeste",
                                                       "jantar", "conheço", "atenção", "foste", "milhões", "devias", "ganhar", "raios");              // not spanish words
                        if (frenchCount < 2 && portugueseCount < 2)
                        {
                            languageName = shortName;
                        }
                    }
                    break;

                case "it_IT":
                    count = GetCount(text, AutoDetectWordsItalian);
                    if (count > bestCount)
                    {
                        int frenchCount  = GetCount(text, "[Cc]'est", "pas", "vous", "pour", "suis", "Pourquoi", "maison", "souviens", "quelque"); // not italian words
                        int spanishCount = GetCount(text, "Hola", "nada", "Vamos", "pasa", "los", "como");                                         // not italian words
                        if (frenchCount < 2 && spanishCount < 2)
                        {
                            languageName = shortName;
                        }
                    }
                    break;

                case "fr_FR":
                    count = GetCount(text, AutoDetectWordsFrench);
                    if (count > bestCount)
                    {
                        int romanianCount = GetCount(text, "[Vv]reau", "[Ss]înt", "[Aa]cum", "pentru", "domnule", "aici");
                        int spanishCount  = GetCount(text, "Hola", "nada", "Vamos", "pasa", "los", "como");    // not french words
                        int italianCount  = GetCount(text, AutoDetectWordsItalian);
                        if (romanianCount < 5 && spanishCount < 2 && italianCount < 2)
                        {
                            languageName = shortName;
                        }
                    }
                    break;

                case "de_DE":
                    count = GetCount(text, AutoDetectWordsGerman);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "nl_NL":
                    count = GetCount(text, AutoDetectWordsDutch);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "pl_PL":
                    count = GetCount(text, AutoDetectWordsPolish);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "el_GR":
                    count = GetCount(text, AutoDetectWordsGreek);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "ru_RU":
                    count = GetCount(text, AutoDetectWordsRussian);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "uk_UA":
                    count = GetCount(text, AutoDetectWordsUkrainian);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "ro_RO":
                    count = GetCount(text, AutoDetectWordsRomanian1);
                    if (count <= bestCount)
                    {
                        count = GetCount(text, AutoDetectWordsRomanian2);
                    }
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "hr_HR":     // Croatian
                    count = GetCount(text, AutoDetectWordsCroatianAndSerbian);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                        if (containsSrLatn)
                        {
                            int croatianCount = GetCount(text, AutoDetectWordsCroatian);
                            int serbianCount  = GetCount(text, AutoDetectWordsSerbian);
                            if (serbianCount > croatianCount)
                            {
                                languageName = "sr-Latn";
                            }
                        }
                    }
                    break;

                case "sr-Latn":     // Serbian (Latin)
                    count = GetCount(text, AutoDetectWordsCroatianAndSerbian);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                        if (containsHrHr)
                        {
                            int croatianCount = GetCount(text, AutoDetectWordsCroatian);
                            int serbianCount  = GetCount(text, AutoDetectWordsSerbian);
                            if (serbianCount < croatianCount)
                            {
                                languageName = "hr_HR";
                            }
                        }
                    }
                    break;

                case "sr":     // Serbian (Cyrillic)
                    count = GetCount(text, AutoDetectWordsSerbianCyrillic);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "pt_PT":     // Portuguese
                    count = GetCount(text, AutoDetectWordsPortuguese);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "pt_BR":     // Portuguese (Brasil)
                    count = GetCount(text, AutoDetectWordsPortuguese);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;

                case "hu_HU":     // Hungarian
                    count = GetCount(text, AutoDetectWordsHungarian);
                    if (count > bestCount)
                    {
                        languageName = shortName;
                    }
                    break;
                }
            }
            return(languageName);
        }
        private static Subtitle ImportTimeCodesOnAloneLines(List <string> lines)
        {
            Paragraph p        = null;
            var       subtitle = new Subtitle();
            var       sb       = new StringBuilder();

            char[] splitChars = { ' ', '\t', '-', '>', '<', '{', '}', '[', ']' };
            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;
                        break;
                    }
                }
                if (allNumbers && lineWithPerhapsOnlyNumbers.Length > 5)
                {
                    string[] arr = line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Length == 1)
                    {
                        string[] tc = arr[0].Trim().Split(ExpectedSplitChars, StringSplitOptions.RemoveEmptyEntries);
                        if (p == null || Math.Abs(p.EndTime.TotalMilliseconds) > 0.001)
                        {
                            if (p != null)
                            {
                                p.Text = sb.ToString().Trim();
                                subtitle.Paragraphs.Add(p);
                                sb.Clear();
                            }
                            p = new Paragraph {
                                StartTime = DecodeTime(tc)
                            };
                        }
                        else
                        {
                            p.EndTime = DecodeTime(tc);
                        }
                    }
                }
                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);
        }
Ejemplo n.º 37
0
        public void MakeHistoryForUndo(string description, SubtitleFormat subtitleFormat, DateTime fileModified, Subtitle original, string originalSubtitleFileName, int lineNumber, int linePosition, int linePositionOriginal)
        {
            // don't fill memory with history - use a max rollback points
            if (HistoryItems.Count > MaximumHistoryItems)
            {
                HistoryItems.RemoveAt(0);
            }

            HistoryItems.Add(new HistoryItem(HistoryItems.Count, this, description, FileName, fileModified, subtitleFormat.FriendlyName, original, originalSubtitleFileName, lineNumber, linePosition, linePositionOriginal));
        }
        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.StartFrame = int.Parse(start);
                            p.EndFrame   = int.Parse(end);
                            p.CalculateTimeCodesFromFrameNumbers(Configuration.Settings.General.CurrentFrameRate);
                        }
                        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);
        }
Ejemplo n.º 39
0
 public static string AutoDetectGoogleLanguage(Subtitle subtitle)
 {
     return(AutoDetectGoogleLanguageOrNull(subtitle) ?? "en");
 }
Ejemplo n.º 40
0
        public string UndoHistory(int index, out string subtitleFormatFriendlyName, out DateTime fileModified, out Subtitle originalSubtitle, out string originalSubtitleFileName)
        {
            Paragraphs.Clear();
            foreach (var p in HistoryItems[index].Subtitle.Paragraphs)
            {
                Paragraphs.Add(new Paragraph(p));
            }

            subtitleFormatFriendlyName = HistoryItems[index].SubtitleFormatFriendlyName;
            FileName                 = HistoryItems[index].FileName;
            fileModified             = HistoryItems[index].FileModified;
            originalSubtitle         = new Subtitle(HistoryItems[index].OriginalSubtitle);
            originalSubtitleFileName = HistoryItems[index].OriginalSubtitleFileName;
            Header = HistoryItems[index].Subtitle.Header;

            return(FileName);
        }
Ejemplo n.º 41
0
 public BookmarkPersistence(Subtitle subtitle, string fileName)
 {
     _subtitle = subtitle;
     _fileName = fileName;
 }
Ejemplo n.º 42
0
        public string UndoHistory(int index, out string subtitleFormatFriendlyName, out DateTime fileModified, out Subtitle originalSubtitle, out string originalSubtitleFileName)
        {
            _paragraphs.Clear();
            foreach (Paragraph p in _history[index].Subtitle.Paragraphs)
            {
                _paragraphs.Add(new Paragraph(p));
            }

            subtitleFormatFriendlyName = _history[index].SubtitleFormatFriendlyName;
            FileName                 = _history[index].FileName;
            fileModified             = _history[index].FileModified;
            originalSubtitle         = new Subtitle(_history[index].OriginalSubtitle);
            originalSubtitleFileName = _history[index].OriginalSubtitleFileName;

            return(FileName);
        }