diff options
Diffstat (limited to 'win/C#/HandBrake.ApplicationServices/Utilities')
3 files changed, 1437 insertions, 0 deletions
diff --git a/win/C#/HandBrake.ApplicationServices/Utilities/PlistUtility.cs b/win/C#/HandBrake.ApplicationServices/Utilities/PlistUtility.cs new file mode 100644 index 000000000..c3dacb6d4 --- /dev/null +++ b/win/C#/HandBrake.ApplicationServices/Utilities/PlistUtility.cs @@ -0,0 +1,653 @@ +/* PlistPresetHandler.cs $
+ This file is part of the HandBrake source code.
+ Homepage: <http://handbrake.fr/>.
+ It may be used under the terms of the GNU General Public License. */
+
+namespace HandBrake.ApplicationServices.Utilities
+{
+ using System;
+ using System.Collections;
+ using System.IO;
+ using System.Text;
+ using System.Windows.Forms;
+ using System.Xml;
+
+ using HandBrake.ApplicationServices.Model;
+ using HandBrake.ApplicationServices.Model.Encoding;
+
+ /// <summary>
+ /// Plist Preset Converter
+ /// </summary>
+ public class PlistPresetHandler
+ {
+ /**
+ * TODO:
+ * - Update with the new vfr,pfr,cfr keys
+ * - Clean up this code, it's pretty nasty right now.
+ **/
+
+ #region Import
+
+ public static QueryParserUtility Import(string filename)
+ {
+ XmlNode root = loadFile(filename);
+ if (root == null) return null;
+
+ // We'll query a query parser object and use it's public var structures to store all the data.
+ // This will allow the preset loader logic to be used instead of writing custom logic just for this file.
+ QueryParserUtility queryParsed = new QueryParserUtility();
+ string qualityMode = string.Empty;
+
+ #region Get a List of Audio Track Objects
+ XmlNode audioListDict = root.ChildNodes[2].ChildNodes[0].FirstChild.ChildNodes[1];
+ ArrayList audioTracks = new ArrayList();
+
+ for (int i = 0; i < audioListDict.ChildNodes.Count; i++)
+ {
+ XmlNode audioChannel = audioListDict.ChildNodes[i];
+ AudioTrack track = new AudioTrack();
+
+ for (int subi = 0; subi < audioChannel.ChildNodes.Count; subi += 2)
+ {
+ // Audio Channel Information is here.
+ string key = audioChannel.ChildNodes[subi].InnerText;
+ string value = audioChannel.ChildNodes[subi + 1].InnerText;
+ switch (key)
+ {
+ case "AudioBitrate":
+ track.Bitrate = value;
+ break;
+ case "AudioEncoder":
+ track.Encoder = value.Replace("AAC (CoreAudio)", "AAC (faac)");
+ break;
+ case "AudioMixdown":
+ track.MixDown = value;
+ break;
+ case "AudioSamplerate":
+ track.SampleRate = value;
+ break;
+ case "AudioTrack":
+ track.Track = value;
+ break;
+ case "AudioTrackDRCSlider":
+ track.DRC = value;
+ break;
+ }
+ }
+ audioTracks.Add(track);
+ queryParsed.AudioInformation = audioTracks;
+ }
+ #endregion
+
+ #region Parse the reset of the plist keys into local variables
+
+ XmlNode presetSettings = root.ChildNodes[2].ChildNodes[0].FirstChild;
+
+ // Start from 2 to avoid the audio settings which we don't need.
+ for (int i = 2; i < presetSettings.ChildNodes.Count; i += 2)
+ {
+ string key = presetSettings.ChildNodes[i].InnerText;
+ string value = presetSettings.ChildNodes[i + 1].InnerText;
+
+ switch (key)
+ {
+ // Output Settings
+ case "FileFormat":
+ queryParsed.Format = value;
+ break;
+ case "Mp4HttpOptimize":
+ queryParsed.OptimizeMP4 = value == "1";
+ break;
+ case "Mp4LargeFile":
+ queryParsed.LargeMP4 = value == "1";
+ break;
+ case "Mp4iPodCompatible":
+ queryParsed.IpodAtom = value == "1";
+ break;
+
+ // Picture Settings
+ case "PictureAutoCrop":
+ // Not used
+ break;
+ case "PictureTopCrop":
+ queryParsed.CropTop = value;
+ break;
+ case "PictureBottomCrop":
+ queryParsed.CropBottom = value;
+ break;
+ case "PictureLeftCrop":
+ queryParsed.CropLeft = value;
+ break;
+ case "PictureRightCrop":
+ queryParsed.CropRight = value;
+ break;
+ case "PictureHeight":
+ queryParsed.Height = int.Parse(value);
+ break;
+ case "PictureWidth":
+ queryParsed.Width = int.Parse(value);
+ break;
+ case "PictureKeepRatio":
+ queryParsed.KeepDisplayAsect = value == "1";
+ break;
+ case "PicturePAR":
+ queryParsed.AnamorphicMode = int.Parse(value);
+ break;
+
+ // Filters
+ case "PictureDeblock":
+ queryParsed.DeBlock = int.Parse(value);
+ break;
+ case "PictureDecomb":
+ queryParsed.Decomb = "Off";
+ // Don't place custom here as it's handled in the filter panel
+ if (value == "2") queryParsed.Decomb = "Default";
+ break;
+ case "PictureDecombCustom":
+ if (value != string.Empty)
+ queryParsed.Decomb = value;
+ break;
+ case "PictureDecombDeinterlace":
+ // Not Used
+ break;
+ case "PictureDeinterlace":
+ switch (value)
+ {
+ case "0":
+ queryParsed.DeInterlace = "Off";
+ break;
+ // Don't place custom here as it's handled in the filter panel
+ case "2":
+ queryParsed.DeInterlace = "Fast";
+ break;
+ case "3":
+ queryParsed.DeInterlace = "Slow";
+ break;
+ case "4":
+ queryParsed.DeInterlace = "Slowest";
+ break;
+ }
+ break;
+ case "PictureDeinterlaceCustom":
+ if (value != string.Empty)
+ queryParsed.DeInterlace = value;
+ break;
+ case "PictureDenoise":
+ switch (value)
+ {
+ case "0":
+ queryParsed.DeNoise = "Off";
+ break;
+ // Don't place custom here as it's handled in the filter panel
+ case "2":
+ queryParsed.DeNoise = "Weak";
+ break;
+ case "3":
+ queryParsed.DeNoise = "Medium";
+ break;
+ case "4":
+ queryParsed.DeNoise = "Strong";
+ break;
+ }
+
+ break;
+ case "PictureDenoiseCustom":
+ if (value != string.Empty)
+ queryParsed.DeNoise = value;
+ break;
+ case "PictureDetelecine":
+ queryParsed.DeTelecine = "Off";
+ if (value == "1") queryParsed.DeTelecine = "Default";
+ break;
+ case "PictureDetelecineCustom":
+ if (value != string.Empty)
+ queryParsed.DeTelecine = value;
+ break;
+
+ // Video Tab
+ case "VideoAvgBitrate":
+ queryParsed.AverageVideoBitrate = value;
+ break;
+ case "VideoEncoder":
+ queryParsed.VideoEncoder = value;
+ break;
+ case "VideoFramerate":
+ queryParsed.VideoFramerate = value;
+ break;
+ case "VideoGrayScale":
+ queryParsed.Grayscale = value == "1";
+ break;
+ case "VideoQualitySlider":
+ queryParsed.VideoQuality = float.Parse(value);
+ break;
+ case "VideoQualityType": // The Type of Quality Mode used
+ qualityMode = value;
+ break;
+ case "VideoTargetSize":
+ queryParsed.VideoTargetSize = value;
+ break;
+ case "VideoTurboTwoPass":
+ queryParsed.TurboFirstPass = value == "1";
+ break;
+ case "VideoTwoPass":
+ queryParsed.TwoPass = value == "1";
+ break;
+
+ // Chapter Markers Tab
+ case "ChapterMarkers":
+ queryParsed.ChapterMarkers = value == "1";
+ break;
+
+ // Advanced x264 tab
+ case "x264Option":
+ queryParsed.H264Query = value;
+ break;
+
+ // Preset Information
+ case "PresetBuildNumber":
+ queryParsed.PresetBuildNumber = int.Parse(value);
+ break;
+ case "PresetDescription":
+ queryParsed.PresetDescription = value;
+ break;
+ case "PresetName":
+ queryParsed.PresetName = value;
+ break;
+ case "Type":
+ queryParsed.Type = value;
+ break;
+ case "UsesMaxPictureSettings":
+ queryParsed.UsesMaxPictureSettings = value == "1";
+ break;
+ case "UsesPictureFilters":
+ queryParsed.UsesPictureFilters = value == "1";
+ break;
+ case "UsesPictureSettings":
+ queryParsed.UsesPictureSettings = value == "1";
+ break;
+ }
+ }
+
+ // Kill any Quality values we don't need.
+ switch (qualityMode)
+ {
+ case "0": // FileSize
+ queryParsed.VideoQuality = -1;
+ queryParsed.AverageVideoBitrate = null;
+ break;
+ case "1": // Avg Bitrate
+ queryParsed.VideoQuality = -1;
+ queryParsed.VideoTargetSize = null;
+ break;
+ case "2": // CQ
+ queryParsed.AverageVideoBitrate = null;
+ queryParsed.VideoTargetSize = null;
+ break;
+ }
+ #endregion
+
+ return queryParsed;
+ }
+
+ private static XmlNode loadFile(string filename)
+ {
+ try
+ {
+ XmlNode root;
+
+ if (!File.Exists(filename))
+ return null;
+
+ StreamReader sr = File.OpenText(filename);
+ string fromfile = string.Empty;
+ int fileChar;
+ while ((fileChar = sr.Read()) != -1)
+ fromfile += Convert.ToChar(fileChar);
+
+ XmlDocument doc = new XmlDocument();
+ doc.LoadXml(fromfile);
+
+ root = doc;
+ if (!root.HasChildNodes)
+ {
+ MessageBox.Show(
+ "The Preset file you selected appears to be invlaid or from an older version of HandBrake",
+ "Error",
+ MessageBoxButtons.OK, MessageBoxIcon.Error);
+ return null;
+ }
+
+ return root;
+ }
+ catch (Exception)
+ {
+ MessageBox.Show(
+ "The Preset file you selected appears to be invlaid or from an older version of HandBrake.\n\n Please note, if you are exporting from the MacGui you may need to rebuild your preset so that it uses the current preset plist format.\n The MacGui does not currently update user presets automatically.",
+ "Error",
+ MessageBoxButtons.OK, MessageBoxIcon.Error);
+ return null;
+ }
+ }
+ #endregion
+
+ #region Export
+
+ /// <summary>
+ /// Export a MacGui style plist preset.
+ /// </summary>
+ /// <param name="path">
+ /// The path.
+ /// </param>
+ /// <param name="preset">
+ /// The preset.
+ /// </param>
+ public static void Export(string path, Preset preset)
+ {
+ QueryParserUtility parsed = QueryParserUtility.Parse(preset.Query);
+ XmlTextWriter xmlWriter = new XmlTextWriter(path, Encoding.UTF8) { Formatting = Formatting.Indented };
+
+ // Header
+ xmlWriter.WriteStartDocument();
+ xmlWriter.WriteDocType("plist", "-//Apple//DTD PLIST 1.0//EN",
+ @"http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);
+
+ xmlWriter.WriteStartElement("plist");
+ xmlWriter.WriteStartElement("array");
+
+ // Add New Preset Here. Can write multiple presets here if required in future.
+ WritePreset(xmlWriter, parsed, preset);
+
+ // Footer
+ xmlWriter.WriteEndElement();
+ xmlWriter.WriteEndElement();
+
+ xmlWriter.WriteEndDocument();
+
+ // Closeout
+ xmlWriter.Close();
+ }
+
+ /// <summary>
+ /// Write the Preset to a file
+ /// </summary>
+ /// <param name="xmlWriter">
+ /// The xml writer.
+ /// </param>
+ /// <param name="parsed">
+ /// The parsed.
+ /// </param>
+ /// <param name="preset">
+ /// The preset.
+ /// </param>
+ private static void WritePreset(XmlTextWriter xmlWriter, QueryParserUtility parsed, Preset preset)
+ {
+ xmlWriter.WriteStartElement("dict");
+ AudioListArrayDict(xmlWriter, parsed);
+ AddEncodeSettings(xmlWriter, parsed, preset);
+
+ xmlWriter.WriteEndElement();
+ }
+
+ /// <summary>
+ /// Add the encode settings to the preset
+ /// </summary>
+ /// <param name="xmlWriter">
+ /// The xml writer.
+ /// </param>
+ /// <param name="parsed">
+ /// The parsed.
+ /// </param>
+ /// <param name="preset">
+ /// The preset.
+ /// </param>
+ private static void AddEncodeSettings(XmlTextWriter xmlWriter, QueryParserUtility parsed, Preset preset)
+ {
+ AddEncodeElement(xmlWriter, "ChapterMarkers", "integer", parsed.ChapterMarkers ? "1" : "0");
+ AddEncodeElement(xmlWriter, "Default", "integer", "0");
+ AddEncodeElement(xmlWriter, "FileFormat", "string", parsed.Format.ToUpper() + " file");
+ AddBooleanElement(xmlWriter, "Folder", false);
+ AddEncodeElement(xmlWriter, "Mp4HttpOptimize", "integer", parsed.OptimizeMP4 ? "1" : "0");
+ AddEncodeElement(xmlWriter, "Mp4LargeFile", "integer", parsed.LargeMP4 ? "1" : "0");
+ AddEncodeElement(xmlWriter, "Mp4iPodCompatible", "integer", parsed.IpodAtom ? "1" : "0");
+ AddEncodeElement(xmlWriter, "PictureAutoCrop", "integer", "1");
+ AddEncodeElement(xmlWriter, "PictureBottomCrop", "integer", parsed.CropBottom);
+
+ // Filters
+ AddEncodeElement(xmlWriter, "PictureDeblock", "integer", parsed.DeBlock.ToString());
+
+ switch (parsed.Decomb)
+ {
+ case "Off":
+ AddEncodeElement(xmlWriter, "PictureDecomb", "integer", "0");
+ AddEncodeElement(xmlWriter, "PictureDecombCustom", "string", string.Empty);
+ break;
+ case "Default":
+ AddEncodeElement(xmlWriter, "PictureDecomb", "integer", "1");
+ AddEncodeElement(xmlWriter, "PictureDecombCustom", "string", string.Empty);
+ break;
+ default:
+ AddEncodeElement(xmlWriter, "PictureDecomb", "integer", "2");
+ AddEncodeElement(xmlWriter, "PictureDecombCustom", "string", parsed.Decomb);
+ break;
+ }
+ AddEncodeElement(xmlWriter, "PictureDecombDeinterlace", "integer", parsed.Decomb != "Off" ? "0" : "1");
+
+ switch (parsed.DeInterlace)
+ {
+ case "Off":
+ AddEncodeElement(xmlWriter, "PictureDeinterlace", "integer", "0");
+ AddEncodeElement(xmlWriter, "PictureDeinterlaceCustom", "string", string.Empty);
+ break;
+ case "Fast":
+ AddEncodeElement(xmlWriter, "PictureDeinterlace", "integer", "1");
+ AddEncodeElement(xmlWriter, "PictureDeinterlaceCustom", "string", string.Empty);
+ break;
+ case "Slow":
+ AddEncodeElement(xmlWriter, "PictureDeinterlace", "integer", "2");
+ AddEncodeElement(xmlWriter, "PictureDeinterlaceCustom", "string", string.Empty);
+ break;
+ case "Slower":
+ AddEncodeElement(xmlWriter, "PictureDeinterlace", "integer", "3");
+ AddEncodeElement(xmlWriter, "PictureDeinterlaceCustom", "string", string.Empty);
+ break;
+ default:
+ AddEncodeElement(xmlWriter, "PictureDeinterlace", "integer", "4");
+ AddEncodeElement(xmlWriter, "PictureDeinterlaceCustom", "string", parsed.DeInterlace);
+ break;
+ }
+
+ switch (parsed.DeNoise)
+ {
+ case "Off":
+ AddEncodeElement(xmlWriter, "PictureDenoise", "integer", "0");
+ AddEncodeElement(xmlWriter, "PictureDenoiseCustom", "string", string.Empty);
+ break;
+ case "Weak":
+ AddEncodeElement(xmlWriter, "PictureDenoise", "integer", "1");
+ AddEncodeElement(xmlWriter, "PictureDenoiseCustom", "string", string.Empty);
+ break;
+ case "Medium":
+ AddEncodeElement(xmlWriter, "PictureDenoise", "integer", "2");
+ AddEncodeElement(xmlWriter, "PictureDenoiseCustom", "string", string.Empty);
+ break;
+ case "Strong":
+ AddEncodeElement(xmlWriter, "PictureDenoise", "integer", "3");
+ AddEncodeElement(xmlWriter, "PictureDenoiseCustom", "string", string.Empty);
+ break;
+ default:
+ AddEncodeElement(xmlWriter, "PictureDenoise", "integer", "4");
+ AddEncodeElement(xmlWriter, "PictureDenoiseCustom", "string", parsed.DeNoise);
+ break;
+ }
+
+ int detelecine;
+ switch (parsed.DeTelecine)
+ {
+ case "Off":
+ detelecine = 0;
+ break;
+ case "Default":
+ detelecine = 2;
+ break;
+ default:
+ detelecine = 1;
+ break;
+ }
+
+ AddEncodeElement(xmlWriter, "PictureDetelecine", "integer", detelecine.ToString());
+ AddEncodeElement(xmlWriter, "PictureDetelecineCustom", "string", detelecine == 1 ? parsed.DeTelecine : string.Empty);
+
+ // Picture Settings
+ AddEncodeElement(xmlWriter, "PictureHeight", "integer", parsed.Height.ToString());
+ AddEncodeElement(xmlWriter, "PictureKeepRatio", "integer", parsed.KeepDisplayAsect ? "1" : "0");
+ AddEncodeElement(xmlWriter, "PictureLeftCrop", "integer", parsed.CropLeft);
+ AddEncodeElement(xmlWriter, "PictureModulus", "integer", parsed.AnamorphicModulus.ToString());
+ AddEncodeElement(xmlWriter, "PicturePAR", "integer", parsed.AnamorphicMode.ToString());
+ AddEncodeElement(xmlWriter, "PictureRightCrop", "integer", parsed.CropRight);
+ AddEncodeElement(xmlWriter, "PictureTopCrop", "integer", parsed.CropTop);
+ AddEncodeElement(xmlWriter, "PictureWidth", "integer", parsed.Width.ToString());
+
+ // Preset Information
+ AddEncodeElement(xmlWriter, "PresetBuildNumber", "string", Init.Build.ToString());
+ AddEncodeElement(xmlWriter, "PresetDescription", "string", "No Description");
+ AddEncodeElement(xmlWriter, "PresetName", "string", preset.Name);
+ AddEncodeElement(xmlWriter, "Type", "integer", "1"); // 1 is user preset, 0 is built in
+
+ // Preset Settings
+ AddEncodeElement(xmlWriter, "UsesMaxPictureSettings", "integer", (parsed.MaxWidth != 0 || parsed.MaxHeight != 0) ? "1" : "0");
+ AddEncodeElement(xmlWriter, "UsesPictureFilters", "integer", "1");
+ AddEncodeElement(xmlWriter, "UsesPictureSettings", "integer", "2");
+
+ // Video Settings
+ AddEncodeElement(xmlWriter, "VideoAvgBitrate", "string", parsed.AverageVideoBitrate);
+ AddEncodeElement(xmlWriter, "VideoEncoder", "string", parsed.VideoEncoder);
+ AddEncodeElement(xmlWriter, "VideoFramerate", "string", parsed.VideoFramerate);
+ AddEncodeElement(xmlWriter, "VideFrameratePFR", "integer", parsed.Pfr ? "1" : "0");
+ AddEncodeElement(xmlWriter, "VideoGrayScale", "integer", parsed.Grayscale ? "1" : "0");
+ AddEncodeElement(xmlWriter, "VideoQualitySlider", "real", parsed.VideoQuality.ToString());
+
+ int videoQualityType = 0;
+ if (!string.IsNullOrEmpty(parsed.VideoTargetSize)) videoQualityType = 0;
+ else if (!string.IsNullOrEmpty(parsed.AverageVideoBitrate)) videoQualityType = 1;
+ else if (parsed.VideoQuality != 0) videoQualityType = 2;
+
+ AddEncodeElement(xmlWriter, "VideoQualityType", "integer", videoQualityType.ToString());
+ AddEncodeElement(xmlWriter, "VideoTargetSize", "string", parsed.VideoTargetSize);
+ AddEncodeElement(xmlWriter, "VideoTurboTwoPass", "integer", parsed.TurboFirstPass ? "1" : "0");
+ AddEncodeElement(xmlWriter, "VideoTwoPass", "integer", parsed.TwoPass ? "1" : "0");
+
+ // x264 string
+ AddEncodeElement(xmlWriter, "x264Option", "string", parsed.H264Query);
+ }
+
+ /// <summary>
+ /// Add a boolean element
+ /// </summary>
+ /// <param name="xmlWriter">
+ /// The xml writer.
+ /// </param>
+ /// <param name="keyName">
+ /// The key name.
+ /// </param>
+ /// <param name="value">
+ /// The value.
+ /// </param>
+ private static void AddBooleanElement(XmlTextWriter xmlWriter, string keyName, bool value)
+ {
+ xmlWriter.WriteStartElement("key");
+ xmlWriter.WriteString(keyName);
+ xmlWriter.WriteEndElement();
+ xmlWriter.WriteStartElement(value ? "true" : "false");
+ xmlWriter.WriteEndElement();
+ }
+
+ /// <summary>
+ /// Add an encode setting element
+ /// </summary>
+ /// <param name="xmlWriter">
+ /// The xml writer.
+ /// </param>
+ /// <param name="keyName">
+ /// The key name.
+ /// </param>
+ /// <param name="type">
+ /// The type.
+ /// </param>
+ /// <param name="value">
+ /// The value.
+ /// </param>
+ private static void AddEncodeElement(XmlTextWriter xmlWriter, string keyName, string type, string value)
+ {
+ xmlWriter.WriteElementString("key", keyName);
+
+ // This is a hack for Apples XML parser. It doesn't understand <integer /> so instead, always set a default value
+ // of 0 if the value is empty.
+ if (type == "integer" && string.IsNullOrEmpty(value))
+ {
+ value = "0";
+ }
+ xmlWriter.WriteElementString(type, value);
+ }
+
+ /// <summary>
+ /// Add an Audio Track Array Dict
+ /// </summary>
+ /// <param name="xmlWriter">
+ /// The xml writer.
+ /// </param>
+ /// <param name="parsed">
+ /// The parsed.
+ /// </param>
+ private static void AudioListArrayDict(XmlTextWriter xmlWriter, QueryParserUtility parsed)
+ {
+ xmlWriter.WriteStartElement("key");
+ xmlWriter.WriteString("AudioList");
+ xmlWriter.WriteEndElement();
+
+ xmlWriter.WriteStartElement("array");
+ foreach (AudioTrack track in parsed.AudioInformation)
+ {
+ AddAudioItem(xmlWriter, track);
+ }
+ xmlWriter.WriteEndElement();
+ }
+
+ /// <summary>
+ /// Add an audio track
+ /// </summary>
+ /// <param name="xmlWriter">
+ /// The xml writer.
+ /// </param>
+ /// <param name="audioTrack">
+ /// The audio track.
+ /// </param>
+ private static void AddAudioItem(XmlTextWriter xmlWriter, AudioTrack audioTrack)
+ {
+ xmlWriter.WriteStartElement("dict");
+
+ xmlWriter.WriteElementString("key", "AudioBitrate");
+ xmlWriter.WriteElementString("string", audioTrack.Bitrate);
+
+ xmlWriter.WriteElementString("key", "AudioEncoder");
+ xmlWriter.WriteElementString("string", audioTrack.Encoder);
+
+ xmlWriter.WriteElementString("key", "AudioMixdown");
+ xmlWriter.WriteElementString("string", audioTrack.MixDown);
+
+ xmlWriter.WriteElementString("key", "AudioSamplerate");
+ xmlWriter.WriteElementString("string", audioTrack.SampleRate);
+
+ xmlWriter.WriteElementString("key", "AudioTrack");
+ xmlWriter.WriteElementString("integer", audioTrack.Track);
+
+ xmlWriter.WriteElementString("key", "AudioTrackDRCSlider");
+ xmlWriter.WriteElementString("real", audioTrack.DRC);
+
+ xmlWriter.WriteElementString("key", "AudioTrackDescription");
+ xmlWriter.WriteElementString("string", "Unknown");
+
+ xmlWriter.WriteEndElement();
+ }
+ #endregion
+ }
+}
\ No newline at end of file diff --git a/win/C#/HandBrake.ApplicationServices/Utilities/QueryParserUtility.cs b/win/C#/HandBrake.ApplicationServices/Utilities/QueryParserUtility.cs new file mode 100644 index 000000000..9f5f93d24 --- /dev/null +++ b/win/C#/HandBrake.ApplicationServices/Utilities/QueryParserUtility.cs @@ -0,0 +1,653 @@ +/* QueryParser.cs $
+ This file is part of the HandBrake source code.
+ Homepage: <http://handbrake.fr>.
+ It may be used under the terms of the GNU General Public License. */
+
+namespace HandBrake.ApplicationServices.Utilities
+{
+ using System;
+ using System.Collections;
+ using System.Globalization;
+ using System.Text.RegularExpressions;
+
+ using HandBrake.ApplicationServices.Functions;
+ using HandBrake.ApplicationServices.Model.Encoding;
+
+ /// <summary>
+ /// Parse a CLI Query
+ /// </summary>
+ public class QueryParserUtility
+ {
+ /// <summary>
+ /// The Culture
+ /// </summary>
+ private static readonly CultureInfo Culture = new CultureInfo("en-US", false);
+
+ #region Varibles
+
+ #region Source Title / Chapters
+ /// <summary>
+ /// Gets or sets Title.
+ /// </summary>
+ public int Title { get; set; }
+
+ /// <summary>
+ /// Gets or sets ChapterStart.
+ /// </summary>
+ public int ChapterStart { get; set; }
+
+ /// <summary>
+ /// Gets or sets ChapterFinish.
+ /// </summary>
+ public int ChapterFinish { get; set; }
+ #endregion
+
+ #region Output Settings
+ /// <summary>
+ /// Gets or sets the file Format. e.g mkv or mp4
+ /// </summary>
+ public string Format { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether LargeMP4 support is enabled.
+ /// This is the 64bit MP4 file that allows >4GB files
+ /// </summary>
+ public bool LargeMP4 { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IpodAtom is inserted
+ /// </summary>
+ public bool IpodAtom { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether OptimizeMP4 is enabed for web streaming
+ /// </summary>
+ public bool OptimizeMP4 { get; set; }
+ #endregion
+
+ #region Picture Settings
+
+ /// <summary>
+ /// Gets or sets Width.
+ /// </summary>
+ public int Width { get; set; }
+
+ /// <summary>
+ /// Gets or sets Height.
+ /// </summary>
+ public int Height { get; set; }
+
+ /// <summary>
+ /// Gets or sets MaxWidth.
+ /// </summary>
+ public int MaxWidth { get; set; }
+
+ /// <summary>
+ /// Gets or sets MaxHeight.
+ /// </summary>
+ public int MaxHeight { get; set; }
+
+ /// <summary>
+ /// Gets or sets CropValues.
+ /// </summary>
+ public string CropValues { get; set; }
+
+ /// <summary>
+ /// Gets or sets CropTop.
+ /// </summary>
+ public string CropTop { get; set; }
+
+ /// <summary>
+ /// Gets or sets CropBottom.
+ /// </summary>
+ public string CropBottom { get; set; }
+
+ /// <summary>
+ /// Gets or sets CropLeft.
+ /// </summary>
+ public string CropLeft { get; set; }
+
+ /// <summary>
+ /// Gets or sets CropRight.
+ /// </summary>
+ public string CropRight { get; set; }
+
+ /// <summary>
+ /// Gets or sets AnamorphicMode.
+ /// </summary>
+ public int AnamorphicMode { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether KeepDisplayAsect.
+ /// </summary>
+ public bool KeepDisplayAsect { get; set; }
+
+ /// <summary>
+ /// Gets or sets DisplayWidthValue.
+ /// </summary>
+ public double DisplayWidthValue { get; set; }
+
+ /// <summary>
+ /// Gets or sets PixelAspectWidth.
+ /// </summary>
+ public int PixelAspectWidth { get; set; }
+
+ /// <summary>
+ /// Gets or sets PixelAspectHeight.
+ /// </summary>
+ public int PixelAspectHeight { get; set; }
+
+ /// <summary>
+ /// Gets or sets AnamorphicModulus.
+ /// </summary>
+ public int AnamorphicModulus { get; set; }
+ #endregion
+
+ #region Video Filters
+
+ /// <summary>
+ /// Gets or sets DeTelecine.
+ /// </summary>
+ public string DeTelecine { get; set; }
+
+ /// <summary>
+ /// Gets or sets DeBlock.
+ /// </summary>
+ public int DeBlock { get; set; }
+
+ /// <summary>
+ /// Gets or sets DeInterlace.
+ /// </summary>
+ public string DeInterlace { get; set; }
+
+ /// <summary>
+ /// Gets or sets DeNoise.
+ /// </summary>
+ public string DeNoise { get; set; }
+
+ /// <summary>
+ /// Gets or sets Decomb.
+ /// </summary>
+ public string Decomb { get; set; }
+ #endregion
+
+ #region Video Settings
+ /// <summary>
+ /// Gets or sets VideoEncoder.
+ /// </summary>
+ public string VideoEncoder { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Grayscale.
+ /// </summary>
+ public bool Grayscale { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether TwoPass.
+ /// </summary>
+ public bool TwoPass { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether TurboFirstPass.
+ /// </summary>
+ public bool TurboFirstPass { get; set; }
+
+ /// <summary>
+ /// Gets or sets VideoFramerate.
+ /// </summary>
+ public string VideoFramerate { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Pfr.
+ /// </summary>
+ public bool Pfr { get; set; }
+
+ /// <summary>
+ /// Gets or sets AverageVideoBitrate.
+ /// </summary>
+ public string AverageVideoBitrate { get; set; }
+
+ /// <summary>
+ /// Gets or sets VideoTargetSize.
+ /// </summary>
+ public string VideoTargetSize { get; set; }
+
+ /// <summary>
+ /// Gets or sets VideoQuality.
+ /// </summary>
+ public float VideoQuality { get; set; }
+ #endregion
+
+ #region Audio Settings
+
+ /// <summary>
+ /// Gets or sets AudioInformation.
+ /// </summary>
+ public ArrayList AudioInformation { get; set; }
+
+ /// <summary>
+ /// Gets or sets Subtitles.
+ /// </summary>
+ public string Subtitles { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether ForcedSubtitles.
+ /// </summary>
+ public bool ForcedSubtitles { get; set; }
+ #endregion
+
+ #region Other
+ /// <summary>
+ /// Gets or sets a value indicating whether ChapterMarkers.
+ /// </summary>
+ public bool ChapterMarkers { get; set; }
+
+ /// <summary>
+ /// Gets or sets H264Query.
+ /// </summary>
+ public string H264Query { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Verbose.
+ /// </summary>
+ public bool Verbose { get; set; }
+ #endregion
+
+ #region Preset Information
+
+ /// <summary>
+ /// Gets or sets PresetBuildNumber.
+ /// </summary>
+ public int PresetBuildNumber { get; set; }
+
+ /// <summary>
+ /// Gets or sets PresetDescription.
+ /// </summary>
+ public string PresetDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets PresetName.
+ /// </summary>
+ public string PresetName { get; set; }
+
+ /// <summary>
+ /// Gets or sets Type.
+ /// </summary>
+ public string Type { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether UsesMaxPictureSettings.
+ /// </summary>
+ public bool UsesMaxPictureSettings { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether UsesPictureFilters.
+ /// </summary>
+ public bool UsesPictureFilters { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether UsesPictureSettings.
+ /// </summary>
+ public bool UsesPictureSettings { get; set; }
+ #endregion
+
+ #endregion
+
+ /// <summary>
+ /// Takes in a query which can be in any order and parses it.
+ /// All varibles are then set so they can be used elsewhere.
+ /// </summary>
+ /// <param name="input">A ClI Query</param>
+ /// <returns>A Parsed Query</returns>
+ public static QueryParserUtility Parse(string input)
+ {
+ var thisQuery = new QueryParserUtility();
+
+ #region Regular Expressions
+
+ // Source
+ Match title = Regex.Match(input, @"-t ([0-9]*)");
+ Match chapters = Regex.Match(input, @"-c ([0-9-]*)");
+
+ // Output Settings
+ Match format = Regex.Match(input, @"-f ([a-z0-9a-z0-9a-z0-9]*)");
+ Match grayscale = Regex.Match(input, @" -g");
+ Match largerMp4 = Regex.Match(input, @" -4");
+ Match ipodAtom = Regex.Match(input, @" -I");
+
+ // Picture Settings Tab
+ Match width = Regex.Match(input, @"-w ([0-9]*)");
+ Match height = Regex.Match(input, @"-l ([0-9]*)");
+ Match maxWidth = Regex.Match(input, @"-X ([0-9]*)");
+ Match maxHeight = Regex.Match(input, @"-Y ([0-9]*)");
+ Match crop = Regex.Match(input, @"--crop ([0-9]*):([0-9]*):([0-9]*):([0-9]*)");
+
+ Match looseAnamorphic = Regex.Match(input, @"--loose-anamorphic");
+ Match strictAnamorphic = Regex.Match(input, @"--strict-anamorphic");
+ Match customAnamorphic = Regex.Match(input, @"--custom-anamorphic");
+
+ Match keepDisplayAsect = Regex.Match(input, @"--keep-display-aspect");
+ Match displayWidth = Regex.Match(input, @"--display-width ([0-9]*)");
+ Match pixelAspect = Regex.Match(input, @"--pixel-aspect ([0-9]*):([0-9]*)");
+ Match modulus = Regex.Match(input, @"--modulus ([0-9]*)");
+
+ // Picture Settings - Filters
+ Match decomb = Regex.Match(input, @" --decomb");
+ Match decombValue = Regex.Match(input, @" --decomb=\""([a-zA-Z0-9.:]*)\""");
+ Match deinterlace = Regex.Match(input, @"--deinterlace=\""([a-zA-Z0-9.:]*)\""");
+ Match denoise = Regex.Match(input, @"--denoise=\""([a-zA-Z0-9.:]*)\""");
+ Match deblock = Regex.Match(input, @"--deblock=([0-9:]*)");
+ Match detelecine = Regex.Match(input, @"--detelecine");
+ Match detelecineValue = Regex.Match(input, @" --detelecine=\""([a-zA-Z0-9.:]*)\""");
+
+ // Video Settings Tab
+ Match videoEncoder = Regex.Match(input, @"-e ([a-zA-Z0-9]*)");
+ Match videoFramerate = Regex.Match(input, @"-r ([0-9.]*)");
+ Match videoBitrate = Regex.Match(input, @"-b ([0-9]*)");
+ Match videoQuality = Regex.Match(input, @"-q ([0-9.]*)");
+ Match videoFilesize = Regex.Match(input, @"-S ([0-9.]*)");
+ Match twoPass = Regex.Match(input, @" -2");
+ Match turboFirstPass = Regex.Match(input, @" -T");
+ Match optimizeMP4 = Regex.Match(input, @" -O");
+ Match pfr = Regex.Match(input, @" --pfr");
+
+ // Audio Settings Tab
+ Match noAudio = Regex.Match(input, @"-a none");
+ Match audioTracks = Regex.Match(input, @"-a ([0-9,]*)");
+ Match audioTrackMixes = Regex.Match(input, @"-6 ([0-9a-zA-Z,]*)");
+ Match audioEncoders = Regex.Match(input, @"-E ([a-zA-Z0-9+,:]*)");
+ Match audioBitrates = Regex.Match(input, @"-B ([0-9a-zA-Z,]*)"); // Auto = a-z
+ Match audioSampleRates = Regex.Match(input, @"-R ([0-9a-zA-Z.,]*)"); // Auto = a-z
+ Match drcValues = Regex.Match(input, @"-D ([0-9.,]*)");
+
+ Match subtitles = Regex.Match(input, @"-s ([0-9a-zA-Z]*)");
+ Match subScan = Regex.Match(input, @" -U");
+ Match forcedSubtitles = Regex.Match(input, @" -F");
+
+ // Chapters Tab
+ Match chapterMarkers = Regex.Match(input, @" -m");
+ Match chapterMarkersFileMode = Regex.Match(input, @"--markers");
+
+ // H264 Tab
+ Match x264 = Regex.Match(input, @"-x ([.,/a-zA-Z0-9=:-]*)");
+
+ // Program Options
+ Match verbose = Regex.Match(input, @" -v");
+
+ #endregion
+
+ #region Set Varibles
+
+ try
+ {
+ #region Source Tab
+
+ if (title.Success)
+ thisQuery.Title = int.Parse(title.ToString().Replace("-t ", string.Empty));
+
+ if (chapters.Success)
+ {
+ string[] actTitles = chapters.ToString().Replace("-c ", string.Empty).Split('-');
+ thisQuery.ChapterStart = int.Parse(actTitles[0]);
+ if (actTitles.Length > 1)
+ {
+ thisQuery.ChapterFinish = int.Parse(actTitles[1]);
+ }
+
+ if ((thisQuery.ChapterStart == 1) && (thisQuery.ChapterFinish == 0))
+ thisQuery.ChapterFinish = thisQuery.ChapterStart;
+ }
+
+ #endregion
+
+ #region Output Settings
+
+ if (format.Success)
+ thisQuery.Format = format.ToString().Replace("-f ", string.Empty);
+ thisQuery.LargeMP4 = largerMp4.Success;
+ thisQuery.IpodAtom = ipodAtom.Success;
+ thisQuery.OptimizeMP4 = optimizeMP4.Success;
+
+ #endregion
+
+ #region Picture Tab
+
+ if (width.Success)
+ thisQuery.Width = int.Parse(width.Groups[0].Value.Replace("-w ", string.Empty));
+
+ if (height.Success)
+ thisQuery.Height = int.Parse(height.Groups[0].Value.Replace("-l ", string.Empty));
+
+ if (maxWidth.Success)
+ thisQuery.MaxWidth = int.Parse(maxWidth.Groups[0].Value.Replace("-X ", string.Empty));
+
+ if (maxHeight.Success)
+ thisQuery.MaxHeight = int.Parse(maxHeight.Groups[0].Value.Replace("-Y ", string.Empty));
+
+ if (crop.Success)
+ {
+ thisQuery.CropValues = crop.ToString().Replace("--crop ", string.Empty);
+ string[] actCropValues = thisQuery.CropValues.Split(':');
+ thisQuery.CropTop = actCropValues[0];
+ thisQuery.CropBottom = actCropValues[1];
+ thisQuery.CropLeft = actCropValues[2];
+ thisQuery.CropRight = actCropValues[3];
+ }
+
+ if (strictAnamorphic.Success)
+ thisQuery.AnamorphicMode = 1;
+ else if (looseAnamorphic.Success)
+ thisQuery.AnamorphicMode = 2;
+ else if (customAnamorphic.Success)
+ thisQuery.AnamorphicMode = 3;
+ else
+ thisQuery.AnamorphicMode = 0;
+
+ thisQuery.KeepDisplayAsect = keepDisplayAsect.Success;
+
+ if (displayWidth.Success)
+ thisQuery.DisplayWidthValue =
+ double.Parse(displayWidth.Groups[0].Value.Replace("--display-width ", string.Empty));
+
+ if (pixelAspect.Success)
+ thisQuery.PixelAspectWidth = int.Parse(pixelAspect.Groups[1].Value.Replace("--pixel-aspect ", string.Empty));
+
+ if (pixelAspect.Success && pixelAspect.Groups.Count >= 3)
+ thisQuery.PixelAspectHeight = int.Parse(pixelAspect.Groups[2].Value.Replace("--pixel-aspect ", string.Empty));
+
+ if (modulus.Success)
+ thisQuery.AnamorphicModulus = int.Parse(modulus.Groups[0].Value.Replace("--modulus ", string.Empty));
+
+ #endregion
+
+ #region Filters
+
+ thisQuery.Decomb = "Off";
+ if (decomb.Success)
+ {
+ thisQuery.Decomb = "Default";
+ if (decombValue.Success)
+ thisQuery.Decomb = decombValue.ToString().Replace("--decomb=", string.Empty).Replace("\"", string.Empty);
+ }
+
+ thisQuery.DeInterlace = "Off";
+ if (deinterlace.Success)
+ {
+ thisQuery.DeInterlace = deinterlace.ToString().Replace("--deinterlace=", string.Empty).Replace("\"", string.Empty);
+ thisQuery.DeInterlace =
+ thisQuery.DeInterlace.Replace("fast", "Fast").Replace("slow", "Slow").Replace("slower", "Slower");
+ thisQuery.DeInterlace = thisQuery.DeInterlace.Replace("slowest", "Slowest");
+ }
+
+ thisQuery.DeNoise = "Off";
+ if (denoise.Success)
+ {
+ thisQuery.DeNoise = denoise.ToString().Replace("--denoise=", string.Empty).Replace("\"", string.Empty);
+ thisQuery.DeNoise =
+ thisQuery.DeNoise.Replace("weak", "Weak").Replace("medium", "Medium").Replace("strong", "Strong");
+ }
+
+ string deblockValue = string.Empty;
+ thisQuery.DeBlock = 0;
+ if (deblock.Success)
+ deblockValue = deblock.ToString().Replace("--deblock=", string.Empty);
+
+ int dval = 0;
+ if (deblockValue != string.Empty)
+ int.TryParse(deblockValue, out dval);
+ thisQuery.DeBlock = dval;
+
+ thisQuery.DeTelecine = "Off";
+ if (detelecine.Success)
+ {
+ thisQuery.DeTelecine = "Default";
+ if (detelecineValue.Success)
+ thisQuery.DeTelecine = detelecineValue.ToString().Replace("--detelecine=", string.Empty).Replace("\"", string.Empty);
+ }
+
+ #endregion
+
+ #region Video Settings Tab
+
+ string videoEncoderConvertion = videoEncoder.ToString().Replace("-e ", string.Empty);
+ switch (videoEncoderConvertion)
+ {
+ case "ffmpeg":
+ videoEncoderConvertion = "MPEG-4 (FFmpeg)";
+ break;
+ case "x264":
+ videoEncoderConvertion = "H.264 (x264)";
+ break;
+ case "theora":
+ videoEncoderConvertion = "VP3 (Theora)";
+ break;
+ default:
+ videoEncoderConvertion = "MPEG-4 (FFmpeg)";
+ break;
+ }
+ thisQuery.VideoEncoder = videoEncoderConvertion;
+ thisQuery.VideoFramerate = videoFramerate.Success
+ ? videoFramerate.ToString().Replace("-r ", string.Empty)
+ : "Same as source";
+
+ thisQuery.Pfr = pfr.Success;
+ thisQuery.Grayscale = grayscale.Success;
+ thisQuery.TwoPass = twoPass.Success;
+ thisQuery.TurboFirstPass = turboFirstPass.Success;
+
+ if (videoBitrate.Success)
+ thisQuery.AverageVideoBitrate = videoBitrate.ToString().Replace("-b ", string.Empty);
+ if (videoFilesize.Success)
+ thisQuery.VideoTargetSize = videoFilesize.ToString().Replace("-S ", string.Empty);
+
+ if (videoQuality.Success)
+ {
+ float qConvert = float.Parse(videoQuality.ToString().Replace("-q ", string.Empty), Culture);
+ thisQuery.VideoQuality = qConvert;
+ }
+ else
+ thisQuery.VideoQuality = -1;
+
+ #endregion
+
+ #region Audio Tab
+
+ // Find out how many tracks we need to add by checking how many encoders or audio tracks are selected.
+ int encoderCount = 0;
+ if (audioEncoders.Success)
+ {
+ string[] audioDataCounters = audioEncoders.ToString().Replace("-E ", string.Empty).Split(',');
+ encoderCount = audioDataCounters.Length;
+ }
+
+ // Get the data from the regular expression results
+ string[] trackData = null;
+ string[] trackMixes = null;
+ string[] trackEncoders = null;
+ string[] trackBitrates = null;
+ string[] trackSamplerates = null;
+ string[] trackDRCvalues = null;
+
+ if (audioTracks.Success)
+ trackData = audioTracks.ToString().Replace("-a ", string.Empty).Split(',');
+ if (audioTrackMixes.Success)
+ trackMixes = audioTrackMixes.ToString().Replace("-6 ", string.Empty).Split(',');
+ if (audioEncoders.Success)
+ trackEncoders = audioEncoders.ToString().Replace("-E ", string.Empty).Split(',');
+ if (audioBitrates.Success)
+ trackBitrates = audioBitrates.ToString().Replace("-B ", string.Empty).Split(',');
+ if (audioSampleRates.Success)
+ trackSamplerates = audioSampleRates.ToString().Replace("-R ", string.Empty).Split(',');
+ if (drcValues.Success)
+ trackDRCvalues = drcValues.ToString().Replace("-D ", string.Empty).Split(',');
+
+ // Create new Audio Track Classes and store them in the ArrayList
+ ArrayList allAudioTrackInfo = new ArrayList();
+ for (int x = 0; x < encoderCount; x++)
+ {
+ AudioTrack track = new AudioTrack();
+ if (trackData != null)
+ if (trackData.Length >= (x + 1)) // Audio Track
+ track.Track = trackData[x].Trim();
+
+ if (trackMixes != null)
+ if (trackMixes.Length >= (x + 1)) // Audio Mix
+ track.MixDown = Converters.GetMixDown(trackMixes[x].Trim());
+
+ if (trackEncoders != null)
+ if (trackEncoders.Length >= (x + 1)) // Audio Mix
+ track.Encoder = Converters.GetAudioEncoder(trackEncoders[x].Trim());
+
+ if (trackBitrates != null)
+ if (trackBitrates.Length >= (x + 1)) // Audio Encoder
+ track.Bitrate = trackBitrates[x].Trim() == "auto" ? "Auto" : trackBitrates[x].Trim();
+
+ if (trackSamplerates != null)
+ if (trackSamplerates.Length >= (x + 1)) // Audio SampleRate
+ track.SampleRate = trackSamplerates[x].Trim() == "0" ? "Auto" : trackSamplerates[x].Trim();
+
+ if (trackDRCvalues != null)
+ if (trackDRCvalues.Length >= (x + 1)) // Audio DRC Values
+ track.DRC = trackDRCvalues[x].Trim();
+
+ allAudioTrackInfo.Add(track);
+ }
+ thisQuery.AudioInformation = allAudioTrackInfo;
+
+ // Subtitle Stuff
+ if (subtitles.Success)
+ thisQuery.Subtitles = subtitles.ToString().Replace("-s ", string.Empty);
+ else
+ thisQuery.Subtitles = subScan.Success ? "Autoselect" : "None";
+
+ thisQuery.ForcedSubtitles = forcedSubtitles.Success;
+
+ #endregion
+
+ #region Chapters Tab
+
+ if (chapterMarkersFileMode.Success || chapterMarkers.Success)
+ thisQuery.ChapterMarkers = true;
+
+ #endregion
+
+ #region H.264 and other
+
+ if (x264.Success)
+ thisQuery.H264Query = x264.ToString().Replace("-x ", string.Empty);
+
+ thisQuery.Verbose = verbose.Success;
+
+ #endregion
+ }
+ catch (Exception exc)
+ {
+ throw new Exception("An error has occured in the QueryParser Utility.", exc);
+ }
+
+ #endregion
+
+ return thisQuery;
+ }
+ }
+}
\ No newline at end of file diff --git a/win/C#/HandBrake.ApplicationServices/Utilities/UtilityService.cs b/win/C#/HandBrake.ApplicationServices/Utilities/UtilityService.cs new file mode 100644 index 000000000..b705cb8e1 --- /dev/null +++ b/win/C#/HandBrake.ApplicationServices/Utilities/UtilityService.cs @@ -0,0 +1,131 @@ +/* UtilityService.cs $
+ This file is part of the HandBrake source code.
+ Homepage: <http://handbrake.fr>.
+ It may be used under the terms of the GNU General Public License. */
+
+namespace HandBrake.ApplicationServices.Services
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.IO;
+ using System.Text;
+ using System.Windows.Forms;
+
+ using HandBrake.ApplicationServices.Functions;
+ using HandBrake.ApplicationServices.Model;
+
+ /// <summary>
+ /// A Set of Static Utilites
+ /// </summary>
+ public class UtilityService
+ {
+ /// <summary>
+ /// The Default Log Directory
+ /// </summary>
+ private static readonly string LogDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
+
+ /// <summary>
+ /// Clear all the log files older than 30 Days
+ /// </summary>
+ /// <param name="daysToKeep">
+ /// The Number of Days to Keep
+ /// </param>
+ public static void ClearLogFiles(int daysToKeep)
+ {
+ if (Directory.Exists(LogDir))
+ {
+ // Get all the log files
+ DirectoryInfo info = new DirectoryInfo(LogDir);
+ FileInfo[] logFiles = info.GetFiles("*.txt");
+
+ // Delete Them
+ foreach (FileInfo file in logFiles)
+ {
+ if (file.LastWriteTime < DateTime.Now.AddDays(-daysToKeep))
+ {
+ if (!file.Name.Contains("last_scan_log.txt") && !file.Name.Contains("last_encode_log.txt"))
+ {
+ File.Delete(file.FullName);
+ }
+ else if (file.Length > 104857600)
+ {
+ File.Delete(file.FullName);
+ }
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Get a list of available DVD drives which are ready and contain DVD content.
+ /// </summary>
+ /// <returns>A List of Drives with their details</returns>
+ public static List<DriveInformation> GetDrives()
+ {
+ List<DriveInformation> drives = new List<DriveInformation>();
+ DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();
+ int id = 0;
+ foreach (DriveInfo curDrive in theCollectionOfDrives)
+ {
+ if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady)
+ {
+ if (Directory.Exists(curDrive.RootDirectory + "VIDEO_TS") || Directory.Exists(curDrive.RootDirectory + "BDMV"))
+ {
+ drives.Add(
+ new DriveInformation
+ {
+ Id = id,
+ VolumeLabel = curDrive.VolumeLabel,
+ RootDirectory = curDrive.RootDirectory.ToString()
+ });
+ id++;
+ }
+ }
+ }
+
+ return drives;
+ }
+
+ /// <summary>
+ /// Get the Process ID of HandBrakeCLI for the current instance.
+ /// </summary>
+ /// <returns>A list of processes</returns>
+ public static Process[] GetCliProcess()
+ {
+ return Process.GetProcessesByName("HandBrakeCLI");
+ }
+
+ /// <summary>
+ /// Add the CLI Query to the Log File.
+ /// </summary>
+ /// <param name="encJob">
+ /// The Encode Job Object
+ /// </param>
+ /// <returns>
+ /// The create cli log header.
+ /// </returns>
+ public static string CreateCliLogHeader(QueueTask encJob)
+ {
+ StringBuilder logHeader = new StringBuilder();
+
+ logHeader.AppendLine(String.Format("# {0}", Init.HandBrakeGuiVersionString));
+ logHeader.AppendLine(String.Format("# Running: {0}", Environment.OSVersion));
+ logHeader.AppendLine(String.Format("# CPU: {0}", SystemInfo.GetCpuCount));
+ logHeader.AppendLine(String.Format("# Ram: {0} MB", SystemInfo.TotalPhysicalMemory));
+ logHeader.AppendLine(String.Format("# Screen: {0}x{1}", SystemInfo.ScreenBounds.Bounds.Width, SystemInfo.ScreenBounds.Bounds.Height));
+ logHeader.AppendLine(String.Format("# Temp Dir: {0}", Path.GetTempPath()));
+ logHeader.AppendLine(String.Format("# Install Dir: {0}", Application.StartupPath));
+ logHeader.AppendLine(String.Format("# Data Dir: {0}\n", Application.UserAppDataPath));
+
+ if (encJob != null)
+ {
+ logHeader.AppendLine(String.Format("# CLI Query: {0}", encJob.Query));
+ logHeader.AppendLine(String.Format("# User Query: {0}", encJob.CustomQuery));
+ }
+ logHeader.AppendLine("-------------------------------------------");
+
+ return logHeader.ToString();
+ }
+ }
+}
|