Example #1
0
            public Bitmap ReadFrameBitmap(int position)
            {
                Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                try
                {
                    // Lock the bitmap's bits.
                    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                    System.Drawing.Imaging.BitmapData bmpData =
                        bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                     bmp.PixelFormat);
                    try
                    {
                        // Get the address of the first line.
                        IntPtr ptr = bmpData.Scan0;
                        // Read data
                        clip.ReadFrame(ptr, bmpData.Stride, position);
                    }
                    finally
                    {
                        // Unlock the bits.
                        bmp.UnlockBits(bmpData);
                    }
                    bmp.RotateFlip(RotateFlipType.Rotate180FlipX);
                    return(bmp);
                }
                catch (System.Runtime.InteropServices.SEHException ex)
                {
                    bmp.Dispose();

                    MeGUI.core.util.LogItem _oLog = MainForm.Instance.AVSScriptCreatorLog;
                    if (_oLog == null)
                    {
                        _oLog = MainForm.Instance.Log.Info("AVS Script Creator");
                        MainForm.Instance.AVSScriptCreatorLog = _oLog;
                    }
                    _oLog.LogValue("Could not read frame", ex.Message, MeGUI.core.util.ImageType.Warning, true);

                    throw;
                }
                catch (Exception ex)
                {
                    bmp.Dispose();

                    MeGUI.core.util.LogItem _oLog = MainForm.Instance.AVSScriptCreatorLog;
                    if (_oLog == null)
                    {
                        _oLog = MainForm.Instance.Log.Info("AVS Script Creator");
                        MainForm.Instance.AVSScriptCreatorLog = _oLog;
                    }
                    _oLog.LogValue("Could not read frame", ex.Message, MeGUI.core.util.ImageType.Warning, true);

                    throw;
                }
            }
Example #2
0
        private void HandleAviSynthWrapperDLL(bool bUnload, string script)
        {
            lock (_lockerDLL)
            {
                if (MainForm.Instance.AviSynthWrapperLog == null)
                {
                    MainForm.Instance.AviSynthWrapperLog = MainForm.Instance.Log.Info("AviSynthWrapper");
                }

                bool bDebug = false;
#if DEBUG
                bDebug = true;
#endif
                core.util.LogItem _oLog = new core.util.LogItem("X");
                if (bUnload)
                {
                    _countDLL--;
                    if (_countDLL > 0)
                    {
                        _oLog = new core.util.LogItem("sessions open: " + _countDLL + ", id: " + _random + ", close");
                    }
                    else
                    {
                        bool   bResult = false;
                        string strFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "avisynthwrapper.dll");
                        foreach (System.Diagnostics.ProcessModule mod in System.Diagnostics.Process.GetCurrentProcess().Modules)
                        {
                            if (mod.FileName.ToLowerInvariant().Equals(strFile.ToLowerInvariant()))
                            {
                                bResult = FreeLibrary(mod.BaseAddress);
                            }
                            else if (mod.FileName.ToLowerInvariant().EndsWith("avisynth.dll"))
                            {
                                FreeLibrary(mod.BaseAddress);
                            }
                        }
                        _oLog = new core.util.LogItem("sessions open: " + _countDLL + ", id: " + _random + ", close: " + bResult);
                    }
                }
                else
                {
                    if (_countDLL == 0)
                    {
                        LoadLibraryA("avisynthwrapper.dll");
                    }
                    _countDLL++;
                    _oLog = new core.util.LogItem("sessions open: " + _countDLL + ", id: " + _random);
                }

                string strFileName = String.Empty;
                if (System.IO.File.Exists(script))
                {
                    strFileName = script;
                    try
                    {
                        System.IO.StreamReader sr = new System.IO.StreamReader(strFileName, Encoding.Default);
                        script = sr.ReadToEnd();
                        sr.Close();
                    }
                    catch (Exception) { }
                }
                _oLog.LogValue("Script" + (!String.IsNullOrEmpty(strFileName) ? ": " + strFileName : string.Empty), script);
                if (bDebug)
                {
                    _oLog.LogValue("StackTrace", Environment.StackTrace);
                }
                MainForm.Instance.AviSynthWrapperLog.Add(_oLog);
            }
        }
Example #3
0
        public static LogItem LogValue(string name, object value, ImageType image)
        {
            if (value == null)
            {
                value = "null"; // to avoid NullReferenceExceptions
            }
            List <Type> candidates = new List <Type>(typesHandled);

            // Remove the types which can't handle value
            candidates.RemoveAll(delegate(Type t)
            {
                return(!t.IsInstanceOfType(value));
            });

            // Ensure we used the most derived type
            candidates.RemoveAll(delegate(Type t)
            {
                foreach (Type t2 in candidates)
                {
                    if (t2.IsSubclassOf(t))
                    {
                        return(true);
                    }
                }
                return(false);
            });

            List <TypeHandler> handlerCands = candidates.ConvertAll <TypeHandler>(delegate(Type t) { return(typeHandlers[t]); });

            Type ty = value.GetType();

            if (ty.IsDefined(typeof(LogByMembersAttribute), true))
            {
                handlerCands.Add(LogByMembers);
            }
            if (ty.IsDefined(typeof(CustomLoggerAttribute), true))
            {
                CustomLoggerAttribute[] c = (CustomLoggerAttribute[])ty.GetCustomAttributes(typeof(CustomLoggerAttribute), true);
                Debug.Assert(c.Length == 1);
                handlerCands.Add(c[0].CustomLogger);
            }
            if (handlerCands.Count == 0 || ty.IsDefined(typeof(LogAsToStringAttribute), true))
            {
                handlerCands.Add(LogAsToString);
            }

            // We are guaranteed to have at least one logger: LogAsToString
            if (handlerCands.Count == 1)
            {
                return(handlerCands[0](name, value, image));
            }
            else
            {
                LogItem i = new LogItem(name, image);
                i.Warn(string.Format("More than 1 loggers are defined for type '{0}'.", ty));
                foreach (TypeHandler t in handlerCands)
                {
                    i.Add(t("Value", value, ImageType.NoImage));
                }
                return(i);
            }
        }
Example #4
0
        /// <summary>
        /// Detects if the AviSynth version can be used
        /// </summary>
        /// <returns>0 if everything is fine, 3 if the version is outdated or a different value for other errors</param>
        public static int CheckAvisynthInstallation(out string strVersion, out bool bIsAVS26, out bool bIsAVSPlus, out bool bIsMT, out string strAviSynthDLL, ref core.util.LogItem oLog)
        {
            strVersion     = "";
            bIsAVS26       = false;
            bIsAVSPlus     = false;
            bIsMT          = false;
            strAviSynthDLL = string.Empty;

            IntPtr             _avs        = new IntPtr(0);
            AVSDLLVideoInfo    _vi         = new AVSDLLVideoInfo();
            AviSynthColorspace _colorSpace = AviSynthColorspace.Unknown;
            AudioSampleType    _sampleType = AudioSampleType.Unknown;

            int iStartResult = -1;

            try
            {
                iStartResult = dimzon_avs_init_2(ref _avs, "Eval", "Version()", ref _vi, ref _colorSpace, ref _sampleType, AviSynthColorspace.RGB24.ToString());

                foreach (System.Diagnostics.ProcessModule module in System.Diagnostics.Process.GetCurrentProcess().Modules)
                {
                    if (module.FileName.ToLowerInvariant().EndsWith("avisynth.dll"))
                    {
                        strAviSynthDLL = module.FileName.ToLowerInvariant();
                    }
                }

                if (iStartResult == 0)
                {
                    int iWrapperVersion = GetAvisynthWrapperInterfaceVersion();
                    try
                    {
                        const int     errlen = 1024;
                        StringBuilder sb     = new StringBuilder(errlen);
                        sb.Length  = dimzon_avs_getstrfunction(_avs, "VersionString", sb, errlen);
                        strVersion = sb.ToString();

                        bool bResult = false;
                        int  iResult = dimzon_avs_functionexists(_avs, "AutoloadPlugins", ref bResult);
                        bIsAVSPlus = false;
                        if (iResult == 0)
                        {
                            bIsAVSPlus = bResult;
                        }

                        if (iWrapperVersion < 5)
                        {
                            bResult  = false;
                            iResult  = dimzon_avs_functionexists(_avs, "ConvertToYV16", ref bResult);
                            bIsAVS26 = false;
                            if (iResult == 0)
                            {
                                bIsAVS26 = bResult;
                            }
                        }
                        else
                        {
                            bIsAVS26 = true;
                        }

                        string strMTFunction = "Prefetch";
                        if (!bIsAVSPlus)
                        {
                            strMTFunction = "SetMTMode";
                        }
                        bResult = false;
                        iResult = dimzon_avs_functionexists(_avs, strMTFunction, ref bResult);
                        bIsMT   = false;
                        if (iResult == 0)
                        {
                            bIsMT = bResult;
                        }
                    }
                    catch (Exception ex)
                    {
                        oLog.LogValue("Error", ex.Message, core.util.ImageType.Error, false);
                    }
                }

                int iCloseResult = dimzon_avs_destroy(ref _avs);
                if (_avs != IntPtr.Zero)
                {
                    CloseHandle(_avs);
                }
                _avs = IntPtr.Zero;
            }
            catch (Exception ex)
            {
                oLog.LogValue("Error", ex.Message, core.util.ImageType.Error, false);
            }

            return(iStartResult);
        }
Example #5
0
        /// <summary>
        /// Attempts to delete all files and directories listed
        /// in job.FilesToDelete if settings.DeleteIntermediateFiles is checked
        /// </summary>
        /// <param name="job">the job which should just have been completed</param>
        public static LogItem DeleteIntermediateFiles(List <string> files, bool bAlwaysAddLog, bool askAboutDelete)
        {
            bool    bShowLog = false;
            LogItem i        = new LogItem(string.Format("[{0:G}] {1}", DateTime.Now, "Deleting intermediate files"));

            List <string> arrFiles = new List <string>();

            foreach (string file in files)
            {
                if (Directory.Exists(file))
                {
                    continue;
                }
                else if (!File.Exists(file))
                {
                    continue;
                }
                if (!arrFiles.Contains(file))
                {
                    arrFiles.Add(file);
                }
            }

            if (arrFiles.Count > 0)
            {
                bShowLog = true;
                bool delete = true;

                if (askAboutDelete)
                {
                    delete = MainForm.Instance.DialogManager.DeleteIntermediateFiles(arrFiles);
                }
                if (!delete)
                {
                    return(null);
                }

                // delete all files first
                foreach (string file in arrFiles)
                {
                    int iCounter = 0;
                    while (File.Exists(file))
                    {
                        try
                        {
                            File.Delete(file);
                            i.LogEvent("Successfully deleted " + file);
                        }
                        catch (IOException e)
                        {
                            if (++iCounter >= 3)
                            {
                                i.LogValue("Problem deleting " + file, e.Message, ImageType.Warning);
                                break;
                            }
                            else
                            {
                                System.Threading.Thread.Sleep(2000);
                            }
                        }
                    }
                }
            }

            // delete empty directories
            foreach (string file in files)
            {
                try
                {
                    if (Directory.Exists(file))
                    {
                        bShowLog = true;
                        if (Directory.GetFiles(file, "*.*", SearchOption.AllDirectories).Length == 0)
                        {
                            Directory.Delete(file, true);
                            i.LogEvent("Successfully deleted directory " + file);
                        }
                        else
                        {
                            i.LogEvent("Did not delete " + file + " as the directory is not empty.", ImageType.Warning);
                        }
                    }
                }
                catch (IOException e)
                {
                    i.LogValue("Problem deleting directory " + file, e.Message, ImageType.Warning);
                }
            }
            if (bAlwaysAddLog || bShowLog)
            {
                return(i);
            }
            return(null);
        }
Example #6
0
        /// <summary>
        /// Detects the AviSynth version/date and writes it into the log
        /// </summary>
        /// <param name="oLog">the version information will be added to the log if available</param>
        public static void CheckAviSynth(LogItem oLog)
        {
            string fileVersion             = string.Empty;
            string fileDate                = string.Empty;
            string fileProductName         = string.Empty;
            bool   bFoundInstalledAviSynth = false;

            // remove msvc files
            LSMASHFileActions(true);
            PortableAviSynthActions(true);

            // detect system installation
            string syswow64path = Environment.GetFolderPath(Environment.SpecialFolder.System).ToLowerInvariant().Replace("\\system32", "\\SysWOW64");

#if x86
            // on a x86 MeGUI build try the SysWOW64 folder first
            if (GetFileInformation(Path.Combine(syswow64path, "avisynth.dll"), out fileVersion, out fileDate, out fileProductName))
            {
                bFoundInstalledAviSynth = true;
            }
            else if (!Directory.Exists(syswow64path) &&
                     GetFileInformation(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "avisynth.dll"), out fileVersion, out fileDate, out fileProductName))
#endif
#if x64
            if (GetFileInformation(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "avisynth.dll"), out fileVersion, out fileDate, out fileProductName))
#endif
            bFoundInstalledAviSynth = true;

            if (bFoundInstalledAviSynth)
            {
                if (fileProductName.Contains("+") && !MainForm.Instance.Settings.AlwaysUsePortableAviSynth)
                {
                    MainForm.Instance.Settings.AviSynthPlus = true;
                }
                if (oLog != null)
                {
                    oLog.LogValue("AviSynth" + (fileProductName.Contains("+") ? "+" : String.Empty),
                                  fileVersion + " (" + fileDate + ")" + (!MainForm.Instance.Settings.AlwaysUsePortableAviSynth ? String.Empty : " (inactive)"));
                }
                if (!MainForm.Instance.Settings.AlwaysUsePortableAviSynth)
                {
                    if (!MainForm.Instance.Settings.AviSynthPlus)
                    {
                        LSMASHFileActions(false);
                    }
                    return;
                }
            }

            // detects included avisynth
            MainForm.Instance.Settings.PortableAviSynth = false;
            if (GetFileInformation(MainForm.Instance.Settings.AviSynth.Path, out fileVersion, out fileDate, out fileProductName))
            {
                if (oLog != null)
                {
                    oLog.LogValue("AviSynth" + (fileProductName.Contains("+") ? "+" : String.Empty) + " portable",
                                  fileVersion + " (" + fileDate + ")" + (!bFoundInstalledAviSynth ? String.Empty : " (active)"));
                }
                if (!bFoundInstalledAviSynth || MainForm.Instance.Settings.AlwaysUsePortableAviSynth)
                {
                    UpdateCacher.CheckPackage("avs");
                    MainForm.Instance.Settings.PortableAviSynth = true;
                    PortableAviSynthActions(false);
                    if (fileProductName.Contains("+"))
                    {
                        MainForm.Instance.Settings.AviSynthPlus = true;
                    }
                }
            }
            else if (!bFoundInstalledAviSynth)
            {
                if (oLog != null)
                {
                    oLog.LogValue("AviSynth", "not found", ImageType.Error);
                }
            }

            if (!MainForm.Instance.Settings.AviSynthPlus)
            {
                LSMASHFileActions(false);
            }
        }
Example #7
0
        /// <summary>
        /// gets the desired resolution based on input settings
        /// </summary>
        /// <param name="sourceWidth">the complete width of the input file without cropping</param>
        /// <param name="sourceHeight">the complete height of the input file without cropping</param>
        /// <param name="inputDAR">the input DAR value</param>
        /// <param name="cropValues">the crop values</param>
        /// <param name="cropEnabled">true if crop values must be used</param>
        /// <param name="mod">the mod value used for the final resize values</param>
        /// <param name="resizeEnabled">true if resize can be used</param>
        /// <param name="upsizingEnabled">true if upsizing can be used</param>
        /// <param name="signalAR">whether or not ar signalling is to be used for the output
        /// (depending on this parameter, resizing changes to match the source AR)</param>
        /// <param name="suggestHeight">true if height should be calculated</param>
        /// <param name="acceptableAspectErrorPercent">acceptable aspect error if signalAR is true</param>
        /// <param name="xTargetDevice">x264 Target Device - may limit the output resolution</param>
        /// <param name="fps">the frames per second of the source</param>
        /// <param name="outputWidth">the calculated output width</param>
        /// <param name="outputHeight">the calculated output height</param>
        /// <param name="paddingValues">the padding values</param>
        /// <param name="outputDar">the output DAR value</param>
        /// <param name="_log">the log item</param>
        public static void GetResolution(int sourceWidth, int sourceHeight, Dar inputDar,
                                         ref CropValues cropValues, bool cropEnabled, int mod, ref bool resizeEnabled, bool upsizingAllowed,
                                         bool signalAR, bool suggestHeight, decimal acceptableAspectErrorPercent,
                                         x264Device xTargetDevice, Double fps, ref int outputWidth, ref int outputHeight,
                                         out CropValues paddingValues, out Dar?outputDar, LogItem _log)
        {
            paddingValues = new CropValues();

            getResolution(sourceWidth, sourceHeight, inputDar,
                          cropValues, cropEnabled, mod, resizeEnabled, upsizingAllowed,
                          signalAR, suggestHeight, acceptableAspectErrorPercent,
                          ref outputWidth, ref outputHeight,
                          out outputDar, _log);

            bool settingsChanged;

            if (isResolutionDeviceCompliant(xTargetDevice, outputWidth, outputHeight, out settingsChanged, ref resizeEnabled, ref cropEnabled, _log) == true)
            {
                if (!cropEnabled)
                {
                    cropValues = new CropValues();
                }
                return;
            }

            if (settingsChanged)
            {
                getResolution(sourceWidth, sourceHeight, inputDar,
                              cropValues, cropEnabled, mod, resizeEnabled, upsizingAllowed,
                              signalAR, suggestHeight, acceptableAspectErrorPercent,
                              ref outputWidth, ref outputHeight,
                              out outputDar, _log);

                // check if the resolution is now compliant
                if (isResolutionDeviceCompliant(xTargetDevice, outputWidth, outputHeight, out settingsChanged, ref resizeEnabled, ref cropEnabled, null) == true)
                {
                    if (!cropEnabled)
                    {
                        cropValues = new CropValues();
                    }
                    return;
                }
            }
            if (!cropEnabled)
            {
                cropValues = new CropValues();
            }

            // adjust horizontal resolution if width or height are too large
            int outputHeightIncludingPadding = 0;
            int outputWidthIncludingPadding  = 0;

            if (xTargetDevice.BluRay)
            {
                if (outputWidth >= 1920)
                {
                    outputWidth = 1920;
                    outputHeightIncludingPadding = 1080;
                }
                else if (outputWidth >= 1280)
                {
                    outputWidth = 1280;
                    outputHeightIncludingPadding = 720;
                }
                else
                {
                    outputWidth = 720;
                    if (fps == 25)
                    {
                        outputHeightIncludingPadding = 576;
                    }
                    else
                    {
                        outputHeightIncludingPadding = 480;
                    }
                }
                outputWidthIncludingPadding = outputWidth;
                if (_log != null)
                {
                    _log.LogEvent("Force resolution of " + outputWidth + "x" + outputHeightIncludingPadding + " as required for " + xTargetDevice.Name);
                }
            }
            else if (xTargetDevice.Width > 0 && outputWidth > xTargetDevice.Width)
            {
                outputWidth = xTargetDevice.Width;
                _log.LogEvent("Set resolution width to " + outputWidth + " as required for " + xTargetDevice.Name);
            }

            // adjust cropped vertical resolution
            getResolution(sourceWidth, sourceHeight, inputDar,
                          cropValues, cropEnabled, mod, resizeEnabled, upsizingAllowed,
                          signalAR, suggestHeight, acceptableAspectErrorPercent,
                          ref outputWidth, ref outputHeight,
                          out outputDar, _log);
            while ((xTargetDevice.Height > 0 && outputHeight > xTargetDevice.Height) || (xTargetDevice.BluRay && outputHeight > outputHeightIncludingPadding))
            {
                outputWidth -= mod;
                getResolution(sourceWidth, sourceHeight, inputDar,
                              cropValues, cropEnabled, mod, resizeEnabled, upsizingAllowed,
                              signalAR, suggestHeight, acceptableAspectErrorPercent,
                              ref outputWidth, ref outputHeight,
                              out outputDar, _log);
            }

            paddingValues.left   = Convert.ToInt32(Math.Floor((outputWidthIncludingPadding - outputWidth) / 2.0));
            paddingValues.right  = Convert.ToInt32(Math.Ceiling((outputWidthIncludingPadding - outputWidth) / 2.0));
            paddingValues.bottom = Convert.ToInt32(Math.Floor((outputHeightIncludingPadding - outputHeight) / 2.0));
            paddingValues.top    = Convert.ToInt32(Math.Ceiling((outputHeightIncludingPadding - outputHeight) / 2.0));

            outputWidth  = outputWidthIncludingPadding;
            outputHeight = outputHeightIncludingPadding;

            if (!cropEnabled)
            {
                cropValues = new CropValues();
            }
        }
Example #8
0
        /// <summary>
        /// gets the desired resolution based on input settings
        /// </summary>
        /// <param name="sourceWidth">the complete width of the input file without cropping</param>
        /// <param name="sourceHeight">the complete height of the input file without cropping</param>
        /// <param name="inputDAR">the input DAR value</param>
        /// <param name="cropping">the crop values</param>
        /// <param name="mod">the mod value used for the final resize values</param>
        /// <param name="resizeEnabled">true if resize can be used</param>
        /// <param name="upsizingEnabled">true if upsizing can be used</param>
        /// <param name="signalAR">whether or not ar signalling is to be used for the output
        /// (depending on this parameter, resizing changes to match the source AR)</param>
        /// <param name="suggestHeight">true if height should be calculated</param>
        /// <param name="acceptableAspectErrorPercent">acceptable aspect error if signalAR is true</param>
        /// <param name="outputWidth">the calculated output width</param>
        /// <param name="outputHeight">the calculated output height</param>
        /// <param name="outputDar">the output DAR value</param>
        /// <param name="_log">the log item</param>
        private static void getResolution(int sourceWidth, int sourceHeight, Dar inputDar,
                                          CropValues cropValues, bool cropEnabled, int mod, bool resizeEnabled,
                                          bool upsizingAllowed, bool signalAR, bool suggestHeight,
                                          decimal acceptableAspectErrorPercent, ref int outputWidth,
                                          ref int outputHeight, out Dar?outputDar, LogItem _log)
        {
            outputDar = null;

            CropValues cropping = new CropValues();

            if (cropEnabled)
            {
                cropping = cropValues.Clone();
            }

            // remove upsizing if not allowed
            if (!upsizingAllowed && sourceWidth - cropping.left - cropping.right < outputWidth)
            {
                outputWidth = sourceWidth - cropping.left - cropping.right;
                if (_log != null)
                {
                    _log.LogEvent("Lowering output width resolution to " + outputWidth + " to avoid upsizing");
                }
            }

            // correct hres if not mod compliant
            if (outputWidth % mod != 0)
            {
                int diff = outputWidth % mod;
                if (outputWidth - diff > 0)
                {
                    outputWidth -= diff;
                }
                else
                {
                    outputWidth = mod;
                }
            }

            if (suggestHeight)
            {
                int scriptVerticalResolution = Resolution.SuggestVerticalResolution(sourceHeight, sourceWidth, inputDar, cropping,
                                                                                    outputWidth, signalAR, out outputDar, mod, acceptableAspectErrorPercent);

                int iMaximum = 9999;
                if (!upsizingAllowed)
                {
                    iMaximum = sourceHeight - cropping.top - cropping.bottom;
                }

                // Reduce horizontal resolution until a fit is found
                while (scriptVerticalResolution > iMaximum && outputWidth > mod)
                {
                    outputWidth -= mod;
                    scriptVerticalResolution = Resolution.SuggestVerticalResolution(sourceHeight, sourceWidth, inputDar, cropping,
                                                                                    outputWidth, signalAR, out outputDar, mod, acceptableAspectErrorPercent);
                }
                outputHeight = scriptVerticalResolution;
            }
            else if (!resizeEnabled)
            {
                outputHeight = sourceHeight - cropping.top - cropping.bottom;
            }
        }
Example #9
0
        /// <summary>
        /// check if resolution is device compatible
        /// </summary>
        /// <param name="xTargetDevice">x264 Target Device - may limit the output resolution</param>
        /// <param name="outputWidth">the calculated output width</param>
        /// <param name="outputHeight">the calculated output height</param>
        /// <param name="settingsChanged">true if resize or crop has been changed</param>
        /// <param name="resizeEnabled">if resize is enabled</param>
        /// <param name="cropEnabled">if crop is enabled</param>
        /// <param name="_log">log item</param>
        /// <returns>true if the settings are device compatible</returns>
        private static bool isResolutionDeviceCompliant(x264Device xTargetDevice, int outputWidth, int outputHeight,
                                                        out bool settingsChanged, ref bool resizeEnabled, ref bool cropEnabled, LogItem _log)
        {
            settingsChanged = false;
            if (xTargetDevice == null)
            {
                return(true);
            }
            if (!xTargetDevice.BluRay && xTargetDevice.Height <= 0 && xTargetDevice.Width <= 0)
            {
                return(true);
            }

            bool bAdjustResolution = false;

            if (xTargetDevice.Width > 0 && xTargetDevice.Width < outputWidth)
            {
                // width must be lowered to be target conform
                bAdjustResolution = true;
                if (!resizeEnabled)
                {
                    resizeEnabled = settingsChanged = true;
                    if (_log != null)
                    {
                        _log.LogEvent("Enabling \"Resize\" as " + xTargetDevice.Name + " does not support a resolution width of "
                                      + outputWidth + ". The maximum value is " + xTargetDevice.Width + ".");
                    }
                }
            }
            else if (xTargetDevice.Height > 0 && xTargetDevice.Height < outputHeight)
            {
                // height must be lowered to be target conform
                bAdjustResolution = true;
                if (!resizeEnabled)
                {
                    resizeEnabled = settingsChanged = true;
                    if (_log != null)
                    {
                        _log.LogEvent("Enabling \"Resize\" as " + xTargetDevice.Name + " does not support a resolution height of "
                                      + outputHeight + ". The maximum value is " + xTargetDevice.Height + ".");
                    }
                }
            }
            else if (xTargetDevice.BluRay)
            {
                string strResolution = outputWidth + "x" + outputHeight;
                if (!strResolution.Equals("1920x1080") &&
                    !strResolution.Equals("1440x1080") &&
                    !strResolution.Equals("1280x720") &&
                    !strResolution.Equals("720x576") &&
                    !strResolution.Equals("720x480"))
                {
                    bAdjustResolution = settingsChanged = true;
                    if (!resizeEnabled)
                    {
                        resizeEnabled = true;
                        if (_log != null)
                        {
                            _log.LogEvent("Enabling \"Resize\" as " + xTargetDevice.Name + " does not support a resolution of "
                                          + outputWidth + "x" + outputHeight
                                          + ". Supported are 1920x1080, 1440x1080, 1280x720, 720x576 and 720x480.");
                        }
                    }
                }
            }

            if (bAdjustResolution && !cropEnabled)
            {
                if (_log != null)
                {
                    _log.LogEvent("Enabling \"Crop\"");
                }
                cropEnabled = settingsChanged = true;
            }

            if (bAdjustResolution)
            {
                return(false);
            }
            return(true);
        }
Example #10
0
        /// <summary>
        /// get number of angles
        /// </summary>
        /// <param name="fileName">name of the IFO file</param>
        /// <param name="iPGCNumber">PGC number</param>
        /// <returns>number of angles</returns>
        public static int GetAngleCount(string strIFOFile, int iPGCNumber)
        {
            byte[] buff        = new byte[4];
            byte   s           = 0;
            int    iAngleCount = 0;

            // find the VTS_PGC starting address of the requested PGC number in VTS_PGCI
            long VTS_PGCI = GetPCGIP_Position(strIFOFile);
            long VTS_PGC  = VTS_PGCI + GetPGCOffset(strIFOFile, VTS_PGCI, iPGCNumber);

            try
            {
                FileStream   fs = new FileStream(strIFOFile, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                Stream       sr = br.BaseStream;

                // go to the cell count in VTS_PGC of the requested PGC number
                sr.Seek(VTS_PGC + 0x03, SeekOrigin.Begin);
                int iCellCount = br.ReadByte();

                //find the cell playback information table start in VTS_PGC of the requested PGC number
                long VTS_PGC_CELL_START = VTS_PGC + ToInt16(GetFileBlock(strIFOFile, VTS_PGC + 0xE8, 2));

                int iAngleCountTemp = 0;
                // cycle through all cell informations
                for (int i = 1; i <= iCellCount; i++)
                {
                    // go to the start of the table
                    sr.Seek(VTS_PGC_CELL_START + (i - 1) * 0x18, SeekOrigin.Begin);
                    s = br.ReadByte();

                    var seamless          = (s >> 0) & 1;
                    var stc               = (s >> 1) & 1;
                    var interleaved       = (s >> 2) & 1;
                    var seamless_playback = (s >> 3) & 1;
                    var block_type        = (s >> 4) & 3;
                    var cell_type         = (s >> 6) & 3;

                    // angle block found?
                    if (block_type != 1)
                    {
                        continue;
                    }

                    // bits: 00 = normal, 01 = first of angle block, 10 = middle of angle block, 11 = last of angle block
                    if (cell_type == 1)
                    {
                        //  first angle block
                        iAngleCountTemp = 1;
                    }
                    else if (cell_type == 2)
                    {
                        // middle of angle block
                        iAngleCountTemp++;
                    }
                    else if (cell_type == 3)
                    {
                        // last of angle block
                        iAngleCountTemp++;
                        if (iAngleCount == 0 || iAngleCount > iAngleCountTemp)
                        {
                            iAngleCount = iAngleCountTemp;
                        }
                    }
                }
                fs.Close();
            }
            catch (Exception ex)
            {
                LogItem _oLog = MainForm.Instance.Log.Info("IFOparser");
                _oLog.LogValue("Error parsing ifo file " + strIFOFile, ex.Message, ImageType.Error);
            }
            return(iAngleCount);
        }
Example #11
0
        /// <summary>
        /// get several Subtitles Informations from the IFO file
        /// </summary>
        /// <param name="fileName">name of the IFO file</param>
        /// <returns>several infos as String</returns>
        public static string[] GetSubtitlesStreamsInfos(string FileName, int iPGC, bool bGetAllStreams)
        {
            byte[]   buff       = new byte[4];
            string[] substreams = new string[32]; // according to the specs 32 is the max value for subtitles streams

            try
            {
                // get the number of subpicture streams in VTS_VOBS
                int iSubtitleCount = ToInt16(GetFileBlock(FileName, 0x254, 2));
                if (iSubtitleCount == 0 && !bGetAllStreams)
                {
                    return(new string[0]);
                }

                string[] subdesc = new string[32];

                FileStream   fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                Stream       sr = br.BaseStream;

                // go to the subpicture attributes of VTS_VOBS
                sr.Seek(0x256, SeekOrigin.Begin);
                for (int i = 0; i < 32; i++)
                {
                    // Presence (1 bit), Coding Mode (1bit), Short Language Code (2bits), Language Extension (1bit), Sub Picture Caption Type (1bit)

                    // ignore presence & coding mode and go to short language code
                    sr.Seek(0x2, SeekOrigin.Current);

                    // read short language code
                    br.Read(buff, 0, 2);

                    string ShortLangCode = String.Format("{0}{1}", (char)buff[0], (char)buff[1]);
                    subdesc[i] = LanguageSelectionContainer.LookupISOCode(ShortLangCode) + " - ";
                    if (String.IsNullOrEmpty(subdesc[i]))
                    {
                        subdesc[i] = "unknown - ";
                    }

                    // Go to Code Extension
                    sr.Seek(1, SeekOrigin.Current);
                    buff[0] = br.ReadByte();

                    switch (buff[0] & 0x0F)
                    {
                    // from http://dvd.sourceforge.net/dvdinfo/sprm.html
                    case 1: subdesc[i] += "Caption "; break;

                    case 2: subdesc[i] += "Caption (Large) "; break;

                    case 3: subdesc[i] += "Caption for Children "; break;

                    case 5: subdesc[i] += "Closed Caption "; break;

                    case 6: subdesc[i] += "Closed Caption (Large) "; break;

                    case 7: subdesc[i] += "Closed Caption for Children "; break;

                    case 9: subdesc[i] += "Forced Caption "; break;

                    case 13: subdesc[i] += "Director Comments "; break;

                    case 14: subdesc[i] += "Director Comments (Large) "; break;

                    case 15: subdesc[i] += "Director Comments for Children "; break;
                    }
                }

                // get VTS_PGCI
                long VTS_PGCI = GetPCGIP_Position(FileName);

                // find the VTS_PGC starting address of the requested PGC number in VTS_PGCI
                long VTS_PGC = VTS_PGCI + GetPGCOffset(FileName, VTS_PGCI, iPGC);

                // go to the Subpicture Stream Control (PGC_SPST_CTL) in VTS_PGC of the requested PGC number
                sr.Seek(VTS_PGC + 0x1C, SeekOrigin.Begin);

                byte[] iCountType = new byte[4];
                for (int i = 0; i < 32; i++)
                {
                    // read subtitle info of stream i
                    br.Read(buff, 0, 4);

                    // if bit 7 = 1 (true) the stream is available
                    if (!GetBit(buff[0], 7))
                    {
                        continue;
                    }

                    // remove bits 7, 6 and 5 as they are reserved
                    for (int j = 0; j < 4; j++)
                    {
                        if (GetBit(buff[j], 7))
                        {
                            buff[j] -= 128;
                        }
                        if (GetBit(buff[j], 6))
                        {
                            buff[j] -= 64;
                        }
                        if (GetBit(buff[j], 5))
                        {
                            buff[j] -= 32;
                        }
                    }

                    if (buff[0] > 0)
                    {
                        substreams[buff[0]] = "[" + String.Format("{0:00}", buff[0]) + "] - " + subdesc[i];
                        iCountType[0]++;
                    }
                    if (buff[1] > 0)
                    {
                        substreams[buff[1]] = "[" + String.Format("{0:00}", buff[1]) + "] - " + subdesc[i];
                        iCountType[1]++;
                    }
                    if (buff[2] > 0)
                    {
                        substreams[buff[2]] = "[" + String.Format("{0:00}", buff[2]) + "] - " + subdesc[i];
                        iCountType[2]++;
                    }
                    if (buff[3] > 0)
                    {
                        substreams[buff[3]] = "[" + String.Format("{0:00}", buff[3]) + "] - " + subdesc[i];
                        iCountType[3]++;
                    }

                    // as stream ID 0 is impossible to detect, we have to guess here
                    if (String.IsNullOrEmpty(substreams[0]))
                    {
                        if (buff[0] == 0 || buff[1] == 0 || buff[2] == 0 || buff[3] == 0)
                        {
                            substreams[0] = "[" + String.Format("{0:00}", 0) + "] - " + subdesc[i];
                        }
                    }
                }

                // check how many different types are there & if therefore the type description has to be added
                int iDifferentTypes = 0;
                if (iCountType[0] > 0)
                {
                    iDifferentTypes++;
                }
                if (iCountType[1] > 0)
                {
                    iDifferentTypes++;
                }
                if (iCountType[2] > 0)
                {
                    iDifferentTypes++;
                }
                if (iCountType[3] > 0)
                {
                    iDifferentTypes++;
                }
                bool bAddTypes = iDifferentTypes > 1;
                if (bAddTypes)
                {
                    for (int i = 0; i < subdesc.Length; i++)
                    {
                        if (!String.IsNullOrEmpty(subdesc[i]))
                        {
                            subdesc[i] += (subdesc[i].Substring(subdesc[i].Length - 1).Equals(" ") ? "(" : " (");
                        }
                    }

                    // go to the Subpicture Stream Control in VTS_PGC of the requested PGC number
                    sr.Seek(VTS_PGC + 0x1C, SeekOrigin.Begin);

                    int iCountStream = 0;
                    for (int i = 0; i < 32; i++)
                    {
                        // read subtitle info of stream i
                        br.Read(buff, 0, 4);

                        // if bit 7 = 1 (true) the stream is available
                        if (!GetBit(buff[0], 7))
                        {
                            continue;
                        }

                        iCountStream++;

                        // remove bits 7, 6 and 5 as they are reserved
                        for (int j = 0; j < 4; j++)
                        {
                            if (GetBit(buff[j], 7))
                            {
                                buff[j] -= 128;
                            }
                            if (GetBit(buff[j], 6))
                            {
                                buff[j] -= 64;
                            }
                            if (GetBit(buff[j], 5))
                            {
                                buff[j] -= 32;
                            }
                        }

                        if (buff[0] > 0)
                        {
                            if (substreams[buff[0]].Substring(substreams[buff[0]].Length - 1).Equals(")"))
                            {
                                substreams[buff[0]] = substreams[buff[0]].Substring(0, substreams[buff[0]].Length - 1) + "/4:3)";
                            }
                            else
                            {
                                substreams[buff[0]] += "(4:3)";
                            }
                        }
                        if (buff[1] > 0)
                        {
                            if (substreams[buff[1]].Substring(substreams[buff[1]].Length - 1).Equals(")"))
                            {
                                substreams[buff[1]] = substreams[buff[1]].Substring(0, substreams[buff[1]].Length - 1) + "/Wide)";
                            }
                            else
                            {
                                substreams[buff[1]] += "(Wide)";
                            }
                        }
                        if (buff[2] > 0)
                        {
                            if (substreams[buff[2]].Substring(substreams[buff[2]].Length - 1).Equals(")"))
                            {
                                substreams[buff[2]] = substreams[buff[2]].Substring(0, substreams[buff[2]].Length - 1) + "/Letterbox)";
                            }
                            else
                            {
                                substreams[buff[2]] += "(Letterbox)";
                            }
                        }
                        if (buff[3] > 0)
                        {
                            if (substreams[buff[3]].Substring(substreams[buff[3]].Length - 1).Equals(")"))
                            {
                                substreams[buff[3]] = substreams[buff[3]].Substring(0, substreams[buff[3]].Length - 1) + "/Pan&Scan)";
                            }
                            else
                            {
                                substreams[buff[3]] += "(Pan&Scan)";
                            }
                        }

                        if (bAddTypes && iCountStream == 2)
                        {
                            // only when the types should be added and the second track is in process
                            // first one is ignored because of the 0 stream ID which cannot be detected
                            int iID = 0;
                            if (buff[0] > 0)
                            {
                                iID = buff[0];
                                if (substreams[0].Substring(substreams[0].Length - 1).Equals(")"))
                                {
                                    substreams[0] = substreams[0].Substring(0, substreams[0].Length - 1) + "/4:3)";
                                }
                                else
                                {
                                    substreams[0] += "(4:3)";
                                }
                            }
                            if (buff[1] > 0 && (iID == 0 || iID == buff[1]))
                            {
                                iID = buff[1];
                                if (substreams[0].Substring(substreams[0].Length - 1).Equals(")"))
                                {
                                    substreams[0] = substreams[0].Substring(0, substreams[0].Length - 1) + "/Wide)";
                                }
                                else
                                {
                                    substreams[0] += "(Wide)";
                                }
                            }
                            if (buff[2] > 0 && (iID == 0 || iID == buff[2]))
                            {
                                iID = buff[2];
                                if (substreams[0].Substring(substreams[0].Length - 1).Equals(")"))
                                {
                                    substreams[0] = substreams[0].Substring(0, substreams[0].Length - 1) + "/Letterbox)";
                                }
                                else
                                {
                                    substreams[0] += "(Letterbox)";
                                }
                            }
                            if (buff[3] > 0 && (iID == 0 || iID == buff[3]))
                            {
                                iID = buff[3];
                                if (substreams[0].Substring(substreams[0].Length - 1).Equals(")"))
                                {
                                    substreams[0] = substreams[0].Substring(0, substreams[0].Length - 1) + "/Pan&Scan)";
                                }
                                else
                                {
                                    substreams[0] += "(Pan&Scan)";
                                }
                            }
                        }
                    }
                }

                if (bGetAllStreams)
                {
                    for (int i = 0; i < 32; i++)
                    {
                        if (String.IsNullOrEmpty(substreams[i]))
                        {
                            substreams[i] = "[" + String.Format("{0:00}", i) + "] - not detected";
                        }
                    }
                }
                else
                {
                    ArrayList arrList = new ArrayList();
                    foreach (string strItem in substreams)
                    {
                        if (!String.IsNullOrEmpty(strItem))
                        {
                            // remove trailing " - " if it exists
                            if (strItem.Substring(strItem.Length - 3).Equals(" - "))
                            {
                                arrList.Add(strItem.Substring(0, strItem.Length - 3).Trim());
                            }
                            else
                            {
                                arrList.Add(strItem.Trim());
                            }
                        }
                    }
                    substreams = new string[arrList.Count];
                    for (int i = 0; i < arrList.Count; i++)
                    {
                        substreams[i] = arrList[i].ToString();
                    }
                }

                fs.Close();
            }
            catch (Exception ex)
            {
                LogItem _oLog = MainForm.Instance.Log.Info("IFOparser");
                _oLog.LogValue("Error parsing ifo file " + FileName, ex.Message, ImageType.Error);
            }
            return(substreams);
        }