示例#1
0
        public void Write(string filePath)
        {
            BinaryFile bf = new BinaryFile(filePath, BinaryFile.ByteOrder.BigEndian, true, Encoding.ASCII);

            Write(bf);
            bf.Close();
        }
示例#2
0
        public void ReadFile(string filePath)
        {
            BinaryFile bf  = new BinaryFile(filePath, BinaryFile.ByteOrder.BigEndian, false, Encoding.ASCII);
            var        fxp = ReadFXP(bf);

            Content     = fxp.Content;
            XmlDocument = fxp.XmlDocument;
            bf.Close(); // cannot close the binary file inside the ReadFXP method since a bank reads several programs of fxp content
        }
示例#3
0
        // constructor with byte array
        public FXP(byte[] values)
        {
            BinaryFile bf  = new BinaryFile(values, BinaryFile.ByteOrder.BigEndian, Encoding.ASCII);
            var        fxp = ReadFXP(bf);

            Content     = fxp.Content;
            XmlDocument = fxp.XmlDocument;
            bf.Close(); // cannot close the binary file inside the ReadFXP method since a bank reads several programs of fxp content
        }
示例#4
0
文件: Program.cs 项目: perivar/Code
        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);
        }
示例#5
0
        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();
            }
        }
示例#6
0
    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();
        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;
        }

        //********Tags********
        filesize = 56 + ((x *3)+zerobytes) * y;
        imagesize = 2 + ((x *3)+zerobytes) * y;

        GlobalMembersUtil.WriteUInt16(19778, bmpfile);
        GlobalMembersUtil.WriteUInt32((UInt32)filesize, bmpfile);
        GlobalMembersUtil.WriteUInt32(0, bmpfile);
        GlobalMembersUtil.WriteUInt32(54, bmpfile);
        GlobalMembersUtil.WriteUInt32(40, bmpfile);
        GlobalMembersUtil.WriteUInt32((UInt32)x, bmpfile);
        GlobalMembersUtil.WriteUInt32((UInt32)y, bmpfile);
        GlobalMembersUtil.WriteUInt16(1, bmpfile);
        GlobalMembersUtil.WriteUInt32(24, bmpfile);
        GlobalMembersUtil.WriteUInt16(0, bmpfile);
        GlobalMembersUtil.WriteUInt32((UInt32)imagesize, bmpfile);
        GlobalMembersUtil.WriteUInt32(2834, bmpfile);
        GlobalMembersUtil.WriteUInt32(2834, bmpfile);
        GlobalMembersUtil.WriteUInt32(0, bmpfile);
        GlobalMembersUtil.WriteUInt32(0, bmpfile);
        //--------Tags--------

        for (iy = y-1; iy!=-1; iy--) { // backwards writing
            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);
            }
        }

        GlobalMembersUtil.WriteUInt16(0, bmpfile);

        bmpfile.Close();

        #if DEBUG
        Console.Write("Image size : {0:D}x{1:D}\n", x, y);
        #endif
    }
示例#7
0
		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();
		}
示例#8
0
        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");
            }
        }
示例#9
0
        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;
        }
示例#10
0
		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;
		}
示例#11
0
        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();
            }
        }
示例#12
0
        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");
            }
        }
示例#13
0
        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("'", "&apos;");
                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();
        }
示例#14
0
        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);
        }
示例#15
0
		/**
		 * 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);
		}
示例#16
0
        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
        }
示例#17
0
		/**
		 * 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;
		}
示例#18
0
        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("'", "&apos;");
                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();
        }
示例#19
0
        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;
            }
        }
示例#20
0
    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 (GlobalMembersUtil.ReadUInt16(bmpfile) != 19778) // "BM" format tag check
        {
            Console.Error.WriteLine("This file is not in BMP format\n");
            GlobalMembersUtil.WinReturn();
            Environment.Exit(1);
        }

        bmpfile.Seek(8, SeekOrigin.Current); // skipping useless tags

        offset = (int) GlobalMembersUtil.ReadUInt32(bmpfile) - 54; // header offset

        bmpfile.Seek(4, SeekOrigin.Current); // skipping useless tags

        x = (int) GlobalMembersUtil.ReadUInt32(bmpfile);
        y = (int) GlobalMembersUtil.ReadUInt32(bmpfile);

        bmpfile.Seek(2, SeekOrigin.Current); // skipping useless tags

        if (GlobalMembersUtil.ReadUInt16(bmpfile) != 24) // Only format supported
        {
            Console.Error.WriteLine("Wrong BMP format, BMP images must be in 24-bit colour\n");
            GlobalMembersUtil.WinReturn();
            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;
        }

        for (iy = y-1; iy!=-1; iy--) { // backwards reading
            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;
    }
示例#21
0
    public static double[][] ReadWaveFile(BinaryFile wavfile, ref int channels, ref int samplecount, ref int samplerate)
    {
        double[][] sound;
        int i = 0;
        int ic = 0;
        int[] tag = new int[13];

        //			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
        // tag[5]	2     Compression code             1 - 65,535
        // 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

        for (i = 0; i<13; i++) // tag reading
        {
            tag[i] = 0;

            if ((i == 5) || (i == 6) || (i == 9) || (i == 10)) {
                tag[i] = GlobalMembersUtil.ReadUInt16(wavfile);
            } else {
                tag[i] = (int) GlobalMembersUtil.ReadUInt32(wavfile);
            }
        }

        //********File format checking********
        if (tag[0]!=1179011410 || tag[2]!=1163280727)
        {
            Console.Error.WriteLine("This file is not in WAVE format\n");
            GlobalMembersUtil.WinReturn();
            Environment.Exit(1);
        }

        if (tag[3]!=544501094 || tag[4]!=16 || tag[11]!=1635017060) //
        {
            Console.Error.WriteLine("This WAVE file format is not currently supported\n");
            GlobalMembersUtil.WinReturn();
            Environment.Exit(1);
        }

        if (tag[10]==24)
        {
            Console.Error.WriteLine("24 bit PCM WAVE files is not currently supported\n");
            GlobalMembersUtil.WinReturn();
            Environment.Exit(1);
        }

        if (tag[5] != WAVE_FORMAT_PCM) {
            Console.Error.WriteLine("Non PCM WAVE files is not currently supported\n");
            GlobalMembersUtil.WinReturn();
            Environment.Exit(1);
        }

        //--------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];
        }

        //********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);
            }
        }

        //--------Data loading--------

        wavfile.Close();
        return sound;
    }