Information for progress dialog. This is independent of any toolkit because it a handler. Progress information is divided into two types: a) the section, which describes what is currently done. The section is a string like "Episode 01 - Extracting subtitle" Every section has... b) ... a number of steps. This is the information how much of the section is handled. An example is the number of processed lines when matching. Each section is finished after the number of processed steps is the same as the number of given steps for this section. Every section has the same share of the total 100%. There are some section fully completed, then there is the "active" section and then sections, that are 0% complete. Every of the n sections has 1/n part in the progress bar. In-between steps are determined by the sub-steps in the active section.
		public static void ExtractSnaphots(Settings settings, String path, List<Tuple<CardInfo, String>> allEntries, InfoProgress progress) {
			foreach(var entry in allEntries) {
				if(progress.Cancelled) break;
				progress.ProcessedSteps(1);

				var cardInfoNameTuple = entry;
				var cardInfo = cardInfoNameTuple.Item1;
				if(!cardInfo.HasImage()) continue;

				// create file at given path
				String outputSnapshotFilename = cardInfoNameTuple.Item2;
				String outputSnapshotFilepath = path + Path.DirectorySeparatorChar + outputSnapshotFilename;

				// get file with snapshot information -> video
				UtilsInputFiles.FileDesc videoFileDesc = cardInfo.episodeInfo.VideoFileDesc;

				// extract image
				double scaling = UtilsVideo.GetMaxScalingByStreamInfo(cardInfo.episodeInfo.VideoStreamInfo, settings.RescaleWidth, settings.RescaleHeight, settings.RescaleMode);
				double timeStamp = UtilsCommon.GetMiddleTime (cardInfo);
				UtilsImage.GetImage (videoFileDesc.filename, timeStamp, outputSnapshotFilepath, scaling);

			}
		}
		public static void ExtractAudio(Settings settings, String path, List<Tuple<CardInfo, String>> allEntries, InfoProgress progress) {
			foreach(var entry in allEntries) {
				progress.ProcessedSteps(1);
				if(progress.Cancelled) return;

				CardInfo cardInfo = entry.Item1;
				if(!cardInfo.HasAudio()) continue;

				String outputAudioFilename = entry.Item2;
				String outputAudioFilepath = path + Path.DirectorySeparatorChar + outputAudioFilename;

				UtilsInputFiles.FileDesc audioFileDesc = cardInfo.episodeInfo.AudioFileDesc;
				var audioStreamInfo = cardInfo.episodeInfo.AudioStreamInfo;

				String arguments = String.Format ("-v quiet -y -i \"{0}\" -map 0:{1} -ss \"{2}\" -to \"{3}\" -vn -c:a libvorbis \"{4}\"",
					audioFileDesc.filename, // input file
					audioStreamInfo.StreamIndex, // audio stream index
					UtilsCommon.ToTimeArg(cardInfo.audioStartTimestamp), // start time
					UtilsCommon.ToTimeArg(cardInfo.audioEndTimestamp), // end time
					outputAudioFilepath // output file
				);
				UtilsCommon.StartProcessAndGetOutput(InstanceSettings.systemSettings.formatConvertCommand, arguments);
			}
		}
        public void ExportData(Settings settings, InfoProgress progressInfo)
        {
            var activeCardList = GetActiveCards();

            progressInfo.AddSection("Exporting text file", 1);
            progressInfo.AddSection("Exporting snapshots", activeCardList.Count);
            progressInfo.AddSection("Exporting audio files", activeCardList.Count);
            if (settings.NormalizeAudio)
            {
                progressInfo.AddSection("Normalize audio files", activeCardList.Count);
            }
            progressInfo.Update();

            ExportTextFile(activeCardList, settings, progressInfo);

            progressInfo.ProcessedSteps(1);

            var cardSnapshotNameTupleList = new List <Tuple <CardInfo, String> >(activeCardList.Count);
            var cardAudioNameTupleList    = new List <Tuple <CardInfo, String> >(activeCardList.Count);

            foreach (var cardInfo in activeCardList)
            {
                cardSnapshotNameTupleList.Add(new Tuple <CardInfo, String>(cardInfo, GetSnapshotFileName(settings, cardInfo)));
                cardAudioNameTupleList.Add(new Tuple <CardInfo, String>(cardInfo, GetAudioFileName(settings, cardInfo)));
            }

            if (progressInfo.Cancelled)
            {
                return;
            }

            // extract images
            String snapshotsPath = settings.OutputDirectoryPath + Path.DirectorySeparatorChar + settings.DeckName + "_snapshots" + Path.DirectorySeparatorChar;

            UtilsCommon.ClearDirectory(snapshotsPath);
            WorkerSnapshot.ExtractSnaphots(settings, snapshotsPath, cardSnapshotNameTupleList, progressInfo);

            if (progressInfo.Cancelled)
            {
                return;
            }

            // extract audio
            String audioPath = settings.OutputDirectoryPath + Path.DirectorySeparatorChar + settings.DeckName + "_audio" + Path.DirectorySeparatorChar;

            UtilsCommon.ClearDirectory(audioPath);
            WorkerAudio.ExtractAudio(settings, audioPath, cardAudioNameTupleList, progressInfo);

            if (progressInfo.Cancelled)
            {
                return;
            }

            if (settings.NormalizeAudio)
            {
                // normalize all audio files
                foreach (var entry in cardAudioNameTupleList)
                {
                    if (progressInfo.Cancelled)
                    {
                        return;
                    }
                    progressInfo.ProcessedSteps(1);

                    var cardInfo = entry.Item1;
                    if (!cardInfo.HasAudio())
                    {
                        continue;
                    }

                    var filepath         = audioPath + entry.Item2;
                    var audioStreamInfos = StreamInfo.ReadAllStreams(filepath);
                    audioStreamInfos.RemoveAll(streamInfo => streamInfo.StreamTypeValue != StreamInfo.StreamType.ST_AUDIO);
                    if (audioStreamInfos.Count != 1)
                    {
                        Console.WriteLine("Skipped normalizing file \"{0}\" because it contains {1} audio streams", filepath, audioStreamInfos.Count);
                        continue;
                    }
                    try {
                        UtilsAudio.NormalizeAudio(filepath, audioStreamInfos[0]);
                    } catch (Exception e) {
                        Console.WriteLine(e.ToString());
                        continue;
                    }
                }
            }
        }
        /** Generates a .tsv file */
        public void ExportTextFile(List <CardInfo> cardInfoList, Settings settings, InfoProgress progressInfo)
        {
            String tsvFilename = settings.OutputDirectoryPath + Path.DirectorySeparatorChar + settings.DeckName + ".tsv";

            Console.WriteLine(tsvFilename);

            // value that will be imported into Anki/SRS-Programs-Field => [sound:???.ogg] and <img src="???.jpg"/>
            var snapshotFields = new List <String>(cardInfoList.Count);
            var audioFields    = new List <String>(cardInfoList.Count);

            foreach (var cardInfo in cardInfoList)
            {
                if (cardInfo.HasImage())
                {
                    var outputSnapshotFilename = GetSnapshotFileName(settings, cardInfo);
                    snapshotFields.Add("<img src=\"" + outputSnapshotFilename + "\"/>"); // TODO: make this flexible
                }
                else
                {
                    snapshotFields.Add("");
                }

                if (cardInfo.HasAudio())
                {
                    var outputAudioFilename = GetAudioFileName(settings, cardInfo);
                    audioFields.Add("[sound:" + outputAudioFilename + "]"); // TODO: make this flexible
                }
                else
                {
                    audioFields.Add("");
                }
            }

            using (var outputStream = new StreamWriter(tsvFilename))
            {
                for (int i = 0; i < cardInfoList.Count; i++)
                {
                    CardInfo cardInfo = cardInfoList[i];

                    // XXX: performance analasys then --- generate a episode-filtered list for context card search (because it has O(n^2) steps)
                    var contextCardsTuple = UtilsSubtitle.GetContextCards(cardInfo.episodeInfo.Index, cardInfo, m_cardInfos);
                    var previousCards     = contextCardsTuple.Item1;
                    var nextCards         = contextCardsTuple.Item2;

                    var previousCardsNativeLanguage = UtilsSubtitle.CardListToMultilineString(previousCards, UtilsCommon.LanguageType.NATIVE);
                    var previousCardsTargetLanguage = UtilsSubtitle.CardListToMultilineString(previousCards, UtilsCommon.LanguageType.TARGET);

                    var nextCardsNativeLanguage = UtilsSubtitle.CardListToMultilineString(nextCards, UtilsCommon.LanguageType.NATIVE);
                    var nextCardsTargetLanguage = UtilsSubtitle.CardListToMultilineString(nextCards, UtilsCommon.LanguageType.TARGET);

                    String keyField   = cardInfo.GetKey();
                    String audioField = audioFields[i];
                    String imageField = snapshotFields[i];
                    String tags       = String.Format("SubtitleMemorize {0} ep{1:000} {2}", settings.DeckNameModified, cardInfo.episodeInfo.Number, InfoLanguages.languages[settings.TargetLanguageIndex].tag);
                    outputStream.WriteLine(UtilsCommon.HTMLify(keyField) + "\t" +
                                           UtilsCommon.HTMLify(imageField) + "\t" +
                                           UtilsCommon.HTMLify(audioField) + "\t" +
                                           UtilsCommon.HTMLify(cardInfo.ToSingleLine(UtilsCommon.LanguageType.TARGET)) + "\t" +
                                           UtilsCommon.HTMLify(cardInfo.ToSingleLine(UtilsCommon.LanguageType.NATIVE)) + "\t" +
                                           UtilsCommon.HTMLify(previousCardsTargetLanguage) + "\t" +
                                           UtilsCommon.HTMLify(previousCardsNativeLanguage) + "\t" +
                                           UtilsCommon.HTMLify(nextCardsTargetLanguage) + "\t" +
                                           UtilsCommon.HTMLify(nextCardsNativeLanguage) + "\t" +
                                           UtilsCommon.HTMLify(tags)
                                           );
                }
            }
        }
        public void ExportData(Settings settings, InfoProgress progressInfo)
        {
          var activeCardList = GetActiveCards();

          progressInfo.AddSection("Exporting text file", 1);
          progressInfo.AddSection("Exporting snapshots", activeCardList.Count);
          progressInfo.AddSection("Exporting audio files", activeCardList.Count);
          if(settings.NormalizeAudio) progressInfo.AddSection("Normalize audio files", activeCardList.Count);
          progressInfo.Update();

          ExportTextFile(activeCardList, settings, progressInfo);

          progressInfo.ProcessedSteps(1);

          var cardSnapshotNameTupleList = new List<Tuple<CardInfo, String>>(activeCardList.Count);
          var cardAudioNameTupleList = new List<Tuple<CardInfo, String>>(activeCardList.Count);
          foreach(var cardInfo in activeCardList) {
            cardSnapshotNameTupleList.Add(new Tuple<CardInfo, String>(cardInfo, GetSnapshotFileName(settings, cardInfo)));
            cardAudioNameTupleList.Add(new Tuple<CardInfo, String>(cardInfo, GetAudioFileName(settings, cardInfo)));
          }

          if(progressInfo.Cancelled) return;

          // extract images
          String snapshotsPath = settings.OutputDirectoryPath + Path.DirectorySeparatorChar + settings.DeckName + "_snapshots" + Path.DirectorySeparatorChar;
          UtilsCommon.ClearDirectory(snapshotsPath);
          WorkerSnapshot.ExtractSnaphots(settings, snapshotsPath, cardSnapshotNameTupleList, progressInfo);

          if(progressInfo.Cancelled) return;

          // extract audio
          String audioPath = settings.OutputDirectoryPath + Path.DirectorySeparatorChar + settings.DeckName + "_audio" + Path.DirectorySeparatorChar;
          UtilsCommon.ClearDirectory(audioPath);
          WorkerAudio.ExtractAudio(settings, audioPath, cardAudioNameTupleList, progressInfo);

          if(progressInfo.Cancelled) return;

          if(settings.NormalizeAudio) {
            // normalize all audio files
            foreach(var entry in cardAudioNameTupleList) {
              if(progressInfo.Cancelled) return;
              progressInfo.ProcessedSteps(1);

              var cardInfo = entry.Item1;
              if(!cardInfo.HasAudio()) continue;

              var filepath = audioPath + entry.Item2;
              var audioStreamInfos = StreamInfo.ReadAllStreams(filepath);
              audioStreamInfos.RemoveAll(streamInfo => streamInfo.StreamTypeValue != StreamInfo.StreamType.ST_AUDIO);
              if(audioStreamInfos.Count != 1) {
                Console.WriteLine("Skipped normalizing file \"{0}\" because it contains {1} audio streams", filepath, audioStreamInfos.Count);
                continue;
              }
              try {
                UtilsAudio.NormalizeAudio(filepath, audioStreamInfos[0]);
              } catch(Exception e) {
                Console.WriteLine(e.ToString());
                continue;
              }
            }
          }
        }
        /** Generates a .tsv file */
        public void ExportTextFile(List<CardInfo> cardInfoList, Settings settings, InfoProgress progressInfo) {
            String tsvFilename = settings.OutputDirectoryPath + Path.DirectorySeparatorChar + settings.DeckName + ".tsv";
            Console.WriteLine(tsvFilename);

            // value that will be imported into Anki/SRS-Programs-Field => [sound:???.ogg] and <img src="???.jpg"/>
            var snapshotFields = new List<String>(cardInfoList.Count);
            var audioFields = new List<String>(cardInfoList.Count);

            foreach(var cardInfo in cardInfoList) {
              if(cardInfo.HasImage()) {
                var outputSnapshotFilename = GetSnapshotFileName(settings, cardInfo);
                snapshotFields.Add("<img src=\"" + outputSnapshotFilename + "\"/>"); // TODO: make this flexible
              } else snapshotFields.Add("");

              if(cardInfo.HasAudio()) {
                var outputAudioFilename = GetAudioFileName(settings, cardInfo);
                audioFields.Add("[sound:" + outputAudioFilename + "]"); // TODO: make this flexible
              } else audioFields.Add("");
            }

            using (var outputStream = new StreamWriter(tsvFilename))
            {
                for (int i = 0; i < cardInfoList.Count; i++)
                {
                    CardInfo cardInfo = cardInfoList[i];

                    // XXX: performance analasys then --- generate a episode-filtered list for context card search (because it has O(n^2) steps)
                    var contextCardsTuple = UtilsSubtitle.GetContextCards(cardInfo.episodeInfo.Index, cardInfo, m_cardInfos);
                    var previousCards = contextCardsTuple.Item1;
                    var nextCards = contextCardsTuple.Item2;

                    var previousCardsNativeLanguage = UtilsSubtitle.CardListToMultilineString(previousCards, UtilsCommon.LanguageType.NATIVE);
                    var previousCardsTargetLanguage = UtilsSubtitle.CardListToMultilineString(previousCards, UtilsCommon.LanguageType.TARGET);

                    var nextCardsNativeLanguage = UtilsSubtitle.CardListToMultilineString(nextCards, UtilsCommon.LanguageType.NATIVE);
                    var nextCardsTargetLanguage = UtilsSubtitle.CardListToMultilineString(nextCards, UtilsCommon.LanguageType.TARGET);

                    String keyField = cardInfo.GetKey();
                    String audioField = audioFields[i];
                    String imageField = snapshotFields[i];
                    String tags = String.Format("SubtitleMemorize {0} ep{1:000} {2}", settings.DeckNameModified, cardInfo.episodeInfo.Number, InfoLanguages.languages[settings.TargetLanguageIndex].tag);
                    outputStream.WriteLine(UtilsCommon.HTMLify(keyField) + "\t" +
                                           UtilsCommon.HTMLify(imageField) + "\t"+
                                           UtilsCommon.HTMLify(audioField) + "\t" +
                                           UtilsCommon.HTMLify(cardInfo.ToSingleLine(UtilsCommon.LanguageType.TARGET)) + "\t" +
                                           UtilsCommon.HTMLify(cardInfo.ToSingleLine(UtilsCommon.LanguageType.NATIVE)) + "\t" +
                                           UtilsCommon.HTMLify(previousCardsTargetLanguage) + "\t" +
                                           UtilsCommon.HTMLify(previousCardsNativeLanguage) + "\t" +
                                           UtilsCommon.HTMLify(nextCardsTargetLanguage) + "\t" +
                                           UtilsCommon.HTMLify(nextCardsNativeLanguage) + "\t" +
                                           UtilsCommon.HTMLify(tags)
                                           );
                }
            }
        }
Esempio n. 7
0
		private void ConnectEventsPreviewWindowOptions() {

			// ----------------------------------------------------------------------------------------------------
			m_previewWindow.DeleteEvent += delegate(object o, DeleteEventArgs args) {
				m_previewWindow.Hide();
				args.RetVal = true; // prevents window from being actually deleted
			};

			// ----------------------------------------------------------------------------------------------------
			m_toolbuttonSelectAll.Clicked += delegate(object sender, EventArgs e) {
				m_treeviewSelectionLines.SelectAll();
			};

			// ----------------------------------------------------------------------------------------------------
			m_toolbuttonSelectNone.Clicked += delegate(object sender, EventArgs e) {
				m_treeviewSelectionLines.UnselectAll();
			};

			// ----------------------------------------------------------------------------------------------------
			m_toolbuttonInvert.Clicked += delegate(object sender, EventArgs e) {
				// get a all selected rows
				TreePath[] selectedTreePaths = m_treeviewSelectionLines.GetSelectedRows();
				bool[] wasLineSelected = new bool[m_liststoreLines.IterNChildren()];
				foreach(TreePath tp in selectedTreePaths)
					wasLineSelected[tp.Indices[0]] = true;

				// Gtk.TreeViews do not provide any easy mechanism to invert selection, so we just select
				// every non-selected row one by one
				m_ignoreLineSelectionChanges = true;
				m_treeviewSelectionLines.UnselectAll();
				for(int index = 0; index < wasLineSelected.Length; index++)
					if(!wasLineSelected[index])
						m_treeviewSelectionLines.SelectPath(new TreePath(new int[]{index}));
				m_ignoreLineSelectionChanges = false;

				SelectCard();
			};

			m_treeviewSelectionLines.Changed += delegate(object sender, EventArgs e) {
				var numLinesSelected = m_treeviewSelectionLines.CountSelectedRows();
				if(numLinesSelected < 2) m_labelNumCardsSelected.Text = numLinesSelected + " Card selected";
				else m_labelNumCardsSelected.Text = numLinesSelected + " Cards selected";
				SelectCard();
			};

			m_buttonReplaceInSub1.Clicked += delegate(object sender, EventArgs e) {
				PreviewWindowRegexReplace(true, false, m_previewWindow_isControlPressed, m_entryReplaceRegexFrom.Text, m_entryReplaceRegexTo.Text);
			};

			m_buttonReplaceInSub2.Clicked += delegate(object sender, EventArgs e) {
				PreviewWindowRegexReplace(false, true, m_previewWindow_isControlPressed, m_entryReplaceRegexFrom.Text, m_entryReplaceRegexTo.Text);
			};

			m_previewWindow.KeyPressEvent += delegate(object o, KeyPressEventArgs args) {
				if(args.Event.KeyValue == Gdk.Keyval.FromName("Shift_R") || args.Event.KeyValue == Gdk.Keyval.FromName("Shift_L"))
					m_previewWindow_isShiftPressed = true;
				if(args.Event.KeyValue == Gdk.Keyval.FromName("Control_R") || args.Event.KeyValue == Gdk.Keyval.FromName("Control_L"))
					m_previewWindow_isControlPressed = true;
				UpdatePreviewWidgetLabels();
			};

			m_previewWindow.KeyReleaseEvent += delegate(object o, KeyReleaseEventArgs args) {
				if(args.Event.KeyValue == Gdk.Keyval.FromName("Shift_R") || args.Event.KeyValue == Gdk.Keyval.FromName("Shift_L"))
					m_previewWindow_isShiftPressed = false;
				if(args.Event.KeyValue == Gdk.Keyval.FromName("Control_R") || args.Event.KeyValue == Gdk.Keyval.FromName("Control_L"))
					m_previewWindow_isControlPressed = false;
				UpdatePreviewWidgetLabels();
			};

			m_buttonSelectLinesBySearch.Clicked += delegate(object sender, EventArgs e) {
				PreviewWindowSelectLines(m_entryLinesSearch.Text, m_previewWindow_isShiftPressed, !m_previewWindow_isControlPressed);
			};

			m_entryLinesSearch.KeyReleaseEvent += delegate(object sender, KeyReleaseEventArgs e) {
				if(e.Event.KeyValue == Gdk.Keyval.FromName("Return")) {
					PreviewWindowSelectLines(m_entryLinesSearch.Text, m_previewWindow_isShiftPressed, !m_previewWindow_isControlPressed);
				}
			};

			m_buttonPlayContent.Clicked += delegate(object sender, EventArgs e) {
				if(m_selectedPreviewIndex < 0) return;

				CardInfo cardInfo = m_previewListModel.GetCardClone(m_selectedPreviewIndex);
				if(!cardInfo.HasAudio()) return;
				EpisodeInfo episodeInfo = cardInfo.episodeInfo;
				String arguments = String.Format("--really-quiet --no-video --start={0} --end={1} \"{2}\"",
						UtilsCommon.ToTimeArg(cardInfo.audioStartTimestamp),
						UtilsCommon.ToTimeArg(cardInfo.audioEndTimestamp),
						episodeInfo.VideoFileDesc.filename);
				// TODO: normalize audio for live audio play


				Thread thr = new Thread (new ThreadStart (delegate() {
					UtilsCommon.StartProcessAndGetOutput("mpv", arguments);
				}));
				thr.Start ();
			};

			m_toolbuttonToggleActivation.Clicked += delegate {
				// switch isActive field for every selected entry
				var updateItems = new List<int>();
				TreePath[] selectedTreePaths = m_treeviewSelectionLines.GetSelectedRows();
				foreach(TreePath treePath in selectedTreePaths) {
					updateItems.Add(treePath.Indices[0]);
				}

				// make internal changes visible to user
				var changeMode = PreviewListModel.BinaryChangeMode.Disable;
				if(m_previewWindow_isControlPressed) { changeMode = PreviewListModel.BinaryChangeMode.Enable; }
				else if(m_previewWindow_isShiftPressed) { changeMode = PreviewListModel.BinaryChangeMode.Toggle; }
				var changeList = m_previewListModel.UpdateCardActivation(updateItems, changeMode);
				UpdatePreviewListViewByChangeList(changeList);
			};

			m_toolbuttonGo.Clicked += delegate {
				new Thread(new ThreadStart(delegate {
					try {
						Console.WriteLine("Start computation");
						InfoProgress progressInfo = new InfoProgress(ProgressHandler);
						m_progressAndCancellable = progressInfo;
						Gtk.Application.Invoke(delegate { m_previewWindow.Hide(); m_windowProgressInfo.Show(); });
						m_previewListModel.ExportData(m_previewSettings, progressInfo);
						Gtk.Application.Invoke(delegate {  m_windowProgressInfo.Hide(); m_previewWindow.Show(); });
						Console.WriteLine("End computation");
					} catch(Exception e) {
						Console.WriteLine(e);
						SetErrorMessage(e.Message);
						Gtk.Application.Invoke(delegate {  m_windowProgressInfo.Hide(); m_previewWindow.Show(); });
					}
				})).Start();

			};


			Action<UtilsCommon.LanguageType> onBufferChange = delegate(UtilsCommon.LanguageType languageType) {
				if(m_ignoreBufferChanges) return;


				var textview = GetTextViewByLanguageType(languageType);
				var cardInfo = m_previewListModel.GetCardClone(m_selectedPreviewIndex);
				cardInfo.SetLineInfosByMultiLineString(languageType, textview.Buffer.Text);
				var changeList = m_previewListModel.SetCard(m_selectedPreviewIndex, cardInfo);
				UpdatePreviewListViewByChangeList(changeList, false);
			};

			// ----------------------------------------------------------------------
			// change entries when text in preview textviews is changed
			m_textviewTargetLanguage.Buffer.Changed += delegate(object sender, EventArgs e) {
				onBufferChange(UtilsCommon.LanguageType.TARGET);
			};

			// ----------------------------------------------------------------------
			// change entries when text in preview textviews is changed
			m_textviewNativeLanguage.Buffer.Changed += delegate(object sender, EventArgs e) {
				onBufferChange(UtilsCommon.LanguageType.NATIVE);
			};

			// ----------------------------------------------------------------------
			// "merge line with next" or "merge selected"
			m_toolbuttonMerge.Clicked += delegate(object sender, EventArgs e) {
				var changeList = m_previewListModel.MergeLines(GetSelectedRows(), m_previewWindow_isControlPressed ? PreviewListModel.MergeMode.Prev : PreviewListModel.MergeMode.Next);
				UpdatePreviewListViewByChangeList(changeList);
			};

			m_eventboxImagePreview.ButtonReleaseEvent += delegate(object o, ButtonReleaseEventArgs args) {
				var imageWnd = new Gtk.Window("SubtitleMemorize - Image preview");
				var image = new Gtk.Image();

				// do not select currently selected entry again
				if (!m_previewListModel.IsIndexInRange(m_selectedPreviewIndex))
					return;

				// get references to classes that describe the video file and stream
				CardInfo cardInfo = m_previewListModel.GetCardClone(m_selectedPreviewIndex);
				UtilsInputFiles.FileDesc videoFilename = cardInfo.episodeInfo.VideoFileDesc;
				StreamInfo videoStreamInfo = cardInfo.episodeInfo.VideoStreamInfo;

				// get right scaling
				double scaling = UtilsVideo.GetMaxScalingByStreamInfo(videoStreamInfo, m_previewSettings.RescaleWidth, m_previewSettings.RescaleHeight, m_previewSettings.RescaleMode);

				// extract big image from video
				UtilsImage.GetImage(videoFilename.filename, UtilsCommon.GetMiddleTime(cardInfo), InstanceSettings.temporaryFilesPath + "subtitleMemorize_real.jpg", scaling);

				image.Pixbuf = new Gdk.Pixbuf (InstanceSettings.temporaryFilesPath + "subtitleMemorize_real.jpg");
				imageWnd.Add(image);
				imageWnd.ShowAll();
			};
		}
Esempio n. 8
0
		/// <summary>
		/// Reads all subtitle files.
		/// </summary>
		/// <returns>Every entry in the outer list refers to exactly one subtitle file and for every file there is a list of all lines in it.</returns>
		/// <param name="settings">Settings.</param>
		/// <param name="attributedFilePaths">Attributed file path string.</param>
		private static List<List<LineInfo>> ReadAllSubtitleFiles (Settings settings, PerSubtitleSettings thisSubtitleSettings, List<EpisodeInfo> episodeInfos, int subtileIndex, InfoProgress progressInfo)
		{
			// read all lines in every subtitle file
			List<List<LineInfo>> lineInfosPerEpisode = new List<List<LineInfo>> ();
			foreach (EpisodeInfo episodeInfo in episodeInfos) {
				UtilsInputFiles.FileDesc fileDesc = episodeInfo.SubsFileDesc [subtileIndex];
				if (fileDesc == null || String.IsNullOrWhiteSpace (fileDesc.filename))
					lineInfosPerEpisode.Add (null);
				else
					lineInfosPerEpisode.Add (UtilsSubtitle.ParseSubtitleWithPostProcessing (settings, thisSubtitleSettings, fileDesc.filename, fileDesc.properties));
				progressInfo.ProcessedSteps (1);

				if (progressInfo.Cancelled)
					return null;
			}

			return lineInfosPerEpisode;
		}
Esempio n. 9
0
		/// <summary>
		/// This reads all subtitles, matches them and saves them to the "m_cardInfos"
		/// </summary>
		/// <param name="settings">Settings.</param>
		private static List<CardInfo> GenerateCardInfo(Settings settings, List<EpisodeInfo> episodeInfos, InfoProgress progressInfo) {

			// read subtitles
			List<List<LineInfo>> lineInfosPerEpisode_TargetLanguage = ReadAllSubtitleFiles(settings, settings.PerSubtitleSettings[0], episodeInfos, 0, progressInfo);
			List<List<LineInfo>> lineInfosPerEpisode_NativeLanguage = ReadAllSubtitleFiles(settings, settings.PerSubtitleSettings[1], episodeInfos, 1, progressInfo);

			if (progressInfo.Cancelled)
				return null;

			List<CardInfo> allCardInfos = new List<CardInfo> ();
			for(int episodeIndex = 0; episodeIndex < lineInfosPerEpisode_TargetLanguage.Count; episodeIndex++) {
				List<LineInfo> list1 = lineInfosPerEpisode_TargetLanguage[episodeIndex];
				List<LineInfo> list2 = lineInfosPerEpisode_NativeLanguage[episodeIndex];
				var episodeInfo = episodeInfos[episodeIndex];

				if(episodeInfo.HasSub2()) {
					// make sure that "other" subtitle has been shifted when aligning "this" subtitle to it
					if(settings.PerSubtitleSettings[0].AlignMode == PerSubtitleSettings.AlignModes.ToSubtitle) {
						UtilsCommon.AlignSub(list2, list1, episodeInfo, settings, settings.PerSubtitleSettings[1]);
						UtilsCommon.AlignSub(list1, list2, episodeInfo, settings, settings.PerSubtitleSettings[0]);
					} else {
						UtilsCommon.AlignSub(list1, list2, episodeInfo, settings, settings.PerSubtitleSettings[0]);
						UtilsCommon.AlignSub(list2, list1, episodeInfo, settings, settings.PerSubtitleSettings[1]);
					}
					var subtitleMatcherParameters = SubtitleMatcher.GetParameterCache (list1, list2);
					var matchedLinesList = SubtitleMatcher.MatchSubtitles(subtitleMatcherParameters);
					var thisEpisodeCardInfos = UtilsSubtitle.GetCardInfo(settings, episodeInfo, matchedLinesList);
					allCardInfos.AddRange(thisEpisodeCardInfos);
				} else {
					UtilsCommon.AlignSub(list1, list2, episodeInfo, settings, settings.PerSubtitleSettings[0]);
					allCardInfos.AddRange(UtilsSubtitle.GetCardInfo(settings, episodeInfo, list1));
				}

				progressInfo.ProcessedSteps (1);

				if (progressInfo.Cancelled)
					return null;
			}

			return allCardInfos;
		}
Esempio n. 10
0
		private void ComputationThread(Settings settings) {

			InfoProgress progressInfo = new InfoProgress(ProgressHandler);
			m_progressAndCancellable = progressInfo;

			// find sub1, sub2, audio and video file per episode
			var episodeInfo = new List<EpisodeInfo>();
			episodeInfo.AddRange(GenerateEpisodeInfos(settings));

			// fill in progress sections
			for(int i = 0; i < episodeInfo.Count; i++)
			progressInfo.AddSection(String.Format("Episode {0:00.}: Extracting Sub1", i + 1), 1);
			for(int i = 0; i < episodeInfo.Count; i++)
			progressInfo.AddSection(String.Format("Episode {0:00.}: Extracting Sub2", i + 1), 1);
			for(int i = 0; i < episodeInfo.Count; i++)
			progressInfo.AddSection(String.Format("Episode {0:00.}: Matching subtitles", i + 1), 1);

			progressInfo.AddSection("Preparing data presentation", 1);
			progressInfo.StartProgressing();


			// read all sub-files, match them and create a list for user that can be presented in preview window
			var cardInfos = new List<CardInfo>();
			cardInfos.AddRange(GenerateCardInfo(settings, episodeInfo, progressInfo) ?? new List<CardInfo>());

			m_previewListModel = new PreviewListModel(cardInfos);

			if(!progressInfo.Cancelled) {

				// finish this last step
				progressInfo.ProcessedSteps(1);

				PopulatePreviewList();
			}

			// close progress window, free pending operation variable
			CloseProgressWindow ();

		}
Esempio n. 11
0
        public static void ExtractSnaphots(Settings settings, String path, List <Tuple <CardInfo, String> > allEntries, InfoProgress progress)
        {
            foreach (var entry in allEntries)
            {
                if (progress.Cancelled)
                {
                    break;
                }
                progress.ProcessedSteps(1);

                var cardInfoNameTuple = entry;
                var cardInfo          = cardInfoNameTuple.Item1;
                if (!cardInfo.HasImage())
                {
                    continue;
                }

                // create file at given path
                String outputSnapshotFilename = cardInfoNameTuple.Item2;
                String outputSnapshotFilepath = path + Path.DirectorySeparatorChar + outputSnapshotFilename;

                // get file with snapshot information -> video
                UtilsInputFiles.FileDesc videoFileDesc = cardInfo.episodeInfo.VideoFileDesc;

                // extract image
                double scaling   = UtilsVideo.GetMaxScalingByStreamInfo(cardInfo.episodeInfo.VideoStreamInfo, settings.RescaleWidth, settings.RescaleHeight, settings.RescaleMode);
                double timeStamp = UtilsCommon.GetMiddleTime(cardInfo);
                UtilsImage.GetImage(videoFileDesc.filename, timeStamp, outputSnapshotFilepath, scaling);
            }
        }
Esempio n. 12
0
        public static void ExtractAudio(Settings settings, String path, List <Tuple <CardInfo, String> > allEntries, InfoProgress progress)
        {
            foreach (var entry in allEntries)
            {
                progress.ProcessedSteps(1);
                if (progress.Cancelled)
                {
                    return;
                }

                CardInfo cardInfo = entry.Item1;
                if (!cardInfo.HasAudio())
                {
                    continue;
                }

                String outputAudioFilename = entry.Item2;
                String outputAudioFilepath = path + Path.DirectorySeparatorChar + outputAudioFilename;

                UtilsInputFiles.FileDesc audioFileDesc = cardInfo.episodeInfo.AudioFileDesc;
                var audioStreamInfo = cardInfo.episodeInfo.AudioStreamInfo;

                String arguments = String.Format("-v quiet -y -i \"{0}\" -map 0:{1} -ss \"{2}\" -to \"{3}\" -vn -c:a libvorbis \"{4}\"",
                                                 audioFileDesc.filename,                              // input file
                                                 audioStreamInfo.StreamIndex,                         // audio stream index
                                                 UtilsCommon.ToTimeArg(cardInfo.audioStartTimestamp), // start time
                                                 UtilsCommon.ToTimeArg(cardInfo.audioEndTimestamp),   // end time
                                                 outputAudioFilepath                                  // output file
                                                 );
                UtilsCommon.StartProcessAndGetOutput(InstanceSettings.systemSettings.formatConvertCommand, arguments);
            }
        }