/* Function: FromBinaryFile * Reads a number set from the current position in a <BinaryFile>. */ static public NumberSet FromBinaryFile(BinaryFile binaryFile) { // [int32: ranges] // [int32: low] [int32: high] // [int32: low] [int32: high] // ... int length = binaryFile.ReadInt32(); if (length < 0) { throw new FormatException(); } NumberSet numberSet = new NumberSet((length != 0 ? length : 1)); numberSet.usedRanges = length; for (int i = 0; i < length; i++) { numberSet.ranges[i].Low = binaryFile.ReadInt32(); numberSet.ranges[i].High = binaryFile.ReadInt32(); } if (!numberSet.Validate()) { throw new FormatException(); } return(numberSet); }
public static float[] ReadFloats(string filePath, string headerExpected) { BinaryFile binFile = new BinaryFile(filePath, BinaryFile.ByteOrder.LittleEndian); string header = binFile.ReadString(4); if (header == headerExpected) // "FPQr", "FQ2p" or "FQ3p" { int version = binFile.ReadInt32(); int parameterCount = binFile.ReadInt32(); var floatArray = new float[parameterCount]; int i = 0; try { for (i = 0; i < parameterCount; i++) { floatArray[i] = binFile.ReadSingle(); } } catch (System.Exception e) { Log.Error("Failed reading floats: {0}", e); } binFile.Close(); return(floatArray); } else { binFile.Close(); return(null); } }
/// <summary> /// Parse out the xml string from the passed chunk data byte array /// </summary> /// <param name="chunkDataByteArray"></param> /// <returns>xml string</returns> private static string ParseChunkData(byte[] chunkDataByteArray) { var bf = new BinaryFile(chunkDataByteArray, BinaryFile.ByteOrder.BigEndian); int val1 = bf.ReadInt32(); int val2 = bf.ReadInt32(); int val3 = bf.ReadInt32(); string val4 = bf.ReadString(4); string val5 = bf.ReadString(4); //int chunkSize = byteArray.Length - 32; int chunkSize = bf.ReadInt32(); //int val6 = bf.ReadInt32(); string val7 = bf.ReadString(4); var xmlChunkBytes = new byte[chunkSize]; xmlChunkBytes = bf.ReadBytes(0, chunkSize, BinaryFile.ByteOrder.LittleEndian); string xmlString = BinaryFile.ByteArrayToString(xmlChunkBytes); int val8 = bf.ReadInt32(BinaryFile.ByteOrder.LittleEndian); return(xmlString); }
/// <summary> /// Parses the <paramref name="binaryFile" /> and returns a <see cref="RIFFFileChunk" />. Note that the position of the /// stream has to point to a riff file chunk. /// </summary> /// <param name="binaryFile"><see cref="BinaryFile" /> which contains the riff file chunk.</param> /// <returns> /// Instance of the <see cref="RIFFFileChunk" /> class or any derived classes. It the stream does not point to a /// wave file chunk the instance of the <see cref="RIFFFileChunk" /> which gets return will be invalid. /// </returns> public static RIFFFileChunk FromBinaryFile(BinaryFile binaryFile) { if (binaryFile == null) { throw new ArgumentNullException("binaryFile"); } if (binaryFile.CanRead == false) { throw new ArgumentException("binaryFile is not readable"); } int id = binaryFile.ReadInt32(BinaryFile.ByteOrder.LittleEndian); // Steinberg CPR files have LittleEndian FourCCs binaryFile.Position -= 4; if (StringUtils.IsAsciiPrintable(FourCC.FromFourCC(id))) { Log.Verbose("Processing chunk: '{0}'", FourCC.FromFourCC(id)); } else { if (id == 0) { // likely corrupt wav file with alot of crap after the chunk // skip bytes until only 8 bytes are left // stream.Position = stream.Length - 8; } else { // try to fix chunks that are not word-aligned but should have been?! Log.Verbose("Processing chunk: {0}", string.Format("{0} is not FourCC", id)); long origPos = binaryFile.Position; // rewind one byte and try again binaryFile.Position -= 1; int id2ndTry = binaryFile.ReadInt32(); binaryFile.Position -= 4; if (StringUtils.IsAsciiPrintable(FourCC.FromFourCC(id2ndTry))) { // we believe it worked Log.Verbose("Seem to have fixed non word-aligned chunk: {0}", FourCC.FromFourCC(id2ndTry)); } else { // still didn't work // put position back to where it was. binaryFile.Position = origPos; } } } return(new RIFFFileChunk(binaryFile)); }
public bool ReadFXP(FXP fxp, string filePath = "") { if (fxp == null || fxp.ChunkDataByteArray == null) { return(false); } var bFile = new BinaryFile(fxp.ChunkDataByteArray, BinaryFile.ByteOrder.LittleEndian); // Read UAD Preset Header information PresetHeaderVar1 = bFile.ReadInt32(); PresetHeaderVar2 = bFile.ReadInt32(); PresetName = bFile.ReadString(32).Trim('\0'); // Read Parameters Input = bFile.ReadSingle(); Phase = bFile.ReadSingle(); HPFreq = bFile.ReadSingle(); LPFreq = bFile.ReadSingle(); HP_LPDynSC = bFile.ReadSingle(); CMPRatio = bFile.ReadSingle(); CMPThresh = bFile.ReadSingle(); CMPRelease = bFile.ReadSingle(); CMPAttack = bFile.ReadSingle(); StereoLink = bFile.ReadSingle(); Select = bFile.ReadSingle(); EXPThresh = bFile.ReadSingle(); EXPRange = bFile.ReadSingle(); EXPRelease = bFile.ReadSingle(); EXPAttack = bFile.ReadSingle(); DYNIn = bFile.ReadSingle(); CompIn = bFile.ReadSingle(); ExpIn = bFile.ReadSingle(); LFGain = bFile.ReadSingle(); LFFreq = bFile.ReadSingle(); LFBell = bFile.ReadSingle(); LMFGain = bFile.ReadSingle(); LMFFreq = bFile.ReadSingle(); LMFQ = bFile.ReadSingle(); HMFQ = bFile.ReadSingle(); HMFGain = bFile.ReadSingle(); HMFFreq = bFile.ReadSingle(); HFGain = bFile.ReadSingle(); HFFreq = bFile.ReadSingle(); HFBell = bFile.ReadSingle(); EQIn = bFile.ReadSingle(); EQDynSC = bFile.ReadSingle(); PreDyn = bFile.ReadSingle(); Output = bFile.ReadSingle(); EQType = bFile.ReadSingle(); Power = bFile.ReadSingle(); return(true); }
/* Function: ReadFrom * Reads a number set from the current position in a <BinaryFile>. */ public void ReadFrom(BinaryFile binaryFile) { // [int32: ranges] int newRangeCount = binaryFile.ReadInt32(); if (newRangeCount < 0) { throw new FormatException(); } // Reallocate if needed if (newRangeCount == 0) { if (ranges != null && ShouldShrinkTo(ranges.Length, 0) == 0) { ranges = null; } usedRanges = 0; } else { int arraySize = (ranges == null ? 0 : ranges.Length); int newArraySize = (newRangeCount >= arraySize ? ShouldGrowTo(arraySize, newRangeCount) : ShouldShrinkTo(arraySize, newRangeCount)); if (arraySize != newArraySize) { ranges = new NumberRange[newArraySize]; } // [int32: low] [int32: high] // [int32: low] [int32: high] // ... for (int i = 0; i < newRangeCount; i++) { ranges[i].Low = binaryFile.ReadInt32(); ranges[i].High = binaryFile.ReadInt32(); } usedRanges = newRangeCount; } if (!Validate()) { throw new FormatException(); } }
private static Entry parse_nimd_file(BinaryFile bFile) { // ready 12 bytes string magic = bFile.ReadString(4); int empty = bFile.ReadInt32(); int totalSize = bFile.ReadInt32(); if (!magic.Equals("NIMD")) { throw new ArgumentException("Invalid NIMD header"); } return(parse_nimd_entry_list(bFile, "")); }
public DungeonBalance(byte[] binData, byte[] entData) { IReadOnlyBinaryDataAccessor binFile = new BinaryFile(binData); IReadOnlyBinaryDataAccessor entFile = new BinaryFile(entData); var entCount = entFile.Length / sizeof(uint) - 1; Entries = new Entry[entCount]; for (var i = 0; i < entCount; i++) { var curr = entFile.ReadInt32(i * sizeof(int)); var next = entFile.ReadInt32((i + 1) * sizeof(int)); Entries[i] = new Entry(binFile.Slice(curr, next - curr)); } }
private static Entry parse_nimd_entry_list(BinaryFile bFile, string name) { // ready 2 ints (8 bytes) int totalSize = bFile.ReadInt32(); int numEntries = bFile.ReadInt32(); var entries = new List <Entry>(); for (int i = 0; i < numEntries; i++) { entries.Add(parse_nimd_entry(bFile)); } return(new Entry(name, entries)); }
public static void Read32Bit(BinaryFile waveFile, float[][] sound, int sampleCount, int channels) { for (int i = 0; i < sampleCount; i++) { for (int ic = 0; ic < channels; ic++) { float f = (float)waveFile.ReadInt32(); f = f / 2147483648.0f; sound[ic][i] = f; } } }
public Farc(byte[] data) { using var accessor = new BinaryFile(data); Magic = accessor.ReadInt32(0); UnknownHeaderData = accessor.ReadArray(4, 0x1C); FarcVersion = accessor.ReadInt32(0x20); if (FarcVersion != 5) { throw new NotSupportedException("Only FARC version 5 is supported"); } var fatOffset = accessor.ReadInt32(0x24); var fatLength = accessor.ReadInt32(0x28); var dataOffset = accessor.ReadInt32(0x2C); var dataLength = accessor.ReadInt32(0x30); var fat = new FarcFat(data, fatOffset, fatLength); var files = new ConcurrentDictionary <uint, byte[]>(); foreach (var file in fat.Entries) { files[file.Hash] = accessor.ReadArray(dataOffset + file.DataOffset, file.DataLength); } Files = files; }
private static Entry parse_nimd_entry(BinaryFile bFile) { // read boolean (1 byte) bool isList = bFile.ReadBoolean(); // ready 2 ints (8 bytes) int total_size = bFile.ReadInt32(); int name_size = bFile.ReadInt32(); string name = bFile.ReadString(name_size); if (isList) { return(parse_nimd_entry_list(bFile, name)); } // ready 2 ints (8 bytes) int data_offset = bFile.ReadInt32(); int data_size = bFile.ReadInt32(); return(new Entry(name, data_offset, data_size)); }
/// <summary> /// Initializes a new instance of the <see cref="RIFFFileChunk" /> class. /// </summary> /// <param name="binaryFile"><see cref="BinaryFile" /> which contains the riff file chunk.</param> public RIFFFileChunk(BinaryFile binaryFile) { if (binaryFile == null) { throw new ArgumentNullException("binaryFile"); } _binaryFile = binaryFile; ChunkID = binaryFile.ReadInt32(BinaryFile.ByteOrder.LittleEndian); // Steinberg CPR files have LittleEndian FourCCs ChunkDataSize = binaryFile.ReadUInt32(); StartPosition = binaryFile.Position; // Log.Verbose("Processing '{0}'. Start position: {1}, Data size: {2}, End position: {3}", StringUtils.IsAsciiPrintable(FourCC.FromFourCC(ChunkID)) ? FourCC.FromFourCC(ChunkID) : string.Format("int {0} is not FourCC", ChunkID), StartPosition, ChunkDataSize, EndPosition); }
public static void Read32Bit(BinaryFile wavfile, double[][] sound, int samplecount, int channels) { #if DEBUG Console.Write("Read32Bit...\n"); #endif for (int i = 0; i < samplecount; i++) { for (int ic = 0; ic < channels; ic++) { double d = (double)wavfile.ReadInt32(); d = d / 2147483648.0; sound[ic][i] = d; } } }
/// <summary> /// Initializes a new instance of the <see cref="RIFFFileReader" /> class. /// </summary> /// <param name="fileName">Filename which points to a wave file.</param> /// <param name="useWordAlignment">whether to ensure word-alignment (defaults to false)</param> public RIFFFileReader(string fileName, bool useWordAlignment = false, bool closeBinaryFile = false) { if (fileName == null) { throw new ArgumentNullException("fileName"); } _useWordAlignment = useWordAlignment; _closeBinaryFile = closeBinaryFile; _binaryFile = new BinaryFile(fileName, BinaryFile.ByteOrder.BigEndian); var firstChunkId = new String(_binaryFile.ReadChars(4)); if (firstChunkId == "RIFF") { // read RIFF data size var chunkSize = _binaryFile.ReadInt32(); // read form-type (WAVE etc) var field = new string(_binaryFile.ReadChars(4)); Log.Verbose("Processing RIFF. Data size: {0}, field: {1}", chunkSize, field); _chunks = ReadChunks(_binaryFile); } else { // unrecognized file format, not a RIFF File _chunks = new List <RIFFFileChunk>(2); Log.Error("Unknown format (not RIFF). First chunk Id: {0}", firstChunkId); } Log.Verbose(GetRIFFFileChunkInformation(Chunks)); _binaryFile.Position = 0; }
static readonly byte[] NKS_NICNT_TOC = new byte[] { 0x2F, 0x5C, 0x20, 0x4E, 0x49, 0x20, 0x46, 0x43, 0x20, 0x54, 0x4F, 0x43, 0x20, 0x20, 0x2F, 0x5C }; // /\ NI FC TOC /\ public static void Unpack(string inputFilePath, string outputDirectoryPath, bool doList, bool doVerbose) { using (BinaryFile bf = new BinaryFile(inputFilePath, BinaryFile.ByteOrder.LittleEndian, false)) { var header = bf.ReadBytes(16); if (header.SequenceEqual(NKS_NICNT_MTD)) // 2F 5C 20 4E 49 20 46 43 20 4D 54 44 20 20 2F 5C /\ NI FC MTD /\ { bf.Seek(66, SeekOrigin.Begin); string version = bf.ReadString(66, Encoding.Unicode).TrimEnd('\0'); Log.Information("Version: " + version); string outputFileName = Path.GetFileNameWithoutExtension(inputFilePath); if (!doList) { IOUtils.CreateDirectoryIfNotExist(Path.Combine(outputDirectoryPath, outputFileName)); } // Save version in ContentVersion.txt if (!doList) { IOUtils.WriteTextToFile(Path.Combine(outputDirectoryPath, outputFileName, "ContentVersion.txt"), version); } int unknown1 = bf.ReadInt32(); if (doVerbose) { Log.Debug("Unknown1: " + unknown1); } bf.Seek(144, SeekOrigin.Begin); int startOffset = bf.ReadInt32(); Log.Information("Start Offset: " + startOffset); int unknown3 = bf.ReadInt32(); if (doVerbose) { Log.Debug("Unknown3: " + unknown3); } bf.Seek(256, SeekOrigin.Begin); string productHintsXml = bf.ReadStringNull(); Log.Information(string.Format("Read ProductHints Xml with length {0} characters.", productHintsXml.Length)); if (doVerbose) { Log.Debug("ProductHints Xml:\n" + productHintsXml); } // Save productHints as xml if (!doList) { IOUtils.WriteTextToFile(Path.Combine(outputDirectoryPath, outputFileName, outputFileName + ".xml"), productHintsXml); } // get the product hints as an object var productHints = ProductHintsFactory.ReadFromString(productHintsXml); if (productHints != null && productHints.Product.Icon != null && productHints.Product.Icon.ImageBytes != null) { ProductHintsFactory.UpdateImageFromImageBytes(productHints); var image = productHints.Product.Icon.Image; var imageFormat = productHints.Product.Icon.ImageFormat; if (image != null && imageFormat != null) { Log.Information(string.Format("Found Icon in ProductHints Xml in {0} format. (Dimensions: {1} x {2}, Width: {1} pixels, Height: {2} pixels, Bit depth: {3} bpp)", imageFormat.Name, image.Width, image.Height, image.PixelType.BitsPerPixel)); // save icon to file if (!doList) { var iconFileName = outputFileName + " Icon." + imageFormat.Name.ToLower(); var iconFilePath = Path.Combine(outputDirectoryPath, outputFileName, iconFileName); if (doVerbose) { Log.Debug("Saving Icon to: " + iconFilePath); } // save using ImageSharp // var imageEncoder = image.GetConfiguration().ImageFormatsManager.FindEncoder(imageFormat); // image.Save(iconFilePath, imageEncoder); // save using image bytes BinaryFile.ByteArrayToFile(iconFilePath, productHints.Product.Icon.ImageBytes); } } } bf.Seek(startOffset + 256, SeekOrigin.Begin); var header2 = bf.ReadBytes(16); if (header2.SequenceEqual(NKS_NICNT_MTD)) // 2F 5C 20 4E 49 20 46 43 20 4D 54 44 20 20 2F 5C /\ NI FC MTD /\ { bf.ReadBytes(116); long unknown4 = bf.ReadInt64(); if (doVerbose) { Log.Debug("Unknown4: " + unknown4); } bf.ReadBytes(4); long unknown5 = bf.ReadInt64(); if (doVerbose) { Log.Debug("Unknown5: " + unknown5); } bf.ReadBytes(104); long unknown6 = bf.ReadInt64(); if (doVerbose) { Log.Debug("Unknown6: " + unknown6); } var delimiter1 = bf.ReadBytes(8); if (doVerbose) { Log.Debug("Delimiter1: " + StringUtils.ByteArrayToHexString(delimiter1)); // F0 F0 F0 F0 F0 F0 F0 F0 } if (!delimiter1.SequenceEqual(new byte[] { 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0 })) { Log.Error("Delimiter1 not as expected 'F0 F0 F0 F0 F0 F0 F0 F0' but got " + StringUtils.ToHexAndAsciiString(delimiter1)); } long totalResourceCount = bf.ReadInt64(); Log.Information("Total Resource Count: " + totalResourceCount); long totalResourceLength = bf.ReadInt64(); Log.Information("Total Resource Byte Length: " + totalResourceLength); var resourceList = new List <NICNTResource>(); var header3 = bf.ReadBytes(16); if (header3.SequenceEqual(NKS_NICNT_TOC)) // 2F 5C 20 4E 49 20 46 43 20 54 4F 43 20 20 2F 5C /\ NI FC TOC /\ { bf.ReadBytes(600); long lastEndIndex = 0; for (int i = 0; i < totalResourceCount; i++) { var resource = new NICNTResource(); Log.Information("-------- Index: " + bf.Position + " --------"); long resCounter = bf.ReadInt64(); Log.Information("Resource Counter: " + resCounter); resource.Count = resCounter; bf.ReadBytes(16); string resName = bf.ReadString(600, Encoding.Unicode).TrimEnd('\0'); Log.Information("Resource Name: " + resName); resource.Name = resName; long resUnknown = bf.ReadInt64(); if (doVerbose) { Log.Debug("Resource Unknown: " + resUnknown); } long resEndIndex = bf.ReadInt64(); Log.Information("Resource End Index: " + resEndIndex); resource.EndIndex = resEndIndex; // store calculated length if (lastEndIndex > 0) { resource.Length = resEndIndex - lastEndIndex; } else { // for the very first entry the end index is the same as the byte length resource.Length = resEndIndex; } Log.Information("Calculated Resource Byte Length: " + resource.Length); lastEndIndex = resEndIndex; resourceList.Add(resource); } Log.Information("-------- Index: " + bf.Position + " --------"); var delimiter2 = bf.ReadBytes(8); if (doVerbose) { Log.Debug("Delimiter2: " + StringUtils.ByteArrayToHexString(delimiter2)); // F1 F1 F1 F1 F1 F1 F1 F1 } if (!delimiter2.SequenceEqual(new byte[] { 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, 0xF1 })) { Log.Error("Delimiter2 not as expected 'F1 F1 F1 F1 F1 F1 F1 F1' but got " + StringUtils.ToHexAndAsciiString(delimiter2)); } long unknown13 = bf.ReadInt64(); if (doVerbose) { Log.Debug("Unknown13: " + unknown13); } long unknown14 = bf.ReadInt64(); if (doVerbose) { Log.Debug("Unknown14: " + unknown14); } var header4 = bf.ReadBytes(16); if (header4.SequenceEqual(NKS_NICNT_TOC)) // 2F 5C 20 4E 49 20 46 43 20 54 4F 43 20 20 2F 5C /\ NI FC TOC /\ { bf.ReadBytes(592); if (!doList) { IOUtils.CreateDirectoryIfNotExist(Path.Combine(outputDirectoryPath, outputFileName, "Resources")); } foreach (var res in resourceList) { // convert the unix filename to a windows supported filename string escapedFileName = FromUnixFileNames(res.Name); // and add the counter in front string escapedFileNameWithNumber = string.Format("{0:D3}{1}", res.Count, escapedFileName); Log.Information(String.Format("Resource '{0}' @ position {1} [{2} bytes]", escapedFileNameWithNumber, bf.Position, res.Length)); res.Data = bf.ReadBytes((int)res.Length); // if not only listing, save files if (!doList) { string outputFilePath = Path.Combine(outputDirectoryPath, outputFileName, "Resources", escapedFileNameWithNumber); BinaryFile outBinaryFile = new BinaryFile(outputFilePath, BinaryFile.ByteOrder.LittleEndian, true); outBinaryFile.Write(res.Data); outBinaryFile.Close(); } } } else { Log.Error(inputFilePath + ": Header4 not as expected '/\\ NI FC TOC /\\' but got " + StringUtils.ToHexAndAsciiString(header4)); } } else { Log.Error(inputFilePath + ": Header3 not as expected '/\\ NI FC TOC /\\' but got " + StringUtils.ToHexAndAsciiString(header3)); } } else { Log.Error(inputFilePath + ": Header2 not as expected '/\\ NI FC MTD /\\' but got " + StringUtils.ToHexAndAsciiString(header2)); } } else { Log.Error(inputFilePath + ": Header not as expected '/\\ NI FC MTD /\\' but got " + StringUtils.ToHexAndAsciiString(header)); } } }
// Group: Loading Functions // __________________________________________________________________________ /* Function: Load * Loads the information in <Languages.nd> into a <Config> object, returning whether it was successful. If it was not * config will be null. */ public bool Load(Path filename, out Config config) { BinaryFile file = new BinaryFile(); try { if (file.OpenForReading(filename, "2.2") == false) { config = null; return(false); } else { config = new Config(); // [String: Language Name] // [[Language Attributes]] // ... // [String: null] string languageName = file.ReadString(); while (languageName != null) { Language language = new Language(languageName); // [Int32: ID] // [Byte: Type] // [String: Simple Identifier] // [Byte: Enum Values] // [Byte: Case Sensitive (1 or 0)] // [String: Member Operator Symbol] // [String: Line Extender Symbol] language.ID = file.ReadInt32(); byte type = file.ReadByte(); if (Enum.IsDefined(typeof(Language.LanguageType), type)) { language.Type = (Language.LanguageType)type; } else { config = null; return(false); } language.SimpleIdentifier = file.ReadString(); byte enumValues = file.ReadByte(); if (Enum.IsDefined(typeof(Language.EnumValues), enumValues)) { language.EnumValue = (Language.EnumValues)enumValues; } else { config = null; return(false); } language.CaseSensitive = (file.ReadByte() == 1); language.MemberOperator = file.ReadString(); language.LineExtender = file.ReadString(); // [String: Line Comment Symbol] [] ... [String: null] // [String: Opening Block Comment Symbol] [String: Closing Block Comment Symbol] [] [] ... [String: null] // [String: Javadoc First Line Comment Symbol] [String: Javadoc Following Lines Comment Symbol [] [] ... [String: null] // [String: Javadoc Opening Block Comment Symbol] [String: Javadoc Closing Block Comment Symbol] [] [] ... [String: null] // [String: XML Line Comment Symbol] [] ... [String: null] var lineCommentSymbols = ReadSymbolList(file); if (lineCommentSymbols != null) { language.LineCommentSymbols = lineCommentSymbols; } var blockCommentSymbols = ReadBlockCommentSymbolsList(file); if (blockCommentSymbols != null) { language.BlockCommentSymbols = blockCommentSymbols; } var javadocLineCommentSymbols = ReadLineCommentSymbolsList(file); if (javadocLineCommentSymbols != null) { language.JavadocLineCommentSymbols = javadocLineCommentSymbols; } var javadocBlockCommentSymbols = ReadBlockCommentSymbolsList(file); if (javadocBlockCommentSymbols != null) { language.JavadocBlockCommentSymbols = javadocBlockCommentSymbols; } var xmlLineCommentSymbols = ReadSymbolList(file); if (xmlLineCommentSymbols != null) { language.XMLLineCommentSymbols = xmlLineCommentSymbols; } // Prototype Enders: // [Int32: Comment Type ID] // [Byte: Include Line Breaks (1 or 0)] // [String: Prototype Ender Symbol] [] ... [String: null] // ... // [Int32: 0] int commentTypeID = file.ReadInt32(); while (commentTypeID != 0) { bool includeLineBreaks = (file.ReadByte() == 1); var enderSymbols = ReadSymbolList(file); language.AddPrototypeEnders(new PrototypeEnders(commentTypeID, enderSymbols, includeLineBreaks)); commentTypeID = file.ReadInt32(); } config.AddLanguage(language); languageName = file.ReadString(); } // [String: Alias] [Int32: Language ID] [] [] ... [String: Null] string alias = file.ReadString(); while (alias != null) { int languageID = file.ReadInt32(); config.AddAlias(alias, languageID); alias = file.ReadString(); } // [String: File Extension] [Int32: Language ID] [] [] ... [String: Null] string fileExtension = file.ReadString(); while (fileExtension != null) { int languageID = file.ReadInt32(); config.AddFileExtension(fileExtension, languageID); fileExtension = file.ReadString(); } // [String: Shebang String] [Int32: Language ID] [] [] ... [String: Null] string shebangString = file.ReadString(); while (shebangString != null) { int languageID = file.ReadInt32(); config.AddShebangString(shebangString, languageID); shebangString = file.ReadString(); } } } catch { config = null; return(false); } finally { file.Close(); } return(true); }
/* Function: Load * Loads the information in <Config.nd> and returns whether it was successful. If not all the out parameters will still * return objects, they will just be empty. */ public bool Load(Path filename, out Config.ProjectInfo projectInfo, out List <Style> styles, out List <FileSourceInfo> fileSourceInfoList) { projectInfo = new Config.ProjectInfo(); styles = new List <Style>(); fileSourceInfoList = new List <FileSourceInfo>(); BinaryFile binaryFile = new BinaryFile(); bool result = true; try { if (binaryFile.OpenForReading(filename, "2.2") == false) { result = false; } else { // [String: Project Title or null] // [String: Project Subtitle or null] // [String: Project Copyright or null] // [String: Project Timestamp Code or null] projectInfo.Title = binaryFile.ReadString(); projectInfo.TitlePropertyLocation = Config.PropertySource.PreviousRun; projectInfo.Subtitle = binaryFile.ReadString(); projectInfo.SubtitlePropertyLocation = Config.PropertySource.PreviousRun; projectInfo.Copyright = binaryFile.ReadString(); projectInfo.CopyrightPropertyLocation = Config.PropertySource.PreviousRun; projectInfo.TimestampCode = binaryFile.ReadString(); projectInfo.TimestampCodePropertyLocation = Config.PropertySource.PreviousRun; // [String: Style Path] // (properties) // [String: Style Path] // ... // [String: null] string stylePath = binaryFile.ReadString(); while (stylePath != null) { Style style; if (stylePath.EndsWith(".css", StringComparison.OrdinalIgnoreCase)) { style = new Styles.CSSOnly(stylePath); } else { style = new Styles.Advanced(stylePath); } styles.Add(style); // [String: Inherit] ... [String: null] string inheritStatement = binaryFile.ReadString(); while (inheritStatement != null) { // Find the name in the list of styles so we can connect the objects together properly. There should only // be one style per name so we can just compare by name. Also, this list is stored in the order in which // they must be applied, which means inherited styles will appear before the ones that inherit from them, // so we can search the list we've built so far instead of waiting until they're all loaded. Style matchingStyle = null; for (int i = 0; i < styles.Count; i++) { if (string.Compare(inheritStatement, styles[i].Name, StringComparison.OrdinalIgnoreCase) == 0) { matchingStyle = styles[i]; break; } } // If there's no match just add it as null. style.AddInheritedStyle(inheritStatement, Config.PropertySource.PreviousRun, matchingStyle); inheritStatement = binaryFile.ReadString(); } // [String: OnLoad] [Byte: Page Type] ... [String: null] string onLoadStatement = binaryFile.ReadString(); while (onLoadStatement != null) { Engine.Styles.PageType pageType = (Engine.Styles.PageType)binaryFile.ReadByte(); style.AddOnLoad(onLoadStatement, Config.PropertySource.PreviousRun, pageType); onLoadStatement = binaryFile.ReadString(); } // [String: Link] [Byte: Page Type] ... [String: null] string linkStatement = binaryFile.ReadString(); while (linkStatement != null) { Engine.Styles.PageType pageType = (Engine.Styles.PageType)binaryFile.ReadByte(); style.AddLinkedFile(linkStatement, Config.PropertySource.PreviousRun, pageType); linkStatement = binaryFile.ReadString(); } // [String: Home Page or null] string homePage = binaryFile.ReadString(); if (homePage != null) { style.SetHomePage(homePage, Config.PropertySource.PreviousRun); } // Next style path stylePath = binaryFile.ReadString(); } projectInfo.StyleName = styles[styles.Count - 1].Name; projectInfo.StyleNamePropertyLocation = Config.PropertySource.PreviousRun; // [Int32: Source FileSource Number] [String: Source FileSource UniqueIDString] // [Int32: Source FileSource Number] [String: Source FileSource UniqueIDString] // ... // [Int32: 0] FileSourceInfo fileSourceInfo = new FileSourceInfo(); fileSourceInfo.Type = Files.InputType.Source; for (;;) { fileSourceInfo.Number = binaryFile.ReadInt32(); if (fileSourceInfo.Number == 0) { break; } fileSourceInfo.UniqueIDString = binaryFile.ReadString(); fileSourceInfoList.Add(fileSourceInfo); } // [Int32: Image FileSource Number] [String: Image FileSource UniqueIDString] // [Int32: Image FileSource Number] [String: Image FileSource UniqueIDString] // ... // [Int32: 0] fileSourceInfo.Type = Files.InputType.Image; for (;;) { fileSourceInfo.Number = binaryFile.ReadInt32(); if (fileSourceInfo.Number == 0) { break; } fileSourceInfo.UniqueIDString = binaryFile.ReadString(); fileSourceInfoList.Add(fileSourceInfo); } } } catch { result = false; } finally { binaryFile.Dispose(); } if (result == false) { projectInfo = new Config.ProjectInfo(); styles.Clear(); fileSourceInfoList.Clear(); } return(result); }
/* Function: Load * Loads the information in <Comments.nd>, which is the computed comment settings from the last time Natural Docs was run. * Returns whether it was successful. If not all the out parameters will still return objects, they will just be empty. */ public bool Load(Path filename, out List <CommentType> binaryCommentTypes, out List <Tag> binaryTags, out List <KeyValuePair <string, int> > binarySingularKeywords, out List <KeyValuePair <string, int> > binaryPluralKeywords, out List <string> binaryIgnoredKeywords) { binaryCommentTypes = new List <CommentType>(); binaryTags = new List <Tag>(); binarySingularKeywords = new List <KeyValuePair <string, int> >(); binaryPluralKeywords = new List <KeyValuePair <string, int> >(); binaryIgnoredKeywords = new List <string>(); BinaryFile file = new BinaryFile(); bool result = true; try { if (file.OpenForReading(filename, "2.0") == false) { result = false; } else { // [String: Tag Name] // [Int32: ID] // ... // [String: null] string tagName = file.ReadString(); while (tagName != null) { Tag tag = new Tag(tagName); tag.ID = file.ReadInt32(); binaryTags.Add(tag); tagName = file.ReadString(); } // [String: Comment Type Name] // [Int32: ID] // [String: Display Name] // [String: Plural Display Name] // [String: Simple Identifier] // [Byte: Index] // [Int32: Index With ID]? // [Byte: Scope] // [Byte: Break Lists] // [UInt16: Flags] // ... // [String: null] string commentTypeName = file.ReadString(); IDObjects.NumberSet commentTypeIDs = new IDObjects.NumberSet(); while (commentTypeName != null) { CommentType commentType = new CommentType(commentTypeName); commentType.ID = file.ReadInt32(); commentType.DisplayName = file.ReadString(); commentType.PluralDisplayName = file.ReadString(); commentType.SimpleIdentifier = file.ReadString(); // We don't have to validate the enum and flag values because they're only used to compare to the config file // versions, which are validated. If these are invalid they'll just show up as changed. commentType.Index = (CommentType.IndexValue)file.ReadByte(); if (commentType.Index == CommentType.IndexValue.IndexWith) { commentType.IndexWith = file.ReadInt32(); } commentType.Scope = (CommentType.ScopeValue)file.ReadByte(); commentType.BreakLists = (file.ReadByte() != 0); commentType.Flags.AllConfigurationProperties = (CommentTypeFlags.FlagValues)file.ReadUInt16(); binaryCommentTypes.Add(commentType); commentTypeIDs.Add(commentType.ID); commentTypeName = file.ReadString(); } // Check the Index With values after they're all entered in. foreach (CommentType commentType in binaryCommentTypes) { if (commentType.Index == CommentType.IndexValue.IndexWith && !commentTypeIDs.Contains(commentType.IndexWith)) { result = false; } } // [String: Singular Keyword] // [Int32: Comment Type ID] // ... // [String: null] string keyword = file.ReadString(); while (keyword != null) { int id = file.ReadInt32(); binarySingularKeywords.Add(new KeyValuePair <string, int>(keyword, id)); if (!commentTypeIDs.Contains(id)) { result = false; } keyword = file.ReadString(); } // [String: Plural Keyword] // [Int32: Comment Type ID] // ... // [String: null] keyword = file.ReadString(); while (keyword != null) { int id = file.ReadInt32(); binaryPluralKeywords.Add(new KeyValuePair <string, int>(keyword, id)); if (!commentTypeIDs.Contains(id)) { result = false; } keyword = file.ReadString(); } // [String: Ignored Keyword] // ... // [String: null] keyword = file.ReadString(); while (keyword != null) { binaryIgnoredKeywords.Add(keyword); keyword = file.ReadString(); } } } catch { result = false; } finally { file.Close(); } if (result == false) { // Reset all the objects to empty versions. binaryCommentTypes.Clear(); binarySingularKeywords.Clear(); binaryPluralKeywords.Clear(); binaryIgnoredKeywords.Clear(); } return(result); }
public bool ReadFFP(string filePath) { BinaryFile binFile = new BinaryFile(filePath, BinaryFile.ByteOrder.LittleEndian); string header = binFile.ReadString(4); if (header != "FPQr") { return(false); } Version = binFile.ReadInt32(); ParameterCount = binFile.ReadInt32(); // Read in how many bands are enabled var numActiveBands = binFile.ReadSingle(); Bands = new List <ProQBand>(); for (int i = 0; i < 24; i++) { var band = new ProQBand(); band.Frequency = FreqConvertBack(binFile.ReadSingle()); band.Gain = binFile.ReadSingle(); // actual gain in dB band.Q = QConvertBack(binFile.ReadSingle()); // 0 - 5 var filterType = binFile.ReadSingle(); switch (filterType) { case (float)ProQShape.Bell: band.Shape = ProQShape.Bell; break; case (float)ProQShape.LowShelf: band.Shape = ProQShape.LowShelf; break; case (float)ProQShape.LowCut: band.Shape = ProQShape.LowCut; break; case (float)ProQShape.HighShelf: band.Shape = ProQShape.HighShelf; break; case (float)ProQShape.HighCut: band.Shape = ProQShape.HighCut; break; case (float)ProQShape.Notch: band.Shape = ProQShape.Notch; break; default: throw new ArgumentOutOfRangeException(string.Format("Filter type is outside range: {0}", filterType)); } // 0 = 6 dB/oct, 1 = 12 dB/oct, 2 = 24 dB/oct, 3 = 48 dB/oct var filterSlope = binFile.ReadSingle(); switch (filterSlope) { case (float)ProQLPHPSlope.Slope6dB_oct: band.LPHPSlope = ProQLPHPSlope.Slope6dB_oct; break; case (float)ProQLPHPSlope.Slope12dB_oct: band.LPHPSlope = ProQLPHPSlope.Slope12dB_oct; break; case (float)ProQLPHPSlope.Slope24dB_oct: band.LPHPSlope = ProQLPHPSlope.Slope24dB_oct; break; case (float)ProQLPHPSlope.Slope48dB_oct: band.LPHPSlope = ProQLPHPSlope.Slope48dB_oct; break; default: throw new ArgumentOutOfRangeException(string.Format("Filter slope is outside range: {0}", filterSlope)); } // 0 = Left, 1 = Right, 2 = Stereo var filterStereoPlacement = binFile.ReadSingle(); switch (filterStereoPlacement) { case (float)ProQStereoPlacement.LeftOrMid: band.StereoPlacement = ProQStereoPlacement.LeftOrMid; break; case (float)ProQStereoPlacement.RightOrSide: band.StereoPlacement = ProQStereoPlacement.RightOrSide; break; case (float)ProQStereoPlacement.Stereo: band.StereoPlacement = ProQStereoPlacement.Stereo; break; default: throw new ArgumentOutOfRangeException(string.Format("Filter stereo placement is outside range: {0}", filterStereoPlacement)); } // always 1.0 ? var unknown = binFile.ReadSingle(); // check if band is enabled if (numActiveBands > 0 && numActiveBands > i) { band.Enabled = true; } Bands.Add(band); } // read the remaining floats try { OutputGain = binFile.ReadSingle(); // -1 to 1 (- Infinity to +36 dB , 0 = 0 dB) OutputPan = binFile.ReadSingle(); // -1 to 1 (0 = middle) DisplayRange = binFile.ReadSingle(); // 0 = 6dB, 1 = 12dB, 2 = 30dB, 3 = 3dB ProcessMode = binFile.ReadSingle(); // 0 = zero latency, 1 = lin.phase.low - medium - high - maximum ChannelMode = binFile.ReadSingle(); // 0 = Left/Right, 1 = Mid/Side Bypass = binFile.ReadSingle(); // 0 = No bypass ReceiveMidi = binFile.ReadSingle(); // 0 = Enabled? Analyzer = binFile.ReadSingle(); // 0 = Off, 1 = Pre, 2 = Post, 3 = Pre+Post AnalyzerResolution = binFile.ReadSingle(); // 0 - 3 : low - medium[x] - high - maximum AnalyzerSpeed = binFile.ReadSingle(); // 0 - 3 : very slow, slow, medium[x], fast SoloBand = binFile.ReadSingle(); // -1 } catch { } // check if mid/side if (ChannelMode == 1) { Bands.ForEach(b => b.ChannelMode = ProQChannelMode.MidSide); } binFile.Close(); return(true); }
// Group: Loading Functions // __________________________________________________________________________ /* Function: Load * Loads the information in <Languages.nd>, which is the computed language settings from the last time Natural Docs * was run. Returns whether it was successful. If not all the out parameters will still return objects, they will just be * empty. */ public bool Load(Path filename, out List <Language> languages, out List <KeyValuePair <string, int> > aliases, out List <KeyValuePair <string, int> > extensions, out List <KeyValuePair <string, int> > shebangStrings, out List <string> ignoredExtensions) { languages = new List <Language>(); aliases = new List <KeyValuePair <string, int> >(); extensions = new List <KeyValuePair <string, int> >(); shebangStrings = new List <KeyValuePair <string, int> >(); ignoredExtensions = new List <string>(); BinaryFile file = new BinaryFile(); bool result = true; IDObjects.NumberSet usedLanguageIDs = new IDObjects.NumberSet(); try { if (file.OpenForReading(filename, "2.0") == false) { result = false; } else { // [String: Language Name] // [Int32: ID] // [Byte: Type] // [String: Simple Identifier] // [Byte: Enum Values] // [Byte: Case Sensitive (1 or 0)] // [String: Member Operator Symbol] // [String: Line Extender Symbol] // [String: Line Comment Symbol] [] ... [String: null] // [String: Opening Block Comment Symbol] [String: Closing Block Comment Symbo] [] [] ... [String: null] // [String: Opening Javadoc Line Comment Symbol] [String: Remainder Javadoc Line Comment Symbol [] ... [String: null] // [String: Opening Javadoc Block Comment Symbol] [String: Closing Javadoc Block Comment Symbol] [] [] ... [String: null] // [String: XML Line Comment Symbol] [] ... [String: null] // [Int32: Comment Type ID] // [Byte: Include Line Breaks (1 or 0)] // [String: Prototype Ender Symbol] [] ... [String: null] // ... // [Int32: 0] // ... // [String: null] for (string languageName = file.ReadString(); languageName != null; languageName = file.ReadString()) { Language language = new Language(languageManager, languageName); language.ID = file.ReadInt32(); byte rawTypeValue = file.ReadByte(); if (Enum.IsDefined(typeof(Language.LanguageType), rawTypeValue)) { language.Type = (Language.LanguageType)rawTypeValue; } else { result = false; } language.SimpleIdentifier = file.ReadString(); byte rawEnumValue = file.ReadByte(); if (Enum.IsDefined(typeof(Language.EnumValues), rawEnumValue)) { language.EnumValue = (Language.EnumValues)rawEnumValue; } else { result = false; } language.CaseSensitive = (file.ReadByte() == 1); language.MemberOperator = file.ReadString(); language.LineExtender = file.ReadString(); language.LineCommentStrings = ReadStringArray(file); language.BlockCommentStringPairs = ReadStringArray(file); language.JavadocLineCommentStringPairs = ReadStringArray(file); language.JavadocBlockCommentStringPairs = ReadStringArray(file); language.XMLLineCommentStrings = ReadStringArray(file); for (int commentTypeID = file.ReadInt32(); commentTypeID != 0; commentTypeID = file.ReadInt32()) { bool includeLineBreaks = (file.ReadByte() == 1); string[] enderSymbols = ReadStringArray(file); language.SetPrototypeEnders(commentTypeID, new PrototypeEnders(enderSymbols, includeLineBreaks)); } languages.Add(language); usedLanguageIDs.Add(language.ID); } // [String: Alias] [Int32: Language ID] [] [] ... [String: Null] for (string alias = file.ReadString(); alias != null; alias = file.ReadString()) { int languageID = file.ReadInt32(); if (usedLanguageIDs.Contains(languageID) == true) { aliases.Add(new KeyValuePair <string, int>(alias, languageID)); } else { result = false; } } // [String: Extension] [Int32: Language ID] [] [] ... [String: Null] for (string extension = file.ReadString(); extension != null; extension = file.ReadString()) { int languageID = file.ReadInt32(); if (usedLanguageIDs.Contains(languageID) == true) { extensions.Add(new KeyValuePair <string, int>(extension, languageID)); } else { result = false; } } // [String: Shebang String] [Int32: Language ID] [] [] ... [String: Null] for (string shebangString = file.ReadString(); shebangString != null; shebangString = file.ReadString()) { int languageID = file.ReadInt32(); if (usedLanguageIDs.Contains(languageID) == true) { shebangStrings.Add(new KeyValuePair <string, int>(shebangString, languageID)); } else { result = false; } } // [String: Ignored Extension] [] ... [String: Null] for (string ignoredExtension = file.ReadString(); ignoredExtension != null; ignoredExtension = file.ReadString()) { ignoredExtensions.Add(ignoredExtension); } } } catch { result = false; } finally { file.Close(); } if (result == false) { // Reset all the objects to empty versions. languages.Clear(); extensions.Clear(); shebangStrings.Clear(); ignoredExtensions.Clear(); } return(result); }
public static void Unpack(string file, string outputDirectoryPath, bool doList, bool doVerbose) { using (BinaryFile bf = new BinaryFile(file, BinaryFile.ByteOrder.LittleEndian, false)) { UInt32 fileSize = bf.ReadUInt32(); Log.Debug("fileSize: " + fileSize); bf.Seek(350, SeekOrigin.Begin); int snpidCount = bf.ReadInt32(); string snpid = bf.ReadString(snpidCount * 2, Encoding.Unicode); // snpid cannot have more than 4 characters (?!) if (snpidCount > 4) { snpidCount = 0; snpid = ""; bf.Seek(355, SeekOrigin.Begin); } else { bf.ReadBytes(25); } Log.Debug("snpid: " + snpid); int versionCount = bf.ReadInt32(); string version = bf.ReadString(versionCount * 2, Encoding.Unicode); Log.Debug("version: " + version); bf.ReadBytes(122); int presetNameCount = bf.ReadInt32(); string presetName = bf.ReadString(presetNameCount * 2, Encoding.Unicode); int presetNameRest = bf.ReadInt32(); Log.Debug("presetName: " + presetName); int companyNameCount = bf.ReadInt32(); string companyName = bf.ReadString(companyNameCount * 2, Encoding.Unicode); int companyNameRest = bf.ReadInt32(); Log.Debug("companyName: " + companyName); bf.ReadBytes(40); int libraryNameCount = bf.ReadInt32(); string libraryName = bf.ReadString(libraryNameCount * 2, Encoding.Unicode); int libraryNameRest = bf.ReadInt32(); Log.Debug("libraryName: " + libraryName); int typeCount = bf.ReadInt32(); if (typeCount != 0) { string type = bf.ReadString(typeCount * 2, Encoding.Unicode); int typeRest = bf.ReadInt32(); Log.Debug("type: " + type); } int number = bf.ReadInt32(); for (int i = 0; i < number * 2; i++) { int sCount = bf.ReadInt32(); string s = bf.ReadString(sCount * 2, Encoding.Unicode); Log.Debug(s); } bf.ReadBytes(249); UInt32 chunkSize = bf.ReadUInt32(); Log.Debug("chunkSize: " + chunkSize); string outputFileName = Path.GetFileNameWithoutExtension(file); string outputFilePath = Path.Combine(outputDirectoryPath, "NKI_CONTENT", outputFileName + ".bin"); IOUtils.CreateDirectoryIfNotExist(Path.Combine(outputDirectoryPath, "NKI_CONTENT")); var nks = new Nks(); nks.BinaryFile = bf; nks.SetKeys = new Dictionary <String, NksSetKey>(); NksEncryptedFileHeader header = new NksEncryptedFileHeader(); header.SetId = snpid.ToUpper(); header.KeyIndex = 0x100; header.Size = chunkSize; BinaryFile outBinaryFile = new BinaryFile(outputFilePath, BinaryFile.ByteOrder.LittleEndian, true); if (snpid == "") { if (!doList) { NKS.ExtractFileEntryToBf(nks, header, outBinaryFile); } } else { if (!doList) { NKS.ExtractEncryptedFileEntryToBf(nks, header, outBinaryFile); } } outBinaryFile.Close(); } }
// Group: Loading Functions // __________________________________________________________________________ /* Function: Load * Loads the information in <Project.nd>, returning whether it was successful. */ public bool Load(Path filename, out ProjectConfig projectConfig) { projectConfig = new ProjectConfig(PropertySource.PreviousRun); this.projectConfig = projectConfig; binaryFile = new BinaryFile(); bool result = true; try { // There were no file format changes between 2.0 and 2.0.2 but there were parsing changes and // bug fixes that require a full rebuild. if (binaryFile.OpenForReading(filename, "2.0.2") == false) { result = false; } else { // [Int32: Tab Width] // [Byte: Documented Only (0 or 1)] // [Byte: Auto Group (0 or 1)] // [Byte: Shrink Files (0 or 1)] projectConfig.TabWidth = binaryFile.ReadInt32(); projectConfig.TabWidthPropertyLocation = PropertySource.PreviousRun; projectConfig.DocumentedOnly = (binaryFile.ReadByte() == 1); projectConfig.DocumentedOnlyPropertyLocation = PropertySource.PreviousRun; projectConfig.AutoGroup = (binaryFile.ReadByte() == 1); projectConfig.AutoGroupPropertyLocation = PropertySource.PreviousRun; projectConfig.ShrinkFiles = (binaryFile.ReadByte() == 1); projectConfig.ShrinkFilesPropertyLocation = PropertySource.PreviousRun; // [String: Identifier] // [[Properties]] // ... // [String: null] string identifier = binaryFile.ReadString(); while (identifier != null) { LoadTarget(identifier); identifier = binaryFile.ReadString(); } } } catch { result = false; // Reset everything. projectConfig = new ProjectConfig(PropertySource.PreviousRun); } finally { binaryFile.Close(); } return(result); }
/* Function: Load * Loads the information in <Config.nd> and returns whether it was successful. If not all the out parameters will still * return objects, they will just be empty. */ public bool Load(Path filename, out List <Style> styles, out List <FileSourceInfo> fileSourceInfoList) { styles = new List <Style>(); fileSourceInfoList = new List <FileSourceInfo>(); BinaryFile binaryFile = new BinaryFile(); bool result = true; try { if (binaryFile.OpenForReading(filename, "2.0") == false) { result = false; } else { // [String: Style Path] // [String: Style Path] // ... // [String: null] string stylePath = binaryFile.ReadString(); while (stylePath != null) { if (stylePath.EndsWith(".css", StringComparison.OrdinalIgnoreCase)) { styles.Add(new Styles.CSSOnly(stylePath)); } else { styles.Add(new Styles.Advanced(stylePath)); } stylePath = binaryFile.ReadString(); } // [Int32: Source FileSource Number] [String: Source FileSource UniqueIDString] // [Int32: Source FileSource Number] [String: Source FileSource UniqueIDString] // ... // [Int32: 0] FileSourceInfo fileSourceInfo = new FileSourceInfo(); fileSourceInfo.Type = Files.InputType.Source; for (;;) { fileSourceInfo.Number = binaryFile.ReadInt32(); if (fileSourceInfo.Number == 0) { break; } fileSourceInfo.UniqueIDString = binaryFile.ReadString(); fileSourceInfoList.Add(fileSourceInfo); } // [Int32: Image FileSource Number] [String: Image FileSource UniqueIDString] // [Int32: Image FileSource Number] [String: Image FileSource UniqueIDString] // ... // [Int32: 0] fileSourceInfo.Type = Files.InputType.Image; for (;;) { fileSourceInfo.Number = binaryFile.ReadInt32(); if (fileSourceInfo.Number == 0) { break; } fileSourceInfo.UniqueIDString = binaryFile.ReadString(); fileSourceInfoList.Add(fileSourceInfo); } } } catch { result = false; } finally { binaryFile.Dispose(); } if (result == false) { styles.Clear(); fileSourceInfoList.Clear(); } return(result); }
public bool ReadFFP(BinaryFile binFile) { Version = binFile.ReadInt32(); ParameterCount = binFile.ReadInt32(); // parametercount = 334 // 24 bands with 13 parameters each = 312 // and then 22 parameters at the end Bands = new List <ProQ3Band>(); for (int i = 0; i < 24; i++) { var band = new ProQ3Band(); // 1 = Enabled, 0 = Disabled var fEnabled = binFile.ReadSingle(); band.Enabled = fEnabled == 1 ? true : false; Log.Debug("Band: {0} => enabled: {1}", i + 1, fEnabled); // unknown 1 var fUnknown1 = binFile.ReadSingle(); Log.Debug("Band: {0} => unknown 1: {1}", i + 1, fUnknown1); // frequency var fFreq = binFile.ReadSingle(); band.Frequency = FreqConvertBack(fFreq); Log.Debug("Band: {0} => freq: {1} => {2}", i + 1, fFreq, band.Frequency); // gain var fGain = binFile.ReadSingle(); band.Gain = fGain; // actual gain in dB Log.Debug("Band: {0} => gain: {1}", i + 1, fGain); // dynamic range (if band is dynamic) var fDynamicRange = binFile.ReadSingle(); band.DynamicRange = fDynamicRange; Log.Debug("Band: {0} => dynamic range: {1}", i + 1, fDynamicRange); // unknown 3 var fUnknown3 = binFile.ReadSingle(); Log.Debug("Band: {0} => unknown 3: {1}", i + 1, fUnknown3); // dynamic threshold in dB (1 = auto) - don't know how to convert this to dB // example numbers: // -1 dbFS 0.9833333 // -90 dbFS 0 // -20 dbFS 0.6666667 // -54 dbFS 0.17500602 var fDynamicThreshold = binFile.ReadSingle(); band.DynamicThreshold = fDynamicThreshold; Log.Debug("Band: {0} => dynamic threshold: {1} => {2}", i + 1, fDynamicThreshold, band.DynamicThreshold); // Q var fQ = binFile.ReadSingle(); band.Q = QConvertBack(fQ); Log.Debug("Band: {0} => Q: {1} => {2}", i + 1, fQ, band.Q); // 0 - 8 var fFilterType = binFile.ReadSingle(); switch (fFilterType) { case (float)ProQ3Shape.Bell: band.Shape = ProQ3Shape.Bell; break; case (float)ProQ3Shape.LowShelf: band.Shape = ProQ3Shape.LowShelf; break; case (float)ProQ3Shape.LowCut: band.Shape = ProQ3Shape.LowCut; break; case (float)ProQ3Shape.HighShelf: band.Shape = ProQ3Shape.HighShelf; break; case (float)ProQ3Shape.HighCut: band.Shape = ProQ3Shape.HighCut; break; case (float)ProQ3Shape.Notch: band.Shape = ProQ3Shape.Notch; break; case (float)ProQ3Shape.BandPass: band.Shape = ProQ3Shape.BandPass; break; case (float)ProQ3Shape.TiltShelf: band.Shape = ProQ3Shape.TiltShelf; break; case (float)ProQ3Shape.FlatTilt: band.Shape = ProQ3Shape.FlatTilt; break; default: throw new ArgumentOutOfRangeException(string.Format("Filter type is outside range: {0}", fFilterType)); } Log.Debug("Band: {0} => filterType: {1} => {2}", i + 1, fFilterType, band.Shape); // 0 - 9 var fFilterSlope = binFile.ReadSingle(); switch (fFilterSlope) { case (float)ProQ3Slope.Slope6dB_oct: band.Slope = ProQ3Slope.Slope6dB_oct; break; case (float)ProQ3Slope.Slope12dB_oct: band.Slope = ProQ3Slope.Slope12dB_oct; break; case (float)ProQ3Slope.Slope18dB_oct: band.Slope = ProQ3Slope.Slope18dB_oct; break; case (float)ProQ3Slope.Slope24dB_oct: band.Slope = ProQ3Slope.Slope24dB_oct; break; case (float)ProQ3Slope.Slope30dB_oct: band.Slope = ProQ3Slope.Slope30dB_oct; break; case (float)ProQ3Slope.Slope36dB_oct: band.Slope = ProQ3Slope.Slope36dB_oct; break; case (float)ProQ3Slope.Slope48dB_oct: band.Slope = ProQ3Slope.Slope48dB_oct; break; case (float)ProQ3Slope.Slope72dB_oct: band.Slope = ProQ3Slope.Slope72dB_oct; break; case (float)ProQ3Slope.Slope96dB_oct: band.Slope = ProQ3Slope.Slope96dB_oct; break; case (float)ProQ3Slope.SlopeBrickwall: band.Slope = ProQ3Slope.SlopeBrickwall; break; default: throw new ArgumentOutOfRangeException(string.Format("Filter slope is outside range: {0}", fFilterSlope)); } Log.Debug("Band: {0} => filterSlope: {1} => {2}", i + 1, fFilterSlope, band.Slope); // 0 = Left, 1 = Right, 2 = Stereo, 3 = Mid, 4 = Side var fFilterStereoPlacement = binFile.ReadSingle(); switch (fFilterStereoPlacement) { case (float)ProQ3StereoPlacement.Left: band.StereoPlacement = ProQ3StereoPlacement.Left; break; case (float)ProQ3StereoPlacement.Right: band.StereoPlacement = ProQ3StereoPlacement.Right; break; case (float)ProQ3StereoPlacement.Stereo: band.StereoPlacement = ProQ3StereoPlacement.Stereo; break; case (float)ProQ3StereoPlacement.Mid: band.StereoPlacement = ProQ3StereoPlacement.Mid; break; case (float)ProQ3StereoPlacement.Side: band.StereoPlacement = ProQ3StereoPlacement.Side; break; default: throw new ArgumentOutOfRangeException(string.Format("Filter stereo placement is outside range: {0}", fFilterStereoPlacement)); } Log.Debug("Band: {0} => filterStereoPlacement: {1} => {2}", i + 1, fFilterStereoPlacement, band.StereoPlacement); // unknown band parameters for (int j = 0; j < 2; j++) { var fUnknown = binFile.ReadSingle(); Log.Debug("Band: {0} => unknown {1}: {2}", i + 1, j + 5, fUnknown); } Bands.Add(band); } // read the remaining floats UnknownParameters = new List <float>(); int remainingParameterCount = ParameterCount - 13 * Bands.Count; for (int i = 0; i < remainingParameterCount; i++) { var fUnknown = binFile.ReadSingle(); Log.Debug("Param unknown {0}: {1}", i + 1, fUnknown); UnknownParameters.Add(fUnknown); } return(true); }
public bool ReadFFP(string filePath) { BinaryFile binFile = new BinaryFile(filePath, BinaryFile.ByteOrder.LittleEndian); string header = binFile.ReadString(4); if (header != "FQ2p") { return(false); } Version = binFile.ReadInt32(); ParameterCount = binFile.ReadInt32(); Bands = new List <ProQ2Band>(); for (int i = 0; i < 24; i++) { var band = new ProQ2Band(); // 1 = Enabled, 2 = Disabled band.Enabled = binFile.ReadSingle() == 1 ? true : false; band.Frequency = FreqConvertBack(binFile.ReadSingle()); band.Gain = binFile.ReadSingle(); // actual gain in dB band.Q = QConvertBack(binFile.ReadSingle()); // 0 - 7 var filterType = binFile.ReadSingle(); switch (filterType) { case (float)ProQ2Shape.Bell: band.Shape = ProQ2Shape.Bell; break; case (float)ProQ2Shape.LowShelf: band.Shape = ProQ2Shape.LowShelf; break; case (float)ProQ2Shape.LowCut: band.Shape = ProQ2Shape.LowCut; break; case (float)ProQ2Shape.HighShelf: band.Shape = ProQ2Shape.HighShelf; break; case (float)ProQ2Shape.HighCut: band.Shape = ProQ2Shape.HighCut; break; case (float)ProQ2Shape.Notch: band.Shape = ProQ2Shape.Notch; break; case (float)ProQ2Shape.BandPass: band.Shape = ProQ2Shape.BandPass; break; case (float)ProQ2Shape.TiltShelf: band.Shape = ProQ2Shape.TiltShelf; break; default: throw new ArgumentOutOfRangeException(string.Format("Filter type is outside range: {0}", filterType)); } // 0 - 8 var filterSlope = binFile.ReadSingle(); switch (filterSlope) { case (float)ProQSlope.Slope6dB_oct: band.Slope = ProQSlope.Slope6dB_oct; break; case (float)ProQSlope.Slope12dB_oct: band.Slope = ProQSlope.Slope12dB_oct; break; case (float)ProQSlope.Slope18dB_oct: band.Slope = ProQSlope.Slope18dB_oct; break; case (float)ProQSlope.Slope24dB_oct: band.Slope = ProQSlope.Slope24dB_oct; break; case (float)ProQSlope.Slope30dB_oct: band.Slope = ProQSlope.Slope30dB_oct; break; case (float)ProQSlope.Slope36dB_oct: band.Slope = ProQSlope.Slope36dB_oct; break; case (float)ProQSlope.Slope48dB_oct: band.Slope = ProQSlope.Slope48dB_oct; break; case (float)ProQSlope.Slope72dB_oct: band.Slope = ProQSlope.Slope72dB_oct; break; case (float)ProQSlope.Slope96dB_oct: band.Slope = ProQSlope.Slope96dB_oct; break; default: throw new ArgumentOutOfRangeException(string.Format("Filter slope is outside range: {0}", filterSlope)); } // 0 = Left, 1 = Right, 2 = Stereo var filterStereoPlacement = binFile.ReadSingle(); switch (filterStereoPlacement) { case (float)ProQ2StereoPlacement.LeftOrMid: band.StereoPlacement = ProQ2StereoPlacement.LeftOrMid; break; case (float)ProQ2StereoPlacement.RightOrSide: band.StereoPlacement = ProQ2StereoPlacement.RightOrSide; break; case (float)ProQ2StereoPlacement.Stereo: band.StereoPlacement = ProQ2StereoPlacement.Stereo; break; default: throw new ArgumentOutOfRangeException(string.Format("Filter stereo placement is outside range: {0}", filterStereoPlacement)); } Bands.Add(band); } // read the remaining floats // int remainingParameterCount = ParameterCount - 7 * Bands.Count; try { ProcessingMode = binFile.ReadSingle(); // Zero Latency: 0.0, Natural Phase: 1.0, Linear Phase: 2.0 ProcessingResolution = binFile.ReadSingle(); // 0 - 4, Medium ChannelMode = binFile.ReadSingle(); // 0 = Left/Right, 1 = Mid/Side GainScale = binFile.ReadSingle(); // 100% OutputLevel = binFile.ReadSingle(); // 0.0 dB, -1 to 1 (- Infinity to +36 dB , 0 = 0 dB) OutputPan = binFile.ReadSingle(); // Left 0 dB, Right: 0 dB, -1 to 1 (0 = middle) ByPass = binFile.ReadSingle(); // Not Bypassed OutputInvertPhase = binFile.ReadSingle(); // Normal AutoGain = binFile.ReadSingle(); // Off AnalyzerShowPreProcessing = binFile.ReadSingle(); // Disabled - 0: Off, 1: On AnalyzerShowPostProcessing = binFile.ReadSingle(); // Disabled - 0: Off, 1: On AnalyzerShowSidechain = binFile.ReadSingle(); // Disabled - 0: Off, 1: On AnalyzerRange = binFile.ReadSingle(); // Analyzer Range in dB. 0.0: 60dB, 1.0: 90dB, 2.0: 120dB AnalyzerResolution = binFile.ReadSingle(); // Analyzer Resolution. 0.0: Low, 1.0: Medium, 2.0: High, 3.00: Maximum AnalyzerSpeed = binFile.ReadSingle(); // Analyzer Speed. 0.0: Very Slow, 1.0: Slow, 2.0: Medium, 3.0 Fast, 4.0: Very Fast AnalyzerTilt = binFile.ReadSingle(); // Analyzer Tilt in dB/oct. 0.0: 0.0, 1.0: 1.5, 2.0: 3.0, 3.0: 4.5, 4.0: 6.0 AnalyzerFreeze = binFile.ReadSingle(); // 0: Off, 1: On SpectrumGrab = binFile.ReadSingle(); // Enabled DisplayRange = binFile.ReadSingle(); // 12dB ReceiveMidi = binFile.ReadSingle(); // Enabled SoloBand = binFile.ReadSingle(); // -1 SoloGain = binFile.ReadSingle(); // 0.00 } catch { } // check if mid/side if (ChannelMode == 1) { Bands.ForEach(b => b.ChannelMode = ProQ2ChannelMode.MidSide); } binFile.Close(); return(true); }
// Group: Loading Functions // __________________________________________________________________________ /* Function: Load * Loads the information in <Project.nd>, returning whether it was successful. */ public bool Load(Path filename, out ProjectConfig projectConfig) { projectConfig = new ProjectConfig(Source.PreviousRun); this.projectConfig = projectConfig; binaryFile = new BinaryFile(); bool result = true; try { if (binaryFile.OpenForReading(filename, "2.0") == false) { result = false; } else { // [Int32: Tab Width] // [Byte: Documented Only (0 or 1)] // [Byte: Auto Group (0 or 1)] // [Byte: Shrink Files (0 or 1)] projectConfig.TabWidth = binaryFile.ReadInt32(); projectConfig.TabWidthPropertyLocation = Source.PreviousRun; projectConfig.DocumentedOnly = (binaryFile.ReadByte() == 1); projectConfig.DocumentedOnlyPropertyLocation = Source.PreviousRun; projectConfig.AutoGroup = (binaryFile.ReadByte() == 1); projectConfig.AutoGroupPropertyLocation = Source.PreviousRun; projectConfig.ShrinkFiles = (binaryFile.ReadByte() == 1); projectConfig.ShrinkFilesPropertyLocation = Source.PreviousRun; // [String: Identifier] // [[Properties]] // ... // [String: null] string identifier = binaryFile.ReadString(); while (identifier != null) { LoadTarget(identifier); identifier = binaryFile.ReadString(); } } } catch { result = false; // Reset everything. projectConfig = new ProjectConfig(Source.PreviousRun); } finally { binaryFile.Close(); } return(result); }
public bool Read(string filePath) { if (File.Exists(filePath)) { string fileName = Path.GetFileNameWithoutExtension(filePath); PresetName = fileName; BinaryFile bFile = new BinaryFile(filePath, BinaryFile.ByteOrder.BigEndian); string firstChunkID = bFile.ReadString(4); // chunk ID = "FORM" int ckSize = bFile.ReadInt32(); string formType = bFile.ReadString(4); // read first data chunk string chunkID = bFile.ReadString(4); // if chunkID == "COMT" then CommentsChunk if (chunkID.Equals("COMT")) { long curposTmpComt = bFile.GetPosition(); bFile.Seek(curposTmpComt - 4); // CommentsChunk string chunkIDComt = bFile.ReadString(4); // chunk ID = "COMT" int chunkSizeComt = bFile.ReadInt32(); int numComments = bFile.ReadUInt16(); long curposTmpComt2 = bFile.GetPosition(); for (int i = 0; i < numComments; i++) { int commentTimestamp = (int)bFile.ReadUInt32(); string marker = bFile.ReadString(4); int count = (int)bFile.ReadByte(); comments.Add(bFile.ReadString(count)); } bFile.Seek(curposTmpComt2 + chunkSizeComt - 2); } string chunkID2 = bFile.ReadString(4); // if chunkID2 == "COMM" then CommonChunk if (chunkID2.Equals("COMM")) { long curposTmpComm = bFile.GetPosition(); bFile.Seek(curposTmpComm - 4); // CommonChunk string chunkIDComm = bFile.ReadString(4); // chunk ID = "COMM" int chunkSizeComm = bFile.ReadInt32(); channels = bFile.ReadInt16(); numSampleFrames = (int)bFile.ReadUInt32(); bitsPerSample = bFile.ReadInt16(); // read IEEE 80-bit extended double precision byte[] sampleRateBytes = bFile.ReadBytes(0, 10, BinaryFile.ByteOrder.LittleEndian); double sampleRateDouble = IEEE.ConvertFromIeeeExtended(sampleRateBytes); sampleRate = (int)sampleRateDouble; } string chunkID3 = bFile.ReadString(4); // if chunkID3 == "SSND" then SoundDataChunk if (chunkID3.Equals("SSND")) { long curposTmpSsnd = bFile.GetPosition(); bFile.Seek(curposTmpSsnd - 4); // SoundDataChunk string chunkIDSsnd = bFile.ReadString(4); // chunk ID = "SSND" int chunkSizeSsnd = bFile.ReadInt32(); int offset = (int)bFile.ReadUInt32(); int blocksize = (int)bFile.ReadUInt32(); byte[] data = bFile.ReadBytes(offset, chunkSizeSsnd - 8, BinaryFile.ByteOrder.LittleEndian); // swap waveform data WaveformData = SwapAiffEndian(data); } bFile.Close(); return(true); } else { return(false); } }
/* Function: Load * Loads <Files.nd> and returns whether it was successful. If it wasn't it will still return valid objects, they will just * be empty. */ public bool Load(Path filename, out IDObjects.Manager <File> files) { files = new IDObjects.Manager <File>(Config.Manager.KeySettingsForPaths, false); BinaryFile binaryFile = new BinaryFile(); bool result = true; try { // We'll continue to handle 2.0 files in 2.0.2 since it's easy enough if (binaryFile.OpenForReading(filename, "2.0") == false) { result = false; } else { // [Int32: ID] // [String: Path] // [Byte: Type] // [Int64: Last Modification in Ticks or 0] // (if image) // [UInt32: Width in Pixels or 0 if unknown] // [UInt32: Height in Pixels or 0 if unknown] // ... // [Int32: 0] int id; Path path; FileType type; DateTime lastModification; File file; uint width, height; for (;;) { id = binaryFile.ReadInt32(); if (id == 0) { break; } path = binaryFile.ReadString(); type = (FileType)binaryFile.ReadByte(); lastModification = new DateTime(binaryFile.ReadInt64()); if (type == FileType.Image) { if (binaryFile.Version < "2.0.2") { width = 0; height = 0; } else { width = binaryFile.ReadUInt32(); height = binaryFile.ReadUInt32(); } if (width == 0 || height == 0) { // If this file is from a different version of Natural Docs, no matter which one, reset the last modification // time so they'll be reparsed and take another stab at getting the dimensions if (binaryFile.Version != Engine.Instance.Version) { lastModification = new DateTime(0); } file = new ImageFile(path, lastModification); } else { file = new ImageFile(path, lastModification, width, height); } } else { file = new File(path, type, lastModification); } file.ID = id; files.Add(file); } } } catch { result = false; } finally { binaryFile.Close(); } if (result == false) { files.Clear(); } return(result); }
/* Function: Load * Loads the information in <Comments.nd> into a <Config> object, returning whether it was successful. If it was not * config will be null. */ public bool Load(Path filename, out Config config) { BinaryFile file = new BinaryFile(); try { if (file.OpenForReading(filename, "2.2") == false) { config = null; return(false); } else { config = new Config(); // [String: Tag Name] // [Int32: ID] // ... // [String: null] string tagName = file.ReadString(); while (tagName != null) { Tag tag = new Tag(tagName); tag.ID = file.ReadInt32(); config.AddTag(tag); tagName = file.ReadString(); } // [String: Comment Type Name] // [Int32: ID] // [String: Display Name] // [String: Plural Display Name] // [String: Simple Identifier] // [Byte: Scope] // [Byte: Flags] // ... // [String: null] string commentTypeName = file.ReadString(); while (commentTypeName != null) { CommentType commentType = new CommentType(commentTypeName); commentType.ID = file.ReadInt32(); commentType.DisplayName = file.ReadString(); commentType.PluralDisplayName = file.ReadString(); commentType.SimpleIdentifier = file.ReadString(); // We don't have to validate the scope and flag values because they're only used to compare to the text file // versions, which are validated. If these are invalid they'll just show up as changed. commentType.Scope = (CommentType.ScopeValue)file.ReadByte(); commentType.Flags = (CommentType.FlagValue)file.ReadByte(); config.AddCommentType(commentType); commentTypeName = file.ReadString(); } // [String: Keyword] // [Byte: Plural (0 or 1)] // [Int32: Comment Type ID] // [Int32: Language ID or 0 if agnostic] // ... // [String: null] string keywordName = file.ReadString(); while (keywordName != null) { var keywordDefinition = new KeywordDefinition(keywordName); keywordDefinition.Plural = (file.ReadByte() != 0); keywordDefinition.CommentTypeID = file.ReadInt32(); int languageID = file.ReadInt32(); if (languageID != 0) { keywordDefinition.LanguageID = languageID; } config.AddKeywordDefinition(keywordDefinition); keywordName = file.ReadString(); } } } catch { config = null; return(false); } finally { file.Close(); } return(true); }