Example #1
0
 public static AudioInfo GetStreamInfo(AudioInfo aStream)
 {
     MediaInfoContainer mi = new MediaInfoContainer();
     try
     {
         mi = Processing.GetMediaInfo(aStream.TempFile);
     }
     catch (TimeoutException ex)
     {
         Log.Error(ex);
         mi = new MediaInfoContainer();
     }
     finally
     {
         if (mi.Audio.Count > 0)
         {
             aStream.Bitrate = mi.Audio[0].BitRate;
             aStream.BitDepth = mi.Audio[0].BitDepth;
             aStream.ChannelCount = mi.Audio[0].Channels;
             aStream.SampleRate = mi.Audio[0].SamplingRate;
             aStream.Format = mi.Audio[0].Format;
             aStream.FormatProfile = mi.Audio[0].FormatProfile;
             aStream.StreamSize = Processing.GetFileSize(aStream.TempFile);
             if (aStream.Format == "PCM")
                 aStream.Length = GetRuntimePCM(aStream);
             else
                 aStream.Length = mi.Audio[0].Duration/1000d; // convert from ms to seconds
         }
     }
     return aStream;
 }
Example #2
0
        public static VideoInfo GetStreamInfo(MediaInfoContainer mi, VideoInfo vStream, bool bluRayTarget)
        {
            if (mi.Video.Count > 0)
            {
                Single.TryParse(mi.Video[0].DisplayAspectRatio, NumberStyles.Number, AppSettings.CInfo,
                                out vStream.AspectRatio);
                vStream.Bitrate = mi.Video[0].BitRate;
                vStream.Format = mi.Video[0].Format;
                vStream.FormatProfile = mi.Video[0].FormatProfile;
                if (mi.Video[0].FrameRateEnumerator < vStream.FrameRateEnumerator*2 || !bluRayTarget)
                {
                    vStream.FPS = mi.Video[0].FrameRate;
                    vStream.FrameCount = mi.Video[0].FrameCount;
                    vStream.FrameRateDenominator = mi.Video[0].FrameRateDenominator;
                    vStream.FrameRateEnumerator = mi.Video[0].FrameRateEnumerator;

                }
                vStream.Height = mi.Video[0].Height;
                vStream.Width = mi.Video[0].Width;
                vStream.Interlaced = mi.Video[0].ScanType != "Progressive";
                vStream.Length = mi.Video[0].DurationTime.TimeOfDay.TotalSeconds;
                vStream.PicSize = mi.Video[0].VideoSize;
                vStream.StreamSize = Processing.GetFileSize(vStream.TempFile);
            }
            return vStream;
        }
Example #3
0
 private static MediaInfoContainer DoWorkHandler(string fileName)
 {
     MediaInfoContainer mi = new MediaInfoContainer();
     mi.GetMediaInfo(fileName);
     return mi;
 }
Example #4
0
        private static InputType CheckFileType(string pathToFile)
        {
            MediaInfoContainer mi;
            try
            {
                mi = GetMediaInfo(pathToFile);
            }
            catch (TimeoutException ex)
            {
                Log.Error(ex);
                mi = new MediaInfoContainer();
            }

            string containerFormat = mi.General.Format;

            Log.InfoFormat(AppSettings.CInfo, "General.FileName:            {0:s}", mi.General.CompleteName);
            Log.InfoFormat(AppSettings.CInfo, "General.FileExtension:       {0:s}", mi.General.FileExtension);
            Log.InfoFormat(AppSettings.CInfo, "General.Format:              {0:s}", mi.General.Format);
            Log.InfoFormat(AppSettings.CInfo, "General.FormatExtensions:    {0:s}", mi.General.FormatExtensions);
            Log.InfoFormat(AppSettings.CInfo, "General.InternetMediaType:   {0:s}", mi.General.InternetMediaType);
            Log.InfoFormat(AppSettings.CInfo, "General.EncodedApplication:  {0:s}", mi.General.EncodedApplication);
            Log.InfoFormat(AppSettings.CInfo, "General.EncodedApplicationUrl:{0:s}", mi.General.EncodedApplicationUrl);
            Log.InfoFormat(AppSettings.CInfo, "General.EncodedLibrary:      {0:s}", mi.General.EncodedLibrary);
            Log.InfoFormat(AppSettings.CInfo, "General.EncodedLibraryDate:  {0:s}", mi.General.EncodedLibraryDate);
            Log.InfoFormat(AppSettings.CInfo, "General.EncodedLibraryName:  {0:s}", mi.General.EncodedLibraryName);
            Log.InfoFormat(AppSettings.CInfo, "General.EncodedLibrarySettings: {0:s}", mi.General.EncodedLibrarySettings);
            Log.InfoFormat(AppSettings.CInfo, "General.EncodedLibraryVersion: {0:s}", mi.General.EncodedLibraryVersion);
            Log.Info(String.Empty);

            foreach (MediaInfoContainer.VideoStreamInfo item in mi.Video)
            {
                Log.InfoFormat(AppSettings.CInfo, "Video.ID:                 {0:g}", item.ID);
                Log.InfoFormat(AppSettings.CInfo, "Video.StreamKindID:       {0:g}", item.StreamKindID);
                Log.InfoFormat(AppSettings.CInfo, "Video.StreamKindPos:      {0:g}", item.StreamKindPos);
                Log.InfoFormat(AppSettings.CInfo, "Video.CodecID:            {0:s}", item.CodecID);
                Log.InfoFormat(AppSettings.CInfo, "Video.CodecIDInfo:        {0:s}", item.CodecIDInfo);
                Log.InfoFormat(AppSettings.CInfo, "Video.CodecIDURL:         {0:s}", item.CodecIDUrl);
                Log.InfoFormat(AppSettings.CInfo, "Video.CodecIDDescription: {0:s}", item.CodecIDDescription);
                Log.InfoFormat(AppSettings.CInfo, "Video.InternetMediaType:  {0:s}", item.InternetMediaType);
                Log.InfoFormat(AppSettings.CInfo, "Video.Format:             {0:s}", item.Format);
                Log.InfoFormat(AppSettings.CInfo, "Video.FormatProfile:      {0:s}", item.FormatProfile);
                Log.InfoFormat(AppSettings.CInfo, "Video.FormatInfo:         {0:s}", item.FormatInfo);
                Log.InfoFormat(AppSettings.CInfo, "Video.FormatVersion:      {0:s}", item.FormatVersion);
                Log.InfoFormat(AppSettings.CInfo, "Video.MultiViewBaseProfile: {0:s}", item.MultiViewBaseProfile);
                Log.InfoFormat(AppSettings.CInfo, "Video.MultiViewCount:     {0:s}", item.MultiViewCount);
                Log.InfoFormat(AppSettings.CInfo, "Video.DisplayAspectRatio: {0:s}", item.DisplayAspectRatio);
                Log.InfoFormat(AppSettings.CInfo, "Video.PixelAspectRatio:   {0:g}", item.PixelAspectRatio);
                Log.InfoFormat(AppSettings.CInfo, "Video.BitrateMode:        {0:s}", item.BitRateMode);
                Log.InfoFormat(AppSettings.CInfo, "Video.Bitrate:            {0:g}", item.BitRate);
                Log.InfoFormat(AppSettings.CInfo, "Video.BitrateNom:         {0:g}", item.BitRateNom);
                Log.InfoFormat(AppSettings.CInfo, "Video.BitrateMin:         {0:g}", item.BitRateMin);
                Log.InfoFormat(AppSettings.CInfo, "Video.BitrateMax:         {0:g}", item.BitRateMax);
                Log.InfoFormat(AppSettings.CInfo, "Video.BitDepth:           {0:g}", item.BitDepth);
                Log.InfoFormat(AppSettings.CInfo, "Video.FrameRate:          {0:g}", item.FrameRate);
                Log.InfoFormat(AppSettings.CInfo, "Video.FrameRateMax:       {0:g}", item.FrameRateMax);
                Log.InfoFormat(AppSettings.CInfo, "Video.FrameRateMin:       {0:g}", item.FrameRateMin);
                Log.InfoFormat(AppSettings.CInfo, "Video.FrameRateNom:       {0:g}", item.FrameRateNom);
                Log.InfoFormat(AppSettings.CInfo, "Video.FrameRateMode:      {0:s}", item.FrameRateMode);
                Log.InfoFormat(AppSettings.CInfo, "Video.Height:             {0:g}", item.Height);
                Log.InfoFormat(AppSettings.CInfo, "Video.Width:              {0:g}", item.Width);
                Log.InfoFormat(AppSettings.CInfo, "Video.VideoSize:          {0:s}", item.VideoSize.ToString());
                Log.InfoFormat(AppSettings.CInfo, "Video.ScanType:           {0:s}", item.ScanType);
                Log.InfoFormat(AppSettings.CInfo, "Video.ScanOrder:          {0:g}", item.ScanOrder);
                Log.InfoFormat(AppSettings.CInfo, "Video.EncodedApplication: {0:s}", item.EncodedApplication);
                Log.InfoFormat(AppSettings.CInfo, "Video.EncodedApplicationUrl: {0:s}", item.EncodedApplicationUrl);
                Log.InfoFormat(AppSettings.CInfo, "Video.EncodedLibrary:     {0:s}", item.EncodedLibrary);
                Log.InfoFormat(AppSettings.CInfo, "Video.EncodedLibraryDate: {0:s}", item.EncodedLibraryDate);
                Log.InfoFormat(AppSettings.CInfo, "Video.EncodedLibraryName: {0:s}", item.EncodedLibraryName);
                Log.InfoFormat(AppSettings.CInfo, "Video.EncodedLibrarySettings: {0:s}", item.EncodedLibrarySettings);
                Log.InfoFormat(AppSettings.CInfo, "Video.EncodedLibraryVersion: {0:s}", item.EncodedLibraryVersion);
            }
            Log.Info(String.Empty);

            foreach (MediaInfoContainer.AudioStreamInfo item in mi.Audio)
            {
                Log.InfoFormat(AppSettings.CInfo, "Audio.ID:                 {0:g}", item.ID);
                Log.InfoFormat(AppSettings.CInfo, "Audio.StreamKindID:       {0:g}", item.StreamKindID);
                Log.InfoFormat(AppSettings.CInfo, "Audio.StreamKindPos:      {0:g}", item.StreamKindPos);
                Log.InfoFormat(AppSettings.CInfo, "Audio.CodecID:            {0:s}", item.CodecID);
                Log.InfoFormat(AppSettings.CInfo, "Audio.CodecIDInfo:        {0:s}", item.CodecIDInfo);
                Log.InfoFormat(AppSettings.CInfo, "Audio.CodecIDURL:         {0:s}", item.CodecIDUrl);
                Log.InfoFormat(AppSettings.CInfo, "Audio.CodecIDDescription: {0:s}", item.CodecIDDescription);
                Log.InfoFormat(AppSettings.CInfo, "Audio.Format:             {0:s}", item.Format);
                Log.InfoFormat(AppSettings.CInfo, "Audio.FormatProfile:      {0:s}", item.FormatProfile);
                Log.InfoFormat(AppSettings.CInfo, "Audio.FormatInfo:         {0:s}", item.FormatInfo);
                Log.InfoFormat(AppSettings.CInfo, "Audio.FormatVersion:      {0:s}", item.FormatVersion);
                Log.InfoFormat(AppSettings.CInfo, "Audio.Channels:           {0:g}", item.Channels);
                Log.InfoFormat(AppSettings.CInfo, "Audio.ChannelsString:     {0:s}", item.ChannelsString);
                Log.InfoFormat(AppSettings.CInfo, "Audio.BitrateMode:        {0:s}", item.BitRateMode);
                Log.InfoFormat(AppSettings.CInfo, "Audio.Bitrate:            {0:g}", item.BitRate);
                Log.InfoFormat(AppSettings.CInfo, "Audio.BitrateNom:         {0:g}", item.BitRateNom);
                Log.InfoFormat(AppSettings.CInfo, "Audio.BitrateMin:         {0:g}", item.BitRateMin);
                Log.InfoFormat(AppSettings.CInfo, "Audio.BitrateMax:         {0:g}", item.BitRateMax);
                Log.InfoFormat(AppSettings.CInfo, "Audio.BitDepth:           {0:g}", item.BitDepth);
                Log.InfoFormat(AppSettings.CInfo, "Audio.SamplingRate:       {0:g}", item.SamplingRate);
                Log.InfoFormat(AppSettings.CInfo, "Audio.EncodedLibrary:     {0:s}", item.EncodedLibrary);
                Log.InfoFormat(AppSettings.CInfo, "Audio.EncodedLibraryDate: {0:s}", item.EncodedLibraryDate);
                Log.InfoFormat(AppSettings.CInfo, "Audio.EncodedLibraryName: {0:s}", item.EncodedLibraryName);
                Log.InfoFormat(AppSettings.CInfo, "Audio.EncodedLibrarySettings: {0:s}", item.EncodedLibrarySettings);
                Log.InfoFormat(AppSettings.CInfo, "Audio.EncodedLibraryVersion: {0:s}", item.EncodedLibraryVersion);
            }
            Log.Info(String.Empty);

            switch (containerFormat)
            {
                case "Matroska":
                    return InputType.InputMatroska;
                case "AVI":
                    return InputType.InputAvi;
                case "MPEG-4":
                    return InputType.InputMp4;
                case "BDAV":
                case "MPEG-TS":
                    return InputType.InputTs;
                case "Windows Media":
                    return InputType.InputWm;
                case "Flash Video":
                    return InputType.InputFlash;
                case "MPEG-PS":
                    return InputType.InputMpegps;
                case "WebM":
                    return InputType.InputWebM;
                case "OGG":
                    return InputType.InputOgg;
            }

            return Path.GetExtension(pathToFile) == ".avs" ? InputType.InputAviSynth : InputType.InputUndefined;
        }
        /// <summary>
        /// Generates AviSynth script used for video encoding
        /// </summary>
        /// <param name="videoInfo">All video properties</param>
        /// <param name="changeFps">Defines whether framerate should be changed</param>
        /// <param name="targetFps">Sets target framerate</param>
        /// <param name="resizeTo">Sets target video resolution</param>
        /// <param name="stereoEncoding">Defines, which stereo encoding mode should be used</param>
        /// <param name="stereoVideoInfo">Sets all parameters for stereo encoding</param>
        /// <param name="isDvdResolution">Defines whether target resolution is used for DVD encoding</param>
        /// <param name="subtitleFile">Sets subtitle file for hardcoding into video</param>
        /// <param name="subtitleOnlyForced">Defines whether only forced captions should be hardcoded</param>
        /// <returns>Path to AviSynth script</returns>
        public static string Generate(VideoInfo videoInfo, bool changeFps, float targetFps, Size resizeTo,
                                      StereoEncoding stereoEncoding, StereoVideoInfo stereoVideoInfo, bool isDvdResolution, string subtitleFile, bool subtitleOnlyForced)
        {
            StringBuilder sb = new StringBuilder();

            bool mtUseful = (videoInfo.Interlaced && AppSettings.UseHQDeinterlace) || changeFps;

            bool useStereo = stereoEncoding != StereoEncoding.None && stereoVideoInfo.RightStreamId > -1;

            // support for multithreaded AviSynth
            if (AppSettings.UseAviSynthMT && mtUseful)
            {
                sb.AppendLine("SetMTMode(2,0)");
                sb.AppendLine("SetMemoryMax(512)");
            }

            //loading plugins
            sb.AppendLine(ImportFFMPEGSource());  // ffms2

            if (changeFps || (videoInfo.Interlaced && AppSettings.UseHQDeinterlace))
                sb.AppendLine(string.Format(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                            Path.Combine(AppSettings.AppPath, "AvsPlugins", "mvtools2.dll")));

            if (videoInfo.Interlaced && AppSettings.UseHQDeinterlace)
            {
                sb.AppendLine(AppSettings.LastAviSynthVer.StartsWith("2.5")
                                  ? string.Format(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                                  Path.Combine(AppSettings.AppPath, "AvsPlugins", "mt_masktools-25.dll"))
                                  : string.Format(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                                  Path.Combine(AppSettings.AppPath, "AvsPlugins", "mt_masktools-26.dll")));

                sb.AppendLine(string.Format(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                            Path.Combine(AppSettings.AppPath, "AvsPlugins", "nnedi3.dll")));
                sb.AppendLine(string.Format(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                            Path.Combine(AppSettings.AppPath, "AvsPlugins", "RemoveGrainSSE2.dll")));
                sb.AppendLine(string.Format(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                            Path.Combine(AppSettings.AppPath, "AvsPlugins", "RepairSSE2.dll")));
                sb.AppendLine(string.Format(AppSettings.CInfo, "Import(\"{0:s}\")",
                                            Path.Combine(AppSettings.AppPath, "AvsPlugins", "QTGMC-3.32.avsi")));
            }
            else if (videoInfo.Interlaced)
            {
                sb.AppendLine(string.Format(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                            Path.Combine(AppSettings.AppPath, "AvsPlugins", "Decomb.dll")));
            }

            if (useStereo)
                sb.AppendLine(string.Format(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                            Path.Combine(AppSettings.AppPath, "AvsPlugins", "H264StereoSource.dll")));

            if (!string.IsNullOrEmpty(subtitleFile) && File.Exists(subtitleFile))
            {
                switch (Path.GetExtension(subtitleFile))
                {
                    case "sup":
                        sb.AppendFormat(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                        Path.Combine(AppSettings.AppPath, "AvsPlugins", "SupTitle.dll"));
                        break;
                    case "ass":
                    case "ssa":
                    case "srt":
                        sb.AppendFormat(AppSettings.CInfo, "LoadPlugin(\"{0:s}\")",
                                        Path.Combine(AppSettings.AppPath, "AvsPlugins", "VSFilter.dll"));
                        break;
                }
                sb.AppendLine();
            }

            //generate rest of the script

            // calculate framerate numerator & denominator
            if (videoInfo.FPS <= 0)
            {
                MediaInfoContainer mi = new MediaInfoContainer();
                try
                {
                     mi = Processing.GetMediaInfo(videoInfo.TempFile);
                }
                catch (TimeoutException ex)
                {
                    Log.Error(ex);
                    mi = new MediaInfoContainer();
                }
                finally
                {
                    if (mi.Video.Count > 0)
                    {
                        videoInfo.FPS = mi.Video[0].FrameRate;
                        Processing.GetFPSNumDenom(videoInfo.FPS, out videoInfo.FrameRateEnumerator,
                                                  out videoInfo.FrameRateDenominator);

                        if (videoInfo.FrameRateEnumerator == 0)
                        {
                            videoInfo.FrameRateEnumerator = (int)Math.Round(videoInfo.FPS) * 1000;
                            videoInfo.FrameRateDenominator =
                                (int)(Math.Round(Math.Ceiling(videoInfo.FPS) - Math.Floor(videoInfo.FPS)) + 1000);
                        }
                    }
                }

            }

            if (videoInfo.FrameRateEnumerator > 0 && videoInfo.FrameRateDenominator > 0)
                sb.AppendLine(string.Format(AppSettings.CInfo,
                                            "FFVideoSource(\"{0:s}\",fpsnum={1:0},fpsden={2:0},threads=1)",
                                            videoInfo.TempFile, videoInfo.FrameRateEnumerator,
                                            videoInfo.FrameRateDenominator));
            else
                sb.AppendLine(string.Format(AppSettings.CInfo, "FFVideoSource(\"{0:s}\",threads=1)", videoInfo.TempFile));

            string stereoVar = string.Empty;

            if (useStereo)
            {
                string configFile = GenerateStereoSourceConfig(stereoVideoInfo);
                sb.AppendLine(string.Format(AppSettings.CInfo, "VideoRight = H264StereoSource(\"{0:s}\",{1:g})",
                                            configFile, videoInfo.FrameCount - 50));
                StereoConfigFile = configFile;
                stereoVar = "VideoRight";
            }

            // deinterlace video source
            if (videoInfo.Interlaced)
            {
                if (AppSettings.UseHQDeinterlace)
                    sb.AppendLine("QTGMC(Preset=\"Slower\")");
                else
                {
                    sb.AppendLine("ConvertToYUY2(interlaced=true)");
                    sb.AppendLine("Telecide(post=4)");
                    sb.AppendLine("Crop(4, 0, -4, 0)");
                    sb.AppendLine("AddBorders(4, 0, 4, 0)");
                    sb.AppendLine("ConvertToYV12()");
                }
            }

            // hardcode subtitles
            if (!string.IsNullOrEmpty(subtitleFile) && File.Exists(subtitleFile))
            {
                switch (Path.GetExtension(subtitleFile))
                {
                    case "sup":
                        sb.AppendFormat(AppSettings.CInfo, "SupTitle(\"{0}\", forcedOnly={1})", subtitleFile,
                                                        subtitleOnlyForced ? "true" : "false");
                        break;
                    case "ass":
                    case "ssa":
                    case "srt":
                        sb.AppendFormat(AppSettings.CInfo, "TextSub(\"{0}\")", subtitleFile);
                        break;
                }

                sb.AppendLine();
            }

            // video cropping
            if (!videoInfo.CropRect.IsEmpty)
            {
                int temp;

                Math.DivRem(videoInfo.CropRect.X, 2, out temp);
                videoInfo.CropRect.X += temp;
                Math.DivRem(videoInfo.CropRect.Y, 2, out temp);
                videoInfo.CropRect.Y += temp;
                Math.DivRem(videoInfo.CropRect.Width, 2, out temp);
                videoInfo.CropRect.Width += temp;
                Math.DivRem(videoInfo.CropRect.Height, 2, out temp);
                videoInfo.CropRect.Height += temp;

                videoInfo.Height = videoInfo.CropRect.Height;
                videoInfo.Width = videoInfo.CropRect.Width;

                if ((videoInfo.CropRect.X > 0) || (videoInfo.CropRect.Y > 0) || (videoInfo.CropRect.Width < videoInfo.Width) ||
                    (videoInfo.CropRect.Height < videoInfo.Height))
                {
                    sb.AppendLine(string.Format(AppSettings.CInfo, "Crop({0:g},{1:g},{2:g},{3:g})",
                                                videoInfo.CropRect.Left,
                                                videoInfo.CropRect.Top,
                                                videoInfo.CropRect.Width,
                                                videoInfo.CropRect.Height));
                    if (useStereo)
                    {
                        sb.AppendLine(string.Format(AppSettings.CInfo,
                                                    "CroppedVideoRight = Crop(VideoRight,{0:g},{1:g},{2:g},{3:g})",
                                                    videoInfo.CropRect.Left,
                                                    videoInfo.CropRect.Top,
                                                    videoInfo.CropRect.Width,
                                                    videoInfo.CropRect.Height));
                        stereoVar = "CroppedVideoRight";
                    }
                }
            }

            // Side-By-Side stereo encoding
            if (!string.IsNullOrEmpty(stereoVar))
            {
                switch(stereoEncoding)
                {
                    case StereoEncoding.FullSideBySideLeft:
                    case StereoEncoding.HalfSideBySideLeft:
                        sb.AppendLine(string.Format("StackHorizontal(last,{0})", stereoVar));
                        break;
                    case StereoEncoding.FullSideBySideRight:
                    case StereoEncoding.HalfSideBySideRight:
                        sb.AppendLine(string.Format("StackHorizontal({0},last)", stereoVar));
                        break;
                }
                sb.AppendLine("ConvertToYV12()");
            }

            int calculatedHeight = videoInfo.Height;
            int calculatedWidth = videoInfo.Width;
            int borderRight = 0;
            int borderLeft = 0;
            int borderBottom = 0;
            int borderTop = 0;
            bool addBorders = false;

            // video resizing
            if (!resizeTo.IsEmpty && (resizeTo.Height != videoInfo.Height || resizeTo.Width != videoInfo.Width))
            {
                // aspect ratios

                float toAr = (float) Math.Round(resizeTo.Width / (float)resizeTo.Height, 3);

                calculatedWidth = resizeTo.Width;

                float mod = 1f;

                if (videoInfo.AspectRatio > toAr) // source aspectratio higher than target aspectratio
                {
                    if (isDvdResolution)
                    {
                        calculatedHeight = (int)(calculatedWidth / videoInfo.AspectRatio);
                        if (calculatedHeight > resizeTo.Height)
                            calculatedHeight = resizeTo.Height;
                        calculatedWidth = 720;
                    }
                    else
                    {
                        calculatedWidth = resizeTo.Width;
                        calculatedHeight = (int)(calculatedWidth / videoInfo.AspectRatio);
                    }

                    int temp;

                    Math.DivRem(calculatedWidth, 2, out temp);
                    calculatedWidth += temp;
                    Math.DivRem(calculatedHeight, 2, out temp);
                    calculatedHeight += temp;

                    if (calculatedHeight != resizeTo.Height)
                    {
                        addBorders = true;
                        int borderHeight = resizeTo.Height - calculatedHeight;
                        borderTop = borderHeight/2;
                        Math.DivRem(borderTop, 2, out temp);
                        borderTop += temp;
                        borderBottom = borderHeight - borderTop;
                    }
                }
                else if (Math.Abs(videoInfo.AspectRatio - toAr) <= 0)  // source and target aspectratio equals
                {
                    if (isDvdResolution)
                    {
                        calculatedHeight = (int)(calculatedWidth / videoInfo.AspectRatio);
                        calculatedWidth = 720;
                        if (calculatedHeight > resizeTo.Height)
                            calculatedHeight = resizeTo.Height;
                    }
                    else
                    {
                        calculatedWidth = resizeTo.Width;
                        calculatedHeight = (int) (calculatedWidth/toAr);
                    }

                    int temp;

                    Math.DivRem(calculatedWidth, 2, out temp);
                    calculatedWidth += temp;
                    Math.DivRem(calculatedHeight, 2, out temp);
                    calculatedHeight += temp;

                    if (calculatedHeight != resizeTo.Height)
                    {
                        addBorders = true;
                        int borderHeight = resizeTo.Height - calculatedHeight;
                        borderTop = borderHeight/2;
                        Math.DivRem(borderTop, 2, out temp);
                        borderTop += temp;
                        borderBottom = borderHeight - borderTop;
                    }
                }
                else
                {
                    if (videoInfo.AspectRatio > 1.4f && isDvdResolution)  // source aspectratio not 4:3, encoding for dvd resolution
                    {
                        mod = 720f/resizeTo.Width;

                        calculatedHeight = (int)(calculatedWidth / videoInfo.AspectRatio);
                        if (calculatedHeight > resizeTo.Height)
                        {
                            calculatedHeight = resizeTo.Height;
                            calculatedWidth = (int)(calculatedHeight * videoInfo.AspectRatio * mod);
                        }
                        else
                            calculatedWidth = 720;
                    }
                    else if (isDvdResolution)
                    {
                        calculatedHeight = resizeTo.Height;
                        calculatedWidth = (int) (calculatedHeight*videoInfo.AspectRatio);
                    }
                    else
                        calculatedHeight = resizeTo.Height;

                    int temp;
                    Math.DivRem(calculatedWidth, 2, out temp);
                    calculatedWidth += temp;
                    Math.DivRem(calculatedHeight, 2, out temp);
                    calculatedHeight += temp;

                    if (Math.Abs(toAr - 1.778f) <= 0)     // aspectratio 16:9
                    {
                        addBorders = true;
                        int borderHeight = resizeTo.Height - calculatedHeight;
                        borderTop = borderHeight/2;
                        Math.DivRem(borderTop, 2, out temp);
                        borderTop += temp;
                        borderBottom = borderHeight - borderTop;

                        int borderWidth = (int) ((resizeTo.Width*mod) - calculatedWidth);
                        borderLeft = borderWidth/2;
                        Math.DivRem(borderLeft, 2, out temp);
                        borderLeft += temp;
                        borderRight = borderWidth - borderLeft;
                    }
                    else if (calculatedWidth != resizeTo.Width)
                    {
                        addBorders = true;
                        int borderWidth = resizeTo.Width - calculatedWidth;
                        borderLeft = borderWidth/2;
                        Math.DivRem(borderLeft, 2, out temp);
                        borderLeft += temp;
                        borderRight = borderWidth - borderLeft;

                        int borderHeight = resizeTo.Height - calculatedHeight;
                        borderTop = borderHeight/2;
                        Math.DivRem(borderTop, 2, out temp);
                        borderTop += temp;
                        borderBottom = borderHeight - borderTop;
                    }
                }
            }

            // apply resize filter
            if (calculatedHeight != videoInfo.Height || calculatedWidth != videoInfo.Width ||
                (stereoEncoding == StereoEncoding.HalfSideBySideLeft ||
                 stereoEncoding == StereoEncoding.HalfSideBySideRight
                && useStereo))
            {
                if (calculatedHeight < videoInfo.Height || calculatedWidth < videoInfo.Width ||
                    (stereoEncoding == StereoEncoding.HalfSideBySideLeft ||
                     stereoEncoding == StereoEncoding.HalfSideBySideRight
                     && useStereo))
                    sb.AppendLine(string.Format(AppSettings.CInfo, "BicubicResize({0:g},{1:g})",
                                                calculatedWidth,
                                                calculatedHeight));
                else
                    sb.AppendLine(string.Format(AppSettings.CInfo, "Lanczos4Resize({0:g},{1:g})",
                                                calculatedWidth,
                                                calculatedHeight));
            }

            // add borders if needed
            if (addBorders && (borderLeft > 0 || borderRight > 0 || borderTop > 0 || borderBottom > 0))
                sb.AppendLine(string.Format(AppSettings.CInfo, "AddBorders({0:g},{1:g},{2:g},{3:g})",
                                            borderLeft,
                                            borderTop,
                                            borderRight,
                                            borderBottom));

            // change framerate
            if (changeFps)
            {
                int fpsnum;
                int fpsden;

                // get framerate numerator & denominator for target framerate
                Processing.GetFPSNumDenom(targetFps, out fpsnum, out fpsden);

                // source is 23.976 or 24 fps
                if (videoInfo.FrameRateEnumerator == 24000 && (videoInfo.FrameRateDenominator == 1001 || videoInfo.FrameRateDenominator == 1000))
                {
                    if (fpsnum == 30000 && fpsden == 1001)
                    {
                        // 3:2 pulldown / telecine
                        sb.AppendLine("AssumeFrameBased()");
                        sb.AppendLine("SeparateFields()");
                        sb.AppendLine("SelectEvery(8, 0, 1, 2, 3, 2, 5, 4, 7, 6, 7)");
                        sb.AppendLine("Weave()");
                    }
                    else if (fpsnum == 25000 && fpsden == 1000)
                    {
                        // convert to 25 fps
                        sb.AppendLine("ConvertToYUY2()");
                        sb.AppendLine("ConvertFPS(50)");
                        sb.AppendLine("AssumeTFF()");
                        sb.AppendLine("SeparateFields()");
                        sb.AppendLine("SelectEvery(4,0,3)");
                        sb.AppendLine("Weave()");
                        sb.AppendLine("ConvertToYV12()");
                    }
                }
                // source is 30fps
                else if (videoInfo.FrameRateEnumerator == 30000)
                {
                    sb.AppendLine("ConvertToYUY2()");
                    sb.AppendLine("DoubleWeave()");
                    sb.AppendLine(string.Format(AppSettings.CInfo, "ConvertFPS({0:0.000})", targetFps*2));
                    sb.AppendLine("SelectEven()");
                    sb.AppendLine("ConvertToYV12()");
                }
                // source is 25fps
                else if (videoInfo.FrameRateEnumerator == 25000 && videoInfo.FrameRateDenominator == 1000)
                {
                    if ((fpsnum == 30000 || fpsnum == 24000) && fpsden == 1001)
                    {
                        sb.AppendLine("ConvertToYUY2()");
                        sb.AppendLine(string.Format(AppSettings.CInfo, "ConvertFPS({0:0.000}*2)", 23.976));
                        if (fpsnum == 30000)
                        {
                            sb.AppendLine("AssumeFrameBased()");
                            sb.AppendLine("SeparateFields()");
                            sb.AppendLine("SelectEvery(8, 0, 1, 2, 3, 2, 5, 4, 7, 6, 7)");
                        }
                        else
                        {
                            sb.AppendLine("AssumeTFF()");
                            sb.AppendLine("SeparateFields()");
                            sb.AppendLine("SelectEven()");
                        }
                        sb.AppendLine("Weave()");
                        sb.AppendLine("ConvertToYV12()");
                    }
                }
                // every other framerate
                else
                {
                    // very slow framerate interpolation
                    sb.AppendLine("super = MSuper(pel=2)");
                    sb.AppendLine("backward_vec = MAnalyse(super, overlap=4, isb = true, search=3)");
                    sb.AppendLine("forward_vec = MAnalyse(super, overlap=4, isb = false, search=3)");
                    sb.AppendFormat("MFlowFps(super, backward_vec, forward_vec, num={0:0}, den={1:0})", fpsnum,
                                    fpsden);
                }

                sb.AppendLine();
            }

            // multithreaded avisynth
            if (AppSettings.UseAviSynthMT && mtUseful)
            {
                sb.AppendLine("SetMTMode(1)");
                sb.AppendLine("GetMTMode(false) > 0 ? distributor() : last");
            }

            return WriteScript(sb.ToString());
        }
        private void GetFileInfo()
        {
            MediaInfoContainer mi = new MediaInfoContainer();
            try
            {
                mi = Processing.GetMediaInfo(JobInfo.InputFile);
            }
            catch (TimeoutException ex)
            {
                Log.Error(ex);
            }

            JobInfo.MediaInfo = mi;

            string fileTitleFormat = Processing.GetResourceString("streamselect_single_file_general");
            string fileAudioFormat = Processing.GetResourceString("streamselect_single_file_audio");
            string fileVideoFormat = Processing.GetResourceString("streamselect_single_file_video");
            string strChapters = Processing.GetResourceString("streamselect_chapters");
            string strVideo = Processing.GetResourceString("streamselect_video");
            string strAudio = Processing.GetResourceString("streamselect_audio");
            string strSubtitles = Processing.GetResourceString("streamselect_subtitles");

            string containerFormat = mi.General.Format;
            string duration = mi.General.DurationTime.ToString("H:mm:ss.fff");
            string shortFileName = mi.General.FileName + "." + mi.General.FileExtension;

            string treeRoot = string.Format(fileTitleFormat, shortFileName, containerFormat, duration);

            TreeNode root = new TreeNode
                {
                    ID = _treeNodeID++,
                    Name = treeRoot,
                    Data = JobInfo.InputFile,
                    IsChecked = true,
                    IsExpanded = true,
                    Children = new List<TreeNode>()
                };
            _tree.Add(root);

            TreeNode chaptersTree = CreateNode(root, strChapters, null);
            TreeNode videoTree = CreateNode(root, strVideo, null);
            TreeNode audioTree = CreateNode(root, strAudio, null);
            TreeNode subTree = CreateNode(root, strSubtitles, null);

            if (mi.Chapters.Count > 0)
            {
                string chaptersTitle = string.Format("{0:0} {1}", mi.Chapters.Count, strChapters);

                CreateNode(chaptersTree, chaptersTitle, mi.Chapters);
            }
            else
                chaptersTree.IsChecked = false;

            int streamIndex = 0;

            foreach (MediaInfoContainer.VideoStreamInfo clip in mi.Video)
            {
                streamIndex++;
                int videoPid = clip.ID;
                string videoCodec = clip.FormatInfo;
                string videoCodecShort = clip.Format;
                string videoDesc = string.Format(fileVideoFormat, clip.Width, clip.Height, clip.ScanType,
                                                 clip.FormatProfile, clip.FrameRate);

                string videoStreamTitle = string.Format("{3:g}: {0} ({1}), {2}", videoCodec, videoCodecShort, videoDesc,
                                                        streamIndex);

                VideoInfo vid = new VideoInfo();
                if (JobInfo.Input == InputType.InputAvi)
                    vid.StreamId = 0;
                else
                    vid.StreamId = videoPid == 0 ? streamIndex : videoPid;
                vid.FPS = clip.FrameRate;
                vid.PicSize = clip.VideoSize;
                vid.Interlaced = clip.ScanType == "Interlaced";
                vid.Format = clip.Format;
                vid.FormatProfile = clip.FormatProfile;
                vid.Height = clip.Height;
                vid.Width = clip.Width;
                vid.FrameCount = clip.FrameCount;
                vid.StreamSize = clip.StreamSize;
                vid.Length = mi.General.DurationTime.TimeOfDay.TotalSeconds;
                Single.TryParse(clip.DisplayAspectRatio, NumberStyles.Number, AppSettings.CInfo, out vid.AspectRatio);
                vid.FrameRateEnumerator = clip.FrameRateEnumerator;
                vid.FrameRateDenominator = clip.FrameRateDenominator;

                CreateNode(videoTree, videoStreamTitle, vid);
            }

            videoTree.IsChecked = videoTree.Children.Count > 0;

            foreach (MediaInfoContainer.AudioStreamInfo audio in mi.Audio)
            {
                streamIndex++;
                int audioPid = audio.ID;
                string audioCodec = audio.FormatInfo;
                string audioCodecShort = audio.Format;
                string audioLangCode = audio.LanguageIso6392;
                string audioLanguage = audio.LanguageFull;
                int audioStreamKindID = audio.StreamKindID;

                string audioDesc = string.Format(fileAudioFormat, audio.Channels, audio.ChannelPositions,
                                                 audio.SamplingRate, audio.BitDepth, audio.BitRate/1000);

                string audioStreamTitle = string.Format("{5:g}: {0} ({1}) / {2} ({3}) / {4}", audioCodec,
                                                        audioCodecShort, audioLangCode, audioLanguage, audioDesc,
                                                        streamIndex);

                if (JobInfo.Input == InputType.InputAvi)
                    audioPid += 1;
                else
                    audioPid = audioPid == 0 ? streamIndex : audioPid;

                AudioInfo aud = new AudioInfo
                    {
                        Id = audioPid,
                        Format = audioCodecShort,
                        FormatProfile = audio.FormatProfile,
                        StreamId = streamIndex,
                        LangCode = audioLangCode,
                        OriginalId = audioPid,
                        StreamKindId = audioStreamKindID,
                        Delay = audio.Delay,
                        Bitrate = audio.BitRate,
                        SampleRate = audio.SamplingRate,
                        ChannelCount = audio.Channels,
                        BitDepth = audio.BitDepth,
                        ShortLang = audio.LanguageIso6391,
                        StreamSize = audio.StreamSize,
                        Length = mi.General.DurationTime.TimeOfDay.TotalSeconds,
                        IsHdStream = audio.CompressionMode == "Lossless"
                    };

                CreateNode(audioTree, audioStreamTitle, aud);
            }

            audioTree.IsChecked = audioTree.Children.Count > 0;

            foreach (MediaInfoContainer.TextStreamInfo sub in mi.Text)
            {
                streamIndex++;
                string subCodec = sub.CodecIDInfo;
                string subCodecShort = sub.Format;
                string subLangCode = sub.LanguageIso6392;
                string subLanguage = sub.LanguageFull;
                int subStreamKindID = sub.StreamKindID;

                string subStreamTitle = string.Format("{4:g}: {0} ({1}) / {2} ({3})", subCodec, subCodecShort,
                                                      subLangCode, subLanguage, streamIndex);

                SubtitleInfo subInfo = new SubtitleInfo
                    {
                        Id = sub.ID,
                        StreamId = streamIndex,
                        LangCode = subLangCode,
                        Format = subCodecShort,
                        StreamKindId = subStreamKindID,
                        Delay = sub.Delay,
                        StreamSize = sub.StreamSize
                    };

                CreateNode(subTree, subStreamTitle, subInfo);
            }

            foreach (MediaInfoContainer.ImageStreamInfo sub in mi.Image)
            {
                streamIndex++;
                string subCodec = sub.CodecIDInfo;
                string subCodecShort = sub.Format;
                string subLangCode = sub.LanguageIso6392;
                string subLanguage = sub.LanguageFull;
                int subStreamKindID = sub.StreamKindID;

                string subStreamTitle = string.Format("{4:g}: {0} ({1}) / {2} ({3})", subCodec, subCodecShort,
                                                      subLangCode, subLanguage, streamIndex);
                SubtitleInfo subInfo = new SubtitleInfo
                    {
                        Id = sub.ID,
                        StreamId = streamIndex,
                        LangCode = subLangCode,
                        Format = subCodecShort,
                        StreamKindId = subStreamKindID,
                        Delay = 0,
                        StreamSize = sub.StreamSize
                    };

                CreateNode(subTree, subStreamTitle, subInfo);
            }

            subTree.IsChecked = subTree.Children.Count > 0;
        }