Exemple #1
0
        public override void Write(BinaryWriter NewPicture)
        {
            Deflater defl = new Deflater();

            defl.SetInput(decopressedData);
            defl.SetLevel(compression.FLEVEL);
            byte[] compressedData = new byte[100000];
            defl.Deflate(compressedData);
            //byte[] data = compressedData.Where(x => x != 0).ToArray();

            //byte[] compressedData = Compress(decopressedData);

            Console.WriteLine("{0} {1}", compressedData.Length, byteData.Length);

            /*foreach (byte b in compressedData) Console.Write(b);
             * Console.WriteLine("\n\n");
             * foreach (byte b in byteData) Console.Write(b);
             * Console.WriteLine("");*/

            NewPicture.Write(BitConverter.GetBytes(compressedData.Length));
            NewPicture.Write(byteSign);
            NewPicture.Write(compressedData);
            NewPicture.Write(byteCheckSum);
        }
    public static byte[] Compress(byte[] input)
    {
        if (input == null || input.Length == 0)
        {
            Debug.LogError("Compress error inputBytes Len = 0");
            return(input);
        }

        // Create the compressor with highest level of compression
        Deflater compressor = GetDeflater();

        compressor.SetLevel(Deflater.BEST_COMPRESSION);

        // Give the compressor the data to compress
        compressor.SetInput(input);
        compressor.Finish();

        /*
         * Create an expandable byte array to hold the compressed data.
         * You cannot use an array that's the same size as the orginal because
         * there is no guarantee that the compressed data will be smaller than
         * the uncompressed data.
         */
        MemoryStream result = new MemoryStream(input.Length);

        // Compress the data
        byte[] buffer = new byte[1024];
        while (!compressor.IsFinished)
        {
            int count = compressor.Deflate(buffer);
            result.Write(buffer, 0, count);
        }

        // Get the compressed data
        return(result.ToArray());
    }
Exemple #3
0
    public static byte[] ZipBytes(byte[] input, int compressLevel)
    {
        UtilsFunc.Assert(input != null);
        Deflater compressor = new Deflater();

        compressor.SetLevel(compressLevel);

        compressor.SetInput(input);
        compressor.Finish();
        byte[] ret = null;

        using (MemoryStream bos = new MemoryStream(input.Length))
        {
            byte[] buf = new byte[1024];
            while (!compressor.IsFinished)
            {
                int count = compressor.Deflate(buf);
                bos.Write(buf, 0, count);
            }
            ret = bos.ToArray();
        }

        return(ret);
    }
Exemple #4
0
        private void Prepare()
        {
            Random random = new Random();

            this.iPGKSeed = (short)(random.Next(0x401, 0x7fff) % 0xffff);
            this.iTotalen = 0;
            for (int i = 0; i < this.iChapter.Count; i++)
            {
                this.iChapter[i] = ((string)this.iChapter[i]).Replace("\r\n", "\u2029");
                this.iContent    = this.iContent + ((string)this.iChapter[i]);
                this.iChapOff[i] = this.iTotalen;
                this.iTotalen   += ((string)this.iChapter[i]).Length * 2;
            }
            this.ibContent = new byte[this.iTotalen];
            int index = 0;

            for (int j = 0; j < this.iChapter.Count; j++)
            {
                byte[] bytes = new byte[((string)this.iChapter[j]).Length * 2];
                bytes = Encoding.Unicode.GetBytes((string)this.iChapter[j]);
                bytes.CopyTo(this.ibContent, index);
                index += bytes.Length;
            }
            int num4 = 0;

            if ((this.iTotalen % 0x8000) == 0)
            {
                num4 = this.iTotalen / 0x8000;
            }
            else
            {
                num4 = (this.iTotalen / 0x8000) + 1;
            }
            this.iZippedSeg = new byte[num4][];
            byte[] input = new byte[0x8000];
            int    num5  = 0;
            int    num6  = 0;

            for (int k = 0; k < this.ibContent.Length; k++)
            {
                input[num5] = this.ibContent[k];
                if ((num5 == 0x7fff) || (k == (this.ibContent.Length - 1)))
                {
                    byte[] output = new byte[0x8000];
                    num5 = 0;
                    Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, false);
                    if (deflater.IsNeedingInput)
                    {
                        deflater.SetInput(input, 0, input.Length);
                    }
                    deflater.Finish();
                    deflater.Deflate(output);
                    this.iZippedSeg[num6] = new byte[deflater.TotalOut];
                    Deflater deflater2 = new Deflater(Deflater.BEST_COMPRESSION, false);
                    if (deflater2.IsNeedingInput)
                    {
                        deflater2.SetInput(input, 0, input.Length);
                    }
                    deflater2.Finish();
                    deflater2.Deflate(this.iZippedSeg[num6]);
                    num6++;
                    input = Encoding.Unicode.GetBytes("");
                    input = new byte[0x8000];
                }
                else
                {
                    num5++;
                }
            }
        }
Exemple #5
0
 private static byte[] Zip(byte[] buffer, int version, byte[] key, byte[] iv)
 {
     byte[] buffer12;
     try
     {
         ZipStream stream = new ZipStream();
         if (version == 0)
         {
             Deflater deflater = new Deflater();
             DateTime now = DateTime.Now;
             long num = (long) ((ulong) ((((((((now.Year - 0x7bc) & 0x7f) << 0x19) | (now.Month << 0x15)) | (now.Day << 0x10)) | (now.Hour << 11)) | (now.Minute << 5)) | (now.Second >> 1)));
             uint[] numArray = new uint[] { 
                 0, 0x77073096, 0xee0e612c, 0x990951ba, 0x76dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0xedb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x9b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 
                 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 
                 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 
                 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 
                 0x76dc4190, 0x1db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x6b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0xf00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x86d3d2d, 0x91646c97, 0xe6635c01, 
                 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 
                 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 
                 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 
                 0xedb88320, 0x9abfb3b6, 0x3b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x4db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0xd6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0xa00ae27, 0x7d079eb1, 
                 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 
                 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 
                 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 
                 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x26d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x5005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0xcb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0xbdbdf21, 
                 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 
                 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 
                 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
              };
             uint maxValue = uint.MaxValue;
             uint num3 = maxValue;
             int num4 = 0;
             int length = buffer.Length;
             while (--length >= 0)
             {
                 num3 = numArray[(int) ((IntPtr) ((num3 ^ buffer[num4++]) & 0xff))] ^ (num3 >> 8);
             }
             num3 ^= maxValue;
             stream.WriteInt(0x4034b50);
             stream.WriteShort(20);
             stream.WriteShort(0);
             stream.WriteShort(8);
             stream.WriteInt((int) num);
             stream.WriteInt((int) num3);
             long position = stream.Position;
             stream.WriteInt(0);
             stream.WriteInt(buffer.Length);
             byte[] bytes = Encoding.UTF8.GetBytes("{data}");
             stream.WriteShort(bytes.Length);
             stream.WriteShort(0);
             stream.Write(bytes, 0, bytes.Length);
             deflater.SetInput(buffer);
             while (!deflater.IsNeedingInput)
             {
                 byte[] output = new byte[0x200];
                 int count = deflater.Deflate(output);
                 if (count <= 0)
                 {
                     break;
                 }
                 stream.Write(output, 0, count);
             }
             deflater.Finish();
             while (!deflater.IsFinished)
             {
                 byte[] buffer4 = new byte[0x200];
                 int num8 = deflater.Deflate(buffer4);
                 if (num8 <= 0)
                 {
                     break;
                 }
                 stream.Write(buffer4, 0, num8);
             }
             long totalOut = deflater.TotalOut;
             stream.WriteInt(0x2014b50);
             stream.WriteShort(20);
             stream.WriteShort(20);
             stream.WriteShort(0);
             stream.WriteShort(8);
             stream.WriteInt((int) num);
             stream.WriteInt((int) num3);
             stream.WriteInt((int) totalOut);
             stream.WriteInt(buffer.Length);
             stream.WriteShort(bytes.Length);
             stream.WriteShort(0);
             stream.WriteShort(0);
             stream.WriteShort(0);
             stream.WriteShort(0);
             stream.WriteInt(0);
             stream.WriteInt(0);
             stream.Write(bytes, 0, bytes.Length);
             stream.WriteInt(0x6054b50);
             stream.WriteShort(0);
             stream.WriteShort(0);
             stream.WriteShort(1);
             stream.WriteShort(1);
             stream.WriteInt(0x2e + bytes.Length);
             stream.WriteInt((30 + bytes.Length) + ((int) totalOut));
             stream.WriteShort(0);
             stream.Seek(position, SeekOrigin.Begin);
             stream.WriteInt((int) totalOut);
         }
         else if (version == 1)
         {
             byte[] buffer5;
             stream.WriteInt(0x17d7a7b);
             stream.WriteInt(buffer.Length);
             for (int i = 0; i < buffer.Length; i += buffer5.Length)
             {
                 buffer5 = new byte[Math.Min(0x1fffff, buffer.Length - i)];
                 Buffer.BlockCopy(buffer, i, buffer5, 0, buffer5.Length);
                 long num11 = stream.Position;
                 stream.WriteInt(0);
                 stream.WriteInt(buffer5.Length);
                 Deflater deflater2 = new Deflater();
                 deflater2.SetInput(buffer5);
                 while (!deflater2.IsNeedingInput)
                 {
                     byte[] buffer6 = new byte[0x200];
                     int num12 = deflater2.Deflate(buffer6);
                     if (num12 <= 0)
                     {
                         break;
                     }
                     stream.Write(buffer6, 0, num12);
                 }
                 deflater2.Finish();
                 while (!deflater2.IsFinished)
                 {
                     byte[] buffer7 = new byte[0x200];
                     int num13 = deflater2.Deflate(buffer7);
                     if (num13 <= 0)
                     {
                         break;
                     }
                     stream.Write(buffer7, 0, num13);
                 }
                 long num14 = stream.Position;
                 stream.Position = num11;
                 stream.WriteInt((int) deflater2.TotalOut);
                 stream.Position = num14;
             }
         }
         else
         {
             if (version == 2)
             {
                 stream.WriteInt(0x27d7a7b);
                 byte[] inputBuffer = Zip(buffer, 1, null, null);
                 using (ICryptoTransform transform = GetDesTransform(key, iv, false))
                 {
                     byte[] buffer9 = transform.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
                     stream.Write(buffer9, 0, buffer9.Length);
                     goto Label_044F;
                 }
             }
             if (version == 3)
             {
                 stream.WriteInt(0x37d7a7b);
                 byte[] buffer10 = Zip(buffer, 1, null, null);
                 using (ICryptoTransform transform2 = GetAesTransform(key, iv, false))
                 {
                     byte[] buffer11 = transform2.TransformFinalBlock(buffer10, 0, buffer10.Length);
                     stream.Write(buffer11, 0, buffer11.Length);
                 }
             }
         }
     Label_044F:
         stream.Flush();
         stream.Close();
         buffer12 = stream.ToArray();
     }
     catch (Exception exception)
     {
         ExceptionMessage = "ERR 2003: " + exception.Message;
         throw;
     }
     return buffer12;
 }
        /// <summary>
        /// Build a binary data frame form the frame object.
        /// </summary>
        /// <param name="frame">ID3 Frame</param>
        /// <returns>binary frame representation</returns>
        public byte[] Make(FrameBase frame, out ushort flags)
        {
            flags = GetFlags(frame);
            var buffer = frame.Make();

            var memoryStream = new MemoryStream();
            var writer       = new BinaryWriter(memoryStream);

            if (frame.Group.HasValue == true)
            {
                writer.Write((byte)frame.Group);
            }

            if (frame.Compression == true)
            {
                switch (Version)
                {
                case 3:
                {
                    writer.Write(Swap.Int32(buffer.Length));
                    break;
                }

                case 4:
                {
                    writer.Write(Sync.UnsafeBigEndian(Swap.UInt32((uint)buffer.Length)));
                    break;
                }

                default:
                {
                    throw new NotImplementedException("ID3v2 Version " + Version + " is not supported.");
                }
                }
                var buf      = new byte[2048];
                var deflater = new Deflater(Deflater.BEST_COMPRESSION);
                deflater.SetInput(buffer, 0, buffer.Length);
                deflater.Finish();
                while (!deflater.IsNeedingInput)
                {
                    int len = deflater.Deflate(buf, 0, buf.Length);
                    if (len <= 0)
                    {
                        break;
                    }
                    memoryStream.Write(buf, 0, len);
                }

                if (!deflater.IsNeedingInput)
                {
                    //TODO: Skip and remove invalid frames.
                    throw new InvalidFrameException("Can't decompress frame '" + frame.FrameId + "' missing data");
                }
            }
            else
            {
                memoryStream.Write(buffer, 0, buffer.Length);
            }

            if (frame.Encryption == true)
            {
                //TODO: Encryption
                throw new NotImplementedException("Encryption is not implemented, consequently it is not supported.");
            }

            if (frame.Unsynchronisation == true)
            {
                MemoryStream synchStream = new MemoryStream();
                Sync.Unsafe(memoryStream, synchStream, (uint)memoryStream.Position);
                memoryStream = synchStream;
            }
            return(memoryStream.ToArray());
        }
Exemple #7
0
        internal byte[] Make([NotNull] FrameBase frame, out ushort flags)
        {
            flags = GetFlags(frame);
            var buffer = frame.Make();

            var memoryStream   = new MemoryStream();
            var streamsToClose = new List <Stream>(2)
            {
                memoryStream
            };

            try
            {
                using (var writer = new BinaryWriter(memoryStream, Encoding.UTF8, true))
                {
                    if (frame.Group.HasValue)
                    {
                        writer.Write((byte)frame.Group);
                    }

                    if (frame.Compression)
                    {
                        switch (_version)
                        {
                        case 3:
                            writer.Write(Swap.Int32(buffer.Length));
                            break;

                        case 4:
                            writer.Write(Sync.UnsafeBigEndian(Swap.UInt32((uint)buffer.Length)));
                            break;

                        default:
                            throw new NotImplementedException($"ID3v2 Version {_version} is not supported.");
                        }

                        var buf      = new byte[2048];
                        var deflater = new Deflater(Deflater.BEST_COMPRESSION);
                        deflater.SetInput(buffer, 0, buffer.Length);
                        deflater.Finish();

                        while (!deflater.IsNeedingInput)
                        {
                            var len = deflater.Deflate(buf, 0, buf.Length);
                            if (len <= 0)
                            {
                                break;
                            }
                            memoryStream.Write(buf, 0, len);
                        }

                        //TODO: Skip and remove invalid frames.
                        if (!deflater.IsNeedingInput)
                        {
                            throw new InvalidFrameException($"Can't decompress frame '{frame.FrameId}' missing data");
                        }
                    }
                    else
                    {
                        memoryStream.Write(buffer, 0, buffer.Length);
                    }

                    //TODO: Encryption
                    if (frame.Encryption)
                    {
                        throw new NotImplementedException(
                                  "Encryption is not implemented, consequently it is not supported.");
                    }

                    if (frame.Unsynchronisation)
                    {
                        var synchStream = new MemoryStream();
                        streamsToClose.Add(synchStream);
                        Sync.Unsafe(memoryStream, synchStream, (uint)memoryStream.Position);
                        memoryStream = synchStream;
                    }

                    return(memoryStream.ToArray());
                }
            }
            finally
            {
                foreach (var streamToClose in streamsToClose)
                {
                    streamToClose.Close();
                }
            }
        }
            public async Task Execute(IReadableChannel input, IWritableChannel output)
            {
                while (true)
                {
                    var inputBuffer = await input;

                    if (inputBuffer.IsEmpty && input.Completion.IsCompleted)
                    {
                        break;
                    }

                    var writerBuffer = output.Alloc(2048);
                    var span         = inputBuffer.FirstSpan;

                    _deflater.SetInput(span.BufferPtr, span.Length);

                    while (!_deflater.NeedsInput())
                    {
                        int written = _deflater.ReadDeflateOutput(writerBuffer.Memory.BufferPtr, writerBuffer.Memory.Length);
                        writerBuffer.CommitBytes(written);
                    }

                    var consumed = span.Length - _deflater.AvailableInput;

                    inputBuffer = inputBuffer.Slice(0, consumed);

                    inputBuffer.Consumed();

                    await writerBuffer.FlushAsync();
                }

                bool flushed;

                do
                {
                    // Need to do more stuff here
                    var writerBuffer = output.Alloc(2048);

                    int compressedBytes;
                    flushed = _deflater.Flush(writerBuffer.Memory.BufferPtr, writerBuffer.Memory.Length, out compressedBytes);
                    writerBuffer.CommitBytes(compressedBytes);

                    await writerBuffer.FlushAsync();
                }while (flushed);

                bool finished;

                do
                {
                    // Need to do more stuff here
                    var writerBuffer = output.Alloc(2048);

                    int compressedBytes;
                    finished = _deflater.Finish(writerBuffer.Memory.BufferPtr, writerBuffer.Memory.Length, out compressedBytes);
                    writerBuffer.CommitBytes(compressedBytes);

                    await writerBuffer.FlushAsync();
                }while (!finished);

                input.CompleteReading();

                output.CompleteWriting();

                _deflater.Dispose();
            }
Exemple #9
0
 /// <summary>
 /// Writes bytes from an array to the compressed stream.
 /// </summary>
 /// <param name="buffer">
 /// The byte array.
 /// </param>
 /// <param name="offset">
 /// The offset into the byte array where to start.
 /// </param>
 /// <param name="count">
 /// The number of bytes to write.
 /// </param>
 public override void Write(byte[] buffer, int offset, int count)
 {
     Deflater.SetInput(buffer, offset, count);
     Deflate();
 }
Exemple #10
0
        private void WritePendingFrame(bool forceKeyFrame)
        {
            if (!framePending)
            {
                return;
            }
            framePending = false;

            bool keyFrame = forceKeyFrame || frameCount % keyFramePeriodInFrames == 0;

            FlvWriter.FlvVideoFrameFlags frameFlags = FlvWriter.FlvVideoFrameFlags.Codec_ScreenVideo
                                                      | (keyFrame ? FlvWriter.FlvVideoFrameFlags.Type_KeyFrame : FlvWriter.FlvVideoFrameFlags.Type_InterFrame);

            flvWriter.WriteFlvVideoFrame(frameFlags,
                                         (int)(frameCount * 1000.0 / framesPerSecond),
                                         reserveBytesPerFrame,
                                         delegate(byte[] buffer, ref int bufferOffset)
            {
                // write frame header
                buffer[bufferOffset++] = (byte)(((nominalBlockWidth / 16 - 1) << 4) | (width >> 8));
                buffer[bufferOffset++] = (byte)width;
                buffer[bufferOffset++] = (byte)(((nominalBlockHeight / 16 - 1) << 4) | (height >> 8));
                buffer[bufferOffset++] = (byte)height;

                // proceed from bottom-left to top-right row by row
                for (int blockYOrigin = height; blockYOrigin >= 0; blockYOrigin -= nominalBlockHeight)
                {
                    int blockHeight = Math.Min(blockYOrigin, nominalBlockHeight);

                    for (int blockXOrigin = 0; blockXOrigin < width; blockXOrigin += nominalBlockWidth)
                    {
                        int blockWidth = Math.Min(width - blockXOrigin, nominalBlockWidth);

                        bool diff             = false;
                        int blockBufferOffset = 0;
                        int frameOffset       = blockYOrigin * width + blockXOrigin;
                        for (int y = 0; y < blockHeight; y++)
                        {
                            frameOffset -= width;

                            for (int x = 0; x < blockWidth; x++)
                            {
                                int color = currentFramePixels[frameOffset];

                                blockBuffer[blockBufferOffset++] = (byte)color;         // B
                                blockBuffer[blockBufferOffset++] = (byte)(color >> 8);  // G
                                blockBuffer[blockBufferOffset++] = (byte)(color >> 16); // R

                                if (previousFramePixels[frameOffset++] != color)
                                {
                                    diff = true;
                                }
                            }

                            frameOffset -= blockWidth;
                        }

                        if (keyFrame || diff)
                        {
                            deflater.Reset();
                            deflater.SetInput(blockBuffer, 0, blockBufferOffset);
                            deflater.Finish();

                            int blockLength = deflater.Deflate(buffer, bufferOffset + 2, buffer.Length - bufferOffset - 2);
                            Debug.Assert(deflater.IsFinished, "Deflater should be finished.");

                            buffer[bufferOffset++] = (byte)(blockLength >> 8);
                            buffer[bufferOffset++] = (byte)blockLength;
                            bufferOffset          += blockLength;
                        }
                        else
                        {
                            buffer[bufferOffset++] = 0;
                            buffer[bufferOffset++] = 0;
                        }
                    }
                }
            });

            frameCount += 1;
        }
        static PNG_Chunk[] ProcessChunks(PNG_Chunk[] chunks)
        {
            List <PNG_Chunk> result = new List <PNG_Chunk>();

            PNG_IHDR header = new PNG_IHDR();

            using (MemoryStream rawData = new MemoryStream())
            {
                foreach (PNG_Chunk chunk in chunks)
                {
                    if (chunk.Name.Equals(PNG_CgBIChunk))
                    {
                        continue;
                    }

                    if (chunk.Name.Equals(PNG_HeaderChunk))
                    {
                        header = PNG_IHDR.FromBytes(chunk.Data);
                    }

                    if (chunk.Name.Equals(PNG_DataChunk))
                    {
                        rawData.Write(chunk.Data, 0, chunk.Data.Length);
                        continue;
                    }

                    if (chunk.Name.Equals(PNG_EndChunk))
                    {
                        const int dataChunkSize = 16 * 1024;

                        rawData.Position = 0;
                        using (MemoryStream buffer = new MemoryStream())
                        {
                            using (InflaterInputStream inflate = new InflaterInputStream(rawData, new Inflater(true)))
                            {
                                inflate.IsStreamOwner = false;
                                IPATools.Utilities.Utils.CopyStream(inflate, buffer);
                                //inflate.CopyTo(buffer);
                            }

                            buffer.Position = 0;
                            rawData.SetLength(0);
                            IPATools.Utilities.Utils.CopyStream(buffer, rawData);
                            //buffer.CopyTo(rawData);
                        }

                        {
                            byte[] imageData = rawData.GetBuffer();

                            int scanlineSize = header.Width * 4 + 1;
                            int scanlinePos  = 0;

                            int bpp = 4;

                            for (int y = 0; y < header.Height; ++y, scanlinePos += scanlineSize)
                            {
                                PNG_Filter filter = (PNG_Filter)imageData[scanlinePos];

                                switch (filter)
                                {
                                case PNG_Filter.Sub:
                                    for (int x = 1 + bpp; x < scanlineSize; ++x)
                                    {
                                        imageData[scanlinePos + x] = (byte)((int)imageData[scanlinePos + x] + (int)imageData[scanlinePos + x - bpp]);
                                    }
                                    break;

                                case PNG_Filter.Up:
                                    if (y > 0)
                                    {
                                        for (int x = 1; x < scanlineSize; ++x)
                                        {
                                            imageData[scanlinePos + x] = (byte)((int)imageData[scanlinePos + x] + (int)imageData[scanlinePos + x - bpp - scanlineSize]);
                                        }
                                    }
                                    break;

                                case PNG_Filter.Average:
                                    if (y > 0)
                                    {
                                        for (int x = 1 + bpp; x < scanlineSize; ++x)
                                        {
                                            imageData[scanlinePos + x] = (byte)
                                                                         (((int)imageData[scanlinePos + x - bpp] +
                                                                           (int)imageData[scanlinePos + x - bpp - scanlineSize]) >> 1);
                                        }
                                    }
                                    break;

                                case PNG_Filter.Paeth:
                                    if (y > 0)
                                    {
                                        for (int x = 1 + bpp; x < scanlineSize; ++x)
                                        {
                                            imageData[scanlinePos + x] =
                                                (byte)FilterPaethPredictor(
                                                    imageData[scanlinePos + x - bpp],
                                                    imageData[scanlinePos + x - bpp - scanlineSize],
                                                    imageData[scanlinePos + x - scanlineSize]);
                                        }
                                    }
                                    break;
                                }

                                for (int x = 0; x < header.Width; ++x)
                                {
                                    byte r = imageData[scanlinePos + x * 4 + 1];
                                    byte g = imageData[scanlinePos + x * 4 + 2];
                                    byte b = imageData[scanlinePos + x * 4 + 3];
                                    byte a = imageData[scanlinePos + x * 4 + 4];

                                    if (a > 0)
                                    {
                                        r = (byte)(255 * r / a);
                                        g = (byte)(255 * g / a);
                                        b = (byte)(255 * b / a);
                                    }

                                    imageData[scanlinePos + x * 4 + 1] = b;
                                    imageData[scanlinePos + x * 4 + 2] = g;
                                    imageData[scanlinePos + x * 4 + 3] = r;
                                    imageData[scanlinePos + x * 4 + 4] = a;
                                }

                                imageData[scanlinePos] = (byte)PNG_Filter.None;

                                //imageData[scanlinePos] = (byte)PNG_Filter.Sub;
                                //for (int x = 1 + bpp; x < scanlineSize; ++x)
                                //{
                                //    byte c = imageData[scanlinePos + x];
                                //    byte l = imageData[scanlinePos + x - bpp];
                                //    imageData[scanlinePos + x] = (byte)(l - c);
                                //}
                            }
                        }

                        Deflater deflater = new Deflater(9);

                        Crc32 crc32 = new Crc32();

                        rawData.Position = 0;
                        long dataLeft = rawData.Length;
                        while (dataLeft > 0)
                        {
                            byte[] chunkData = new byte[dataChunkSize];

                            int dataInChunk = rawData.Read(chunkData, 0, dataChunkSize);

                            dataLeft -= dataInChunk;

                            byte[] deflatedChunkData = new byte[dataChunkSize];
                            deflater.SetInput(chunkData, 0, dataInChunk);
                            if (dataLeft > 0)
                            {
                                deflater.Flush();
                            }
                            else
                            {
                                deflater.Finish();
                            }
                            int deflatedBytes = deflater.Deflate(deflatedChunkData, 0, dataInChunk);

                            PNG_Chunk dataChunk = new PNG_Chunk();
                            dataChunk.Name = PNG_DataChunk;
                            dataChunk.Data = new byte[deflatedBytes];

                            for (int i = 0; i < deflatedBytes; ++i)
                            {
                                dataChunk.Data[i] = deflatedChunkData[i];
                            }

                            crc32.Reset();
                            crc32.Update(ASCIIEncoding.ASCII.GetBytes(dataChunk.Name));
                            crc32.Update(dataChunk.Data);
                            dataChunk.CRC = (uint)crc32.Value;

                            result.Add(dataChunk);
                        }
                    }

                    result.Add(chunk);
                }
            }

            return(result.ToArray());
        }
Exemple #12
0
            public async Task Execute(IReadableChannel input, IWritableChannel output)
            {
                while (true)
                {
                    var inputBuffer = await input.ReadAsync();

                    if (inputBuffer.IsEmpty && input.Reading.IsCompleted)
                    {
                        break;
                    }

                    var writerBuffer = output.Alloc(2048);
                    var memory       = inputBuffer.First;

                    unsafe
                    {
                        _deflater.SetInput((IntPtr)memory.UnsafePointer, memory.Length);
                    }

                    while (!_deflater.NeedsInput())
                    {
                        unsafe
                        {
                            int written = _deflater.ReadDeflateOutput((IntPtr)writerBuffer.Memory.UnsafePointer, writerBuffer.Memory.Length);
                            writerBuffer.Advance(written);
                        }
                    }

                    var consumed = memory.Length - _deflater.AvailableInput;

                    inputBuffer = inputBuffer.Slice(0, consumed);

                    input.Advance(inputBuffer.End);

                    await writerBuffer.FlushAsync();
                }

                bool flushed;

                do
                {
                    // Need to do more stuff here
                    var writerBuffer = output.Alloc(2048);
                    var memory       = writerBuffer.Memory;

                    unsafe
                    {
                        int compressedBytes;
                        flushed = _deflater.Flush((IntPtr)memory.UnsafePointer, memory.Length, out compressedBytes);
                        writerBuffer.Advance(compressedBytes);
                    }

                    await writerBuffer.FlushAsync();
                }while (flushed);

                bool finished;

                do
                {
                    // Need to do more stuff here
                    var writerBuffer = output.Alloc(2048);
                    var memory       = writerBuffer.Memory;

                    unsafe
                    {
                        int compressedBytes;
                        finished = _deflater.Finish((IntPtr)memory.UnsafePointer, memory.Length, out compressedBytes);
                        writerBuffer.Advance(compressedBytes);
                    }

                    await writerBuffer.FlushAsync();
                }while (!finished);

                input.Complete();

                output.Complete();

                _deflater.Dispose();
            }
        public static String Compress(string str)
        {
            byte[] bytesToCompress = ASCIIEncoding.UTF8.GetBytes(str);
            // Compressor with highest level of compression.
            Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION);
            compressor.SetInput(bytesToCompress); // Give the compressor the data to
            // compress.
            compressor.Finish();

            // Create an expandable byte array to hold the compressed data.
            // It is not necessary that the compressed data will be smaller than
            // the uncompressed data.
            byte[] ret = null;

            using (MemoryStream memStream = new MemoryStream(bytesToCompress.Length))
            {
                // Compress the data
                byte[] buf = new byte[bytesToCompress.Length + 100];
                while (!compressor.IsFinished)
                {
                    memStream.Write(buf, 0, compressor.Deflate(buf));
                }
                memStream.Close();
                ret = memStream.ToArray();
            }

            // Get the compressed data
            return Convert.ToBase64String(ret);
        }
Exemple #14
0
        private byte[][] CompressTxtContent(Encoding encoding, CChapterList chapters)
        {
            string    s    = string.Empty;
            int       num  = 0;
            ArrayList list = new ArrayList(chapters.Count);

            int[] numArray = new int[chapters.Count];
            for (int i = 0; i < chapters.Count; i++)
            {
                string str2 = chapters[i].Content.Replace("\r\n", "\u2029") + "\u2029";
                list.Add(str2);
                s           = s + str2;
                numArray[i] = num;
                num        += str2.Length * 2;
            }
            byte[] bytes = new byte[num];
            bytes = Encoding.Unicode.GetBytes(s);
            int num3 = 0;

            if ((num % 0x8000) == 0)
            {
                num3 = num / 0x8000;
            }
            else
            {
                num3 = (num / 0x8000) + 1;
            }
            byte[][] bufferArray = new byte[num3][];
            int      index       = 0;

            byte[] input = new byte[0x8000];
            int    num5  = 0;

            for (int j = 0; j < bytes.Length; j++)
            {
                input[num5] = bytes[j];
                num5++;
                if ((num5 == 0x8000) || (j == (bytes.Length - 1)))
                {
                    byte[]   output   = new byte[0x8000];
                    Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, false);
                    if (deflater.IsNeedingInput)
                    {
                        deflater.SetInput(input, 0, input.Length);
                    }
                    deflater.Finish();
                    deflater.Deflate(output);
                    bufferArray[index] = new byte[deflater.TotalOut];
                    Deflater deflater2 = new Deflater(Deflater.BEST_COMPRESSION, false);
                    if (deflater2.IsNeedingInput)
                    {
                        deflater2.SetInput(input, 0, input.Length);
                    }
                    deflater2.Finish();
                    deflater2.Deflate(bufferArray[index]);
                    index++;
                    input = null;
                    input = new byte[0x8000];
                    num5  = 0;
                }
            }
            return(bufferArray);
        }
 /// <summary>
 /// Writes a len bytes from an array to the compressed stream.
 /// </summary>
 /// <param name="buf">
 /// the byte array.
 /// </param>
 /// <param name="off">
 /// the offset into the byte array where to start.
 /// </param>
 /// <param name="len">
 /// the number of bytes to write.
 /// </param>
 public override void Write(byte[] buf, int off, int len)
 {
     //    System.err.println("DOS with off " + off + " and len " + len);
     def.SetInput(buf, off, len);
     deflate();
 }
Exemple #16
0
        /// <inheritdoc/>
        public IDataStorerEntry Add(string path, params byte[] data)
        {
            Validation.NotNull("Path", path);
            Validation.NotNull("Data", data);

            string normalizedPath = path.Replace('\\', '/');

            int pos = normalizedPath.IndexOf(':');

            if (pos >= 0)
            {
                normalizedPath = normalizedPath.Remove(0, pos + 1);
            }

            normalizedPath = normalizedPath.Trim('/');

            int uncompressedLength = data.Length;
            int compressedLength;

            byte[]            compressedData;
            CompressionMethod compressionMethod;

            if (this.enableCompression)
            {
                Deflater deflater = new Deflater(Deflater.DEFLATED);
                deflater.SetInput(data, 0, uncompressedLength);
                deflater.Finish();

                compressedData   = new byte[uncompressedLength];
                compressedLength = deflater.Deflate(compressedData, 0, uncompressedLength);
                if (deflater.IsFinished && compressedLength <= uncompressedLength)
                {
                    // Use deflate
                    compressionMethod = CompressionMethod.Deflate;
                }
                else
                {
                    // Force to store
                    compressedData    = data;
                    compressedLength  = uncompressedLength;
                    compressionMethod = CompressionMethod.Store;
                }
            }
            else
            {
                // Only store
                compressedData    = data;
                compressedLength  = uncompressedLength;
                compressionMethod = CompressionMethod.Store;
            }

            uint uncompressedSize = (uint)uncompressedLength;
            uint compressedSize   = (uint)compressedLength;
            uint crc32            = CRC32.Calculate(data);
            uint headerOffset     = (uint)this.zipFileWriter.Position;

            ZipWriteOnlyStorerEntry fileEntry = new ZipWriteOnlyStorerEntry(
                normalizedPath,
                uncompressedSize,
                compressionMethod,
                compressedSize,
                headerOffset,
                crc32,
                DateTime.Now,
                comment ?? ""
                );

            this.WriteFileHeader(this.zipFileWriter, fileEntry, false);

            this.zipFileWriter.WriteBytes(compressedData, 0, compressedLength);
            this.entries.AddLast(fileEntry);

            return(fileEntry);
        }
 /// <summary>
 /// Writes bytes from an array to the compressed stream.
 /// </summary>
 /// <param name="buf">The byte array</param>
 /// <param name="off">The offset into the byte array where to start.</param>
 /// <param name="len">The number of bytes to write.</param>
 public override void Write(byte[] buf, int off, int len)
 {
     def.SetInput(buf, off, len);
     Deflate();
 }
Exemple #18
0
        public void PackText(FileStream fileStream, uint off, uint zsize, uint size, Dictionary <ulong, string> dbd, uint hash2, uint hash1, int endtable, int somework)
        {
            BinaryReader binaryReader = new BinaryReader(fileStream);

            binaryReader.BaseStream.Position = off;
            binaryReader.ReadBytes(36);
            byte[]   input    = binaryReader.ReadBytes((int)zsize);
            byte[]   buffer   = new byte[size];
            Inflater inflater = new Inflater();

            inflater.SetInput(input);
            inflater.Inflate(buffer);
            BinaryReader binaryReader2 = new BinaryReader(new MemoryStream(buffer));

            binaryReader2.ReadBytes(3);
            int num  = binaryReader2.ReadInt32();
            int num2 = num * 26 + 7;
            Dictionary <ulong, string> dictionary = new Dictionary <ulong, string>();
            int          num3         = 0;
            MemoryStream memoryStream = new MemoryStream();
            BinaryWriter binaryWriter = new BinaryWriter(memoryStream);

            binaryWriter.Write((byte)1);
            binaryWriter.Write((byte)0);
            binaryWriter.Write((byte)0);
            binaryWriter.Write(num);
            while (num3 < num)
            {
                long  num4   = binaryReader2.ReadInt64();
                byte  b      = binaryReader2.ReadByte();
                byte  value  = binaryReader2.ReadByte();
                float value2 = binaryReader2.ReadSingle();
                int   num5   = binaryReader2.ReadInt32();
                int   num6   = binaryReader2.ReadInt32();
                binaryReader2.ReadInt32();
                long   position     = binaryReader2.BaseStream.Position;
                string change_value = "0";
                if (num5 > 0)
                {
                    binaryReader2.BaseStream.Seek(num6, SeekOrigin.Begin);
                    byte[] bytes = binaryReader2.ReadBytes(num5);
                    string text  = Encoding.UTF8.GetString(bytes).Replace("\n", "\\n");
                    ulong  key   = UniqueId(num4, b);
                    if (changes == "1")
                    {
                        if (dictionary_en.TryGetValue(key, out string _))
                        {
                            if (dictionary_en[key] != text)
                            {
                                dbd.Remove(key);
                                dictionary_xml_m.Remove(key);
                                dictionary_xml_w.Remove(key);
                                dictionary_xml_translator_m.Remove(key);
                                dictionary_xml_translator_w.Remove(key);
                                change_value = "1";
                            }
                            else
                            {
                                change_value = "0";
                            }
                        }
                    }
                    if (dbd.TryGetValue(key, out string _))
                    {
                        dictionary.Add(key, dbd[key]);
                        _    = dbd[key];
                        num5 = Encoding.UTF8.GetBytes(dbd[key].Replace("\\n", "\n")).Length;
                    }
                    else
                    {
                        transl_a = "";
                        if (ConfigurationManager.AppSettings["a_translate"] == "1" && somework == 1)
                        {
                            if (File.Exists(@"C:\\Program Files\\Mozilla Firefox\\firefox.exe") || File.Exists(@"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"))
                            {
                                transl_a = Translator(text, "Deepl");

                                /*string instrrr = "INSERT INTO Translated (fileinfo,hash,key_unic,text_en,text_ru_m,translator_m) VALUES ('" + hash1 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(transl_a) + "','Deepl');";
                                 * using (StreamWriter file_for_exam = new StreamWriter("db\\deepl_trans.txt", true))
                                 * {
                                 *  file_for_exam.WriteLine(instrrr);
                                 * }
                                 * transl_a = "";*/
                            }
                            else
                            {
                                transl_a = Translator(text, "Promt");
                            }
                        }
                        if (transl_a == "")
                        {
                            dictionary.Add(key, text);
                            dictionary_xml_m.Add(key, text);
                            dictionary_xml_w.Add(key, text);
                            dictionary_xml_translator_m.Add(key, "Deepl");
                            dictionary_xml_translator_w.Add(key, "Deepl");
                            num5 = Encoding.UTF8.GetBytes(text.Replace("\\n", "\n")).Length;
                        }
                        else
                        {
                            dictionary.Add(key, transl_a);
                            dictionary_xml_m.Add(key, transl_a);
                            dictionary_xml_w.Add(key, transl_a);
                            dictionary_xml_translator_m.Add(key, "Deepl");
                            dictionary_xml_translator_w.Add(key, "Deepl");
                            num5 = Encoding.UTF8.GetBytes(transl_a.Replace("\\n", "\n")).Length;
                            using (SQLiteConnection sqlite_conn = new SQLiteConnection("Data Source=db\\translate.db3; Version = 3; New = True; Compress = True; "))
                            {
                                sqlite_conn.Open();
                                using (SQLiteCommand sqlite_cmd = new SQLiteCommand(sqlite_conn))
                                {
                                    if (change_value == "1")
                                    {
                                        sqlite_cmd.CommandText = "UPDATE Translated SET text_en='" + WebUtility.HtmlEncode(text) + "', text_ru_m='" + WebUtility.HtmlEncode(transl_a) + "',translator_m='Deepl',text_ru_w=NULL,translator_w=NULL WHERE key_unic ='" + key + "'";
                                    }
                                    else
                                    {
                                        sqlite_cmd.CommandText = "INSERT INTO Translated (fileinfo,hash,key_unic,text_en,text_ru_m,translator_m) VALUES ('" + hash1 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(transl_a) + "','Deepl')";
                                    }
                                    sqlite_cmd.ExecuteNonQuery();
                                }
                            }
                        }

                        /*string xml_text = "<hash>" + hash1 + "</hash><key>" + key + "</key><text_en>" + WebUtility.HtmlEncode(text) + "</text_en>";
                         * using (StreamWriter file_for_exam =
                         * new StreamWriter("db\\new_eng.txt", true))
                         * {
                         *  file_for_exam.WriteLine(xml_text);
                         * }
                         *
                         * string xml_text = "<filesinfo></filesinfo><hash>" + hash1 + "</hash><key>" + key + "</key><text_en>" + WebUtility.HtmlEncode(text) + "</text_en><text_ru_m transl=\"3\">" + WebUtility.HtmlEncode(dbd[key]) + "</text_ru_m><text_ru_w  transl=\"3\"></text_ru_w>";
                         *      using (StreamWriter file_for_exam =
                         *      new StreamWriter(@"C:\Users\Tidus\source\repos\SWToR_RUS\bin\Debug\db\all2.txt", true, encoding: Encoding.UTF8))
                         *      {
                         *          file_for_exam.WriteLine(xml_text);
                         *      }
                         *      SQLiteConnection sqlite_conn;
                         *      sqlite_conn = new SQLiteConnection("Data Source=db\\translate.db3; Version = 3; New = True; Compress = True; ");
                         *      sqlite_conn.Open();
                         *      SQLiteCommand sqlite_cmd;
                         *      sqlite_cmd = sqlite_conn.CreateCommand();
                         *      string sql_insert = "INSERT INTO Translated (hash,key_unic,text_en,text_ru_m,translator_m) VALUES ('" + hash1.ToString() + "','" + key.ToString() + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(dbd[key]) + "','3')";
                         *      sqlite_cmd.CommandText = sql_insert;
                         *      sqlite_cmd.ExecuteNonQuery();
                         *      sqlite_conn.Close();*/
                    }

                    /*if (somework == 1)
                     * {
                     *  string tmp_base;
                     *  if (dictionary_xml_translator_w.TryGetValue(key, out string sdfg) && dictionary_xml_m[key] != dictionary_xml_w[key])
                     *  {
                     *      tmp_base = "INSERT INTO Translated (fileinfo,hash,key_unic,text_en,text_ru_m,translator_m,text_ru_w,translator_w) VALUES ('" + hash1 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(dictionary_xml_m[key]).Replace("\n \n", "\n\n").Replace("\n", "\\n") + "','" + dictionary_xml_translator_m[key] + "','" + WebUtility.HtmlEncode(dictionary_xml_w[key]).Replace("\n \n", "\n\n").Replace("\n", "\\n") + "','" + dictionary_xml_translator_w[key] + "');";
                     *  }
                     *  else
                     *  {
                     *      tmp_base = "INSERT INTO Translated (fileinfo,hash,key_unic,text_en,text_ru_m,translator_m) VALUES ('" + hash1 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(dictionary_xml_m[key]).Replace("\n \n", "\n\n").Replace("\n", "\\n") + "','" + dictionary_xml_translator_m[key] + "');";
                     *  }
                     * tmp_base = "'" + nu88 + "','" + num4 + "','" + b + "','" + value + "','" + value2 + "','" + num6 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(dictionary_xml_m[key]).Replace("\n \n", "\n\n").Replace("\n", "\\n") + "','" + dictionary_xml_translator_m[key] + "'";
                     *  using (StreamWriter file_for_exam = new StreamWriter("db\\allbase.txt", true))
                     *  {
                     *      file_for_exam.WriteLine(tmp_base);
                     *  }
                     * }*/
                }
                binaryReader2.BaseStream.Position = position;
                num3++;
                binaryWriter.Write(num4);
                binaryWriter.Write(b);
                binaryWriter.Write(value);
                binaryWriter.Write(value2);
                binaryWriter.Write(num5);
                binaryWriter.Write(num2);
                num2 += num5;
                binaryWriter.Write(num5);
            }
            foreach (KeyValuePair <ulong, string> item in dictionary)
            {
                Encoding.UTF8.GetBytes(item.Value.Replace("\\n", "\n"));
                binaryWriter.Write(Encoding.UTF8.GetBytes(item.Value.Replace("\\n", "\n")));
            }
            MemoryStream memoryStream2 = new MemoryStream();
            Deflater     deflater      = new Deflater();

            deflater.SetInput(memoryStream.ToArray());
            deflater.Finish();
            byte[] array = new byte[size * 3];
            while (!deflater.IsNeedingInput)
            {
                int count = deflater.Deflate(array);
                memoryStream2.Write(array, 0, count);
                if (deflater.IsFinished)
                {
                    break;
                }
            }
            deflater.Reset();
            int newsize  = memoryStream.ToArray().Length;
            int newzsize = memoryStream2.ToArray().Length;

            byte[] array2 = new byte[36];
            array2[0] = 2;
            array2[2] = 32;
            byte[] array3 = new byte[array2.Length + memoryStream2.ToArray().Length];
            array2.CopyTo(array3, 0);
            memoryStream2.ToArray().CopyTo(array3, array2.Length);

            if (somework == 1)
            {
                using (StreamReader Hashes_Names = new StreamReader("db\\hashes_filename.txt", Encoding.Default))
                {
                    while (!Hashes_Names.EndOfStream)
                    {
                        string line = Hashes_Names.ReadLine();
                        if (line.IndexOf(hash1.ToString("X")) != -1)
                        {
                            string rez  = line.Substring(line.IndexOf("/resources/en-us/str/") + 21);
                            string rez2 = rez.Substring(0, rez.IndexOf("#"));
                            if (File_Name_List.Contains(hash1.ToString()))
                            {
                                using (SQLiteConnection sqlite_conn = new SQLiteConnection("Data Source=db\\translate.db3; Version = 3; New = True; Compress = True; "))
                                {
                                    sqlite_conn.Open();
                                    using (SQLiteCommand sqlite_cmd = new SQLiteCommand(sqlite_conn))
                                    {
                                        sqlite_cmd.CommandText = "UPDATE Translated SET fileinfo='" + WebUtility.HtmlEncode(rez2) + "' WHERE hash ='" + hash1 + "'";
                                        sqlite_cmd.ExecuteNonQuery();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Hhh(fileStream, array3, newzsize, newsize, hash2, hash1, endtable);
        }
Exemple #19
0
        private byte[] CompressRecord(string path)
        {
            var len   = (int)((new FileInfo(path)).Length);
            var level = 5;

            switch (cmbCompLevel.SelectedIndex)
            {
            case 0:
                level = 9;
                break;

            case 1:
                level = 7;
                break;

            case 2:
                level = 5;
                break;

            case 3:
                level = 3;
                break;

            case 4:
                level = 1;
                break;
            }
            var def = new Deflater(level);
            var In  = File.ReadAllBytes(path);
            var Out = new byte[In.Length + 64];

            def.SetInput(In);
            def.Finish();
            var size = def.Deflate(Out);

            Array.Resize(ref Out, size);

            float mul = 0;

            switch (cmbCompression.SelectedIndex)
            {
            case 6:
            case 5:
                return(Out);

            case 4:
                mul = 0.8f;
                break;

            case 3:
                mul = 0.6f;
                break;

            case 2:
                mul = 0.4f;
                break;

            case 1:
                mul = 0.2f;
                break;
            }
            var f = size / (float)len;

            if (f < mul)
            {
                return(Out);
            }
            return(null);
        }
Exemple #20
0
    static int Deflate(Deflater def, byte [] src, byte [] dest)
    {
        bool count;
        int offset, length, remain;

        if (dest == null) {
            dest = new byte [BlockSize];
            count = true;
        } else
            count = false;

        def.Reset ();
        def.SetInput (src);

        offset = 0;
        while (!def.IsFinished) {
            if (def.IsNeedingInput)
                def.Finish ();

            remain = Math.Min (dest.Length - offset, BlockSize);
            if (remain == 0)
                break;

            length = def.Deflate (dest, offset, remain);
            if (!count)
                offset += length;
        }

        return def.TotalOut;
    }
Exemple #21
0
        /// <summary>
        /// Writes the MPK to a specific filename
        /// </summary>
        /// <param name="fname"></param>
        public void Write(string fname)
        {
            Deflater def;

            byte[] buf, dir, name;
            var    files = new MPKFile[_files.Count];

            using (var dirmem = new MemoryStream(_files.Count * MPKFileHeader.MaxSize))
            {
                int  index     = 0;
                uint offset    = 0;
                uint diroffset = 0;

                foreach (MPKFile file in _files.Values)
                {
                    file.Header.DirectoryOffset = diroffset;
                    file.Header.Offset          = offset;
                    files[index] = file;

                    using (var wrtr = new BinaryWriter(dirmem, Encoding.UTF8))
                    {
                        file.Header.Write(wrtr);
                    }

                    offset    += file.Header.UncompressedSize;
                    diroffset += file.Header.CompressedSize;
                    index++;
                }

                def = new Deflater();
                def.SetInput(dirmem.GetBuffer(), 0, (int)dirmem.Position);
                def.Finish();

                dir = new byte[dirmem.Position];
                def.Deflate(dir);
                _sizeDir = (int)def.TotalOut;
            }

            def = new Deflater();

            _crc.Reset();
            _crc.Update(dir, 0, _sizeDir);

            def.SetInput(Encoding.UTF8.GetBytes(_name));
            def.Finish();

            name = new byte[_name.Length];
            def.Deflate(name);

            _numFiles = _files.Count;
            _sizeName = (int)def.TotalOut;

            using (var filemem = new MemoryStream())
            {
                using (var wrtr = new BinaryWriter(filemem, Encoding.UTF8))
                {
                    wrtr.Write((int)_crc.Value);
                    wrtr.Write(_sizeDir);
                    wrtr.Write(_sizeName);
                    wrtr.Write(_numFiles);

                    buf = new byte[16];
                    Buffer.BlockCopy(filemem.GetBuffer(), 0, buf, 0, 16);

                    for (byte i = 0; i < 16; i++)
                    {
                        buf[i] ^= i;
                    }
                }
            }

            using (FileStream fileStream = File.Open(fname, FileMode.Create, FileAccess.Write))
            {
                using (var wrtr = new BinaryWriter(fileStream, Encoding.UTF8))
                {
                    wrtr.Write(Magic);
                    wrtr.Write((byte)2);
                    wrtr.Write(buf, 0, 16);
                    wrtr.Write(name, 0, _sizeName);
                    wrtr.Write(dir, 0, _sizeDir);

                    foreach (MPKFile file in files)
                    {
                        wrtr.Write(file.CompressedData);
                    }
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Build a binary data frame form the frame object.
        /// </summary>
        /// <param name="frameBase">ID3 Frame</param>
        /// <returns>binary frame representation</returns>
        public byte[] Make(IFrame frameBase)
        {
            flagHandler.Flags = frameBase.Flags;
            byte[] frame = frameBase.Make();

            MemoryStream memoryStream = new MemoryStream();
            BinaryWriter writer       = new BinaryWriter(memoryStream);

            if (flagHandler.Grouping == true)
            {
                //TODO: Do grouping some place in the universe
                byte _group = 0;
                writer.Write(_group);
            }
            if (flagHandler.Compression == true)
            {
                switch (flagHandler.Version)
                {
                case 3:
                {
                    writer.Write(Swap.Int32(frame.Length));
                    break;
                }

                case 4:
                {
                    writer.Write(Sync.UnsafeBigEndian(Swap.UInt32((uint)frame.Length)));
                    break;
                }

                default:
                {
                    throw new NotImplementedException("ID3v2 Version " + flagHandler.Version + " is not supported.");
                }
                }
                byte[]   buf      = new byte[2048];
                Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
                deflater.SetInput(frame, 0, frame.Length);
                deflater.Finish();
                while (!deflater.IsNeedingInput)
                {
                    int len = deflater.Deflate(buf, 0, buf.Length);
                    if (len <= 0)
                    {
                        break;
                    }
                    memoryStream.Write(buf, 0, len);
                }

                if (!deflater.IsNeedingInput)
                {
                    //TODO: Skip and remove invalid frames.
                    throw new InvalidFrameException("Can't decompress frame '" + frameBase.FrameId + "' missing data");
                }
            }
            else
            {
                memoryStream.Write(frame, 0, frame.Length);
            }

            if (flagHandler.Encryption == true)
            {
                //TODO: Encryption
                throw new NotImplementedException("Encryption is not implemented, consequently it is not supported.");
            }

            if (flagHandler.Unsynchronisation == true)
            {
                MemoryStream synchStream = new MemoryStream();
                Sync.Unsafe(memoryStream, synchStream, (uint)memoryStream.Position);
                memoryStream = synchStream;
            }
            return(memoryStream.ToArray());
        }