Subtitle CreateSubtitle(SubtitleInfomation subtitleInfomation) { if (subtitleInfomation.type != SubtitlePacketType.SUBTITLE_ASS && subtitleInfomation.type != SubtitlePacketType.SUBTITLE_TEXT) { return(null); } Subtitle subtitle = null; string nameFormat = "[MKV] {0}"; subtitle = new Subtitle() { SubtitleFileKind = SubtitleFileKind.Internal }; subtitle.AddLanguage(subtitleInfomation.language + ":" + subtitleInfomation.streamIndex, new List <KeyValuePair <string, string> >()); if (subtitleInfomation.type == SubtitlePacketType.SUBTITLE_ASS) { //ASS의 경우 스타일 로딩 AssParser assParser = new AssParser(); assParser.LoadHeader(subtitleInfomation.header); subtitle.Parser = assParser; subtitle.Title = string.Format(nameFormat, GetSubtitleName(subtitleInfomation)); } else if (subtitleInfomation.type == SubtitlePacketType.SUBTITLE_TEXT) { subtitle.Parser = new SrtParser(); subtitle.Title = string.Format(nameFormat, GetSubtitleName(subtitleInfomation)); } return(subtitle); }
public void ParseFieldHeaders_Valid_Success() { const string Line = "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"; var headers = AssParser.ParseFieldHeaders(Line); Assert.Equal(1, headers["Start"]); Assert.Equal(2, headers["End"]); Assert.Equal(9, headers["Text"]); }
public void Parse_Valid_Success() { using (var stream = File.OpenRead("Test Data/example.ass")) { var parsed = new AssParser().Parse(stream, CancellationToken.None); Assert.Single(parsed.TrackEvents); var trackEvent = parsed.TrackEvents[0]; Assert.Equal("1", trackEvent.Id); Assert.Equal(TimeSpan.Parse("00:00:01.18", CultureInfo.InvariantCulture).Ticks, trackEvent.StartPositionTicks); Assert.Equal(TimeSpan.Parse("00:00:06.85", CultureInfo.InvariantCulture).Ticks, trackEvent.EndPositionTicks); Assert.Equal("Like an Angel with pity on nobody\r\nThe second line in subtitle", trackEvent.Text); } }
private void SetMkvSubtitleLanguageList(MKVFileSource mkvFileSource) { var codecs = mkvFileSource.UsableSubtitleCodecs; Subtitle subtitle = null; byte[] header = null; string nameFormat = "[MKV] {0} {1}"; List <PickerItem <string, string> > list = new List <PickerItem <string, string> >(); foreach (var codec in codecs) { header = codec.TrackEntry.CodecPrivate; subtitle = new Subtitle() { SubtitleFileKind = SubtitleFileKind.Internal }; subtitle.AddLanguage(codec.TrackNumber.ToString(), new List <KeyValuePair <string, string> >()); if (codec is ASSCodec || codec is SSACodec) { //ASS의 경우 스타일 로딩 AssParser assParser = new AssParser(); assParser.LoadHeader(Encoding.UTF8.GetString(header, 0, header.Length)); subtitle.Parser = assParser; subtitle.Title = string.Format(nameFormat, GetCodecName(codec), assParser.GetTitle()); } else if (codec is SRTCodec) { subtitle.Parser = new SrtParser(); subtitle.Title = string.Format(nameFormat, GetCodecName(codec), string.Empty); } list.Add(new PickerItem <string, string> { Key = codec.TrackNumber.ToString(), Name = subtitle.Title, Payload = subtitle, Payload2 = (byte)4 }); } //재생패널 콤보에 추가 MessengerInstance.Send <Message>(new Message("SubtitlesLoaded", list), TransportControlViewModel.NAME); }
public void TestParse() { var expectedSubs = new SubtitleTrackInfo { TrackEvents = new List <SubtitleTrackEvent> { new SubtitleTrackEvent { Id = "1", StartPositionTicks = 24000000, EndPositionTicks = 72000000, Text = "Senator, we're " + ParserValues.NewLine + "making our final " + ParserValues.NewLine + "approach into Coruscant." }, new SubtitleTrackEvent { Id = "2", StartPositionTicks = 97100000, EndPositionTicks = 133900000, Text = "Very good, Lieutenant." }, new SubtitleTrackEvent { Id = "3", StartPositionTicks = 150400000, EndPositionTicks = 180400000, Text = "It's " + ParserValues.NewLine + "a " + ParserValues.NewLine + "trap!" } } }; var sut = new AssParser(); var stream = File.OpenRead(@"MediaEncoding\Subtitles\TestSubtitles\data.ass"); var result = sut.Parse(stream, CancellationToken.None); Assert.IsNotNull(result); Assert.AreEqual(expectedSubs.TrackEvents.Count, result.TrackEvents.Count); for (int i = 0; i < expectedSubs.TrackEvents.Count; i++) { Assert.AreEqual(expectedSubs.TrackEvents[i].Id, result.TrackEvents[i].Id); Assert.AreEqual(expectedSubs.TrackEvents[i].StartPositionTicks, result.TrackEvents[i].StartPositionTicks); Assert.AreEqual(expectedSubs.TrackEvents[i].EndPositionTicks, result.TrackEvents[i].EndPositionTicks); Assert.AreEqual(expectedSubs.TrackEvents[i].Text, result.TrackEvents[i].Text); } }
public void TestParse2() { var sut = new AssParser(); var stream = File.OpenRead(@"MediaEncoding\Subtitles\TestSubtitles\data2.ass"); var result = sut.Parse(stream, CancellationToken.None); Assert.IsNotNull(result); using (var ms = new MemoryStream()) { var writer = new SrtWriter(); writer.Write(result, ms, CancellationToken.None); ms.Position = 0; var text = Encoding.UTF8.GetString(ms.ToArray()); var b = text; } }
private void btnSyncAss_Click(object sender, EventArgs e) { try { AssParser assP = new AssParser(); assP.ParseASS(txtAssFile.Text); VideoFrameList vfl = _Kienzan.VideoFrames; //Double framerate = AcHelper.ConvertToDouble(Convert.ToString(comTargetFramerate.SelectedItem)); foreach (AssDialogue assD in assP.AssContents) { Decimal timeToDelete = 0m; for (Int32 currentSection = 0; currentSection < vfl.FrameSections.Count; currentSection++) { VideoFrameSection vfs = vfl.FrameSections[currentSection]; Decimal startSection = vfl.FrameList[vfs.FrameStart].FrameStartTime; Decimal endSection = vfl.FrameList[vfs.FrameEnd].FrameEndTime; //Check if the sub ends before the section if (assD.time_end_double <= startSection) { assD.deleted = true; break; } //Check if the sub starts after the section if (assD.time_start_double >= endSection) { //If its the last sections, then delete the sub if (currentSection == vfl.FrameSections.Count - 1) { assD.deleted = true; break; } else { if (currentSection == 0) { timeToDelete = startSection; } else { Decimal start = startSection; Decimal end = endSection; Decimal prevEnd = vfl.FrameList[vfl.FrameSections[currentSection - 1].FrameEnd].FrameEndTime; timeToDelete += start - prevEnd; } continue; } } //Time to resync the sub if (currentSection == 0) { TimeSpan ts; timeToDelete = startSection; assD.time_start_double = assD.time_start_double - timeToDelete; ts = TimeSpan.FromMilliseconds(Convert.ToDouble(assD.time_start_double)); assD.time_start = ts.Hours.ToString("0") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00") + "." + ts.Milliseconds.ToString("00"); assD.time_end_double = assD.time_end_double - timeToDelete; ts = TimeSpan.FromMilliseconds(Convert.ToDouble(assD.time_end_double)); assD.time_end = ts.Hours.ToString("0") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00") + "." + ts.Milliseconds.ToString("00"); break; } else { TimeSpan ts; Decimal start = startSection; Decimal end = endSection; Decimal prevEnd = vfl.FrameList[vfl.FrameSections[currentSection - 1].FrameEnd].FrameEndTime; timeToDelete += start - prevEnd; assD.time_start_double = assD.time_start_double - timeToDelete; ts = TimeSpan.FromMilliseconds(Convert.ToDouble(assD.time_start_double)); assD.time_start = ts.Hours.ToString("0") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00") + "." + (ts.Milliseconds / 10).ToString("00"); assD.time_end_double = assD.time_end_double - timeToDelete; ts = TimeSpan.FromMilliseconds(Convert.ToDouble(assD.time_end_double)); assD.time_end = ts.Hours.ToString("0") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00") + "." + (ts.Milliseconds / 10).ToString("00"); break; } } } assP.WriteFinalAss(txtAssFile.Text.Substring(0, txtAssFile.Text.LastIndexOf(".")) + ".resync.ass"); ShowSuccessMessage("Resync complete!"); } catch (Exception ex) { ShowExceptionMessage(ex); } }
private void btnSplit_Click(object sender, EventArgs e) { try { AssParser assP = new AssParser(); assP.ParseASS(txtAssFile.Text); VideoFrameList vfl = new VideoFrameList(); SectionParser.ParseSections(txtSectionsFile.Text, vfl); Decimal framerate = AcHelper.DecimalParse(txtFramerate.Text); foreach (AssDialogue assD in assP.AssContents) { Decimal timeToDelete = 0; for (Int32 currentSection = 0; currentSection < vfl.FrameSections.Count; currentSection++) { VideoFrameSection vfs = vfl.FrameSections[currentSection]; Decimal startSection = VideoFrame.GetStartTimeFromFrameNumber(vfs.FrameStart, framerate); Decimal endSection = VideoFrame.GetStartTimeFromFrameNumber(vfs.FrameEnd, framerate); //Check if the sub ends before the section if (assD.time_end_double <= startSection) { assD.deleted = true; break; } //Check if the sub starts after the section if (assD.time_start_double >= endSection) { //If its the last sections, then delete the sub if (currentSection == vfl.FrameSections.Count - 1) { assD.deleted = true; break; } else { continue; } } //Time to resync the sub if (currentSection == 0) { TimeSpan ts; timeToDelete = startSection; assD.time_start_double = assD.time_start_double - timeToDelete; ts = TimeSpan.FromMilliseconds(Convert.ToDouble(assD.time_start_double)); assD.time_start = ts.Hours.ToString("0") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00") + "." + ts.Milliseconds.ToString("00"); assD.time_end_double = assD.time_end_double - timeToDelete; ts = TimeSpan.FromMilliseconds(Convert.ToDouble(assD.time_end_double)); assD.time_end = ts.Hours.ToString("0") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00") + "." + ts.Milliseconds.ToString("00"); break; } else { TimeSpan ts; Decimal start = startSection; Decimal end = endSection; Decimal prevEnd = VideoFrame.GetStartTimeFromFrameNumber(vfl.FrameSections[currentSection - 1].FrameEnd, framerate); timeToDelete += start - prevEnd - VideoFrame.GetDurationFromFrameRate(framerate); assD.time_start_double = assD.time_start_double - timeToDelete; ts = TimeSpan.FromMilliseconds(Convert.ToDouble(assD.time_start_double)); assD.time_start = ts.Hours.ToString("0") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00") + "." + ts.Milliseconds.ToString("00"); assD.time_end_double = assD.time_end_double - timeToDelete; ts = TimeSpan.FromMilliseconds(Convert.ToDouble(assD.time_end_double)); assD.time_end = ts.Hours.ToString("0") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00") + "." + ts.Milliseconds.ToString("00"); break; } } } assP.WriteFinalAss(txtAssFile.Text.Substring(0, txtAssFile.Text.LastIndexOf(".") - 1) + ".resync.ass"); MessageBox.Show("Resync complete!", "Success!"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error!"); } }
private void translateAss() { String clientSecret = "t2TgsRqHDyX9sDuUhV6j+A0cTc9cqPVQCptbELxtll0="; String clientId = "AcTools"; AdmAccessToken admToken; string headerValue; //Get Client Id and Client Secret from https://datamarket.azure.com/developer/applications/ //Refer obtaining AccessToken (http://msdn.microsoft.com/en-us/library/hh454950.aspx) AdmAuthentication admAuth = new AdmAuthentication(clientId, clientSecret); admToken = admAuth.GetAccessToken(); // Create a header with the access_token property of the returned token headerValue = "Bearer " + admToken.access_token; //String key = "ABQIAAAAI4Uz6--7ldB77aSAjIT7DBR_SxwQvsoWDay0I_E-DJX3B_bnPhSeckwBVQ-R5MPCAZlrImAtgeHnIA"; //String langpair = "ja%7Cen"; //String langpair = "zh-CN%7Cen"; String langSource = "zh-CN"; String langDest = "en"; statusStrip.BeginInvoke(new UpdateStatusDelegate(UpdateStatus), "Starting parsing ass file..."); Application.DoEvents(); AssParser assP = new AssParser(); assP.ParseASS(txtAssFile.Text); progressBar.ProgressBar.BeginInvoke(new UpdateProgressMinimumDelegate(UpdateProgressMinimum), 0); progressBar.ProgressBar.BeginInvoke(new UpdateProgressMinimumDelegate(UpdateProgressMaximum), assP.AssContents.Count); int i = 1; statusStrip.BeginInvoke(new UpdateStatusDelegate(UpdateStatus), "Starting translating ass file..."); Application.DoEvents(); foreach (AssDialogue assD in assP.AssContents) { string translation = String.Empty; string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(assD.subtitle) + "&from=" + langSource + "&to=" + langDest; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri); httpWebRequest.Headers.Add("Authorization", headerValue); WebResponse response2 = null; try { response2 = httpWebRequest.GetResponse(); using (Stream stream = response2.GetResponseStream()) { System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String")); translation = (string)dcs.ReadObject(stream); } } catch { throw; } finally { if (response2 != null) { response2.Close(); response2 = null; } } assD.subtitle = translation; //// used to build entire input //StringBuilder sb = new StringBuilder(); //// used on each read operation //byte[] buf = new byte[8192]; //String url = String.Format("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={0}&langpair={1}&key={2}", assD.subtitle, langpair, key); ////String url = String.Format("https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}", // // key, langSource, langDest, System.Web.HttpUtility.HtmlEncode(assD.subtitle)); //// prepare the web page we will be asking for //HttpWebRequest request = (HttpWebRequest) // WebRequest.Create(url); ////lblStatus.Text =String.Format( "Requesting translation for line {0}...", i); //statusStrip.BeginInvoke(new UpdateStatusDelegate(UpdateStatus), String.Format("Requesting translation for line {0}/{1}...", // i, assP.AssContents.Count)); //Application.DoEvents(); //// execute the request //HttpWebResponse response = (HttpWebResponse) // request.GetResponse(); //// we will read data via the response stream //Stream resStream = response.GetResponseStream(); //string tempString = null; //int count = 0; //do //{ // // fill the buffer with data // count = resStream.Read(buf, 0, buf.Length); // // make sure we read some data // if (count != 0) // { // // translate from bytes to UTF8 text // tempString = Encoding.UTF8.GetString(buf, 0, count); // // continue building the string // sb.Append(tempString); // } //} //while (count > 0); // any more data to read? //JsonTextParser parser = new JsonTextParser(); //JsonObject obj = parser.Parse(sb.ToString()); //foreach (JsonObject field in obj as JsonObjectCollection) //{ // string name = field.Name; // if (name.ToLower().Contains("responsedata")) // { // List<JsonObject> lst = (List<JsonObject>)field.GetValue(); // //String str2 = getRomanji(assD.subtitle); // String str = String.Empty; // if (lst != null) // { // str = lst[0].GetValue().ToString(); // } // assD.subtitle = System.Web.HttpUtility.HtmlDecode(System.Web.HttpUtility.UrlDecode(str)); // } //} statusStrip.BeginInvoke(new UpdateStatusDelegate(UpdateStatus), String.Format("Translated line {0}/{1}!", i, assP.AssContents.Count)); progressBar.ProgressBar.BeginInvoke(new UpdateProgressDelegate(UpdateProgress), i); i++; } statusStrip.BeginInvoke(new UpdateStatusDelegate(UpdateStatus), "Started Writing translated ass file..."); assP.WriteFinalAss(txtAssFile.Text.Substring(0, txtAssFile.Text.LastIndexOf(".")) + ".trans.ass"); }