private static void WriteAudioData(BinaryFile binaryFile, float[] audioData, int length) { for (int i = 0; i < audioData.Length; i++) { binaryFile.Write(audioData[i]); } // pad if neccesary if (length > audioData.Length) { for (int i = 0; i < length - audioData.Length; i++) { binaryFile.Write(0); } } }
/* * Native Formats * Number of Bits MATLAB Data Type Data Range * 8 uint8 (unsigned integer) 0 <= y <= 255 * 16 int16 (signed integer) -32768 <= y <= +32767 * 24 int32 (signed integer) -2^23 <= y <= 2^23-1 * 32 single (floating point) -1.0 <= y < +1.0 * * typedef uint8_t u8_t; ///< unsigned 8-bit value (0 to 255) * typedef int8_t s8_t; ///< signed 8-bit value (-128 to +127) * typedef uint16_t u16_t; ///< unsigned 16-bit value (0 to 65535) * typedef int16_t s16_t; ///< signed 16-bit value (-32768 to 32767) * typedef uint32_t u32_t; ///< unsigned 32-bit value (0 to 4294967296) * typedef int32_t s32_t; ///< signed 32-bit value (-2147483648 to +2147483647) */ public static void Read8Bit(BinaryFile wavfile, double[][] sound, int samplecount, int channels) { #if DEBUG Console.Write("Read8Bit...\n"); #endif for (int i = 0; i < samplecount; i++) { for (int ic = 0; ic < channels; ic++) { byte @byte = wavfile.ReadByte(); sound[ic][i] = (double) @byte / 128.0 - 1.0; } } }
public static void Read16Bit(BinaryFile wavfile, double[][] sound, int samplecount, int channels) { #if DEBUG Console.Write("Read16Bit...\n"); #endif for (int i = 0; i < samplecount; i++) { for (int ic = 0; ic < channels; ic++) { double d = (double) wavfile.ReadInt16(); d = d / 32768.0; sound[ic][i] = d; } } }
public static void Write16Bit(BinaryFile wavfile, double[][] sound, int samplecount, int channels) { #if DEBUG Console.Write("Write16Bit...\n"); #endif for (int i = 0; i<samplecount; i++) { for (int ic = 0;ic<channels;ic++) { int val = Util.RoundToClosestInt(sound[ic][i] * 32768); if (val > 32767) val = 32767; if (val < -32768) val = -32768; wavfile.Write((Int16) val); } } }
public static void Main(string[] args) { string inLeft = @"F:\SAMPLES\IMPULSE RESPONSES\PER IVAR IR SAMPLES\ALTIVERB-QUAD-IMPULSE-RESPONSES\Scoring Stages (Orchestral Studios)_Todd-AO - California US_st to st wide mics at 18m90_L.wav"; string inRight = @"F:\SAMPLES\IMPULSE RESPONSES\PER IVAR IR SAMPLES\ALTIVERB-QUAD-IMPULSE-RESPONSES\Scoring Stages (Orchestral Studios)_Todd-AO - California US_st to st wide mics at 18m90_R.wav"; float[] channel1; float[] channel2; float[] channel3; float[] channel4; AudioUtilsNAudio.SplitStereoWaveFileToMono(inLeft, out channel1, out channel2); AudioUtilsNAudio.SplitStereoWaveFileToMono(inRight, out channel3, out channel4); // find out what channel is longest int maxLength = Math.Max(channel1.Length, channel3.Length); string outputFile = @"Scoring Stages (Orchestral Studios)_Todd-AO - California US_st to st wide mics at 18m90V2.sir"; //string cfh_data = @"abe6f4214362.34U4T9yaBCCDEuyH0uCm7T6Pf.z+PqR.kBAoHEfz3DlPB4lX.K4XirMP+3WCzJZ6RYE0ka38ty94e5j858dEG1RUZlT3iZV2EATQgrjIV5ixyF5zA0qasZdXlJpZ8FtlNjwomlnU8lHn+JhPP48khE9n1HPSpVyoJhg5itqiqqKp600.vKJEevIQJ4fXS0aTksgilV6fMkL4wNFPLDn33w5irgZ7lpiNZaJe791OXu1ATcghs1bHHwzElL49JBlnXKYBBeeT8QCedFNXTRbHdVznj7XbHjFhSlLFaURBSgnoA1RJ7UWAwYQSCSew407fANeNiyoYvERkkO.1PVR0vMSTEqnZihvsR6eC5ammIKKcBl.NPeBmsPpDLBjimqMfQB15NVIEpXEZfXflcpdxcd77xh56HaQM9Shz7rIRJa4p+EHo0YfjCv3BeKI87QR6yGIW1qI+hIdM99OMVIuF+7+KqzUe.bo2V9C"; string cfh_data = @"abe6f42143 "; BinaryFile binaryFile = new BinaryFile(outputFile, BinaryFile.ByteOrder.LittleEndian, true); binaryFile.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); binaryFile.Write("\n\n"); binaryFile.Write("<SirImpulseFile version=\"2.1\" cfh_data=\""); binaryFile.Write(cfh_data); binaryFile.Write("\"/>"); binaryFile.Write("\r\n"); binaryFile.Write((byte)0); WriteAudioBlock(binaryFile, channel1, maxLength, "0"); WriteAudioBlock(binaryFile, channel2, maxLength, "1"); WriteAudioBlock(binaryFile, channel3, maxLength, "2"); WriteAudioBlock(binaryFile, channel4, maxLength, "3"); binaryFile.Close(); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
public static void Write8Bit(BinaryFile wavfile, double[][] sound, int samplecount, int channels) { #if DEBUG Console.Write("Write8Bit...\n"); #endif for (int i = 0; i < samplecount; i++) { for (int ic = 0; ic < channels; ic++) { int val = Util.RoundToClosestInt((sound[ic][i] + 1) * 128); if (val > 255) val = 255; if (val < 0) val = 0; byte @byte = (byte) val; wavfile.Write(@byte); } } }
/// <summary> /// Seek in BinaryFile until pattern is found, return start index /// </summary> /// <param name="binaryFile">binaryFile</param> /// <param name="pattern">byte pattern to find</param> /// <param name="offset">offset to seek to (if > 0)</param> /// <param name="maxEndIndex">optional end index within the BinaryFile</param> /// <returns>index where found (BinaryFile position will be at this index)</returns> public static int IndexOf(this BinaryFile binaryFile, byte[] pattern, int offset, int maxEndIndex = -1) { // seek to offset if (offset > 0 && offset < binaryFile.Length) { binaryFile.Seek(offset, SeekOrigin.Begin); } int success = 0; long remainingBytes = binaryFile.Length - binaryFile.Position; if (maxEndIndex > 0) { remainingBytes = Math.Min(maxEndIndex, remainingBytes); } for (int i = 0; i < (int)remainingBytes; i++) { var b = binaryFile.ReadByte(); if (b == pattern[success]) { success++; } else { success = 0; } if (pattern.Length == success) { int index = (int)(binaryFile.Position - pattern.Length); binaryFile.Seek(index, SeekOrigin.Begin); return(index); } } return(-1); }
private static void WriteAudioBlock(BinaryFile binaryFile, float[] audioData, int length, string channel) { binaryFile.Write("BLOCK"); binaryFile.Write((byte)0); string lengthText = length.ToString(); int lenghtTextLength = lengthText.Length; int blockLength = length*4+lenghtTextLength+13; string blockLengthText = blockLength.ToString(); binaryFile.Write(blockLengthText); // length from where "AUDIODATA" starts binaryFile.Write((byte)0); binaryFile.Write("AUDIODATA"); binaryFile.Write((byte)0); binaryFile.Write(channel); // channel text ("0" - "3") binaryFile.Write((byte)0); binaryFile.Write(lengthText); binaryFile.Write((byte)0); // Example: // channel 1 mono (L - 1) // length 701444 bytes / 4 bytes per float = 175361 float's WriteAudioData(binaryFile, audioData, length); }
// constructor with byte array public FXP(byte[] values) { BinaryFile bf = new BinaryFile(values, BinaryFile.ByteOrder.BigEndian); ReadFXP(bf); }
public bool ReadFXP(FXP fxp, string filePath="") { 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 false; }
public static double[][] ReadBMPGrayscale(string filePath) { double[][] image; var bmpfile = new BinaryFile(filePath); // "BM" format tag check if (!"BM".Equals(bmpfile.ReadString(2))) { Console.Error.WriteLine("This file is not in BMP format"); return(null); } bmpfile.Seek(8, SeekOrigin.Current); // skipping useless tags int offset = (int)bmpfile.ReadUInt32() - 54; // header offset bmpfile.Seek(4, SeekOrigin.Current); // skipping useless tags int x = (int)bmpfile.ReadUInt32(); int y = (int)bmpfile.ReadUInt32(); bmpfile.Seek(2, SeekOrigin.Current); // skipping useless tags int bitDepth = bmpfile.ReadUInt16(); int numBytes = bitDepth / 8; bmpfile.Seek(24 + offset, SeekOrigin.Current); // skipping useless tags // image allocation image = new double[y][]; // initialise jagged array for (int iy = 0; iy < y; iy++) { image[iy] = new double[x]; } // calculate zero bytes (bytes to skip at the end of each bitmap line) int zerobytes = (byte)(4 - ((x * numBytes) & numBytes)); if (zerobytes == 4) { zerobytes = 0; } // backwards reading for (int iy = y - 1; iy != -1; iy--) { for (int ix = 0; ix < x; ix++) { for (int ic = numBytes - 1; ic != -1; ic--) { int val = bmpfile.ReadByte(); if (ic == 0 && numBytes == 4) { // if reading 32 bit, ignore the alpha bit } else { // Conversion to grey by averaging the three channels image[iy][ix] += (double)val * (1.0 / (255.0 * 3.0)); } } } bmpfile.Seek(zerobytes, SeekOrigin.Current); // skipping padding bytes } bmpfile.Close(); return(image); }
public static bool Convert2FabfilterProQ(REWEQFilters filters, string filePath) { List<ProQBand> proQBands = new List<ProQBand>(); foreach (REWEQBand filter in filters) { ProQBand band = new ProQBand(); band.FilterFreq = filter.FilterFreq; band.FilterGain = filter.FilterGain; band.FilterQ = filter.FilterQ; band.Enabled = filter.Enabled; switch (filter.FilterType) { case REWEQFilterType.PK: band.FilterType = ProQFilterType.Bell; break; case REWEQFilterType.LP: band.FilterType = ProQFilterType.HighCut; break; case REWEQFilterType.HP: band.FilterType = ProQFilterType.LowCut; break; case REWEQFilterType.LS: band.FilterType = ProQFilterType.LowShelf; break; case REWEQFilterType.HS: band.FilterType = ProQFilterType.HighShelf; break; default: band.FilterType = ProQFilterType.Bell; break; } band.FilterLPHPSlope = ProQLPHPSlope.Slope24dB_oct; band.FilterStereoPlacement = ProQStereoPlacement.Stereo; proQBands.Add(band); } BinaryFile binFile = new BinaryFile(filePath, BinaryFile.ByteOrder.LittleEndian, true); binFile.Write("FPQr"); binFile.Write((int) 2); binFile.Write((int) 180); binFile.Write((float) proQBands.Count); for (int i = 0; i < 24; i++) { if (i < proQBands.Count) { binFile.Write((float) FreqConvert(proQBands[i].FilterFreq)); binFile.Write((float) proQBands[i].FilterGain); binFile.Write((float) QConvert(proQBands[i].FilterQ)); binFile.Write((float) proQBands[i].FilterType); binFile.Write((float) proQBands[i].FilterLPHPSlope); binFile.Write((float) proQBands[i].FilterStereoPlacement); binFile.Write((float) (proQBands[i].Enabled ? 1 : 0) ); } else { binFile.Write((float) FreqConvert(1000)); binFile.Write((float) 0); binFile.Write((float) QConvert(1)); binFile.Write((float) ProQFilterType.Bell); binFile.Write((float) ProQLPHPSlope.Slope24dB_oct); binFile.Write((float) ProQStereoPlacement.Stereo); binFile.Write((float) 1); } } binFile.Write((float) 0); // float output_gain; // -1 to 1 (- Infinity to +36 dB , 0 = 0 dB) binFile.Write((float) 0); // float output_pan; // -1 to 1 (0 = middle) binFile.Write((float) 2); // float display_range; // 0 = 6dB, 1 = 12dB, 2 = 30dB, 3 = 3dB binFile.Write((float) 0); // float process_mode; // 0 = zero latency, 1 = lin.phase.low - medium - high - maximum binFile.Write((float) 0); // float channel_mode; // 0 = Left/Right, 1 = Mid/Side binFile.Write((float) 0); // float bypass; // 0 = No bypass binFile.Write((float) 0); // float receive_midi; // 0 = Enabled? binFile.Write((float) 3); // float analyzer; // 0 = Off, 1 = Pre, 2 = Post, 3 = Pre+Post binFile.Write((float) 1); // float analyzer_resolution; // 0 - 3 : low - medium[x] - high - maximum binFile.Write((float) 2); // float analyzer_speed; // 0 - 3 : very slow, slow, medium[x], fast binFile.Write((float) -1); // float solo_band; // -1 binFile.Close(); return true; }
public void Write(BinaryFile bf) { Write(bf, Content, XmlDocument); }
private static FXP ReadFXP(BinaryFile bf) { string ChunkMagic = bf.ReadString(4); if (ChunkMagic != "CcnK") { throw new FormatException(string.Format("Error reading file. Missing preset header information {0}", ChunkMagic)); } var fxp = new FXP(); int ByteSize = bf.ReadInt32(); string FxMagic = bf.ReadString(4); if (FxMagic == "FBCh") { // Bank (.fxb) with chunk (magic = 'FBCh') var chunkSet = new FxChunkSet(); chunkSet.ChunkMagic = ChunkMagic; chunkSet.ByteSize = ByteSize; chunkSet.FxMagic = FxMagic; chunkSet.Version = bf.ReadInt32(); chunkSet.FxID = bf.ReadString(4); chunkSet.FxVersion = bf.ReadInt32(); chunkSet.NumPrograms = bf.ReadInt32(); chunkSet.Future = bf.ReadString(128).TrimEnd('\0'); chunkSet.ChunkSize = bf.ReadInt32(); // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format chunkSet.ChunkData = bf.ReadBytes(0, chunkSet.ChunkSize, BinaryFile.ByteOrder.LittleEndian); // read the xml chunk into memory try { if (chunkSet.ChunkData != null) { var xmlDocument = new XmlDocument(); var chunkAsString = Encoding.UTF8.GetString(chunkSet.ChunkData); xmlDocument.LoadXml(chunkAsString); fxp.XmlDocument = xmlDocument; } } catch (XmlException) { } fxp.Content = chunkSet; } else if (FxMagic == "FPCh") { // Preset (Program) (.fxp) with chunk (magic = 'FPCh') var programSet = new FxProgramSet(); programSet.ChunkMagic = ChunkMagic; programSet.ByteSize = ByteSize; programSet.FxMagic = FxMagic; programSet.Version = bf.ReadInt32(); programSet.FxID = bf.ReadString(4); programSet.FxVersion = bf.ReadInt32(); programSet.NumPrograms = bf.ReadInt32(); programSet.Name = bf.ReadString(28).TrimEnd('\0'); programSet.ChunkSize = bf.ReadInt32(); // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format programSet.ChunkData = bf.ReadBytes(0, programSet.ChunkSize, BinaryFile.ByteOrder.LittleEndian); // read the xml chunk into memory try { if (programSet.ChunkData != null) { var xmlDocument = new XmlDocument(); var chunkAsString = Encoding.UTF8.GetString(programSet.ChunkData); xmlDocument.LoadXml(chunkAsString); fxp.XmlDocument = xmlDocument; } } catch (XmlException) { } fxp.Content = programSet; } else if (FxMagic == "FxCk") { // For Preset (Program) (.fxp) without chunk (magic = 'FxCk') var program = new FxProgram(); program.ChunkMagic = ChunkMagic; program.ByteSize = ByteSize; program.FxMagic = FxMagic; program.Version = bf.ReadInt32(); program.FxID = bf.ReadString(4); program.FxVersion = bf.ReadInt32(); program.NumParameters = bf.ReadInt32(); program.ProgramName = bf.ReadString(28).TrimEnd('\0'); // variable no. of parameters program.Parameters = new float[program.NumParameters]; for (int i = 0; i < program.NumParameters; i++) { program.Parameters[i] = bf.ReadSingle(); } fxp.Content = program; } else if (FxMagic == "FxBk") { // For bank (.fxb) without chunk (magic = 'FxBk') var set = new FxSet(); set.ChunkMagic = ChunkMagic; set.ByteSize = ByteSize; set.FxMagic = FxMagic; set.Version = bf.ReadInt32(); set.FxID = bf.ReadString(4); set.FxVersion = bf.ReadInt32(); set.NumPrograms = bf.ReadInt32(); set.Future = bf.ReadString(128).TrimEnd('\0'); // variable no. of programs set.Programs = new FxProgram[set.NumPrograms]; for (int p = 0; p < set.NumPrograms; p++) { var content = ReadFXP(bf).Content; if (content is FxProgram) { set.Programs[p] = (FxProgram)content; } } fxp.Content = set; } return(fxp); }
public static void Write32BitFloat(BinaryFile wavfile, double[][] sound, int samplecount, int channels) { #if DEBUG Console.Write("Write32BitFloat...\n"); #endif for (int i = 0; i < samplecount; i++) { for (int ic = 0; ic < channels; ic++) { wavfile.Write((float)sound[ic][i]); } } }
/** * Reads raw data into the buffer. * * @param fs input file stream * @param buffer pointer to data array * @param bufferLength data buffer size */ private void LoadRawData(ref BinaryFile fs, short[] buffer, UInt32 bufferLength) { for (int i = 0; i < bufferLength; i++) { buffer[i] = (short) fs.ReadInt16(); } }
public static void Write32Bit(BinaryFile wavfile, double[][] sound, int samplecount, int channels) { #if DEBUG Console.Write("Write32Bit...\n"); #endif for (int i = 0; i < samplecount; i++) { for (int ic = 0; ic < channels; ic++) { int val = Util.RoundToClosestInt(sound[ic][i] * 2147483648); if (val > 2147483647) val = 2147483647; if (val < -2147483648) val = -2147483648; wavfile.Write((int) val); } } }
public static void Read32BitFloat(BinaryFile wavfile, double[][] sound, int samplecount, int channels) { #if DEBUG Console.Write("Read32BitFloat...\n"); #endif for (int i = 0; i < samplecount; i++) { for (int ic = 0; ic < channels; ic++) { double d = (double) wavfile.ReadSingle(); sound[ic][i] = d; } } }
public static void Read8Bit(BinaryFile wavfile, float[][] sound, Int32 samplecount, Int32 channels) { Int32 i = new Int32(); Int32 ic = new Int32(); byte @byte = new byte(); #if DEBUG Console.Write("Read8Bit...\n"); #endif for (i = 0; i<samplecount; i++) { for (ic = 0;ic<channels;ic++) { @byte = wavfile.ReadByte(); sound[ic][i] = (float) @byte/128.0f - 1.0f; } } }
public static double[][] BMPRead(BinaryFile bmpfile, ref int y, ref int x) { int iy = 0; // various iterators int ix = 0; int ic = 0; int offset = 0; double[][] image; byte zerobytes = new byte(); byte val = new byte(); #if DEBUG Console.Write("BMPRead...\n"); #endif if (Util.ReadUInt16(bmpfile) != 19778) // "BM" format tag check { Console.Error.WriteLine("This file is not in BMP format\n"); Util.ReadUserReturn(); Environment.Exit(1); } bmpfile.Seek(8, SeekOrigin.Current); // skipping useless tags offset = (int) Util.ReadUInt32(bmpfile) - 54; // header offset bmpfile.Seek(4, SeekOrigin.Current); // skipping useless tags x = (int) Util.ReadUInt32(bmpfile); y = (int) Util.ReadUInt32(bmpfile); bmpfile.Seek(2, SeekOrigin.Current); // skipping useless tags if (Util.ReadUInt16(bmpfile) != 24) // Only format supported { Console.Error.WriteLine("Wrong BMP format, BMP images must be in 24-bit colour\n"); Util.ReadUserReturn(); Environment.Exit(1); } bmpfile.Seek(24+offset, SeekOrigin.Current); // skipping useless tags // image allocation image = new double[y][]; for (iy = 0; iy< y; iy++) { image[iy] = new double[x]; } zerobytes = (byte)(4 - ((x *3) & 3)); if (zerobytes == 4) { zerobytes = 0; } // backwards reading for (iy = y-1; iy!=-1; iy--) { for (ix = 0; ix< x; ix++) { for (ic = 2;ic!=-1;ic--) { val = bmpfile.ReadByte(); image[iy][ix] += (double) val * (1.0/(255.0 * 3.0)); // Conversion to grey by averaging the three channels } } bmpfile.Seek(zerobytes, SeekOrigin.Current); // skipping padding bytes } bmpfile.Close(); return image; }
public static void BMPWrite(BinaryFile bmpfile, double[][] image, int y, int x) { int i = 0; // various iterators int iy = 0; int ix = 0; int ic = 0; int filesize = 0; int imagesize = 0; byte zerobytes = new byte(); byte val = new byte(); const byte zero = 0; double vald; #if DEBUG Console.Write("BMPWrite...\n"); #endif zerobytes = (byte) (4 - ((x *3) & 3)); // computation of zero bytes if (zerobytes == 4) { zerobytes = 0; } #region Tags filesize = 56 + ((x *3)+zerobytes) * y; imagesize = 2 + ((x *3)+zerobytes) * y; Util.WriteUInt16(19778, bmpfile); Util.WriteUInt32((uint)filesize, bmpfile); Util.WriteUInt32(0, bmpfile); Util.WriteUInt32(54, bmpfile); Util.WriteUInt32(40, bmpfile); Util.WriteUInt32((uint)x, bmpfile); Util.WriteUInt32((uint)y, bmpfile); Util.WriteUInt16(1, bmpfile); Util.WriteUInt32(24, bmpfile); Util.WriteUInt16(0, bmpfile); Util.WriteUInt32((uint)imagesize, bmpfile); Util.WriteUInt32(2834, bmpfile); Util.WriteUInt32(2834, bmpfile); Util.WriteUInt32(0, bmpfile); Util.WriteUInt32(0, bmpfile); #endregion Tags // backwards writing for (iy = y-1; iy!=-1; iy--) { for (ix = 0; ix<x; ix++) { // define color vald = image[iy][ix] * 255.0; if (vald > 255.0) { vald = 255.0; } if (vald < 0.0) { vald = 0.0; } val = (byte) vald; for (ic = 2; ic!=-1; ic--) { bmpfile.Write(val); } } // write padding bytes for (i = 0; i<zerobytes; i++) { bmpfile.Write(zero); } } Util.WriteUInt16(0, bmpfile); bmpfile.Close(); #if DEBUG Console.Write("Image size : {0:D}x{1:D}\n", x, y); #endif }
public void ReadFXP(BinaryFile bf) { ChunkMagic = bf.ReadString(4); if (ChunkMagic != "CcnK") { Console.Out.WriteLine("Error reading file. Missing preset header information."); } ByteSize = bf.ReadInt32(); FxMagic = bf.ReadString(4); if (FxMagic == "FBCh") { // Bank with Chunk Data Version = bf.ReadInt32(); FxID = bf.ReadString(4); FxVersion = bf.ReadInt32(); ProgramCount = bf.ReadInt32(); Future = bf.ReadString(128); ChunkSize = bf.ReadInt32(); // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format chunkDataByteArray = new byte[ChunkSize]; chunkDataByteArray = bf.ReadBytes(0, ChunkSize, BinaryFile.ByteOrder.LittleEndian); chunkData = BinaryFile.ByteArrayToString(chunkDataByteArray); } else if (FxMagic == "FPCh") { // Preset with Chunk Data Version = bf.ReadInt32(); FxID = bf.ReadString(4); FxVersion = bf.ReadInt32(); ProgramCount = bf.ReadInt32(); Name = bf.ReadString(28); ChunkSize = bf.ReadInt32(); // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format chunkDataByteArray = new byte[ChunkSize]; chunkDataByteArray = bf.ReadBytes(0, ChunkSize, BinaryFile.ByteOrder.LittleEndian); chunkData = BinaryFile.ByteArrayToString(chunkDataByteArray); } else if (FxMagic == "FxCk") { // For Preset (Program) (.fxp) without chunk (magic = 'FxCk') Version = bf.ReadInt32(); FxID = bf.ReadString(4); FxVersion = bf.ReadInt32(); ParameterCount = bf.ReadInt32(); Name = bf.ReadString(28); // variable no. of parameters Parameters = new float[ParameterCount]; for (int i = 0; i < ParameterCount; i++) { Parameters[i] = bf.ReadSingle(); } } bf.Close(); // read the xml chunk into memory XmlDocument = new XmlDocument(); try { if (chunkData != null) { XmlDocument.LoadXml(chunkData); } } catch (XmlException) { //Console.Out.WriteLine("No XML found"); } }
public static double[][] ReadWaveFile(BinaryFile wavfile, ref int channels, ref int samplecount, ref int samplerate) { double[][] sound; int i = 0; int ic = 0; var tag = new int[13]; // integers int RIFF = BinaryFile.StringToInt32("RIFF"); // 1179011410 int WAVE = BinaryFile.StringToInt32("WAVE"); // 1163280727 int FMT = BinaryFile.StringToInt32("fmt "); // 544501094 int DATA = BinaryFile.StringToInt32("data"); // 1635017060 // Size Description Value // tag[0] 4 RIFF Header RIFF (1179011410) // tag[1] 4 RIFF data size // tag[2] 4 form-type (WAVE etc) (1163280727) // tag[3] 4 Chunk ID "fmt " (0x666D7420) = 544501094 // tag[4] 4 Chunk Data Size 16 + extra format bytes // long chunkSize; // tag[5] 2 Compression code 1 - 65,535 // short wFormatTag; // tag[6] 2 Number of channels 1 - 65,535 // tag[7] 4 Sample rate 1 - 0xFFFFFFFF // tag[8] 4 Average bytes per second 1 - 0xFFFFFFFF // tag[9] 2 Block align 1 - 65,535 (4) // tag[10] 2 Significant bits per sample 2 - 65,535 (32) // tag[11] 4 IEEE = 1952670054 (0x74636166) = fact chunk // PCM = 1635017060 (0x61746164) (datachunk = 1635017060) // tag[12] 4 IEEE = 4 , PCM = 5292000 (0x0050BFE0) #if DEBUG Console.Write("ReadWaveFile...\n"); #endif // tag reading for (i = 0; i < 13; i++) { tag[i] = 0; if ((i == 5) || (i == 6) || (i == 9) || (i == 10)) { tag[i] = Util.ReadUInt16(wavfile); } else { tag[i] = (int) Util.ReadUInt32(wavfile); } } #region File format checking if (tag[0] != RIFF || tag[2] != WAVE) { Console.Error.WriteLine("This file is not in WAVE format\n"); Util.ReadUserReturn(); Environment.Exit(1); } // fmt tag, chunkSize and data tag if (tag[3] != FMT || tag[4] != 16 || tag[11] != DATA) { Console.Error.WriteLine("This WAVE file format is not currently supported\n"); Util.ReadUserReturn(); Environment.Exit(1); } // bits per sample if (tag[10] == 24) { Console.Error.WriteLine("24 bit PCM WAVE files are not currently supported\n"); Util.ReadUserReturn(); Environment.Exit(1); } // wFormatTag if (tag[5] != WAVE_FORMAT_PCM && tag[5] != WAVE_FORMAT_IEEE_FLOAT) { Console.Error.WriteLine("Non PCM WAVE files are not currently supported\n"); Util.ReadUserReturn(); Environment.Exit(1); } #endregion File format checking channels = tag[6]; samplecount = tag[12] / (tag[10] / 8) / channels; samplerate = tag[7]; sound = new double[channels][]; for (ic = 0; ic < channels; ic++) { sound[ic] = new double[samplecount]; } #region Data loading if (tag[10] == 8) { Read8Bit(wavfile, sound, samplecount, channels); } if (tag[10] == 16) { Read16Bit(wavfile, sound, samplecount, channels); } if (tag[10] == 32) { if (tag[5] == WAVE_FORMAT_PCM) { Read32Bit(wavfile, sound, samplecount, channels); } else if (tag[5] == WAVE_FORMAT_IEEE_FLOAT) { Read32BitFloat(wavfile, sound, samplecount, channels); } } #endregion Data loading wavfile.Close(); return sound; }
/** * Reads file header into the struct. * * @param fs input file stream * @see WaveFile::hdr */ private void LoadHeader(ref BinaryFile fs) { hdr.RIFF = fs.ReadString(4); hdr.DataLength = fs.ReadUInt32(); hdr.WAVE = fs.ReadString(4); hdr.fmt_ = fs.ReadString(4); hdr.SubBlockLength = fs.ReadUInt32(); hdr.formatTag = fs.ReadUInt16(); hdr.Channels = fs.ReadUInt16(); hdr.SampFreq = fs.ReadUInt32(); hdr.BytesPerSec = fs.ReadUInt32(); hdr.BytesPerSamp = fs.ReadUInt16(); hdr.BitsPerSamp = fs.ReadUInt16(); hdr.data = fs.ReadString(4); hdr.WaveSize = fs.ReadUInt32(); }
public static void WriteWaveFile(BinaryFile wavfile, double[][] sound, int channels, int samplecount, int samplerate, int format_param) { int i = 0; // "RIFF" = 1179011410 // "WAVE" = 1163280727 // "fmt " = 544501094 // "data" = 1635017060 int[] tag = {1179011410, 0, 1163280727, 544501094, 16, 1, 1, 0, 0, 0, 0, 1635017060, 0, 0}; #if DEBUG Console.Write("WriteWaveFile...\n"); #endif #region WAV tags generation tag[12] = samplecount*(format_param/8)*channels; tag[1] = tag[12]+36; tag[7] = samplerate; tag[8] = samplerate *format_param/8; tag[9] = format_param/8; tag[6] = channels; tag[10] = format_param; if ((format_param == 8) || (format_param == 16)) tag[5] = 1; if (format_param == 32) tag[5] = 3; #endregion WAV tags generation // tag writing for (i = 0; i<13; i++) { if ((i == 5) || (i == 6) || (i == 9) || (i == 10)) { Util.WriteUInt16((ushort)tag[i], wavfile); } else { Util.WriteUInt32((uint)tag[i], wavfile); } } if (format_param == 8) Write8Bit(wavfile, sound, samplecount, channels); if (format_param == 16) Write16Bit(wavfile, sound, samplecount, channels); if (format_param == 32) Write32BitFloat(wavfile, sound, samplecount, channels); wavfile.Close(); }
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(); //comments = bFile.ReadString(chunkSizeComt-2); 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 = NAudio.Utils.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; } }
public void WriteFile(string filePath) { BinaryFile bf = new BinaryFile(filePath, BinaryFile.ByteOrder.BigEndian, true); // determine if the chunkdata is saved as XML bool writeXMLChunkData = false; string xmlChunkData = ""; if (XmlDocument != null) { StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); XmlDocument.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); xmlChunkData = stringWriter.ToString().Replace("'", "'"); ChunkSize = xmlChunkData.Length; writeXMLChunkData = true; } if (ChunkMagic != "CcnK") { Console.Out.WriteLine("Cannot save the preset file. Missing preset header information."); return; } Console.Out.WriteLine("Writing FXP to {0} ...", filePath); bf.Write(ChunkMagic); // chunkMagic, 4 // check what preset type we are saving if (FxMagic == "FBCh") { // Bank with Chunk Data ByteSize = 152 + ChunkSize; bf.Write(ByteSize); // byteSize = 4 bf.Write(FxMagic); // fxMagic, 4 bf.Write(Version); // version, 4 bf.Write(FxID); // fxID, 4 bf.Write(FxVersion); // fxVersion, 4 bf.Write(ProgramCount); // numPrograms, 4 bf.Write(Future, 128); // future, 128 bf.Write(ChunkSize); // chunkSize, 4 if (writeXMLChunkData) { bf.Write(xmlChunkData); // chunkData, <chunkSize> } else { // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format bf.Write(chunkDataByteArray, BinaryFile.ByteOrder.LittleEndian); } } else if (FxMagic == "FPCh") { // Preset with Chunk Data ByteSize = 52 + ChunkSize; bf.Write(ByteSize); // byteSize = 4 bf.Write(FxMagic); // fxMagic, 4 bf.Write(Version); // version, 4 bf.Write(FxID); // fxID, 4 bf.Write(FxVersion); // fxVersion, 4 bf.Write(ProgramCount); // numPrograms, 4 bf.Write(Name, 28); // name, 28 bf.Write(ChunkSize); // chunkSize, 4 if (writeXMLChunkData) { bf.Write(xmlChunkData); // chunkData, <chunkSize> } else { // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format bf.Write(chunkDataByteArray, BinaryFile.ByteOrder.LittleEndian); } } else if (FxMagic == "FxCk") { // For Preset (Program) (.fxp) without chunk (magic = 'FxCk') // Bank with Chunk Data ByteSize = 48 + (4 * ParameterCount); bf.Write(ByteSize); // byteSize = 4 bf.Write(FxMagic); // fxMagic, 4 bf.Write(Version); // version, 4 bf.Write(FxID); // fxID, 4 bf.Write(FxVersion); // fxVersion, 4 bf.Write(ParameterCount); // numParameters, 4 bf.Write(Name, 28); // name, 28 // variable no. of parameters for (int i = 0; i < ParameterCount; i++) { bf.Write((float)Parameters[i]); } } bf.Close(); }
private static void Write(BinaryFile bf, FxContent content, XmlDocument xmlDocument) { if (content == null) { Log.Error("Error writing file. Missing preset content."); return; } // determine if the chunkdata is saved as XML bool writeXMLChunkData = false; string xmlChunkData = ""; if (xmlDocument != null) { StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); xmlDocument.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); xmlChunkData = stringWriter.ToString().Replace("'", "'"); writeXMLChunkData = true; if (content is FxProgramSet) { ((FxProgramSet)content).ChunkSize = xmlChunkData.Length; } else if (content is FxChunkSet) { ((FxChunkSet)content).ChunkSize = xmlChunkData.Length; } } if (content.ChunkMagic != "CcnK") { Log.Error("Cannot save the preset file. Missing preset header information."); return; } bf.Write(content.ChunkMagic); // chunkMagic, 4 // check what preset type we are saving if (content.FxMagic == "FBCh") { // Bank (.fxb) with chunk (magic = 'FBCh') var chunkSet = (FxChunkSet)content; chunkSet.ByteSize = 152 + chunkSet.ChunkSize; bf.Write(chunkSet.ByteSize); // byteSize = 4 bf.Write(chunkSet.FxMagic); // fxMagic, 4 bf.Write(chunkSet.Version); // version, 4 bf.Write(chunkSet.FxID); // fxID, 4 bf.Write(chunkSet.FxVersion); // fxVersion, 4 bf.Write(chunkSet.NumPrograms); // numPrograms, 4 bf.Write(chunkSet.Future, 128); // future, 128 bf.Write(chunkSet.ChunkSize); // chunkSize, 4 if (writeXMLChunkData) { bf.Write(xmlChunkData); // chunkData, <chunkSize> } else { // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format bf.Write(chunkSet.ChunkData, BinaryFile.ByteOrder.LittleEndian); } } else if (content.FxMagic == "FPCh") { // Preset (Program) (.fxp) with chunk (magic = 'FPCh') var programSet = (FxProgramSet)content; programSet.ByteSize = 52 + programSet.ChunkSize; bf.Write(programSet.ByteSize); // byteSize = 4 bf.Write(programSet.FxMagic); // fxMagic, 4 bf.Write(programSet.Version); // version, 4 bf.Write(programSet.FxID); // fxID, 4 bf.Write(programSet.FxVersion); // fxVersion, 4 bf.Write(programSet.NumPrograms); // numPrograms, 4 bf.Write(programSet.Name, 28); // name, 28 bf.Write(programSet.ChunkSize); // chunkSize, 4 if (writeXMLChunkData) { bf.Write(xmlChunkData); // chunkData, <chunkSize> } else { // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format bf.Write(programSet.ChunkData, BinaryFile.ByteOrder.LittleEndian); } } else if (content.FxMagic == "FxCk") { // For Preset (Program) (.fxp) without chunk (magic = 'FxCk') var program = (FxProgram)content; program.ByteSize = 48 + (4 * program.NumParameters); bf.Write(program.ByteSize); // byteSize = 4 bf.Write(program.FxMagic); // fxMagic, 4 bf.Write(program.Version); // version, 4 bf.Write(program.FxID); // fxID, 4 bf.Write(program.FxVersion); // fxVersion, 4 bf.Write(program.NumParameters); // numParameters, 4 bf.Write(program.ProgramName, 28); // name, 28 // variable no. of parameters for (int i = 0; i < program.NumParameters; i++) { bf.Write((float)program.Parameters[i]); } } else if (content.FxMagic == "FxBk") { // For bank (.fxb) without chunk (magic = 'FxBk') var set = (FxSet)content; // variable no. of programs var byteSize = 48; for (int i = 0; i < set.NumPrograms; i++) { var program = set.Programs[i]; byteSize += (4 * program.NumParameters); } set.ByteSize = 156 + byteSize; bf.Write(set.ByteSize); // byteSize = 4 bf.Write(set.FxMagic); // fxMagic, 4 bf.Write(set.Version); // version, 4 bf.Write(set.FxID); // fxID, 4 bf.Write(set.FxVersion); // fxVersion, 4 bf.Write(set.NumPrograms); // numPrograms, 4 bf.Write(set.Future, 128); // future, 128 // variable no. of programs for (int i = 0; i < set.NumPrograms; i++) { var program = set.Programs[i]; Write(bf, program, null); } } }
public static void Main(string[] args) { int argc = args.Length; BinaryFile fin; BinaryFile fout; double[][] sound; double[][] image; double basefreq = 0; double maxfreq = 0; double pixpersec = 0; double bpo = 0; double brightness = 1; int channels = 0; int samplecount = 0; int samplerate = 0; int Xsize = 0; int Ysize = 0; int format_param = 0; long clockb = 0; Mode mode = Mode.None; string in_name = null; string out_name = null; #if QUIET Util.quiet = true; #else Util.quiet = false; #endif Console.Write("The Analysis & Resynthesis Sound Spectrograph {0}\n", version); // initialize the random class RandomUtils.Seed(Guid.NewGuid().GetHashCode()); bool doHelp = false; for (int i = 0; i < argc; i++) { // DOS friendly help if (string.Compare(args[i], "/?")==0) { doHelp = true; } // if the argument is not a function if (args[i][0] != '-') { if (in_name == null) { // if the input file name hasn't been filled in yet in_name = args[i]; } else if (out_name == null) { // if the input name has been filled but not the output name yet out_name = args[i]; } else { // if both names have already been filled in Console.Error.WriteLine("You can only have two file names as parameters.\nRemove parameter \"%s\".\nExiting with error.\n", args[i]); Environment.Exit(1); } } else { // if the argument is a parameter if (string.Compare(args[i], "--analysis")==0 || string.Compare(args[i], "-a")==0) { mode = Mode.Analysis; } if (string.Compare(args[i], "--sine")==0 || string.Compare(args[i], "-s")==0) { mode = Mode.Synthesis_Sine; } if (string.Compare(args[i], "--noise")==0 || string.Compare(args[i], "-n")==0) { mode = Mode.Synthesis_Noise; } if (string.Compare(args[i], "--quiet")==0 || string.Compare(args[i], "-q")==0) { Util.quiet = true; } if (string.Compare(args[i], "--linear")==0 || string.Compare(args[i], "-l")==0) { DSP.LOGBASE = 1.0; } if (string.Compare(args[i], "--sample-rate")==0 || string.Compare(args[i], "-r")==0) { if (StringUtils.IsNumeric(args[++i])) { samplerate = Convert.ToInt32(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--min-freq")==0 || string.Compare(args[i], "-min")==0) { if (StringUtils.IsNumeric(args[++i])) { basefreq = Convert.ToDouble(args[i]); if (basefreq == 0) { // Set it to this extremely close-to-zero number so that it's considered set basefreq = Double.MinValue; } } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--max-freq")==0 || string.Compare(args[i], "-max")==0) { if (StringUtils.IsNumeric(args[++i])) { maxfreq = Convert.ToDouble(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--bpo")==0 || string.Compare(args[i], "-b")==0) { if (StringUtils.IsNumeric(args[++i])) { bpo = Convert.ToDouble(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--pps")==0 || string.Compare(args[i], "-p")==0) { if (StringUtils.IsNumeric(args[++i])) { pixpersec = Convert.ToDouble(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--height")==0 || string.Compare(args[i], "-y")==0) { if (StringUtils.IsNumeric(args[++i])) { Ysize = Convert.ToInt32(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--width")==0 || string.Compare(args[i], "-x")==0) { if (StringUtils.IsNumeric(args[++i])) { Xsize = Convert.ToInt32(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--loop-size")==0) { if (StringUtils.IsNumeric(args[++i])) { DSP.LOOP_SIZE_SEC = Convert.ToInt32(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--log-base")==0) { if (StringUtils.IsNumeric(args[++i])) { DSP.LOGBASE = Convert.ToDouble(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--bmsq-lut-size")==0) { if (StringUtils.IsNumeric(args[++i])) { DSP.BMSQ_LUT_SIZE = Convert.ToInt32(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--pi")==0) { if (StringUtils.IsNumeric(args[++i])) { DSP.PI = Convert.ToDouble(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--format-param")==0 || string.Compare(args[i], "-f")==0) { if (StringUtils.IsNumeric(args[++i])) { format_param = Convert.ToInt32(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } if (string.Compare(args[i], "--brightness")==0 || string.Compare(args[i], "-g")==0) { if (StringUtils.IsNumeric(args[++i])) { brightness = Convert.ToDouble(args[i]); } } else { Console.Error.WriteLine(MSG_NUMBER_EXPECTED, args[i-1]); Environment.Exit(1); } // TODO implement --duration, -d if (string.Compare(args[i], "--version")==0 || string.Compare(args[i], "-v")==0) { Console.Write("Copyright (C) 2005-2008 Michel Rouzic\nProgram last modified by its author on {0}\n", date); Environment.Exit(0); } if (doHelp || string.Compare(args[i], "--help")==0 || string.Compare(args[i], "-h")==0) { PrintHelp(); Environment.Exit(0); } if (string.Compare(args[i], "--adv-help")==0) { PrintAdvancedHelp(); Environment.Exit(0); } } } // if in_name has already been filled in if (in_name != null) { // try to open it fin = new BinaryFile(in_name); if (fin == null) { Console.Error.WriteLine("The input file {0} could not be found\nExiting with error.\n", in_name); Environment.Exit(1); } Console.Write("Input file : {0}\n", in_name); } else { if (Util.quiet) { Console.Error.WriteLine("Please specify an input file.\nExiting with error.\n"); Environment.Exit(1); } Console.Write("Type 'help' to read the manual page\n"); do { fin = null; Console.Write("Input file : "); in_name = Util.ReadUserInputString(); // if 'help' has been typed if (string.Compare(in_name, "help", StringComparison.Ordinal) == 0) { fin = null; PrintHelp(); // print the help } else { if (File.Exists(in_name)) { fin = new BinaryFile(in_name); } } } while (fin == null); } // if out_name has already been filled in if (out_name != null) { fout = new BinaryFile(out_name, BinaryFile.ByteOrder.LittleEndian, true); if (fout == null) { Console.Error.WriteLine("The output file {0} could not be opened.\nPlease make sure it isn't opened by any other program and press Return.\nExiting with error.\n", out_name); Environment.Exit(1); } Console.Write("Output file : {0}\n", out_name); } else { if (Util.quiet) { Console.Error.WriteLine("Please specify an output file.\nExiting with error.\n"); Environment.Exit(1); } Console.Write("Output file : "); out_name = Util.ReadUserInputString(); fout = null; if (!string.IsNullOrEmpty(out_name)) { fout = new BinaryFile(out_name, BinaryFile.ByteOrder.LittleEndian, true); } while (fout == null) { Console.Write("Output file : "); out_name = Util.ReadUserInputString(); if (!string.IsNullOrEmpty(out_name)) { fout = new BinaryFile(out_name, BinaryFile.ByteOrder.LittleEndian, true); } } // we will never get here cause BinaryFile does not return a null while (fout == null) { Console.Error.WriteLine("The output file {0} could not be opened.\nPlease make sure it isn't opened by any other program and press Return.\n", out_name); Console.Read(); fout = new BinaryFile(out_name, BinaryFile.ByteOrder.LittleEndian, true); } } // make the string lowercase in_name = in_name.ToLower(); if (in_name.EndsWith(".wav") && (mode == Mode.None || mode == Mode.Synthesis_Sine || mode == Mode.Synthesis_Noise)) { mode = Mode.Analysis; // Automatic switch to the Analysis mode } if (mode == Mode.None) { do { if (Util.quiet) { Console.Error.WriteLine("Please specify an operation mode.\nUse either --analysis (-a), --sine (-s) or --noise (-n).\nExiting with error.\n"); Environment.Exit(1); } Console.Write("Choose the mode (Press 1, 2 or 3) :\n\t1. Analysis\n\t2. Sine synthesis\n\t3. Noise synthesis\n> "); mode = (Mode) Util.ReadUserInputFloat(); } while (mode != Mode.Analysis && mode != Mode.Synthesis_Sine && mode != Mode.Synthesis_Noise); } if (mode == Mode.Analysis) { sound = SoundIO.ReadWaveFile(fin, ref channels, ref samplecount, ref samplerate); // Sound input fin.Close(); #if DEBUG Console.Write("Samplecount : {0:D}\nChannels : {1:D}\n", samplecount, channels); #endif SettingsInput(ref Ysize, ref samplecount, ref samplerate, ref basefreq, ref maxfreq, ref pixpersec, ref bpo, ref Xsize, Mode.Analysis); // User settings input image = DSP.Analyze(ref sound[0], ref samplecount, ref samplerate, ref Xsize, ref Ysize, ref bpo, ref pixpersec, ref basefreq); // Analysis if (brightness != 1.0) { DSP.BrightnessControl(ref image, ref Ysize, ref Xsize, 1.0/brightness); } ImageIO.BMPWrite(fout, image, Ysize, Xsize); // Image output /* var audio2Midi = new CommonUtils.MathLib.FFT.Audio2Midi(); string fileNameSine = @"C:\Users\perivar.nerseth\Documents\My Projects\CommonUtils\Library\Tests\Passacaglia, Handel-Sine-86bmp.wav"; string fileNameSaw = @"C:\Users\perivar.nerseth\Documents\My Projects\CommonUtils\Library\Tests\Passacaglia, Handel-Saw-86bmp.wav"; string fileNamePiano = @"C:\Users\perivar.nerseth\Documents\My Projects\CommonUtils\Library\Tests\Passacaglia, Handel-Piano-86bmp.wav"; //string fileName = @"C:\\Users\\perivar.nerseth\\Documents\\Processing\\spectrotune\\music\\piano.wav"; int frames = audio2Midi.OpenAudioFile(fileNameSine); */ /* // Testing using the Spectrogram methods to synthesize and resynthesize var spectrogram = new ArssSpectrogram.Spectrogram(); var spectrogramImage = spectrogram.ToImage(ref sound[0], samplerate); spectrogramImage.Save("test2.bmp", ImageFormat.Bmp); return; //double[] soundSynth = spectrogram.SynthetizeSine(new System.Drawing.Bitmap("test2.bmp"), samplerate); var testImage = new BinaryFile("test2.bmp"); int testImageX = 0; int testImageY = 0; var testImageArray = ImageIO.BMPRead(testImage, ref testImageY, ref testImageX); // Image input double[] soundSynth2 = spectrogram.SynthetizeSine(testImageArray, samplerate); CommonUtils.Audio.NAudio.AudioUtilsNAudio.WriteIEEE32WaveFileMono("test2.wav", samplerate, MathUtils.DoubleToFloat(soundSynth2)); */ } if (mode == Mode.Synthesis_Sine || mode == Mode.Synthesis_Noise) { sound = new double[1][]; image = ImageIO.BMPRead(fin, ref Ysize, ref Xsize); // Image input // if the output format parameter is undefined if (format_param == 0) { if (!Util.quiet) { // if prompting is allowed format_param = SoundIO.ReadUserWaveOutParameters(); } else { format_param = 32; // default is 32 } } SettingsInput(ref Ysize, ref samplecount, ref samplerate, ref basefreq, ref maxfreq, ref pixpersec, ref bpo, ref Xsize, Mode.Synthesis_Sine); // User settings input if (brightness!=1.0) { DSP.BrightnessControl(ref image, ref Ysize, ref Xsize, brightness); } if (mode == Mode.Synthesis_Sine) { sound[0] = DSP.SynthesizeSine(ref image, ref Xsize, ref Ysize, ref samplecount, ref samplerate, ref basefreq, ref pixpersec, ref bpo); // Sine synthesis } else { sound[0] = DSP.SynthesizeNoise(ref image, ref Xsize, ref Ysize, ref samplecount, ref samplerate, ref basefreq, ref pixpersec, ref bpo); // Noise synthesis } SoundIO.WriteWaveFile(fout, sound, 1, samplecount, samplerate, format_param); } clockb = Util.GetTimeTicks(); TimeSpan duration = TimeSpan.FromMilliseconds(clockb-DSP.clockA); Console.Write("Processing time : {0:D2} m {1:D2} s {2:D2} ms\n", duration.Minutes, duration.Seconds, duration.Milliseconds); Util.ReadUserReturn(); }
public bool Process() { int bytespersec = 0; int byteread = 0; bool isPCM = false; var listinfo = new Dictionary <string, string>(); for (int i = 0; i < infotype.Length; i++) { listinfo.Add(infotype[i], infodesc[i]); } var bf = new BinaryFile(selectedFile); try { var fileInfo = new FileInfo(selectedFile); fileLength = fileInfo.Length; int chunkSize = 0, infochunksize = 0, bytecount = 0, listbytecount = 0; string sfield = "", infofield = "", infodescription = "", infodata = ""; /* -------- Get RIFF chunk header --------- */ sfield = bf.ReadString(4); #if DEBUG Console.WriteLine("RIFF Header: {0}", sfield); #endif if (sfield != "RIFF") { Console.WriteLine(" **** Not a valid RIFF file ****"); return(false); } // read RIFF data size chunkSize = bf.ReadInt32(); #if DEBUG Console.WriteLine("RIFF data size: {0}", chunkSize); #endif // read form-type (WAVE etc) sfield = bf.ReadString(4); #if DEBUG Console.WriteLine("Form-type: {0}", sfield); #endif riffDataSize = chunkSize; bytecount = 4; // initialize bytecount to include RIFF form-type bytes. while (bytecount < riffDataSize) // check for chunks inside RIFF data area. { sfield = ""; int firstbyte = bf.ReadByte(); if (firstbyte == 0) // if previous data had odd bytecount, was padded by null so skip { bytecount++; continue; } sfield += (char)firstbyte; // if we have a new chunk for (int i = 1; i <= 3; i++) { sfield += (char)bf.ReadByte(); } chunkSize = 0; chunkSize = bf.ReadInt32(); bytecount += (8 + chunkSize); #if DEBUG Console.WriteLine("{0} ----- data size: {1} bytes", sfield, chunkSize); #endif if (sfield == "data") { //get data size to compute duration later. dataSize = chunkSize; } if (sfield == "fmt ") { /* * Offset Size Description Value * 0x00 4 Chunk ID "fmt " (0x666D7420) * 0x04 4 Chunk Data Size 16 + extra format bytes * 0x08 2 Compression code 1 - 65,535 * 0x0a 2 Number of channels 1 - 65,535 * 0x0c 4 Sample rate 1 - 0xFFFFFFFF * 0x10 4 Average bytes per second 1 - 0xFFFFFFFF * 0x14 2 Block align 1 - 65,535 * 0x16 2 Significant bits per sample 2 - 65,535 * 0x18 2 Extra format bytes 0 - 65,535 * 0x1a * Extra format bytes * */ // extract info from "format" chunk. if (chunkSize < 16) { Console.WriteLine(" **** Not a valid fmt chunk ****"); return(false); } // Read compression code, 2 bytes wFormatTag = bf.ReadInt16(); switch (wFormatTag) { case WAVE_FORMAT_PCM: case WAVE_FORMAT_EXTENSIBLE: case WAVE_FORMAT_IEEE_FLOAT: isPCM = true; break; } switch (wFormatTag) { case WAVE_FORMAT_PCM: Console.WriteLine("\twFormatTag: WAVE_FORMAT_PCM"); break; case WAVE_FORMAT_EXTENSIBLE: Console.WriteLine("\twFormatTag: WAVE_FORMAT_EXTENSIBLE"); break; case WAVE_FORMAT_IEEE_FLOAT: Console.WriteLine("\twFormatTag: WAVE_FORMAT_IEEE_FLOAT"); break; case WAVE_FORMAT_MPEGLAYER3: Console.WriteLine("\twFormatTag: WAVE_FORMAT_MPEGLAYER3"); break; default: Console.WriteLine("\twFormatTag: non-PCM format {0}", wFormatTag); break; } // Read number of channels, 2 bytes nChannels = bf.ReadInt16(); #if DEBUG Console.WriteLine("\tnChannels: {0}", nChannels); #endif // Read sample rate, 4 bytes nSamplesPerSec = bf.ReadInt32(); #if DEBUG Console.WriteLine("\tnSamplesPerSec: {0}", nSamplesPerSec); #endif // Read average bytes per second, 4 bytes nAvgBytesPerSec = bf.ReadInt32(); bytespersec = nAvgBytesPerSec; #if DEBUG Console.WriteLine("\tnAvgBytesPerSec: {0}", nAvgBytesPerSec); #endif // Read block align, 2 bytes nBlockAlign = bf.ReadInt16(); #if DEBUG Console.WriteLine("\tnBlockAlign: {0}", nBlockAlign); #endif // Read significant bits per sample, 2 bytes if (isPCM) // if PCM or EXTENSIBLE format { wBitsPerSample = bf.ReadInt16(); #if DEBUG Console.WriteLine("\twBitsPerSample: {0}", wBitsPerSample); #endif } else { bf.ReadBytes(2); wBitsPerSample = 0; } //skip over any extra bytes in format specific field. bf.ReadBytes(chunkSize - 16); } else if (sfield == "LIST") { String listtype = bf.ReadString(4); // skip over LIST chunks which don't contain INFO subchunks if (listtype != "INFO") { bf.ReadBytes(chunkSize - 4); continue; } try { listbytecount = 4; #if DEBUG Console.WriteLine("------- INFO chunks: {0} bytes -------", chunkSize); #endif // iterate over all entries in LIST chunk while (listbytecount < chunkSize) { infofield = ""; infodescription = ""; infodata = ""; firstbyte = bf.ReadByte(); // if previous data had odd bytecount, was padded by null so skip if (firstbyte == 0) { listbytecount++; continue; } // if firstbyte is not an alpha char, read one more byte if (!Char.IsLetterOrDigit((char)firstbyte)) { firstbyte = bf.ReadByte(); listbytecount++; } // if we have a new chunk infofield += (char)firstbyte; for (int i = 1; i <= 3; i++) //get the remaining part of info chunk name ID { infofield += (char)bf.ReadByte(); } // get the info chunk data byte size infochunksize = bf.ReadInt32(); listbytecount += (8 + infochunksize); //Console.WriteLine("infofield: {0}, listbytecount: {1}, infochunksize: {2}", infofield, listbytecount, infochunksize); if (listbytecount > chunkSize) { bf.SetPosition(bf.GetPosition() - 8); break; } // get the info chunk data for (int i = 0; i < infochunksize; i++) { byteread = bf.ReadByte(); if (byteread == 0) // if null byte in string, ignore it { continue; } infodata += (char)byteread; } int unknownCount = 1; try { infodescription = (string)listinfo[infofield]; } catch (KeyNotFoundException) {} if (infodescription != null) { #if DEBUG Console.WriteLine("{0} ({1}) = {2}", infofield, infodescription, infodata); #endif InfoChunks.Add(infodescription, infodata); } else { #if DEBUG Console.WriteLine("unknown: {0} = {1}", infofield, infodata); #endif InfoChunks.Add(String.Format("unknown{0}", unknownCount), infodata); unknownCount++; } } //------- end iteration over LIST chunk ------------ } catch (Exception) {; // don't care about these? //Console.WriteLine("Error: {0}", e.ToString()); } #if DEBUG Console.WriteLine("------- end INFO chunks -------"); #endif } else { if (sfield.Equals("data")) { sampleCount = (int)dataSize / (wBitsPerSample / 8) / nChannels; soundData = new float[nChannels][]; for (int ic = 0; ic < nChannels; ic++) { soundData[ic] = new float[sampleCount]; } //********Data loading******** if (BitsPerSample == 8) { Read8Bit(bf, soundData, sampleCount, nChannels); } if (BitsPerSample == 16) { Read16Bit(bf, soundData, sampleCount, nChannels); } if (BitsPerSample == 32) { if (wFormatTag == WAVE_FORMAT_PCM) { Read32Bit(bf, soundData, sampleCount, nChannels); } else if (wFormatTag == WAVE_FORMAT_IEEE_FLOAT) { Read32BitFloat(bf, soundData, sampleCount, nChannels); } } } else { // if NOT the fmt or LIST chunks skip data bf.ReadBytes(chunkSize); } } } // end while. //----------- End of chunk iteration ------------- if (isPCM && dataSize > 0) // compute duration of PCM wave file { long waveduration = 1000L * dataSize / bytespersec; // in msec units long mins = waveduration / 60000; // integer minutes double secs = 0.001 * (waveduration % 60000); //double secs. #if DEBUG Console.WriteLine("wav duration: {0} mins {1} sec", mins, secs); #endif } #if DEBUG Console.WriteLine("Final RIFF data bytecount: {0}", bytecount); #endif if ((8 + bytecount) != (int)fileLength) { Console.WriteLine("!!!!!!! Problem with file structure !!!!!!!!!"); return(false); } else { #if DEBUG Console.WriteLine("File chunk structure consistent with valid RIFF"); #endif } return(true); } catch (Exception e) { Console.WriteLine("Error: {0}", e.ToString()); return(false); } finally { // close all streams. bf.Close(); } }
public void ReadFXP(BinaryFile bf) { ChunkMagic = bf.ReadString(4); if (ChunkMagic != "CcnK") { Console.Out.WriteLine("Error reading file. Missing preset header information."); } ByteSize = bf.ReadInt32(); FxMagic = bf.ReadString(4); if (FxMagic == "FBCh") { // Bank with Chunk Data Version = bf.ReadInt32(); FxID = bf.ReadString(4); FxVersion = bf.ReadInt32(); ProgramCount = bf.ReadInt32(); Future = bf.ReadString(128); ChunkSize = bf.ReadInt32(); // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format chunkDataByteArray = new byte[ChunkSize]; chunkDataByteArray = bf.ReadBytes(0, ChunkSize, BinaryFile.ByteOrder.LittleEndian); chunkData = BinaryFile.ByteArrayToString(chunkDataByteArray); } else if (FxMagic == "FPCh") { // Preset with Chunk Data Version = bf.ReadInt32(); FxID = bf.ReadString(4); FxVersion = bf.ReadInt32(); ProgramCount = bf.ReadInt32(); Name = bf.ReadString(28); ChunkSize = bf.ReadInt32(); // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format chunkDataByteArray = new byte[ChunkSize]; chunkDataByteArray = bf.ReadBytes(0, ChunkSize, BinaryFile.ByteOrder.LittleEndian); chunkData = BinaryFile.ByteArrayToString(chunkDataByteArray); } else if (FxMagic == "FxCk") { // For Preset (Program) (.fxp) without chunk (magic = 'FxCk') Version = bf.ReadInt32(); FxID = bf.ReadString(4); FxVersion = bf.ReadInt32(); ParameterCount = bf.ReadInt32(); Name = bf.ReadString(28); // variable no. of parameters Parameters = new float[ParameterCount]; for (int i = 0; i < ParameterCount; i++) { Parameters[i] = bf.ReadSingle(); } } bf.Close(); // read the xml chunk into memory XmlDocument = new XmlDocument(); try { if (chunkData != null) XmlDocument.LoadXml(chunkData); } catch (XmlException) { //Console.Out.WriteLine("No XML found"); } }
public static void WriteBMPGrayscale(string filePath, double[][] image, int bitDepth = 24) { var bmpfile = new BinaryFile(filePath, BinaryFile.ByteOrder.LittleEndian, true); int y = image.Length; int x = image[0].Length; const byte zerobyte = 255; // what byte should we pad with int numBytes = bitDepth / 8; // calculate zero bytes (bytes to skip at the end of each bitmap line) int zerobytes = (byte)(4 - ((x * numBytes) & numBytes)); if (zerobytes == 4) { zerobytes = 0; } #region Tags int filesize = 54 + ((x * numBytes) + zerobytes) * y; int imagesize = ((x * numBytes) + zerobytes) * y; bmpfile.Write("BM"); bmpfile.Write((UInt32)filesize); // filesize bmpfile.Write((UInt32)0); // reserved bmpfile.Write((UInt32)54); // off bits bmpfile.Write((UInt32)40); // bitmap info header size bmpfile.Write((UInt32)x); // width bmpfile.Write((UInt32)y); // height bmpfile.Write((UInt16)1); // planes bmpfile.Write((UInt32)bitDepth); // bit depth bmpfile.Write((UInt16)0); // compression bmpfile.Write((UInt32)imagesize); //bmpfile.Write((UInt32) 0); // There are at least three kind value of PelsPerMeter used for 96 DPI bitmap: // 0 - the bitmap just simply doesn't set this value // 2834 - 72 DPI // 3780 - 96 DPI const UInt32 pelsPerMeter = 0; //3780; bmpfile.Write((UInt32)pelsPerMeter); // XPelsPerMeter bmpfile.Write((UInt32)pelsPerMeter); // YPelsPerMeter bmpfile.Write((UInt32)0); // clr used bmpfile.Write((UInt32)0); // clr important #endregion Tags // backwards writing for (int iy = y - 1; iy != -1; iy--) { for (int ix = 0; ix < x; ix++) { // define color (grayscale) double vald = image[iy][ix] * 255.0; if (vald > 255.0) { vald = 255.0; } if (vald < 0.0) { vald = 0.0; } byte val = Convert.ToByte(vald); for (int ic = numBytes - 1; ic != -1; ic--) { if (ic == 0 && numBytes == 4) { bmpfile.Write((byte)0); // alpha bit } else { bmpfile.Write(val); } } } // write padding bytes for (int i = 0; i < zerobytes; i++) { bmpfile.Write(zerobyte); } } //bmpfile.Write((UInt16)0); bmpfile.Close(); #if DEBUG Console.Write("Image size : {0:D}x{1:D}\n", x, y); #endif }
public bool Process() { int bytespersec = 0; int byteread = 0; bool isPCM = false; Dictionary <string,string>listinfo = new Dictionary<string,string>(); for (int i=0; i<infotype.Length; i++) { listinfo.Add(infotype[i], infodesc[i]); } BinaryFile bf = new BinaryFile(selectedFile); try { FileInfo fileInfo = new FileInfo(selectedFile); fileLength = fileInfo.Length; int chunkSize=0, infochunksize=0, bytecount=0, listbytecount=0; string sfield="", infofield="", infodescription="", infodata=""; /* -------- Get RIFF chunk header --------- */ sfield = bf.ReadString(4); #if DEBUG Console.WriteLine("RIFF Header: {0}", sfield); #endif if (sfield != "RIFF") { Console.WriteLine(" **** Not a valid RIFF file ****"); return false; } // read RIFF data size chunkSize = bf.ReadInt32(); #if DEBUG Console.WriteLine("RIFF data size: {0}", chunkSize); #endif // read form-type (WAVE etc) sfield = bf.ReadString(4); #if DEBUG Console.WriteLine("Form-type: {0}", sfield); #endif riffDataSize = chunkSize; bytecount = 4; // initialize bytecount to include RIFF form-type bytes. while (bytecount < riffDataSize ) { // check for chunks inside RIFF data area. sfield=""; int firstbyte = bf.ReadByte() ; if (firstbyte == 0) { // if previous data had odd bytecount, was padded by null so skip bytecount++; continue; } sfield+= (char) firstbyte; // if we have a new chunk for (int i=1; i<=3; i++) { sfield += (char) bf.ReadByte() ; } chunkSize = 0; chunkSize = bf.ReadInt32(); bytecount += ( 8 + chunkSize ); #if DEBUG Console.WriteLine("{0} ----- data size: {1} bytes", sfield, chunkSize); #endif if (sfield == "data") { //get data size to compute duration later. dataSize = chunkSize; } if (sfield == "fmt ") { /* Offset Size Description Value 0x00 4 Chunk ID "fmt " (0x666D7420) 0x04 4 Chunk Data Size 16 + extra format bytes 0x08 2 Compression code 1 - 65,535 0x0a 2 Number of channels 1 - 65,535 0x0c 4 Sample rate 1 - 0xFFFFFFFF 0x10 4 Average bytes per second 1 - 0xFFFFFFFF 0x14 2 Block align 1 - 65,535 0x16 2 Significant bits per sample 2 - 65,535 0x18 2 Extra format bytes 0 - 65,535 0x1a Extra format bytes * */ // extract info from "format" chunk. if (chunkSize < 16) { Console.WriteLine(" **** Not a valid fmt chunk ****"); return false; } // Read compression code, 2 bytes wFormatTag = bf.ReadInt16(); if (wFormatTag == WAVE_FORMAT_PCM || wFormatTag == WAVE_FORMAT_EXTENSIBLE || wFormatTag == WAVE_FORMAT_IEEE_FLOAT) { isPCM = true; } if (wFormatTag == WAVE_FORMAT_PCM) { #if DEBUG Console.WriteLine("\twFormatTag: WAVE_FORMAT_PCM") ; #endif } else if (wFormatTag == WAVE_FORMAT_EXTENSIBLE) { #if DEBUG Console.WriteLine("\twFormatTag: WAVE_FORMAT_EXTENSIBLE") ; #endif } else if (wFormatTag == WAVE_FORMAT_IEEE_FLOAT) { #if DEBUG Console.WriteLine("\twFormatTag: WAVE_FORMAT_IEEE_FLOAT") ; #endif } else if (wFormatTag == WAVE_FORMAT_MPEGLAYER3) { #if DEBUG Console.WriteLine("\twFormatTag: WAVE_FORMAT_MPEGLAYER3") ; #endif } else { #if DEBUG Console.WriteLine("\twFormatTag: non-PCM format {0}", wFormatTag) ; #endif } // Read number of channels, 2 bytes nChannels = bf.ReadInt16(); #if DEBUG Console.WriteLine("\tnChannels: {0}", nChannels); #endif // Read sample rate, 4 bytes nSamplesPerSec = bf.ReadInt32(); #if DEBUG Console.WriteLine("\tnSamplesPerSec: {0}", nSamplesPerSec); #endif // Read average bytes per second, 4 bytes nAvgBytesPerSec = bf.ReadInt32(); bytespersec = nAvgBytesPerSec; #if DEBUG Console.WriteLine("\tnAvgBytesPerSec: {0}", nAvgBytesPerSec); #endif // Read block align, 2 bytes nBlockAlign = bf.ReadInt16(); #if DEBUG Console.WriteLine("\tnBlockAlign: {0}", nBlockAlign); #endif // Read significant bits per sample, 2 bytes if (isPCM) { // if PCM or EXTENSIBLE format wBitsPerSample = bf.ReadInt16(); #if DEBUG Console.WriteLine("\twBitsPerSample: {0}", wBitsPerSample); #endif } else { bf.ReadBytes(2); wBitsPerSample = 0; } //skip over any extra bytes in format specific field. bf.ReadBytes(chunkSize - 16); } else if (sfield == "LIST") { String listtype = bf.ReadString(4); // skip over LIST chunks which don't contain INFO subchunks if (listtype != "INFO") { bf.ReadBytes(chunkSize - 4); continue; } try { listbytecount = 4; #if DEBUG Console.WriteLine("------- INFO chunks: {0} bytes -------", chunkSize); #endif // iterate over all entries in LIST chunk while (listbytecount < chunkSize) { infofield = ""; infodescription = ""; infodata = ""; firstbyte = bf.ReadByte(); // if previous data had odd bytecount, was padded by null so skip if (firstbyte == 0) { listbytecount++; continue; } // if firstbyte is not an alpha char, read one more byte if (!Char.IsLetterOrDigit( (char) firstbyte )) { firstbyte = bf.ReadByte(); listbytecount++; } // if we have a new chunk infofield += (char) firstbyte; for (int i=1; i<=3; i++) { //get the remaining part of info chunk name ID infofield += (char) bf.ReadByte() ; } // get the info chunk data byte size infochunksize = bf.ReadInt32(); listbytecount += ( 8 + infochunksize ); //Console.WriteLine("infofield: {0}, listbytecount: {1}, infochunksize: {2}", infofield, listbytecount, infochunksize); if (listbytecount > chunkSize) { bf.SetPosition(bf.GetPosition() - 8); break; } // get the info chunk data for (int i=0; i < infochunksize; i++) { byteread = bf.ReadByte(); if (byteread == 0) { // if null byte in string, ignore it continue; } infodata += (char) byteread; } int unknownCount = 1; try { infodescription = (string) listinfo[infofield]; } catch (KeyNotFoundException) {} if (infodescription != null) { #if DEBUG Console.WriteLine("{0} ({1}) = {2}", infofield, infodescription, infodata); #endif InfoChunks.Add(infodescription, infodata); } else { #if DEBUG Console.WriteLine("unknown: {0} = {1}", infofield, infodata); #endif InfoChunks.Add(String.Format("unknown{0}", unknownCount), infodata); unknownCount++; } } //------- end iteration over LIST chunk ------------ } catch (Exception) {; // don't care about these? //Console.WriteLine("Error: {0}", e.ToString()); } #if DEBUG Console.WriteLine("------- end INFO chunks -------"); #endif } else { if (sfield.Equals("data")) { sampleCount = (int) dataSize / (wBitsPerSample / 8) / nChannels; soundData = new float[nChannels][]; for (int ic = 0; ic < nChannels; ic++) { soundData[ic] = new float[sampleCount]; } //********Data loading******** if (BitsPerSample == 8) { Read8Bit(bf, soundData, sampleCount, nChannels); } if (BitsPerSample == 16) { Read16Bit(bf, soundData, sampleCount, nChannels); } if (BitsPerSample == 32) { if (wFormatTag == WAVE_FORMAT_PCM) { Read32Bit(bf, soundData, sampleCount, nChannels); } else if (wFormatTag == WAVE_FORMAT_IEEE_FLOAT) { Read32BitFloat(bf, soundData, sampleCount, nChannels); } } } else { // if NOT the fmt or LIST chunks skip data bf.ReadBytes(chunkSize); } } } // end while. //----------- End of chunk iteration ------------- if(isPCM && dataSize > 0) { // compute duration of PCM wave file long waveduration = 1000L * dataSize / bytespersec; // in msec units long mins = waveduration / 60000; // integer minutes double secs = 0.001 * (waveduration % 60000); //double secs. #if DEBUG Console.WriteLine("wav duration: {0} mins {1} sec", mins, secs); #endif } #if DEBUG Console.WriteLine("Final RIFF data bytecount: {0}", bytecount); #endif if ( ( 8 + bytecount) != (int) fileLength) { Console.WriteLine("!!!!!!! Problem with file structure !!!!!!!!!"); return false; } else { #if DEBUG Console.WriteLine("File chunk structure consistent with valid RIFF") ; #endif } return true; } catch (Exception e) { Console.WriteLine("Error: {0}", e.ToString()) ; return false; } finally { // close all streams. bf.Close(); } }
public void ReadFile( string filePath ) { BinaryFile bf = new BinaryFile(filePath, BinaryFile.ByteOrder.BigEndian); ReadFXP(bf); }
public void WriteFile( string filePath ) { BinaryFile bf = new BinaryFile(filePath, BinaryFile.ByteOrder.BigEndian, true); // determine if the chunkdata is saved as XML bool writeXMLChunkData = false; string xmlChunkData = ""; if (XmlDocument != null) { StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); XmlDocument.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); xmlChunkData = stringWriter.ToString().Replace("'", "'"); ChunkSize = xmlChunkData.Length; writeXMLChunkData = true; } if (ChunkMagic != "CcnK") { Console.Out.WriteLine("Cannot save the preset file. Missing preset header information."); return; } Console.Out.WriteLine("Writing FXP to {0} ...", filePath); bf.Write(ChunkMagic); // chunkMagic, 4 // check what preset type we are saving if (FxMagic == "FBCh") { // Bank with Chunk Data ByteSize = 152 + ChunkSize; bf.Write(ByteSize); // byteSize = 4 bf.Write(FxMagic); // fxMagic, 4 bf.Write(Version); // version, 4 bf.Write(FxID); // fxID, 4 bf.Write(FxVersion); // fxVersion, 4 bf.Write(ProgramCount); // numPrograms, 4 bf.Write(Future, 128); // future, 128 bf.Write(ChunkSize); // chunkSize, 4 if (writeXMLChunkData) { bf.Write(xmlChunkData); // chunkData, <chunkSize> } else { // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format bf.Write(chunkDataByteArray, BinaryFile.ByteOrder.LittleEndian); } } else if (FxMagic == "FPCh") { // Preset with Chunk Data ByteSize = 52 + ChunkSize; bf.Write(ByteSize); // byteSize = 4 bf.Write(FxMagic); // fxMagic, 4 bf.Write(Version); // version, 4 bf.Write(FxID); // fxID, 4 bf.Write(FxVersion); // fxVersion, 4 bf.Write(ProgramCount); // numPrograms, 4 bf.Write(Name, 28); // name, 28 bf.Write(ChunkSize); // chunkSize, 4 if (writeXMLChunkData) { bf.Write(xmlChunkData); // chunkData, <chunkSize> } else { // Even though the main FXP is BigEndian format the preset chunk is saved in LittleEndian format bf.Write(chunkDataByteArray, BinaryFile.ByteOrder.LittleEndian); } } else if (FxMagic == "FxCk") { // For Preset (Program) (.fxp) without chunk (magic = 'FxCk') // Bank with Chunk Data ByteSize = 48 + (4*ParameterCount); bf.Write(ByteSize); // byteSize = 4 bf.Write(FxMagic); // fxMagic, 4 bf.Write(Version); // version, 4 bf.Write(FxID); // fxID, 4 bf.Write(FxVersion); // fxVersion, 4 bf.Write(ParameterCount); // numParameters, 4 bf.Write(Name, 28); // name, 28 // variable no. of parameters for (int i = 0; i < ParameterCount; i++) { bf.Write((float) Parameters[i]); } } bf.Close(); }
/** * Reads the header and channel data from given .wav file. * * Data are read into a temporary buffer and then converted to * channel sample vectors. If source is a mono recording, samples * are written to left channel. * * To improve performance, no format checking is performed. * * @param file full path to .wav file */ public void Load(string file) { filename = file; LChTab.Clear(); RChTab.Clear(); if (frameLength != 0) ClearFrames(); // first we read header from the stream // then as we know now the data size, we create a temporary // buffer and read raw data into that buffer BinaryFile fs = new BinaryFile(filename); LoadHeader(ref fs); short[] data = new short[hdr.WaveSize/2]; LoadRawData(ref fs, data, hdr.WaveSize/2); fs.Close(); // initialize data channels (using right channel only in stereo mode) uint channelSize = hdr.WaveSize/hdr.BytesPerSamp; //LChTab.resize(channelSize); //if (2 == hdr.Channels) //RChTab.resize(channelSize); // most important conversion happens right here if (16 == hdr.BitsPerSamp) { if (2 == hdr.Channels) { Convert16Stereo(data, channelSize); } else { Convert16Mono(data, channelSize); } } else { if (2 == hdr.Channels) { Convert8Stereo(data, channelSize); } else { Convert8Mono(data, channelSize); } } // clear the buffer data = null; // when we have the data, it is possible to create frames if (frameLength != 0) DivideFrames(LChTab); }
public static bool Convert2ReaEQ(REWEQFilters filters, string filePath) { List<ReaEQBand> ReaEqBands = new List<ReaEQBand>(); foreach (REWEQBand filter in filters) { ReaEQBand band = new ReaEQBand(); band.LogScaleAutoFreq = true; band.FilterFreq = filter.FilterFreq; band.FilterGain = filter.FilterGain; band.FilterBWOct = filter.FilterBWOct; band.Enabled = filter.Enabled; switch (filter.FilterType) { case REWEQFilterType.PK: band.FilterType = ReaEQFilterType.Band; break; case REWEQFilterType.LP: band.FilterType = ReaEQFilterType.LowPass; break; case REWEQFilterType.HP: band.FilterType = ReaEQFilterType.HighPass; break; case REWEQFilterType.LS: band.FilterType = ReaEQFilterType.LowShelf; break; case REWEQFilterType.HS: band.FilterType = ReaEQFilterType.HighShelf; break; default: band.FilterType = ReaEQFilterType.Band; break; } ReaEqBands.Add(band); } // store to file FXP fxp = new FXP(); fxp.ChunkMagic = "CcnK"; fxp.ByteSize = 0; // will be set correctly by FXP class fxp.FxMagic = "FPCh"; // FPCh = FXP (preset), FBCh = FXB (bank) fxp.Version = 1; // Format Version (should be 1) fxp.FxID = "reeq"; fxp.FxVersion = 1100; fxp.ProgramCount = 1; fxp.Name = ""; using(MemoryStream memStream = new MemoryStream(10)) { BinaryFile binFile = new BinaryFile(memStream, BinaryFile.ByteOrder.LittleEndian); binFile.Write((int)33); binFile.Write((int)ReaEqBands.Count); foreach (ReaEQBand band in ReaEqBands) { binFile.Write((int) band.FilterType); binFile.Write((int) (band.Enabled ? 1 : 0) ); binFile.Write((double) band.FilterFreq); binFile.Write((double) Decibel2AmplitudeRatio(band.FilterGain)); binFile.Write((double) band.FilterBWOct); binFile.Write((byte) 1); } binFile.Write((int)1); binFile.Write((int)1); binFile.Write((double) Decibel2AmplitudeRatio(0.00)); binFile.Write((int)0); memStream.Flush(); byte[] chunkData = memStream.GetBuffer(); fxp.ChunkSize = chunkData.Length; fxp.ChunkDataByteArray = chunkData; } fxp.WriteFile(filePath); return true; }
/** * Saves selected frame span to a new file. * * @param filename where to save frames * @param begin number of the first frame * @param end number of the last frame * @throw FormatException not allowed to save 8b-mono files */ public void SaveFrames(string filename, int begin, int end) { if (1 == hdr.Channels && 8 == hdr.BitsPerSamp) { throw new FormatException("Save error: 8-bit mono files are not supported yet!"); } int samples = GetSamplesPerFrame(); // calculate the boundaries of a fragment of the source channel // which correspond to given frame numbers int startPos = (int)(begin * samples * (1 - overlap)); int endPos = (int)((end + 1) * samples * (1 - overlap) + samples * overlap); if (endPos > LChTab.Count) endPos = LChTab.Count; // number of data bytes in the resulting wave file UInt32 waveSize = (UInt32) (endPos - startPos) * hdr.BytesPerSamp; // prepare a new header and write it to file stream WaveHeader newHdr = new WaveHeader(); //std.strncpy(newHdr.RIFF, hdr.RIFF, 4); newHdr.DataLength = (UInt32) (waveSize + newHdr.WaveHeaderSize); //std.strncpy(newHdr.WAVE, hdr.WAVE, 4); //std.strncpy(newHdr.fmt_, hdr.fmt_, 4); newHdr.SubBlockLength = hdr.SubBlockLength; newHdr.formatTag = hdr.formatTag; newHdr.Channels = hdr.Channels; newHdr.SampFreq = hdr.SampFreq; newHdr.BytesPerSec = hdr.BytesPerSec; newHdr.BytesPerSamp = hdr.BytesPerSamp; newHdr.BitsPerSamp = hdr.BitsPerSamp; //std.strncpy(newHdr.data, hdr.data, 4); newHdr.WaveSize = waveSize; BinaryFile fs = new BinaryFile(filename); //fs.write((string) newHdr, sizeof(WaveHeader)); fs.Write(newHdr.RIFF); fs.Write(newHdr.DataLength); fs.Write(newHdr.WAVE); fs.Write(newHdr.fmt_); fs.Write(newHdr.SubBlockLength); fs.Write(newHdr.formatTag); fs.Write(newHdr.Channels); fs.Write(newHdr.SampFreq); fs.Write(newHdr.BytesPerSec); fs.Write(newHdr.BytesPerSamp); fs.Write(newHdr.BitsPerSamp); fs.Write(newHdr.data); fs.Write(newHdr.WaveSize); // convert our data from source channels to a temporary buffer short[] data = new short[waveSize/2]; for (int i = startPos, di = 0; i < endPos; ++i, ++di) { if (16 == hdr.BitsPerSamp) { if (2 == hdr.Channels) { data[2 *di] = LChTab[i]; data[2 *di+1] = RChTab[i]; } else { data[di] = LChTab[i]; } } else { if (2 == hdr.Channels) { //data[di/2] = ((RChTab[i] + 128) << 8) | (LChTab[i] + 128); } } } // write the raw data to file and clean the buffer for (int i = 0; i < data.Length; i++) { fs.Write(data[i]); } fs.Close(); data = null; }
private byte[] GetChunkData() { var memStream = new MemoryStream(); var bFile = new BinaryFile(memStream, BinaryFile.ByteOrder.LittleEndian); // Write UAD Preset Header information bFile.Write((int) PresetHeaderVar1); bFile.Write((int) PresetHeaderVar2); bFile.Write(PresetName, 32); // Write Parameters bFile.Write((float) Input); // (-20.0 dB -> 20.0 dB) bFile.Write((float) Phase); // (Normal -> Inverted) bFile.Write((float) HPFreq); // (Out -> 304 Hz) bFile.Write((float) LPFreq); // (Out -> 3.21 k) bFile.Write((float) HP_LPDynSC); // (Off -> On) bFile.Write((float) CMPRatio); // (1.00:1 -> Limit) bFile.Write((float) CMPThresh); // (10.0 dB -> -20.0 dB) bFile.Write((float) CMPRelease); // (0.10 s -> 4.00 s) bFile.Write((float) CMPAttack); // (Auto -> Fast) bFile.Write((float) StereoLink); // (UnLink -> Link) bFile.Write((float) Select); // (Expand -> Gate 2) bFile.Write((float) EXPThresh); // (-30.0 dB -> 10.0 dB) bFile.Write((float) EXPRange); // (0.0 dB -> 40.0 dB) bFile.Write((float) EXPRelease); // (0.10 s -> 4.00 s) bFile.Write((float) EXPAttack); // (Auto -> Fast) bFile.Write((float) DYNIn); // (Out -> In) bFile.Write((float) CompIn); // (Out -> In) bFile.Write((float) ExpIn); // (Out -> In) bFile.Write((float) LFGain); // (-10.0 dB -> 10.0 dB) bFile.Write((float) LFFreq); // (36.1 Hz -> 355 Hz) bFile.Write((float) LFBell); // (Shelf -> Bell) bFile.Write((float) LMFGain); // (-15.6 dB -> 15.6 dB) bFile.Write((float) LMFFreq); // (251 Hz -> 2.17 k) bFile.Write((float) LMFQ); // (2.50 -> 2.50) bFile.Write((float) HMFQ); // (4.00 -> 0.40) bFile.Write((float) HMFGain); // (-16.5 dB -> 16.5 dB) bFile.Write((float) HMFFreq); // (735 Hz -> 6.77 k) bFile.Write((float) HFGain); // (-16.0 dB -> 16.1 dB) bFile.Write((float) HFFreq); // (6.93 k -> 21.7 k) bFile.Write((float) HFBell); // (Shelf -> Bell) bFile.Write((float) EQIn); // (Out -> In) bFile.Write((float) EQDynSC); // (Off -> On) bFile.Write((float) PreDyn); // (Off -> On) bFile.Write((float) Output); // (-20.0 dB -> 20.0 dB) bFile.Write((float) EQType); // (Black -> Brown) bFile.Write((float) Power); // (Off -> On) byte[] chunkData = memStream.ToArray(); memStream.Close(); return chunkData; }
public void ReadFile(string filePath) { BinaryFile bf = new BinaryFile(filePath, BinaryFile.ByteOrder.BigEndian); ReadFXP(bf); }