示例#1
0
        private void button_play_Click(object sender, RoutedEventArgs e)
        {
            if (m.inaudiostreams.Count > 0 && m.outaudiostreams.Count > 0)
            {
                //определяем аудио потоки
                AudioStream instream  = (AudioStream)m.inaudiostreams[m.inaudiostream];
                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

                if (textbox_apath.Text != instream.audiopath)
                {
                    if (textbox_apath.Text == "")
                    {
                        instream.audiopath  = null;
                        instream.audiofiles = null;
                    }
                    else
                    {
                        instream.audiopath  = textbox_apath.Text;
                        instream.audiofiles = new string[] { instream.audiopath };
                    }
                }

                /* if (m.vdecoder == AviSynthScripting.Decoders.FFmpegSource)
                 * {
                 *   ////Получаем информацию через AviSynth и кешируем аудио для FFmpegSource
                 *   //Caching cach = new Caching(m);
                 *   //m = cach.m.Clone();
                 *
                 *   string script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.FastPreview);
                 *   AviSynthScripting.WriteScriptToFile(script, "tracker");
                 *   PlayInWPFPlayer(Settings.TempPath + "\\tracker.avs");
                 * }
                 * else   */
                {
                    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);
                            return;
                        }
                    }

                    string script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.FastPreview);
                    AviSynthScripting.WriteScriptToFile(script, "tracker");
                    if (instream.audiopath == null || File.Exists(instream.audiopath))
                    {
                        try
                        {
                            Process.Start(Calculate.StartupPath + "\\WPF_VideoPlayer.exe", Settings.TempPath + "\\tracker.avs");
                        }
                        catch (Exception ex)
                        {
                            ErrorException(ex.Message, ex.StackTrace);
                        }
                    }
                }
            }
        }
示例#2
0
        private void button_analysevolume_Click(object sender, RoutedEventArgs e)
        {
            //определяем аудио потоки
            AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];

            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);
                    return;
                }

                //обновляем скрипт
                m = AviSynthScripting.CreateAutoAviSynthScript(m);
            }

            AnalyseVolume();
            SetInfo();
        }
示例#3
0
        private void button_ok_Click(object sender, RoutedEventArgs e)
        {
            if (m.inaudiostreams.Count > 0)
            {
                //определяем аудио потоки
                AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];

                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);
                    }
                }

                if ((m.volume != "Disabled" && Settings.AutoVolumeMode != Settings.AutoVolumeModes.Disabled) &&
                    !instream.gaindetected)
                {
                    AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                    if (outstream.codec != "Copy")
                    {
                        AnalyseVolume();
                    }
                }
            }

            if (mode == AudioOptionsModes.AllOptions)
            {
                m = AviSynthScripting.CreateAutoAviSynthScript(m);
                if (p.m.script != m.script)
                {
                    Refresh();
                }
            }

            Close();
        }
示例#4
0
        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();
        }
示例#5
0
        private void demux_pmp(Demuxer.DemuxerMode dmode)
        {
            //определяем аудио потоки
            AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];
            AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

            //if (m.infileslist.Length > 1)
            //    ShowMessage(Languages.Translate("Sorry, but stream will be extracted only from first file! :("),
            //        Languages.Translate("Warning"));

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

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

            if (dmode == Demuxer.DemuxerMode.ExtractVideo)
                step++;

            busyfile = Path.GetFileName(m.infilepath);
            info.Arguments = "\"" + m.infilepath + "\"";

            m.outvideofile = m.infilepath + ".avi";
            outstream.audiopath = m.infilepath + ".1.aac";

            SetLog("Demuxing video stream to: " + m.outvideofile);
            SetLog(m.inresw + "x" + m.inresh + " " + m.invcodecshort + " " + m.invbitrate + "kbps " + m.inframerate + "fps" +
                Environment.NewLine);

            if (outstream.codec == "Copy")
            {
                SetLog("Demuxing audio stream to: " + outstream.audiopath);
                SetLog(instream.codecshort + " " + instream.bitrate + "kbps " + instream.channels + "ch " + instream.bits + "bit " + instream.samplerate + "khz" +
                    Environment.NewLine);
            }

            if (Settings.ArgumentsToLog)
            {
                SetLog("pmp_demuxer.exe: " + info.Arguments + Environment.NewLine);
            }

            encoderProcess.StartInfo = info;
            encoderProcess.Start();

            string line;
            string pat = @"(\d+)\D/\D(\d+)";
            Regex r = new Regex(pat, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
            Match mat;

            int outframes = m.outframes;
            m.outframes = m.inframes;
            SetMaximum(m.outframes);
            //первый проход
            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
                    {
                        AppendEncoderText(line);
                    }
                }
            }
            m.outframes = outframes;
            SetMaximum(m.outframes);

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

            if (IsAborted || IsErrors) return;

            if (!File.Exists(outstream.audiopath))
            {
                instream.codec = "MP3";
                outstream.audiopath = m.infilepath + ".1.mp3";
            }

            //проверка на удачное завершение
            if (!File.Exists(m.outvideofile) ||
                new FileInfo(m.outvideofile).Length == 0)
            {
                IsErrors = true;
                ErrorException(encodertext.ToString());
            }

            if (dmode == Demuxer.DemuxerMode.ExtractVideo)
            {
                if (outstream.codec == "Copy")
                {
                    if (new FileInfo(outstream.audiopath).Length == 0)
                    {
                        IsErrors = true;
                        ErrorException(encodertext.ToString());
                    }
                }
                else
                    File.Delete(outstream.audiopath);
            }

            encodertext.Length = 0;

            //вытягиваем RAW h264 из AVI
            string old_infilepath = m.infilepath;
            m.infilepath = m.outvideofile;
            m.outvideofile = null;
            demux_ffmpeg(Demuxer.DemuxerMode.ExtractVideo);
            SafeDelete(m.infilepath);
            m.infilepath = old_infilepath;
            SafeDelete(m.infilepath + ".log");
        }
示例#6
0
        private void demux_mp4box(Demuxer.DemuxerMode dmode)
        {
            //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;

            string outfile = "";

            if (dmode == Demuxer.DemuxerMode.ExtractAudio)
            {
                AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];
                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

                busyfile = Path.GetFileName(outstream.audiopath);

                outfile = outstream.audiopath;
                info.Arguments = "-raw " + instream.mi_id + " \"" + m.infilepath + "\" -out \"" + outfile + "\"";

                SetLog("Demuxing audio stream to: " + outstream.audiopath);
                SetLog(instream.codecshort + " " + instream.bitrate + "kbps " + instream.channels + "ch " + instream.bits + "bit " + instream.samplerate + "khz" +
                    Environment.NewLine);
            }
            else if (dmode == Demuxer.DemuxerMode.ExtractVideo)
            {
                step++;

                if (m.outvideofile == null)
                    m.outvideofile = Settings.TempPath + "\\" + m.key + "." + Format.GetValidRAWVideoEXT(m);

                //подхватываем готовый файл
                if (File.Exists(m.outvideofile))
                {
                    SetLog(Languages.Translate("Using already created file") + ": " + m.outvideofile + Environment.NewLine);
                    return;
                }

                busyfile = Path.GetFileName(m.outvideofile);

                SetLog("Demuxing video stream to: " + m.outvideofile);
                SetLog(m.inresw + "x" + m.inresh + " " + m.invcodecshort + " " + m.invbitrate + "kbps " + m.inframerate + "fps" +
                    Environment.NewLine);

                outfile = m.outvideofile;
                info.Arguments = "-raw " + m.invideostream_mi_id + " \"" + m.infilepath + "\" -out \"" + outfile + "\"";
            }

            if (Settings.ArgumentsToLog)
            {
                SetLog("mp4box.exe: " + info.Arguments + Environment.NewLine);
            }

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

            int outframes = m.outframes;
            m.outframes = m.inframes;
            SetMaximum(m.outframes);

            //Извлекаем
            Do_MP4Box_Cycle(info);

            m.outframes = outframes;
            SetMaximum(m.outframes);

            if (IsAborted || IsErrors) return;

            //проверка на удачное завершение
            if (!File.Exists(outfile) || new FileInfo(outfile).Length == 0)
            {
                IsErrors = true;
                ErrorException(encodertext.ToString());
            }

            encodertext.Length = 0;
        }
示例#7
0
        private void demux_mkv(Demuxer.DemuxerMode dmode)
        {
            //список файлов
            string outfile = "", 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;

            if (dmode == Demuxer.DemuxerMode.ExtractAudio)
            {
                //определяем аудио потоки
                AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];
                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

                busyfile = Path.GetFileName(outstream.audiopath);

                outfile = outstream.audiopath;
                info.Arguments = "tracks " + flist + instream.mi_order + ":" + "\"" + outfile + "\" --output-charset UTF-8";

                SetLog("Demuxing audio stream to: " + outstream.audiopath);
                SetLog(instream.codecshort + " " + instream.bitrate + "kbps " + instream.channels + "ch " + instream.bits + "bit " + instream.samplerate + "khz" +
                    Environment.NewLine);
            }
            else if (dmode == Demuxer.DemuxerMode.ExtractVideo)
            {
                step++;

                if (m.outvideofile == null)
                    m.outvideofile = Settings.TempPath + "\\" + m.key + "." + Format.GetValidRAWVideoEXT(m);

                //подхватываем готовый файл
                if (File.Exists(m.outvideofile))
                {
                    SetLog(Languages.Translate("Using already created file") + ": " + m.outvideofile + Environment.NewLine);
                    return;
                }

                busyfile = Path.GetFileName(m.outvideofile);

                outfile = m.outvideofile;
                info.Arguments = "tracks " + flist + m.invideostream_mi_order + ":" + "\"" + outfile + "\" --output-charset UTF-8";

                SetLog("Demuxing video stream to: " + m.outvideofile);
                SetLog(m.inresw + "x" + m.inresh + " " + m.invcodecshort + " " + m.invbitrate + "kbps " + m.inframerate + "fps" +
                    Environment.NewLine);
            }

            if (Settings.ArgumentsToLog)
            {
                SetLog("mkvextract.exe: " + info.Arguments + Environment.NewLine);
            }

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

            int outframes = m.outframes;
            m.outframes = m.inframes;
            SetMaximum(m.outframes);

            //Извлекаем
            Do_MKVToolnix_Cycle(info);

            m.outframes = outframes;
            SetMaximum(m.outframes);

            if (IsAborted || IsErrors) return;

            //проверка на удачное завершение
            if (!File.Exists(outfile) || new FileInfo(outfile).Length == 0)
            {
                IsErrors = true;
                ErrorException(encodertext.ToString());
            }

            encodertext.Length = 0;
        }
示例#8
0
        private void demux_ffmpeg(Demuxer.DemuxerMode dmode)
        {
            //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\\ffmpeg\\ffmpeg.exe";
            info.WorkingDirectory = Path.GetDirectoryName(info.FileName);
            info.UseShellExecute = false;
            info.RedirectStandardOutput = false;
            info.RedirectStandardError = true;
            info.StandardErrorEncoding = Encoding.UTF8;
            info.CreateNoWindow = true;

            string format = "";
            string outfile = "";

            if (dmode == Demuxer.DemuxerMode.ExtractAudio)
            {
                //определяем аудио потоки
                AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];
                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

                busyfile = Path.GetFileName(outstream.audiopath);

                outfile = outstream.audiopath;

                string forceformat = "";
                string outext = Path.GetExtension(outfile);
                if (outext == ".lpcm" || instream.codec == "LPCM")
                    forceformat = " -f s16be";

                info.Arguments = "-i \"" + m.infilepath + "\" -map 0." + instream.ff_order + " -sn -vn -acodec copy" + forceformat + " \"" + outfile + "\"";

                SetLog("Demuxing audio stream to: " + outstream.audiopath);
                SetLog(instream.codecshort + " " + instream.bitrate + "kbps " + instream.channels + "ch " + instream.bits + "bit " + instream.samplerate + "khz" +
                    Environment.NewLine);
            }
            else if (dmode == Demuxer.DemuxerMode.ExtractVideo)
            {
                step++;

                if (m.outvideofile == null)
                    m.outvideofile = Settings.TempPath + "\\" + m.key + "." + Format.GetValidRAWVideoEXT(m);

                //подхватываем готовый файл
                if (File.Exists(m.outvideofile))
                {
                    SetLog(Languages.Translate("Using already created file") + ": " + m.outvideofile + Environment.NewLine);
                    return;
                }

                busyfile = Path.GetFileName(m.outvideofile);

                SetLog("Demuxing video stream to: " + m.outvideofile);
                SetLog(m.inresw + "x" + m.inresh + " " + m.invcodecshort + " " + m.invbitrate + "kbps " + m.inframerate + "fps" +
                    Environment.NewLine);

                string outext = Path.GetExtension(m.outvideofile).ToLower();
                if (outext == ".264" || outext == ".h264")
                    format = " -f h264";

                //if (outext == ".m2v")
                //    format = " -f vob";

                outfile = m.outvideofile;
                info.Arguments = "-i \"" + m.infilepath + "\" -map 0:v:0 -sn -an -vcodec copy" + format + " \"" + outfile + "\" -hide_banner -nostdin";
            }

            if (Settings.ArgumentsToLog)
            {
                SetLog("ffmpeg.exe: " + info.Arguments + Environment.NewLine);
            }

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

            int outframes = m.outframes;
            string outfps = m.outframerate;
            m.outframerate = m.inframerate;
            m.outframes = m.inframes;
            SetMaximum(m.outframes);

            //Демуксим
            Do_FFmpeg_Cycle(info);

            m.outframerate = outfps;
            m.outframes = outframes;
            SetMaximum(m.outframes);

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

            if (IsAborted || IsErrors) return;

            //проверка на удачное завершение
            if (!File.Exists(outfile) || new FileInfo(outfile).Length == 0)
            {
                IsErrors = true;
                ErrorException(encodertext.ToString());
            }

            encodertext.Length = 0;
        }
示例#9
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();
        }
示例#10
0
        private void button_ok_Click(object sender, RoutedEventArgs e)
        {
            if (m.inaudiostreams.Count > 0)
            {
                //определяем аудио потоки
                AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];

                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);
                    }
                }

                if ((m.volume != "Disabled" && Settings.AutoVolumeMode != Settings.AutoVolumeModes.Disabled) &&
                    !instream.gaindetected)
                {
                    AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                    if (outstream.codec != "Copy")
                        AnalyseVolume();
                }
            }

            if (mode == AudioOptionsModes.AllOptions)
            {
                m = AviSynthScripting.CreateAutoAviSynthScript(m);
                if (p.m.script != m.script)
                    Refresh();
            }

            Close();
        }
示例#11
0
        private void menu_demux_video_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (m == null) return;
            if (!m.isvideo)
            {
                Message mess = new Message(this);
                mess.ShowMessage(Languages.Translate("File doesn`t have video streams!"), Languages.Translate("Error"));
            }
            else
            {
                string ext = Format.GetValidRAWVideoEXT(m);

                System.Windows.Forms.SaveFileDialog o = new System.Windows.Forms.SaveFileDialog();
                o.Filter = ext.ToUpper() + " " + Languages.Translate("Video").ToLower() + Languages.Translate("files") + "|*." + ext;
                o.Title = Languages.Translate("Select output file") + ":";
                o.FileName = Path.GetFileNameWithoutExtension(m.infilepath) + "." + ext;

                if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (o.FileName == m.infilepath)
                    {
                        ErrorException(Languages.Translate("Select another name for output file!"));
                        return;
                    }
                    Demuxer dem = new Demuxer(m, Demuxer.DemuxerMode.ExtractVideo, o.FileName);
                    if (dem.IsErrors)
                    {
                        new Message(this).ShowMessage(dem.error_message, Languages.Translate("Error"), Message.MessageStyle.Ok);
                    }
                }
            }
        }
示例#12
0
        private void menu_demux_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (m == null) return;
            if (m.inaudiostreams.Count == 0)
            {
                Message mess = new Message(this);
                mess.ShowMessage(Languages.Translate("File doesn`t have audio streams!"), Languages.Translate("Error"));
            }
            else
            {
                AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];
                System.Windows.Forms.SaveFileDialog o = new System.Windows.Forms.SaveFileDialog();
                o.Filter = instream.codecshort + " " + Languages.Translate("files") + "|*." + instream.codecshort.ToLower();
                o.Title = Languages.Translate("Select output file") + ":";
                o.FileName = Path.GetFileNameWithoutExtension(m.infilepath) + Format.GetValidRAWAudioEXT(instream.codecshort);

                if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (o.FileName == m.infilepath)
                    {
                        ErrorException(Languages.Translate("Select another name for output file!"));
                        return;
                    }
                    Demuxer dem = new Demuxer(m, Demuxer.DemuxerMode.ExtractAudio, o.FileName);
                    if (dem.IsErrors)
                    {
                        new Message(this).ShowMessage(dem.error_message, Languages.Translate("Error"), Message.MessageStyle.Ok);
                    }
                }
            }
        }
示例#13
0
        private void action_save_wav()
        {
            System.Windows.Forms.SaveFileDialog o = new System.Windows.Forms.SaveFileDialog();
            o.Filter = Languages.Translate("Windows PCM (*.wav)") + "|*.wav";
            o.Title = Languages.Translate("Select output file") + ":";
            o.FileName = Path.GetFileNameWithoutExtension(m.infilepath) + ".wav";

            if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (o.FileName == m.infilepath)
                {
                    ErrorException(Languages.Translate("Select another name for output file!"));
                    return;
                }
                Demuxer dem = new Demuxer(m, Demuxer.DemuxerMode.DecodeToWAV, o.FileName);
                if (dem.IsErrors)
                {
                    new Message(this).ShowMessage(dem.error_message, Languages.Translate("Error"), Message.MessageStyle.Ok);
                }
            }
        }
示例#14
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);
            }
        }
示例#15
0
        private void button_analysevolume_Click(object sender, RoutedEventArgs e)
        {
            //определяем аудио потоки
            AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];

            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);
                    return;
                }

                //обновляем скрипт
                m = AviSynthScripting.CreateAutoAviSynthScript(m);
            }

            AnalyseVolume();
            SetInfo();
        }
示例#16
0
        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();
        }
示例#17
0
        private void action_encode(Massive mass)
        {
            //закрываем все дочерние окна
            CloseChildWindows();

            if (mass.inaudiostreams.Count > 0 && mass.outaudiostreams.Count > 0)
            {
                //определяем аудио потоки
                AudioStream instream = (AudioStream)mass.inaudiostreams[mass.inaudiostream];
                AudioStream outstream = (AudioStream)mass.outaudiostreams[mass.outaudiostream];

                if (instream.audiopath != null && !File.Exists(instream.audiopath))
                {
                    if (!Format.IsDirectRemuxingPossible(mass) && outstream.codec == "Copy" ||
                        Format.IsDirectRemuxingPossible(mass) && outstream.codec != "Copy")
                    {
                        Demuxer dem = new Demuxer(mass, Demuxer.DemuxerMode.ExtractAudio, instream.audiopath);
                        if (dem.m != null) mass = dem.m.Clone();

                        //обновляем скрипт
                        mass = AviSynthScripting.CreateAutoAviSynthScript(mass);

                        UpdateTaskMassive(mass);
                    }
                }

                //определяем громкоcть (перед кодированием)
                if (Settings.Volume != "Disabled" && Settings.AutoVolumeMode == Settings.AutoVolumeModes.OnExport &&
                    outstream.codec != "Copy" && outstream.codec != "Disabled")
                {
                    if (!instream.gaindetected)
                    {
                        mass.volume = Settings.Volume;
                        Normalize norm = new Normalize(mass);
                        if (norm.m != null) mass = norm.m.Clone();
                    }

                    mass = AviSynthScripting.SetGain(mass);
                    UpdateTaskMassive(mass);
                }

                //Временный WAV-файл для 2pass AAC
                if (outstream.codec == "AAC" && mass.aac_options.encodingmode == Settings.AudioEncodingModes.TwoPass)
                {
                    if ((instream.audiofiles == null || instream.audiofiles.Length < 2) && File.Exists(instream.audiopath) && Path.GetExtension(instream.audiopath).ToLower() == ".wav" &&
                        !mass.trim_is_on && !m.testscript && instream.bits == outstream.bits && instream.channels == outstream.channels && instream.delay == outstream.delay &&
                        instream.gain == outstream.gain && instream.samplerate == outstream.samplerate && mass.script == AviSynthScripting.CreateAutoAviSynthScript(mass).script)
                    {
                        outstream.nerotemp = instream.audiopath;
                    }
                    else
                    {
                        outstream.nerotemp = Settings.TempPath + "\\" + mass.key + "_nerotemp.wav";
                        Demuxer dem = new Demuxer(mass, Demuxer.DemuxerMode.NeroTempWAV, outstream.nerotemp);
                        if (dem.IsErrors)
                        {
                            ErrorException(dem.error_message);
                            UpdateTaskStatus(mass.key, TaskStatus.Errors);
                            return;
                        }
                        deletefiles.Add(outstream.nerotemp);
                    }
                }
            }

            try
            {
                //запускаем кодер
                Encoder enc = new Encoder(mass, this);
            }
            catch (Exception ex)
            {
                ErrorException("RunEncoder: " + ex.Message, ex.StackTrace);
            }
        }
示例#18
0
        private void button_play_Click(object sender, RoutedEventArgs e)
        {
            if (m.inaudiostreams.Count > 0 && m.outaudiostreams.Count > 0)
            {
                //определяем аудио потоки
                AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];
                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];

                if (textbox_apath.Text != instream.audiopath)
                {
                    if (textbox_apath.Text == "")
                    {
                        instream.audiopath = null;
                        instream.audiofiles = null;
                    }
                    else
                    {
                        instream.audiopath = textbox_apath.Text;
                        instream.audiofiles = new string[] { instream.audiopath };
                    }
                }

               /* if (m.vdecoder == AviSynthScripting.Decoders.FFmpegSource)
                {
                    ////Получаем информацию через AviSynth и кешируем аудио для FFmpegSource
                    //Caching cach = new Caching(m);
                    //m = cach.m.Clone();

                    string script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.FastPreview);
                    AviSynthScripting.WriteScriptToFile(script, "tracker");
                    PlayInWPFPlayer(Settings.TempPath + "\\tracker.avs");
                }
                else   */
                {
                    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);
                            return;
                        }
                    }

                    string script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.FastPreview);
                    AviSynthScripting.WriteScriptToFile(script, "tracker");
                    if (instream.audiopath == null || File.Exists(instream.audiopath))
                    {
                        try
                        {
                            Process.Start(Calculate.StartupPath + "\\WPF_VideoPlayer.exe", Settings.TempPath + "\\tracker.avs");
                        }
                        catch (Exception ex)
                        {
                            ErrorException(ex.Message, ex.StackTrace);
                        }
                    }
                }
            }
        }
示例#19
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();
        }