Esempio n. 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);
                        }
                    }
                }
            }
        }
Esempio n. 2
0
        private void combo_framerateconvertor_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if ((combo_framerateconvertor.IsDropDownOpen || combo_framerateconvertor.IsSelectionBoxHighlighted) && combo_framerateconvertor.SelectedItem != null)
            {
                Settings.FramerateModifer = m.frameratemodifer = (AviSynthScripting.FramerateModifers)((ComboBoxItem)combo_framerateconvertor.SelectedItem).Content;

                m.sampleratemodifer = Settings.SamplerateModifer;
                m = AviSynthScripting.CreateAutoAviSynthScript(m);

                //механизм обхода ошибок SSRC
                if (m.sampleratemodifer == AviSynthScripting.SamplerateModifers.SSRC &&
                    m.inaudiostreams.Count > 0 && m.outaudiostreams.Count > 0)
                {
                    AudioStream instream  = (AudioStream)m.inaudiostreams[m.inaudiostream];
                    AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                    if (instream.samplerate != outstream.samplerate && outstream.samplerate != null &&
                        Calculate.CheckScriptErrors(m) == "SSRC: could not resample between the two samplerates.")
                    {
                        m.sampleratemodifer = AviSynthScripting.SamplerateModifers.ResampleAudio;
                        m = AviSynthScripting.CreateAutoAviSynthScript(m);
                    }
                }

                //обновляем конечное колличество фреймов, с учётом режима деинтерелейса
                m             = Calculate.UpdateOutFrames(m);
                m.outfilesize = Calculate.GetEncodingSize(m);

                p.m = m.Clone();
                p.Refresh(m.script);
                this.Focus();
            }
        }
Esempio n. 3
0
 private void Refresh()
 {
     if (oldm != null)
     {
         m   = AviSynthScripting.CreateAutoAviSynthScript(m);
         p.m = m.Clone();
         p.Refresh(m.script);
         this.Focus();
     }
 }
Esempio n. 4
0
        private void Refresh()
        {
            m   = AviSynthScripting.CreateAutoAviSynthScript(m);
            p.m = m.Clone();
            p.Refresh(m.script);
            this.Focus();

            CalculateMod();
            FillManualBox();
        }
Esempio n. 5
0
 private void button_refresh_Click(object sender, System.Windows.RoutedEventArgs e)
 {
     if (m != null)
     {
         m   = AviSynthScripting.CreateAutoAviSynthScript(m);
         p.m = m.Clone();
         p.Refresh(m.script);
         this.Focus();
     }
 }
Esempio n. 6
0
        private void Refresh()
        {
            if (m != null)
            {
                CheckFramerateModifierIsApplied();

                m   = AviSynthScripting.CreateAutoAviSynthScript(m);
                p.m = m.Clone();
                p.Refresh(m.script);
                this.Focus();
            }
        }
Esempio n. 7
0
        private void combo_framerate_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if ((combo_framerate.IsDropDownOpen || combo_framerate.IsSelectionBoxHighlighted || combo_framerate.IsEditable) && combo_framerate.SelectedItem != null)
            {
                if (combo_framerate.SelectedItem.ToString().Length == 0)
                {
                    //Включаем редактирование
                    combo_framerate.IsEditable = true;
                    combo_framerate.ToolTip    = Languages.Translate("Enter - apply, Esc - cancel.");
                    combo_framerate.ApplyTemplate();
                    return;
                }
                else
                {
                    m.outframerate = Calculate.GetSplittedString(combo_framerate.SelectedItem.ToString(), 0);

                    m.sampleratemodifer = Settings.SamplerateModifer;
                    m = AviSynthScripting.CreateAutoAviSynthScript(m);

                    //механизм обхода ошибок SSRC
                    if (m.sampleratemodifer == AviSynthScripting.SamplerateModifers.SSRC &&
                        m.inaudiostreams.Count > 0 && m.outaudiostreams.Count > 0)
                    {
                        AudioStream instream  = (AudioStream)m.inaudiostreams[m.inaudiostream];
                        AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                        if (instream.samplerate != outstream.samplerate && outstream.samplerate != null &&
                            Calculate.CheckScriptErrors(m) == "SSRC: could not resample between the two samplerates.")
                        {
                            m.sampleratemodifer = AviSynthScripting.SamplerateModifers.ResampleAudio;
                            m = AviSynthScripting.CreateAutoAviSynthScript(m);
                        }
                    }

                    //обновляем конечное колличество фреймов, с учётом режима деинтерелейса
                    m             = Calculate.UpdateOutFrames(m);
                    m.outfilesize = Calculate.GetEncodingSize(m);

                    CheckFramerateModifierIsApplied();

                    p.m = m.Clone();
                    p.Refresh(m.script);
                    this.Focus();
                }

                if (combo_framerate.IsEditable)
                {
                    //Выключаем редактирование
                    combo_framerate.IsEditable = false;
                    combo_framerate.ToolTip    = null;
                }
            }
        }
Esempio n. 8
0
        private void button_ok_Click(object sender, RoutedEventArgs e)
        {
            if (m != null)
            {
                //Новый скрипт
                m = AviSynthScripting.CreateAutoAviSynthScript(m);

                //Проверяем, изменился ли скрипт
                NeedUpdate = (old_raw_script != m.script);
            }

            Close();
        }
Esempio n. 9
0
        private void Refresh()
        {
            m   = AviSynthScripting.CreateAutoAviSynthScript(m);
            p.m = m.Clone();
            p.Refresh(m.script);

            if (m.outaudiostreams.Count > 0)
            {
                AudioStream outstream = (AudioStream)m.outaudiostreams[m.outaudiostream];
                if (p.combo_aencoding.SelectedItem.ToString() != outstream.encoding)
                {
                    p.combo_aencoding.SelectedItem = outstream.encoding;
                }
            }
        }
Esempio n. 10
0
 private void button_ok_Click(object sender, System.Windows.RoutedEventArgs e)
 {
     if (m != null && (
             p.m.inaspect != m.inaspect ||
             p.m.outaspect != m.outaspect ||
             p.m.outresw != m.outresw ||
             p.m.outresh != m.outresh ||
             p.m.cropl != m.cropl ||
             p.m.cropr != m.cropr ||
             p.m.cropb != m.cropb ||
             p.m.cropt != m.cropt ||
             p.m.blackw != m.blackw ||
             p.m.blackh != m.blackh ||
             p.m.aspectfix != m.aspectfix))
     {
         m = AviSynthScripting.CreateAutoAviSynthScript(m);
     }
     Close();
 }
Esempio n. 11
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();
        }
Esempio n. 12
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();
        }
Esempio n. 13
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);
            }
        }
Esempio n. 14
0
        private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                //забиваем необходимые параметры
                MediaInfoWrapper media = new MediaInfoWrapper();
                media.Open(m.infilepath);
                m.invcodec      = media.VCodecString;
                m.invcodecshort = media.VCodecShort;
                //Добавляем инфу, по которой потом можно будет определить, применять ли ForceFilm
                m.inframerate = media.FrameRate;
                bool pulldown = media.ScanOrder.Contains("Pulldown");
                media.Close();

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

                //проверка на невалидную индексацию
                if (!NV && m.invcodecshort != "MPEG2" && m.invcodecshort != "MPEG1")
                {
                    //Выходим отсюда, декодер будет выбран позже
                    m.indexfile = null;
                    m.vdecoder  = 0;
                    return;
                }

                //получаем индекс файл
                m.indexfile = Calculate.GetBestIndexFile(m.infilepath, NV);

                //определяем видео декодер
                if (NV)
                {
                    m.vdecoder     = AviSynthScripting.Decoders.DGSource;
                    m.dgdecnv_path = Calculate.StartupPath + "\\apps\\DGDecNV\\";
                }
                else
                {
                    m.vdecoder = AviSynthScripting.Decoders.MPEG2Source;
                }

                if (File.Exists(m.indexfile) && !worker.CancellationPending)
                {
                    //Определяем, использовался ли Force Film (#1)
                    //Для DGSource ForceFilm задается через скрипт, а не через правку индекс-файла,
                    //его в любой момент можно вкл\выкл, поэтому тут нужно определиться, использовать ли ForceFilm.
                    if (m.vdecoder == AviSynthScripting.Decoders.DGSource)
                    {
                        if (Indexing_DGIndexNV.CheckIndexAndForceFilm(m.indexfile, m.inframerate))
                        {
                            m.IsForcedFilm = true;
                            m.interlace    = SourceType.UNKNOWN;
                        }
                    }

                    //проверяем папки
                    script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.Info);
                    reader = new AviSynthReader();
                    reader.ParseScript(script);
                    m.induration = TimeSpan.FromSeconds((double)reader.FrameCount / reader.Framerate);

                    //Определяем, использовался ли Force Film (#2)
                    //Для MPEG2Source ForceFilm задается через правку индекс-файла,
                    //поэтому изменив его однажды (при индексации) ForceFilm всегда будет вкл.
                    if (m.vdecoder == AviSynthScripting.Decoders.MPEG2Source)
                    {
                        if ((pulldown && m.inframerate == "23.976" || m.inframerate == "29.970") && Math.Abs(reader.Framerate - 23.976) < 0.001)
                        {
                            m.IsForcedFilm = true;
                            m.interlace    = SourceType.UNKNOWN;
                        }
                    }

                    //Закрываем ридер
                    CloseReader(true);

                    //проверка на устаревшую индекс папку
                    string ifopath = Calculate.GetIFO(m.infilepath);
                    if (File.Exists(ifopath) && !worker.CancellationPending)
                    {
                        VStripWrapper vs = new VStripWrapper();
                        vs.Open(ifopath);
                        TimeSpan duration = vs.Duration();
                        vs.Close();

                        //папка устарела (если разница между продолжительностью в скрипте и в IFO больше 10-ти секунд)
                        if (Math.Abs(m.induration.Duration().TotalSeconds - duration.TotalSeconds) > 10)
                        {
                            //Будем папку удалять..
                            throw new Exception("MPEG2Source");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (worker != null && !worker.CancellationPending && m != null && num_closes == 0)
                {
                    //Ошибка
                    ex.HelpLink = script;
                    e.Result    = ex;
                }
            }
            finally
            {
                CloseReader(true);
            }
        }
Esempio n. 15
0
        private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                //Готовим скрипт
                script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.Autocrop);
                script = AviSynthScripting.TuneAutoCropScript(script, frame);

                //Открываем скрипт
                reader = new AviSynthReader();
                reader.ParseScript(script);

                int width  = m.inresw;
                int height = m.inresh;
                int frames = reader.FrameCount;

                ArrayList ll = new ArrayList();
                ArrayList tt = new ArrayList();
                ArrayList rr = new ArrayList();
                ArrayList bb = new ArrayList();

                //Проигрываем все кадры и считываем значения кропа
                for (int i = 0; i < frames && !worker.CancellationPending; i++)
                {
                    reader.ReadFrameDummy(i);
                    worker.ReportProgress(((i + 1) * 100) / frames);

                    //Фильтрация возможных(?) недопустимых значений
                    ll.Add(Math.Min(Math.Max(reader.GetVarInteger("crop_left", 0), 0), width));
                    tt.Add(Math.Min(Math.Max(reader.GetVarInteger("crop_top", 0), 0), height));
                    rr.Add(Math.Min(Math.Max(reader.GetVarInteger("crop_right", 0), 0), width));
                    bb.Add(Math.Min(Math.Max(reader.GetVarInteger("crop_bottom", 0), 0), height));
                }

                //Анализ полученного
                if (!worker.CancellationPending)
                {
                    if (ll.Count > 0)
                    {
                        bool new_mode = Settings.AutocropMostCommon;

                        //Ищем наиболее часто встречающиеся значения ("усредняем") или берём минимальные значения
                        m.cropl = m.cropl_copy = (ll.Count > 4 && new_mode) ? FindMostCommon(ll) : FindMinimum(ll);  //Слева
                        m.cropt = m.cropt_copy = (tt.Count > 4 && new_mode) ? FindMostCommon(tt) : FindMinimum(tt);  //Сверху
                        m.cropr = m.cropr_copy = (rr.Count > 4 && new_mode) ? FindMostCommon(rr) : FindMinimum(rr);  //Справа
                        m.cropb = m.cropb_copy = (bb.Count > 4 && new_mode) ? FindMostCommon(bb) : FindMinimum(bb);  //Снизу
                    }
                    else
                    {
                        m.cropl = m.cropl_copy = 0;  //Слева
                        m.cropt = m.cropt_copy = 0;  //Сверху
                        m.cropr = m.cropr_copy = 0;  //Справа
                        m.cropb = m.cropb_copy = 0;  //Снизу
                    }
                }
            }
            catch (Exception ex)
            {
                if (worker != null && !worker.CancellationPending && m != null && num_closes == 0)
                {
                    //Ошибка
                    ex.HelpLink = script;
                    e.Result    = ex;
                }
            }
            finally
            {
                CloseReader(true);
            }
        }
Esempio n. 16
0
        public MT_Settings(Massive mass, System.Windows.Window owner)
        {
            this.InitializeComponent();
            this.Owner = owner;

            if (mass != null)
            {
                m = mass.Clone();

                //Скрипт для определения изменений
                m = AviSynthScripting.CreateAutoAviSynthScript(m);
                old_raw_script = m.script;
            }

            //переводим
            MT.Header = Title = Languages.Translate("MT settings");
            label_memorymax.Content      = Languages.Translate("Value for SetMemoryMax") + ":";
            label_mtmode_before.Content  = Languages.Translate("Start SetMTMode with") + ":";
            label_mtmode_after.Content   = Languages.Translate("End SetMTMode with") + ":";
            label_mtmode_threads.Content = Languages.Translate("Threads number") + ":";
            label_mt_internal.Content    = Languages.Translate("MT internal handling") + ":";
            button_ok.Content            = Languages.Translate("OK");

            if (SysInfo.AVSIsMT)
            {
                string info = Languages.Translate("Please refer to MUXER documentation for more info").Replace("MUXER", "AviSynth") + ".\r\n\r\n";
                num_memorymax.ToolTip     = Languages.Translate("Sets the size of the frame buffer cache, in Mb (0 - Auto)") + ".\r\n" + info + _def + "0";
                num_mtmode_before.ToolTip = Languages.Translate("MT mode before video importing function (0 - don't add SetMTMode)") + ".\r\n" +
                                            Languages.Translate("Recommended value: 3, 5 or 6") + "\r\n\r\n" + info + _def + "0";
                num_mtmode_after.ToolTip = Languages.Translate("MT mode after video importing function (0 - don't add SetMTMode)") + ".\r\n" +
                                           Languages.Translate("Recommended value: 2") + "\r\n\r\n" + info + _def + "0";
                num_mtmode_threads.ToolTip = Languages.Translate("Sets the number of threads for MT (0 - Auto)") + ".\r\n" + info + _def + "0";

                if (Settings.MTSettings_Warning)
                {
                    Message mes = new Message(this);
                    mes.ShowMessage(Languages.Translate("This settings is for advanced users only.") + "\r\n" +
                                    Languages.Translate("Incorrect values may leads to hangs or crashes!") + "\r\n" +
                                    Languages.Translate("Use it at your own risk!"), Languages.Translate("Warning"), Message.MessageStyle.Ok);
                    Settings.MTSettings_Warning = false;
                }
            }
            else
            {
                grid_main.IsEnabled = false;
                grid_main.ToolTip   = Languages.Translate("You need a multithreaded (MT) version of AviSynth to use this settings") + ".\r\n" +
                                      Languages.Translate("Your current version is") + ": " + SysInfo.AVSVersionString;
            }

            combo_mt_internal.Items.Add(new ComboBoxItem()
            {
                Content = "Undefined", Tag = MTMode.Undefined, ToolTip = Languages.Translate("Don't care about multithreading")
            });
            combo_mt_internal.Items.Add(new ComboBoxItem()
            {
                Content = "Deactivate", Tag = MTMode.Disabled, ToolTip = Languages.Translate("Deactivate multithreading")
            });
            combo_mt_internal.Items.Add(new ComboBoxItem()
            {
                Content = "Distributor", Tag = MTMode.AddDistr, ToolTip = Languages.Translate("Add Distributor() at the end of the script")
            });

            num_memorymax.Value             = Settings.SetMemoryMax;
            num_mtmode_before.Value         = Settings.SetMTMode_1;
            num_mtmode_after.Value          = Settings.SetMTMode_2;
            num_mtmode_threads.Value        = Settings.SetMTMode_Threads;
            combo_mt_internal.SelectedValue = Settings.MTMode_Internal;

            ShowDialog();
        }
Esempio n. 17
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);
            }
        }
Esempio n. 18
0
        private void RunAnalyzer(Detecting detecting, int frameCount, string trimLine)
        {
            if (IsAborted || IsErrors)
            {
                return;
            }
            string script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.Interlace);

            int numFrames = 0;

            if (frameCount > 0)
            {
                numFrames = frameCount;
            }
            else
            {
                try
                {
                    reader = new AviSynthReader();
                    reader.ParseScript(script);
                    numFrames = reader.FrameCount;
                }
                catch (Exception ex)
                {
                    if (!IsAborted && num_closes == 0)
                    {
                        IsErrors   = true;
                        ErrorText  = "SourceDetector (RunAnalyzer): " + ex.Message;
                        StackTrace = ex.StackTrace;
                        Script     = script;
                    }
                }
                finally
                {
                    CloseReader(true);
                }
            }

            if (IsAborted || IsErrors)
            {
                return;
            }

            //Еще настройки
            int SelectLength       = 5;                        //Длина выборки (5 кадров)
            int MinAnalyseSections = Settings.SD_Min_Sections; //Мин. кол-во секций для анализа, 150

            if (detecting == Detecting.Fields)
            {
                //Тут в описании неточность, в оригинале выход скрипта имеет в два раза больше кадров из-за
                //loop(2), а не из-за SeparateFields. Вместо loop(2) лучше использовать один из уже готовых
                //клипов с удвоенным кол-вом кадров: atff или abff (без разницы) - декодеру не придется
                //дважды проходить по одному и тому-же месту (loop(2) - дошли до конца, идем в начало и
                //начинаем новый проход через весь клип). А если еще вместо DifferenceFromPrevious
                //использовать DifferenceToNext, то скорость вырастет еще больше!
                //SelectLength надо тоже установить равным 10-ти, иначе в одной выборке для FieldOrder
                //будут группы кадров (полей) из двух разных участков видео.
                //-----
                // Field order script. For this, we separatefields, so we have twice as many frames anyway
                // It saves time, and costs nothing to halve the minimum sections to analyse for this example
                //minAnalyseSections = minAnalyseSections / 2 + 1; // We add one to prevent getting 0;

                int NewLength = 10; //Длина выборки будет 10 кадров, а мин. кол-во секций пропорционально уменьшаем
                MinAnalyseSections = (int)Math.Max(MinAnalyseSections / (NewLength / (double)SelectLength), 1);
                SelectLength       = NewLength;
            }

            // Check if we need to modify the SelectRangeEvery parameters:
            int SelectEvery = (int)((100.0 * (double)SelectLength) / AnalysePercent);

            if (((double)SelectLength * (double)numFrames / (double)SelectEvery) < (int)MinAnalyseSections * SelectLength)
            {
                if (numFrames >= MinAnalyseSections * SelectLength) // If there are actually enough frames
                {
                    SelectEvery = (int)(((double)numFrames / ((double)MinAnalyseSections * (double)SelectLength)) * (double)SelectLength);
                }
                else
                {
                    // if there aren't enough frames, analyse everything -- that's got to be good enough
                    SelectEvery = SelectLength;
                }
            }

            //Имя лог-файла
            string logFileName = Settings.TempPath + "\\detecting_" + detecting.ToString().ToLower() + ".log";

            File.Delete(logFileName);

            //Прогон скрипта
            if (detecting == Detecting.Fields)
            {
                SetFieldPhase();
            }
            PlayScript(AviSynthScripting.GetSourceDetectionScript(detecting, script, trimLine, logFileName, SelectEvery, SelectLength));

            if (IsAborted || IsErrors)
            {
                return;
            }

            //Определение интерлейса\полей (чтение и анализ лог-файлов)
            if (detecting == Detecting.Interlace)
            {
                AnalyseInterlace(logFileName, SelectEvery, SelectLength, numFrames);
            }
            else if (detecting == Detecting.Fields)
            {
                AnalyseFields(logFileName, SelectLength);
            }
        }
Esempio n. 19
0
        public VisualCrop(Massive mass, Window owner)
        {
            m    = mass.Clone();
            oldm = mass.Clone();
            this.InitializeComponent();
            this.Owner = owner;

            //Создаем скрипт (т.к. текущий с кропом и ресайзом не годится)
            script = AviSynthScripting.GetInfoScript(m, AviSynthScripting.ScriptMode.VCrop);

            numl.Value = left = m.cropl;
            numr.Value = right = m.cropr;
            numt.Value = top = m.cropt;
            numb.Value = bottom = m.cropb;

            Color color = Settings.VCropBrush;

            slider_R.Value   = R = color.R;
            slider_G.Value   = G = color.G;
            slider_B.Value   = B = color.B;
            slider_A.Value   = A = color.A;
            FinalColor.Color = Color.FromArgb(255, R, G, B);

            numl.ToolTip                    = Languages.Translate("Left");
            numt.ToolTip                    = Languages.Translate("Top");
            numr.ToolTip                    = Languages.Translate("Right");
            numb.ToolTip                    = Languages.Translate("Bottom");
            button_autocrop.Content         = Languages.Translate("Analyse");
            button_autocrop.ToolTip         = Languages.Translate("Autocrop black borders");
            button_autocrop_current.ToolTip = Languages.Translate("Autocrop on current frame");
            button_uncrop.ToolTip           = Languages.Translate("Remove crop");
            button_settings.ToolTip         = Languages.Translate("Settings");
            slider_A.ToolTip                = Languages.Translate("Transparency of the mask");
            slider_R.ToolTip                = slider_G.ToolTip = slider_B.ToolTip = Languages.Translate("Brightness of the mask");

            button_fullscreen.ToolTip = Languages.Translate("Fullscreen mode");
            button_cancel.Content     = Languages.Translate("Cancel");
            frame_of  = Languages.Translate("Frame XX of YY").ToLower();
            cropped_s = Languages.Translate("cropped size");

            try
            {
                reader = new AviSynthReader(AviSynthColorspace.RGB24, AudioSampleType.Undefined);
                reader.ParseScript(script);

                if (reader.Clip.HasVideo && reader.FrameCount > 0)
                {
                    slider_pos.Maximum = reader.FrameCount;
                    slider_pos.Value   = (Settings.VCropFrame == "THM-frame") ? m.thmframe : 0;
                    numl.Maximum       = numr.Maximum = width = reader.Width;
                    numt.Maximum       = numb.Maximum = height = reader.Height;
                    fps = reader.Framerate;

                    stride   = width * bpp;
                    buffer   = Marshal.AllocHGlobal(stride * height);
                    HasVideo = true;

                    SetFrame((int)slider_pos.Value);
                    ShowCroppedFrame();
                }
                else
                {
                    PreviewError("NO VIDEO", Brushes.Gainsboro);
                }
            }
            catch (Exception ex)
            {
                SetPreviewError(ex);
            }

            if (IsError)
            {
                CloseReader();
                Close();
            }
            else
            {
                WindowLoaded = true;
                ShowDialog();
            }
        }