public static bool CheckIndexAndForceFilm(string indexfile, string inframerate) { int FilmPercent = 0; int size_w = 0, size_h = 0; int fps_n = 0, fps_d = 0; string line; #region /* * FPS 25000 / 1000 * CODED 30791 * PLAYBACK 30791 * 0.00% FILM * ORDER 1 * ------------- * SIZ 720 x 480 * FPS 30000 / 1001 * CODED 679 * PLAYBACK 849 * 100.00% FILM * ORDER 1 * ------------- * Файл не проиндексировался: * SIZ 0 x 0 * FPS 0 / 0 * CODED 0 * PLAYBACK 0 * 0.00% FILM * ORDER -1 */ #endregion //Проверка индекса и получение процента для ForceFilm Match mat; //100.00% FILM Regex film = new Regex(@"^(\d+\.*\d*)%\sFILM", RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); Regex size = new Regex(@"^SIZ\s(\d+)\sx\s(\d+)", RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); Regex fps = new Regex(@"^FPS\s(\d+)\s/\s(\d+)", RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); using (StreamReader sr = new StreamReader(indexfile, Encoding.Default)) while (!sr.EndOfStream) { line = sr.ReadLine(); mat = film.Match(line); if (mat.Success) { FilmPercent = Convert.ToInt32(Calculate.ConvertStringToDouble(mat.Groups[1].Value)); continue; } mat = size.Match(line); if (mat.Success) { size_w = Convert.ToInt32(mat.Groups[1].Value); size_h = Convert.ToInt32(mat.Groups[2].Value); continue; } mat = fps.Match(line); if (mat.Success) { fps_n = Convert.ToInt32(mat.Groups[1].Value); fps_d = Convert.ToInt32(mat.Groups[2].Value); continue; } } //Кривой индекс (произошла ошибка) if (size_w == 0 || size_h == 0 || fps_n == 0 || fps_d == 0) { throw new Exception(Languages.Translate("Broken or incomplete index file detected!") + "\r\n" + Languages.Translate("Unsupported by DGDIndexNV container or codec - one of the reasons for this.")); } if (!Settings.DGForceFilm || FilmPercent < Settings.DGFilmPercent) { return(false); } if (!string.IsNullOrEmpty(inframerate) && (inframerate == "23.976" || inframerate == "29.970")) { return(true); } return(false); }
private void combo_profile_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { if ((combo_profile.IsDropDownOpen || combo_profile.IsSelectionBoxHighlighted) && combo_profile.SelectedItem != null) { RefreshCodecProfileWindow(); //определяем аудио потоки AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream]; //правим выходной битрейт if (outstream.codec == "Copy") { outstream.bitrate = instream.bitrate; } if (outstream.codec == "Disabled") { outstream.bitrate = 0; } UpdateOutSize(); //проверяем можно ли копировать данный формат if (outstream.codec == "Copy") { string CopyProblems = Format.ValidateCopyAudio(m); if (CopyProblems != null) { new Message(this).ShowMessage(Languages.Translate("The stream contains parameters incompatible with this format") + " " + Format.EnumToString(m.format) + ": " + CopyProblems + "." + Environment.NewLine + Languages.Translate("(You see this message because audio encoder = Copy)"), Languages.Translate("Warning")); } } } }
private void combo_atracks_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (combo_atracks.IsDropDownOpen || combo_atracks.IsSelectionBoxHighlighted) { m.inaudiostream = combo_atracks.SelectedIndex; //передаём активный трек на выход AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; //Требуется извлечение звука if (instream.audiopath == null && instream.decoder == 0 && m.inaudiostream > 0) { //FFMS2 и LSMASH умеют переключать треки, для них их можно не извлекать if (!(m.vdecoder == AviSynthScripting.Decoders.FFmpegSource2 && Settings.FFMS_Enable_Audio || ((m.vdecoder == AviSynthScripting.Decoders.LSMASHVideoSource || m.vdecoder == AviSynthScripting.Decoders.LWLibavVideoSource) && Settings.LSMASH_Enable_Audio))) { string outext = Format.GetValidRAWAudioEXT(instream.codecshort); instream.audiopath = Settings.TempPath + "\\" + m.key + "_" + m.inaudiostream + outext; instream.audiofiles = new string[] { instream.audiopath }; instream = Format.GetValidADecoder(instream); } } textbox_apath.Text = instream.audiopath; //перезабиваем поток на выход AudioStream stream = new AudioStream(); m.outaudiostreams.Clear(); if (Settings.ApplyDelay) { stream.delay = instream.delay; } m.outaudiostreams.Add(stream); AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream]; //забиваем аудио настройки outstream.encoding = Settings.GetAEncodingPreset(Settings.FormatOut); outstream.codec = PresetLoader.GetACodec(m.format, outstream.encoding); outstream.passes = PresetLoader.GetACodecPasses(m); m = Format.GetValidSamplerate(m); //определяем битность m = Format.GetValidBits(m); //определяем колличество каналов m = Format.GetValidChannelsConverter(m); m = Format.GetValidChannels(m); //проверяем можно ли копировать данный формат if (outstream.codec == "Copy") { //AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; outstream.audiopath = instream.audiopath; outstream.bitrate = instream.bitrate; string CopyProblems = Format.ValidateCopyAudio(m); if (CopyProblems != null) { Message mess = new Message(this); mess.ShowMessage(Languages.Translate("The stream contains parameters incompatible with this format") + " " + Format.EnumToString(m.format) + ": " + CopyProblems + "." + Environment.NewLine + Languages.Translate("(You see this message because audio encoder = Copy)"), Languages.Translate("Warning")); } } else { string aext = Format.GetValidRAWAudioEXT(outstream.codec); outstream.audiopath = Settings.TempPath + "\\" + m.key + aext; } SetAudioOptions(); SetInfo(); } }
public void Reload(Massive mass) { m = mass.Clone(); oldm = mass.Clone(); ////забиваем необходимые декодеры //if (m.vdecoder == 0) // m = Format.GetValidVDecoder(m); //if (instream.decoder == 0) // instream = Format.GetValidADecoder(instream); //перевод group_audio.Header = Languages.Translate("Source"); label_apath.Content = Languages.Translate("Path") + ":"; label_atrack.Content = Languages.Translate("Track") + ":"; this.Title = Languages.Translate("Editing audio options") + ":"; button_cancel.Content = Languages.Translate("Cancel"); button_ok.Content = Languages.Translate("OK"); button_apply.Content = Languages.Translate("Apply"); group_delay.Header = Languages.Translate("Delay"); group_info.Header = Languages.Translate("Info"); group_samplerate.Header = Languages.Translate("Samplerate"); group_volume.Header = Languages.Translate("Volume"); group_channels.Header = Languages.Translate("Channels"); label_delayout.Content = Languages.Translate("Output") + ":"; label_outsamplerate.Content = Languages.Translate("Output") + ":"; label_converter.Content = Languages.Translate("Converter") + ":"; label_accurate.Content = Languages.Translate("Analyse") + ":"; //label_mixing.Content = Languages.Translate("Mixing") + ":"; //путь к звуковой дорожке combo_atracks.Items.Clear(); if (m.inaudiostreams.Count > 0) { //забиваем в список каналы звука int n = 1; foreach (AudioStream stream in m.inaudiostreams) { ComboBoxItem item = new ComboBoxItem(); item.Content = n.ToString("00") + ". " + stream.language + " " + stream.codecshort + " " + stream.channels + "ch"; item.ToolTip = item.Content + " " + stream.samplerate + "Hz " + stream.bitrate + "kbps " + stream.delay + "ms"; combo_atracks.Items.Add(item); n++; } combo_atracks.SelectedIndex = m.inaudiostream; //определяем аудио потоки AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; if (instream.audiopath == null && instream.badmixing) { string outext = Format.GetValidRAWAudioEXT(instream.codecshort); instream.audiopath = Settings.TempPath + "\\" + m.key + "_" + m.inaudiostream + outext; instream.audiofiles = new string[] { instream.audiopath }; instream = Format.GetValidADecoder(instream); } if (instream.audiopath != null) { textbox_apath.Text = instream.audiopath; } } check_apply_delay.IsChecked = Settings.ApplyDelay; //только для all режима if (mode == AudioOptionsModes.AllOptions) { //прописываем samplerate combo_samplerate.Items.Clear(); foreach (string f in Format.GetValidSampleratesList(m)) { combo_samplerate.Items.Add(f); } combo_converter.Items.Clear(); foreach (AviSynthScripting.SamplerateModifers ratechangers in Enum.GetValues(typeof(AviSynthScripting.SamplerateModifers))) { combo_converter.Items.Add(new ComboBoxItem() { Content = ratechangers }); } //прописываем громкость combo_volume.Items.Clear(); combo_volume.Items.Add("Disabled"); for (int y = 30; y < 401; y += 10) { combo_volume.Items.Add(y + "%"); } //прописываем аккуратность определения громкости combo_accurate.Items.Clear(); for (int y = 1; y <= 9; y++) { combo_accurate.Items.Add(y + "%"); } for (int y = 10; y <= 100; y += 10) { combo_accurate.Items.Add(y + "%"); } //прогружаем работу с каналами combo_mixing.Items.Clear(); foreach (string channelschanger in Enum.GetNames(typeof(ChannelConverters))) { combo_mixing.Items.Add(EnumMixingToString((ChannelConverters)Enum.Parse(typeof(ChannelConverters), channelschanger))); } if (m.outaudiostreams.Count > 0) { if (((AudioStream)m.outaudiostreams[m.outaudiostream]).codec == "Copy") { group_delay.IsEnabled = Settings.CopyDelay; group_channels.IsEnabled = group_samplerate.IsEnabled = group_volume.IsEnabled = false; } else { group_delay.IsEnabled = group_channels.IsEnabled = group_samplerate.IsEnabled = group_volume.IsEnabled = true; } } else { group_delay.IsEnabled = group_channels.IsEnabled = group_samplerate.IsEnabled = group_volume.IsEnabled = false; } } //закончился режим all else { //режим только для выбора треков this.Title = Languages.Translate("Select audio track") + ":"; group_channels.Visibility = Visibility.Hidden; group_info.Visibility = Visibility.Hidden; group_samplerate.Visibility = Visibility.Hidden; group_volume.Visibility = Visibility.Hidden; group_audio.Margin = new Thickness(8, 8, 8, 0); group_delay.Margin = new Thickness(8, 100, 8, 0); button_apply.Visibility = Visibility.Hidden; button_cancel.Visibility = Visibility.Hidden; button_ok.Margin = new Thickness(0, 5, 8, 5); this.Width = 500; this.Height = 240; } //прописываем в форму текущие настройки if (m.inaudiostreams.Count > 0 && m.outaudiostreams.Count > 0) { SetAudioOptions(); } //прописываем информацию SetInfo(); //прописываем тултипы SetTooltips(); }
private void combo_codec_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { if ((combo_codec.IsDropDownOpen || combo_codec.IsSelectionBoxHighlighted) && combo_codec.SelectedItem != null) { UnLoadCodecWindow(); m.x265options = new x265_arguments(); m.x264options = new x264_arguments(); m.x262options = new x262_arguments(); m.XviD_options = new XviD_arguments(); m.ffmpeg_options = new ffmpeg_arguments(); m.outvcodec = combo_codec.SelectedItem.ToString(); m = Format.GetValidVEncodingMode(m); LoadCodecWindow(); if (m.outvcodec == "Copy") { combo_profile.SelectedItem = m.outvcodec; m.vencoding = m.outvcodec; } else { UpdateManualProfile(); } //проверяем можно ли копировать данный формат if (m.outvcodec == "Copy") { string CopyProblems = Format.ValidateCopyVideo(m); if (CopyProblems != null) { new Message(this).ShowMessage(Languages.Translate("The stream contains parameters incompatible with this format") + " " + Format.EnumToString(m.format) + ": " + CopyProblems + "." + Environment.NewLine + Languages.Translate("(You see this message because video encoder = Copy)"), Languages.Translate("Warning")); } } //правим выходной битрейт if (m.outvcodec == "Copy") { m.outvbitrate = m.invbitrate; } UpdateOutSize(); if (x265c != null) { x265c.UpdateCLI(); } if (x264c != null) { x264c.UpdateCLI(); } if (x262c != null) { x262c.UpdateCLI(); } if (xvid != null) { xvid.UpdateCLI(); } if (mpeg4 != null) { mpeg4.UpdateCLI(); } if (mpeg2 != null) { mpeg2.UpdateCLI(); } if (mpeg1 != null) { mpeg1.UpdateCLI(); } if (flv != null) { flv.UpdateCLI(); } } }
private void button_add_Click(object sender, System.Windows.RoutedEventArgs e) { if (m.outvcodec == "Copy") { return; } if (x265c == null && x264c == null && x262c == null && xvid == null && mpeg4 == null && mpeg2 == null && mpeg1 == null && flv == null) { UpdateMassive(); //CustomCLI } string auto_name = m.outvcodec + " "; if (m.outvcodec == "HUFF" || m.outvcodec == "FFV1") { auto_name += "LossLess"; } else if (m.outvcodec == "DV") { auto_name += "Custom"; } else { if (m.outvbitrate == 0 || m.outvcodec == "x265" && m.x265options.lossless) { auto_name += "LL"; } else { if (m.encodingmode == Settings.EncodingModes.Quality || m.encodingmode == Settings.EncodingModes.Quantizer || m.encodingmode == Settings.EncodingModes.TwoPassQuality || m.encodingmode == Settings.EncodingModes.ThreePassQuality) { auto_name += "Q" + m.outvbitrate; } else if (m.encodingmode == Settings.EncodingModes.OnePass || m.encodingmode == Settings.EncodingModes.TwoPass || m.encodingmode == Settings.EncodingModes.ThreePass) { auto_name += m.outvbitrate + "k"; } else { auto_name += m.outvbitrate + "MB"; } } if (m.outvcodec != "MJPEG") { if (m.encodingmode == Settings.EncodingModes.TwoPass || m.encodingmode == Settings.EncodingModes.TwoPassSize || m.encodingmode == Settings.EncodingModes.TwoPassQuality) { auto_name += " 2P"; } else if (m.encodingmode == Settings.EncodingModes.ThreePass || m.encodingmode == Settings.EncodingModes.ThreePassSize || m.encodingmode == Settings.EncodingModes.ThreePassQuality) { auto_name = " 3P"; } } auto_name += " Custom"; } NewProfile newp = new NewProfile(auto_name, Format.EnumToString(m.format), NewProfile.ProfileType.VEncoding, this); if (newp.profile != null) { string old_encoding = m.vencoding; m.vencoding = newp.profile; //Название для нового пресета try { PresetLoader.CreateVProfile(m); //Пресет записывается в файл LoadProfiles(); //Обновляется содержимое комбобокса с пресетами, выбирается текущий пресет } catch (Exception ex) { new Message(this).ShowMessage(Languages.Translate("Can`t save profile") + ": " + ex.Message, Languages.Translate("Error"), Message.MessageStyle.Ok); m.vencoding = old_encoding; } } //Не совсем понятно, зачем нужно перезагружаться с пресета, который мы только что сохранили.. if (x265c == null && x264c == null && x262c == null && xvid == null && mpeg4 == null && mpeg2 == null && mpeg1 == null && flv == null) //CustomCLI { LoadProfileToCodec(); UpdateOutSize(); UpdateCodecMassive(); } }
private void demux_pmp() { //if (m.infileslist.Length > 1) // ShowMessage(Languages.Translate("Sorry, but stream will be extracted only from first file! :("), // Languages.Translate("Warning")); encoderProcess = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = Calculate.StartupPath + "\\apps\\pmp_muxer_avc\\pmp_demuxer.exe"; info.WorkingDirectory = Path.GetDirectoryName(info.FileName); info.UseShellExecute = false; info.RedirectStandardOutput = true; info.RedirectStandardError = false; info.CreateNoWindow = true; info.Arguments = "\"" + source_file + "\""; string vfile = source_file + ".avi"; string afile = source_file + ".1.aac"; //удаляем старый файл SafeDelete(outfile); encoderProcess.StartInfo = info; encoderProcess.Start(); string line; string pat = @"(\d+)\D/\D(\d+)"; Regex r = new Regex(pat, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); Match mat; //первый проход while (!encoderProcess.HasExited) { line = encoderProcess.StandardOutput.ReadLine(); if (line != null) { mat = r.Match(line); if (mat.Success) { int frame = Convert.ToInt32(mat.Groups[1].Value); worker.ReportProgress((int)(((double)(frame) / (double)m.inframes) * 100.0)); } else { AppendEncoderText(line); } } } //чистим ресурсы encoderProcess.Close(); encoderProcess.Dispose(); encoderProcess = null; if (IsAborted || IsErrors) { return; } if (mode == DemuxerMode.ExtractVideo) { //проверка на удачное завершение if (!File.Exists(vfile) || new FileInfo(vfile).Length == 0) { throw new Exception(Languages.Translate("Can`t find output video file!")); } SafeDelete(afile); //вытягиваем RAW h264 из AVI string old_infilepath = source_file; source_file = vfile; demux_ffmpeg(); SafeDelete(vfile); source_file = old_infilepath; } if (mode == DemuxerMode.ExtractAudio) { //проверка на удачное завершение if (!File.Exists(afile) || new FileInfo(afile).Length == 0) { throw new Exception(Languages.Translate("Can`t find output audio file!")); } SafeDelete(vfile); File.Move(afile, outfile); } //перемещаем файл в правильное место encodertext.Length = 0; SafeDelete(source_file + ".log"); }
private void button_add_Click(object sender, System.Windows.RoutedEventArgs e) { AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream]; if (outstream.codec == "Copy" || outstream.codec == "Disabled") { return; } UpdateMassive(); string auto_name = outstream.codec; if (outstream.codec == "AAC") { if (m.aac_options.aacprofile == "AAC-LC") { auto_name += "-LC"; } else if (m.aac_options.aacprofile == "AAC-HE") { auto_name += "-HE"; } else if (m.aac_options.aacprofile == "AAC-HEv2") { auto_name += "-HEv2"; } auto_name += " " + m.aac_options.encodingmode.ToString(); if (m.aac_options.encodingmode == Settings.AudioEncodingModes.VBR) { auto_name += " Q" + m.aac_options.quality; } else { auto_name += " " + outstream.bitrate + "k"; } } else if (outstream.codec == "QAAC") { if (m.qaac_options.encodingmode != Settings.AudioEncodingModes.ALAC) { if (m.qaac_options.aacprofile == "AAC-LC") { auto_name += "-LC"; } else if (m.qaac_options.aacprofile == "AAC-HE") { auto_name += "-HE"; } auto_name += " " + m.qaac_options.encodingmode.ToString(); if (m.qaac_options.encodingmode == Settings.AudioEncodingModes.VBR) { auto_name += " Q" + m.qaac_options.quality; } else { auto_name += " " + outstream.bitrate + "k"; } } else { auto_name += " " + m.qaac_options.encodingmode.ToString(); } } else if (outstream.codec == "MP3") { auto_name += " " + m.mp3_options.encodingmode.ToString().ToUpper(); if (m.mp3_options.encodingmode == Settings.AudioEncodingModes.VBR) { auto_name += " Q" + m.mp3_options.quality; } else { auto_name += " " + outstream.bitrate + "k"; } } else if (outstream.codec == "PCM" || outstream.codec == "LPCM") { auto_name += " " + outstream.bits + "bit"; } else if (outstream.codec == "AC3" || outstream.codec == "MP2") { auto_name += " " + outstream.bitrate + "k"; } else if (outstream.codec == "FLAC") { auto_name += " Q" + m.flac_options.level; } auto_name += " Custom"; NewProfile newp = new NewProfile(auto_name, Format.EnumToString(m.format), NewProfile.ProfileType.AEncoding, this); if (newp.profile != null) { string old_encoding = outstream.encoding; outstream.encoding = newp.profile; try { PresetLoader.CreateAProfile(m); LoadProfiles(); } catch (Exception ex) { new Message(this).ShowMessage(Languages.Translate("Can`t save profile") + ": " + ex.Message, Languages.Translate("Error"), Message.MessageStyle.Ok); outstream.encoding = old_encoding; } } LoadProfileToCodec(); UpdateOutSize(); UpdateCodecMassive(); }
private void demux_ffmpeg() { if (m.infileslist.Length > 1) { ShowMessage(Languages.Translate("Sorry, but stream will be extracted only from first file! :("), Languages.Translate("Warning")); } //удаляем старый файл SafeDelete(outfile); encoderProcess = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = Calculate.StartupPath + "\\apps\\ffmpeg\\ffmpeg.exe"; info.WorkingDirectory = Path.GetDirectoryName(info.FileName); info.UseShellExecute = false; info.RedirectStandardOutput = false; info.RedirectStandardError = true; info.StandardErrorEncoding = Encoding.UTF8; info.CreateNoWindow = true; encodertext.Length = 0; if (mode == DemuxerMode.ExtractAudio) { AudioStream s = (AudioStream)m.inaudiostreams[m.inaudiostream]; string acodec = "copy", forceformat = ""; string outext = Path.GetExtension(outfile).ToLower(); if (outext == ".lpcm" || s.codec == "LPCM") { forceformat = " -f s16be"; } else if (outext == ".wav") { acodec = "pcm_s16le"; forceformat = " -f wav"; } else if (outext == ".truehd") { forceformat = " -f truehd"; } info.Arguments = "-hide_banner -nostdin -i \"" + source_file + "\" -map 0:" + s.ff_order + " -sn -vn -acodec " + acodec + forceformat + " \"" + outfile + "\""; } else if (mode == DemuxerMode.ExtractVideo) { string forceformat = ""; //string outext = Path.GetExtension(outfile); //if (outext == ".m2v") // forceformat = " -f vob"; info.Arguments = "-hide_banner -nostdin -i \"" + source_file + "\" -map 0:v:0 -sn -an -vcodec copy" + forceformat + " \"" + outfile + "\""; } double percentage_k = m.induration.TotalSeconds / 100.0; TimeSpan current_sec = TimeSpan.Zero; encoderProcess.StartInfo = info; encoderProcess.Start(); string line; string pat = @"time=(\d+:\d+:\d+\.?\d*)"; Regex r = new Regex(pat, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); Match mat; //первый проход while (!encoderProcess.HasExited) { line = encoderProcess.StandardError.ReadLine(); if (line != null) { mat = r.Match(line); if (mat.Success && TimeSpan.TryParse(mat.Groups[1].Value, out current_sec)) { worker.ReportProgress((int)(current_sec.TotalSeconds / percentage_k)); } else { AppendEncoderText(line); } } } //Дочитываем остатки лога, если что-то не успело считаться line = encoderProcess.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(line)) { AppendEncoderText(Calculate.FilterLogMessage(r, line)); } //чистим ресурсы exit_code = encoderProcess.ExitCode; encoderProcess.Close(); encoderProcess.Dispose(); encoderProcess = null; if (IsAborted) { return; } //проверка на удачное завершение if (exit_code != 0 && encodertext.Length > 0) { //Оставляем только последнюю строчку из всего лога string[] log = encodertext.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); throw new Exception(log[log.Length - 1]); } if (!File.Exists(outfile) || new FileInfo(outfile).Length == 0) { if (mode == DemuxerMode.ExtractVideo) { throw new Exception(Languages.Translate("Can`t find output video file!")); } if (mode == DemuxerMode.ExtractAudio) { throw new Exception(Languages.Translate("Can`t find output audio file!")); } } encodertext.Length = 0; }
private void demux_mp4box() { //if (m.infileslist.Length > 1) // ShowMessage(Languages.Translate("Sorry, but stream will be extracted only from first file! :("), // Languages.Translate("Warning")); encoderProcess = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = Calculate.StartupPath + "\\apps\\MP4Box\\MP4Box.exe"; info.WorkingDirectory = Path.GetDirectoryName(info.FileName); info.UseShellExecute = false; info.RedirectStandardOutput = false; info.RedirectStandardError = true; info.CreateNoWindow = true; encodertext.Length = 0; //удаляем старый файл SafeDelete(outfile); if (mode == Demuxer.DemuxerMode.ExtractVideo) { info.Arguments = "-raw " + m.invideostream_mi_id + " \"" + source_file + "\" -out \"" + outfile + "\""; } if (mode == Demuxer.DemuxerMode.ExtractAudio) { //определяем аудио потоки AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; info.Arguments = "-raw " + instream.mi_id + " \"" + source_file + "\" -out \"" + outfile + "\""; } encoderProcess.StartInfo = info; encoderProcess.Start(); string line; string pat = @"(\d+)/(\d+)"; Regex r = new Regex(pat, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); Match mat; //первый проход while (!encoderProcess.HasExited) { line = encoderProcess.StandardError.ReadLine(); if (line != null) { mat = r.Match(line); if (mat.Success) { worker.ReportProgress(Convert.ToInt32(mat.Groups[1].Value)); } else { AppendEncoderText(line); } } } //Дочитываем остатки лога, если что-то не успело считаться line = encoderProcess.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(line)) { AppendEncoderText(Calculate.FilterLogMessage(r, line)); } //чистим ресурсы exit_code = encoderProcess.ExitCode; encoderProcess.Close(); encoderProcess.Dispose(); encoderProcess = null; if (IsAborted) { return; } //проверка на удачное завершение if (exit_code != 0) { throw new Exception(encodertext.ToString()); } if (!File.Exists(outfile) || new FileInfo(outfile).Length == 0) { if (mode == DemuxerMode.ExtractVideo) { throw new Exception(Languages.Translate("Can`t find output video file!")); } if (mode == DemuxerMode.ExtractAudio) { throw new Exception(Languages.Translate("Can`t find output audio file!")); } } encodertext.Length = 0; }
private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { try //Индексация { indexfile = m.indexfile; //создаём папку if (!Directory.Exists(Path.GetDirectoryName(m.indexfile))) { Directory.CreateDirectory(Path.GetDirectoryName(m.indexfile)); } encoderProcess = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = Calculate.StartupPath + "\\apps\\DGMPGDec\\DGIndex.exe"; info.WorkingDirectory = Path.GetDirectoryName(info.FileName); //создаём список файлов string files_list = ""; foreach (string _line in m.infileslist) { files_list += _line + "\r\n"; } File.WriteAllText((filelistpath = Settings.TempPath + "\\" + m.key + ".lst"), files_list, Encoding.Default); //Выходим при отмене if (worker.CancellationPending) { return; } //Извлекаем звук, только если он нам нужен string ademux = (Settings.EnableAudio) ? "-OM=2" : "-OM=0"; info.Arguments = "-SD=\" -FO=0 " + ademux + " -BF=\"" + filelistpath + "\" -OF=\"" + Calculate.RemoveExtention(m.indexfile, true) + "\" -HIDE -EXIT"; encoderProcess.StartInfo = info; encoderProcess.Start(); encoderProcess.PriorityClass = ProcessPriorityClass.Normal; encoderProcess.PriorityBoostEnabled = true; for (int i = 0; iHandle == 0 && i < 20; i++) { iHandle = Win32.GetWindowHandle("DGIndex["); Thread.Sleep(100); } if (iHandle != 0) { Match mat; StringBuilder st = new StringBuilder(256); Regex r = new Regex(@"(\d+)%", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); while (!encoderProcess.HasExited) { if (Win32.GetWindowText(iHandle, st, 256) > 0) { mat = r.Match(st.ToString()); if (mat.Success) { worker.ReportProgress(Convert.ToInt32(mat.Groups[1].Value)); } } Thread.Sleep(100); } } encoderProcess.WaitForExit(); //Индекс-файл не найден if (!worker.CancellationPending && !File.Exists(m.indexfile)) { throw new Exception(Languages.Translate("Can`t find file") + ": " + m.indexfile); } } catch (Exception ex) { if (worker != null && !worker.CancellationPending && m != null && num_closes == 0) { //Ошибка e.Result = ex; } m = null; return; } try { //Auto ForceFilm (только для 23.976, 29.970, и если частота неизвестна) if (worker.CancellationPending || !Settings.DGForceFilm || !string.IsNullOrEmpty(m.inframerate) && m.inframerate != "23.976" && m.inframerate != "29.970") { return; } } catch (Exception) { //worker или m == null return; } try //Теперь ForceFilm { FilmPercent = 0; //Получение процента для ForceFilm Match mat; //FINISHED 94.57% FILM Regex r = new Regex(@"^FINISHED\s+(\d+\.*\d*)%.FILM", RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); using (StreamReader sr = new StreamReader(m.indexfile, Encoding.Default)) while (!sr.EndOfStream) { mat = r.Match(sr.ReadLine()); if (mat.Success) { FilmPercent = Convert.ToInt32(Calculate.ConvertStringToDouble(mat.Groups[1].Value)); } } //Выход при отмене, или если процент Film недостаточен if (worker.CancellationPending || FilmPercent < Settings.DGFilmPercent) { return; } //Перезапись d2v-файла string file = "", line = ""; using (StreamReader sr = new StreamReader(m.indexfile, Encoding.Default)) while (!sr.EndOfStream) { line = sr.ReadLine(); if (line.StartsWith("Field_Operation")) { file += "Field_Operation=1\r\n"; } else if (line.StartsWith("Frame_Rate")) { file += "Frame_Rate=23976 (24000/1001)\r\n"; } else { file += line + Environment.NewLine; } } using (StreamWriter sw = new StreamWriter(m.indexfile, false, Encoding.Default)) sw.Write(file); m.IsForcedFilm = true; } catch (Exception ex) { if (worker != null && !worker.CancellationPending && m != null && num_closes == 0) { //Ошибка e.Result = ex; } m = null; } }
public VisualCrop(Massive mass, Window owner) { m = mass.Clone(); oldm = mass.Clone(); this.InitializeComponent(); this.Owner = owner; //Создаем скрипт (т.к. текущий с кропом и ресайзом не годится) script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.VCrop); numl.Value = left = m.cropl; numr.Value = right = m.cropr; numt.Value = top = m.cropt; numb.Value = bottom = m.cropb; Color color = Settings.VCropBrush; slider_R.Value = R = color.R; slider_G.Value = G = color.G; slider_B.Value = B = color.B; slider_A.Value = A = color.A; FinalColor.Color = Color.FromArgb(255, R, G, B); numl.ToolTip = Languages.Translate("Left"); numt.ToolTip = Languages.Translate("Top"); numr.ToolTip = Languages.Translate("Right"); numb.ToolTip = Languages.Translate("Bottom"); button_autocrop.Content = Languages.Translate("Analyse"); button_autocrop.ToolTip = Languages.Translate("Autocrop black borders"); button_autocrop_current.ToolTip = Languages.Translate("Autocrop on current frame"); button_uncrop.ToolTip = Languages.Translate("Remove crop"); button_settings.ToolTip = Languages.Translate("Settings"); slider_A.ToolTip = Languages.Translate("Transparency of the mask"); slider_R.ToolTip = slider_G.ToolTip = slider_B.ToolTip = Languages.Translate("Brightness of the mask"); button_fullscreen.ToolTip = Languages.Translate("Fullscreen mode"); button_cancel.Content = Languages.Translate("Cancel"); frame_of = Languages.Translate("Frame XX of YY").ToLower(); cropped_s = Languages.Translate("cropped size"); try { reader = new AviSynthReader(AviSynthColorspace.RGB24, AudioSampleType.Undefined); reader.ParseScript(script); if (reader.Clip.HasVideo && reader.FrameCount > 0) { slider_pos.Maximum = reader.FrameCount; slider_pos.Value = (Settings.VCropFrame == "THM-frame") ? m.thmframe : 0; numl.Maximum = numr.Maximum = width = reader.Width; numt.Maximum = numb.Maximum = height = reader.Height; fps = reader.Framerate; stride = width * bpp; buffer = Marshal.AllocHGlobal(stride * height); HasVideo = true; SetFrame((int)slider_pos.Value); ShowCroppedFrame(); } else { PreviewError("NO VIDEO", Brushes.Gainsboro); } } catch (Exception ex) { SetPreviewError(ex); } if (IsError) { CloseReader(); Close(); } else { WindowLoaded = true; ShowDialog(); } }
private void ErrorException(string message, string info) { new Message((this.IsLoaded) ? this : Owner).ShowMessage(message, info, Languages.Translate("Error")); }
public AudioEncoding(Massive mass, MainWindow parent) { this.InitializeComponent(); if (mass != null) { this.m = mass.Clone(); this.oldm = mass.Clone(); } else { //Заполняем массив m = new Massive(); m.format = Settings.FormatOut; m.infilepath = "C:\\file.mkv"; //Добавляем звук m.inaudiostreams.Add(new AudioStream()); m.outaudiostreams.Add(new AudioStream()); m.inaudiostream = m.outaudiostream = 0; //Убираем лишнее, т.к. всё-равно показывать там нечего text_insize_value.Visibility = text_outsize_value.Visibility = Visibility.Collapsed; text_codec.Margin = text_incodec_value.Margin = combo_codec.Margin = new Thickness(16, 8, 16, 8); row2.Height = new GridLength(0); } this.Owner = parent; //определяем аудио потоки AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream]; if (oldm == null) { //Заполняем параметры треков outstream.encoding = old_aencoding = Settings.GetAEncodingPreset(m.format); outstream.codec = PresetLoader.GetACodec(m.format, outstream.encoding); outstream.passes = PresetLoader.GetACodecPasses(m); instream.audiopath = "C:\\file.mp3"; instream.codecshort = "NOINPUT"; instream.bitrate = 128; instream.bits = outstream.bits = 16; instream.channels = outstream.channels = 2; instream.samplerate = outstream.samplerate = "44100"; m = PresetLoader.DecodePresets(m); } //загружаем список кодеков соответвующий формату foreach (string codec in Format.GetACodecsList(m.format)) { combo_codec.Items.Add(codec); } if (oldm != null) { combo_codec.Items.Add("Disabled"); } combo_codec.Items.Add("Copy"); if (!combo_codec.Items.Contains(outstream.codec)) { combo_codec.Items.Add(outstream.codec); } combo_codec.SelectedItem = outstream.codec; text_incodec_value.Content = instream.codecshort; text_insize_value.Content = m.infilesize; text_outsize_value.Content = m.outfilesize = Calculate.GetEncodingSize(m); //загружаем правильную страницу LoadCodecWindow(); //переводим Title = Languages.Translate("Audio encoding settings"); text_size.Content = Languages.Translate("Size") + ":"; text_codec.Content = Languages.Translate("Codec") + ":"; text_profile.Content = Languages.Translate("Profile:"); button_cancel.Content = Languages.Translate("Cancel"); button_ok.Content = Languages.Translate("OK"); button_add.ToolTip = Languages.Translate("Add profile"); button_remove.ToolTip = Languages.Translate("Remove profile"); LoadProfiles(); ShowDialog(); }
private void demux_mkv() { //удаляем старый файл SafeDelete(outfile); //список файлов string flist = ""; foreach (string _file in m.infileslist) { flist += "\"" + _file + "\" "; } encoderProcess = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = Calculate.StartupPath + "\\apps\\MKVtoolnix\\mkvextract.exe"; info.WorkingDirectory = Path.GetDirectoryName(info.FileName); info.UseShellExecute = false; info.StandardOutputEncoding = System.Text.Encoding.UTF8; info.RedirectStandardOutput = true; info.RedirectStandardError = false; info.CreateNoWindow = true; encodertext.Length = 0; if (mode == DemuxerMode.ExtractAudio) { AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; info.Arguments = "tracks " + flist + instream.mi_order + ":" + "\"" + outfile + "\" --output-charset UTF-8"; } else if (mode == DemuxerMode.ExtractVideo) { info.Arguments = "tracks " + flist + m.invideostream_mi_order + ":" + "\"" + outfile + "\" --output-charset UTF-8"; } else if (mode == DemuxerMode.RepairMKV) { info.FileName = Calculate.StartupPath + "\\apps\\MKVtoolnix\\mkvmerge.exe"; info.Arguments = "-S \"" + source_file + "\" -o \"" + outfile + "\" --output-charset UTF-8"; } encoderProcess.StartInfo = info; encoderProcess.Start(); string line; string pat = @"^[^\+].+:\s(\d+)%"; Regex r = new Regex(pat, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); Match mat; //первый проход while (!encoderProcess.HasExited) { line = encoderProcess.StandardOutput.ReadLine(); if (line != null) { mat = r.Match(line); if (mat.Success) { worker.ReportProgress(Convert.ToInt32(mat.Groups[1].Value)); } else if (line != "") { AppendEncoderText(line); } } } //Дочитываем остатки лога, если что-то не успело считаться line = encoderProcess.StandardOutput.ReadToEnd(); if (!string.IsNullOrEmpty(line)) { AppendEncoderText(Calculate.FilterLogMessage(r, line.Replace("\r\r\n", "\r\n"))); } //чистим ресурсы exit_code = encoderProcess.ExitCode; encoderProcess.Close(); encoderProcess.Dispose(); encoderProcess = null; if (IsAborted) { return; } //проверка на удачное завершение if (exit_code < 0 || exit_code > 1) //1 - Warning, 2 - Error { throw new Exception(encodertext.ToString()); } if (!File.Exists(outfile) || new FileInfo(outfile).Length == 0) { if (mode == DemuxerMode.ExtractVideo) { throw new Exception(Languages.Translate("Can`t find output video file!")); } if (mode == DemuxerMode.ExtractAudio) { throw new Exception(Languages.Translate("Can`t find output audio file!")); } } encodertext.Length = 0; }
private void combo_codec_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { if ((combo_codec.IsDropDownOpen || combo_codec.IsSelectionBoxHighlighted) && combo_codec.SelectedItem != null) { //определяем аудио потоки AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream]; UnLoadCodecWindow(); outstream.codec = combo_codec.SelectedItem.ToString(); m.mp3_options = new mp3_arguments(); m.aac_options = new aac_arguments(); m.qaac_options = new qaac_arguments(); m.ac3_options = new ac3_arguments(); m.flac_options = new flac_arguments(); LoadCodecWindow(); if (outstream.codec == "Disabled") { combo_profile.SelectedItem = outstream.codec; outstream.encoding = outstream.codec; } else if (outstream.codec == "Copy") { combo_profile.SelectedItem = outstream.codec; outstream.encoding = outstream.codec; outstream.bitrate = instream.bitrate; m = Format.GetValidSamplerate(m); m = Format.GetValidBits(m); m = Format.GetValidChannelsConverter(m); m = Format.GetValidChannels(m); } else { m = Format.GetValidSamplerate(m); m = Format.GetValidBits(m); m = Format.GetValidChannelsConverter(m); m = Format.GetValidChannels(m); UpdateManualProfile(); } //правим выходной битрейт if (outstream.codec == "Disabled") { outstream.bitrate = 0; } //проверяем можно ли копировать данный формат if (outstream.codec == "Copy") { string CopyProblems = Format.ValidateCopyAudio(m); if (CopyProblems != null) { new Message(this).ShowMessage(Languages.Translate("The stream contains parameters incompatible with this format") + " " + Format.EnumToString(m.format) + ": " + CopyProblems + "." + Environment.NewLine + Languages.Translate("(You see this message because audio encoder = Copy)"), Languages.Translate("Warning")); } } UpdateOutSize(); } }
private void ErrorExeption(string message) { ShowMessage(message, Languages.Translate("Error")); }
private void combo_profile_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { if ((combo_profile.IsDropDownOpen || combo_profile.IsSelectionBoxHighlighted) && combo_profile.SelectedItem != null) { RefreshCodecProfileWindow(); //правим выходной битрейт if (m.outvcodec == "Copy") { m.outvbitrate = m.invbitrate; } profile_was_changed = true; UpdateOutSize(); profile_was_changed = false; //проверяем можно ли копировать данный формат if (m.outvcodec == "Copy") { string CopyProblems = Format.ValidateCopyVideo(m); if (CopyProblems != null) { new Message(this).ShowMessage(Languages.Translate("The stream contains parameters incompatible with this format") + " " + Format.EnumToString(m.format) + ": " + CopyProblems + "." + Environment.NewLine + Languages.Translate("(You see this message because video encoder = Copy)"), Languages.Translate("Warning")); } } } }
private ArrayList raw_action = new ArrayList(); //Action, не переведенные public Settings_Window(MainWindow parent, int set_focus_to) { this.InitializeComponent(); this.Owner = this.p = parent; //переводим button_ok.Content = Languages.Translate("OK"); Title = Languages.Translate("Settings") + ":"; check_x264_psnr.ToolTip = Languages.Translate("Show x264 PSNR info"); check_x264_ssim.ToolTip = Languages.Translate("Show x264 SSIM info"); check_x265_psnr.ToolTip = check_x264_psnr.ToolTip.ToString().Replace("x264", "x265"); check_x265_ssim.ToolTip = check_x264_ssim.ToolTip.ToString().Replace("x264", "x265"); check_x262_psnr.ToolTip = check_x264_psnr.ToolTip.ToString().Replace("x264", "x262"); check_x262_ssim.ToolTip = check_x264_ssim.ToolTip.ToString().Replace("x264", "x262"); check_show_arguments.Content = Languages.Translate("Show encoding arguments"); check_show_script.Content = Languages.Translate("Show AviSynth script"); check_search_temp.Content = Languages.Translate("Search the best temp folder place on program start"); check_auto_colormatrix.Content = Languages.Translate("Auto apply ColorMatrix for MPEG2 files"); label_temppath.Content = Languages.Translate("Temp folder path:"); button_temppath.ToolTip = Languages.Translate("Edit path"); button_temppath_open.ToolTip = Languages.Translate("Open folder"); check_window_size.Content = Languages.Translate("Restore the size and location of the main window"); check_window_pos.Content = Languages.Translate("Fit windows to the working area bounds"); check_hide_comments.Content = Languages.Translate("Remove comments (#text) from the AviSynth script"); check_show_ftooltips.Content = Languages.Translate("Show advanced tooltips for filtering presets"); check_resize_first.Content = Languages.Translate("Make crop/resize before filtering (otherwise - after filtering)"); check_read_prmtrs.Content = Languages.Translate("Read parameters from the script when saving a new task"); check_log_to_file.Content = Languages.Translate("Write encoding log to file"); check_logfile_tempfolder.Content = Languages.Translate("in Temp folder"); label_extensions.Content = Languages.Translate("Only files with this extensions will be opened:"); check_batch_autoencoding.Content = Languages.Translate("Start encoding after opening all files"); check_is_always_close_encoding.Content = Languages.Translate("Autoclose encoding window if task was successfully accomplished"); label_clone.Content = Languages.Translate("Clone from the already opened file to each other:"); check_clone_ar.Content = Languages.Translate("Aspect/Resolution info (crop, aspect, etc)"); check_clone_trim.Content = Languages.Translate("Trim"); check_clone_deint.Content = Languages.Translate("Deinterlace"); check_clone_fps.Content = Languages.Translate("Framerate"); check_clone_audio.Content = Languages.Translate("Audio options"); check_batch_pause.Content = Languages.Translate("Make a pause after 1-st opened file"); string create_cache = " - " + Languages.Translate("Create caches in Temp folder"); string delete_cache = " - " + Languages.Translate("Auto delete caches"); check_ffms_cache_in_temp.Content = "FFmpegSource2" + create_cache; check_delete_ff_cache.Content = "FFmpegSource2" + delete_cache; check_dgindex_cache_in_temp.Content = "DGIndex" + create_cache; check_delete_dgindex_cache.Content = "DGIndex" + delete_cache; check_dgindexnv_cache_in_temp.Content = "DGIndexNV" + create_cache; check_delete_dgindexnv_cache.Content = "DGIndexNV" + delete_cache; check_delete_lsmash_cache.Content = "LWLibav" + delete_cache; if (SysInfo.GetOSArchInt() == 64) { check_use_64x264.Content = Languages.Translate("Use 64-bit x264"); check_use_64x264.ToolTip = Languages.Translate("This option will allow you to use 64-bit x264 with 32-bit AviSynth (via avs4x26x proxy)"); check_use_64x265.Content = check_use_64x264.Content.ToString().Replace("x264", "x265"); check_use_64x265.ToolTip = check_use_64x264.ToolTip.ToString().Replace("x264", "x265"); } else { check_use_64x264.Content = Languages.Translate("Run x264 using avs4x26x proxy"); check_use_64x264.ToolTip = Languages.Translate("Use this option if you run out of memory due to 32-bit OS limitation of ~2GB per process"); check_use_64x265.Content = Languages.Translate("Use 64-bit x264").Replace("x264", "x265"); check_use_64x265.IsChecked = false; check_use_64x265.IsEnabled = false; } check_dont_delete_caches.Content = Languages.Translate("Don`t delete any caches and temporal files"); check_use_trayicon.Content = Languages.Translate("Enable system tray icon"); check_audio_first.Content = Languages.Translate("Encode audio first, then video"); check_batch_pause.ToolTip = Languages.Translate("So you can tune all encoding settings as needed, and then continue opening"); check_clone_ar.ToolTip = Languages.Translate("Clone: resolution, crop on each side, added black borders, output SAR/aspect and aspect adjusting method.") + "\r\n" + Languages.Translate("Note: Autocrop analysis will not be performed!"); check_clone_trim.ToolTip = Languages.Translate("Clone: trim start and trim end (for each region)"); check_clone_deint.ToolTip = Languages.Translate("Clone: source type, field order, deinterlace method.") + "\r\n" + Languages.Translate("Note: Autodeinterlace analysis will not be performed!"); check_clone_fps.ToolTip = Languages.Translate("Clone: output framerate"); check_clone_audio.ToolTip = Languages.Translate("Clone: output samplerate, samplerate converter, channels, channels converter"); check_dont_delete_caches.ToolTip = Languages.Translate("Enable this option only if you use XviD4PSP as script creator, and then encoding it in another application.") + "\r\n" + Languages.Translate("Or for experiments. In any other cases this option must be disabled (unchecked)!"); check_read_prmtrs.ToolTip = Languages.Translate("Read from the script: width, height, fps, duration and frames count.") + "\r\n" + Languages.Translate("Use it only if these parameters was changed manually in the script!"); check_use_win7taskbar.Content = Languages.Translate("Enable Windows 7 taskbar progress indication"); check_enable_backup.Content = Languages.Translate("Create a backups of the tasks list"); check_validate_pathes.Content = Languages.Translate("Check for illegal characters in pathes"); check_sort_by_time.Content = Languages.Translate("Sort presets by last modification time"); check_auto_abort.Content = Languages.Translate("Cancel encoding if there is no progress (in minutes):"); button_restore_hotkeys.Content = Languages.Translate("Restore default settings"); button_edit_hotkeys.Content = Languages.Translate("Edit"); button_save_hotkeys.Content = Languages.Translate("Save"); label_action.Content = Languages.Translate("Action") + ":"; label_combination.Content = Languages.Translate("Combination") + ":"; tab_main.Header = Languages.Translate("Misc"); tab_encoding.Header = Languages.Translate("Encoding"); tab_temp.Header = Languages.Translate("Temp files"); tab_open_folder.Header = Languages.Translate("Batch encoding"); //tab_hotkeys.Header = Languages.Translate("HotKeys"); check_x264_psnr.IsChecked = Settings.x264_PSNR; check_x264_ssim.IsChecked = Settings.x264_SSIM; check_x265_psnr.IsChecked = Settings.x265_PSNR; check_x265_ssim.IsChecked = Settings.x265_SSIM; check_x262_psnr.IsChecked = Settings.x262_PSNR; check_x262_ssim.IsChecked = Settings.x262_SSIM; check_show_arguments.IsChecked = Settings.ArgumentsToLog; check_show_script.IsChecked = Settings.PrintAviSynth; check_delete_ff_cache.IsChecked = Settings.DeleteFFCache; check_delete_lsmash_cache.IsChecked = Settings.DeleteLSMASHCache; check_delete_dgindex_cache.IsChecked = Settings.DeleteDGIndexCache; check_delete_dgindexnv_cache.IsChecked = Settings.DeleteDGIndexNVCache; check_search_temp.IsChecked = Settings.SearchTempPath; textbox_temp.Text = Settings.TempPath; check_auto_colormatrix.IsChecked = Settings.AutoColorMatrix; check_window_size.IsChecked = Settings.WindowResize; //Восстанавливать параметры главного окна check_hide_comments.IsChecked = Settings.HideComments; //Удалять комментарии из скрипта check_show_ftooltips.IsChecked = Settings.ShowFToolTips; //Показывать подсказки к пресетам фильтрации check_resize_first.IsChecked = Settings.ResizeFirst; //Ресайз перед фильтрацией check_read_prmtrs.IsChecked = Settings.ReadScript; //Считывать параметры скрипта check_log_to_file.IsChecked = Settings.WriteLog; //Записывать лог кодирования в файл.. check_logfile_tempfolder.IsChecked = Settings.LogInTemp; //.. а файл поместить во временную папку textbox_extensions.Text = Settings.GoodFilesExtensions; //Окно со списком допустимых расширений файлов (при пакетной обработке) check_batch_autoencoding.IsChecked = Settings.AutoBatchEncoding; //Автозапуск кодирования (при пакетной обработке) check_ffms_cache_in_temp.IsChecked = Settings.FFMS_IndexInTemp; //Помещать FFMS2-кэш в Темп-папку check_dgindex_cache_in_temp.IsChecked = Settings.DGIndexInTemp; //Помещать DGIndex-кэш в Темп-папку check_dgindexnv_cache_in_temp.IsChecked = Settings.DGIndexNVInTemp; //Помещать DGIndexNV-кэш в Темп-папку check_clone_ar.IsChecked = Settings.BatchCloneAR; //Наследовать параметры Разрешения\Аспекта от предыдущего файла (при пакетной обработке) check_clone_trim.IsChecked = Settings.BatchCloneTrim; //То-же что и выше, но для обрезки check_clone_deint.IsChecked = Settings.BatchCloneDeint; //А это для деинтерлейса check_clone_fps.IsChecked = Settings.BatchCloneFPS; //Это для fps check_clone_audio.IsChecked = Settings.BatchCloneAudio; //Ну а это для звуковых параметров check_batch_pause.IsChecked = Settings.BatchPause; //Пауза после первого открытого файла (чтоб выставить настройки и т.д.) check_use_64x264.IsChecked = Settings.UseAVS4x264; //Запускать x264\x264_64 через avs4x26x if (check_use_64x265.IsEnabled) { check_use_64x265.IsChecked = Settings.UseAVS4x265; //Использовать 64-битный x265 } check_is_always_close_encoding.IsChecked = Settings.AutoClose; //Автозакрытие окна кодирования check_dont_delete_caches.IsChecked = !(check_delete_ff_cache.IsEnabled = check_delete_lsmash_cache.IsEnabled = check_delete_dgindex_cache.IsEnabled = check_delete_dgindexnv_cache.IsEnabled = Settings.DeleteTempFiles); //Удалять кэши и временные файлы check_use_trayicon.IsChecked = Settings.TrayIconIsEnabled; //Иконка в трее вкл\выкл check_audio_first.IsChecked = Settings.EncodeAudioFirst; //Кодировать сначала звук, потом видео check_use_win7taskbar.IsChecked = Settings.Win7TaskbarIsEnabled; //Поддержка таскбара в Win7 вкл\выкл check_enable_backup.IsChecked = Settings.EnableBackup; //Разрешаем сохранять резервную копию списка заданий check_validate_pathes.IsChecked = Settings.ValidatePathes; //Проверять пути на "нехорошие" символы check_sort_by_time.IsChecked = Settings.SortPresetsByTime; //Сортировка пресетов по времени изменений check_auto_abort.IsChecked = Settings.AutoAbortEncoding; //Автоматически прерывать зависшие задания num_auto_abort.Value = Settings.AutoAbortThreshold; //Время отсутствия прогресса для определения зависания num_auto_abort.Tag = (check_auto_abort.IsChecked.Value) ? null : "Inactive"; if ((bool)(check_window_pos.IsChecked = Settings.CheckWindowsPos)) //Проверять размер и расположение окон { this.SourceInitialized += new EventHandler(Window_SourceInitialized); } //Загружаем HotKeys (плюс перевод к действиям) foreach (string line in HotKeys.Data) { if (line.Contains("=")) { string[] action_and_combination = line.Split(new string[] { "=" }, StringSplitOptions.None); raw_action.Add(action_and_combination[0].Trim()); string translated_action = Languages.Translate(action_and_combination[0].Trim()); combo_action.Items.Add(translated_action); listview_hotkeys.Items.Add(new { Column1 = translated_action, Column2 = action_and_combination[1] }); } } combo_action.SelectedIndex = listview_hotkeys.SelectedIndex = 0; textbox_combination.Text = HotKeys.GetKeys(raw_action[combo_action.SelectedIndex].ToString()); list_loaded = true; //Чтоб открыть окно на нужной вкладке if (set_focus_to == 2) { tab_temp.IsSelected = true; } else if (set_focus_to == 3) { tab_encoding.IsSelected = true; } else if (set_focus_to == 4) { tab_open_folder.IsSelected = true; } else if (set_focus_to == 5) { tab_hotkeys.IsSelected = true; } ShowDialog(); }
public VideoEncoding(Massive mass, MainWindow parent) { this.InitializeComponent(); if (mass != null) { this.m = mass.Clone(); this.oldm = mass.Clone(); } else { //Заполняем массив m = new Massive(); m.format = Settings.FormatOut; m.vencoding = old_vencoding = Settings.GetVEncodingPreset(m.format); m.outvcodec = PresetLoader.GetVCodec(m); m.vpasses = PresetLoader.GetVCodecPasses(m); m = PresetLoader.DecodePresets(m); m.infilepath = "C:\\file.mkv"; m.invcodecshort = "NOINPUT"; m.inresw = m.outresw = 640; m.inresh = m.outresh = 480; m.induration = m.outduration = TimeSpan.FromMinutes(1); m.inframerate = m.outframerate = "25.000"; m.inframes = m.outframes = 1000; m.infilesizeint = 1000; m.invbitrate = 1000; //Убираем лишнее, т.к. всё-равно показывать там нечего text_insize_value.Visibility = text_outsize_value.Visibility = Visibility.Collapsed; text_inquality_value.Visibility = text_outquality_value.Visibility = Visibility.Collapsed; text_codec.Margin = text_incodec_value.Margin = combo_codec.Margin = new Thickness(16, 8, 16, 8); row2.Height = row3.Height = new GridLength(0); } this.Owner = this.p = parent; //загружаем список кодеков соответвующий формату foreach (string codec in Format.GetVCodecsList(m.format)) { combo_codec.Items.Add(codec); } combo_codec.Items.Add("Copy"); if (!combo_codec.Items.Contains(m.outvcodec)) { combo_codec.Items.Add(m.outvcodec); } combo_codec.SelectedItem = m.outvcodec; text_incodec_value.Content = m.invcodecshort; text_insize_value.Content = m.infilesize; text_outsize_value.Content = m.outfilesize = Calculate.GetEncodingSize(m); //загружаем правильную страницу LoadCodecWindow(); //переводим Title = Languages.Translate("Video encoding settings"); text_size.Content = Languages.Translate("Size") + ":"; text_codec.Content = Languages.Translate("Codec") + ":"; text_quality.Content = Languages.Translate("Quality") + ":"; text_profile.Content = Languages.Translate("Profile:"); button_cancel.Content = Languages.Translate("Cancel"); button_ok.Content = Languages.Translate("OK"); button_add.ToolTip = Languages.Translate("Add profile"); button_remove.ToolTip = Languages.Translate("Remove profile"); //bit-pixels calculation text_inquality_value.Content = Calculate.GetQualityIn(m); text_outquality_value.Content = Calculate.GetQualityOut(m, true); LoadProfiles(); ShowDialog(); }
private void ErrorException(string message) { new Message(this).ShowMessage(message, Languages.Translate("Error")); }
private void button_remove_Click(object sender, System.Windows.RoutedEventArgs e) { if (m.outvcodec == "Copy") { return; } if (combo_profile.Items.Count > 1) { UpdateMassive(); Message mess = new Message(this); mess.ShowMessage(Languages.Translate("Do you realy want to remove profile") + " \"" + m.vencoding + "\"?", Languages.Translate("Question"), Message.MessageStyle.YesNo); if (mess.result == Message.Result.Yes) { int last_num = combo_profile.SelectedIndex; string profile_path = Calculate.StartupPath + "\\presets\\encoding\\" + Format.EnumToString(m.format) + "\\video\\" + m.vencoding + ".txt"; try { File.Delete(profile_path); } catch (Exception ex) { new Message(this).ShowMessage(Languages.Translate("Can`t delete profile") + ": " + ex.Message, Languages.Translate("Error"), Message.MessageStyle.Ok); return; } //загружаем список пресетов combo_profile.Items.Clear(); try { foreach (string file in Calculate.GetSortedFiles(Calculate.StartupPath + "\\presets\\encoding\\" + Format.EnumToString(m.format) + "\\video", "*.txt")) { combo_profile.Items.Add(Path.GetFileNameWithoutExtension(file)); } } catch { } combo_profile.Items.Add("Copy"); //прописываем текущий пресет кодирования if (last_num == 0) { //Самый первый пресет m.vencoding = combo_profile.Items[0].ToString(); } else { //Предыдущий (перед удалённым) пресет m.vencoding = combo_profile.Items[last_num - 1].ToString(); } combo_profile.SelectedItem = m.vencoding; combo_profile.UpdateLayout(); RefreshCodecProfileWindow(); UpdateOutSize(); UpdateCodecMassive(); LoadProfileToCodec(); //проверяем можно ли копировать данный формат if (m.outvcodec == "Copy") { string CopyProblems = Format.ValidateCopyVideo(m); if (CopyProblems != null) { new Message(this).ShowMessage(Languages.Translate("The stream contains parameters incompatible with this format") + " " + Format.EnumToString(m.format) + ": " + CopyProblems + "." + Environment.NewLine + Languages.Translate("(You see this message because video encoder = Copy)"), Languages.Translate("Warning")); } } } } else { new Message(this).ShowMessage(Languages.Translate("Not allowed removing the last profile!"), Languages.Translate("Warning"), Message.MessageStyle.Ok); } }
private void button_save_hotkeys_Click(object sender, RoutedEventArgs e) { if (edit) { if (textbox_combination.Text != "") { string Action = HotKeys.GetAction("=" + textbox_combination.Text); if (Action != "" && Action != raw_action[combo_action.SelectedIndex].ToString()) { ErrorException(Languages.Translate("Combination") + " \"" + textbox_combination.Text + "\" " + Languages.Translate("already used for") + " \"" + Languages.Translate(Action) + "\"."); return; } } string output = ""; foreach (string line in HotKeys.Data) { if (line.Contains("=")) { string[] action = line.Trim().Split(new string[] { "=" }, StringSplitOptions.None); if (action[0] == raw_action[combo_action.SelectedIndex].ToString()) { output += action[0] + "=" + textbox_combination.Text + "; "; } else { output += line.Trim() + "; "; } } } Settings.HotKeys = output; p.SetHotKeys(); //Тут происходит обновление HotKeys.Data UpdateHotKeysBox(); Menu_Changed(null, null); } }
private void AddExternalTrack(string infilepath) { //получаем медиа информацию MediaInfoWrapper mi = null; FFInfo ff = null; try { AudioStream stream = null; int old_stream = 0; string ext = Path.GetExtension(infilepath).ToLower(); if (ext != ".avs" && ext != ".grf") { mi = new MediaInfoWrapper(); stream = mi.GetAudioInfoFromAFile(infilepath, false); stream.mi_order = mi.ATrackOrder(0); stream.mi_id = mi.ATrackID(0); ff = new FFInfo(); ff.Open(infilepath); //Аналогично тому, как сделано в Informer'е if (ff.AudioStreams().Count > 0) { stream.ff_order = ff.FirstAudioStreamID(); stream.ff_order_filtered = ff.FilteredStreamOrder(stream.ff_order); if (stream.mi_order < 0) { stream.mi_order = stream.ff_order; } if (stream.bitrate == 0) { stream.bitrate = ff.AudioBitrate(stream.ff_order); } if (stream.channels == 0) { stream.channels = ff.StreamChannels(stream.ff_order); } if (stream.samplerate == null) { stream.samplerate = ff.StreamSamplerate(stream.ff_order); } if (stream.language == "Unknown") { stream.language = ff.StreamLanguage(stream.ff_order); } stream.ff_bits = ff.StreamBits(stream.ff_order); //if (stream.bits == 0) stream.bits = stream.ff_bits; stream.ff_codec = ff.StreamCodec(stream.ff_order); if (stream.codec == "A_MS/ACM" || stream.codec == "") { stream.codec = stream.ff_codec; stream.codecshort = ff.StreamCodecShort(stream.ff_order); } } } else { stream = new AudioStream(); stream.audiopath = infilepath; stream.audiofiles = new string[] { stream.audiopath }; stream.codec = stream.codecshort = "PCM"; stream.language = "Unknown"; } //Добавляем этот трек old_stream = m.inaudiostream; stream = Format.GetValidADecoder(stream); m.inaudiostream = m.inaudiostreams.Count; m.inaudiostreams.Add(stream.Clone()); //Оставшаяся инфа + ошибки Caching cach = new Caching(m, true); if (cach.m == null) { //Удаляем этот трек m.inaudiostream = old_stream; m.inaudiostreams.RemoveAt(m.inaudiostreams.Count - 1); return; } m = cach.m.Clone(); textbox_apath.Text = infilepath; //разрешаем формы group_channels.IsEnabled = true; group_delay.IsEnabled = true; group_samplerate.IsEnabled = true; group_volume.IsEnabled = true; //прописываем в список внешний трек ComboBoxItem item = new ComboBoxItem(); stream = (AudioStream)m.inaudiostreams[m.inaudiostream]; //Переопределяем с новыми параметрами item.Content = (combo_atracks.Items.Count + 1).ToString("00") + ". " + stream.language + " " + stream.codecshort + " " + stream.channels + "ch"; item.ToolTip = item.Content + " " + stream.samplerate + "Hz " + stream.bitrate + "kbps " + stream.delay + "ms"; combo_atracks.Items.Add(item); combo_atracks.SelectedIndex = combo_atracks.Items.Count - 1; } catch (Exception ex) { ErrorException("AddExternalTrack: " + ex.Message, ex.StackTrace); return; } finally { if (mi != null) { mi.Close(); mi = null; } if (ff != null) { ff.Close(); ff = null; } } AudioStream newstream = new AudioStream(); m.outaudiostreams.Clear(); m.outaudiostreams.Add(newstream); AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream]; //забиваем аудио настройки outstream.encoding = Settings.GetAEncodingPreset(Settings.FormatOut); outstream.codec = PresetLoader.GetACodec(m.format, outstream.encoding); outstream.passes = PresetLoader.GetACodecPasses(m); m = Format.GetValidSamplerate(m); //определяем битность m = Format.GetValidBits(m); //определяем колличество каналов m = Format.GetValidChannelsConverter(m); m = Format.GetValidChannels(m); //проверяем можно ли копировать данный формат if (outstream.codec == "Copy") { AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; outstream.audiopath = instream.audiopath; outstream.bitrate = instream.bitrate; string CopyProblems = Format.ValidateCopyAudio(m); if (CopyProblems != null) { Message mess = new Message(this); mess.ShowMessage(Languages.Translate("The stream contains parameters incompatible with this format") + " " + Format.EnumToString(m.format) + ": " + CopyProblems + "." + Environment.NewLine + Languages.Translate("(You see this message because audio encoder = Copy)"), Languages.Translate("Warning")); } } else { string aext = Format.GetValidRAWAudioEXT(outstream.codec); outstream.audiopath = Settings.TempPath + "\\" + m.key + aext; } SetAudioOptions(); SetInfo(); }
private void LoadCodecWindow() { //определяем аудио потоки AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream]; AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream]; //загрузка if (outstream.codec == "AAC") { aac = new NeroAAC(m, this); grid_codec.Children.Add(aac); } else if (outstream.codec == "QAAC") { qaac = new QuickTimeAAC(m, this); grid_codec.Children.Add(qaac); } else if (outstream.codec == "MP3") { mp3 = new LameMP3(m, this); grid_codec.Children.Add(mp3); } else if (outstream.codec == "AC3") { ac3 = new AftenAC3(m, this); grid_codec.Children.Add(ac3); } else if (outstream.codec == "MP2") { fmp2 = new FMP2(m, this); grid_codec.Children.Add(fmp2); } else if (outstream.codec == "PCM") { fpcm = new FPCM(m, this); grid_codec.Children.Add(fpcm); } else if (outstream.codec == "LPCM") { flpcm = new FLPCM(m, this); grid_codec.Children.Add(flpcm); } else if (outstream.codec == "FLAC") { fflac = new FFLAC(m, this); grid_codec.Children.Add(fflac); } else if (outstream.codec == "Copy" || outstream.codec == "Disabled") { copyordisabled = new CopyOrDisabled(); if (outstream.codec == "Disabled") { copyordisabled.text_info.Content = Languages.Translate("Output file will be created without sound."); } else { copyordisabled.text_info.Content = "Codec: " + instream.codecshort + Environment.NewLine; copyordisabled.text_info.Content += "Bitrate: " + instream.bitrate + " kbps" + Environment.NewLine; copyordisabled.text_info.Content += "Channels: " + instream.channels + " ch" + Environment.NewLine; copyordisabled.text_info.Content += "Samplerate: " + instream.samplerate + " Hz" + Environment.NewLine; copyordisabled.text_info.Content += "Bits: " + instream.bits + " bit"; } grid_codec.Children.Add(copyordisabled); } }
private void ErrorException(string message, string info) { Message mes = new Message(this); mes.ShowMessage(message, info, Languages.Translate("Error")); }
private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { try //Индексация { indexfile = m.indexfile; encoderProcess = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = Calculate.StartupPath + "\\apps\\DGDecNV\\DGIndexNV.exe"; info.WorkingDirectory = Path.GetDirectoryName(info.FileName); //DGIndexNV.exe отсутствует if (!File.Exists(info.FileName)) { throw new Exception("DGIndexNV <- " + Languages.Translate("You need to obtain your licensed copy of the DGDecNV package from the author (Donald Graft) in order to use it!") + "\r\n" + Languages.Translate("Home page") + ": http://rationalqm.us/dgdecnv/dgdecnv.html"); } //создаём папку if (!Directory.Exists(Path.GetDirectoryName(m.indexfile))) { Directory.CreateDirectory(Path.GetDirectoryName(m.indexfile)); } //создаём список файлов string files_list = ""; for (int i = 0; i < m.infileslist.Length; i++) { files_list += "\"" + m.infileslist[i] + "\""; if (i < m.infileslist.Length - 1) { files_list += ","; } } //Извлекаем звук, только если он нам нужен string ademux = (Settings.EnableAudio) ? " -a" : ""; //Выходим при отмене if (worker.CancellationPending) { return; } //DGIndexNV -i "d:\files\my wedding day.264","d:\files\my divorce day.264" -o "d:\my wedding day.dgi" -e info.Arguments = "-i " + files_list + " -o \"" + Calculate.RemoveExtention(m.indexfile, true) + ".dgi\" -h" + ademux; info.CreateNoWindow = true; info.UseShellExecute = false; info.RedirectStandardOutput = true; info.RedirectStandardError = false; encoderProcess.StartInfo = info; encoderProcess.Start(); encoderProcess.PriorityClass = ProcessPriorityClass.Normal; encoderProcess.PriorityBoostEnabled = true; Match mat; Regex r = new Regex(@"(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); while (!encoderProcess.HasExited) { string line = encoderProcess.StandardOutput.ReadLine(); if (line != null) { mat = r.Match(line); if (mat.Success) { worker.ReportProgress(Convert.ToInt32(mat.Groups[1].Value)); } } } encoderProcess.WaitForExit(); //Индекс-файл не найден if (!worker.CancellationPending && !File.Exists(m.indexfile)) { throw new Exception(Languages.Translate("Can`t find file") + ": " + m.indexfile); } if (worker.CancellationPending) { return; } } catch (Exception ex) { if (worker != null && !worker.CancellationPending && m != null && num_closes == 0) { //Ошибка e.Result = ex; } m = null; return; } try //Перепроверка индекса и ForceFilm { m.IsForcedFilm = CheckIndexAndForceFilm(m.indexfile, m.inframerate); } catch (Exception ex) { if (worker != null && !worker.CancellationPending && m != null && num_closes == 0) { //Ошибка e.Result = ex; } m = null; } }