Пример #1
0
        private void action_encode(Massive mass)
        {
            //закрываем все дочерние окна
            CloseChildWindows();

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

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

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

                        UpdateTaskMassive(mass);
                    }
                }

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

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

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

            try
            {
                //запускаем кодер
                Encoder enc = new Encoder(mass, this);
            }
            catch (Exception ex)
            {
                ErrorException("RunEncoder: " + ex.Message, ex.StackTrace);
            }
        }
Пример #2
0
 private void AnalyseVolume()
 {
     if (combo_volume.SelectedItem != null)
     {
         AudioStream instream = (AudioStream)m.inaudiostreams[m.inaudiostream];
         if (combo_volume.SelectedItem.ToString() == "Disabled")
         {
             instream.gain = "0.0";
             instream.gaindetected = false;
         }
         else
         {
             Normalize norm = new Normalize(m);
             if (norm.m != null)
             {
                 m = norm.m.Clone();
                 instream.gaindetected = true;
             }
             else
             {
                 instream.gain = "0.0";
                 instream.gaindetected = false;
             }
         }
     }
 }
Пример #3
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);
            }
        }