Exemplo n.º 1
1
        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}";
            var sb = new StringBuilder();
            int count = 0;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                count++;
                var 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();
        }
Exemplo n.º 2
0
 public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
 {
     _errorCount = 0;
     subtitle.Paragraphs.Clear();
     foreach (string line in lines)
     {
         var s = line.Trim();
         if (s.Length > 35 && RegexTimeCodes.IsMatch(s))
         {
             try
             {
                 string timePart = s.Substring(4, 10).TrimEnd();
                 var start = DecodeTimeCode(timePart);
                 timePart = s.Substring(15, 10).Trim();
                 var end = DecodeTimeCode(timePart);
                 var paragraph = new Paragraph { StartTime = start, EndTime = end };
                 paragraph.Text = s.Substring(38).Replace(" \\n ", Environment.NewLine).Replace("\\n", Environment.NewLine);
                 subtitle.Paragraphs.Add(paragraph);
             }
             catch
             {
                 _errorCount++;
             }
         }
     }
     subtitle.Renumber();
 }
Exemplo n.º 3
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
                "<EEG708Captions/>";

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

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("Caption");
                XmlAttribute start = xml.CreateAttribute("timecode");
                start.InnerText = EncodeTimeCode(p.StartTime);
                paragraph.Attributes.Append(start);
                XmlNode text = xml.CreateElement("Text");
                text.InnerText = p.Text;
                paragraph.AppendChild(text);
                xml.DocumentElement.AppendChild(paragraph);

                paragraph = xml.CreateElement("Caption");
                start = xml.CreateAttribute("timecode");
                start.InnerText = EncodeTimeCode(p.EndTime);
                paragraph.Attributes.Append(start);
                xml.DocumentElement.AppendChild(paragraph);
            }

            return ToUtf8XmlString(xml);
        }
Exemplo n.º 4
0
        public override string ToText(Subtitle subtitle, string title)
        {
            var sb = new StringBuilder();
            sb.AppendLine(title);
            sb.AppendLine(@"1ab

23/03/2012
03/05/2012
**:**:**.**
01:00:00.00
**:**:**.**
**:**:**.**
01:01:01.12
01:02:30.00
01:02:54.01
**:**:**.**
**:**:**.**
01:19:33.08
");

            int count = 1;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                sb.AppendLine(string.Format("{0}:  {1}  {2}\r\n{3}", count.ToString(CultureInfo.InvariantCulture).PadLeft(9, ' '), MakeTimeCode(p.StartTime), MakeTimeCode(p.EndTime), p.Text));
                count++;
            }

            var rtBox = new System.Windows.Forms.RichTextBox { Text = sb.ToString().Trim() };
            return rtBox.Rtf;
        }
Exemplo n.º 5
0
        public override string ToText(Subtitle subtitle, string title)
        {
            const string paragraphWriteFormat = "{0:00}:{1:00}:{2:00}.{3:00}, {4:00}:{5:00}:{6:00}.{7:00}{8}{9}";

            //00:00:07.00, 00:00:12.00
            //Welche Auswirkung Mikroversicherungen auf unsere Klienten hat? Lassen wir sie für sich selber sprechen!
            //
            //00:00:22.00, 00:00:27.00
            //Arme Menschen in Uganda leben oft in schlechten Unterkünften.

            var sb = new StringBuilder();
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                string text = p.Text.Replace(Environment.NewLine, "|");

                sb.AppendLine(string.Format(paragraphWriteFormat,
                                        p.StartTime.Hours,
                                        p.StartTime.Minutes,
                                        p.StartTime.Seconds,
                                        RoundTo2Cifres(p.StartTime.Milliseconds),
                                        p.EndTime.Hours,
                                        p.EndTime.Minutes,
                                        p.EndTime.Seconds,
                                        RoundTo2Cifres(p.EndTime.Milliseconds),
                                        Environment.NewLine,
                                        text));
                sb.AppendLine();
            }
            return sb.ToString().Trim();
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            const string timeCodeFormatNoHours = "{0:00}:{1:00}.{2:000}"; // h:mm:ss.cc
            const string timeCodeFormatHours = "{0}:{1:00}:{2:00}.{3:000}"; // h:mm:ss.cc
            const string paragraphWriteFormat = "{0} --> {1}{4}{2}{3}{4}";

            var sb = new StringBuilder();
            sb.AppendLine("WEBVTT FILE");
            sb.AppendLine();
            int count = 1;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                string start = string.Format(timeCodeFormatNoHours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds);
                string end = string.Format(timeCodeFormatNoHours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds);

                if (p.StartTime.Hours > 0 || p.EndTime.Hours > 0)
                {
                    start = string.Format(timeCodeFormatHours, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds);
                    end = string.Format(timeCodeFormatHours, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds);
                }

                string style = string.Empty;
                if (!string.IsNullOrEmpty(p.Extra) && subtitle.Header == "WEBVTT FILE")
                    style = p.Extra;
                sb.AppendLine(count.ToString());
                sb.AppendLine(string.Format(paragraphWriteFormat, start, end, FormatText(p), style, Environment.NewLine));
                count++;
            }
            return sb.ToString().Trim();
        }
Exemplo n.º 7
0
        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();
            _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);
                        var p = new Paragraph(DecodeTimeCode(startParts), DecodeTimeCode(endParts), text);
                        subtitle.Paragraphs.Add(p);
                    }
                }
                else
                {
                    _errorCount += 10;
                }
            }

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

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

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

                XmlAttribute start = xml.CreateAttribute("start");
                start.InnerText = string.Format("{0}", p.StartTime.TotalMilliseconds / 1000).Replace(",", ".");
                paragraph.Attributes.Append(start);

                XmlAttribute duration = xml.CreateAttribute("dur");
                duration.InnerText = string.Format("{0}", p.Duration.TotalMilliseconds / 1000).Replace(",", ".");
                paragraph.Attributes.Append(duration);

                paragraph.InnerText = p.Text;

                xml.DocumentElement.AppendChild(paragraph);
            }

            return ToUtf8XmlString(xml);
        }
Exemplo 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();
            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 = Utilities.RemoveHtmlTags(p.Text.Replace(Environment.NewLine, "|"));

                reel.AppendChild(paragraph);
            }

            return ToUtf8XmlString(xml);
        }
Exemplo n.º 10
0
        public override string ToText(Subtitle subtitle, string title)
        {
            var sb = new StringBuilder();
            sb.AppendLine(title);
            sb.AppendLine(@"1ab

10/01/2012
10/01/2012
01:00:22.09
01:00:30.09
**:**:**.**
**:**:**.**
01:00:51.09
01:00:55.22
01:01:10.09
**:**:**.**
**:**:**.**
01:13:23.09");
            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}:  {1}  {2}\r\n{3}\r\n", count, MakeTimeCode(p.StartTime), MakeTimeCode(p.EndTime), text));
                count++;
            }

            return sb.ToString();
        }
Exemplo n.º 11
0
        public override string ToText(Subtitle subtitle, string title)
        {
            const string paragraphWriteFormat = "{0} , {1} , {2}\r\n";
            const string timeFormat = "{0:00}:{1:00}:{2:00}:{3:00}";
            const string header = @"$VertAlign          =   Bottom
$Bold               =   FALSE
$Underlined         =   FALSE
$Italic             =   0
$XOffset                =   0
$YOffset                =   -5
$TextContrast           =   15
$Outline1Contrast           =   15
$Outline2Contrast           =   13
$BackgroundContrast     =   0
$ForceDisplay           =   FALSE
$FadeIn             =   0
$FadeOut                =   0
$HorzAlign          =   Center
";

            var sb = new StringBuilder();
            sb.AppendLine(header);
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                double factor = (1000.0 / Configuration.Settings.General.CurrentFrameRate);
                string startTime = string.Format(timeFormat, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, (int)Math.Round(p.StartTime.Milliseconds / factor));
                string endTime = string.Format(timeFormat, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, (int)Math.Round(p.EndTime.Milliseconds / factor));
                sb.AppendFormat(paragraphWriteFormat, startTime, endTime, DvdStudioPro.EncodeStyles(p.Text));
            }
            return sb.ToString().Trim();
        }
Exemplo n.º 12
0
        public override string ToText(Subtitle subtitle, string title)
        {
            StringBuilder sb = new StringBuilder();
            int index = 0;
            sb.AppendLine("<Window" + Environment.NewLine +
                "  Width    = \"640\"" + Environment.NewLine +
                "  Height   = \"480\"" + Environment.NewLine +
                "  WordWrap = \"true\"" + Environment.NewLine +
                "  Loop     = \"true\"" + Environment.NewLine +
                "  bgcolor  = \"black\"" + Environment.NewLine +
                ">" + Environment.NewLine +
                "<Font" + Environment.NewLine +
                "  Color = \"white\"" + Environment.NewLine +
                "  Face  = \"Arial\"" + Environment.NewLine +
                "  Size  = \"+2\"" + Environment.NewLine +
                ">" + Environment.NewLine +
                "<center>" + Environment.NewLine +
                "<b>" + Environment.NewLine);

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                //<Time begin="0:03:24.8" end="0:03:29.4" /><clear/>Man stjæler ikke fra Chavo, nej.
                sb.AppendLine(string.Format("<Time begin=\"{0}\" end=\"{1}\" /><clear/>{2}", EncodeTimeCode(p.StartTime), EncodeTimeCode(p.EndTime), p.Text.Replace(Environment.NewLine, " ")));
                index++;
            }
            sb.AppendLine("</b>");
            sb.AppendLine("</center>");
            return sb.ToString();
        }
Exemplo n.º 13
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) || new TMPlayer().IsMine(lines, fileName))
                    return false;
                return true;
            }
            return false;
        }
Exemplo n.º 14
0
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            //<Time begin="0:03:24.8" end="0:03:29.4" /><clear/>Man stjæler ikke fra Chavo, nej.
            subtitle.Paragraphs.Clear();
            _errorCount = 0;
            foreach (string line in lines)
            {
                try
                {
                    if (line.Contains("<Time ") && line.Contains(" begin=") && line.Contains("end="))
                    {
                        int indexOfBegin = line.IndexOf(" begin=", StringComparison.Ordinal);
                        int indexOfEnd = line.IndexOf(" end=", StringComparison.Ordinal);
                        string begin = line.Substring(indexOfBegin + 7, 11);
                        string end = line.Substring(indexOfEnd + 5, 11);

                        string[] startParts = begin.Split(new[] { ':', '.', '"' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] endParts = end.Split(new[] { ':', '.', '"' }, StringSplitOptions.RemoveEmptyEntries);
                        if (startParts.Length == 4 && endParts.Length == 4)
                        {
                            string text = line.Substring(line.LastIndexOf("/>", StringComparison.Ordinal) + 2);
                            var p = new Paragraph(DecodeTimeCode(startParts), DecodeTimeCode(endParts), text);
                            subtitle.Paragraphs.Add(p);
                        }
                    }
                }
                catch
                {
                    _errorCount++;
                }
            }

            subtitle.Renumber();
        }
Exemplo n.º 15
0
 public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
 {
     _errorCount = 0;
     int number = 0;
     foreach (string line in lines)
     {
         if (line.Trim().Length > 0 && line[0] != '$' && !line.StartsWith("//"))
         {
             if (RegexTimeCodes.Match(line).Success)
             {
                 string[] toPart = line.Substring(0, 25).Split(new[] { " ," }, StringSplitOptions.None);
                 Paragraph p = new Paragraph();
                 if (toPart.Length == 2 &&
                     DvdStudioPro.GetTimeCode(p.StartTime, toPart[0]) &&
                     DvdStudioPro.GetTimeCode(p.EndTime, toPart[1]))
                 {
                     number++;
                     p.Number = number;
                     string text = line.Substring(27).Trim();
                     p.Text = text.Replace(" | ", Environment.NewLine).Replace("|", Environment.NewLine);
                     p.Text = DvdStudioPro.DecodeStyles(p.Text);
                     subtitle.Paragraphs.Add(p);
                 }
             }
             else
             {
                 _errorCount++;
             }
         }
     }
 }
Exemplo n.º 16
0
        public override string ToText(Subtitle subtitle, string title)
        {
            var 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 = Utilities.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++;
            }

            var rtBox = new System.Windows.Forms.RichTextBox();
            rtBox.Text = sb.ToString();
            string rtf = rtBox.Rtf;
            rtBox.Dispose();
            return rtf;
        }
Exemplo n.º 17
0
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            _errorCount = 0;
            var sb = new StringBuilder();
            foreach (string line in lines)
                sb.AppendLine(line);

            string rtf = sb.ToString().Trim();
            if (!rtf.StartsWith("{\\rtf"))
                return;

            string[] arr = null;
            var rtBox = new System.Windows.Forms.RichTextBox();
            try
            {
                rtBox.Rtf = rtf;
                arr = rtBox.Text.Replace("\r", string.Empty).Split('\n');
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(exception.Message);
                return;
            }
            finally
            {
                rtBox.Dispose();
            }

            lines = new List<string>();
            foreach (string s in arr)
                lines.Add(s);
            base.LoadSubtitle(subtitle, lines, fileName);
        }
Exemplo n.º 18
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();
        }
Exemplo n.º 19
0
        public void Initialize(Subtitle subtitle)
        {
            _subtitle = subtitle;

            FindAllNames();
            GeneratePreview();
        }
        /// <summary>
        /// The initialize.
        /// </summary>
        /// <param name="subtitle">
        /// The subtitle.
        /// </param>
        /// <param name="fileName">
        /// The file name.
        /// </param>
        internal void Initialize(Subtitle subtitle, string fileName)
        {
            this._subtitle = subtitle;
            this._fileName = fileName;
            this.textBoxText.ReadOnly = true;
            this.comboBoxTimeCodeSeparator.SelectedIndex = 0;
            this.GeneratePreview();

            this.comboBoxEncoding.Items.Clear();
            int encodingSelectedIndex = 0;
            this.comboBoxEncoding.Items.Add(Encoding.UTF8.EncodingName);
            foreach (EncodingInfo ei in Encoding.GetEncodings())
            {
                if (ei.Name != Encoding.UTF8.BodyName && ei.CodePage >= 949 && !ei.DisplayName.Contains("EBCDIC") && ei.CodePage != 1047)
                {
                    this.comboBoxEncoding.Items.Add(ei.CodePage + ": " + ei.DisplayName);
                    if (ei.Name == Configuration.Settings.General.DefaultEncoding)
                    {
                        encodingSelectedIndex = this.comboBoxEncoding.Items.Count - 1;
                    }
                }
            }

            this.comboBoxEncoding.SelectedIndex = encodingSelectedIndex;
        }
 public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
 {
     this._errorCount = 0;
     int number = 0;
     foreach (string line in lines)
     {
         if (!string.IsNullOrWhiteSpace(line) && line[0] != '$')
         {
             if (RegexTimeCodes.Match(line).Success)
             {
                 string[] threePart = line.Split(new[] { "\t,\t" }, StringSplitOptions.None);
                 Paragraph p = new Paragraph();
                 if (threePart.Length == 3 && GetTimeCode(p.StartTime, threePart[0]) && GetTimeCode(p.EndTime, threePart[1]))
                 {
                     number++;
                     p.Number = number;
                     p.Text = threePart[2].TrimEnd().Replace(" | ", Environment.NewLine).Replace("|", Environment.NewLine);
                     p.Text = DecodeStyles(p.Text);
                     subtitle.Paragraphs.Add(p);
                 }
             }
             else
             {
                 this._errorCount++;
             }
         }
     }
 }
Exemplo n.º 22
0
        public override string ToText(Subtitle subtitle, string title)
        {
            const string paragraphWriteFormat = "{0:00}:{1:00}:{2:00},{3:00}:{4:00}:{5:00}{6}{7}";

            //00:00:08,00:00:13
            //The 8.7 update will bring the British self-propelled guns, the map, called Severogorsk,

            //00:00:13,00:00:18
            //the soviet light tank MT-25 and the new German premium TD, the E25.

            //00:00:18,00:00:22
            //We will tell you about this and lots of other things in our review.

            var sb = new StringBuilder();
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                string text = p.Text.Replace(Environment.NewLine, " ");

                sb.AppendLine(string.Format(paragraphWriteFormat,
                                        p.StartTime.Hours,
                                        p.StartTime.Minutes,
                                        RoundSeconds(p.StartTime),
                                        p.EndTime.Hours,
                                        p.EndTime.Minutes,
                                        RoundSeconds(p.EndTime),
                                        Environment.NewLine,
                                        text));
                sb.AppendLine();
            }
            return sb.ToString().Trim();
        }
Exemplo n.º 23
0
        public override string ToText(Subtitle subtitle, string title)
        {
            //SUBTITLE: 1   TIMEIN: 00:00:07:01 DURATION: 03:11 TIMEOUT: 00:00:10:12
            //Voor de oorlog

            //SUBTITLE: 2   TIMEIN: 00:00:10:16 DURATION: 01:08 TIMEOUT: 00:00:11:24
            //Ik ben Marie Pinhas. Ik ben geboren
            //in Thessaloniki in Griekenland,

            //SUBTITLE: 3   TIMEIN: 00:00:12:12 DURATION: 02:10 TIMEOUT: 00:00:14:22
            //op 6 maart '31,
            //in een heel oude Griekse familie.

            const string paragraphWriteFormat = "SUBTITLE: {1}\tTIMEIN: {0}\tDURATION: {4}\tTIMEOUT: {2}\r\n{3}\r\n";

            var sb = new StringBuilder();
            int count = 1;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                // to avoid rounding errors in duration
                var startFrame = MillisecondsToFramesMaxFrameRate(p.StartTime.Milliseconds);
                var endFrame = MillisecondsToFramesMaxFrameRate(p.EndTime.Milliseconds);
                var durationCalc = new Paragraph(
                        new TimeCode(p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, FramesToMillisecondsMax999(startFrame)),
                        new TimeCode(p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, FramesToMillisecondsMax999(endFrame)),
                        string.Empty);

                string startTime = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, startFrame);
                string timeOut = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, endFrame);
                string timeDuration = string.Format("{0:00}:{1:00}", durationCalc.Duration.Seconds, MillisecondsToFramesMaxFrameRate(durationCalc.Duration.Milliseconds));
                sb.AppendLine(string.Format(paragraphWriteFormat, startTime, count, timeOut, p.Text, timeDuration));
                count++;
            }
            return sb.ToString().Trim();
        }
Exemplo n.º 24
0
        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();
        }
Exemplo n.º 25
0
        public override string ToText(Subtitle subtitle, string title)
        {
            const string paragraphWriteFormat = "{0}-{1}\r\n{2}";
            var sb = new StringBuilder();
            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine();
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                string text = p.Text;
                if (Utilities.CountTagInText(text, Environment.NewLine) > 1)
                    text = Utilities.AutoBreakLine(text);
                text = Utilities.RemoveHtmlTags(text, true);
                if (p.Text.Contains("<i>"))
                {
                    if (Utilities.CountTagInText(p.Text, "<i>") == 1 && Utilities.CountTagInText(p.Text, "</i>") == 1 &&
                        p.Text.StartsWith("<i>") && p.Text.StartsWith("<i>"))
                    {
                        text = "||" + text.Replace(Environment.NewLine, "||" + Environment.NewLine + "||") + "||";
                    }
                    else if (Utilities.CountTagInText(p.Text, "<i>") == 2 && Utilities.CountTagInText(p.Text, "</i>") == 2 &&
                        p.Text.StartsWith("<i>") && p.Text.StartsWith("<i>") && p.Text.Contains("</i>" + Environment.NewLine + "<i>"))
                    {
                        text = "||" + text.Replace(Environment.NewLine, "||" + Environment.NewLine + "||") + "||";
                    }
                }

                if (!text.Contains(Environment.NewLine))
                    text = Environment.NewLine + text;
                sb.AppendLine(string.Format(paragraphWriteFormat, FormatTime(p.StartTime), FormatTime(p.EndTime), text));
            }
            sb.AppendLine();
            return sb.ToString();
        }
Exemplo n.º 26
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
                "<uts>" + Environment.NewLine +
                "</uts>";

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

            XmlNode root = xml.DocumentElement;

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                //<ut secOut="26.4" secIn="21.8">
                //  <![CDATA[Pozdrav i dobrodošli natrag<br>u drugi dio naše emisije]]>
                //</ut>
                XmlNode ut = xml.CreateElement("ut");

                XmlAttribute et = xml.CreateAttribute("secOut");
                et.InnerText = string.Format("{0:0.0##}", p.EndTime.TotalSeconds).Replace(",", ".");
                ut.Attributes.Append(et);

                XmlAttribute st = xml.CreateAttribute("secIn");
                st.InnerText = string.Format("{0:0.0##}", p.StartTime.TotalSeconds).Replace(",", ".");
                ut.Attributes.Append(st);

                ut.InnerText = p.Text;
                ut.InnerXml = "<![CDATA[" + ut.InnerXml.Replace(Environment.NewLine, "<br>") + "]]>";

                root.AppendChild(ut);
            }

            return ToUtf8XmlString(xml);
        }
 public override bool IsMine(List<string> lines, string fileName)
 {
     var subtitle = new Subtitle();
     LoadSubtitle(subtitle, lines, fileName);
     Errors = null;
     return subtitle.Paragraphs.Count > _errorCount;
 }
Exemplo n.º 28
0
        public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
        {
            _errorCount = 0;
            var regexTimeCode = new Regex(@"^E 1 \d:\d\d:\d\d.\d\d \d:\d\d:\d\d.\d\d Default NTP ", RegexOptions.Compiled);
            //E 1 0:50:05.42 0:50:10.06 Default NTP

            subtitle.Paragraphs.Clear();
            foreach (string line in lines)
            {
                if (regexTimeCode.IsMatch(line))
                {
                    try
                    {
                        string timePart = line.Substring(4, 10).Trim();
                        var start = DecodeTimeCode(timePart);
                        timePart = line.Substring(15, 10).Trim();
                        var end = DecodeTimeCode(timePart);
                        var paragraph = new Paragraph();
                        paragraph.StartTime = start;
                        paragraph.EndTime = end;
                        paragraph.Text = line.Substring(38).Replace(" \\n ", Environment.NewLine).Replace("\\n", Environment.NewLine);
                        subtitle.Paragraphs.Add(paragraph);
                    }
                    catch
                    {
                        _errorCount++;
                    }
                }
            }
            subtitle.Renumber();
        }
Exemplo n.º 29
0
        public override string ToText(Subtitle subtitle, string title)
        {
            var sb = new StringBuilder();

            sb.AppendLine(" " + subtitle.Paragraphs.Count.ToString() + "           4             1234 ");
            sb.AppendLine(@"NORMAL
00:00:00.00

SRPSKI

00:00:00.00
26.11.2008  18:54:15");

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                string firstLine = string.Empty;
                string secondLine = string.Empty;
                string[] lines = p.Text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (lines.Length > 2)
                {
                    lines = Utilities.AutoBreakLine(p.Text).Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                }
                if (lines.Length > 0)
                    firstLine = lines[0];
                if (lines.Length > 1)
                    secondLine = lines[1];

                sb.AppendLine(string.Format(" {0}          {1} " + Environment.NewLine +
                                            "1    0    0    0    0    0" + Environment.NewLine +
                                            "{2}" + Environment.NewLine +
                                            "{3}", p.StartTime.TotalMilliseconds / 10, p.EndTime.TotalMilliseconds / 10, firstLine, secondLine));
            }
            return sb.ToString().Trim();
        }
Exemplo n.º 30
0
 public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
 {
     _errorCount = 0;
     Paragraph p = null;
     subtitle.Paragraphs.Clear();
     foreach (string line in lines)
     {
         if (regexTimeCodes.IsMatch(line))
         {
             p = new Paragraph(DecodeTimeCode(line), new TimeCode(0,0,0,0), string.Empty);
             subtitle.Paragraphs.Add(p);
         }
         else if (line.Trim().Length == 0)
         {
             // skip these lines
         }
         else if (line.Trim().Length > 0 && p != null)
         {
             if (string.IsNullOrEmpty(p.Text))
                 p.Text = line;
             else
                 p.Text = p.Text + Environment.NewLine + line;
         }
     }
     foreach (Paragraph p2 in subtitle.Paragraphs)
     {
         p2.Text = Utilities.AutoBreakLine(p2.Text);
     }
     subtitle.RecalculateDisplayTimes(Configuration.Settings.General.SubtitleMaximumDisplayMilliseconds, null);
     subtitle.Renumber(1);
 }
Exemplo n.º 31
0
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            const int startPosition = 256 * 3; // First 256 bytes block is just id, two next blocks are ProgramManagementInformation, then comes the list of PageManagementInformations

            _errorCount = 0;
            subtitle.Paragraphs.Clear();
            subtitle.Header = null;
            var    buffer = FileUtil.ReadAllBytesShared(fileName);
            int    index  = startPosition;
            string label  = Encoding.ASCII.GetString(buffer, 0, 8);

            if (label != "DCAPTION" && label != "BCAPTION" && label != "MCAPTION")
            {
                return;
            }

            var programManagementInformation = new ProgramManagement(buffer, 256 + 4);

            while (index + 255 < buffer.Length)
            {
                if (buffer[index + 4] == 0x2a) // Page management information
                {
                    int blockstart = index;
                    int length     = (buffer[index + 2] << 8) + buffer[index + 3];
                    index += 5;
                    var pageManagementInformationLength = (buffer[index++] << 8) + buffer[index++];
                    var pageManagementInformation       = new PageManagement(buffer, index);
                    index += pageManagementInformationLength;
                    if (buffer[index] == 0x3a) // Caption text page management data
                    {
                        index++;
                        var captionTextPageManagementLength = (buffer[index++] << 8) + buffer[index++];
                        var captionTextPageManagement       = new CaptionTextPageManagement(buffer, index);
                        index += captionTextPageManagementLength;

                        if (buffer[index] == 0x4a) // Caption text data
                        {
                            index++;
                            var subtitleDataLength = (buffer[index++] << 8) + buffer[index++];
                            try
                            {
                                var captionText = new CaptionText(buffer, index, captionTextPageManagement.Iso639Languagecode);
                                var p           = new Paragraph
                                {
                                    StartTime = pageManagementInformation.GetStartTime(),
                                    EndTime   = pageManagementInformation.GetEndTime()
                                };
                                foreach (var unit in captionText.CaptionTextUnits)
                                {
                                    foreach (var text in unit.AribText.Texts)
                                    {
                                        p.Text = (p.Text + Environment.NewLine + text.Text).Trim();
                                    }
                                }
                                subtitle.Paragraphs.Add(p);
                            }
                            catch
                            {
                                _errorCount++;
                            }
                        }
                    }
                    index = RoundUp(blockstart + length, 256);
                }
                else
                {
                    index += 256;
                }
            }
            for (int i = 0; i < subtitle.Paragraphs.Count - 1; i++)
            {
                var paragraph = subtitle.Paragraphs[i];
                if (Math.Abs(paragraph.EndTime.TotalMilliseconds) < 0.001)
                {
                    var next = subtitle.Paragraphs[i + 1];
                    paragraph.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - Configuration.Settings.General.MinimumMillisecondsBetweenLines;
                }
            }
            if (subtitle.Paragraphs.Count > 0 && Math.Abs(subtitle.Paragraphs[subtitle.Paragraphs.Count - 1].EndTime.TotalMilliseconds) < 0.001)
            {
                var p = subtitle.Paragraphs[subtitle.Paragraphs.Count - 1];
                p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + Utilities.GetOptimalDisplayMilliseconds(p.Text);
            }

            subtitle.Renumber();
        }
Exemplo n.º 32
0
        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().Replace(" & ", " &amp; ").Replace("Q&A", "Q&amp;A").RemoveControlCharactersButWhiteSpace().Trim());

            var nsmgr = new XmlNamespaceManager(xml.NameTable);
            nsmgr.AddNamespace("ttaf1", xml.DocumentElement.NamespaceURI);

            var div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).SelectSingleNode("ttaf1:div", nsmgr);
            if (div == null)
                div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).FirstChild;

            var styleDic = new Dictionary<string, string>();
            foreach (XmlNode node in xml.DocumentElement.SelectNodes("//ttaf1:style", nsmgr))
            {
                if (node.Attributes["tts:fontStyle"] != null && node.Attributes["xml:id"] != null)
                {
                    styleDic.Add(node.Attributes["xml:id"].Value, node.Attributes["tts:fontStyle"].Value);
                }
            }
            bool couldBeFrames = true;
            bool couldBeMillisecondsWithMissingLastDigit = true;
            foreach (XmlNode node in div.ChildNodes)
            {
                try
                {
                    var pText = new StringBuilder();
                    foreach (XmlNode innerNode in node.ChildNodes)
                    {
                        switch (innerNode.Name.Replace("tt:", string.Empty))
                        {
                            case "br":
                                pText.AppendLine();
                                break;
                            case "span":
                                bool italic = false;
                                if (innerNode.Attributes["style"] != null && styleDic.ContainsKey(innerNode.Attributes["style"].Value))
                                {
                                    if (styleDic[innerNode.Attributes["style"].Value].Contains("italic"))
                                    {
                                        italic = true;
                                        pText.Append("<i>");
                                    }
                                }
                                if (!italic && innerNode.Attributes != null)
                                {
                                    var fs = innerNode.Attributes.GetNamedItem("tts:fontStyle");
                                    if (fs != null && fs.Value == "italic")
                                    {
                                        italic = true;
                                        pText.Append("<i>");
                                    }
                                }
                                if (innerNode.HasChildNodes)
                                {
                                    foreach (XmlNode innerInnerNode in innerNode.ChildNodes)
                                    {
                                        if (innerInnerNode.Name == "br" || innerInnerNode.Name == "tt:br")
                                        {
                                            pText.AppendLine();
                                        }
                                        else
                                        {
                                            pText.Append(innerInnerNode.InnerText);
                                        }
                                    }
                                }
                                else
                                {
                                    pText.Append(innerNode.InnerText);
                                }
                                if (italic)
                                    pText.Append("</i>");
                                break;
                            case "i":
                                pText.Append("<i>" + innerNode.InnerText + "</i>");
                                break;
                            case "b":
                                pText.Append("<b>" + innerNode.InnerText + "</b>");
                                break;
                            default:
                                pText.Append(innerNode.InnerText);
                                break;
                        }
                    }

                    string start = null;
                    string end = null;
                    string dur = null;
                    foreach (XmlAttribute attr in node.Attributes)
                    {
                        if (attr.Name.EndsWith("begin", StringComparison.Ordinal))
                            start = attr.InnerText;
                        else if (attr.Name.EndsWith("end", StringComparison.Ordinal))
                            end = attr.InnerText;
                        else if (attr.Name.EndsWith("duration", StringComparison.Ordinal))
                            dur = attr.InnerText;
                    }
                    string text = pText.ToString();
                    text = text.Replace(Environment.NewLine + "</i>", "</i>" + Environment.NewLine);
                    text = text.Replace("<i></i>", string.Empty).Trim();
                    if (!string.IsNullOrEmpty(end))
                    {
                        if (end.Length != 11 || end.Substring(8, 1) != ":" || start == null || start.Length != 11 || start.Substring(8, 1) != ":")
                        {
                            couldBeFrames = false;
                        }

                        if (couldBeMillisecondsWithMissingLastDigit && (end.Length != 11 || start == null || start.Length != 11 || end.Substring(8, 1) != "." || start.Substring(8, 1) != "."))
                        {
                            couldBeMillisecondsWithMissingLastDigit = false;
                        }

                        double dBegin, dEnd;
                        if (!start.Contains(':') && Utilities.CountTagInText(start, '.') == 1 &&
                            !end.Contains(':') && Utilities.CountTagInText(end, '.') == 1 &&
                            double.TryParse(start, NumberStyles.Float, CultureInfo.InvariantCulture, out dBegin) && double.TryParse(end, NumberStyles.Float, CultureInfo.InvariantCulture, out dEnd))
                        {
                            subtitle.Paragraphs.Add(new Paragraph(text, dBegin * TimeCode.BaseUnit, dEnd * TimeCode.BaseUnit));
                        }
                        else
                        {
                            if (start.Length == 8 && start[2] == ':' && start[5] == ':' && end.Length == 8 && end[2] == ':' && end[5] == ':')
                            {
                                var p = new Paragraph();
                                var parts = start.Split(SplitCharColon);
                                p.StartTime = new TimeCode(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0);
                                parts = end.Split(SplitCharColon);
                                p.EndTime = new TimeCode(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), 0);
                                p.Text = text;
                                subtitle.Paragraphs.Add(p);
                            }
                            else
                            {
                                subtitle.Paragraphs.Add(new Paragraph(TimedText10.GetTimeCode(start, false), TimedText10.GetTimeCode(end, false), text));
                            }
                        }
                    }
                    else if (!string.IsNullOrEmpty(dur))
                    {
                        if (dur.Length != 11 || dur.Substring(8, 1) != ":" || start == null || start.Length != 11 || start.Substring(8, 1) != ":")
                        {
                            couldBeFrames = false;
                        }

                        if (couldBeMillisecondsWithMissingLastDigit && (dur.Length != 11 || start == null || start.Length != 11 || dur.Substring(8, 1) != "." || start.Substring(8, 1) != "."))
                        {
                            couldBeMillisecondsWithMissingLastDigit = false;
                        }

                        TimeCode duration = TimedText10.GetTimeCode(dur, false);
                        TimeCode startTime = TimedText10.GetTimeCode(start, false);
                        var endTime = new TimeCode(startTime.TotalMilliseconds + duration.TotalMilliseconds);
                        subtitle.Paragraphs.Add(new Paragraph(startTime, endTime, text));
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    _errorCount++;
                }
            }
            subtitle.RemoveEmptyLines();

            if (couldBeFrames)
            {
                bool all30OrBelow = true;
                foreach (Paragraph p in subtitle.Paragraphs)
                {
                    if (p.StartTime.Milliseconds > 30 || p.EndTime.Milliseconds > 30)
                    {
                        all30OrBelow = false;
                        break;
                    }
                }
                if (all30OrBelow)
                {
                    foreach (Paragraph p in subtitle.Paragraphs)
                    {
                        p.StartTime.Milliseconds = SubtitleFormat.FramesToMillisecondsMax999(p.StartTime.Milliseconds);
                        p.EndTime.Milliseconds = SubtitleFormat.FramesToMillisecondsMax999(p.EndTime.Milliseconds);
                    }
                }
            }
            else if (couldBeMillisecondsWithMissingLastDigit && Configuration.Settings.SubtitleSettings.TimedText10TimeCodeFormatSource != "hh:mm:ss.ms-two-digits")
            {
                foreach (Paragraph p in subtitle.Paragraphs)
                {
                    p.StartTime.Milliseconds *= 10;
                    p.EndTime.Milliseconds *= 10;
                }
            }

            subtitle.Renumber();
        }
Exemplo n.º 33
0
 public override string ToText(Subtitle subtitle, string title)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 34
0
        private void AddWaterMark(Subtitle subtitle, string input)
        {
            if (subtitle == null || subtitle.Paragraphs.Count == 0)
            {
                return;
            }

            byte[] buffer = Encoding.ASCII.GetBytes(input);

            if (radioButtonCurrentLine.Checked)
            {
                StringBuilder sb = new StringBuilder();
                foreach (byte b in buffer)
                {
                    sb.Append(ZeroWidthSpace);
                    for (int i = 0; i < b; i++)
                    {
                        sb.Append(ZeroWidthNoBreakSpace);
                    }
                }
                Paragraph p = subtitle.GetParagraphOrDefault(_firstSelectedIndex);
                if (p != null)
                {
                    if (p.Text.Length > 1)
                    {
                        p.Text = p.Text.Insert(p.Text.Length / 2, sb.ToString());
                    }
                    else
                    {
                        p.Text = sb + p.Text;
                    }
                }
            }
            else
            {
                Random     r       = new Random();
                List <int> indices = new List <int>();
                foreach (byte b in buffer)
                {
                    int number = r.Next(subtitle.Paragraphs.Count - 1);
                    if (indices.Contains(number))
                    {
                        number = r.Next(subtitle.Paragraphs.Count - 1);
                    }
                    if (indices.Contains(number))
                    {
                        number = r.Next(subtitle.Paragraphs.Count - 1);
                    }
                    indices.Add(number);
                }

                indices.Sort();
                int j = 0;
                foreach (byte b in buffer)
                {
                    StringBuilder sb = new StringBuilder();
                    Paragraph     p  = subtitle.Paragraphs[indices[j]];
                    sb.Append(ZeroWidthSpace);
                    for (int i = 0; i < b; i++)
                    {
                        sb.Append(ZeroWidthNoBreakSpace);
                    }
                    if (p.Text.Length > 1)
                    {
                        p.Text = p.Text.Insert(p.Text.Length / 2, sb.ToString());
                    }
                    else
                    {
                        p.Text = sb + p.Text;
                    }
                    j++;
                }
            }
        }
Exemplo n.º 35
0
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            _errorCount = 0;
            bool expectStartTime = true;
            var  p = new Paragraph();

            subtitle.Paragraphs.Clear();
            foreach (string line in lines)
            {
                string s     = line.Trim().Replace("*", string.Empty);
                var    match = regexTimeCodes.Match(s);
                if (match.Success)
                {
                    string[] parts = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length == 4)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(p.Text))
                            {
                                subtitle.Paragraphs.Add(p);
                                p = new Paragraph();
                            }
                            p.StartTime     = DecodeTimeCode(parts[1]);
                            p.EndTime       = DecodeTimeCode(parts[2]);
                            expectStartTime = false;
                        }
                        catch (Exception exception)
                        {
                            _errorCount++;
                            System.Diagnostics.Debug.WriteLine(exception.Message);
                        }
                    }
                }
                else if (string.IsNullOrWhiteSpace(line))
                {
                    if (p.StartTime.TotalMilliseconds == 0 && p.EndTime.TotalMilliseconds == 0)
                    {
                        _errorCount++;
                    }
                    else
                    {
                        subtitle.Paragraphs.Add(p);
                    }
                    p = new Paragraph();
                }
                else if (!expectStartTime)
                {
                    p.Text = (p.Text + Environment.NewLine + line).Trim();
                    if (p.Text.Length > 500)
                    {
                        _errorCount += 10;
                        return;
                    }
                    while (p.Text.Contains(Environment.NewLine + " "))
                    {
                        p.Text = p.Text.Replace(Environment.NewLine + " ", Environment.NewLine);
                    }
                }
            }
            if (!string.IsNullOrEmpty(p.Text))
            {
                subtitle.Paragraphs.Add(p);
            }

            subtitle.RemoveEmptyLines();
            subtitle.Renumber(1);
        }
Exemplo n.º 36
0
 public void Save(string fileName, string videoFileName, Subtitle subtitle)
 {
 }
Exemplo n.º 37
0
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            _errorCount = 0;

            var sb = new StringBuilder();

            lines.ForEach(line => sb.AppendLine(line));
            if (!sb.ToString().Contains("</annotations>") || !sb.ToString().Contains("</TEXT>"))
            {
                return;
            }

            var xml = new XmlDocument {
                XmlResolver = null
            };

            try
            {
                string xmlText = sb.ToString();
                xml.LoadXml(xmlText);
                var styles = new List <string> {
                    "speech"
                };

                if (_promtForStyles)
                {
                    var stylesWithCount = new Dictionary <string, int>();
                    foreach (XmlNode node in xml.SelectNodes("//annotation"))
                    {
                        try
                        {
                            if (node.Attributes["style"] != null && node.Attributes["style"].Value != null)
                            {
                                string style = node.Attributes["style"].Value;

                                XmlNode     textNode = node.SelectSingleNode("TEXT");
                                XmlNodeList regions  = node.SelectNodes("segment/movingRegion/anchoredRegion");

                                if (regions.Count != 2)
                                {
                                    regions = node.SelectNodes("segment/movingRegion/rectRegion");
                                }

                                if (textNode != null && regions.Count == 2)
                                {
                                    if (stylesWithCount.ContainsKey(style))
                                    {
                                        stylesWithCount[style]++;
                                    }
                                    else
                                    {
                                        stylesWithCount.Add(style, 1);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                    }
                    if (stylesWithCount.Count > 1 && GetYouTubeAnnotationStyles != null)
                    {
                        styles = GetYouTubeAnnotationStyles.GetYouTubeAnnotationStyles(stylesWithCount);
                    }
                    else
                    {
                        styles.Clear();
                        foreach (var k in stylesWithCount.Keys)
                        {
                            styles.Add(k);
                        }
                    }
                }
                else
                {
                    styles.Add("popup");
                    styles.Add("anchored");
                }

                foreach (XmlNode node in xml.SelectNodes("//annotation"))
                {
                    try
                    {
                        if (node.Attributes["style"] != null && styles.Contains(node.Attributes["style"].Value))
                        {
                            XmlNode     textNode = node.SelectSingleNode("TEXT");
                            XmlNodeList regions  = node.SelectNodes("segment/movingRegion/anchoredRegion");

                            if (regions.Count != 2)
                            {
                                regions = node.SelectNodes("segment/movingRegion/rectRegion");
                            }

                            if (textNode != null && regions.Count == 2)
                            {
                                string startTime = regions[0].Attributes["t"].Value;
                                string endTime   = regions[1].Attributes["t"].Value;
                                var    p         = new Paragraph();
                                p.StartTime = DecodeTimeCode(startTime);
                                p.EndTime   = DecodeTimeCode(endTime);
                                p.Text      = textNode.InnerText;
                                subtitle.Paragraphs.Add(p);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                        _errorCount++;
                    }
                }
                subtitle.Sort(SubtitleSortCriteria.StartTime); // force order by start time
                subtitle.Renumber();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                _errorCount = 1;
                return;
            }
        }
Exemplo n.º 38
0
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            var regexTimeCodes = new Regex(@"^\d\d:\d\d:\d\d.\d+,\d\d:\d\d:\d\d.\d+$", RegexOptions.Compiled);

            var           paragraph = new Paragraph();
            ExpectingLine expecting = ExpectingLine.TimeCodes;

            _errorCount = 0;

            subtitle.Paragraphs.Clear();
            foreach (string line in lines)
            {
                if (regexTimeCodes.IsMatch(line))
                {
                    string[] parts = line.Split(new[] { ':', ',', '.' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length == 8)
                    {
                        try
                        {
                            int startHours        = int.Parse(parts[0]);
                            int startMinutes      = int.Parse(parts[1]);
                            int startSeconds      = int.Parse(parts[2]);
                            int startMilliseconds = int.Parse(parts[3]);
                            int endHours          = int.Parse(parts[4]);
                            int endMinutes        = int.Parse(parts[5]);
                            int endSeconds        = int.Parse(parts[6]);
                            int endMilliseconds   = int.Parse(parts[7]);
                            paragraph.StartTime = new TimeCode(startHours, startMinutes, startSeconds, startMilliseconds);
                            paragraph.EndTime   = new TimeCode(endHours, endMinutes, endSeconds, endMilliseconds);
                            expecting           = ExpectingLine.Text;
                        }
                        catch
                        {
                            expecting = ExpectingLine.TimeCodes;
                        }
                    }
                }
                else
                {
                    if (expecting == ExpectingLine.Text)
                    {
                        if (line.Length > 0)
                        {
                            string text = line.Replace("[br]", Environment.NewLine);
                            text = text.Replace("{\\i1}", "<i>");
                            text = text.Replace("{\\i0}", "</i>");
                            text = text.Replace("{\\b1}", "<b>'");
                            text = text.Replace("{\\b0}", "</b>");
                            text = text.Replace("{\\u1}", "<u>");
                            text = text.Replace("{\\u0}", "</u>");

                            paragraph.Text = text;
                            subtitle.Paragraphs.Add(paragraph);
                            paragraph = new Paragraph();
                            expecting = ExpectingLine.TimeCodes;
                        }
                    }
                }
            }
            subtitle.Renumber(1);
        }
Exemplo n.º 39
0
        internal void LoadTMpeg(Subtitle subtitle, List <string> lines, bool mustHaveLineBreakAsEnd)
        {
            _errorCount = 0;
            double startSeconds = 0;

            var sb = new StringBuilder();

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

            xml.LoadXml(sb.ToString().Trim());
            var italicStyles = new List <bool>();

            foreach (XmlNode node in xml.DocumentElement.SelectNodes("Layout/LayoutItem"))
            {
                XmlNode fontItalic = node.SelectSingleNode("FontItalic");
                if (fontItalic != null && fontItalic.InnerText == "1")
                {
                    italicStyles.Add(true);
                }
                else
                {
                    italicStyles.Add(false);
                }
            }

            foreach (XmlNode node in xml.DocumentElement.SelectNodes("Subtitle/SubtitleItem"))
            {
                try
                {
                    var pText = new StringBuilder();
                    foreach (XmlNode innerNode in node.SelectSingleNode("Text").ChildNodes)
                    {
                        switch (innerNode.Name)
                        {
                        case "br":
                            pText.AppendLine();
                            break;

                        default:
                            pText.Append(innerNode.InnerText.Trim());
                            break;
                        }
                    }

                    var start = string.Empty;
                    if (node.Attributes["starttime"] != null)
                    {
                        start = node.Attributes["starttime"].InnerText;
                    }

                    var end = string.Empty;
                    if (node.Attributes["endtime"] != null)
                    {
                        end = node.Attributes["endtime"].InnerText;
                    }

                    var startCode = TimeCode.FromSeconds(startSeconds);
                    if (start.Length > 0)
                    {
                        startCode = GetTimeCode(start);
                    }

                    TimeCode endCode;
                    if (end.Length > 0)
                    {
                        endCode = GetTimeCode(end);
                    }
                    else
                    {
                        endCode = new TimeCode(startCode.TotalMilliseconds + 3000);
                    }
                    startSeconds = endCode.TotalSeconds;
                    if (mustHaveLineBreakAsEnd)
                    {
                        if (!pText.ToString().EndsWith("\\n", StringComparison.Ordinal))
                        {
                            _errorCount++;
                        }
                    }
                    else
                    {
                        if (pText.ToString().EndsWith("\\n", StringComparison.Ordinal))
                        {
                            _errorCount++;
                        }
                    }

                    var p = new Paragraph(startCode, endCode, pText.ToString().Trim().Replace("<Text>", string.Empty).Replace("</Text>", string.Empty).Replace("\\n", Environment.NewLine).TrimEnd());
                    if (node.Attributes["layoutindex"] != null)
                    {
                        int idx;
                        if (int.TryParse(node.Attributes["layoutindex"].InnerText, out idx))
                        {
                            if (idx >= 0 && idx < italicStyles.Count && italicStyles[idx])
                            {
                                p.Text = "<i>" + p.Text + "</i>";
                            }
                        }
                    }
                    subtitle.Paragraphs.Add(p);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    _errorCount++;
                }
            }
            subtitle.Renumber();
        }
Exemplo n.º 40
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
                "<document>" + Environment.NewLine +
                "   <requestheader video_id=\"X\"/>" + Environment.NewLine +
                "  <annotations/>" + Environment.NewLine +
                "</document>";

            var xml = new XmlDocument();

            xml.LoadXml(xmlStructure);

            XmlNode annotations = xml.DocumentElement.SelectSingleNode("annotations");

            int count = 1;

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                //<annotation id="annotation_126995" author="StopFear" type="text" style="speech">
                //  <TEXT>BUT now something inside is BROKEN!</TEXT>
                //  <segment>
                //    <movingRegion type="anchored">
                //      <anchoredRegion x="6.005" y="9.231" w="26.328" h="18.154" sx="40.647" sy="14.462" t="0:01:08.0" d="0"/>
                //      <anchoredRegion x="6.005" y="9.231" w="26.328" h="18.154" sx="40.647" sy="14.462" t="0:01:13.0" d="0"/>
                //    </movingRegion>
                //  </segment>
                //</annotation>

                XmlNode annotation = xml.CreateElement("annotation");

                XmlAttribute att = xml.CreateAttribute("id");
                att.InnerText = "annotation_" + count;
                annotation.Attributes.Append(att);

                att           = xml.CreateAttribute("author");
                att.InnerText = "Subtitle Edit";
                annotation.Attributes.Append(att);

                att           = xml.CreateAttribute("type");
                att.InnerText = "text";
                annotation.Attributes.Append(att);

                att           = xml.CreateAttribute("style");
                att.InnerText = "speech";
                annotation.Attributes.Append(att);

                XmlNode text = xml.CreateElement("TEXT");
                text.InnerText = p.Text;
                annotation.AppendChild(text);

                XmlNode segment = xml.CreateElement("segment");
                annotation.AppendChild(segment);

                XmlNode movingRegion = xml.CreateElement("movingRegion");
                segment.AppendChild(movingRegion);

                att           = xml.CreateAttribute("type");
                att.InnerText = "anchored";
                movingRegion.Attributes.Append(att);

                XmlNode anchoredRegion = xml.CreateElement("anchoredRegion");
                movingRegion.AppendChild(anchoredRegion);
                att           = xml.CreateAttribute("t");
                att.InnerText = EncodeTime(p.StartTime);
                anchoredRegion.Attributes.Append(att);
                att           = xml.CreateAttribute("d");
                att.InnerText = "0";
                anchoredRegion.Attributes.Append(att);

                anchoredRegion = xml.CreateElement("anchoredRegion");
                movingRegion.AppendChild(anchoredRegion);
                att           = xml.CreateAttribute("t");
                att.InnerText = EncodeTime(p.EndTime);
                anchoredRegion.Attributes.Append(att);
                att           = xml.CreateAttribute("d");
                att.InnerText = "0";
                anchoredRegion.Attributes.Append(att);

                annotations.AppendChild(annotation);
                count++;
            }

            return(ToUtf8XmlString(xml));
        }
Exemplo n.º 41
0
 public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
 {
     LoadTMpeg(subtitle, lines, false);
 }
Exemplo n.º 42
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
                "<tt xmlns=\"http://www.w3.org/2006/10/ttaf1\" xmlns:ttp=\"http://www.w3.org/2006/10/ttaf1#parameter\" ttp:timeBase=\"media\" xmlns:tts=\"http://www.w3.org/2006/10/ttaf1#style\" xml:lang=\"en\" xmlns:ttm=\"http://www.w3.org/2006/10/ttaf1#metadata\">" + Environment.NewLine +
                "   <head>" + Environment.NewLine +
                "       <metadata>" + Environment.NewLine +
                "           <ttm:title></ttm:title>" + Environment.NewLine +
                "      </metadata>" + Environment.NewLine +
                "       <styling>" + Environment.NewLine +
                "         <style id=\"s0\" tts:backgroundColor=\"black\" tts:fontStyle=\"normal\" tts:fontSize=\"16\" tts:fontFamily=\"sansSerif\" tts:color=\"white\" />" + Environment.NewLine +
                "      </styling>" + Environment.NewLine +
                "   </head>" + Environment.NewLine +
                "   <body tts:textAlign=\"center\" style=\"s0\">" + Environment.NewLine +
                "       <div />" + Environment.NewLine +
                "   </body>" + Environment.NewLine +
                "</tt>";

            var xml = new XmlDocument();
            xml.LoadXml(xmlStructure);
            var nsmgr = new XmlNamespaceManager(xml.NameTable);
            nsmgr.AddNamespace("ttaf1", "http://www.w3.org/2006/10/ttaf1");
            nsmgr.AddNamespace("ttp", "http://www.w3.org/2006/10/ttaf1#parameter");
            nsmgr.AddNamespace("tts", "http://www.w3.org/2006/10/ttaf1#style");
            nsmgr.AddNamespace("ttm", "http://www.w3.org/2006/10/ttaf1#metadata");

            XmlNode titleNode = xml.DocumentElement.SelectSingleNode("//ttaf1:head", nsmgr).FirstChild.FirstChild;
            titleNode.InnerText = title;

            XmlNode div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).SelectSingleNode("ttaf1:div", nsmgr);
            if (div == null)
                div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).FirstChild;

            int no = 0;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("p", "http://www.w3.org/2006/10/ttaf1");

                string text = p.Text.Replace(Environment.NewLine, "\n").Replace("\n", "@iNEWLINE__");
                text = HtmlUtil.RemoveHtmlTags(text);
                paragraph.InnerText = text;
                paragraph.InnerXml = paragraph.InnerXml.Replace("@iNEWLINE__", "<br />");

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

                XmlAttribute id = xml.CreateAttribute("id");
                id.InnerText = "p" + no;
                paragraph.Attributes.Append(id);

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

                div.AppendChild(paragraph);
                no++;
            }

            string s = ToUtf8XmlString(xml);
            s = s.Replace(" xmlns=\"\"", string.Empty);
            return s;
        }