Example #1
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();
        }
Example #2
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();
        }
Example #3
0
        //повторное открытие файла после смены декодера
        private void reopen_file(Massive old_m)
        {
            bool restore = false;

            //Переключились на MPEG2Source
            if (m.vdecoder == AviSynthScripting.Decoders.MPEG2Source && old_m.vdecoder != AviSynthScripting.Decoders.MPEG2Source)
            {
                //Если индекс-файла нет или он не тот, то надо индексировать (со всеми проверками - проще открыть файл заново)
                if (string.IsNullOrEmpty(m.indexfile) || !File.Exists(m.indexfile) || Path.GetExtension(m.indexfile).ToLower() != ".d2v")
                {
                    //Но проверить на МПЕГ можно и тут
                    if (m.invcodecshort == "MPEG1" || m.invcodecshort == "MPEG2")
                    {
                        Massive x = m.Clone();
                        x.inaudiostreams = new ArrayList();
                        x.outaudiostreams = new ArrayList();

                        CloseFile(false);
                        action_open(x);
                        return;
                    }
                    else
                    {
                        restore = true;
                        goto finish;
                    }
                }
            }

            //Переключились на DGSource
            if (m.vdecoder == AviSynthScripting.Decoders.DGSource && old_m.vdecoder != AviSynthScripting.Decoders.DGSource)
            {
                //Если индекс-файла нет или он не тот, то надо индексировать (со всеми проверками - проще открыть файл заново)
                if (string.IsNullOrEmpty(m.indexfile) || !File.Exists(m.indexfile) || Path.GetExtension(m.indexfile).ToLower() != ".dgi")
                {
                    Massive x = m.Clone();
                    x.inaudiostreams = new ArrayList();
                    x.outaudiostreams = new ArrayList();

                    CloseFile(false);
                    action_open(x);
                    return;
                }
            }

            //Переключились на FFmpegSource2
            if (m.vdecoder == AviSynthScripting.Decoders.FFmpegSource2 && old_m.vdecoder != AviSynthScripting.Decoders.FFmpegSource2)
            {
                //Индексация для FFmpegSource2
                Indexing_FFMS ffindex = new Indexing_FFMS(m);
                if (ffindex.m == null)
                {
                    restore = true;
                    goto finish;
                }
            }

            //Получаем информацию через AviSynth и ловим ошибки
            Caching cach = new Caching(m, false);
            if (cach.m == null)
            {
                restore = true;
                goto finish;
            }
            m = cach.m.Clone();
            old_m = null;

            //перезабиваем специфику формата
            if (m.format != Format.ExportFormats.Audio)
            {
                m = Format.GetOutInterlace(m);
                m = Format.GetValidResolution(m);
                m = Format.GetValidOutAspect(m);
                m = AspectResolution.FixAspectDifference(m);
                m = Format.GetValidFramerate(m);
                m = Calculate.UpdateOutFrames(m);
            }

            m = FillAudio(m);
            SetAudioPreset();

            //обнуляем громкость
            foreach (object s in m.inaudiostreams)
            {
                AudioStream stream = (AudioStream)s;
                stream.gain = "0.0";
                stream.gaindetected = false;
            }

            //обновляем скрипт с учётом полученных данных
            m = AviSynthScripting.CreateAutoAviSynthScript(m);

            //обновляем дочерние окна
            ReloadChildWindows();

            //загружаем видео в плеер
            LoadVideo(MediaLoad.update);
            UpdateTaskMassive(m);

            finish:
            if (restore)
            {
                //Восстанавливаем массив из сохраненного
                m = old_m.Clone();
                old_m = null;
            }
        }
Example #4
0
        private void action_add()
        {
            //запоминаем старое положени трекбара
            string[] oldfiles = m.infileslist;
            Massive x = m.Clone();

            try
            {
                FilesListWindow f = new FilesListWindow(x);
                if (f.m == null) return;
                x = f.m.Clone();

                //если что-то изменилось
                bool needupdate = false;
                if (oldfiles.Length != x.infileslist.Length)
                    needupdate = true;
                else
                {
                    for (int i = 0; i < x.infileslist.Length; i++)
                    {
                        //Файлы поменялись местами
                        if (oldfiles[i] != x.infileslist[i])
                        {
                            needupdate = true; break;
                        }
                    }
                }

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

                    //Для MPEG2Source и DGSource надо переиндексировать - проще закрыть и открыть файл(ы) заново
                    if (x.vdecoder == AviSynthScripting.Decoders.MPEG2Source && !string.IsNullOrEmpty(x.indexfile) && ext != ".d2v" ||
                        x.vdecoder == AviSynthScripting.Decoders.DGSource && !string.IsNullOrEmpty(x.indexfile) && ext != ".dgi")
                    {
                        //Тут должна удалиться индекс-папка
                        CloseFile(true);

                        x.inaudiostreams = new ArrayList();
                        x.outaudiostreams = new ArrayList();
                        action_open(x);
                        return;
                    }

                    //Обновляем возможные индекс-файлы от FFmpegSource2
                    if (!x.ffms_indexintemp)
                    {
                        foreach (string file in x.infileslist)
                        {
                            if (!ffcache.Contains(file + ".ffindex"))
                                ffcache.Add(file + ".ffindex");
                        }
                    }

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

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

                    if (x.inaudiostreams.Count > 0)
                    {
                        AudioStream s = (AudioStream)x.inaudiostreams[x.inaudiostream];
                        ArrayList afiles = new ArrayList();
                        if (ext == ".d2v" || ext == ".dga" || ext == ".dgi")
                        {
                            foreach (string file in x.infileslist)
                            {
                                ArrayList afileslist = Indexing.GetTracks(file);
                                if (afileslist.Count > 0)
                                    afiles.Add(afileslist[Math.Min(x.inaudiostream, afileslist.Count - 1)]);
                            }
                        }
                        else if (!x.isvideo) //Для аудио файлов
                        {
                            foreach (string file in x.infileslist)
                                afiles.Add(file);

                            x.inframes = 0;
                            x.induration = TimeSpan.Zero;
                        }
                        else
                            afiles.Add(s.audiopath);

                        s.audiofiles = Calculate.ConvertArrayListToStringArray(afiles);
                    }

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

                    //подсчитываем размер
                    long sizeb = 0;
                    foreach (string file in x.infileslist)
                    {
                        sizeb += new FileInfo(file).Length;
                    }
                    x.infilesize = Calculate.ConvertDoubleToPointString((double)sizeb / 1049511, 1) + " mb";
                    x.infilesizeint = (int)((double)sizeb / 1049511);

                    //получаем длительность и фреймы
                    Caching cach = new Caching(x, false);
                    if (cach.m == null) return;
                    x = cach.m.Clone();

                    //Нужно обновить кол-во кадров в BlankClip()
                    if (x.vdecoder == AviSynthScripting.Decoders.BlankClip)
                        x = AviSynthScripting.CreateAutoAviSynthScript(x);

                    x = Calculate.UpdateOutFrames(x);

                    //загружаем обновлённый скрипт
                    m = x.Clone();
                    LoadVideo(MediaLoad.load);
                    UpdateTaskMassive(m);
                }
            }
            catch (Exception ex)
            {
                ErrorException("AppendFile: " + ex.Message, ex.StackTrace);
            }
        }
Example #5
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);
            }
        }