Beispiel #1
0
        private void LoadProfiles()
        {
            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            //загружаем список пресетов
            combo_profile.Items.Clear();
            try
            {
                foreach (string file in Calculate.GetSortedFiles(Calculate.StartupPath + "\\presets\\encoding\\" + Format.EnumToString(m.format) + "\\audio", "*.txt"))
                {
                    combo_profile.Items.Add(Path.GetFileNameWithoutExtension(file));
                }
            }
            catch { }
            if (oldm != null)
            {
                combo_profile.Items.Add("Disabled");
            }
            combo_profile.Items.Add("Copy");

            //прописываем текущий пресет кодирования
            combo_profile.SelectedItem = outstream.encoding;
        }
Beispiel #2
0
 private void LoadBitrates()
 {
     try
     {
         combo_bitrate.Items.Clear();
         AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
         if (m.aac_options.encodingmode == Settings.AudioEncodingModes.VBR)
         {
             double n = 0;
             while (n <= 1.01)
             {
                 combo_bitrate.Items.Add(n.ToString("0.00").Replace(",", "."));
                 n += 0.01;
             }
             //Битрейт для VBR
             outstream.bitrate = 0;
         }
         else
         {
             int n = 16;
             while (n <= Format.GetMaxAACBitrate(m))
             {
                 combo_bitrate.Items.Add(n);
                 n += 4;
             }
             //Битрейт по умолчанию
             if (!combo_bitrate.Items.Contains(outstream.bitrate) || outstream.bitrate == 0)
             {
                 outstream.bitrate = 128;
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
        private void button_apply_Click(object sender, RoutedEventArgs e)
        {
            if (m.inaudiostreams.Count > 0)
            {
                AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];

                string outacodec = null;
                if (m.outaudiostreams.Count > 0)
                {
                    AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                    outacodec = outstream.codec;
                }

                if (instream.audiopath != null && !File.Exists(instream.audiopath))
                {
                    Demuxer dem = new Demuxer(m, Demuxer.DemuxerMode.ExtractAudio, instream.audiopath);
                    if (dem.IsErrors)
                    {
                        ErrorException(dem.error_message, null);

                        //Обходим анализ громкости
                        Refresh();
                        SetInfo();
                        return;
                    }
                }

                if ((m.volume != "Disabled" && Settings.AutoVolumeMode != Settings.AutoVolumeModes.Disabled) &&
                    !instream.gaindetected && outacodec != "Copy")
                {
                    AnalyseVolume();
                }
            }

            Refresh();
            SetInfo();
        }
Beispiel #4
0
        public static Massive DecodeLine(Massive m)
        {
            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            //берём пока что за основу последнюю строку
            string line = outstream.passes;

            string[] separator = new string[] { " " };
            string[] cli       = line.Split(separator, StringSplitOptions.None);
            int      n         = 0;

            foreach (string value in cli)
            {
                if (value == "-acodec")
                {
                    string bit = cli[n + 1];

                    if (bit == "pcm_s16be")
                    {
                        outstream.bits = 16;
                    }
                    if (bit == "pcm_s24be")
                    {
                        outstream.bits = 24;
                    }
                    if (bit == "pcm_s32be")
                    {
                        outstream.bits = 32;
                    }
                }
            }

            outstream.bitrate = (int)(0.016 * outstream.channels * (double)Convert.ToInt32(outstream.samplerate) * (double)outstream.bits / 16.0);

            return(m);
        }
Beispiel #5
0
        public static Massive EncodeLine(Massive m)
        {
            string line = "-acodec flac -f flac";

            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            if (m.flac_options.level != 5)
            {
                line += " -compression_level " + m.flac_options.level;
            }
            if (m.flac_options.use_lpc != 1)
            {
                line += " -use_lpc " + m.flac_options.use_lpc;
            }
            if (m.flac_options.lpc_precision != 15)
            {
                line += " -lpc_coeff_precision " + m.flac_options.lpc_precision;
            }

            //забиваем данные в массив
            outstream.passes = line;

            return(m);
        }
Beispiel #6
0
        private void createEncoderProcess()
        {
            try
            {
                _encoderProcess = new Process();
                ProcessStartInfo info = new ProcessStartInfo();

                AudioStream stream = (AudioStream)m.outaudiostreams[m.outaudiostream];

                if (encoderPath.EndsWith("neroAacEnc.exe"))
                {
                    info.Arguments = "-ignorelength " + stream.passes + " -if - -of \"" + outfilepath + "\"";
                }
                else if (encoderPath.EndsWith("qaac.exe"))
                {
                    info.Arguments = stream.passes + " --no-optimize --ignorelength - -o \"" + outfilepath + "\"";
                    info.StandardOutputEncoding = Encoding.UTF8;
                    info.StandardErrorEncoding  = Encoding.UTF8;
                }
                else if (encoderPath.EndsWith("lame.exe"))
                {
                    string resample = "";
                    if (m.mp3_options.forcesamplerate)
                    {
                        resample = Calculate.ConvertDoubleToPointString(Convert.ToDouble(stream.samplerate) / 1000.0, 1);
                    }
                    info.Arguments = stream.passes + resample + " - \"" + outfilepath + "\"";
                    if (stream.channels == 1)
                    {
                        //Не уверен, что это вообще нужно..
                        info.Arguments = info.Arguments.Replace("-m s", "-m m").Replace("-m j", "-m m").Replace("-m f", "-m m");
                        if (!info.Arguments.Contains("-m m"))
                        {
                            info.Arguments = "-m m " + info.Arguments;
                        }
                    }
                }
                else if (encoderPath.EndsWith("ffmpeg.exe"))
                {
                    info.Arguments = "-i - " + stream.passes + " -vn \"" + outfilepath + "\" -hide_banner -nostdin";
                    info.StandardOutputEncoding = Encoding.UTF8;
                    info.StandardErrorEncoding  = Encoding.UTF8;
                }
                else if (encoderPath.EndsWith("aften.exe"))
                {
                    info.Arguments = stream.passes + " - \"" + outfilepath + "\"";
                }

                //запоминаем аргументы для лога
                args = info.Arguments;

                info.FileName               = encoderPath;
                info.WorkingDirectory       = Path.GetDirectoryName(info.FileName);
                info.UseShellExecute        = false;
                info.RedirectStandardInput  = true;
                info.RedirectStandardOutput = true;
                info.RedirectStandardError  = true;
                info.CreateNoWindow         = true;
                _encoderProcess.StartInfo   = info;
                _encoderProcess.Start();
                SetPriority(Settings.ProcessPriority);
                _readFromStdOutThread = new Thread(new ThreadStart(readStdOut));
                _readFromStdErrThread = new Thread(new ThreadStart(readStdErr));
                _readFromStdOutThread.Start();
                _readFromStdOutThread.Priority = ThreadPriority.Normal;
                _readFromStdErrThread.Start();
                _readFromStdErrThread.Priority = ThreadPriority.Normal;
            }
            catch (Exception e)
            {
                if (_encoderProcess != null)
                {
                    try
                    {
                        _encoderProcess.Kill();
                        _encoderProcess.WaitForExit();
                        _readFromStdErrThread.Join();
                        _readFromStdOutThread.Join();
                    }
                    catch { }
                    finally { _encoderProcess = null; }
                }

                throw new Exception("Can't start encoder: " + e.Message, e);
            }
        }
Beispiel #7
0
        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();
        }
Beispiel #8
0
        public static AudioStream GetValidADecoder(AudioStream instream)
        {
            if (instream.audiopath != null)
               {
               string ext = Path.GetExtension(instream.audiopath).ToLower().TrimStart(new char[] { '.' });

               if (ext == "avs")
               {
                   instream.decoder = AviSynthScripting.Decoders.WAVSource; //Нет, не Import
                   return instream;
               }
               if (ext == "grf")
               {
                   instream.decoder = AviSynthScripting.Decoders.DirectShowSource;
                   return instream;
               }

               string other_dec = AviSynthScripting.Decoders.bassAudioSource.ToString(); //Дефолт
               foreach (string line in (Settings.ADecoders.ToLower().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)))
               {
                   string[] extension_and_decoder = line.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                   if (extension_and_decoder.Length == 2)
                   {
                       string extension = extension_and_decoder[0].Trim();
                       string decoder = extension_and_decoder[1].Trim();

                       if (extension == Decoders_Settings.other_files) other_dec = decoder;
                       else if (extension == ext && decoder.Length > 0)
                       {
                           //Мы нашли декодер для этого расширения
                           instream.decoder = (AviSynthScripting.Decoders)Enum.Parse(typeof(AviSynthScripting.Decoders), decoder, true);
                           return instream;
                       }
                   }
               }

               if (other_dec.Length > 0) instream.decoder = (AviSynthScripting.Decoders)Enum.Parse(typeof(AviSynthScripting.Decoders), other_dec, true);
               else instream.decoder = AviSynthScripting.Decoders.bassAudioSource;
               }
               else instream.decoder = 0;
               return instream;
        }
Beispiel #9
0
        private void make_pmp()
        {
            IsNoProgressStage = true;

            if (m.outaudiostreams.Count == 0)
            {
                AudioStream stream = new AudioStream();
                stream.audiopath = Settings.TempPath + "\\" + m.key + ".m4a";
                File.Copy(Calculate.StartupPath + "\\apps\\pmp_muxer_avc\\fake.m4a",
                    stream.audiopath);
                m.outaudiostreams.Add(stream);
            }
            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            SafeDelete(m.outfilepath);

            busyfile = Path.GetFileName(m.outfilepath);
            step++;

            //проверка на правильное расширение
            string testext = Path.GetExtension(m.outvideofile);
            if (testext == ".h264")
            {
                string goodpath = Calculate.RemoveExtention(m.outvideofile, true) + ".264";
                File.Move(m.outvideofile, goodpath);
                m.outvideofile = goodpath;
            }

            //info строка
            SetLog("Video file: " + m.outvideofile);
            SetLog("Audio file: " + outstream.audiopath);
            SetLog("Muxing to: " + m.outfilepath);
            SetLog(Languages.Translate("Please wait") + "...");

            encoderProcess = new Process();
            ProcessStartInfo info = new ProcessStartInfo();

            info.FileName = Calculate.StartupPath + "\\apps\\pmp_muxer_avc\\pmp_muxer_avc.exe";
            info.WorkingDirectory = Path.GetDirectoryName(info.FileName);
            info.UseShellExecute = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;
            info.CreateNoWindow = true;

            string rate = "-r " + m.outframerate.Replace(".", "") + " ";
            if (m.outvcodec == "Copy")
            {
                if (m.inframerate != null)
                    rate = "-r " + m.inframerate.Replace(".", "") + " ";
                else
                    rate = "";
            }

            string ovext = Path.GetExtension(m.outvideofile).ToLower();
            if (ovext == ".h264")
            {
                File.Move(m.outvideofile, Calculate.RemoveExtention(m.outvideofile, true) + ".264");
                m.outvideofile = Calculate.RemoveExtention(m.outvideofile, true) + ".264";
            }

            info.Arguments = rate +
                "-w " + m.outresw.ToString() +
                " -h " + m.outresh + " -s 1000" +
                " -v \"" + m.outvideofile + "\"" +
                " -a \"" + outstream.audiopath + "\""
                + " -o \"" + m.outfilepath + "\"";

            //прописываем аргументы командной строки
            SetLog("");
            if (Settings.ArgumentsToLog)
            {
                SetLog("pmp_muxer_avc.exe:" + " " + info.Arguments);
                SetLog("");
            }

            SetLog("...import video...");

            encoderProcess.StartInfo = info;
            encoderProcess.Start();
            SetPriority(Settings.ProcessPriority);

            string line = "";
            string pat = @"(\d+)";
            Regex r = new Regex(pat, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
            Match mat;
            bool IsNum;
            int aframes = 0;

            //первый проход
            //while (!encoderProcess.HasExited)
            while (line != null)
            {
                locker.WaitOne();
                line = encoderProcess.StandardOutput.ReadLine();

                if (line == null)
                    break;

                    mat = r.Match(line);

                    try
                    {
                        int n = Int32.Parse(line);
                        IsNum = true;
                    }
                    catch
                    {
                        if (line.Contains(" / ") &&
                            !line.Contains("unused_bytes") &&
                            !line.Contains("difference"))
                            IsNum = true;
                        else
                            IsNum = false;
                    }

                    if (line.Contains("first frame at"))
                    {
                        step++;
                        SetLog("...import audio...");
                        string[] separator = new string[] { " " };
                        string[] a = line.Split(separator, StringSplitOptions.None);
                        aframes = Convert.ToInt32(a[3]);
                    }

                    if (line.Contains("Interleaving ..."))
                    {
                        step++;
                        SetLog("...interleaving...");
                    }

                    if (line.Contains("Writing ..."))
                    {
                        step++;
                        SetLog("...writing...");
                    }

                    if (mat.Success && IsNum)
                    {
                        if (line.Contains(" / ") && !line.Contains("unused_bytes"))
                        {
                            string[] separator = new string[] { "/" };
                            string[] a = line.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                            worker.ReportProgress((m.outframes / Convert.ToInt32(a[1])) * Convert.ToInt32(a[0]));
                        }
                        else
                        {
                            if (aframes == 0)
                                worker.ReportProgress(Convert.ToInt32(mat.Groups[1].Value));
                            else
                                worker.ReportProgress((m.outframes / aframes) * Convert.ToInt32(mat.Groups[1].Value));
                        }
                    }
                    else
                    {
                        if (line.StartsWith("Status:"))
                        {
                            AppendEncoderText(line);
                            //SetLog(line);
                        }
                    }
            }

            //обнуляем прогресс
            ResetProgress();

            //чистим ресурсы
            encoderProcess.Close();
            encoderProcess.Dispose();
            encoderProcess = null;

            if (IsAborted || IsErrors) return;

            //проверка на удачное завершение
            if (!File.Exists(m.outfilepath) || new FileInfo(m.outfilepath).Length == 0)
            {
                IsErrors = true;
                ErrorException(encodertext.ToString());
            }
            else
            {
                //Удаление лога муксера
                File.Delete(m.outfilepath + ".log");
            }

            encodertext.Length = 0;

            SetLog("");
        }
Beispiel #10
0
        public static Massive EncodeLine(Massive m)
        {
            string line = "";

            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            if (m.mp3_options.channelsmode == "Stereo")
            {
                line += "-m s ";
            }
            else if (m.mp3_options.channelsmode == "Joint Stereo")
            {
                line += "-m j ";
            }
            else if (m.mp3_options.channelsmode == "Forced Joint Stereo")
            {
                line += "-m f ";
            }
            else if (m.mp3_options.channelsmode == "Mono")
            {
                line += "-m m ";
            }

            if (m.mp3_options.encodingmode == Settings.AudioEncodingModes.ABR)
            {
                line += "--abr " + outstream.bitrate;

                if (m.mp3_options.minb != 32)
                {
                    line += " -b " + m.mp3_options.minb;
                }
                if (m.mp3_options.maxb != 320)
                {
                    line += " -B " + m.mp3_options.maxb;
                }
            }
            else if (m.mp3_options.encodingmode == Settings.AudioEncodingModes.VBR)
            {
                line += "-V " + m.mp3_options.quality;

                if (m.mp3_options.minb != 32)
                {
                    line += " -b " + m.mp3_options.minb;
                }
                if (m.mp3_options.maxb != 320)
                {
                    line += " -B " + m.mp3_options.maxb;
                }
            }
            else
            {
                line += "-b " + outstream.bitrate;
            }

            line += " -q " + m.mp3_options.encquality;

            if (m.mp3_options.replay_gain == 0)
            {
                line += " --noreplaygain";
            }
            else if (m.mp3_options.replay_gain == 2)
            {
                line += " --replaygain-accurate";
            }

            if (m.mp3_options.forcesamplerate)
            {
                line += " --resample ";
            }

            //забиваем данные в массив
            outstream.passes = line;

            return(m);
        }
Beispiel #11
0
        private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            //Выходим при отмене
            if (m == null || worker.CancellationPending)
            {
                return;
            }

            string script = "";

            try
            {
                string ext = Path.GetExtension(m.infilepath).ToLower();

                //получаем инфу из простого avs
                script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.Info);

                reader = new AviSynthReader(AviSynthColorspace.RGB24, AudioSampleType.INT16);
                reader.ParseScript(script);

                //Выходим при отмене
                if (m == null || worker.CancellationPending)
                {
                    return;
                }

                //Видео
                if (!only_audio)
                {
                    if (reader.Framerate != Double.PositiveInfinity && reader.Framerate != 0.0)
                    {
                        m.induration  = TimeSpan.FromSeconds((double)reader.FrameCount / reader.Framerate);
                        m.outduration = m.induration;
                        m.inframes    = reader.FrameCount;
                        if (string.IsNullOrEmpty(m.inframerate))
                        {
                            m.inframerate = Calculate.ConvertDoubleToPointString(reader.Framerate);
                        }
                    }

                    if (m.isvideo && ext != ".avs" && (reader.Width == 0 || reader.Height == 0))
                    {
                        throw new Exception(m.vdecoder.ToString() + " can't decode video (zero-size image was returned)!");
                    }
                    else if ((m.vdecoder == AviSynthScripting.Decoders.LSMASHVideoSource || m.vdecoder == AviSynthScripting.Decoders.LWLibavVideoSource) && //16 - допуск на паддинг и т.д.
                             string.IsNullOrEmpty(m.disable_hacked_vout) && ((Math.Abs(reader.Width / 2 - m.inresw) < 16) || (Math.Abs(reader.Height / 2 - m.inresh)) < 16))
                    {
                        //LSMASH декодирует многобитное видео с удвоением ширины\высоты, пока-что это не поддерживается
                        m.disable_hacked_vout = Calculate.GetLSMASHFormat8(reader.Clip.OriginalColorspace);
                        throw new Exception("Hacked output");
                    }
                    else
                    {
                        m.inresw = reader.Width;
                        m.inresh = reader.Height;

                        if (m.inaspect == 0 || double.IsNaN(m.inaspect))
                        {
                            m.inaspect = (double)m.inresw / (double)m.inresh;
                        }

                        if (ext == ".avs")
                        {
                            //Такое можно получить видимо только вписав в скрипт KillVideo()\KillAudio()
                            if ((reader.Width == 0 || reader.Height == 0) && reader.Samplerate == 0)
                            {
                                throw new Exception("An empty script (no video and no audio)!");
                            }

                            //Считываем SAR из скрипта
                            m.pixelaspect = reader.GetVarFloat("OUT_SAR_X", 1) / reader.GetVarFloat("OUT_SAR_Y", 1);
                        }
                    }
                }

                //Звук
                if (reader.Samplerate == 0)
                {
                    if (m.inaudiostreams.Count > 0 && Settings.EnableAudio || only_audio)
                    {
                        //похоже что звук не декодируется этим декодером
                        throw new Exception("Script doesn't contain audio!");
                    }
                }
                else
                {
                    //Определение продолжительности и числа кадров для audio-only файлов (т.е. без видео)
                    if (!m.isvideo && m.inframes == 0 && m.induration == TimeSpan.Zero)
                    {
                        m.induration = m.outduration = TimeSpan.FromSeconds(reader.SamplesCount / (double)reader.Samplerate);
                        m.inframes   = (int)(m.induration.TotalSeconds * ((!string.IsNullOrEmpty(m.inframerate)) ? Calculate.ConvertStringToDouble(m.inframerate) : 25));
                    }

                    AudioStream instream = (m.inaudiostreams.Count > 0) ? (AudioStream)m.inaudiostreams[m.inaudiostream] : new AudioStream();

                    if (instream.channels > 0)
                    {
                        //вероятно аудио декодер меняет количество каналов
                        if (instream.channels != reader.Channels)
                        {
                            instream.badmixing = true;
                        }
                    }
                    else
                    {
                        instream.channels = reader.Channels;
                    }

                    instream.samplerate = reader.Samplerate.ToString();
                    instream.bits       = reader.BitsPerSample;

                    if (m.inaudiostreams.Count > 0)
                    {
                        //Битрейт для PCM
                        if (instream.bitrate == 0 && (instream.codecshort == "PCM" || instream.codecshort == "LPCM"))
                        {
                            instream.bitrate = (reader.BitsPerSample * reader.Samplerate * reader.Channels) / 1000; //kbps
                        }
                    }
                    else if (ext == ".avs" && !only_audio)
                    {
                        //Звук из скрипта
                        instream.bitrate  = (reader.BitsPerSample * reader.Samplerate * reader.Channels) / 1000; //kbps
                        instream.codec    = instream.codecshort = "PCM";
                        instream.language = "Unknown";
                        m.inaudiostreams.Add(instream.Clone());
                    }
                }
            }
            catch (Exception ex)
            {
                if (worker != null && !worker.CancellationPending && m != null && num_closes == 0)
                {
                    //Ошибка
                    ex.HelpLink = script;
                    e.Result    = ex;

                    try
                    {
                        //записываем скрипт с ошибкой в файл
                        AviSynthScripting.WriteScriptToFile(script + "\r\n\r\n__END__\r\n\r\n   Error: " + ex.Message + "\r\n" + ex.StackTrace, "error");
                    }
                    catch (Exception) { }
                }
            }
            finally
            {
                CloseReader(true);
            }
        }
Beispiel #12
0
        public static Massive DecodeLine(Massive m)
        {
            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            //создаём свежий массив параметров Nero AAC
            m.aac_options = new aac_arguments();

            //берём пока что за основу последнюю строку
            string line = outstream.passes;

            string[] separator = new string[] { " " };
            string[] cli = line.Split(separator, StringSplitOptions.None);
            int      n = 0; bool auto = true;

            foreach (string value in cli)
            {
                if (value == "-2pass")
                {
                    m.aac_options.encodingmode = Settings.AudioEncodingModes.TwoPass;
                }
                else if (value == "-q")
                {
                    m.aac_options.encodingmode = Settings.AudioEncodingModes.VBR;
                    m.aac_options.quality      = Calculate.ConvertStringToDouble(cli[n + 1]);
                }
                else if (value == "-br" || value == "-cbr")
                {
                    if (m.aac_options.encodingmode != Settings.AudioEncodingModes.TwoPass)
                    {
                        if (value == "-br")
                        {
                            m.aac_options.encodingmode = Settings.AudioEncodingModes.ABR;
                        }
                        else
                        {
                            m.aac_options.encodingmode = Settings.AudioEncodingModes.CBR;
                        }
                    }
                    outstream.bitrate = Convert.ToInt32(cli[n + 1].Replace("000", ""));
                }
                else if (value == "-lc" || value == "-he" || value == "-hev2")
                {
                    auto = false;
                    if (value == "-lc")
                    {
                        m.aac_options.aacprofile = "AAC-LC";
                    }
                    else if (value == "-he")
                    {
                        m.aac_options.aacprofile = "AAC-HE";
                    }
                    else
                    {
                        m.aac_options.aacprofile = "AAC-HEv2";
                    }
                }
                else if (value == "-2passperiod")
                {
                    m.aac_options.period = Convert.ToInt32(cli[n + 1]);
                }

                if (auto)
                {
                    m.aac_options.aacprofile = "Auto";
                }
                n++;
            }

            return(m);
        }
Beispiel #13
0
        public void MuxStreams(Massive m)
        {
            //создаём новый файл
            using (FileStream target = new FileStream(m.outfilepath, FileMode.Create))
            {
                //создаём заголовок
                DPGHeader header = new DPGHeader();
                header.version      = version_id.DPG0;
                header.aoffset      = 36;
                header.frames       = m.outframes;
                header.fps          = (int)Calculate.ConvertStringToDouble(m.outframerate);
                header.vsize        = (int)new FileInfo(m.outvideofile).Length;
                header.pixel_format = pixel_format.RGB24;
                if (m.outaudiostreams.Count > 0)
                {
                    AudioStream a = (AudioStream)m.outaudiostreams[m.outaudiostream];
                    header.samplerate = Convert.ToInt32(a.samplerate);
                    header.asize      = (int)new FileInfo(a.audiopath).Length;
                    string aext = Path.GetExtension(a.audiopath).ToLower();

                    if (aext == ".mp2")
                    {
                        header.audio_id = audio_id.MP2;
                    }
                    if (aext == ".gsm" && a.channels == 1)
                    {
                        header.audio_id = audio_id.GSM1;
                    }
                    if (aext == ".gsm" && a.channels == 2)
                    {
                        header.audio_id = audio_id.GSM2;
                    }
                    if (aext == ".ogg")
                    {
                        header.audio_id = audio_id.OGG;
                    }
                }

                //пишем заголовок
                WriteHeader(target, header);

                //вычисляем процент
                long total = header.aoffset + header.asize + header.vsize;

                //пишем звук
                if (m.outaudiostreams.Count > 0)
                {
                    AudioStream a = (AudioStream)m.outaudiostreams[m.outaudiostream];
                    using (FileStream fs = File.OpenRead(a.audiopath))
                    {
                        byte[] buffer = new byte[16384];
                        int    bytesRead;
                        while (true)
                        {
                            //читаем
                            bytesRead = fs.Read(buffer, 0, buffer.Length);

                            //прогресс
                            double progress = ((double)target.Position / (double)total) * 100.0;
                            ProgressChanged(progress);

                            //файл закончился
                            if (bytesRead == 0)
                            {
                                break;
                            }

                            //пишем в новый файл
                            target.Write(buffer, 0, bytesRead);
                            fs.Flush();
                            target.Flush();
                        }
                    }
                }

                //пишем видео
                using (FileStream fs = File.OpenRead(m.outvideofile))
                {
                    byte[] buffer = new byte[16384];
                    int    bytesRead;
                    while (true)
                    {
                        //читаем
                        bytesRead = fs.Read(buffer, 0, buffer.Length);

                        //файл закончился
                        if (bytesRead == 0)
                        {
                            break;
                        }

                        //прогресс
                        double progress = ((double)target.Position / (double)total) * 100.0;
                        ProgressChanged(progress);

                        //пишем в файл
                        target.Write(buffer, 0, bytesRead);
                        fs.Flush();
                        target.Flush();
                    }
                }
            }
        }
Beispiel #14
0
        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();
        }
Beispiel #15
0
        private void button_remove_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            if (outstream.codec == "Copy" ||
                outstream.codec == "Disabled")
            {
                return;
            }

            if (combo_profile.Items.Count > 1)
            {
                UpdateMassive();

                Message mess = new Message(this);
                mess.ShowMessage(Languages.Translate("Do you realy want to remove profile") + " \"" + outstream.encoding + "\"?",
                                 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) + "\\audio\\" + outstream.encoding + ".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) + "\\audio", "*.txt"))
                        {
                            combo_profile.Items.Add(Path.GetFileNameWithoutExtension(file));
                        }
                    }
                    catch { }
                    if (oldm != null)
                    {
                        combo_profile.Items.Add("Disabled");
                    }
                    combo_profile.Items.Add("Copy");

                    //прописываем текущий пресет кодирования
                    if (last_num == 0)
                    {
                        //Самый первый пресет (кроме "Disabled")
                        outstream.encoding = combo_profile.Items[0].ToString();
                        if (outstream.encoding == "Disabled")
                        {
                            outstream.encoding = "Copy";
                        }
                    }
                    else
                    {
                        //Предыдущий (перед удалённым) пресет
                        outstream.encoding = combo_profile.Items[last_num - 1].ToString();
                    }
                    combo_profile.SelectedItem = outstream.encoding;
                    combo_profile.UpdateLayout();

                    RefreshCodecProfileWindow();

                    UpdateOutSize();
                    UpdateCodecMassive();
                    LoadProfileToCodec();

                    //проверяем можно ли копировать данный формат
                    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"));
                        }
                    }
                }
            }
            else
            {
                new Message(this).ShowMessage(Languages.Translate("Not allowed removing the last profile!"), Languages.Translate("Warning"), Message.MessageStyle.Ok);
            }
        }
Beispiel #16
0
        private void LoadProfileToCodec()
        {
            //записываем профиль в реестр
            Settings.SetAEncodingPreset(m.format, combo_profile.SelectedItem.ToString());

            m = Format.GetValidChannelsConverter(m);
            m = Format.GetValidChannels(m);
            m = Format.GetValidSamplerate(m);
            m = Format.GetValidBits(m);

            if (aac != null)
            {
                AudioStream outstream = (AudioStream)aac.m.outaudiostreams[aac.m.outaudiostream];
                //забиваем настройки из профиля
                outstream.encoding = combo_profile.SelectedItem.ToString();
                outstream.codec    = PresetLoader.GetACodec(aac.m.format, outstream.encoding);
                outstream.passes   = PresetLoader.GetACodecPasses(aac.m);
                aac.m = PresetLoader.DecodePresets(aac.m);
                aac.LoadFromProfile();
            }
            else if (qaac != null)
            {
                AudioStream outstream = (AudioStream)qaac.m.outaudiostreams[qaac.m.outaudiostream];
                //забиваем настройки из профиля
                outstream.encoding = combo_profile.SelectedItem.ToString();
                outstream.codec    = PresetLoader.GetACodec(qaac.m.format, outstream.encoding);
                outstream.passes   = PresetLoader.GetACodecPasses(qaac.m);
                qaac.m             = PresetLoader.DecodePresets(qaac.m);
                qaac.LoadFromProfile();
            }
            else if (mp3 != null)
            {
                AudioStream outstream = (AudioStream)mp3.m.outaudiostreams[mp3.m.outaudiostream];
                //забиваем настройки из профиля
                outstream.encoding = combo_profile.SelectedItem.ToString();
                outstream.codec    = PresetLoader.GetACodec(mp3.m.format, outstream.encoding);
                outstream.passes   = PresetLoader.GetACodecPasses(mp3.m);
                mp3.m = PresetLoader.DecodePresets(mp3.m);
                mp3.LoadFromProfile();
            }
            else if (ac3 != null)
            {
                AudioStream outstream = (AudioStream)ac3.m.outaudiostreams[ac3.m.outaudiostream];
                //забиваем настройки из профиля
                outstream.encoding = combo_profile.SelectedItem.ToString();
                outstream.codec    = PresetLoader.GetACodec(ac3.m.format, outstream.encoding);
                outstream.passes   = PresetLoader.GetACodecPasses(ac3.m);
                ac3.m = PresetLoader.DecodePresets(ac3.m);
                ac3.LoadFromProfile();
            }
            else if (fmp2 != null)
            {
                AudioStream outstream = (AudioStream)fmp2.m.outaudiostreams[fmp2.m.outaudiostream];
                //забиваем настройки из профиля
                outstream.encoding = combo_profile.SelectedItem.ToString();
                outstream.codec    = PresetLoader.GetACodec(fmp2.m.format, outstream.encoding);
                outstream.passes   = PresetLoader.GetACodecPasses(fmp2.m);
                fmp2.m             = PresetLoader.DecodePresets(fmp2.m);
                fmp2.LoadFromProfile();
            }
            else if (fpcm != null)
            {
                AudioStream outstream = (AudioStream)fpcm.m.outaudiostreams[fpcm.m.outaudiostream];
                //забиваем настройки из профиля
                outstream.encoding = combo_profile.SelectedItem.ToString();
                outstream.codec    = PresetLoader.GetACodec(fpcm.m.format, outstream.encoding);
                outstream.passes   = PresetLoader.GetACodecPasses(fpcm.m);
                fpcm.m             = PresetLoader.DecodePresets(fpcm.m);
                fpcm.LoadFromProfile();
            }
            else if (flpcm != null)
            {
                AudioStream outstream = (AudioStream)flpcm.m.outaudiostreams[flpcm.m.outaudiostream];
                //забиваем настройки из профиля
                outstream.encoding = combo_profile.SelectedItem.ToString();
                outstream.codec    = PresetLoader.GetACodec(flpcm.m.format, outstream.encoding);
                outstream.passes   = PresetLoader.GetACodecPasses(flpcm.m);
                flpcm.m            = PresetLoader.DecodePresets(flpcm.m);
                flpcm.LoadFromProfile();
            }
            else if (fflac != null)
            {
                AudioStream outstream = (AudioStream)fflac.m.outaudiostreams[fflac.m.outaudiostream];
                //забиваем настройки из профиля
                outstream.encoding = combo_profile.SelectedItem.ToString();
                outstream.codec    = PresetLoader.GetACodec(fflac.m.format, outstream.encoding);
                outstream.passes   = PresetLoader.GetACodecPasses(fflac.m);
                fflac.m            = PresetLoader.DecodePresets(fflac.m);
                fflac.LoadFromProfile();
            }
        }
Beispiel #17
0
        private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                string ext = Path.GetExtension((m.infilepath_source != null) ? m.infilepath_source : m.infilepath).ToLower();
                if (ext != ".avs" && ext != ".grf" && ext != ".d2v" && ext != ".dga" && ext != ".dgi")
                {
                    //забиваем максимум параметров файла
                    MediaInfoWrapper media = new MediaInfoWrapper();
                    media.Open(m.infilepath);

                    //Выходим при отмене
                    if (m == null || worker.CancellationPending)
                    {
                        return;
                    }

                    m.invcodec      = media.VCodecString;
                    m.invcodecshort = media.VCodecShort;
                    m.invbitrate    = media.VideoBitrate;
                    m.inresw        = media.Width;
                    m.inresh        = media.Height;
                    m.inaspect      = media.Aspect;
                    //m.pixelaspect = (m.inresw != 0 && m.inresh != 0) ? (m.inaspect / ((double)m.inresw / (double)m.inresh)) : 1.0;
                    m.pixelaspect            = media.PixelAspect;
                    m.invideostream_mi_id    = media.VTrackID();
                    m.invideostream_mi_order = media.VTrackOrder();
                    m.inframerate            = media.FrameRate;
                    m.induration             = TimeSpan.FromMilliseconds(media.Milliseconds);
                    m.outduration            = m.induration;
                    m.interlace      = media.Interlace;
                    m.interlace_raw  = media.ScanType;
                    m.fieldOrder_raw = media.ScanOrder;
                    m.inframes       = media.Frames;

                    //Возвращаем 29фпс для видео с пуллдауном, т.к. MediaInfo выдает для него 23фпс, а MPEG2Source\DGSource
                    //без ForceFilm из-за пуллдауна будет декодировать с 29-ю. Продолжительность пересчитывается в Caching.
                    if (m.vdecoder == AviSynthScripting.Decoders.MPEG2Source || m.vdecoder == AviSynthScripting.Decoders.DGSource)
                    {
                        if (media.ScanOrder.Contains("Pulldown") && m.inframerate == "23.976" && !m.IsForcedFilm)
                        {
                            m.inframerate = "29.970";
                            m.interlace   = SourceType.FILM;
                        }
                        else if (m.IsForcedFilm)
                        {
                            m.inframerate = "23.976";
                            m.interlace   = SourceType.UNKNOWN;
                        }
                    }

                    //забиваем аудио потоки
                    if (ext == ".pmp" && Settings.EnableAudio)
                    {
                        AudioStream stream = new AudioStream();
                        stream.codec      = "AAC";
                        stream.codecshort = "AAC";
                        stream.samplerate = "44100";
                        stream.bits       = 16;
                        stream.channels   = 2;
                        stream.language   = "English";
                        m.inaudiostreams.Add(stream.Clone());
                        m.inaudiostream = 0;
                    }
                    else if (ext == ".dpg")
                    {
                        dpgmuxer           dpg    = new dpgmuxer();
                        dpgmuxer.DPGHeader header = dpg.ReadHeader(m.infilepath_source);
                        m.inframes    = header.frames;
                        m.inframerate = Calculate.ConvertDoubleToPointString((double)header.fps);
                        m.induration  = TimeSpan.FromSeconds((double)header.frames / (double)header.fps);
                        m.outduration = m.induration;

                        if (m.inaudiostreams.Count > 0 && Settings.EnableAudio)
                        {
                            AudioStream stream = (AudioStream)m.inaudiostreams[m.inaudiostream];
                            //забиваем в список все найденные треки
                            MediaInfoWrapper mi = new MediaInfoWrapper();
                            stream            = mi.GetAudioInfoFromAFile(stream.audiopath, true);
                            stream.samplerate = header.samplerate.ToString();
                            m.inaudiostreams[m.inaudiostream] = stream;
                        }
                    }
                    else if (ext == ".cda")
                    {
                        AudioStream stream = new AudioStream();
                        stream.codec      = "CDDA";
                        stream.codecshort = "CDDA";
                        //stream.bitrate = media.AudioBitrate(snum);
                        //stream.mkvid = media.AudioID(snum);
                        //stream.samplerate = media.Samplerate(snum);
                        //stream.bits = media.Bits(snum);
                        //stream.channels = media.Channels(snum);
                        stream.language = "English";

                        m.isvideo         = false;
                        stream.audiopath  = m.infilepath;
                        stream.audiofiles = new string[] { stream.audiopath };
                        stream            = Format.GetValidADecoder(stream);

                        m.inaudiostreams.Add(stream.Clone());
                    }
                    else if (m.indexfile != null && File.Exists(m.indexfile) && Settings.EnableAudio)
                    {
                        int       n       = 0;
                        ArrayList atracks = Indexing.GetTracks(m.indexfile);
                        foreach (string apath in atracks)
                        {
                            //определяем аудио потоки
                            AudioStream stream = new AudioStream();

                            //забиваем в список все найденные треки
                            MediaInfoWrapper mi = new MediaInfoWrapper();
                            stream           = mi.GetAudioInfoFromAFile(apath, true);
                            stream.audiopath = apath;
                            stream.delay     = Calculate.GetDelay(apath);
                            stream           = Format.GetValidADecoder(stream);

                            stream.mi_id    = media.ATrackID(n);
                            stream.mi_order = media.ATrackOrder(n);

                            m.inaudiostreams.Add(stream.Clone());
                            n++;
                        }
                        m.inaudiostream = 0;
                    }
                    else
                    {
                        if (Settings.EnableAudio || media.CountVideoStreams == 0)
                        {
                            for (int snum = 0; snum < media.CountAudioStreams; snum++)
                            {
                                AudioStream stream = new AudioStream();
                                stream.codec      = media.ACodecString(snum);
                                stream.codecshort = media.ACodecShort(snum);
                                stream.bitrate    = media.AudioBitrate(snum);
                                stream.mi_id      = media.ATrackID(snum);
                                stream.mi_order   = media.ATrackOrder(snum);
                                stream.samplerate = media.Samplerate(snum);
                                stream.bits       = media.Bits(snum);
                                stream.channels   = media.Channels(snum);
                                if (m.indexfile == null)
                                {
                                    stream.delay = media.Delay(snum);
                                }
                                stream.language = media.AudioLanguage(snum);

                                //вероятно звуковой файл
                                if (media.CountVideoStreams == 0)
                                {
                                    m.isvideo         = false;
                                    stream.audiopath  = m.infilepath;
                                    stream.audiofiles = new string[] { stream.audiopath };
                                    stream            = Format.GetValidADecoder(stream);
                                }

                                m.inaudiostreams.Add(stream.Clone());
                            }
                            //делаем первый трек активным
                            m.inaudiostream = 0;
                        }

                        //довбиваем duration и frames для join заданий
                        if (m.infileslist.Length > 1)
                        {
                            TimeSpan ts = TimeSpan.Zero;
                            foreach (string file in m.infileslist)
                            {
                                MediaInfoWrapper med = new MediaInfoWrapper();
                                med.Open(file);
                                ts += med.Duration;
                                med.Close();
                            }
                            m.induration  = ts;
                            m.outduration = m.induration;
                            m.inframes    = (int)(m.induration.TotalSeconds * Calculate.ConvertStringToDouble(m.inframerate));
                        }
                    }

                    //довбиваем параметры из IFO
                    string ifo = Calculate.GetIFO(m.infilepath);
                    if (File.Exists(ifo))
                    {
                        //через MediaInfo
                        media.Close();
                        media.Open(ifo);
                        int n = 0;
                        foreach (AudioStream stream in m.inaudiostreams)
                        {
                            stream.language = media.AudioLanguage(n);
                            n++;
                        }

                        //через VStrip
                        VStripWrapper vs = new VStripWrapper();
                        vs.Open(ifo);
                        m.induration  = vs.Duration();
                        m.outduration = m.induration;
                        m.inframes    = (int)(m.induration.TotalSeconds * Calculate.ConvertStringToDouble(m.inframerate));
                        vs.Close();

                        #region Язык через VStrip:
                        //iifo_lang_tbl[] parse_ifo.c (The ISO 639 language codes)
                        //??? (AC3 2ch, 0xBD 0x80) [0,1] //MI - "Unknown"
                        //Italiano (AC3 2ch, 0xBD 0x82) [0,1]" //MI - "Italian", есть и др. несоответствия..
                        //Russian (AC3 2ch, 0xBD 0x80) [0,1]"
                        #endregion
                    }

                    //закрываем MediaInfo
                    media.Close();
                }

                if (ext == ".grf" || ext == ".d2v" || ext == ".dga" || ext == ".dgi")
                {
                    #region grf, d2v, dga, dgi
                    if (ext == ".grf")
                    {
                        string infile = Path.GetFileNameWithoutExtension(m.infilepath).ToLower();
                        if (infile.StartsWith("audio"))
                        {
                            //Это аудио-граф
                            m.isvideo = false;

                            AudioStream stream = new AudioStream();
                            stream.audiopath  = m.infilepath;
                            stream.audiofiles = new string[] { stream.audiopath };
                            stream.codec      = stream.codecshort = "PCM";
                            stream.language   = "Unknown";
                            stream            = Format.GetValidADecoder(stream);
                            m.inaudiostreams.Add(stream.Clone());
                        }
                        else
                        {
                            //Это видео-граф
                            m.invcodec      = "RAWVIDEO";
                            m.invcodecshort = "RAWVIDEO";

                            //Если DirectShowSource не сможет определить fps, то требуемое значение можно будет указать в имени файла..
                            Regex r   = new Regex(@"(fps\s?=\s?([\d\.\,]*))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Match mat = r.Match(infile);
                            if (mat.Success)
                            {
                                double fps = Calculate.ConvertStringToDouble(mat.Groups[2].Value);
                                if (fps > 0)
                                {
                                    m.inframerate = Calculate.ConvertDoubleToPointString(fps);
                                }

                                //"Очищаем" имя файла
                                infile = infile.Replace(mat.Groups[1].Value, "").Trim(new char[] { ' ', '_', '-', '(', ')', '.', ',' });
                            }

                            //Ищем звук к нему
                            if (Settings.EnableAudio)
                            {
                                //Почему на шаблон "audio*.grf" находятся и файлы типа "Копия audio file.grf"?!
                                string[] afiles = Directory.GetFiles(Path.GetDirectoryName(m.infilepath), "audio*.grf");
                                foreach (string afile in afiles)
                                {
                                    string aname = Path.GetFileNameWithoutExtension(afile).ToLower();
                                    if (aname.StartsWith("audio") && aname.Contains(infile))
                                    {
                                        AudioStream stream = new AudioStream();
                                        stream.audiopath  = afile;
                                        stream.audiofiles = new string[] { stream.audiopath };
                                        stream.codec      = stream.codecshort = "PCM";
                                        stream.language   = "Unknown";
                                        stream            = Format.GetValidADecoder(stream);
                                        m.inaudiostreams.Add(stream.Clone());
                                        break; //Только один трек
                                    }
                                }
                            }
                        }
                    }
                    else if (ext == ".d2v")
                    {
                        //Читаем d2v-файл
                        int    n    = 0;
                        string line = "";
                        Match  mat1;
                        Match  mat2;
                        Regex  r1 = new Regex(@"Picture_Size=(\d+)x(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                        Regex  r2 = new Regex(@"Aspect_Ratio=(\d+\.*\d*):(\d+\.*\d*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                        int    result1 = 720; int result2 = 576; double result3 = 4; double result4 = 3; //Значения по-умолчанию
                        using (StreamReader sr = new StreamReader(m.indexfile, System.Text.Encoding.Default))
                            while (!sr.EndOfStream && n < 15)                                            //Ограничиваемся первыми 15-ю строчками
                            {
                                line = sr.ReadLine();
                                mat1 = r1.Match(line);
                                mat2 = r2.Match(line);
                                if (mat1.Success)
                                {
                                    result1 = Convert.ToInt32(mat1.Groups[1].Value);
                                    result2 = Convert.ToInt32(mat1.Groups[2].Value);
                                }
                                if (mat2.Success)
                                {
                                    result3 = Calculate.ConvertStringToDouble(mat2.Groups[1].Value);
                                    result4 = Calculate.ConvertStringToDouble(mat2.Groups[2].Value);
                                }
                                n += 1;
                            }
                        m.inresw        = result1;
                        m.inresh        = result2;
                        m.inaspect      = result3 / result4;
                        m.pixelaspect   = m.inaspect / ((double)m.inresw / (double)m.inresh);
                        m.invcodecshort = "MPEG2";
                    }
                    else if (ext == ".dga")
                    {
                        //Смотрим, на месте ли log-файл
                        string log_file = Calculate.RemoveExtention(m.infilepath) + "log";
                        if (File.Exists(log_file))
                        {
                            //Читаем log-файл
                            string text_log = "";
                            Match  mat;
                            Regex  r1 = new Regex(@"Frame.Size:.(\d+)x(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Regex  r2 = new Regex(@"SAR:.(\d+):(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            int    result1 = 1280; int result2 = 720; double result3 = 1; double result4 = 1; //Значения по-умолчанию
                            using (StreamReader sr = new StreamReader(log_file, System.Text.Encoding.Default))
                                text_log = sr.ReadToEnd();

                            mat = r1.Match(text_log);
                            if (mat.Success)
                            {
                                result1 = Convert.ToInt32(mat.Groups[1].Value);
                                result2 = Convert.ToInt32(mat.Groups[2].Value);
                            }
                            mat = r2.Match(text_log);
                            if (mat.Success)
                            {
                                result3 = Convert.ToDouble(mat.Groups[1].Value);
                                result4 = Convert.ToDouble(mat.Groups[2].Value);
                            }

                            m.inresw      = result1;
                            m.inresh      = result2;
                            m.inaspect    = (result3 / result4) * ((double)m.inresw / (double)m.inresh);
                            m.pixelaspect = m.inaspect / ((double)m.inresw / (double)m.inresh);
                            //можно еще определить тут фпс, но всё-равно это будет сделано позже через ависинт-скрипт (class Caching).
                            m.invcodecshort = "h264";
                        }
                        else
                        {
                            //Если нет log-файла, ищем исходный файл и берем инфу из него
                            Match  mat;
                            string source_file = "";
                            Regex  r           = new Regex(@"(\D:\\.*\..*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            using (StreamReader sr = new StreamReader(m.indexfile, System.Text.Encoding.Default))
                                for (int i = 0; i < 3 && !sr.EndOfStream; i += 1)
                                {
                                    source_file = sr.ReadLine();
                                }
                            mat = r.Match(source_file);
                            if (mat.Success && File.Exists(source_file = mat.Groups[1].Value))
                            {
                                MediaInfoWrapper media = new MediaInfoWrapper();
                                media.Open(source_file);
                                m.invcodecshort = media.VCodecShort;
                                m.inresw        = media.Width;
                                m.inresh        = media.Height;
                                m.inaspect      = media.Aspect;
                                m.pixelaspect   = media.PixelAspect;
                                media.Close();
                            }
                            else
                            {
                                throw new Exception(Languages.Translate("Can`t find DGAVCIndex log-file:") + " " + log_file +
                                                    "\r\n" + Languages.Translate("And can`t determine the source-file."));
                            }
                        }
                    }
                    else if (ext == ".dgi")
                    {
                        //Путь к декодеру
                        using (StreamReader sr = new StreamReader(m.indexfile, System.Text.Encoding.Default))
                            for (int i = 0; i < 2 && !sr.EndOfStream; i += 1)
                            {
                                m.dgdecnv_path = sr.ReadLine();
                            }
                        if (!File.Exists(m.dgdecnv_path + "DGDecodeNV.dll"))
                        {
                            throw new Exception(Languages.Translate("Can`t find file") + ": " + m.dgdecnv_path + "DGDecodeNV.dll");
                        }

                        //Смотрим, на месте ли log-файл
                        string log_file = Calculate.RemoveExtention(m.infilepath) + "log";
                        if (File.Exists(log_file))
                        {
                            //Читаем log-файл
                            Match  mat;
                            string text_log = "";
                            Regex  r1 = new Regex(@"Coded.Size:.(\d+)x(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Regex  r2 = new Regex(@"SAR:.(\d+):(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Regex  r3 = new Regex(@"Aspect.Ratio:.(\d+\.*\d*):(\d+\.*\d*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Regex  r4 = new Regex(@"Video.Type:.(.*).", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            double result1, result2;
                            text_log = File.ReadAllText(log_file, System.Text.Encoding.Default);

                            //Разрешение (Coded Size:)
                            mat = r1.Match(text_log);
                            if (mat.Success)
                            {
                                m.inresw = Convert.ToInt32(mat.Groups[1].Value);
                                m.inresh = Convert.ToInt32(mat.Groups[2].Value);

                                //Аспект (SAR:)
                                mat = r2.Match(text_log);
                                if (mat.Success)
                                {
                                    result1 = Convert.ToDouble(mat.Groups[1].Value);
                                    result2 = Convert.ToDouble(mat.Groups[2].Value);

                                    m.inaspect    = (result1 / result2) * ((double)m.inresw / (double)m.inresh);
                                    m.pixelaspect = result1 / result2;
                                }
                                else
                                {
                                    //Аспект (Aspect Ratio:)
                                    mat = r3.Match(text_log);
                                    if (mat.Success)
                                    {
                                        result1 = Calculate.ConvertStringToDouble(mat.Groups[1].Value);
                                        result2 = Calculate.ConvertStringToDouble(mat.Groups[2].Value);

                                        m.inaspect    = result1 / result2;
                                        m.pixelaspect = m.inaspect / ((double)m.inresw / (double)m.inresh);
                                    }
                                    else
                                    {
                                        m.inaspect    = (double)m.inresw / (double)m.inresh;
                                        m.pixelaspect = 1.0;
                                    }
                                }
                            }
                            else
                            {
                                m.inaspect    = 16.0 / 9.0;
                                m.pixelaspect = 1.0;
                            }

                            //Кодек
                            mat = r4.Match(text_log);
                            if (mat.Success)
                            {
                                string codec = mat.Groups[1].Value;
                                if (codec == "AVC")
                                {
                                    codec = "h264";
                                }
                                m.invcodecshort = codec;
                            }
                        }
                        else
                        {
                            //Если нет log-файла, ищем исходный файл и берем инфу из него
                            string source_file = "";
                            Regex  r           = new Regex(@"(\D:\\.*\..*)\s\d+", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            using (StreamReader sr = new StreamReader(m.indexfile, System.Text.Encoding.Default))
                                for (int i = 0; i < 4 && !sr.EndOfStream; i += 1)
                                {
                                    source_file = sr.ReadLine();
                                }
                            Match mat = r.Match(source_file);
                            if (mat.Success && File.Exists(source_file = mat.Groups[1].Value))
                            {
                                MediaInfoWrapper media = new MediaInfoWrapper();
                                media.Open(source_file);
                                m.invcodecshort = media.VCodecShort;
                                m.inresw        = media.Width;
                                m.inresh        = media.Height;
                                m.inaspect      = media.Aspect;
                                m.pixelaspect   = media.PixelAspect;
                                media.Close();
                            }
                            else
                            {
                                throw new Exception(Languages.Translate("Can`t find DGIndexNV log-file:") + " " + log_file +
                                                    "\r\n" + Languages.Translate("And can`t determine the source-file."));
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    //Довбиваем параметры с помощью FFmpeg
                    ff = new FFInfo();
                    ff.Open(m.infilepath);

                    //Выходим при отмене
                    if (m == null || worker.CancellationPending)
                    {
                        return;
                    }

                    //Видео
                    if (ff.VideoStreams().Count > 0)
                    {
                        m.invideostream_ff_order          = ff.FirstVideoStreamID();
                        m.invideostream_ff_order_filtered = ff.FilteredStreamOrder(m.invideostream_ff_order);
                        if (m.invideostream_mi_order < 0)
                        {
                            m.invideostream_mi_order = m.invideostream_ff_order;
                        }

                        if (ext == ".avs")
                        {
                            m.invcodec      = ff.StreamCodec(m.invideostream_ff_order);
                            m.invcodecshort = ff.StreamCodecShort(m.invideostream_ff_order);
                            m.invbitrate    = ff.VideoBitrate(m.invideostream_ff_order);
                            m.inresw        = ff.StreamW(m.invideostream_ff_order);
                            m.inresh        = ff.StreamH(m.invideostream_ff_order);
                            m.inaspect      = (double)m.inresw / (double)m.inresh;
                        }
                        else
                        {
                            //Через MI нашелся только звук, но у FFmpeg есть и видео
                            if (!m.isvideo)
                            {
                                if (ext != ".cda")
                                {
                                    m.isvideo       = true;
                                    m.invcodec      = ff.StreamCodec(m.invideostream_ff_order);
                                    m.invcodecshort = ff.StreamCodecShort(m.invideostream_ff_order);
                                    m.invbitrate    = ff.VideoBitrate(m.invideostream_ff_order);
                                    m.inresw        = ff.StreamW(m.invideostream_ff_order);
                                    m.inresh        = ff.StreamH(m.invideostream_ff_order);

                                    double sar = ff.CalculateSAR(m.invideostream_ff_order);
                                    m.pixelaspect = (sar != 0) ? sar : 1.0;
                                    double dar = ff.CalculateDAR(m.invideostream_ff_order);
                                    m.inaspect = (dar != 0) ? dar : ((double)m.inresw / (double)m.inresh);

                                    //Обнуляем аудио пути (там сейчас вписан сам исходник и декодер под его расширение)
                                    foreach (AudioStream stream in m.inaudiostreams)
                                    {
                                        stream.audiopath  = null;
                                        stream.audiofiles = null;
                                        stream.decoder    = 0;
                                    }
                                }
                            }
                            else if (Settings.UseFFmpegAR)
                            {
                                double sar = ff.CalculateSAR(m.invideostream_ff_order);
                                if (sar != 0)
                                {
                                    m.pixelaspect = sar;
                                }
                                double dar = ff.CalculateDAR(m.invideostream_ff_order);
                                if (dar != 0)
                                {
                                    m.inaspect = dar;
                                }
                            }
                        }

                        //null - MediaInfo для этого файла не запускалась (avs, grf,..)
                        //"" - MediaInfo запускалась, но нужной инфы получить не удалось
                        //При null тут все-же можно определить fps для avs, но т.к. FFmpeg
                        //сильно округляет fps, то лучше сами позже определим его в Caching().
                        if (m.inframerate == "")
                        {
                            m.inframerate = ff.StreamFramerate(m.invideostream_ff_order);
                            if (m.inframerate != "")
                            {
                                m.induration  = ff.Duration();
                                m.outduration = m.induration;
                                m.inframes    = (int)(m.induration.TotalSeconds * Calculate.ConvertStringToDouble(m.inframerate));
                            }
                        }
                    }

                    //Аудио
                    if (ff.AudioStreams().Count > 0)
                    {
                        ArrayList AStreams      = ff.AudioStreams();
                        ArrayList AStreams_done = new ArrayList();

                        //подправляем кодек, ffID, язык
                        //Это будет работать как надо, только если очерёдность наших треков
                        //совпадает с их очерёдностью в FFmpeg, иначе инфа о треках перепутается!
                        int astream = 0;
                        foreach (AudioStream stream in m.inaudiostreams)
                        {
                            stream.ff_order          = (int)AStreams[astream]; //ID трека для FFmpeg
                            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);
                            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);
                            }

                            AStreams_done.Add(AStreams[astream]);

                            astream++;
                            if (astream >= AStreams.Count)
                            {
                                break;
                            }
                        }

                        //Удаляем все FF-треки, инфа от которых уже взята
                        foreach (object obj in AStreams_done)
                        {
                            AStreams.Remove(obj);
                        }

                        //Еще раз перепроверка для звуковых файлов (файл без видео), если
                        //выше через MI это не отловилось (т.е. через MI звук не обнаружился)
                        bool is_audio_only = (m.isvideo && string.IsNullOrEmpty(m.inframerate) && string.IsNullOrEmpty(m.invcodec) && (m.inresw == 0 || m.inresh == 0) && ff.VideoStreams().Count == 0);

                        if ((m.indexfile == null && Settings.EnableAudio || ext == ".avs" || is_audio_only) && AStreams.Count > 0)
                        {
                            //забиваем аудио, если они ещё не забиты (если FF-треков осталось больше, чем у нас уже есть)
                            //Все оставшиеся треки от FFmpeg добавляются к уже имеющимся. Тут тоже нужно как-то
                            //сопоставлять треки, и объединить это всё с кодом, который выше!
                            foreach (int stream_num in AStreams)
                            {
                                AudioStream stream = new AudioStream();
                                stream.ff_bits           = ff.StreamBits(stream_num);
                                stream.ff_codec          = stream.codec = ff.StreamCodec(stream_num);
                                stream.codecshort        = ff.StreamCodecShort(stream_num);
                                stream.bitrate           = ff.AudioBitrate(stream_num);
                                stream.samplerate        = ff.StreamSamplerate(stream_num);
                                stream.bits              = ff.StreamBits(stream_num);
                                stream.channels          = ff.StreamChannels(stream_num);
                                stream.language          = ff.StreamLanguage(stream_num);
                                stream.mi_order          = stream.ff_order = stream_num;
                                stream.ff_order_filtered = ff.FilteredStreamOrder(stream_num);

                                if (is_audio_only)
                                {
                                    m.isvideo         = false;
                                    stream.audiopath  = m.infilepath;
                                    stream.audiofiles = new string[] { stream.audiopath };
                                    stream            = Format.GetValidADecoder(stream);
                                }

                                m.inaudiostreams.Add(stream.Clone());
                            }

                            m.inaudiostream = 0;
                        }
                    }

                    //Закрываем FFInfo
                    CloseFFInfo();
                }

                if (!m.isvideo)
                {
                    m.invcodec    = m.invcodecshort = "NONE";
                    m.inframerate = m.outframerate = "25.000";
                    m.vdecoder    = AviSynthScripting.Decoders.BlankClip;

                    //Кол-во кадров и продолжительность определятся в Caching()
                    //на основе реальной продолжительности звука от декодера
                    m.induration = m.outduration = TimeSpan.Zero;
                    m.inframes   = m.outframes = 0;
                }

                //определяем аудио декодер
                foreach (AudioStream stream in m.inaudiostreams)
                {
                    if (stream.decoder == 0)
                    {
                        stream.decoder = Format.GetValidADecoder(stream).decoder;
                    }
                }

                //подсчитываем размер
                long sizeb = 0;
                foreach (string f in m.infileslist)
                {
                    FileInfo info = new FileInfo(f);
                    sizeb += info.Length;
                }
                m.infilesize    = Calculate.ConvertDoubleToPointString((double)sizeb / 1049511, 1) + " mb";
                m.infilesizeint = (int)((double)sizeb / 1049511);
            }
            catch (Exception ex)
            {
                if (worker != null && !worker.CancellationPending && m != null && num_closes == 0)
                {
                    //Ошибка
                    e.Result = ex;
                }

                m = null;
            }
        }
Beispiel #18
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();
            }
        }
Beispiel #19
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;
        }
Beispiel #20
0
        public AudioStream GetAudioInfoFromAFile(string filepath, bool and_close_mi)
        {
            AudioStream stream = new AudioStream();
            Open(filepath);

            stream.audiopath = filepath;
            stream.audiofiles = new string[] { stream.audiopath };
            stream.codec = ACodecString(0);
            stream.codecshort = ACodecShort(0);
            stream.language = AudioLanguage(0);
            stream.bitrate = AudioBitrate(0);
            stream.samplerate = Samplerate(0);
            stream.channels = Channels(0);
            stream.bits = Bits(0);
            stream.delay = 0;

            //определяем битрейт
            if (stream.bitrate == 0)
            {
                if (!File.Exists(filepath) || Duration.TotalSeconds == 0)
                    stream.bitrate = (stream.bits * Convert.ToInt32(stream.samplerate) * stream.channels) / 1000; //kbps
                else
                {
                    FileInfo info = new FileInfo(filepath);
                    stream.bitrate = (int)(((info.Length / Duration.TotalSeconds) * stream.bits) / stream.channels) / 1000; //kbps
                }
            }

            if (and_close_mi)
                Close();

            return stream;
        }
Beispiel #21
0
        private Massive FillAudio(Massive mass)
        {
            //передаём активный трек на выход
            if (mass.inaudiostreams.Count > 0)
            {
                //if (mass.outaudiostreams.Count == 0)
                //{
                AudioStream stream = new AudioStream();
                mass.outaudiostreams.Clear();
                AudioStream instream = (AudioStream)mass.inaudiostreams[mass.inaudiostream];
                if (Settings.ApplyDelay) stream.delay = instream.delay;
                mass.outaudiostreams.Add(stream);
                //}

                AudioStream outstream = (AudioStream)mass.outaudiostreams[mass.outaudiostream];

                //Клонируем звуковые параметры от предыдущего файла
                if (IsBatchOpening && m != null && Settings.BatchCloneAudio)
                {
                    if (m.outaudiostreams.Count > 0)
                    {
                        AudioStream old_outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                        outstream.encoding = old_outstream.encoding;
                        outstream.codec = old_outstream.codec;
                        outstream.passes = old_outstream.passes;
                        outstream.samplerate = old_outstream.samplerate;
                        mass.sampleratemodifer = m.sampleratemodifer;
                        outstream.channels = old_outstream.channels;
                        instream.channelconverter = ((AudioStream)m.inaudiostreams[m.inaudiostream]).channelconverter;
                        outstream.bits = old_outstream.bits;
                    }
                    else
                    {
                        //Клонируем Audio = Disabled
                        mass.outaudiostreams.Clear();
                        return mass;
                    }
                }
                else
                {
                    //забиваем аудио настройки
                    outstream.encoding = Settings.GetAEncodingPreset(Settings.FormatOut);
                    outstream.codec = PresetLoader.GetACodec(mass.format, outstream.encoding);
                    outstream.passes = PresetLoader.GetACodecPasses(mass);

                    mass = Format.GetValidSamplerate(mass);

                    //определяем битность
                    mass = Format.GetValidBits(mass);

                    //определяем колличество каналов
                    mass = Format.GetValidChannelsConverter(mass);
                    mass = Format.GetValidChannels(mass);
                }

                if (outstream.codec == "Disabled") outstream.bitrate = 0;

                //проверяем можно ли копировать данный формат
                if (outstream.codec == "Copy")
                {
                    //AudioStream instream = (AudioStream)mass.inaudiostreams[mass.inaudiostream];
                    if (instream.audiopath == null)
                    {
                        string outext = Format.GetValidRAWAudioEXT(instream.codecshort);
                        string outpath = Settings.TempPath + "\\" + mass.key + "_" + mass.inaudiostream + outext;
                        outstream.audiopath = outpath;
                    }
                    else
                    {
                        outstream.audiopath = instream.audiopath;
                    }

                    outstream.bitrate = instream.bitrate;

                    string CopyProblems = Format.ValidateCopyAudio(mass);
                    if (CopyProblems != null)
                    {
                        Message mess = new Message(this);
                        mess.ShowMessage(Languages.Translate("The stream contains parameters incompatible with this format") +
                            " " + Format.EnumToString(mass.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 + "\\" + mass.key + aext;
                }
            }
            return mass;
        }
        public static void CreateMuxingScript(Massive m, bool CopyDelay)
        {
            string muxer_cli = "", language_a = "";

            if (Formats.GetDefaults(m.format).IsEditable)
            {
                //Получение CLI и расшифровка подставных значений
                muxer_cli = Calculate.ExpandVariables(m, Formats.GetSettings(m.format, "CLI_virtualdubmod", Formats.GetDefaults(m.format).CLI_virtualdubmod));
            }

            using (StreamWriter sw = new StreamWriter(Settings.TempPath + "\\" + m.key + ".vcf", false, System.Text.Encoding.Default))
            {
                sw.WriteLine("VirtualDub.RemoveInputStreams();");
                sw.WriteLine("VirtualDub.Open(\"" + Calculate.GetUTF8String(m.outvideofile) + "\", 0, 0);");

                if (m.outaudiostreams.Count > 0)
                {
                    AudioStream instream  = (AudioStream)m.inaudiostreams[m.inaudiostream];
                    AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                    if (outstream.audiopath != null)
                    {
                        string interleave = "", title_a = "";
                        if (!string.IsNullOrEmpty(muxer_cli))
                        {
                            string mux_o = Calculate.GetRegexValue(@"\[o\](.*?)\[/o\]", muxer_cli);
                            if (!string.IsNullOrEmpty(mux_o))
                            {
                                interleave = Calculate.GetRegexValue("interleave=\"(\\d*,\\s?\\d*,\\s?\\d*,\\s?\\d*)\"", mux_o);
                            }

                            string mux_a = Calculate.GetRegexValue(@"\[a\](.*?)\[/a\]", muxer_cli);
                            if (!string.IsNullOrEmpty(mux_a))
                            {
                                language_a = Calculate.GetRegexValue("language=\"(.*?)\"", mux_a);
                                title_a    = Calculate.GetRegexValue("title=\"(.*?)\"", mux_a);
                            }
                        }

                        string aext = Path.GetExtension(outstream.audiopath).ToLower();
                        string key  = "00000201";
                        if (aext == ".mp3" ||
                            aext == ".mp2" ||
                            aext == ".mpa")
                        {
                            key = "00000202";
                        }
                        else if (aext == ".ac3")
                        {
                            key = "00000203";
                        }
                        else if (aext == ".ogg")
                        {
                            key = "00000204";
                        }
                        else if (aext == ".dts")
                        {
                            key = "00000205";
                        }

                        //Для правильного муксинга вбр и абр мп3-звука
                        string vbr = "0"; //0 - переписывать заголовок (CBR), 1 - не переписывать (VBR и ABR)
                        if (outstream.codec == "MP3" && m.mp3_options.encodingmode != Settings.AudioEncodingModes.CBR ||
                            instream.codecshort == "MP3" && outstream.codec == "Copy")
                        {
                            vbr = "1";
                        }

                        sw.WriteLine("VirtualDub.stream[0].SetSource(\"" + Calculate.GetUTF8String(outstream.audiopath) + "\", 0x" + key + ", " + vbr + ");");
                        sw.WriteLine("VirtualDub.stream[0].DeleteComments(1);");
                        sw.WriteLine("VirtualDub.stream[0].AdjustChapters(1);");
                        sw.WriteLine("VirtualDub.stream[0].SetMode(0);");
                        sw.WriteLine("VirtualDub.stream[0].SetClipMode(1, 1);");
                        sw.WriteLine("VirtualDub.stream[0].SetConversion(0, 0, 0, 0, 0);");
                        sw.WriteLine("VirtualDub.stream[0].SetVolume();");
                        sw.WriteLine("VirtualDub.stream[0].SetCompression();");
                        sw.WriteLine("VirtualDub.stream[0].EnableFilterGraph(0);");
                        sw.WriteLine("VirtualDub.stream[0].filters.Clear();");

                        //Interleaving
                        if (!string.IsNullOrEmpty(interleave))
                        {
                            sw.WriteLine("VirtualDub.stream[0].SetInterleave(" + interleave + ", " + (CopyDelay ? outstream.delay.ToString() : "0") + ");");
                        }

                        //Title (audio)
                        if (!string.IsNullOrEmpty(title_a))
                        {
                            sw.WriteLine("VirtualDub.stream[0].AddComment(0x00000003, \"INAM\", \"" + title_a + "\");");
                        }
                    }
                }

                sw.WriteLine("VirtualDub.video.DeleteComments(1);");
                sw.WriteLine("VirtualDub.video.AdjustChapters(1);");
                sw.WriteLine("VirtualDub.video.SetDepth(24, 24);");
                sw.WriteLine("VirtualDub.video.SetMode(0);");
                sw.WriteLine("VirtualDub.video.SetFrameRate(0, 1);");
                sw.WriteLine("VirtualDub.video.SetIVTC(0, 0, -1, 0);");
                sw.WriteLine("VirtualDub.video.SetCompression();");
                sw.WriteLine("VirtualDub.video.filters.Clear();");

                string title = "", author = "", copyright = "";
                if (!string.IsNullOrEmpty(muxer_cli))
                {
                    string mux_v = Calculate.GetRegexValue(@"\[v\](.*?)\[/v\]", muxer_cli);
                    if (!string.IsNullOrEmpty(mux_v))
                    {
                        title     = Calculate.GetRegexValue("title=\"(.*?)\"", mux_v);
                        author    = Calculate.GetRegexValue("author=\"(.*?)\"", mux_v);
                        copyright = Calculate.GetRegexValue("copyright=\"(.*?)\"", mux_v);
                    }
                }

                //Language (audio)
                if (!string.IsNullOrEmpty(language_a))
                {
                    sw.WriteLine("VirtualDub.video.AddComment(0x00000000, \"IAS1\", \"" + language_a + "\");");
                }

                //Title
                if (!string.IsNullOrEmpty(title))
                {
                    sw.WriteLine("VirtualDub.video.AddComment(0x00000003, \"INAM\", \"" + title + "\");");
                }

                //Author
                if (!string.IsNullOrEmpty(author))
                {
                    sw.WriteLine("VirtualDub.video.AddComment(0x00000005, \"IART\", \"" + author + "\");");
                }

                //Copyright
                if (!string.IsNullOrEmpty(copyright))
                {
                    sw.WriteLine("VirtualDub.video.AddComment(0x00000006, \"ICOP\", \"" + copyright + "\");");
                }

                sw.WriteLine("VirtualDub.SaveAVI(\"" + Calculate.GetUTF8String(m.outfilepath) + "\");");
                sw.WriteLine("VirtualDub.Close();");

                sw.Close();
            }
        }
Beispiel #23
0
        public static Massive DecodeLine(Massive m)
        {
            //создаём свежий массив параметров Lame
            m.mp3_options = new mp3_arguments();

            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            int n   = 0;
            int b   = -1;
            int B   = -1;
            int V   = -1;
            int abr = -1;

            //берём пока что за основу последнюю строку
            string line = outstream.passes;

            string[] cli = line.Split(new string[] { " " }, StringSplitOptions.None);

            foreach (string value in cli)
            {
                if (value == "-m")
                {
                    string cmode = cli[n + 1];
                    if (cmode == "s")
                    {
                        m.mp3_options.channelsmode = "Stereo";
                    }
                    else if (cmode == "j")
                    {
                        m.mp3_options.channelsmode = "Joint Stereo";
                    }
                    else if (cmode == "f")
                    {
                        m.mp3_options.channelsmode = "Forced Joint Stereo";
                    }
                    else if (cmode == "m")
                    {
                        m.mp3_options.channelsmode = "Mono";
                    }
                    else
                    {
                        m.mp3_options.channelsmode = "Auto";
                    }
                }

                else if (value == "-q")
                {
                    int num = 0;
                    int.TryParse(cli[n + 1], out num);
                    m.mp3_options.encquality = num;
                }

                else if (value == "-b")
                {
                    b = Convert.ToInt32(cli[n + 1]);
                }

                else if (value == "-B")
                {
                    B = Convert.ToInt32(cli[n + 1]);
                }

                else if (value == "-V")
                {
                    V = Convert.ToInt32(cli[n + 1]);
                }

                else if (value == "--abr")
                {
                    abr = Convert.ToInt32(cli[n + 1]);
                }

                else if (value == "--noreplaygain")
                {
                    m.mp3_options.replay_gain = 0;
                }

                else if (value == "--replaygain-fast")
                {
                    m.mp3_options.replay_gain = 1;
                }

                else if (value == "--replaygain-accurate")
                {
                    m.mp3_options.replay_gain = 2;
                }

                else if (value == "--resample")
                {
                    m.mp3_options.forcesamplerate = true;
                }

                n++;
            }

            //вычисляем какой всё таки это был режим
            if (V >= 0)
            {
                m.mp3_options.encodingmode = Settings.AudioEncodingModes.VBR;
                outstream.bitrate          = 0;
                m.mp3_options.quality      = V;
                m.mp3_options.minb         = (b >= 0) ? b : 32;
                m.mp3_options.maxb         = (B >= 0) ? B : 320;
            }
            else if (abr >= 0)
            {
                m.mp3_options.encodingmode = Settings.AudioEncodingModes.ABR;
                outstream.bitrate          = abr;
                m.mp3_options.minb         = (b >= 0) ? b : 32;
                m.mp3_options.maxb         = (B >= 0) ? B : 320;
            }
            else
            {
                m.mp3_options.encodingmode = Settings.AudioEncodingModes.CBR;
                outstream.bitrate          = (b >= 0) ? b : 128;
                m.mp3_options.minb         = 32;
                m.mp3_options.maxb         = 320;
            }

            return(m);
        }
Beispiel #24
0
        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();
            }
        }
Beispiel #25
0
        private void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            //Выходим при отмене
            if (m == null || worker == null || num_closes > 0)
            {
                Close();
                return;
            }

            if (e.Error != null)
            {
                ErrorException("Caching (Unhandled): " + ((Exception)e.Error).Message, ((Exception)e.Error).StackTrace);
                m = null;
                Close();
                return;
            }

            //Всё OK - выходим
            if (e.Result == null)
            {
                Close();
                return;
            }

            //Извлекаем текст ошибки
            string error      = ((Exception)e.Result).Message.Trim();
            string stacktrace = ((Exception)e.Result).StackTrace;

            if (!string.IsNullOrEmpty(((Exception)e.Result).HelpLink))
            {
                //Добавляем скрипт в StackTrace
                stacktrace += Calculate.WrapScript(((Exception)e.Result).HelpLink, 150);
            }

            string      ext      = Path.GetExtension(m.infilepath).ToLower();
            AudioStream instream = (m.inaudiostreams.Count > 0) ? (AudioStream)m.inaudiostreams[m.inaudiostream] : new AudioStream();

            //Ошибка в пользовательском скрипте, в графе, или это была проверка звука
            if (ext == ".avs" || ext == ".grf" || only_audio)
            {
                ErrorException("Caching: " + error, stacktrace);
                m = null;
                Close();
                return;
            }

            //Начался разбор ошибок
            if ((error == "Script doesn't contain audio!" || error.StartsWith("DirectShowSource:") ||
                 error.StartsWith("FFAudioSource:") || error.Contains(" audio track")) && m.isvideo)
            {
                bool demux_audio = true;

                //Переключение на FFmpegSource2 при проблемах с DirectShowSource (кроме проблем со звуком)
                if (error.StartsWith("DirectShowSource:") && !error.Contains("unable to determine the duration of the audio.") &&
                    !error.Contains("Timeout waiting for audio."))
                {
                    demux_audio = !Settings.FFMS_Enable_Audio;
                    m.vdecoder  = AviSynthScripting.Decoders.FFmpegSource2;

                    //И тут-же индексируем (чтоб не делать это через Ависинт)
                    Indexing_FFMS ffindex = new Indexing_FFMS(m);
                    if (ffindex.m == null)
                    {
                        m = null;
                        Close();
                        return;
                    }
                }

                //Извлечение звука
                if (m.inaudiostreams.Count > 0 && demux_audio && !File.Exists(instream.audiopath))
                {
                    string outext  = Format.GetValidRAWAudioEXT(instream.codecshort);
                    string outpath = Settings.TempPath + "\\" + m.key + "_" + m.inaudiostream + outext;

                    //удаляем старый файл
                    SafeDelete(outpath);

                    //извлекаем новый файл
                    if (outext == ".wav")
                    {
                        Decoder dec = new Decoder(m, Decoder.DecoderModes.DecodeAudio, outpath);
                        if (dec.IsErrors)
                        {
                            ErrorException("Decode to WAV: " + dec.error_message, null);
                            m = null;
                            Close();
                            return;
                        }
                    }
                    else
                    {
                        Demuxer dem = new Demuxer(m, Demuxer.DemuxerMode.ExtractAudio, outpath);
                        if (dem.IsErrors)
                        {
                            //Вместо вывода сообщения об ошибке тут можно назначить декодирование в WAV, но тогда в режиме Copy будет копироваться WAV..
                            ErrorException(dem.error_message, null);
                            m = null;
                            Close();
                            return;
                        }
                    }

                    //проверка на удачное завершение
                    if (File.Exists(outpath) && new FileInfo(outpath).Length != 0)
                    {
                        instream.audiopath  = outpath;
                        instream.audiofiles = new string[] { outpath };
                        instream            = Format.GetValidADecoder(instream);
                        ((MainWindow)Owner).deletefiles.Add(outpath);
                    }
                    else
                    {
                        instream.audiopath = null;
                        instream.decoder   = 0;
                    }
                }
                else if (m.inaudiostreams.Count > 0 && (!demux_audio || File.Exists(instream.audiopath)) && counter > 0)
                {
                    //Мы тут уже были - пора выходить с ошибкой..
                    ErrorException("Caching: " + error, stacktrace);
                    m = null;
                    Close();
                    return;
                }

                counter += 1;
                worker.RunWorkerAsync();
                return;
            }
            else if (instream.decoder == AviSynthScripting.Decoders.bassAudioSource && error.EndsWith("File could not be opened!"))
            {
                instream.decoder = AviSynthScripting.Decoders.FFAudioSource;
                worker.RunWorkerAsync();
                return;
            }
            else if (m.vdecoder == AviSynthScripting.Decoders.DirectShowSource && error.Contains("convertfps"))
            {
                m.isconvertfps = false;
                worker.RunWorkerAsync();
                return;
            }
            else if (error == "Hacked output")
            {
                worker.RunWorkerAsync();
                return;
            }
            else if (error == "Cannot load avisynth.dll")
            {
                string mess = Languages.Translate("AviSynth is not found!") + Environment.NewLine +
                              Languages.Translate("Please install AviSynth 2.5.7 MT or higher.");
                ErrorException(mess, null);
                m = null;
            }
            else
            {
                ErrorException("Caching: " + error, stacktrace);
                m = null;
            }

            Close();
        }
Beispiel #26
0
        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;
        }
Beispiel #27
0
        public static string[] GetValidSampleratesList(Massive m)
        {
            if (m.format == ExportFormats.PmpAvc)
               return new string[] { "44100" };
               else if (m.format == ExportFormats.DpgNintendoDS)
               return new string[] { "32000", "48000" }; //"32768"
               else if (Formats.GetDefaults(m.format).IsEditable)
               {
               string[] rates;
               if (Formats.GetDefaults(m.format).Samplerates_IsEditable)
               {
                   rates = Formats.GetSettings(m.format, "Samplerates", Formats.GetDefaults(m.format).Samplerates);
               }
               else
                   rates = Formats.GetDefaults(m.format).Samplerates;

               bool auto = false;
               foreach (string rate in rates)
               {
                   if (rate.ToLower() == "auto") auto = true;
               }
               if (!auto) return rates;
               }

               AudioStream outstream;
               if (m.outaudiostreams.Count > 0)
               outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
               else
               {
               outstream = new AudioStream();
               outstream.encoding = Settings.GetAEncodingPreset(Settings.FormatOut);
               outstream.codec = PresetLoader.GetACodec(m.format, outstream.encoding);
               }

               if (m.format == ExportFormats.Flv)
               return new string[] { "44100" };
               else if (m.format == ExportFormats.AviDVPAL || m.format == ExportFormats.AviDVNTSC)
               return new string[] { "32000", "48000" };
               else if (outstream.codec == "MP3" || outstream.codec == "MP2")
               return new string[] { "32000", "44100", "48000" };
               else if (outstream.codec == "AC3")
               {
               if (m.format == ExportFormats.AviHardware || m.format == ExportFormats.AviHardwareHD ||
                   m.format == ExportFormats.Mpeg2PS || m.format == ExportFormats.Mpeg2PAL ||
                   m.format == ExportFormats.Mpeg2NTSC || m.format == ExportFormats.TS ||
                   m.format == ExportFormats.M2TS || m.format == ExportFormats.BluRay) //Audio mp4 mov mkv
                   return new string[] { "48000" };
               else
                   return new string[] { "32000", "44100", "48000" };
               }
               else if (outstream.codec == "PCM" || outstream.codec == "LPCM")
               {
               if (m.format == ExportFormats.TS || m.format == ExportFormats.M2TS || m.format == ExportFormats.BluRay)
                   return new string[] { "48000", "96000", "192000" };
               else if (m.format == ExportFormats.Mpeg2PS || m.format == ExportFormats.Mpeg2PAL || m.format == ExportFormats.Mpeg2NTSC)
                   return new string[] { "48000" };
               else
                   return new string[] { "22050", "32000", "44100", "48000", "96000", "192000" };
               }
               else
               return new string[] { "22050", "32000", "44100", "48000" };
        }
Beispiel #28
0
        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();
        }
Beispiel #29
0
        private void make_mp4()
        {
            //заглушка, PSP не читает видео без звука
            if (m.format == Format.ExportFormats.Mp4PSPAVC ||
                m.format == Format.ExportFormats.Mp4PSPAVCTV ||
                m.format == Format.ExportFormats.Mp4PSPASP)
            {
                if (m.outaudiostreams.Count == 0)
                {
                    AudioStream stream = new AudioStream();
                    stream.audiopath = Settings.TempPath + "\\" + m.key + ".m4a";
                    File.Copy(Calculate.StartupPath + "\\apps\\pmp_muxer_avc\\fake.m4a",
                        stream.audiopath);
                    m.outaudiostreams.Add(stream);
                }
            }

            SafeDelete(m.outfilepath);

            busyfile = Path.GetFileName(m.outfilepath);
            step++;

            //info строка
            SetLog("Video file: " + m.outvideofile);
            if (m.outaudiostreams.Count > 0)
            {
                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                if (outstream.audiopath != null)
                    SetLog("Audio file: " + outstream.audiopath);
            }
            SetLog("Muxing to: " + m.outfilepath);

            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;

            string rate = "-fps " + m.outframerate + " ";
            if (m.outvcodec == "Copy")
            {
                if (m.inframerate != null)
                    rate = "-fps " + m.inframerate + " ";
                else
                    rate = "";
            }

            //Доп. параметры муксинга
            string mux_v = "", mux_a = "", mux_o = "";
            if (Formats.GetDefaults(m.format).IsEditable)
            {
                //Получение CLI и расшифровка подставных значений
                string muxer_cli = Calculate.ExpandVariables(m, Formats.GetSettings(m.format, "CLI_mp4box", Formats.GetDefaults(m.format).CLI_mp4box));
                mux_v = Calculate.GetRegexValue(@"\[v\](.*?)\[/v\]", muxer_cli);
                mux_a = Calculate.GetRegexValue(@"\[a\](.*?)\[/a\]", muxer_cli);
                mux_o = Calculate.GetRegexValue(@"\[o\](.*?)\[/o\]", muxer_cli);
                mux_o = (!string.IsNullOrEmpty(mux_o)) ? mux_o + " " : "";
            }

            string split = "";
            if (!string.IsNullOrEmpty(Splitting) && Splitting != "Disabled")
            {
                int size = 0;
                string svalue = Calculate.GetRegexValue(@"(\d+)\D*", Splitting);
                if (svalue != null) Int32.TryParse(svalue, NumberStyles.Integer, null, out size);
                if (size != 0) { split = "-split-size " + size + "000 "; IsSplitting = true; }
            }

            string addaudio = "";
            if (m.outaudiostreams.Count > 0)
            {
                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                addaudio = " -add \"" + outstream.audiopath + "\"" + mux_a + (CopyDelay ? " -delay 2=" + outstream.delay : "");
            }

            info.Arguments = mux_o + rate + split + "-add \"" + m.outvideofile + "\"" + mux_v + addaudio + " -new \"" + m.outfilepath +
                "\" -tmp \"" + Settings.TempPath + "\"";

            //прописываем аргументы командной строки
            SetLog("");
            if (Settings.ArgumentsToLog)
            {
                SetLog("MP4Box.exe: " + info.Arguments);
                SetLog("");
            }

            //Муксим
            Do_MP4Box_Cycle(info);

            //обнуляем прогресс
            ResetProgress();

            if (IsAborted || IsErrors) return;

            //если включено деление
            if (IsSplitting) m.outfilepath = Calculate.RemoveExtention(m.outfilepath, true) + "_001" + Path.GetExtension(m.outfilepath).ToLower();

            //проверка на удачное завершение
            if (!File.Exists(m.outfilepath) || new FileInfo(m.outfilepath).Length == 0)
            {
                IsErrors = true;
                ErrorException(encodertext.ToString());
                //throw new Exception(Languages.Translate("Can`t find output video file!"));
            }

            encodertext.Length = 0;

            SetLog("");
        }
Beispiel #30
0
        public static Massive DecodePresets(Massive m)
        {
            //расшифровываем видео параметры
            if (m.outvcodec == "x265")
            {
                m = x265.DecodeLine(m);
            }
            else if (m.outvcodec == "x264")
            {
                m = x264.DecodeLine(m);
            }
            else if (m.outvcodec == "x262")
            {
                m = x262.DecodeLine(m);
            }
            else if (m.outvcodec == "XviD")
            {
                m = XviD.DecodeLine(m);
            }
            else if (m.outvcodec == "MPEG2")
            {
                m = FMPEG2.DecodeLine(m);
            }
            else if (m.outvcodec == "MPEG1")
            {
                m = FMPEG1.DecodeLine(m);
            }
            else if (m.outvcodec == "MPEG4")
            {
                m = FMPEG4.DecodeLine(m);
            }
            else if (m.outvcodec == "DV")
            {
                m = FDV.DecodeLine(m);
            }
            else if (m.outvcodec == "HUFF")
            {
                m = FFHUFF.DecodeLine(m);
            }
            else if (m.outvcodec == "MJPEG")
            {
                m = FMJPEG.DecodeLine(m);
            }
            else if (m.outvcodec == "FFV1")
            {
                m = FFV1.DecodeLine(m);
            }
            else if (m.outvcodec == "FLV1")
            {
                m = FLV1.DecodeLine(m);
            }

            if (m.outaudiostreams.Count > 0)
            {
                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

                //расшифровываем audio параметры
                if (outstream.codec == "AAC")
                {
                    m = NeroAAC.DecodeLine(m);
                }
                else if (outstream.codec == "QAAC")
                {
                    m = QuickTimeAAC.DecodeLine(m);
                }
                else if (outstream.codec == "MP3")
                {
                    m = LameMP3.DecodeLine(m);
                }
                else if (outstream.codec == "AC3")
                {
                    m = AftenAC3.DecodeLine(m);
                }
                else if (outstream.codec == "MP2")
                {
                    m = FMP2.DecodeLine(m);
                }
                else if (outstream.codec == "PCM")
                {
                    m = FPCM.DecodeLine(m);
                }
                else if (outstream.codec == "LPCM")
                {
                    m = FLPCM.DecodeLine(m);
                }
                else if (outstream.codec == "FLAC")
                {
                    m = FFLAC.DecodeLine(m);
                }
            }

            return(m);
        }
Beispiel #31
0
        private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                //определяем аудио потоки
                AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];

                script  = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.Normalize);
                script += Environment.NewLine + "Trim(0, " + vtrim + ")";

                avs = new AviSynthEncoder(m, script);

                //Запускаем анализ
                avs.start();

                //Выводим прогресс
                while (avs.IsBusy())
                {
                    if (worker.CancellationPending)
                    {
                        avs.stop();
                    }
                    else if (avs.frame > 0)
                    {
                        worker.ReportProgress(avs.frame);
                    }
                    Thread.Sleep(100);
                }

                //Результаты
                if (!worker.CancellationPending)
                {
                    if (!avs.IsErrors)
                    {
                        instream.gain = avs.gain.ToString("##0.000").Replace(",", ".");
                        if (instream.gain == "0.000")
                        {
                            instream.gain = "0.0";
                        }
                        instream.gaindetected = true;
                    }
                    else
                    {
                        instream.gain         = "0.0";
                        instream.gaindetected = false;
                        throw new Exception(avs.error_text, avs.exception_raw);
                    }
                }
            }
            catch (Exception ex)
            {
                if (worker != null && !worker.CancellationPending && m != null && num_closes == 0)
                {
                    //Ошибка
                    ex.HelpLink = script;
                    e.Result    = ex;
                }
            }
            finally
            {
                CloseEncoder(true);
            }
        }
Beispiel #32
0
        public static Massive DecodeLine(Massive m)
        {
            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            //создаём свежий массив параметров QuickTime AAC
            m.qaac_options = new qaac_arguments();

            //берём пока что за основу последнюю строку
            string line = outstream.passes;

            string[] separator = new string[] { " " };
            string[] cli       = line.Split(separator, StringSplitOptions.None);
            int      n         = 0;

            foreach (string value in cli)
            {
                if (value == "-q")
                {
                    m.qaac_options.accuracy = Convert.ToInt32(cli[n + 1]);
                }
                else if (value == "--tvbr")
                {
                    m.qaac_options.encodingmode = Settings.AudioEncodingModes.VBR;
                    m.qaac_options.quality      = Convert.ToInt32(cli[n + 1]) / 9;
                }
                else if (value == "--cbr" || value == "--abr" || value == "--cvbr")
                {
                    if (value == "--cbr")
                    {
                        m.qaac_options.encodingmode = Settings.AudioEncodingModes.CBR;
                    }
                    else if (value == "--abr")
                    {
                        m.qaac_options.encodingmode = Settings.AudioEncodingModes.ABR;
                    }
                    else
                    {
                        m.qaac_options.encodingmode = Settings.AudioEncodingModes.CVBR;
                    }

                    outstream.bitrate = Convert.ToInt32(cli[n + 1]);
                }
                else if (value == "--alac")
                {
                    m.qaac_options.encodingmode = Settings.AudioEncodingModes.ALAC;
                }
                else if (value == "--he")
                {
                    m.qaac_options.aacprofile = "AAC-HE";
                }
                else if (value == "--no-delay")
                {
                    m.qaac_options.no_delay = true;
                }
                else if (value == "--gapless-mode")
                {
                    m.qaac_options.gapless_mode = Convert.ToInt32(cli[n + 1]);
                }

                n++;
            }

            return(m);
        }
Beispiel #33
0
        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();
        }
Beispiel #34
0
        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);
            }
        }
Beispiel #35
0
        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();
            }
        }
Beispiel #36
0
        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();
        }
Beispiel #37
0
        public Task(string thm, TaskStatus status, Massive mass)
        {
            _info   = "";
            _thm    = thm;
            _status = status;
            _name   = Path.GetFileName(mass.outfilepath);

            if (mass.outvcodec != "Copy" &&
                mass.outvcodec != "Disabled")
            {
                //Переопределение некоторых параметров видео на основе текущего скрипта (т.к. он мог быть изменен вручную)
                if (Settings.ReadScript) //если в настройках это разрешено
                {
                    bool           recalc_sar = false;
                    AviSynthReader reader     = null;

                    try
                    {
                        reader = new AviSynthReader();
                        reader.ParseScript(mass.script);

                        if (mass.outresw != reader.Width)
                        {
                            if (mass.outvcodec == "x264" && Calculate.GetScriptBitDepth(mass.script) != 8)
                            {
                                if (mass.outresw != reader.Width / 2)
                                {
                                    mass.outresw = reader.Width / 2;
                                    recalc_sar   = true;
                                }
                            }
                            else
                            {
                                mass.outresw = reader.Width;
                                recalc_sar   = true;
                            }
                        }

                        if (mass.outresh != reader.Height)
                        {
                            mass.outresh = reader.Height; recalc_sar = true;
                        }

                        mass.outframes    = reader.FrameCount;
                        mass.outframerate = Calculate.ConvertDoubleToPointString(reader.Framerate);
                        mass.outduration  = TimeSpan.FromSeconds((double)mass.outframes / reader.Framerate);
                        mass.outfilesize  = Calculate.GetEncodingSize(mass);
                    }
                    catch { }
                    finally
                    {
                        reader.Close();
                        reader = null;
                    }

                    //Переопределяем SAR в случае анаморфного кодирования (если разрешение поменялось)
                    if (recalc_sar && mass.sar != null && mass.sar != "1:1")
                    {
                        mass = Calculate.CalculateSAR(mass);
                    }
                }

                _info += mass.outresw + "x" + mass.outresh;
                _info += "  " + mass.outframerate;
                if (mass.encodingmode == Settings.EncodingModes.Quality ||
                    mass.encodingmode == Settings.EncodingModes.Quantizer ||
                    mass.encodingmode == Settings.EncodingModes.TwoPassQuality ||
                    mass.encodingmode == Settings.EncodingModes.ThreePassQuality)
                {
                    _info += "  Q" + Calculate.ConvertDoubleToPointString((double)mass.outvbitrate, 1);
                }
                else if (mass.encodingmode == Settings.EncodingModes.TwoPassSize ||
                         mass.encodingmode == Settings.EncodingModes.ThreePassSize ||
                         mass.encodingmode == Settings.EncodingModes.OnePassSize)
                {
                    _info += "  " + mass.outvbitrate + "mb";
                }
                else
                {
                    _info += "  " + mass.outvbitrate + "kbps";
                }
            }
            else if (mass.outvcodec == "Copy")
            {
                _info += mass.inresw + "x" + mass.inresh;
                _info += "  " + mass.inframerate;
                _info += "  " + mass.invbitrate + "kbps";
            }

            if (mass.outaudiostreams.Count > 0)
            {
                AudioStream outstream = (AudioStream)mass.outaudiostreams[mass.outaudiostream];

                if (outstream.codec != "Copy")
                {
                    _info += "  " + outstream.samplerate + "Hz";
                    _info += "  " + Calculate.ExplainChannels(outstream.channels);
                    _info += "  " + ((outstream.bitrate > 0) ? outstream.bitrate + "kbps" : "VBR");

                    if (mass.volume != "Disabled")
                    {
                        _info += "  " + mass.volume;
                    }
                }
                else
                {
                    if (mass.inaudiostreams.Count > 0)
                    {
                        AudioStream instream = (AudioStream)mass.inaudiostreams[mass.inaudiostream];
                        _info += "  " + instream.samplerate + "Hz";
                        _info += "  " + Calculate.ExplainChannels(instream.channels);
                        _info += "  " + instream.bitrate + "kbps";
                    }
                }
            }

            _info += "  " + ((mass.outfilesize != Languages.Translate("Unknown")) ? mass.outfilesize.Replace(" ", "") : "?mb");

            _mass = mass.Clone();
            _id   = mass.key;
        }
Beispiel #38
0
        private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                string ext = Path.GetExtension((m.infilepath_source != null) ? m.infilepath_source : m.infilepath).ToLower();
                if (ext != ".avs" && ext != ".grf" && ext != ".d2v" && ext != ".dga" && ext != ".dgi")
                {
                    //забиваем максимум параметров файла
                    MediaInfoWrapper media = new MediaInfoWrapper();
                    media.Open(m.infilepath);

                    //Выходим при отмене
                    if (m == null || worker.CancellationPending)
                        return;

                    m.invcodec = media.VCodecString;
                    m.invcodecshort = media.VCodecShort;
                    m.invbitrate = media.VideoBitrate;
                    m.inresw = media.Width;
                    m.inresh = media.Height;
                    m.inaspect = media.Aspect;
                    //m.pixelaspect = (m.inresw != 0 && m.inresh != 0) ? (m.inaspect / ((double)m.inresw / (double)m.inresh)) : 1.0;
                    m.pixelaspect = media.PixelAspect;
                    m.invideostream_mi_id = media.VTrackID();
                    m.invideostream_mi_order = media.VTrackOrder();
                    m.inframerate = media.FrameRate;
                    m.induration = TimeSpan.FromMilliseconds(media.Milliseconds);
                    m.outduration = m.induration;
                    m.interlace = media.Interlace;
                    m.interlace_raw = media.ScanType;
                    m.fieldOrder_raw = media.ScanOrder;
                    m.inframes = media.Frames;

                    //Возвращаем 29фпс для видео с пуллдауном, т.к. MediaInfo выдает для него 23фпс, а MPEG2Source\DGSource
                    //без ForceFilm из-за пуллдауна будет декодировать с 29-ю. Продолжительность пересчитывается в Caching.
                    if (m.vdecoder == AviSynthScripting.Decoders.MPEG2Source || m.vdecoder == AviSynthScripting.Decoders.DGSource)
                    {
                        if (media.ScanOrder.Contains("Pulldown") && m.inframerate == "23.976" && !m.IsForcedFilm)
                        {
                            m.inframerate = "29.970";
                            m.interlace = SourceType.FILM;
                        }
                        else if (m.IsForcedFilm)
                        {
                            m.inframerate = "23.976";
                            m.interlace = SourceType.UNKNOWN;
                        }
                    }

                    //забиваем аудио потоки
                    if (ext == ".pmp" && Settings.EnableAudio)
                    {
                        AudioStream stream = new AudioStream();
                        stream.codec = "AAC";
                        stream.codecshort = "AAC";
                        stream.samplerate = "44100";
                        stream.bits = 16;
                        stream.channels = 2;
                        stream.language = "English";
                        m.inaudiostreams.Add(stream.Clone());
                        m.inaudiostream = 0;
                    }
                    else if (ext == ".dpg")
                    {
                        dpgmuxer dpg = new dpgmuxer();
                        dpgmuxer.DPGHeader header = dpg.ReadHeader(m.infilepath_source);
                        m.inframes = header.frames;
                        m.inframerate = Calculate.ConvertDoubleToPointString((double)header.fps);
                        m.induration = TimeSpan.FromSeconds((double)header.frames / (double)header.fps);
                        m.outduration = m.induration;

                        if (m.inaudiostreams.Count > 0 && Settings.EnableAudio)
                        {
                            AudioStream stream = (AudioStream)m.inaudiostreams[m.inaudiostream];
                            //забиваем в список все найденные треки
                            MediaInfoWrapper mi = new MediaInfoWrapper();
                            stream = mi.GetAudioInfoFromAFile(stream.audiopath, true);
                            stream.samplerate = header.samplerate.ToString();
                            m.inaudiostreams[m.inaudiostream] = stream;
                        }
                    }
                    else if (ext == ".cda")
                    {
                        AudioStream stream = new AudioStream();
                        stream.codec = "CDDA";
                        stream.codecshort = "CDDA";
                        //stream.bitrate = media.AudioBitrate(snum);
                        //stream.mkvid = media.AudioID(snum);
                        //stream.samplerate = media.Samplerate(snum);
                        //stream.bits = media.Bits(snum);
                        //stream.channels = media.Channels(snum);
                        stream.language = "English";

                        m.isvideo = false;
                        stream.audiopath = m.infilepath;
                        stream.audiofiles = new string[] { stream.audiopath };
                        stream = Format.GetValidADecoder(stream);

                        m.inaudiostreams.Add(stream.Clone());
                    }
                    else if (m.indexfile != null && File.Exists(m.indexfile) && Settings.EnableAudio)
                    {
                        int n = 0;
                        ArrayList atracks = Indexing.GetTracks(m.indexfile);
                        foreach (string apath in atracks)
                        {
                            //определяем аудио потоки
                            AudioStream stream = new AudioStream();

                            //забиваем в список все найденные треки
                            MediaInfoWrapper mi = new MediaInfoWrapper();
                            stream = mi.GetAudioInfoFromAFile(apath, true);
                            stream.audiopath = apath;
                            stream.delay = Calculate.GetDelay(apath);
                            stream = Format.GetValidADecoder(stream);

                            stream.mi_id = media.ATrackID(n);
                            stream.mi_order = media.ATrackOrder(n);

                            m.inaudiostreams.Add(stream.Clone());
                            n++;
                        }
                        m.inaudiostream = 0;
                    }
                    else
                    {
                        if (Settings.EnableAudio || media.CountVideoStreams == 0)
                        {
                            for (int snum = 0; snum < media.CountAudioStreams; snum++)
                            {
                                AudioStream stream = new AudioStream();
                                stream.codec = media.ACodecString(snum);
                                stream.codecshort = media.ACodecShort(snum);
                                stream.bitrate = media.AudioBitrate(snum);
                                stream.mi_id = media.ATrackID(snum);
                                stream.mi_order = media.ATrackOrder(snum);
                                stream.samplerate = media.Samplerate(snum);
                                stream.bits = media.Bits(snum);
                                stream.channels = media.Channels(snum);
                                if (m.indexfile == null)
                                    stream.delay = media.Delay(snum);
                                stream.language = media.AudioLanguage(snum);

                                //вероятно звуковой файл
                                if (media.CountVideoStreams == 0)
                                {
                                    m.isvideo = false;
                                    stream.audiopath = m.infilepath;
                                    stream.audiofiles = new string[] { stream.audiopath };
                                    stream = Format.GetValidADecoder(stream);
                                }

                                m.inaudiostreams.Add(stream.Clone());
                            }
                            //делаем первый трек активным
                            m.inaudiostream = 0;
                        }

                        //довбиваем duration и frames для join заданий
                        if (m.infileslist.Length > 1)
                        {
                            TimeSpan ts = TimeSpan.Zero;
                            foreach (string file in m.infileslist)
                            {
                                MediaInfoWrapper med = new MediaInfoWrapper();
                                med.Open(file);
                                ts += med.Duration;
                                med.Close();
                            }
                            m.induration = ts;
                            m.outduration = m.induration;
                            m.inframes = (int)(m.induration.TotalSeconds * Calculate.ConvertStringToDouble(m.inframerate));
                        }
                    }

                    //довбиваем параметры из IFO
                    string ifo = Calculate.GetIFO(m.infilepath);
                    if (File.Exists(ifo))
                    {
                        //через MediaInfo
                        media.Close();
                        media.Open(ifo);
                        int n = 0;
                        foreach (AudioStream stream in m.inaudiostreams)
                        {
                            stream.language = media.AudioLanguage(n);
                            n++;
                        }

                        //через VStrip
                        VStripWrapper vs = new VStripWrapper();
                        vs.Open(ifo);
                        m.induration = vs.Duration();
                        m.outduration = m.induration;
                        m.inframes = (int)(m.induration.TotalSeconds * Calculate.ConvertStringToDouble(m.inframerate));
                        vs.Close();

                        #region Язык через VStrip:
                        //iifo_lang_tbl[] parse_ifo.c (The ISO 639 language codes)
                        //??? (AC3 2ch, 0xBD 0x80) [0,1] //MI - "Unknown"
                        //Italiano (AC3 2ch, 0xBD 0x82) [0,1]" //MI - "Italian", есть и др. несоответствия..
                        //Russian (AC3 2ch, 0xBD 0x80) [0,1]"
                        #endregion
                    }

                    //закрываем MediaInfo
                    media.Close();
                }

                if (ext == ".grf" || ext == ".d2v" || ext == ".dga" || ext == ".dgi")
                {
                    #region grf, d2v, dga, dgi
                    if (ext == ".grf")
                    {
                        string infile = Path.GetFileNameWithoutExtension(m.infilepath).ToLower();
                        if (infile.StartsWith("audio"))
                        {
                            //Это аудио-граф
                            m.isvideo = false;

                            AudioStream stream = new AudioStream();
                            stream.audiopath = m.infilepath;
                            stream.audiofiles = new string[] { stream.audiopath };
                            stream.codec = stream.codecshort = "PCM";
                            stream.language = "Unknown";
                            stream = Format.GetValidADecoder(stream);
                            m.inaudiostreams.Add(stream.Clone());
                        }
                        else
                        {
                            //Это видео-граф
                            m.invcodec = "RAWVIDEO";
                            m.invcodecshort = "RAWVIDEO";

                            //Если DirectShowSource не сможет определить fps, то требуемое значение можно будет указать в имени файла..
                            Regex r = new Regex(@"(fps\s?=\s?([\d\.\,]*))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Match mat = r.Match(infile);
                            if (mat.Success)
                            {
                                double fps = Calculate.ConvertStringToDouble(mat.Groups[2].Value);
                                if (fps > 0) m.inframerate = Calculate.ConvertDoubleToPointString(fps);

                                //"Очищаем" имя файла
                                infile = infile.Replace(mat.Groups[1].Value, "").Trim(new char[] { ' ', '_', '-', '(', ')', '.', ',' });
                            }

                            //Ищем звук к нему
                            if (Settings.EnableAudio)
                            {
                                //Почему на шаблон "audio*.grf" находятся и файлы типа "Копия audio file.grf"?!
                                string[] afiles = Directory.GetFiles(Path.GetDirectoryName(m.infilepath), "audio*.grf");
                                foreach (string afile in afiles)
                                {
                                    string aname = Path.GetFileNameWithoutExtension(afile).ToLower();
                                    if (aname.StartsWith("audio") && aname.Contains(infile))
                                    {
                                        AudioStream stream = new AudioStream();
                                        stream.audiopath = afile;
                                        stream.audiofiles = new string[] { stream.audiopath };
                                        stream.codec = stream.codecshort = "PCM";
                                        stream.language = "Unknown";
                                        stream = Format.GetValidADecoder(stream);
                                        m.inaudiostreams.Add(stream.Clone());
                                        break; //Только один трек
                                    }
                                }
                            }
                        }
                    }
                    else if (ext == ".d2v")
                    {
                        //Читаем d2v-файл
                        int n = 0;
                        string line = "";
                        Match mat1;
                        Match mat2;
                        Regex r1 = new Regex(@"Picture_Size=(\d+)x(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                        Regex r2 = new Regex(@"Aspect_Ratio=(\d+\.*\d*):(\d+\.*\d*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                        int result1 = 720; int result2 = 576; double result3 = 4; double result4 = 3; //Значения по-умолчанию
                        using (StreamReader sr = new StreamReader(m.indexfile, System.Text.Encoding.Default))
                            while (!sr.EndOfStream && n < 15) //Ограничиваемся первыми 15-ю строчками
                            {
                                line = sr.ReadLine();
                                mat1 = r1.Match(line);
                                mat2 = r2.Match(line);
                                if (mat1.Success)
                                {
                                    result1 = Convert.ToInt32(mat1.Groups[1].Value);
                                    result2 = Convert.ToInt32(mat1.Groups[2].Value);
                                }
                                if (mat2.Success)
                                {
                                    result3 = Calculate.ConvertStringToDouble(mat2.Groups[1].Value);
                                    result4 = Calculate.ConvertStringToDouble(mat2.Groups[2].Value);
                                }
                                n += 1;
                            }
                        m.inresw = result1;
                        m.inresh = result2;
                        m.inaspect = result3 / result4;
                        m.pixelaspect = m.inaspect / ((double)m.inresw / (double)m.inresh);
                        m.invcodecshort = "MPEG2";
                    }
                    else if (ext == ".dga")
                    {
                        //Смотрим, на месте ли log-файл
                        string log_file = Calculate.RemoveExtention(m.infilepath) + "log";
                        if (File.Exists(log_file))
                        {
                            //Читаем log-файл
                            string text_log = "";
                            Match mat;
                            Regex r1 = new Regex(@"Frame.Size:.(\d+)x(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Regex r2 = new Regex(@"SAR:.(\d+):(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            int result1 = 1280; int result2 = 720; double result3 = 1; double result4 = 1; //Значения по-умолчанию
                            using (StreamReader sr = new StreamReader(log_file, System.Text.Encoding.Default))
                                text_log = sr.ReadToEnd();

                            mat = r1.Match(text_log);
                            if (mat.Success)
                            {
                                result1 = Convert.ToInt32(mat.Groups[1].Value);
                                result2 = Convert.ToInt32(mat.Groups[2].Value);
                            }
                            mat = r2.Match(text_log);
                            if (mat.Success)
                            {
                                result3 = Convert.ToDouble(mat.Groups[1].Value);
                                result4 = Convert.ToDouble(mat.Groups[2].Value);
                            }

                            m.inresw = result1;
                            m.inresh = result2;
                            m.inaspect = (result3 / result4) * ((double)m.inresw / (double)m.inresh);
                            m.pixelaspect = m.inaspect / ((double)m.inresw / (double)m.inresh);
                            //можно еще определить тут фпс, но всё-равно это будет сделано позже через ависинт-скрипт (class Caching).
                            m.invcodecshort = "h264";
                        }
                        else
                        {
                            //Если нет log-файла, ищем исходный файл и берем инфу из него
                            Match mat;
                            string source_file = "";
                            Regex r = new Regex(@"(\D:\\.*\..*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            using (StreamReader sr = new StreamReader(m.indexfile, System.Text.Encoding.Default))
                                for (int i = 0; i < 3 && !sr.EndOfStream; i += 1)
                                {
                                    source_file = sr.ReadLine();
                                }
                            mat = r.Match(source_file);
                            if (mat.Success && File.Exists(source_file = mat.Groups[1].Value))
                            {
                                MediaInfoWrapper media = new MediaInfoWrapper();
                                media.Open(source_file);
                                m.invcodecshort = media.VCodecShort;
                                m.inresw = media.Width;
                                m.inresh = media.Height;
                                m.inaspect = media.Aspect;
                                m.pixelaspect = media.PixelAspect;
                                media.Close();
                            }
                            else
                            {
                                throw new Exception(Languages.Translate("Can`t find DGAVCIndex log-file:") + " " + log_file +
                                    "\r\n" + Languages.Translate("And can`t determine the source-file."));
                            }
                        }
                    }
                    else if (ext == ".dgi")
                    {
                        //Путь к декодеру
                        using (StreamReader sr = new StreamReader(m.indexfile, System.Text.Encoding.Default))
                            for (int i = 0; i < 2 && !sr.EndOfStream; i += 1)
                            {
                                m.dgdecnv_path = sr.ReadLine();
                            }
                        if (!File.Exists(m.dgdecnv_path + "DGDecodeNV.dll"))
                        {
                            throw new Exception(Languages.Translate("Can`t find file") + ": " + m.dgdecnv_path + "DGDecodeNV.dll");
                        }

                        //Смотрим, на месте ли log-файл
                        string log_file = Calculate.RemoveExtention(m.infilepath) + "log";
                        if (File.Exists(log_file))
                        {
                            //Читаем log-файл
                            Match mat;
                            string text_log = "";
                            Regex r1 = new Regex(@"Coded.Size:.(\d+)x(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Regex r2 = new Regex(@"SAR:.(\d+):(\d+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Regex r3 = new Regex(@"Aspect.Ratio:.(\d+\.*\d*):(\d+\.*\d*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            Regex r4 = new Regex(@"Video.Type:.(.*).", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            double result1, result2;
                            text_log = File.ReadAllText(log_file, System.Text.Encoding.Default);

                            //Разрешение (Coded Size:)
                            mat = r1.Match(text_log);
                            if (mat.Success)
                            {
                                m.inresw = Convert.ToInt32(mat.Groups[1].Value);
                                m.inresh = Convert.ToInt32(mat.Groups[2].Value);

                                //Аспект (SAR:)
                                mat = r2.Match(text_log);
                                if (mat.Success)
                                {
                                    result1 = Convert.ToDouble(mat.Groups[1].Value);
                                    result2 = Convert.ToDouble(mat.Groups[2].Value);

                                    m.inaspect = (result1 / result2) * ((double)m.inresw / (double)m.inresh);
                                    m.pixelaspect = result1 / result2;
                                }
                                else
                                {
                                    //Аспект (Aspect Ratio:)
                                    mat = r3.Match(text_log);
                                    if (mat.Success)
                                    {
                                        result1 = Calculate.ConvertStringToDouble(mat.Groups[1].Value);
                                        result2 = Calculate.ConvertStringToDouble(mat.Groups[2].Value);

                                        m.inaspect = result1 / result2;
                                        m.pixelaspect = m.inaspect / ((double)m.inresw / (double)m.inresh);
                                    }
                                    else
                                    {
                                        m.inaspect = (double)m.inresw / (double)m.inresh;
                                        m.pixelaspect = 1.0;
                                    }
                                }
                            }
                            else
                            {
                                m.inaspect = 16.0 / 9.0;
                                m.pixelaspect = 1.0;
                            }

                            //Кодек
                            mat = r4.Match(text_log);
                            if (mat.Success)
                            {
                                string codec = mat.Groups[1].Value;
                                if (codec == "AVC") codec = "h264";
                                m.invcodecshort = codec;
                            }
                        }
                        else
                        {
                            //Если нет log-файла, ищем исходный файл и берем инфу из него
                            string source_file = "";
                            Regex r = new Regex(@"(\D:\\.*\..*)\s\d+", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
                            using (StreamReader sr = new StreamReader(m.indexfile, System.Text.Encoding.Default))
                                for (int i = 0; i < 4 && !sr.EndOfStream; i += 1)
                                {
                                    source_file = sr.ReadLine();
                                }
                            Match mat = r.Match(source_file);
                            if (mat.Success && File.Exists(source_file = mat.Groups[1].Value))
                            {
                                MediaInfoWrapper media = new MediaInfoWrapper();
                                media.Open(source_file);
                                m.invcodecshort = media.VCodecShort;
                                m.inresw = media.Width;
                                m.inresh = media.Height;
                                m.inaspect = media.Aspect;
                                m.pixelaspect = media.PixelAspect;
                                media.Close();
                            }
                            else
                            {
                                throw new Exception(Languages.Translate("Can`t find DGIndexNV log-file:") + " " + log_file +
                                   "\r\n" + Languages.Translate("And can`t determine the source-file."));
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    //Довбиваем параметры с помощью FFmpeg
                    ff = new FFInfo();
                    ff.Open(m.infilepath);

                    //Выходим при отмене
                    if (m == null || worker.CancellationPending)
                        return;

                    //Видео
                    if (ff.VideoStreams().Count > 0)
                    {
                        m.invideostream_ff_order = ff.FirstVideoStreamID();
                        m.invideostream_ff_order_filtered = ff.FilteredStreamOrder(m.invideostream_ff_order);
                        if (m.invideostream_mi_order < 0) m.invideostream_mi_order = m.invideostream_ff_order;

                        if (ext == ".avs")
                        {
                            m.invcodec = ff.StreamCodec(m.invideostream_ff_order);
                            m.invcodecshort = ff.StreamCodecShort(m.invideostream_ff_order);
                            m.invbitrate = ff.VideoBitrate(m.invideostream_ff_order);
                            m.inresw = ff.StreamW(m.invideostream_ff_order);
                            m.inresh = ff.StreamH(m.invideostream_ff_order);
                            m.inaspect = (double)m.inresw / (double)m.inresh;
                        }
                        else
                        {
                            //Через MI нашелся только звук, но у FFmpeg есть и видео
                            if (!m.isvideo)
                            {
                                if (ext != ".cda")
                                {
                                    m.isvideo = true;
                                    m.invcodec = ff.StreamCodec(m.invideostream_ff_order);
                                    m.invcodecshort = ff.StreamCodecShort(m.invideostream_ff_order);
                                    m.invbitrate = ff.VideoBitrate(m.invideostream_ff_order);
                                    m.inresw = ff.StreamW(m.invideostream_ff_order);
                                    m.inresh = ff.StreamH(m.invideostream_ff_order);

                                    double sar = ff.CalculateSAR(m.invideostream_ff_order);
                                    m.pixelaspect = (sar != 0) ? sar : 1.0;
                                    double dar = ff.CalculateDAR(m.invideostream_ff_order);
                                    m.inaspect = (dar != 0) ? dar : ((double)m.inresw / (double)m.inresh);

                                    //Обнуляем аудио пути (там сейчас вписан сам исходник и декодер под его расширение)
                                    foreach (AudioStream stream in m.inaudiostreams)
                                    {
                                        stream.audiopath = null;
                                        stream.audiofiles = null;
                                        stream.decoder = 0;
                                    }
                                }
                            }
                            else if (Settings.UseFFmpegAR)
                            {
                                double sar = ff.CalculateSAR(m.invideostream_ff_order);
                                if (sar != 0) m.pixelaspect = sar;
                                double dar = ff.CalculateDAR(m.invideostream_ff_order);
                                if (dar != 0) m.inaspect = dar;
                            }
                        }

                        //null - MediaInfo для этого файла не запускалась (avs, grf,..)
                        //"" - MediaInfo запускалась, но нужной инфы получить не удалось
                        //При null тут все-же можно определить fps для avs, но т.к. FFmpeg
                        //сильно округляет fps, то лучше сами позже определим его в Caching().
                        if (m.inframerate == "")
                        {
                            m.inframerate = ff.StreamFramerate(m.invideostream_ff_order);
                            if (m.inframerate != "")
                            {
                                m.induration = ff.Duration();
                                m.outduration = m.induration;
                                m.inframes = (int)(m.induration.TotalSeconds * Calculate.ConvertStringToDouble(m.inframerate));
                            }
                        }
                    }

                    //Аудио
                    if (ff.AudioStreams().Count > 0)
                    {
                        ArrayList AStreams = ff.AudioStreams();
                        ArrayList AStreams_done = new ArrayList();

                        //подправляем кодек, ffID, язык
                        //Это будет работать как надо, только если очерёдность наших треков
                        //совпадает с их очерёдностью в FFmpeg, иначе инфа о треках перепутается!
                        int astream = 0;
                        foreach (AudioStream stream in m.inaudiostreams)
                        {
                            stream.ff_order = (int)AStreams[astream]; //ID трека для FFmpeg
                            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);
                            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);
                            }

                            AStreams_done.Add(AStreams[astream]);

                            astream++;
                            if (astream >= AStreams.Count) break;
                        }

                        //Удаляем все FF-треки, инфа от которых уже взята
                        foreach (object obj in AStreams_done)
                            AStreams.Remove(obj);

                        //Еще раз перепроверка для звуковых файлов (файл без видео), если
                        //выше через MI это не отловилось (т.е. через MI звук не обнаружился)
                        bool is_audio_only = (m.isvideo && string.IsNullOrEmpty(m.inframerate) && string.IsNullOrEmpty(m.invcodec) && (m.inresw == 0 || m.inresh == 0) && ff.VideoStreams().Count == 0);

                        if ((m.indexfile == null && Settings.EnableAudio || ext == ".avs" || is_audio_only) && AStreams.Count > 0)
                        {
                            //забиваем аудио, если они ещё не забиты (если FF-треков осталось больше, чем у нас уже есть)
                            //Все оставшиеся треки от FFmpeg добавляются к уже имеющимся. Тут тоже нужно как-то
                            //сопоставлять треки, и объединить это всё с кодом, который выше!
                            foreach (int stream_num in AStreams)
                            {
                                AudioStream stream = new AudioStream();
                                stream.ff_bits = ff.StreamBits(stream_num);
                                stream.ff_codec = stream.codec = ff.StreamCodec(stream_num);
                                stream.codecshort = ff.StreamCodecShort(stream_num);
                                stream.bitrate = ff.AudioBitrate(stream_num);
                                stream.samplerate = ff.StreamSamplerate(stream_num);
                                stream.bits = ff.StreamBits(stream_num);
                                stream.channels = ff.StreamChannels(stream_num);
                                stream.language = ff.StreamLanguage(stream_num);
                                stream.mi_order = stream.ff_order = stream_num;
                                stream.ff_order_filtered = ff.FilteredStreamOrder(stream_num);

                                if (is_audio_only)
                                {
                                    m.isvideo = false;
                                    stream.audiopath = m.infilepath;
                                    stream.audiofiles = new string[] { stream.audiopath };
                                    stream = Format.GetValidADecoder(stream);
                                }

                                m.inaudiostreams.Add(stream.Clone());
                            }

                            m.inaudiostream = 0;
                        }
                    }

                    //Закрываем FFInfo
                    CloseFFInfo();
                }

                if (!m.isvideo)
                {
                    m.invcodec = m.invcodecshort = "NONE";
                    m.inframerate = m.outframerate = "25.000";
                    m.vdecoder = AviSynthScripting.Decoders.BlankClip;

                    //Кол-во кадров и продолжительность определятся в Caching()
                    //на основе реальной продолжительности звука от декодера
                    m.induration = m.outduration = TimeSpan.Zero;
                    m.inframes = m.outframes = 0;
                }

                //определяем аудио декодер
                foreach (AudioStream stream in m.inaudiostreams)
                {
                    if (stream.decoder == 0)
                        stream.decoder = Format.GetValidADecoder(stream).decoder;
                }

                //подсчитываем размер
                long sizeb = 0;
                foreach (string f in m.infileslist)
                {
                    FileInfo info = new FileInfo(f);
                    sizeb += info.Length;
                }
                m.infilesize = Calculate.ConvertDoubleToPointString((double)sizeb / 1049511, 1) + " mb";
                m.infilesizeint = (int)((double)sizeb / 1049511);
            }
            catch (Exception ex)
            {
                if (worker != null && !worker.CancellationPending && m != null && num_closes == 0)
                {
                    //Ошибка
                    e.Result = ex;
                }

                m = null;
            }
        }
Beispiel #39
0
        private void combo_mode_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if ((combo_mode.IsDropDownOpen || combo_mode.IsSelectionBoxHighlighted) && combo_mode.SelectedItem != null)
            {
                string mode = combo_mode.SelectedItem.ToString();
                if (mode == "CBR")
                {
                    m.qaac_options.encodingmode = Settings.AudioEncodingModes.CBR;
                }
                else if (mode == "ABR")
                {
                    m.qaac_options.encodingmode = Settings.AudioEncodingModes.ABR;
                }
                else if (mode == "Constrained VBR")
                {
                    m.qaac_options.encodingmode = Settings.AudioEncodingModes.CVBR;
                }
                else if (mode == "Lossless (ALAC)")
                {
                    m.qaac_options.encodingmode = Settings.AudioEncodingModes.ALAC;
                }
                else
                {
                    m.qaac_options.encodingmode = Settings.AudioEncodingModes.VBR;
                    if (combo_aac_profile.SelectedIndex == 1)
                    {
                        //AAC-HE запрещен при True VBR
                        combo_aac_profile.SelectedIndex = 0;
                        m.qaac_options.aacprofile       = "AAC-LC";
                    }
                }

                LoadBitrates();

                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                if (m.qaac_options.encodingmode == Settings.AudioEncodingModes.VBR)
                {
                    combo_bitrate.SelectedIndex = m.qaac_options.quality;
                }
                else if (m.qaac_options.encodingmode == Settings.AudioEncodingModes.ALAC)
                {
                    combo_bitrate.SelectedIndex = combo_bitrate.Items.Count - 1;
                }
                else
                {
                    combo_bitrate.SelectedItem = outstream.bitrate;
                }

                root_window.UpdateOutSize();
                root_window.UpdateManualProfile();
            }

            if (combo_mode.SelectedIndex != -1)
            {
                if (combo_mode.SelectedIndex < 3)
                {
                    combo_bitrate.ToolTip       = combo_bitrate.Tag;
                    combo_aac_profile.IsEnabled = true;
                    text_bitrate.Content        = str_bitrate + " (?)";
                }
                else
                {
                    combo_bitrate.ToolTip       = null;
                    combo_aac_profile.IsEnabled = false;
                    text_bitrate.Content        = (combo_mode.SelectedIndex == 3) ? str_quality : str_bitrate;
                }

                if (combo_aac_profile.SelectedIndex == 1 ||  //AAC-HE
                    combo_mode.SelectedIndex == 4)           //ALAC
                {
                    m.qaac_options.no_delay  = false;
                    check_no_delay.IsChecked = false;
                    check_no_delay.IsEnabled = false;
                }
                else
                {
                    check_no_delay.IsEnabled = true;
                }

                combo_bitrate.IsEnabled = combo_accuracy.IsEnabled = (combo_mode.SelectedIndex != 4);
            }
        }
Beispiel #40
0
        //начало открытия файла
        private void action_open(Massive x)
        {
            try
            {
                if (x == null) return;

                //Если AviSynth не был найден при старте и не был установлен после него
                if (SysInfo.AVSVersionFloat == 0 && !SysInfo.RetrieveAviSynthInfo())
                {
                    throw new Exception(Languages.Translate("AviSynth is not found!") + "\r\n" +
                        Languages.Translate("Please install AviSynth 2.5.7 MT or higher."));
                }

                string ext = Path.GetExtension(x.infilepath).ToLower();

                //Уводим фокус с комбобоксов куда-нибудь!
                if (!slider_pos.Focus()) slider_Volume.Focus();

                //Проверка на "нехорошие" символы в путях
                if (ext != ".tsks" && !Calculate.ValidatePath(x.infilepath, !IsBatchOpening))
                    return;

                //Закрываем уже открытый файл; обнуляем трим и его кнопки
                if (!IsBatchOpening && m != null) CloseFile(false);
                else ResetTrim();

                //Загружаем сохраненные задания
                if (ext == ".tsks")
                {
                    RestoreTasks(x.infilepath, ref x);

                    //Выходим при ошибке или если были только одни задания;
                    //если был и массив, то открываем его
                    if (x == null) return;
                    else m = x.Clone();
                    x = null;

                    LoadVideoPresets();

                    if (m.outaudiostreams.Count > 0)
                    {
                        AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                        LoadAudioPresets();
                        combo_aencoding.SelectedItem = outstream.encoding;
                        Settings.SetAEncodingPreset(m.format, outstream.encoding);
                    }
                    else
                    {
                        combo_aencoding.SelectedItem = "Disabled";
                    }

                    combo_format.SelectedItem = Format.EnumToString(Settings.FormatOut = m.format);
                    combo_sbc.SelectedItem = Settings.SBC = m.sbc;
                    combo_filtering.SelectedValue = Settings.Filtering = m.filtering;
                    combo_vencoding.SelectedItem = m.vencoding;
                    Settings.SetVEncodingPreset(m.format, m.vencoding);

                    goto finish;
                }

                //Определяем, где создавать индекс-файлы для FFmpegSource2 + занесение их в список на удаление
                if (!(x.ffms_indexintemp = (Settings.FFMS_IndexInTemp || Calculate.IsReadOnly(x.infilepath))))
                {
                    foreach (string file in x.infileslist)
                    {
                        if (!ffcache.Contains(file + ".ffindex"))
                            ffcache.Add(file + ".ffindex");
                    }
                }

                //Возможные индекс-файлы от LSMASH
                foreach (string file in x.infileslist)
                {
                    if (!lsmashcache.Contains(file + ".lwi"))
                        lsmashcache.Add(file + ".lwi");
                }

                //присваиваем заданию уникальный ключ
                if (Settings.Key == "9999")
                    Settings.Key = "0000";
                x.key = Settings.Key;

                //имя
                if (x.taskname == null)
                    x.taskname = Path.GetFileNameWithoutExtension(x.infilepath);

                //забиваем основные параметры кодирования
                x.format = Settings.FormatOut;
                x.sbc = Settings.SBC;
                x = ColorCorrection.DecodeProfile(x);
                x.filtering = Settings.Filtering;
                x.resizefilter = Settings.ResizeFilter;

                //Звук для d2v, dga и dgi файлов
                if (ext == ".d2v" || ext == ".dga" || ext == ".dgi")
                {
                    x.indexfile = x.infilepath;
                    ArrayList atracks = Indexing.GetTracks(x.indexfile);
                    int n = 0;
                    if (atracks.Count > 0 && Settings.EnableAudio)
                    {
                        foreach (string apath in atracks)
                        {
                            //забиваем в список все найденные треки
                            MediaInfoWrapper mi = new MediaInfoWrapper();
                            AudioStream stream = mi.GetAudioInfoFromAFile(apath, true);
                            stream.delay = Calculate.GetDelay(apath);
                            x.inaudiostreams.Add(stream.Clone());
                            n++;
                        }
                        x.inaudiostream = 0;
                    }
                }

                //блок для файлов с обязательной разборкой
                if (ext == ".dpg")
                {
                    x.invcodecshort = "MPEG1";
                    string outext = Format.GetValidRAWVideoEXT(x);
                    string vpath = Settings.TempPath + "\\" + x.key + "." + outext;
                    string apath = Settings.TempPath + "\\" + x.key + "_0.mp2";

                    //удаляем старый файл
                    SafeDelete(vpath);
                    SafeDelete(apath);

                    //извлекаем новый файл
                    Demuxer dem = new Demuxer(x, Demuxer.DemuxerMode.ExtractVideo, vpath);
                    if (!dem.IsErrors && Settings.EnableAudio) dem = new Demuxer(x, Demuxer.DemuxerMode.ExtractAudio, apath);

                    //проверка на удачное завершение
                    if (File.Exists(vpath) && new FileInfo(vpath).Length != 0)
                    {
                        x.infilepath_source = x.infilepath;
                        x.infilepath = vpath;
                        x.infileslist = new string[] { x.infilepath };
                        deletefiles.Add(vpath);
                    }

                    //проверка на удачное завершение
                    if (File.Exists(apath) && new FileInfo(apath).Length != 0)
                    {
                        AudioStream stream = new AudioStream();
                        stream.audiopath = apath;
                        stream.audiofiles = new string[] { apath };
                        stream = Format.GetValidADecoder(stream);
                        x.inaudiostreams.Add(stream.Clone());
                        x.inaudiostream = 0;
                        deletefiles.Add(apath);
                    }
                }

                //Имя для DVD
                if (Calculate.IsValidVOBName(x.infilepath))
                {
                    x.dvdname = Calculate.GetDVDName(x.infilepath);
                    string title = Calculate.GetTitleNum(x.infilepath);
                    if (!string.IsNullOrEmpty(title)) title = "_T" + title;
                    x.taskname = x.dvdname + title;
                }

                //Определяем видеодекодер (#1)
                x.vdecoder = Format.GetValidVDecoder(x);

                //Проверка необходимости индексации для DGIndex\DGIndexNV
                if (x.vdecoder == AviSynthScripting.Decoders.MPEG2Source && ext != ".d2v" || x.vdecoder == AviSynthScripting.Decoders.DGSource && ext != ".dgi")
                {
                    if (x.vdecoder == AviSynthScripting.Decoders.MPEG2Source)
                    {
                        //Проверяем индекс папку (проверка содержимого файла для DGIndex - если там MPEG1\2, то можно индексировать; тут-же идет запуск MediaInfo)
                        IndexChecker ich = new IndexChecker(x, false);
                        if (ich.m == null) return;
                        x = ich.m.Clone();

                        if (x.indexfile != null)
                        {
                            //Индексация DGIndex
                            if (!File.Exists(x.indexfile))
                            {
                                Indexing index = new Indexing(x);
                                if (index.m == null) return;
                                x = index.m.Clone();
                            }

                            //Добавление кэш-файла в список на удаление
                            if (!dgcache.Contains(x.indexfile) && Path.GetDirectoryName(x.indexfile).EndsWith(".index") && x.indexfile != x.infilepath)
                                dgcache.Add(x.indexfile);
                        }
                        else if (x.vdecoder == 0)
                        {
                            //Определяем видеодекодер (#2)
                            //Файл распознался, как MPEG-PS\TS, но внутри оказался не MPEG1\2, поэтому декодер обнулился.
                            //Вторая попытка - на случай, если для "другие файлы" выбран DGSource.
                            x.vdecoder = Format.GetValidVDecoder(x);
                        }
                    }

                    if (x.vdecoder == AviSynthScripting.Decoders.DGSource)
                    {
                        //Проверяем индекс папку
                        IndexChecker ich = new IndexChecker(x, true);
                        if (ich.m == null) return;
                        x = ich.m.Clone();

                        if (x.indexfile != null)
                        {
                            //Индексация DGIndexNV
                            if (!File.Exists(x.indexfile))
                            {
                                Indexing_DGIndexNV index = new Indexing_DGIndexNV(x);
                                if (index.m == null) return;
                                x = index.m.Clone();
                            }

                            //Добавление кэш-файла в список на удаление
                            if (!dgcacheNV.Contains(x.indexfile) && Path.GetDirectoryName(x.indexfile).EndsWith(".idxNV") && x.indexfile != x.infilepath)
                                dgcacheNV.Add(x.indexfile);
                        }
                    }
                }

                //получаем информацию через MediaInfo
                if (ext != ".vdr")
                {
                    Informer info = new Informer(x);
                    if (info.m == null) return;
                    x = info.m.Clone();
                }

                //Определяем видеодекодер (#3), т.к. выше он мог обнулиться
                if (x.vdecoder == 0) x.vdecoder = Format.GetValidVDecoder(x);

                //принудительный фикс цвета для DVD
                if (Settings.AutoColorMatrix && x.format != Format.ExportFormats.Audio)
                {
                    if (x.iscolormatrix == false &&
                        x.invcodecshort == "MPEG2")
                    {
                        x.iscolormatrix = true;
                        if (combo_sbc.Items.Contains("MPEG2Fix") &&
                            Settings.SBC == "Disabled")
                            combo_sbc.SelectedItem = "MPEG2Fix";
                    }
                }

                //похоже что к нам идёт звковой файл
                if (x.format != Format.ExportFormats.Audio && !x.isvideo)
                {
                    Settings.FormatOut = x.format = Format.ExportFormats.Audio;
                    combo_format.SelectedItem = Format.EnumToString(Format.ExportFormats.Audio);
                    LoadAudioPresets();
                    SetAudioPreset();
                }

                //Индексация для FFmpegSource2
                if (x.vdecoder == AviSynthScripting.Decoders.FFmpegSource2)
                {
                    Indexing_FFMS ffindex = new Indexing_FFMS(x);
                    if (ffindex.m == null) return;
                }

                if (x.inaudiostreams.Count > 0 && Settings.EnableAudio)
                {
                    //Автовыбор трека
                    if (x.inaudiostreams.Count > 1)
                    {
                        if (Settings.DefaultATrackMode == Settings.ATrackModes.Language)
                        {
                            //По языку
                            for (int i = 0; i < x.inaudiostreams.Count; i++)
                            {
                                if (((AudioStream)x.inaudiostreams[i]).language.ToLower() == Settings.DefaultATrackLang.ToLower())
                                {
                                    x.inaudiostream = i;
                                    break;
                                }
                            }
                        }
                        else if (Settings.DefaultATrackMode == Settings.ATrackModes.Number)
                        {
                            //По номеру
                            x.inaudiostream = Settings.DefaultATrackNum - 1;
                            if (x.inaudiostream >= x.inaudiostreams.Count)
                                x.inaudiostream = 0;
                        }

                        AudioStream instream = (AudioStream)x.inaudiostreams[x.inaudiostream];

                        //Требуется извлечение звука
                        if (instream.audiopath == null && instream.decoder == 0 && x.inaudiostream > 0)
                        {
                            //FFMS2 и LSMASH умеют переключать треки, для них их можно не извлекать
                            if (!(x.vdecoder == AviSynthScripting.Decoders.FFmpegSource2 && Settings.FFMS_Enable_Audio ||
                                ((x.vdecoder == AviSynthScripting.Decoders.LSMASHVideoSource || x.vdecoder == AviSynthScripting.Decoders.LWLibavVideoSource) &&
                                Settings.LSMASH_Enable_Audio)))
                            {
                                string outext = Format.GetValidRAWAudioEXT(instream.codecshort);
                                instream.audiopath = Settings.TempPath + "\\" + x.key + "_" + x.inaudiostream + outext;
                                instream.audiofiles = new string[] { instream.audiopath };
                                instream = Format.GetValidADecoder(instream);
                            }
                        }
                    }

                    //Извлечение звука (если запрещено прямое декодирование из исходника, декодер этого не умеет или это автовыбор трека)
                    if (x.vdecoder == AviSynthScripting.Decoders.FFmpegSource2 && !Settings.FFMS_Enable_Audio ||
                        x.vdecoder == AviSynthScripting.Decoders.DirectShowSource && !Settings.DSS_Enable_Audio ||
                        (x.vdecoder == AviSynthScripting.Decoders.LSMASHVideoSource || x.vdecoder == AviSynthScripting.Decoders.LWLibavVideoSource) &&
                        !Settings.LSMASH_Enable_Audio || x.vdecoder == AviSynthScripting.Decoders.DirectShowSource2 ||
                        ((AudioStream)x.inaudiostreams[x.inaudiostream]).audiopath != null && x.isvideo)
                    {
                        AudioStream instream = (AudioStream)x.inaudiostreams[x.inaudiostream];
                        if (instream.audiopath == null || !File.Exists(instream.audiopath))
                        {
                            string outpath = (instream.audiopath == null) ? Settings.TempPath + "\\" + x.key + "_" + x.inaudiostream +
                                Format.GetValidRAWAudioEXT(instream.codecshort) : instream.audiopath;

                            //удаляем старый файл
                            SafeDelete(outpath);

                            //извлекаем новый файл
                            if (Path.GetExtension(outpath) == ".wav")
                            {
                                Decoder dec = new Decoder(x, Decoder.DecoderModes.DecodeAudio, outpath);
                                if (dec.IsErrors) throw new Exception("Decode to WAV: " + dec.error_message);
                            }
                            else
                            {
                                Demuxer dem = new Demuxer(x, Demuxer.DemuxerMode.ExtractAudio, outpath);
                                if (dem.IsErrors) throw new Exception(dem.error_message);
                            }

                            //проверка на удачное завершение
                            if (File.Exists(outpath) && new FileInfo(outpath).Length != 0)
                            {
                                instream.audiopath = outpath;
                                instream.audiofiles = new string[] { outpath };
                                instream = Format.GetValidADecoder(instream);
                                deletefiles.Add(outpath);
                            }
                        }
                    }
                }

                //получаем выходной фреймрейт
                x = Format.GetValidFramerate(x);
                x = Calculate.UpdateOutFrames(x);

                //Получаем информацию через AviSynth и ловим ошибки
                Caching cach = new Caching(x, false);
                if (cach.m == null) return;
                x = cach.m.Clone();

                //забиваем-обновляем аудио массивы
                x = FillAudio(x);

                //выбираем трек
                if (x.inaudiostreams.Count > 1 && Settings.EnableAudio && Settings.DefaultATrackMode == Settings.ATrackModes.Manual)
                {
                    AudioOptions ao = new AudioOptions(x, this, AudioOptions.AudioOptionsModes.TracksOnly);
                    if (ao.m == null) return;
                    x = ao.m.Clone();
                }

                //извлечение трека при badmixing
                if (x.inaudiostreams.Count == 1 && Settings.EnableAudio)
                {
                    AudioStream instream = (AudioStream)x.inaudiostreams[x.inaudiostream];

                    if (instream.badmixing)
                    {
                        string outext = Format.GetValidRAWAudioEXT(instream.codecshort);
                        instream.audiopath = Settings.TempPath + "\\" + x.key + "_" + x.inaudiostream + outext;
                        instream.audiofiles = new string[] { instream.audiopath };
                        instream = Format.GetValidADecoder(instream);

                        if (!File.Exists(instream.audiopath))
                        {
                            Demuxer dem = new Demuxer(x, Demuxer.DemuxerMode.ExtractAudio, instream.audiopath);
                            if (dem.IsErrors) throw new Exception(dem.error_message);
                        }
                    }
                }

                //забиваем видео настройки
                if (x.format != Format.ExportFormats.Audio)
                {
                    x.vencoding = Settings.GetVEncodingPreset(Settings.FormatOut);
                    x.outvcodec = PresetLoader.GetVCodec(x);
                    x.vpasses = PresetLoader.GetVCodecPasses(x);
                }
                else
                {
                    x.vencoding = "Disabled";
                    x.outvcodec = "Disabled";
                    x.vpasses.Clear();
                    combo_vencoding.SelectedItem = x.vencoding;
                }

                //забиваем аргументы к кодированию аудио и видео
                x = PresetLoader.DecodePresets(x);

                //автоматический деинтерлейс
                if (x.format != Format.ExportFormats.Audio)
                {
                    //Клонируем деинтерлейс от предыдущего файла
                    if (IsBatchOpening && m != null && Settings.BatchCloneDeint)
                    {
                        x.interlace = m.interlace;
                        x.fieldOrder = m.fieldOrder;
                        x.deinterlace = m.deinterlace;
                    }
                    else
                    {
                        if (Settings.AutoDeinterlaceMode == Settings.AutoDeinterlaceModes.AllFiles &&
                            x.outvcodec != "Copy" ||
                            Settings.AutoDeinterlaceMode == Settings.AutoDeinterlaceModes.MPEGs &&
                            Calculate.IsMPEG(x.infilepath) &&
                            x.outvcodec != "Copy" ||
                            Settings.AutoDeinterlaceMode == Settings.AutoDeinterlaceModes.MPEGs &&
                            ext == ".evo" &&
                            x.outvcodec != "Copy")
                        {
                            if (x.inframerate == "23.976")
                            {
                                x.interlace = SourceType.PROGRESSIVE;
                                x = Format.GetOutInterlace(x);
                            }
                            else
                            {
                                //перепроверяем входной интерлейс
                                SourceDetector sd = new SourceDetector(x);
                                if (sd.m != null) x = sd.m.Clone();
                            }
                        }
                        else
                        {
                            x = Format.GetOutInterlace(x);
                        }
                    }
                }

                //ищем субтитры
                if (x.format != Format.ExportFormats.Audio)
                {
                    string subs = Calculate.RemoveExtention(x.infilepath, true);
                    if (File.Exists(subs + ".srt")) x.subtitlepath = subs + ".srt";
                    if (File.Exists(subs + ".sub")) x.subtitlepath = subs + ".sub";
                    if (File.Exists(subs + ".idx")) x.subtitlepath = subs + ".idx";
                    if (File.Exists(subs + ".ssa")) x.subtitlepath = subs + ".ssa";
                    if (File.Exists(subs + ".ass")) x.subtitlepath = subs + ".ass";
                    if (File.Exists(subs + ".psb")) x.subtitlepath = subs + ".psb";
                    if (File.Exists(subs + ".smi")) x.subtitlepath = subs + ".smi";
                }

                //автокроп
                if (x.format != Format.ExportFormats.Audio)
                {
                    //Клонируем разрешение от предыдущего файла
                    if (IsBatchOpening && m != null && Settings.BatchCloneAR)
                    {
                        x.outresw = m.outresw;
                        x.outresh = m.outresh;
                        x.cropl = x.cropl_copy = m.cropl;
                        x.cropt = x.cropt_copy = m.cropt;
                        x.cropr = x.cropr_copy = m.cropr;
                        x.cropb = x.cropb_copy = m.cropb;
                        x.blackw = m.blackw;
                        x.blackh = m.blackh;
                        x.flipv = m.flipv;
                        x.fliph = m.fliph;
                        x.outaspect = m.outaspect;
                        x.aspectfix = m.aspectfix;
                        x.sar = m.sar;
                    }
                    else
                    {
                        if (Settings.AutocropMode == Autocrop.AutocropMode.AllFiles &&
                        x.outvcodec != "Copy" ||
                        Settings.AutocropMode == Autocrop.AutocropMode.MPEGOnly &&
                        Calculate.IsMPEG(x.infilepath) &&
                        x.outvcodec != "Copy")
                        {
                            if (x.format != Format.ExportFormats.BluRay)
                            {
                                Autocrop acrop = new Autocrop(x, this, -1);
                                if (acrop.m != null) x = acrop.m.Clone();
                            }
                        }

                        //подправляем входной аспект
                        x = AspectResolution.FixInputAspect(x);

                        //забиваем видео параметры на выход
                        x = Format.GetValidResolution(x);
                        x = Format.GetValidOutAspect(x);
                        x = AspectResolution.FixAspectDifference(x);
                    }

                    //Клонируем частоту кадров от предыдущего файла
                    if (IsBatchOpening && m != null && Settings.BatchCloneFPS)
                    {
                        x.outframerate = m.outframerate;
                    }
                    else
                    {
                        x = Format.GetValidFramerate(x);
                    }

                    //обновление выходных битрейтов
                    if (x.outvcodec == "Disabled") x.outvbitrate = 0;
                }
                else
                {
                    //для звуковых заданий
                    x.outframerate = x.inframerate;
                    x.outresw = x.inresw;
                    x.outresh = x.inresh;
                    x.outaspect = x.inaspect;

                    //обнуляем делей
                    foreach (object o in x.outaudiostreams)
                    {
                        AudioStream s = (AudioStream)o;
                        s.delay = 0;
                    }

                    //запрещаем видео разделы
                    combo_vencoding.IsEnabled = false;
                    button_edit_vencoding.IsEnabled = false;
                    combo_sbc.IsEnabled = false;
                    button_edit_sbc.IsEnabled = false;
                }

                //переполучаем параметры из профилей
                x = PresetLoader.DecodePresets(x);

                //Клонируем Трим от предыдущего файла
                if (IsBatchOpening && m != null && Settings.BatchCloneTrim)
                {
                    x.trims = (ArrayList)m.trims.Clone();
                    x.trim_is_on = m.trim_is_on;
                    x.trim_num = m.trim_num;
                }

                //Пересчитываем кол-во кадров и продолжительность
                x = Calculate.UpdateOutFrames(x);

                //создаём AviSynth скрипт
                x = AviSynthScripting.CreateAutoAviSynthScript(x);

                //Автогромкость
                if (x.inaudiostreams.Count > 0)
                {
                    //определяем громкоcть
                    x.volume = Settings.Volume;
                    if (Settings.Volume != "Disabled" &&
                        Settings.AutoVolumeMode == Settings.AutoVolumeModes.OnImport)
                    {
                        Normalize norm = new Normalize(x);
                        if (norm.m != null)
                        {
                            x = norm.m.Clone();
                            x = AviSynthScripting.CreateAutoAviSynthScript(x);
                        }
                    }
                }

                //проверка на размер
                x.outfilesize = Calculate.GetEncodingSize(x);

                //запрещаем профиль кодирования если нет звука
                if (x.inaudiostreams.Count == 0 || x.outaudiostreams.Count == 0)
                {
                    combo_aencoding.SelectedItem = "Disabled";
                }
                else
                {
                    if (combo_aencoding.SelectedItem.ToString() == "Disabled")
                        combo_aencoding.SelectedItem = Settings.GetAEncodingPreset(x.format);
                }

                //проверяем можно ли копировать данный формат
                if (x.vencoding == "Copy")
                {
                    string CopyProblems = Format.ValidateCopyVideo(x);
                    if (CopyProblems != null)
                    {
                        Message mess = new Message(this);
                        mess.ShowMessage(Languages.Translate("The stream contains parameters incompatible with this format") +
                            " " + Format.EnumToString(x.format) + ": " + CopyProblems + "." + Environment.NewLine +
                            Languages.Translate("(You see this message because video encoder = Copy)"), Languages.Translate("Warning"));
                    }
                }

                //передаём массив
                m = x.Clone();
                x = null;

            finish:

                //снимаем выделение
                list_tasks.SelectedIndex = -1;

                //загружаем скрипт в форму
                if (!IsBatchOpening)
                {
                    if (!PauseAfterFirst)
                    {
                        //Обновляем список недавно открытых файлов
                        string source = (string.IsNullOrEmpty(m.infilepath_source)) ? m.infilepath : m.infilepath_source;
                        string[] files = Settings.RecentFiles.Split(new string[] { ";" }, StringSplitOptions.None);
                        string output = source + "; ";

                        int items = 1; //Первый - source
                        int count = Settings.RecentFilesCount;
                        for (int i = 0; i < files.Length && items < count; i++)
                        {
                            string file = files[i].Trim();
                            if (file.Length > 0 && file != source)
                            {
                                output += (file + "; ");
                                items += 1;
                            }
                        }

                        Settings.RecentFiles = output;
                        UpdateRecentFiles();
                    }

                    LoadVideo(MediaLoad.load);
                }
            }
            catch (Exception ex)
            {
                //записываем плохой скрипт
                if (x != null && x.script != null)
                    AviSynthScripting.WriteScriptToFile(x.script, "error");

                x = null;

                if (ex.Message.Contains("DirectX"))
                {
                    Message mess = new Message(this);
                    mess.ShowMessage(Languages.Translate("Need update DirectX files! Do it now?"),
                        Languages.Translate("Error"), Message.MessageStyle.YesNo);
                    if (mess.result == Message.Result.Yes)
                    {
                        Process.Start(Calculate.StartupPath + "\\apps\\DirectX_Update\\dxwebsetup.exe");
                        Close();
                    }
                }
                else
                    ErrorException("LoadFile: " + ex.Message, ex.StackTrace);
            }
        }